toolnet-memory 0.2.20 → 0.3.0
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/.env.example +9 -0
- package/bin/toolnet-memory +76 -0
- package/bundle/agy-hook.js +67 -46
- package/bundle/agy.js +104 -38
- package/bundle/api.js +52 -0
- package/bundle/auto-integrate.js +66 -19
- package/bundle/claude-hook.js +78 -0
- package/bundle/claude.js +3 -0
- package/bundle/codex-context.js +30 -25
- package/bundle/codex.js +80 -61
- package/bundle/context-runtime.js +43 -38
- package/bundle/context.js +15 -14
- package/bundle/continuity-certify.js +49 -0
- package/bundle/doctor.js +4 -4
- package/bundle/full-index.js +18 -8
- package/bundle/graph-index.js +4 -4
- package/bundle/handoff-refresh.js +10 -10
- package/bundle/impact.js +3 -3
- package/bundle/incremental.js +4 -4
- package/bundle/init.js +763 -0
- package/bundle/learner.js +5 -5
- package/bundle/mcp.js +19 -15
- package/bundle/memory-agent.js +10 -11
- package/bundle/memory-query.js +7 -7
- package/bundle/opencode.js +72 -53
- package/bundle/production-certify.js +5 -0
- package/bundle/project-manual.js +6 -6
- package/bundle/recovery-certify.js +55 -0
- package/bundle/runtime.js +11 -11
- package/bundle/semantic.js +6 -6
- package/bundle/setup.js +69 -22
- package/bundle/snapshot.js +4 -4
- package/bundle/update.js +4 -1
- package/bundle/work-continuity.js +6 -6
- package/dist/sdk/public.d.ts +2 -0
- package/dist/sdk/public.js +2 -0
- package/dist/sdk/remote-client.d.ts +41 -0
- package/dist/sdk/remote-client.js +185 -0
- package/dist/sdk/types.d.ts +402 -0
- package/dist/sdk/types.js +1 -0
- package/package.json +14 -5
package/bundle/full-index.js
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
|
-
import{closeSync as
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function
|
|
3
|
-
`,{encoding:"utf8",mode:384}),_t(o,r)}function Ze(s,e){return{id:s.id,name:s.name,remote:s.remote,rootPath:e,createdAt:s.createdAt,updatedAt:s.updatedAt,graphVersion:s.graphVersion,memoryVersion:s.memoryVersion,metadata:s.metadata}}var Z=class{detect(e=process.cwd()){let t=K(e),r=Ft(t),i=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(l=>Oe(X(r,l))),n=Dt(t,i?r:void 0);if(n){let l=Me(n),u=Kt(l);return u.rootPath!==n&&(u.rootPath=n,u.updatedAt=new Date().toISOString(),Qe(n,u)),Ze(u,n)}let a=new Date().toISOString(),m=Nt(r),c={version:1,id:Mt(r),name:m,remote:m,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return Qe(r,c),Ze(c,r)}};var $t=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_\-]{20,}\b/g},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._\-]{16,}\b/gi},{type:"jwt",regex:/\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\b/g},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g},{type:"password_assignment",regex:/\b(password|passwd|pwd)\s*[:=]\s*["']?[^"'\s]{6,}["']?/gi},{type:"secret_assignment",regex:/\b(secret|api[_-]?key|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?[^"'\s]{8,}["']?/gi},{type:"cookie",regex:/\b(cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi}],ee=class{scan(e){let t=[];for(let r of $t){let o=new RegExp(r.regex.source,r.regex.flags);for(let i of e.matchAll(o))t.push({type:r.type,value:i[0]})}return t}hasSecrets(e){return this.scan(e).length>0}};var $=class{scanner=new ee;sanitize(e){let t=e,r=this.scanner.scan(e),o=new Set;for(let i of r)o.add(i.type),t=t.split(i.value).join(`[REDACTED:${i.type}]`);return{text:t,redacted:r.length,secretTypes:[...o]}}sanitizeValue(e){if(typeof e=="string")return this.sanitize(e).text;if(Array.isArray(e))return e.map(t=>this.sanitizeValue(t));if(e&&typeof e=="object"){let t={};for(let[r,o]of Object.entries(e)){let i=r.toLowerCase();i.includes("password")||i.includes("secret")||i.includes("token")||i.includes("cookie")||i.includes("authorization")?t[r]="[REDACTED]":t[r]=this.sanitizeValue(o)}return t}return e}};var tt=[{id:"openai-compatible",label:"OpenAI-compatible",requiresApiKey:!0,requiresBaseUrl:!0,transport:"openai-compatible"},{id:"alibaba",label:"Alibaba / DashScope",requiresApiKey:!0,requiresBaseUrl:!0,transport:"openai-compatible"},{id:"openrouter",label:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1",requiresApiKey:!0,transport:"openai-compatible"},{id:"groq",label:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1",requiresApiKey:!0,transport:"openai-compatible"},{id:"deepseek",label:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com",defaultModel:"deepseek-v4-flash",requiresApiKey:!0,transport:"openai-compatible"},{id:"nvidia",label:"NVIDIA NIM",defaultBaseUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"deepseek-ai/deepseek-v4-pro",requiresApiKey:!0,transport:"openai-compatible"},{id:"gemini",label:"Gemini",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta",requiresApiKey:!0,transport:"gemini"},{id:"huggingface",label:"Hugging Face",defaultBaseUrl:"https://router.huggingface.co/v1",requiresApiKey:!0,transport:"openai-compatible"},{id:"ollama",label:"Ollama / Local",defaultBaseUrl:"http://127.0.0.1:11434/v1",requiresApiKey:!1,transport:"openai-compatible"},{id:"custom",label:"Custom endpoint",requiresApiKey:!1,requiresBaseUrl:!0,transport:"openai-compatible"},{id:"cloudflare",label:"Cloudflare Workers AI",requiresApiKey:!0,requiresAccountId:!0,transport:"cloudflare"}];function te(s){let e=tt.find(t=>t.id===s);if(!e)throw new Error(`Unsupported AI provider: ${s}`);return e}function re(s){return tt.some(e=>e.id===s)}function g(s){return process.env[s]?.trim()||void 0}function P(...s){return s.find(e=>!!e?.trim())}function rt(){if(g("GROQ_API_KEY"))return"groq";if(g("DEEPSEEK_API_KEY"))return"deepseek";if(g("NVIDIA_API_KEY")||g("NVIDIA_NIM_API_KEY"))return"nvidia";if(g("OPENROUTER_API_KEY"))return"openrouter";if(g("ALIBABA_API_KEY")||g("DASHSCOPE_API_KEY"))return"alibaba";if(g("GEMINI_API_KEY")||g("GOOGLE_API_KEY"))return"gemini";if(g("CLOUDFLARE_API_TOKEN")&&g("CLOUDFLARE_ACCOUNT_ID"))return"cloudflare";if(g("HF_TOKEN"))return"huggingface";if(g("OLLAMA_MODEL")||g("OLLAMA_BASE_URL"))return"ollama"}function Gt(){let s=g("TOOLNET_LLM_PROVIDER");return s&&re(s)?s:rt()??"openai-compatible"}function je(s){let e=te(s);switch(s){case"alibaba":return{provider:s,apiKey:P(g("ALIBABA_API_KEY"),g("DASHSCOPE_API_KEY")),baseUrl:P(g("ALIBABA_BASE_URL"),g("DASHSCOPE_BASE_URL"),e.defaultBaseUrl),model:P(g("ALIBABA_MODEL"),g("DASHSCOPE_MODEL"))};case"openrouter":return{provider:s,apiKey:g("OPENROUTER_API_KEY"),baseUrl:P(g("OPENROUTER_BASE_URL"),e.defaultBaseUrl),model:g("OPENROUTER_MODEL")};case"groq":return{provider:s,apiKey:g("GROQ_API_KEY"),baseUrl:P(g("GROQ_BASE_URL"),e.defaultBaseUrl),model:g("GROQ_MODEL")};case"deepseek":return{provider:s,apiKey:g("DEEPSEEK_API_KEY"),baseUrl:P(g("DEEPSEEK_BASE_URL"),e.defaultBaseUrl),model:P(g("DEEPSEEK_MODEL"),e.defaultModel)};case"nvidia":return{provider:s,apiKey:P(g("NVIDIA_API_KEY"),g("NVIDIA_NIM_API_KEY")),baseUrl:P(g("NVIDIA_BASE_URL"),g("NVIDIA_NIM_BASE_URL"),e.defaultBaseUrl),model:P(g("NVIDIA_MODEL"),g("NVIDIA_NIM_MODEL"),e.defaultModel)};case"gemini":return{provider:s,apiKey:P(g("GEMINI_API_KEY"),g("GOOGLE_API_KEY")),baseUrl:P(g("GEMINI_BASE_URL"),e.defaultBaseUrl),model:g("GEMINI_MODEL")};case"huggingface":return{provider:s,apiKey:g("HF_TOKEN"),baseUrl:P(g("HF_INFERENCE_BASE_URL"),e.defaultBaseUrl),model:P(g("HF_LLM_MODEL"),g("HF_MODEL"))};case"ollama":return{provider:s,apiKey:g("OLLAMA_API_KEY"),baseUrl:P(g("OLLAMA_BASE_URL"),e.defaultBaseUrl),model:g("OLLAMA_MODEL")};case"cloudflare":return{provider:s,accountId:g("CLOUDFLARE_ACCOUNT_ID"),apiKey:g("CLOUDFLARE_API_TOKEN"),baseUrl:g("CLOUDFLARE_AI_BASE_URL"),model:g("CLOUDFLARE_MODEL")};case"custom":return{provider:s,apiKey:g("CUSTOM_AI_API_KEY"),baseUrl:g("CUSTOM_AI_BASE_URL"),model:g("CUSTOM_AI_MODEL")};default:return{provider:"openai-compatible",apiKey:P(g("OPENAI_API_KEY"),g("MODEL_API_KEY")),baseUrl:P(g("OPENAI_BASE_URL"),g("MODEL_BASE_URL")),model:P(g("OPENAI_MODEL"),g("MODEL_NAME"))}}}function Ut(){let s=g("TOOLNET_LLM_PROVIDER"),e=s&&re(s)?s:Gt(),t=te(e),r=je(e);return{provider:e,apiKey:P(g("TOOLNET_LLM_API_KEY"),r.apiKey),baseUrl:P(g("TOOLNET_LLM_BASE_URL"),r.baseUrl,t.defaultBaseUrl),model:P(g("TOOLNET_LLM_MODEL"),r.model,t.defaultModel),accountId:P(g("TOOLNET_LLM_ACCOUNT_ID"),r.accountId)}}function Bt(){let s=g("TOOLNET_EMBEDDING_PROVIDER");return s==="local"?"local":s&&re(s)?s:g("HF_TOKEN")||g("HF_EMBEDDING_MODEL")?"huggingface":"local"}function zt(){let s=Bt();if(s==="local")return{provider:"local",model:P(g("TOOLNET_EMBEDDING_MODEL"),g("LOCAL_EMBEDDING_MODEL"))};let e=te(s),t,r,o,i;switch(s){case"huggingface":t=g("HF_TOKEN"),r=g("HF_INFERENCE_BASE_URL"),o=g("HF_EMBEDDING_MODEL");break;case"openai-compatible":t=g("OPENAI_API_KEY"),r=g("OPENAI_BASE_URL"),o=g("OPENAI_EMBEDDING_MODEL");break;case"cloudflare":t=g("CLOUDFLARE_API_TOKEN"),r=g("CLOUDFLARE_AI_BASE_URL"),o=g("CLOUDFLARE_EMBEDDING_MODEL"),i=g("CLOUDFLARE_ACCOUNT_ID");break;default:t=je(s).apiKey,r=je(s).baseUrl,o=g(`${s.toUpperCase().replace(/-/g,"_")}_EMBEDDING_MODEL`)}let n=P(g("TOOLNET_EMBEDDING_ACCOUNT_ID"),i),a=P(g("TOOLNET_EMBEDDING_BASE_URL"),r,e.defaultBaseUrl),m=s==="cloudflare"&&!a&&n?`https://api.cloudflare.com/client/v4/accounts/${n}/ai/v1`:a;return{provider:s,apiKey:P(g("TOOLNET_EMBEDDING_API_KEY"),t),baseUrl:m,model:P(g("TOOLNET_EMBEDDING_MODEL"),o),accountId:n}}function st(){let s=Ut(),e=zt();return{llm:s,embedding:e,legacy:{llm:!g("TOOLNET_LLM_PROVIDER")&&!!rt(),embedding:!g("TOOLNET_EMBEDDING_PROVIDER")&&!!(g("HF_TOKEN")||g("HF_EMBEDDING_MODEL"))}}}var se=class{constructor(e){this.options=e}options;name="gemini";async embed(e){let t=this.options.model.replace(/^models\//,""),o=`${this.options.baseUrl?.replace(/\/+$/,"")||"https://generativelanguage.googleapis.com/v1beta"}/models/${encodeURIComponent(t)}:embedContent?key=${encodeURIComponent(this.options.apiKey)}`,i=await fetch(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:`models/${t}`,content:{parts:[{text:e}]}})});if(!i.ok)throw new Error(`Gemini embedding failed: ${i.status} ${await i.text()}`);let a=(await i.json()).embedding?.values;if(!Array.isArray(a)||a.length===0)throw new Error("Gemini embedding returned invalid response");return a}async embedMany(e){let t=[];for(let r of e)t.push(await this.embed(r));return t}};import{createHash as Ht}from"node:crypto";var oe=class{name="hash-fallback";dimensions=128;async embed(e){let t=new Array(this.dimensions).fill(0),r=e.toLowerCase().split(/\s+/).filter(Boolean);for(let o of r){let n=Ht("sha256").update(o).digest().readUInt32BE(0)%this.dimensions;t[n]+=1}return Vt(t)}async embedMany(e){return Promise.all(e.map(t=>this.embed(t)))}};function Vt(s){let e=Math.sqrt(s.reduce((t,r)=>t+r*r,0));return e===0?s:s.map(t=>t/e)}var ne=class{constructor(e){this.options=e;this.dimensions=e.dimensions}options;name="openai-compatible";dimensions;async embed(e){let[t]=await this.embedMany([e]);return t}async embedMany(e){if(e.length===0)return[];let t=this.options.baseUrl.replace(/\/+$/,""),r=await fetch(`${t}/embeddings`,{method:"POST",headers:{"content-type":"application/json",...this.options.apiKey?{authorization:`Bearer ${this.options.apiKey}`}:{}},body:JSON.stringify({model:this.options.model,input:e})});if(!r.ok)throw new Error(`Embedding failed: ${r.status} ${await r.text()}`);let i=(await r.json()).data?.sort((n,a)=>(n.index??0)-(a.index??0)).map(n=>n.embedding);if(!i||i.length!==e.length||i.some(n=>!Array.isArray(n)))throw new Error("Embedding provider returned invalid response");return i}};var ie=class{constructor(e){this.options=e}options;name="huggingface";dimensions=384;async embed(e){let[t]=await this.embedMany([e]);return t}async embedMany(e){if(e.length===0)return[];let t=`https://router.huggingface.co/hf-inference/models/${this.options.model}/pipeline/feature-extraction`,r=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${this.options.token}`,"Content-Type":"application/json"},body:JSON.stringify({inputs:e,options:{wait_for_model:!0}})});if(!r.ok)throw new Error(`HF embedding failed: ${r.status} ${await r.text()}`);let o=await r.json();if(!Array.isArray(o))throw new Error("HF embedding returned invalid response");return o.map(i=>Wt(i))}};function Wt(s){if(!Array.isArray(s))throw new Error("Invalid embedding");if(s.length>0&&typeof s[0]=="number")return s;if(s.length>0&&Array.isArray(s[0])){let e=s;if(e.length===0)return[];let t=e[0].length,r=new Array(t).fill(0);for(let o of e)for(let i=0;i<t;i++)r[i]+=o[i]??0;for(let o=0;o<t;o++)r[o]/=e.length;return r}throw new Error("Unsupported embedding shape")}var De=class{constructor(e,t=new oe){this.primary=e;this.fallback=t}primary;fallback;name="resilient";async embed(e){if(this.primary)try{return await this.primary.embed(e)}catch(t){console.warn("[embedding] primary failed, fallback enabled:",t instanceof Error?t.message:t)}return this.fallback.embed(e)}async embedMany(e){if(this.primary)try{return await this.primary.embedMany(e)}catch(t){console.warn("[embedding] primary failed, fallback enabled:",t instanceof Error?t.message:t)}return this.fallback.embedMany(e)}};function Yt(s){return`https://api.cloudflare.com/client/v4/accounts/${s}/ai/v1`}function qt(){let s=st().embedding;if(s.provider==="local")return null;if(s.provider==="huggingface")return!s.apiKey||!s.model?null:new ie({token:s.apiKey,model:s.model});if(s.provider==="gemini")return!s.apiKey||!s.model?null:new se({apiKey:s.apiKey,model:s.model,baseUrl:s.baseUrl});let e=s.baseUrl;return s.provider==="cloudflare"&&!e&&s.accountId&&(e=Yt(s.accountId)),e&&s.model?new ne({apiKey:s.apiKey,baseUrl:e,model:s.model}):null}function ot(){return new De(qt())}import{readdir as Xt}from"node:fs/promises";import{extname as er,join as tr,relative as rr}from"node:path";import{basename as Jt}from"node:path";var Qt=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),Zt=new Set([".pem",".key",".p12",".pfx"]);function nt(s){let e=Jt(s).toLowerCase();if(Qt.has(e))return!0;for(let t of Zt)if(e.endsWith(t))return!0;return!1}var sr=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),or=new Set(["node_modules",".git","dist","build","coverage",".next",".cache",".toolnet-memory"]);async function Fe(s){let e=[];async function t(r){let o=await Xt(r,{withFileTypes:!0});for(let i of o){if(or.has(i.name))continue;let n=tr(r,i.name);if(i.isDirectory()){await t(n);continue}sr.has(er(i.name))&&(nt(n)||e.push(rr(s,n)))}}return await t(s),e.sort()}import{readFile as nr}from"node:fs/promises";import{join as ir}from"node:path";import{createHash as ar}from"node:crypto";import*as C from"typescript";function it(s,e){return ar("sha256").update(`${s}:${e}`).digest("hex").slice(0,24)}function Ke(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}async function $e(s,e,t){let r=ir(e,t),o=await nr(r,"utf8"),i=C.createSourceFile(t,o,C.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?C.ScriptKind.TSX:C.ScriptKind.TS),n=[],a=[],m=[],c=[],l={id:it(s,`file:${t}`),projectId:s,name:t,qualifiedName:t,type:"file",filePath:t,startLine:1,endLine:i.getLineAndCharacterOfPosition(i.end).line+1};n.push(l);let u=[],d=[];function f(h,v,S,x){let L=it(s,`${t}:${S}:${x??v}:${h.pos}`);return n.push({id:L,projectId:s,name:v,qualifiedName:x??v,type:S,filePath:t,startLine:Ke(i,h),endLine:i.getLineAndCharacterOfPosition(h.end).line+1}),L}function y(h){if(!C.isStringLiteral(h.moduleSpecifier))return;let v=[],S=h.importClause;if(S?.name&&v.push({localName:S.name.text,importedName:"default",kind:"default"}),S?.namedBindings&&C.isNamedImports(S.namedBindings))for(let x of S.namedBindings.elements)v.push({localName:x.name.text,importedName:x.propertyName?.text??x.name.text,kind:"named"});S?.namedBindings&&C.isNamespaceImport(S.namedBindings)&&v.push({localName:S.namedBindings.name.text,importedName:"*",kind:"namespace"}),a.push({source:h.moduleSpecifier.text,bindings:v})}function p(h,v){for(let S of h.heritageClauses??[])for(let x of S.types){let L=x.expression.getText(i).split(".").at(-1)??"";L&&c.push({fromId:v,targetName:L,type:S.token===C.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function E(h){let v=!1,S=!1;if(C.isImportDeclaration(h)&&y(h),C.isInterfaceDeclaration(h)&&f(h,h.name.text,"interface",h.name.text),C.isClassDeclaration(h)&&h.name){let x=f(h,h.name.text,"class",h.name.text);p(h,x),d.push({id:x,name:h.name.text}),S=!0}if(C.isFunctionDeclaration(h)&&h.name){let x=f(h,h.name.text,"function",h.name.text);u.push(x),v=!0}if(C.isMethodDeclaration(h)&&h.name){let x=h.name.getText(i),L=d.at(-1)?.name,A=f(h,x,"method",L?`${L}.${x}`:x);u.push(A),v=!0}if(C.isCallExpression(h)&&(C.isIdentifier(h.expression)&&m.push({callerId:u.at(-1),calleeName:h.expression.text,line:Ke(i,h)}),C.isPropertyAccessExpression(h.expression))){let x=h.expression;m.push({callerId:u.at(-1),qualifier:x.expression.getText(i),calleeName:x.name.text,line:Ke(i,h)})}C.forEachChild(h,E),v&&u.pop(),S&&d.pop()}return E(i),{filePath:t,symbols:n,imports:a,calls:m,heritage:c}}import{createHash as cr}from"node:crypto";import{dirname as lr,extname as dr,normalize as pr,posix as mr}from"node:path";var G=class{symbols=new Map;edges=new Map;addSymbol(e){this.symbols.set(e.id,e)}addEdge(e){this.edges.set(e.id,e)}getSymbol(e){return this.symbols.get(e)}findByName(e,t){return[...this.symbols.values()].filter(r=>r.projectId===e&&(r.name===t||r.qualifiedName===t))}allSymbols(e){return[...this.symbols.values()].filter(t=>t.projectId===e)}allEdges(e){return[...this.edges.values()].filter(t=>t.projectId===e)}import(e,t){for(let r of e)this.addSymbol(r);for(let r of t)this.addEdge(r)}clearProject(e){for(let[t,r]of this.symbols)r.projectId===e&&this.symbols.delete(t);for(let[t,r]of this.edges)r.projectId===e&&this.edges.delete(t)}};function ur(s,e,t,r){return cr("sha256").update(`${s}:${e}:${t}:${r}`).digest("hex").slice(0,24)}function k(s){return pr(s).replaceAll("\\","/")}function Ge(s,e,t){if(!e.startsWith("."))return;let r=k(mr.join(lr(s),e)),o=dr(r),i;if(o===".js"){let n=r.slice(0,-3);i=[`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}.jsx`]}else if(o===".mjs"){let n=r.slice(0,-4);i=[`${n}.mts`,`${n}.ts`,`${n}.mjs`]}else if(o===".cjs"){let n=r.slice(0,-4);i=[`${n}.cts`,`${n}.ts`,`${n}.cjs`]}else o?i=[r]:i=[`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}.js`,`${r}.jsx`,`${r}.mjs`,`${r}.cjs`,`${r}/index.ts`,`${r}/index.tsx`,`${r}/index.js`,`${r}/index.jsx`];return i.find(n=>t.has(k(n)))}var U=class{build(e,t){let r=new G,o=new Map;for(let n of t)for(let a of n.symbols)r.addSymbol(a),a.type==="file"&&o.set(k(n.filePath),a);let i=new Set(o.keys());for(let n of t){let a=k(n.filePath),m=o.get(a);if(m){for(let c of n.symbols)c.id!==m.id&&r.addEdge(this.edge(e,m.id,"DEFINES",c.id));for(let c of n.imports){let l=Ge(a,c.source,i);if(!l)continue;let u=o.get(l);u&&r.addEdge(this.edge(e,m.id,"IMPORTS",u.id,{source:c.source}))}for(let c of n.heritage){let l=r.findByName(e,c.targetName).filter(u=>u.type==="class"||u.type==="interface");for(let u of l)r.addEdge(this.edge(e,c.fromId,c.type,u.id))}for(let c of n.calls){if(!c.callerId)continue;let l=this.resolveCallTargets(e,n,c.calleeName,c.qualifier,t,r,i);for(let u of l)u.id!==c.callerId&&r.addEdge(this.edge(e,c.callerId,"CALLS",u.id,{line:c.line,qualifier:c.qualifier}))}}}return r}resolveCallTargets(e,t,r,o,i,n,a){let m=k(t.filePath),c=n.findByName(e,r).filter(l=>k(l.filePath)===m);if(!o&&c.length)return c;if(o)for(let l of t.imports){if(!l.bindings.find(f=>f.kind==="namespace"&&f.localName===o))continue;let d=Ge(m,l.source,a);if(d)return n.findByName(e,r).filter(f=>k(f.filePath)===d)}for(let l of t.imports){let u=l.bindings.find(p=>p.localName===r);if(!u)continue;let d=Ge(m,l.source,a);if(!d)continue;let f=u.importedName==="default"?r:u.importedName,y=n.findByName(e,f).filter(p=>k(p.filePath)===d);if(y.length)return y}return n.findByName(e,r).filter(l=>l.type==="function"||l.type==="method")}edge(e,t,r,o,i){return{id:ur(e,t,r,o),projectId:e,from:t,to:o,type:r,metadata:i}}};var ae=class{async index(e,t){let r=await Fe(t),o=[];for(let n of r)try{o.push(await $e(e,t,n))}catch(a){console.warn(`[indexer] skipped ${n}:`,a instanceof Error?a.message:a)}let i=new U().build(e,o);return{files:o.length,symbols:i.allSymbols(e).length,edges:i.allEdges(e).length,graph:i}}};import{execFile as fr}from"node:child_process";import{promisify as gr}from"node:util";var Vo=gr(fr);var B=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};import{createHash as hr}from"node:crypto";import{readFile as yr}from"node:fs/promises";import{join as Sr}from"node:path";function at(s){return hr("sha256").update(s).digest("hex")}var ce=class{sanitizer=new $;async build(e,t,r,o={}){let i=o.maxLines??80,n=o.overlapLines??10,a=new Map;for(let c of r){let l=a.get(c.filePath)??[];l.push(c),a.set(c.filePath,l)}let m=[];for(let[c,l]of a){let u;try{u=await yr(Sr(t,c),"utf8")}catch{continue}let d=u.split(/\r?\n/),f=l.filter(y=>y.type!=="file"&&typeof y.startLine=="number"&&typeof y.endLine=="number");if(f.length>0)for(let y of f)m.push(...this.chunkRange({projectId:e,filePath:c,lines:d,symbol:y,startLine:y.startLine,endLine:y.endLine,maxLines:i,overlapLines:n}));else m.push(...this.chunkRange({projectId:e,filePath:c,lines:d,startLine:1,endLine:Math.max(1,d.length),maxLines:i,overlapLines:n}))}return m}chunkRange(e){let{projectId:t,filePath:r,lines:o,symbol:i,maxLines:n}=e,a=Math.min(e.overlapLines,Math.max(0,n-1)),m=Math.max(1,e.startLine),c=Math.min(o.length,Math.max(m,e.endLine)),l=[],u=m,d=0;for(;u<=c;){let f=Math.min(c,u+n-1),y=o.slice(u-1,f).join(`
|
|
4
|
-
`).trim();if(y){let
|
|
5
|
-
`)),
|
|
6
|
-
`));return w.parseJsonConfigFileContent(o.config,w.sys,vr(t))}return{fileNames:w.sys.readDirectory(e,[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],["node_modules",".git","dist","build","coverage"]),options:{allowJs:!0,checkJs:!1,target:w.ScriptTarget.ES2022,module:w.ModuleKind.NodeNext,moduleResolution:w.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noEmit:!0}}}};import{createHash as Cr}from"node:crypto";import{dirname as wr,relative as H,resolve as V}from"node:path";import*as b from"typescript";function I(s){return s.replaceAll("\\","/").replace(/^\.\//,"")}function Be(...s){return Cr("sha256").update(s.join(":")).digest("hex").slice(0,24)}function W(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}var Pr=new Set(["get","post","put","patch","delete","options","head"]),Ar=new Set([b.SyntaxKind.EqualsToken,b.SyntaxKind.PlusEqualsToken,b.SyntaxKind.MinusEqualsToken,b.SyntaxKind.AsteriskEqualsToken,b.SyntaxKind.SlashEqualsToken,b.SyntaxKind.PercentEqualsToken,b.SyntaxKind.QuestionQuestionEqualsToken,b.SyntaxKind.AmpersandAmpersandEqualsToken,b.SyntaxKind.BarBarEqualsToken]),he=class{constructor(e){this.graph=e}graph;enrich(e,t,r){let o={routes:0,tests:0,usesType:0,writes:0,callReferences:0,properties:0},i=this.loadConfig(t),n=b.createProgram({rootNames:i.fileNames,options:i.options}),a=n.getTypeChecker();for(let m of n.getSourceFiles()){if(m.isDeclarationFile)continue;let c=I(H(t,V(m.fileName)));if(c.startsWith("../")||c.includes("node_modules/"))continue;let l=this.fileNode(e,c);if(!l)continue;let u=d=>{if(b.isCallExpression(d)&&this.addRoute(e,t,m,l,d,a)&&o.routes++,b.isTypeReferenceNode(d)&&this.addTypeUse(e,t,m,d,a)&&o.usesType++,b.isBinaryExpression(d)&&Ar.has(d.operatorToken.kind)){let f=this.addWrite(e,t,m,d.left,a);f.added&&(o.writes++,f.propertyCreated&&o.properties++)}if((b.isPrefixUnaryExpression(d)||b.isPostfixUnaryExpression(d))&&(d.operator===b.SyntaxKind.PlusPlusToken||d.operator===b.SyntaxKind.MinusMinusToken)){let f=this.addWrite(e,t,m,d.operand,a);f.added&&(o.writes++,f.propertyCreated&&o.properties++)}b.forEachChild(d,u)};u(m)}return o.tests+=this.addTestEdges(e),r&&(o.callReferences+=this.addResolvedCalls(e,r)),o}addRoute(e,t,r,o,i,n){if(!b.isPropertyAccessExpression(i.expression))return!1;let a=i.expression.name.text.toLowerCase();if(!Pr.has(a))return!1;let m=i.arguments[0];if(!m||!(b.isStringLiteral(m)||b.isNoSubstitutionTemplateLiteral(m)))return!1;let c=m.text;if(!c.startsWith("/"))return!1;let l=W(r,i),u=Be(e,r.fileName,l,a,c);this.graph.getSymbol(u)||(this.graph.addSymbol({id:u,projectId:e,name:`${a.toUpperCase()} ${c}`,qualifiedName:`${a.toUpperCase()} ${c}`,type:"route",filePath:o.filePath,startLine:l,endLine:l}),this.graph.addEdge(this.edge(e,o.id,"DEFINES",u)));let d=i.arguments.at(-1);if(d){let f=this.resolveNodeSymbol(e,t,d,n);f&&this.graph.addEdge(this.edge(e,u,"ROUTE",f.id,{method:a.toUpperCase(),path:c}))}return!0}addTypeUse(e,t,r,o,i){let n=this.resolveNodeSymbol(e,t,o.typeName,i);if(!n)return!1;let a=this.containingSymbol(e,I(H(t,V(r.fileName))),W(r,o));return!a||a.id===n.id?!1:(this.graph.addEdge(this.edge(e,a.id,"USES_TYPE",n.id)),!0)}addWrite(e,t,r,o,i){let n=this.resolveTsSymbol(o,i),a=n?.valueDeclaration??n?.declarations?.[0];if(!a)return{added:!1,propertyCreated:!1};let m=a.getSourceFile();if(m.isDeclarationFile)return{added:!1,propertyCreated:!1};let c=I(H(t,V(m.fileName)));if(c.startsWith("../")||c.includes("node_modules/"))return{added:!1,propertyCreated:!1};let l=W(m,a),u=this.findSymbolAt(e,c,l),d=!1;if(!u||u.type==="file"){let p=n?.getName()??o.getText(r),E=Be(e,c,"property",p,l);if(u=this.graph.getSymbol(E),!u){u={id:E,projectId:e,name:p,qualifiedName:p,type:"property",filePath:c,startLine:l,endLine:l},this.graph.addSymbol(u);let h=this.fileNode(e,c);h&&this.graph.addEdge(this.edge(e,h.id,"DEFINES",u.id)),d=!0}}if(!u)return{added:!1,propertyCreated:d};let f=I(H(t,V(r.fileName))),y=this.containingSymbol(e,f,W(r,o));return!y||y.id===u.id?{added:!1,propertyCreated:d}:(this.graph.addEdge(this.edge(e,y.id,"WRITES",u.id,{expression:o.getText(r)})),{added:!0,propertyCreated:d})}addTestEdges(e){let t=this.graph.allEdges(e),r=0;for(let o of t){if(o.type!=="IMPORTS")continue;let i=this.graph.getSymbol(o.from),n=this.graph.getSymbol(o.to);!i||!n||!this.isTestFile(i.filePath)||this.isTestFile(n.filePath)||(this.graph.addEdge(this.edge(e,i.id,"TESTS",n.id)),r++)}return r}addResolvedCalls(e,t){let r=0;for(let o of t.resolutions){if(o.kind!=="CALL"||!o.targetSymbolId)continue;let i=this.graph.getSymbol(o.targetSymbolId);if(!i)continue;let n=this.containingSymbol(e,o.sourceFile,o.sourceLine);!n||n.id===i.id||this.graph.allEdges(e).some(m=>m.type==="CALLS"&&m.from===n.id&&m.to===i.id)||(this.graph.addEdge(this.edge(e,n.id,"CALL_REFERENCE",i.id,{expression:o.expression,confidence:o.confidence,resolver:o.resolver})),r++)}return r}resolveNodeSymbol(e,t,r,o){let i=this.resolveTsSymbol(r,o),n=i?.valueDeclaration??i?.declarations?.[0];if(!n)return;let a=n.getSourceFile();if(a.isDeclarationFile)return;let m=I(H(t,V(a.fileName)));if(!(m.startsWith("../")||m.includes("node_modules/")))return this.findSymbolAt(e,m,W(a,n),i?.getName())}resolveTsSymbol(e,t){let r=t.getSymbolAtLocation(e);if(r&&r.flags&b.SymbolFlags.Alias)try{r=t.getAliasedSymbol(r)}catch{}return r}containingSymbol(e,t,r){return this.graph.allSymbols(e).filter(o=>I(o.filePath)===I(t)&&typeof o.startLine=="number"&&typeof o.endLine=="number"&&o.startLine<=r&&o.endLine>=r).sort((o,i)=>(o.endLine??0)-(o.startLine??0)-((i.endLine??0)-(i.startLine??0)))[0]}findSymbolAt(e,t,r,o){let i=this.graph.allSymbols(e).filter(n=>I(n.filePath)===I(t)&&typeof n.startLine=="number"&&typeof n.endLine=="number"&&n.startLine<=r&&n.endLine>=r).sort((n,a)=>(n.endLine??0)-(n.startLine??0)-((a.endLine??0)-(a.startLine??0)));if(o){let n=i.find(a=>a.name===o||(a.qualifiedName?.endsWith(`.${o}`)??!1));if(n)return n}return i[0]}fileNode(e,t){return this.graph.allSymbols(e).find(r=>r.type==="file"&&I(r.filePath)===I(t))}isTestFile(e){let t=I(e).toLowerCase();return t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t)}edge(e,t,r,o,i){return{id:Be(e,t,r,o,JSON.stringify(i??{})),projectId:e,from:t,to:o,type:r,metadata:i}}loadConfig(e){let t=b.findConfigFile(e,b.sys.fileExists,"tsconfig.json");if(t){let r=b.readConfigFile(t,b.sys.readFile);return b.parseJsonConfigFileContent(r.config,b.sys,wr(t))}return{fileNames:b.sys.readDirectory(e,[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],["node_modules",".git","dist","build","coverage"]),options:{allowJs:!0,noEmit:!0,skipLibCheck:!0,target:b.ScriptTarget.ES2022,module:b.ModuleKind.NodeNext,moduleResolution:b.ModuleResolutionKind.NodeNext}}}};function Lr(s){return s.replaceAll("\\","/").toLowerCase()}var j=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),o=[];for(let n of t){if(n.type!=="route"&&n.type!=="file")continue;let a=this.classify(n,r);a&&o.push({symbolId:n.id,filePath:n.filePath,name:n.name,kind:a.kind,score:a.score,reasons:a.reasons})}let i=new Map;for(let n of o){let a=n.kind==="route"?n.symbolId:n.filePath,m=i.get(a);(!m||n.score>m.score)&&i.set(a,n)}return[...i.values()].sort((n,a)=>a.score-n.score||n.filePath.localeCompare(a.filePath))}classify(e,t){let r=Lr(e.filePath),o=[];if(e.type==="route")return{kind:"route",score:100,reasons:["HTTP route"]};let i=null,n=0;if(r.startsWith("bin/"))i="cli",n=100,o.push("bin executable");else if(/(^|\/)(cli)\.[^.]+$/.test(r))i="cli",n=90,o.push("CLI entry file");else if(/(^|\/)(main|server)\.[^.]+$/.test(r))i="main",n=90,o.push("main/server file");else if(r.includes("/runtime/")&&/(^|\/)(bootstrap|index)\.[^.]+$/.test(r))i="runtime",n=75,o.push("runtime bootstrap");else if(/(^|\/)index\.[^.]+$/.test(r)){let m=t.filter(l=>l.to===e.id&&l.type!=="DEFINES").length,c=t.filter(l=>l.from===e.id&&l.type!=="DEFINES").length;(r.startsWith("packages/")||m===0||c>0)&&(i="package",n=r.startsWith("packages/")?70:55,o.push("package/public index"))}return i?(t.filter(m=>m.to===e.id&&m.type!=="DEFINES").length===0&&(n+=10,o.push("no incoming dependency")),{kind:i,score:n,reasons:o}):null}};var Ir={CALL_REFERENCE:6,CALLS:4,IMPORTS:3,USES_TYPE:4,WRITES:5,ROUTE:4,TESTS:1,INHERITS:5,IMPLEMENTS:5,DEFINES:.25},ye=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),o=new Map(t.map(c=>[c.id,c])),i=new Map,n=c=>{let l=i.get(c);return l||(l={symbols:0,incoming:0,outgoing:0,weightedIncoming:0,weightedOutgoing:0,writes:0,callReferences:0,crossFile:0},i.set(c,l)),l};for(let c of t)n(c.filePath).symbols++;for(let c of r){let l=o.get(c.from),u=o.get(c.to);if(!l||!u)continue;let d=Ir[c.type]??1,f=n(l.filePath),y=n(u.filePath);f.outgoing++,y.incoming++,f.weightedOutgoing+=d,y.weightedIncoming+=d,c.type==="WRITES"&&f.writes++,c.type==="CALL_REFERENCE"&&f.callReferences++,l.filePath!==u.filePath&&(f.crossFile++,y.crossFile++)}let a=[...i.entries()].map(([c,l])=>{let u=Number((l.symbols*.4+l.weightedIncoming*1.75+l.weightedOutgoing*.65+l.crossFile*1.5+l.writes*3+l.callReferences*2).toFixed(2)),d=[];return l.incoming>=10&&d.push("high incoming dependency"),l.crossFile>=10&&d.push("high cross-file coupling"),l.callReferences>=5&&d.push("many exact call references"),l.writes>0&&d.push("contains write relationships"),l.symbols>=10&&d.push("high symbol density"),{filePath:c,score:u,symbols:l.symbols,incoming:l.incoming,outgoing:l.outgoing,reasons:d}}).filter(c=>c.score>0).sort((c,l)=>l.score-c.score||c.filePath.localeCompare(l.filePath));if(a.length===0)return[];let m=Math.max(1,Math.min(30,Math.ceil(a.length*.15)));return a.slice(0,m)}};function Rr(s){return s.replaceAll("\\","/").toLowerCase()}var Tr={CALL_REFERENCE:6,CALLS:4,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:6,IMPLEMENTS:6,ROUTE:3,TESTS:1},Se=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),o=new Map(t.map(a=>[a.id,a])),i=[...new Set(t.map(a=>a.filePath))].sort(),n=new Map;for(let a of i)n.set(a,this.classifyPath(a));for(let a=0;a<3;a++){let m=!1;for(let c of i){let l=n.get(c);if(!l||l.layer!=="unknown")continue;let u=new Map;for(let f of r){let y=o.get(f.from),p=o.get(f.to);if(!y||!p||y.filePath===p.filePath)continue;let E=null;if(y.filePath===c?E=p.filePath:p.filePath===c&&(E=y.filePath),!E)continue;let h=n.get(E);if(!h||h.layer==="unknown"||h.layer==="tests")continue;let v=Tr[f.type]??1;u.set(h.layer,(u.get(h.layer)??0)+v)}let d=[...u.entries()].sort((f,y)=>y[1]-f[1]||f[0].localeCompare(y[0]))[0];d&&d[1]>=4&&(n.set(c,{filePath:c,layer:d[0],confidence:.65,reasons:[`graph-neighbor vote=${d[1]}`]}),m=!0)}if(!m)break}return i.map(a=>n.get(a))}classifyPath(e){let t=Rr(e);return t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t)?{filePath:e,layer:"tests",confidence:1,reasons:["test path"]}:t.startsWith("bin/")||t.includes("/mcp/")||t.includes("/cli/")||t.includes("/api/")||t.includes("/routes/")||t.includes("/hooks/")?{filePath:e,layer:"interface",confidence:.9,reasons:["interface boundary"]}:t.includes("/runtime/")||t.includes("/processor/")||t.includes("/retrieval/")||t.includes("/snapshot/")||t.includes("/code-intelligence/")?{filePath:e,layer:"application",confidence:.85,reasons:["application orchestration"]}:t.includes("/core/")||t.includes("/memory/")||/(^|\/)types\.[^.]+$/.test(t)?{filePath:e,layer:"domain",confidence:.9,reasons:["domain/core logic"]}:t.includes("/storage/")||t.includes("/production/")||t.includes("/security/")||t.includes("/config/")||t.includes("/utils/")?{filePath:e,layer:"infrastructure",confidence:.85,reasons:["infrastructure boundary"]}:{filePath:e,layer:"unknown",confidence:.35,reasons:[]}}};import{createHash as _r}from"node:crypto";var kr={CALL_REFERENCE:7,CALLS:3,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:7,IMPLEMENTS:7,ROUTE:4,TESTS:1};function Nr(s){return _r("sha256").update(s).digest("hex").slice(0,12)}function be(s){return s.replaceAll("\\","/")}function Or(s){let t=be(s).split("/").filter(Boolean);return t[0]==="src"&&t[1]?`src/${t[1]}`:t[0]==="packages"&&t[1]?`packages/${t[1]}`:t[0]==="tests"?"tests":t[0]==="bin"?"bin":t[0]??"root"}function Mr(s){let e=s.replace(/^src\//,"").replace(/^packages\//,"");return{"code-intelligence":"Code Intelligence",memory:"Memory",storage:"Storage",retrieval:"Retrieval",runtime:"Runtime",mcp:"MCP",hooks:"Hooks",security:"Security",snapshot:"Snapshots",production:"Production",capture:"Capture",processor:"Processor",core:"Core",tests:"Tests",bin:"CLI",sdk:"SDK",cli:"CLI"}[e]??e}var Ee=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),o=new Map(t.map(d=>[d.id,d])),i=[...new Set(t.map(d=>be(d.filePath)))].sort(),n=new Map,a=(d,f)=>{let y=[d,f].sort();return`${y[0]}\0${y[1]}`};for(let d of r){let f=o.get(d.from),y=o.get(d.to);if(!f||!y)continue;let p=be(f.filePath),E=be(y.filePath);if(p===E)continue;let h=kr[d.type]??0;if(h<=0)continue;let v=a(p,E),S=n.get(v);S?S.weight+=h:n.set(v,{a:[p,E].sort()[0],b:[p,E].sort()[1],weight:h})}let m=new Map;for(let d of i){let f=Or(d),y=m.get(f)??[];y.push(d),m.set(f,y)}let c=[];for(let[d,f]of m){if(f.sort(),f.length<=30){c.push({subsystem:d,files:f});continue}let y=new Set(f),p=new Map;for(let S of f)p.set(S,new Set);for(let S of n.values())!y.has(S.a)||!y.has(S.b)||S.weight>=8&&(p.get(S.a)?.add(S.b),p.get(S.b)?.add(S.a));let E=new Set,h=[];for(let S of f){if(E.has(S))continue;let x=[S],L=[];for(E.add(S);x.length>0;){let A=x.shift();L.push(A);for(let T of p.get(A)??[])E.has(T)||(E.add(T),x.push(T))}h.push(L.sort())}let v=[];for(let S of h)S.length>=2?c.push({subsystem:d,files:S}):v.push(...S);v.length>0&&c.push({subsystem:`${d}/residual`,files:v.sort()})}let l=c.map(d=>({subsystem:d.subsystem,files:[...d.files]}));for(let d=0;d<3;d++){let f=!1;e:for(let y=0;y<l.length;y++){let p=l[y];if(!(!p||p.files.length>3))for(let E=0;E<l.length;E++){if(y===E)continue;let h=l[E];if(!h)continue;let v=0,S=new Set(p.files),x=new Set(h.files);for(let L of n.values())(S.has(L.a)&&x.has(L.b)||S.has(L.b)&&x.has(L.a))&&(v+=L.weight);if(v>=20){h.files=[...new Set([...h.files,...p.files])].sort(),l.splice(y,1),f=!0;break e}}}if(!f)break}let u=[];for(let d of l){let f=new Set(d.files),y=0,p=0;for(let x of n.values()){let L=f.has(x.a),A=f.has(x.b);L&&A?y+=x.weight:(L||A)&&(p+=x.weight)}let E=y+p,h=d.subsystem.replace(/\/residual$/,""),v=Mr(h),S=d.subsystem.endsWith("/residual")?`${v} Misc`:v;u.push({id:`cluster-${Nr(`${d.subsystem}:${d.files.join("|")}`)}`,label:S,subsystem:h,files:d.files,size:d.files.length,internalWeight:y,externalWeight:p,cohesion:E>0?Number((y/E).toFixed(4)):0})}return u.sort((d,f)=>f.size-d.size||f.cohesion-d.cohesion||d.label.localeCompare(f.label))}};var ve=class{constructor(e){this.graph=e;this.entryPoints=new j(e),this.hotspots=new ye(e),this.layers=new Se(e),this.clusters=new Ee(e)}graph;entryPoints;hotspots;layers;clusters;analyze(e){let t=this.entryPoints.detect(e),r=this.hotspots.analyze(e),o=this.layers.detect(e),i=this.clusters.detect(e),n=new Set(this.graph.allSymbols(e).map(a=>a.filePath));return{version:1,projectId:e,updatedAt:new Date().toISOString(),summary:{files:n.size,entryPoints:t.length,hotspots:r.length,layers:o.length,clusters:i.length},entryPoints:t,hotspots:r,layers:o,clusters:i}}};var dt=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE","TESTS"]);function ze(s){return s.replaceAll("\\","/").toLowerCase()}function jr(s){let e=ze(s);return e.startsWith("tests/")||e.includes("/tests/")||e.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(e)}function Dr(s){let e=ze(s.filePath);return e.startsWith("bin/")||/(^|\/)index\.[^.]+$/.test(e)||/(^|\/)(main|server|cli)\.[^.]+$/.test(e)}var xe=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),o=new Set(new j(this.graph).detect(e).map(n=>n.symbolId)),i=[];for(let n of t){if(!["function","method","class","interface","property"].includes(n.type)||jr(n.filePath)||o.has(n.id)||Dr(n)||r.filter(f=>f.to===n.id&&dt.has(f.type)).length>0)continue;let m=r.filter(f=>f.from===n.id&&dt.has(f.type)),c=["no incoming usage edge"],l=50;(n.type==="function"||n.type==="method")&&(l+=20,c.push("callable symbol")),n.type==="property"&&(l-=15),m.length===0&&(l+=10,c.push("no outgoing dependency")),ze(n.filePath).includes("/internal/")&&(l+=10,c.push("internal implementation")),n.name.startsWith("_")&&(l+=5);let d=l>=75?"high":l>=55?"medium":"low";i.push({symbolId:n.id,name:n.name,qualifiedName:n.qualifiedName,type:n.type,filePath:n.filePath,startLine:n.startLine,confidence:d,score:l,reasons:c})}return i.sort((n,a)=>a.score-n.score||n.filePath.localeCompare(a.filePath)||n.name.localeCompare(a.name))}};var Fr=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE"]),Ce=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e).filter(n=>Fr.has(n.type)),o=new Map(t.map(n=>[n.id,n]));return[...new Set(t.map(n=>n.filePath))].sort().map(n=>{let a=new Set,m=new Set,c=0,l=0;for(let u of r){let d=o.get(u.from),f=o.get(u.to);!d||!f||d.filePath===f.filePath||(d.filePath===n&&(a.add(f.filePath),c++),f.filePath===n&&(m.add(d.filePath),l++))}return{filePath:n,dependencies:[...a].sort(),dependents:[...m].sort(),outgoingEdges:c,incomingEdges:l}})}};var we=class{constructor(e){this.graph=e}graph;analyze(e){let t=new xe(this.graph).analyze(e),r=new Ce(this.graph).analyze(e);return{version:1,projectId:e,updatedAt:new Date().toISOString(),summary:{deadCodeCandidates:t.length,highConfidenceDeadCode:t.filter(o=>o.confidence==="high").length,files:r.length},deadCode:t,dependencies:r}}};var Pe=class{constructor(e){this.graph=e}graph;build(e,t,r){let o=this.graph.allSymbols(e),i=this.graph.allEdges(e),n=new Map(t?.layers.map(p=>[p.filePath,p.layer])??[]),a=new Map;for(let p of t?.clusters??[])for(let E of p.files)a.set(E,{id:p.id,label:p.label});let m=new Map(t?.hotspots.map(p=>[p.filePath,p.score])??[]),c=new Map(r?.deadCode.map(p=>[p.symbolId,{confidence:p.confidence,score:p.score}])??[]),l=new Map,u=new Map;for(let p of i)u.set(p.from,(u.get(p.from)??0)+1),l.set(p.to,(l.get(p.to)??0)+1);let d=o.map(p=>{let E=a.get(p.filePath);return{id:p.id,name:p.name,qualifiedName:p.qualifiedName,type:p.type,filePath:p.filePath,layer:n.get(p.filePath),cluster:E?.id,clusterLabel:E?.label,hotspotScore:m.get(p.filePath),deadCode:c.get(p.id),incoming:l.get(p.id)??0,outgoing:u.get(p.id)??0}}),f=new Set(d.map(p=>p.id)),y=i.filter(p=>f.has(p.from)&&f.has(p.to)).map(p=>({source:p.from,target:p.to,type:p.type,confidence:typeof p.metadata?.confidence=="string"?p.metadata.confidence:void 0,resolver:typeof p.metadata?.resolver=="string"?p.metadata.resolver:void 0}));return{version:1,projectId:e,generatedAt:new Date().toISOString(),summary:{nodes:d.length,links:y.length,files:new Set(d.map(p=>p.filePath)).size,clusters:new Set(d.map(p=>p.cluster).filter(Boolean)).size},nodes:d,links:y}}};import{homedir as as}from"node:os";import{join as cs}from"node:path";import{DeleteObjectCommand as Kr,GetObjectCommand as $r,HeadObjectCommand as Gr,ListObjectsV2Command as Ur,PutObjectCommand as Br,S3Client as zr}from"@aws-sdk/client-s3";import{getSignedUrl as Hr}from"@aws-sdk/s3-request-presigner";var Ae=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new zr({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,r="application/octet-stream"){let o=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Br({Bucket:this.bucket,Key:e,Body:o,ContentType:r}))}async get(e){let t=await Hr(this.client,new $r({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new Gr({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new Kr({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let o=await this.client.send(new Ur({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let i of o.Contents??[])i.Key&&t.push({key:i.Key,size:i.Size,updatedAt:i.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return t}};import{access as pt,mkdir as Vr,readFile as Wr,readdir as Yr,rm as qr,stat as mt,writeFile as Jr}from"node:fs/promises";import{dirname as Qr,join as Zr,relative as ut,resolve as Xr}from"node:path";var Y=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return Xr(this.root,t)}async put(e,t){let r=this.path(e);await Vr(Qr(r),{recursive:!0}),await Jr(r,t)}async get(e){try{return await Wr(this.path(e))}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return null;throw t}}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await pt(this.path(e)),!0}catch{return!1}}async delete(e){await qr(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),r=[];try{await pt(t)}catch{return r}let o=async n=>{let a=await Yr(n,{withFileTypes:!0});for(let m of a){let c=Zr(n,m.name);if(m.isDirectory()){await o(c);continue}let l=await mt(c);r.push({key:ut(this.root,c),size:l.size,updatedAt:l.mtime.toISOString()})}},i=await mt(t);return i.isDirectory()?await o(t):r.push({key:ut(this.root,t),size:i.size,updatedAt:i.mtime.toISOString()}),r}};import{DeleteObjectCommand as es,GetObjectCommand as ts,HeadObjectCommand as rs,ListObjectsV2Command as ss,PutObjectCommand as os,S3Client as ns}from"@aws-sdk/client-s3";import{getSignedUrl as is}from"@aws-sdk/s3-request-presigner";var q=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new ns({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,r="application/octet-stream"){let o=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new os({Bucket:this.bucket,Key:e,Body:o,ContentType:r}))}async get(e){let t=await is(this.client,new ts({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new rs({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new es({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let o=await this.client.send(new ss({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let i of o.Contents??[])i.Key&&t.push({key:i.Key,size:i.Size,updatedAt:i.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return t}};function He(s,e){return console.warn(e),new Y(s)}function ft(s){let e=s.localRoot??cs(as(),".toolnet-memory","storage");if(s.provider==="r2"){let t=s.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new q({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):He(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(s.provider==="s3"){let t=s.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?new q({name:"s3",endpoint:t.endpoint,region:t.region??"us-east-1",bucket:t.bucket,forcePathStyle:t.forcePathStyle??!1,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):He(e,"[storage] S3 credentials missing. Using local fallback.")}if(s.provider==="huggingface"){let t=s.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new Ae({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):He(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new Y(e)}function ls(s){return new Promise(e=>setTimeout(e,s))}async function gt(s,e={}){let t=Math.max(1,e.attempts??3),r=e.baseDelayMs??150,o=e.maxDelayMs??2e3,i;for(let n=1;n<=t;n++)try{return await s()}catch(a){if(i=a,n>=t)break;let m=Math.min(o,r*2**(n-1)),c=Math.floor(Math.random()*Math.max(1,m*.2));await ls(m+c)}throw i}var ds=new Set(["put","get","getText","delete","list"]);function ht(s,e={}){return new Proxy(s,{get(t,r){let o=Reflect.get(t,r,t);return typeof o!="function"?o:ds.has(r)?(...i)=>gt(()=>Promise.resolve(o.apply(t,i)),e):o.bind(t)}})}function yt(s){let e=s.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function St(s){let e=s.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let t=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(t)return`${t[1]}memory/records/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),t)return`${t[1]}memory/vectors/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),t)return`${t[1]}code/graph/${t[2]}`;let r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let o=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return o?`${o[1]}memory/records/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),o?`${o[1]}memory/vectors/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),o?`${o[1]}code/graph/${o[2]}`:e))}var Le=class{constructor(e,t,r,o){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=r,this.folder=yt(o??r),this.sourcePrefix=`projects/${t}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,t=new Date().toISOString(),r=t,o=await this.provider.getText(e);if(o){let n;try{n=JSON.parse(o)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${a instanceof Error?a.message:String(a)}`)}if(typeof n.id=="string"&&n.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${n.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof n.createdAt=="string"&&(r=n.createdAt)}let i={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:t};await this.provider.put(e,JSON.stringify(i,null,2)+`
|
|
7
|
-
`,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=
|
|
8
|
-
|
|
1
|
+
import{closeSync as Ss,mkdirSync as Es,openSync as vs,rmSync as xs,writeFileSync as ws}from"node:fs";import{join as tt}from"node:path";import{existsSync as Rt,readFileSync as Tt}from"node:fs";import{homedir as kt}from"node:os";import{join as Mt}from"node:path";function _t(s){let e=s.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Nt(){let s=process.env.TOOLNET_GLOBAL_ENV??Mt(kt(),".config","toolnet-memory",".env");if(!Rt(s))return;let e=Tt(s,"utf8");for(let t of e.split(/\r?\n/)){let r=t.trim();if(!r||r.startsWith("#"))continue;r.startsWith("export ")&&(r=r.slice(7));let n=r.indexOf("=");if(n<=0)continue;let i=r.slice(0,n).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&process.env[i]===void 0&&(process.env[i]=_t(r.slice(n+1)))}}Nt();function $(s,e){return s===void 0?e:["1","true","yes","on"].includes(s.toLowerCase())}function F(s,e){if(!s)return e;let t=Number(s);return Number.isFinite(t)?t:e}function st(){return{memory:{autoCapture:$(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:$(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:$(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:$(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:F(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:F(process.env.MEMORY_RERANK_TOP,10),finalContext:F(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:F(process.env.MEMORY_TOKEN_BUDGET,2e3)},storage:{provider:process.env.MEMORY_STORAGE_PROVIDER??"huggingface",r2:{accountId:process.env.R2_ACCOUNT_ID,bucket:process.env.R2_BUCKET,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY},s3:{endpoint:process.env.S3_ENDPOINT,region:process.env.S3_REGION,bucket:process.env.S3_BUCKET,accessKeyId:process.env.S3_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY,forcePathStyle:$(process.env.S3_FORCE_PATH_STYLE,!1)},huggingface:{namespace:process.env.HF_NAMESPACE,bucket:process.env.HF_BUCKET,accessKeyId:process.env.HF_S3_ACCESS_KEY_ID,secretAccessKey:process.env.HF_S3_SECRET_ACCESS_KEY},localRoot:process.env.MEMORY_LOCAL_STORAGE_PATH},cache:{maxMb:F(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as Ot}from"node:crypto";import{existsSync as Fe,mkdirSync as jt,readFileSync as Dt,renameSync as $t,writeFileSync as Ft}from"node:fs";import{basename as Kt,dirname as ee,join as re,parse as it,resolve as K}from"node:path";var at=".toolnet",Ut="project.json";function Gt(s){return Ot("sha256").update(s).digest("hex").slice(0,16)}function Ke(s){return re(s,at,Ut)}function Bt(s){return Fe(Ke(s))}function zt(s,e){let t=K(s),r=it(t).root;for(;;){if(Bt(t))return t;if(t===r||e&&t===K(e))break;let n=ee(t);if(n===t)break;t=n}return null}function Ht(s){let e=K(s),t=it(e).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(i=>Fe(re(e,i))))return e;if(e===t)break;let n=ee(e);if(n===e)break;e=n}return K(s)}function Vt(s){let e;try{e=JSON.parse(Dt(s,"utf8"))}catch(n){throw new Error(`Invalid ToolNet project manifest: ${s}: ${n instanceof Error?n.message:String(n)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${s}`);let t=e;if(typeof t.id!="string"||!t.id.trim())throw new Error(`ToolNet project manifest is missing id: ${s}`);if(typeof t.name!="string"||!t.name.trim())throw new Error(`ToolNet project manifest is missing name: ${s}`);let r=new Date().toISOString();return{version:1,id:t.id,name:t.name,remote:typeof t.remote=="string"&&t.remote.trim()?t.remote:t.name,rootPath:typeof t.rootPath=="string"?t.rootPath:ee(ee(s)),createdAt:typeof t.createdAt=="string"?t.createdAt:r,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:r,graphVersion:typeof t.graphVersion=="number"?t.graphVersion:0,memoryVersion:typeof t.memoryVersion=="number"?t.memoryVersion:0,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:void 0}}function nt(s,e){let t=re(s,at);jt(t,{recursive:!0});let r=Ke(s),n=`${r}.tmp-${process.pid}`;Ft(n,JSON.stringify(e,null,2)+`
|
|
3
|
+
`,{encoding:"utf8",mode:384}),$t(n,r)}function ot(s,e){return{id:s.id,name:s.name,remote:s.remote,rootPath:e,createdAt:s.createdAt,updatedAt:s.updatedAt,graphVersion:s.graphVersion,memoryVersion:s.memoryVersion,metadata:s.metadata}}var te=class{detect(e=process.cwd()){let t=K(e),r=Ht(t),i=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(l=>Fe(re(r,l))),o=zt(t,i?r:void 0);if(o){let l=Ke(o),m=Vt(l);return m.rootPath!==o&&(m.rootPath=o,m.updatedAt=new Date().toISOString(),nt(o,m)),ot(m,o)}let a=new Date().toISOString(),p=Kt(r),c={version:1,id:Gt(r),name:p,remote:p,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return nt(r,c),ot(c,r)}};var Wt=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_\-]{20,}\b/g},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._\-]{16,}\b/gi},{type:"jwt",regex:/\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\b/g},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g},{type:"password_assignment",regex:/\b(password|passwd|pwd)\s*[:=]\s*["']?[^"'\s]{6,}["']?/gi},{type:"secret_assignment",regex:/\b(secret|api[_-]?key|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?[^"'\s]{8,}["']?/gi},{type:"cookie",regex:/\b(cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi}],se=class{scan(e){let t=[];for(let r of Wt){let n=new RegExp(r.regex.source,r.regex.flags);for(let i of e.matchAll(n))t.push({type:r.type,value:i[0]})}return t}hasSecrets(e){return this.scan(e).length>0}};var U=class{scanner=new se;sanitize(e){let t=e,r=this.scanner.scan(e),n=new Set;for(let i of r)n.add(i.type),t=t.split(i.value).join(`[REDACTED:${i.type}]`);return{text:t,redacted:r.length,secretTypes:[...n]}}sanitizeValue(e){if(typeof e=="string")return this.sanitize(e).text;if(Array.isArray(e))return e.map(t=>this.sanitizeValue(t));if(e&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e)){let i=r.toLowerCase();i.includes("password")||i.includes("secret")||i.includes("token")||i.includes("cookie")||i.includes("authorization")?t[r]="[REDACTED]":t[r]=this.sanitizeValue(n)}return t}return e}};var ct=[{id:"openai-compatible",label:"OpenAI-compatible",requiresApiKey:!0,requiresBaseUrl:!0,transport:"openai-compatible"},{id:"alibaba",label:"Alibaba / DashScope",requiresApiKey:!0,requiresBaseUrl:!0,transport:"openai-compatible"},{id:"openrouter",label:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1",requiresApiKey:!0,transport:"openai-compatible"},{id:"groq",label:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1",requiresApiKey:!0,transport:"openai-compatible"},{id:"deepseek",label:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com",defaultModel:"deepseek-v4-flash",requiresApiKey:!0,transport:"openai-compatible"},{id:"nvidia",label:"NVIDIA NIM",defaultBaseUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"deepseek-ai/deepseek-v4-pro",requiresApiKey:!0,transport:"openai-compatible"},{id:"gemini",label:"Gemini",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta",requiresApiKey:!0,transport:"gemini"},{id:"huggingface",label:"Hugging Face",defaultBaseUrl:"https://router.huggingface.co/v1",requiresApiKey:!0,transport:"openai-compatible"},{id:"ollama",label:"Ollama / Local",defaultBaseUrl:"http://127.0.0.1:11434/v1",requiresApiKey:!1,transport:"openai-compatible"},{id:"custom",label:"Custom endpoint",requiresApiKey:!1,requiresBaseUrl:!0,transport:"openai-compatible"},{id:"cloudflare",label:"Cloudflare Workers AI",requiresApiKey:!0,requiresAccountId:!0,transport:"cloudflare"}];function ne(s){let e=ct.find(t=>t.id===s);if(!e)throw new Error(`Unsupported AI provider: ${s}`);return e}function oe(s){return ct.some(e=>e.id===s)}function g(s){return process.env[s]?.trim()||void 0}function P(...s){return s.find(e=>!!e?.trim())}function lt(){if(g("GROQ_API_KEY"))return"groq";if(g("DEEPSEEK_API_KEY"))return"deepseek";if(g("NVIDIA_API_KEY")||g("NVIDIA_NIM_API_KEY"))return"nvidia";if(g("OPENROUTER_API_KEY"))return"openrouter";if(g("ALIBABA_API_KEY")||g("DASHSCOPE_API_KEY"))return"alibaba";if(g("GEMINI_API_KEY")||g("GOOGLE_API_KEY"))return"gemini";if(g("CLOUDFLARE_API_TOKEN")&&g("CLOUDFLARE_ACCOUNT_ID"))return"cloudflare";if(g("HF_TOKEN"))return"huggingface";if(g("OLLAMA_MODEL")||g("OLLAMA_BASE_URL"))return"ollama"}function Yt(){let s=g("TOOLNET_LLM_PROVIDER");return s&&oe(s)?s:lt()??"openai-compatible"}function Ue(s){let e=ne(s);switch(s){case"alibaba":return{provider:s,apiKey:P(g("ALIBABA_API_KEY"),g("DASHSCOPE_API_KEY")),baseUrl:P(g("ALIBABA_BASE_URL"),g("DASHSCOPE_BASE_URL"),e.defaultBaseUrl),model:P(g("ALIBABA_MODEL"),g("DASHSCOPE_MODEL"))};case"openrouter":return{provider:s,apiKey:g("OPENROUTER_API_KEY"),baseUrl:P(g("OPENROUTER_BASE_URL"),e.defaultBaseUrl),model:g("OPENROUTER_MODEL")};case"groq":return{provider:s,apiKey:g("GROQ_API_KEY"),baseUrl:P(g("GROQ_BASE_URL"),e.defaultBaseUrl),model:g("GROQ_MODEL")};case"deepseek":return{provider:s,apiKey:g("DEEPSEEK_API_KEY"),baseUrl:P(g("DEEPSEEK_BASE_URL"),e.defaultBaseUrl),model:P(g("DEEPSEEK_MODEL"),e.defaultModel)};case"nvidia":return{provider:s,apiKey:P(g("NVIDIA_API_KEY"),g("NVIDIA_NIM_API_KEY")),baseUrl:P(g("NVIDIA_BASE_URL"),g("NVIDIA_NIM_BASE_URL"),e.defaultBaseUrl),model:P(g("NVIDIA_MODEL"),g("NVIDIA_NIM_MODEL"),e.defaultModel)};case"gemini":return{provider:s,apiKey:P(g("GEMINI_API_KEY"),g("GOOGLE_API_KEY")),baseUrl:P(g("GEMINI_BASE_URL"),e.defaultBaseUrl),model:g("GEMINI_MODEL")};case"huggingface":return{provider:s,apiKey:g("HF_TOKEN"),baseUrl:P(g("HF_INFERENCE_BASE_URL"),e.defaultBaseUrl),model:P(g("HF_LLM_MODEL"),g("HF_MODEL"))};case"ollama":return{provider:s,apiKey:g("OLLAMA_API_KEY"),baseUrl:P(g("OLLAMA_BASE_URL"),e.defaultBaseUrl),model:g("OLLAMA_MODEL")};case"cloudflare":return{provider:s,accountId:g("CLOUDFLARE_ACCOUNT_ID"),apiKey:g("CLOUDFLARE_API_TOKEN"),baseUrl:g("CLOUDFLARE_AI_BASE_URL"),model:g("CLOUDFLARE_MODEL")};case"custom":return{provider:s,apiKey:g("CUSTOM_AI_API_KEY"),baseUrl:g("CUSTOM_AI_BASE_URL"),model:g("CUSTOM_AI_MODEL")};default:return{provider:"openai-compatible",apiKey:P(g("OPENAI_API_KEY"),g("MODEL_API_KEY")),baseUrl:P(g("OPENAI_BASE_URL"),g("MODEL_BASE_URL")),model:P(g("OPENAI_MODEL"),g("MODEL_NAME"))}}}function qt(){let s=g("TOOLNET_LLM_PROVIDER"),e=s&&oe(s)?s:Yt(),t=ne(e),r=Ue(e);return{provider:e,apiKey:P(g("TOOLNET_LLM_API_KEY"),r.apiKey),baseUrl:P(g("TOOLNET_LLM_BASE_URL"),r.baseUrl,t.defaultBaseUrl),model:P(g("TOOLNET_LLM_MODEL"),r.model,t.defaultModel),accountId:P(g("TOOLNET_LLM_ACCOUNT_ID"),r.accountId)}}function Jt(){let s=g("TOOLNET_EMBEDDING_PROVIDER");return s==="local"?"local":s&&oe(s)?s:g("HF_TOKEN")||g("HF_EMBEDDING_MODEL")?"huggingface":"local"}function Qt(){let s=Jt();if(s==="local")return{provider:"local",model:P(g("TOOLNET_EMBEDDING_MODEL"),g("LOCAL_EMBEDDING_MODEL"))};let e=ne(s),t,r,n,i;switch(s){case"huggingface":t=g("HF_TOKEN"),r=g("HF_INFERENCE_BASE_URL"),n=g("HF_EMBEDDING_MODEL");break;case"openai-compatible":t=g("OPENAI_API_KEY"),r=g("OPENAI_BASE_URL"),n=g("OPENAI_EMBEDDING_MODEL");break;case"cloudflare":t=g("CLOUDFLARE_API_TOKEN"),r=g("CLOUDFLARE_AI_BASE_URL"),n=g("CLOUDFLARE_EMBEDDING_MODEL"),i=g("CLOUDFLARE_ACCOUNT_ID");break;default:t=Ue(s).apiKey,r=Ue(s).baseUrl,n=g(`${s.toUpperCase().replace(/-/g,"_")}_EMBEDDING_MODEL`)}let o=P(g("TOOLNET_EMBEDDING_ACCOUNT_ID"),i),a=P(g("TOOLNET_EMBEDDING_BASE_URL"),r,e.defaultBaseUrl),p=s==="cloudflare"&&!a&&o?`https://api.cloudflare.com/client/v4/accounts/${o}/ai/v1`:a;return{provider:s,apiKey:P(g("TOOLNET_EMBEDDING_API_KEY"),t),baseUrl:p,model:P(g("TOOLNET_EMBEDDING_MODEL"),n),accountId:o}}function dt(){let s=qt(),e=Qt();return{llm:s,embedding:e,legacy:{llm:!g("TOOLNET_LLM_PROVIDER")&&!!lt(),embedding:!g("TOOLNET_EMBEDDING_PROVIDER")&&!!(g("HF_TOKEN")||g("HF_EMBEDDING_MODEL"))}}}var ie=class{constructor(e){this.options=e}options;name="gemini";async embed(e){let t=this.options.model.replace(/^models\//,""),n=`${this.options.baseUrl?.replace(/\/+$/,"")||"https://generativelanguage.googleapis.com/v1beta"}/models/${encodeURIComponent(t)}:embedContent?key=${encodeURIComponent(this.options.apiKey)}`,i=await fetch(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:`models/${t}`,content:{parts:[{text:e}]}})});if(!i.ok)throw new Error(`Gemini embedding failed: ${i.status} ${await i.text()}`);let a=(await i.json()).embedding?.values;if(!Array.isArray(a)||a.length===0)throw new Error("Gemini embedding returned invalid response");return a}async embedMany(e){let t=[];for(let r of e)t.push(await this.embed(r));return t}};import{createHash as Zt}from"node:crypto";var ae=class{name="hash-fallback";dimensions=128;async embed(e){let t=new Array(this.dimensions).fill(0),r=e.toLowerCase().split(/\s+/).filter(Boolean);for(let n of r){let o=Zt("sha256").update(n).digest().readUInt32BE(0)%this.dimensions;t[o]+=1}return Xt(t)}async embedMany(e){return Promise.all(e.map(t=>this.embed(t)))}};function Xt(s){let e=Math.sqrt(s.reduce((t,r)=>t+r*r,0));return e===0?s:s.map(t=>t/e)}var ce=class{constructor(e){this.options=e;this.dimensions=e.dimensions}options;name="openai-compatible";dimensions;async embed(e){let[t]=await this.embedMany([e]);return t}async embedMany(e){if(e.length===0)return[];let t=this.options.baseUrl.replace(/\/+$/,""),r=await fetch(`${t}/embeddings`,{method:"POST",headers:{"content-type":"application/json",...this.options.apiKey?{authorization:`Bearer ${this.options.apiKey}`}:{}},body:JSON.stringify({model:this.options.model,input:e})});if(!r.ok)throw new Error(`Embedding failed: ${r.status} ${await r.text()}`);let i=(await r.json()).data?.sort((o,a)=>(o.index??0)-(a.index??0)).map(o=>o.embedding);if(!i||i.length!==e.length||i.some(o=>!Array.isArray(o)))throw new Error("Embedding provider returned invalid response");return i}};var le=class{constructor(e){this.options=e}options;name="huggingface";dimensions=384;async embed(e){let[t]=await this.embedMany([e]);return t}async embedMany(e){if(e.length===0)return[];let t=`https://router.huggingface.co/hf-inference/models/${this.options.model}/pipeline/feature-extraction`,r=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${this.options.token}`,"Content-Type":"application/json"},body:JSON.stringify({inputs:e,options:{wait_for_model:!0}})});if(!r.ok)throw new Error(`HF embedding failed: ${r.status} ${await r.text()}`);let n=await r.json();if(!Array.isArray(n))throw new Error("HF embedding returned invalid response");return n.map(i=>er(i))}};function er(s){if(!Array.isArray(s))throw new Error("Invalid embedding");if(s.length>0&&typeof s[0]=="number")return s;if(s.length>0&&Array.isArray(s[0])){let e=s;if(e.length===0)return[];let t=e[0].length,r=new Array(t).fill(0);for(let n of e)for(let i=0;i<t;i++)r[i]+=n[i]??0;for(let n=0;n<t;n++)r[n]/=e.length;return r}throw new Error("Unsupported embedding shape")}var Ge=class{constructor(e,t=new ae){this.primary=e;this.fallback=t}primary;fallback;name="resilient";async embed(e){if(this.primary)try{return await this.primary.embed(e)}catch(t){console.warn("[embedding] primary failed, fallback enabled:",t instanceof Error?t.message:t)}return this.fallback.embed(e)}async embedMany(e){if(this.primary)try{return await this.primary.embedMany(e)}catch(t){console.warn("[embedding] primary failed, fallback enabled:",t instanceof Error?t.message:t)}return this.fallback.embedMany(e)}};function tr(s){return`https://api.cloudflare.com/client/v4/accounts/${s}/ai/v1`}function rr(){let s=dt().embedding;if(s.provider==="local")return null;if(s.provider==="huggingface")return!s.apiKey||!s.model?null:new le({token:s.apiKey,model:s.model});if(s.provider==="gemini")return!s.apiKey||!s.model?null:new ie({apiKey:s.apiKey,model:s.model,baseUrl:s.baseUrl});let e=s.baseUrl;return s.provider==="cloudflare"&&!e&&s.accountId&&(e=tr(s.accountId)),e&&s.model?new ce({apiKey:s.apiKey,baseUrl:e,model:s.model}):null}function pt(){return new Ge(rr())}import{readdir as ir}from"node:fs/promises";import{extname as ar,join as cr,relative as lr}from"node:path";import{basename as sr}from"node:path";var nr=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),or=new Set([".pem",".key",".p12",".pfx"]);function ut(s){let e=sr(s).toLowerCase();if(nr.has(e))return!0;for(let t of or)if(e.endsWith(t))return!0;return!1}var dr=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),pr=new Set(["node_modules",".git","dist","build","coverage",".next",".cache",".toolnet-memory"]);async function Be(s){let e=[];async function t(r){let n=await ir(r,{withFileTypes:!0});for(let i of n){if(pr.has(i.name))continue;let o=cr(r,i.name);if(i.isDirectory()){await t(o);continue}dr.has(ar(i.name))&&(ut(o)||e.push(lr(s,o)))}}return await t(s),e.sort()}import{readFile as ur}from"node:fs/promises";import{join as mr}from"node:path";import{createHash as fr}from"node:crypto";import*as w from"typescript";function mt(s,e){return fr("sha256").update(`${s}:${e}`).digest("hex").slice(0,24)}function ze(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}async function He(s,e,t){let r=mr(e,t),n=await ur(r,"utf8"),i=w.createSourceFile(t,n,w.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?w.ScriptKind.TSX:w.ScriptKind.TS),o=[],a=[],p=[],c=[],l={id:mt(s,`file:${t}`),projectId:s,name:t,qualifiedName:t,type:"file",filePath:t,startLine:1,endLine:i.getLineAndCharacterOfPosition(i.end).line+1};o.push(l);let m=[],d=[];function f(h,v,b,x){let L=mt(s,`${t}:${b}:${x??v}:${h.pos}`);return o.push({id:L,projectId:s,name:v,qualifiedName:x??v,type:b,filePath:t,startLine:ze(i,h),endLine:i.getLineAndCharacterOfPosition(h.end).line+1}),L}function y(h){if(!w.isStringLiteral(h.moduleSpecifier))return;let v=[],b=h.importClause;if(b?.name&&v.push({localName:b.name.text,importedName:"default",kind:"default"}),b?.namedBindings&&w.isNamedImports(b.namedBindings))for(let x of b.namedBindings.elements)v.push({localName:x.name.text,importedName:x.propertyName?.text??x.name.text,kind:"named"});b?.namedBindings&&w.isNamespaceImport(b.namedBindings)&&v.push({localName:b.namedBindings.name.text,importedName:"*",kind:"namespace"}),a.push({source:h.moduleSpecifier.text,bindings:v})}function u(h,v){for(let b of h.heritageClauses??[])for(let x of b.types){let L=x.expression.getText(i).split(".").at(-1)??"";L&&c.push({fromId:v,targetName:L,type:b.token===w.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function E(h){let v=!1,b=!1;if(w.isImportDeclaration(h)&&y(h),w.isInterfaceDeclaration(h)&&f(h,h.name.text,"interface",h.name.text),w.isClassDeclaration(h)&&h.name){let x=f(h,h.name.text,"class",h.name.text);u(h,x),d.push({id:x,name:h.name.text}),b=!0}if(w.isFunctionDeclaration(h)&&h.name){let x=f(h,h.name.text,"function",h.name.text);m.push(x),v=!0}if(w.isMethodDeclaration(h)&&h.name){let x=h.name.getText(i),L=d.at(-1)?.name,I=f(h,x,"method",L?`${L}.${x}`:x);m.push(I),v=!0}if(w.isCallExpression(h)&&(w.isIdentifier(h.expression)&&p.push({callerId:m.at(-1),calleeName:h.expression.text,line:ze(i,h)}),w.isPropertyAccessExpression(h.expression))){let x=h.expression;p.push({callerId:m.at(-1),qualifier:x.expression.getText(i),calleeName:x.name.text,line:ze(i,h)})}w.forEachChild(h,E),v&&m.pop(),b&&d.pop()}return E(i),{filePath:t,symbols:o,imports:a,calls:p,heritage:c}}import{createHash as gr}from"node:crypto";import{dirname as hr,extname as yr,normalize as br,posix as Sr}from"node:path";var G=class{symbols=new Map;edges=new Map;addSymbol(e){this.symbols.set(e.id,e)}addEdge(e){this.edges.set(e.id,e)}getSymbol(e){return this.symbols.get(e)}findByName(e,t){return[...this.symbols.values()].filter(r=>r.projectId===e&&(r.name===t||r.qualifiedName===t))}allSymbols(e){return[...this.symbols.values()].filter(t=>t.projectId===e)}allEdges(e){return[...this.edges.values()].filter(t=>t.projectId===e)}import(e,t){for(let r of e)this.addSymbol(r);for(let r of t)this.addEdge(r)}clearProject(e){for(let[t,r]of this.symbols)r.projectId===e&&this.symbols.delete(t);for(let[t,r]of this.edges)r.projectId===e&&this.edges.delete(t)}};function Er(s,e,t,r){return gr("sha256").update(`${s}:${e}:${t}:${r}`).digest("hex").slice(0,24)}function _(s){return br(s).replaceAll("\\","/")}function Ve(s,e,t){if(!e.startsWith("."))return;let r=_(Sr.join(hr(s),e)),n=yr(r),i;if(n===".js"){let o=r.slice(0,-3);i=[`${o}.ts`,`${o}.tsx`,`${o}.js`,`${o}.jsx`]}else if(n===".mjs"){let o=r.slice(0,-4);i=[`${o}.mts`,`${o}.ts`,`${o}.mjs`]}else if(n===".cjs"){let o=r.slice(0,-4);i=[`${o}.cts`,`${o}.ts`,`${o}.cjs`]}else n?i=[r]:i=[`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}.js`,`${r}.jsx`,`${r}.mjs`,`${r}.cjs`,`${r}/index.ts`,`${r}/index.tsx`,`${r}/index.js`,`${r}/index.jsx`];return i.find(o=>t.has(_(o)))}var B=class{build(e,t){let r=new G,n=new Map;for(let o of t)for(let a of o.symbols)r.addSymbol(a),a.type==="file"&&n.set(_(o.filePath),a);let i=new Set(n.keys());for(let o of t){let a=_(o.filePath),p=n.get(a);if(p){for(let c of o.symbols)c.id!==p.id&&r.addEdge(this.edge(e,p.id,"DEFINES",c.id));for(let c of o.imports){let l=Ve(a,c.source,i);if(!l)continue;let m=n.get(l);m&&r.addEdge(this.edge(e,p.id,"IMPORTS",m.id,{source:c.source}))}for(let c of o.heritage){let l=r.findByName(e,c.targetName).filter(m=>m.type==="class"||m.type==="interface");for(let m of l)r.addEdge(this.edge(e,c.fromId,c.type,m.id))}for(let c of o.calls){if(!c.callerId)continue;let l=this.resolveCallTargets(e,o,c.calleeName,c.qualifier,t,r,i);for(let m of l)m.id!==c.callerId&&r.addEdge(this.edge(e,c.callerId,"CALLS",m.id,{line:c.line,qualifier:c.qualifier}))}}}return r}resolveCallTargets(e,t,r,n,i,o,a){let p=_(t.filePath),c=o.findByName(e,r).filter(l=>_(l.filePath)===p);if(!n&&c.length)return c;if(n)for(let l of t.imports){if(!l.bindings.find(f=>f.kind==="namespace"&&f.localName===n))continue;let d=Ve(p,l.source,a);if(d)return o.findByName(e,r).filter(f=>_(f.filePath)===d)}for(let l of t.imports){let m=l.bindings.find(u=>u.localName===r);if(!m)continue;let d=Ve(p,l.source,a);if(!d)continue;let f=m.importedName==="default"?r:m.importedName,y=o.findByName(e,f).filter(u=>_(u.filePath)===d);if(y.length)return y}return o.findByName(e,r).filter(l=>l.type==="function"||l.type==="method")}edge(e,t,r,n,i){return{id:Er(e,t,r,n),projectId:e,from:t,to:n,type:r,metadata:i}}};var de=class{async index(e,t,r={}){let n=await Be(t);r.onProgress?.({phase:"scan",current:n.length,total:n.length});let i=[],o=0;for(let p of n)try{i.push(await He(e,t,p))}catch(c){console.warn(`[indexer] skipped ${p}:`,c instanceof Error?c.message:c)}finally{o+=1,r.onProgress?.({phase:"parse",current:o,total:n.length,file:p})}let a=new B().build(e,i);return{files:i.length,symbols:a.allSymbols(e).length,edges:a.allEdges(e).length,graph:a}}};import{execFile as vr}from"node:child_process";import{promisify as xr}from"node:util";var ao=xr(vr);var z=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};import{createHash as wr}from"node:crypto";import{readFile as Cr}from"node:fs/promises";import{join as Pr}from"node:path";function ft(s){return wr("sha256").update(s).digest("hex")}var pe=class{sanitizer=new U;async build(e,t,r,n={}){let i=n.maxLines??80,o=n.overlapLines??10,a=new Map;for(let c of r){let l=a.get(c.filePath)??[];l.push(c),a.set(c.filePath,l)}let p=[];for(let[c,l]of a){let m;try{m=await Cr(Pr(t,c),"utf8")}catch{continue}let d=m.split(/\r?\n/),f=l.filter(y=>y.type!=="file"&&typeof y.startLine=="number"&&typeof y.endLine=="number");if(f.length>0)for(let y of f)p.push(...this.chunkRange({projectId:e,filePath:c,lines:d,symbol:y,startLine:y.startLine,endLine:y.endLine,maxLines:i,overlapLines:o}));else p.push(...this.chunkRange({projectId:e,filePath:c,lines:d,startLine:1,endLine:Math.max(1,d.length),maxLines:i,overlapLines:o}))}return p}chunkRange(e){let{projectId:t,filePath:r,lines:n,symbol:i,maxLines:o}=e,a=Math.min(e.overlapLines,Math.max(0,o-1)),p=Math.max(1,e.startLine),c=Math.min(n.length,Math.max(p,e.endLine)),l=[],m=p,d=0;for(;m<=c;){let f=Math.min(c,m+o-1),y=n.slice(m-1,f).join(`
|
|
4
|
+
`).trim();if(y){let u=this.sanitizer.sanitize(y).text,E=ft(u),h=[t,r,i?.id??"file",String(d),E].join(":");l.push({id:ft(h).slice(0,32),projectId:t,filePath:r,symbolId:i?.id,symbolName:i?.qualifiedName??i?.name,symbolType:i?.type,startLine:m,endLine:f,content:u,contentHash:E})}if(f>=c)break;m=f-a+1,d++}return l}};var ue=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"code","chunks","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};var me=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"code","vectors","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};var fe=class{records=new Map;upsert(e){this.records.set(e.id,e)}get(e){return this.records.get(e)}has(e){return this.records.has(e)}remove(e){return this.records.delete(e)}clearProject(e){let t=0;for(let[r,n]of this.records)n.projectId===e&&(this.records.delete(r),t++);return t}exportProject(e){return[...this.records.values()].filter(t=>t.projectId===e)}importRecords(e){let t=0;for(let r of e)!r?.id||!r?.projectId||!Array.isArray(r.vector)||(this.records.set(r.id,r),t++);return t}search(e,t,r=10){let n=[];for(let i of this.records.values()){if(i.projectId!==e)continue;let o=Ar(t,i.vector);n.push({id:i.id,score:o,metadata:i.metadata})}return n.sort((i,o)=>o.score-i.score).slice(0,r)}size(){return this.records.size}};function Ar(s,e){if(s.length===0||e.length===0||s.length!==e.length)return 0;let t=0,r=0,n=0;for(let i=0;i<s.length;i++){let o=s[i]??0,a=e[i]??0;t+=o*a,r+=o*o,n+=a*a}return r===0||n===0?0:t/(Math.sqrt(r)*Math.sqrt(n))}function We(s){return s.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}_\-./]+/gu," ").split(/\s+/).map(e=>e.trim()).filter(e=>e.length>1)}function gt(s,e){let t=s.toLowerCase().replaceAll("\\","/"),r=e.toLowerCase(),n=/\b(test|tests|spec|fixture|mock)\b/.test(r);return(t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t))&&!n?.35:t.includes("/generated/")||t.includes(".generated.")?.25:1}var ge=class{constructor(e){this.options=e}options;vectors=new fe;chunks=new Map;async initialize(){let{projectId:e,rootPath:t,storage:r,embeddings:n,graph:i,model:o}=this.options,a=new ue(r),p=new me(r),c=await new pe().build(e,t,i.allSymbols(e));this.chunks.clear();for(let I of c)this.chunks.set(I.id,I);let l=await a.load(e),m=!l||l.chunks.length!==c.length||l.chunks.some(I=>!this.chunks.has(I.id));m&&await a.save({version:1,projectId:e,updatedAt:new Date().toISOString(),chunks:c});let d=await p.load(e),f=0;d&&d.model===o&&(f=this.vectors.importRecords(d.records));let y=new Set(c.map(I=>I.id)),u=0;for(let I of this.vectors.exportProject(e))y.has(I.id)||this.vectors.remove(I.id)&&u++;let E=c.filter(I=>{let k=this.vectors.get(I.id);return k?k.metadata?.contentHash!==I.contentHash:!0}),h=0,v=8,b=this.vectors.exportProject(e)[0]?.vector.length;for(let I=0;I<E.length;I+=v){let k=E.slice(I,I+v),It=k.map(T=>[`file: ${T.filePath}`,T.symbolName?`symbol: ${T.symbolName}`:"",T.symbolType?`type: ${T.symbolType}`:"",T.content].filter(Boolean).join(`
|
|
5
|
+
`)),Lt=await n.embedMany(It);for(let T=0;T<k.length;T++){let M=k[T],O=Lt[T];if(!(!M||!O||O.length===0)){if(b===void 0&&(b=O.length),O.length!==b){console.warn(`[code-semantic] skip dimension mismatch: ${O.length} != ${b}`);continue}this.vectors.upsert({id:M.id,projectId:e,vector:O,metadata:{contentHash:M.contentHash,filePath:M.filePath,symbolName:M.symbolName,symbolType:M.symbolType,startLine:M.startLine,endLine:M.endLine}}),h++}}}let x=this.vectors.exportProject(e),L=h>0||u>0||!d||d.model!==o;return L&&await p.save({version:1,projectId:e,model:o,dimensions:x[0]?.vector.length??b??0,updatedAt:new Date().toISOString(),records:x}),{chunks:c.length,vectorsLoaded:f,vectorsIndexed:h,vectorsRemoved:u,totalVectors:x.length,savedChunks:m,savedVectors:L}}async search(e,t=8){let r=await this.options.embeddings.embed(e),n=this.vectors.search(this.options.projectId,r,Math.max(t*4,20)),i=new Set(We(e)),o=[];for(let a of n){let p=this.chunks.get(a.id);if(!p)continue;let c=new Set(We([p.filePath,p.symbolName??"",p.symbolType??"",p.content].join(" "))),l=0;for(let u of i)c.has(u)&&l++;let m=i.size===0?0:l/i.size,d=Math.max(0,a.score),f=gt(p.filePath,e),y=(d*.75+m*.25)*f;o.push({chunk:p,score:y,vectorScore:d,lexicalScore:m})}return o.sort((a,p)=>p.score-a.score).slice(0,t)}size(){return this.chunks.size}};import{createHash as Ir}from"node:crypto";import{dirname as Lr,relative as he,resolve as ye}from"node:path";import*as C from"typescript";function j(s){return s.replaceAll("\\","/").replace(/^\.\//,"")}function ht(s){return Ir("sha256").update(s).digest("hex").slice(0,24)}function H(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}function Rr(s){let e=s;if(e.name&&C.isIdentifier(e.name))return e.name.text}var be=class{constructor(e){this.graph=e}graph;async resolveProject(e,t){let r=this.loadConfig(t),n=C.createProgram({rootNames:r.fileNames,options:r.options}),i=n.getTypeChecker(),o=[];for(let a of n.getSourceFiles()){if(a.isDeclarationFile)continue;let p=ye(a.fileName),c=j(he(t,p));if(c.startsWith("../")||c.includes("node_modules/"))continue;let l=m=>{if(C.isCallExpression(m)){let d=this.resolveCall({projectId:e,rootPath:t,source:a,node:m,checker:i});d&&o.push(d)}C.isClassDeclaration(m)&&o.push(...this.resolveHeritage({projectId:e,rootPath:t,source:a,node:m,checker:i})),C.forEachChild(m,l)};l(a)}return{version:1,projectId:e,updatedAt:new Date().toISOString(),total:o.length,exact:o.filter(a=>a.confidence==="exact").length,high:o.filter(a=>a.confidence==="high").length,fallback:o.filter(a=>a.confidence==="fallback").length,resolutions:o}}resolveCall(e){let{projectId:t,rootPath:r,source:n,node:i,checker:o}=e,a;if(a=o.getResolvedSignature(i)?.declaration,!a){let c=o.getSymbolAtLocation(i.expression);a=c?.valueDeclaration??c?.declarations?.[0]}return a?this.fromDeclaration({projectId:t,rootPath:r,source:n,sourceNode:i,declaration:a,expression:i.expression.getText(n),kind:"CALL"}):this.fallbackCall(t,r,n,i)}resolveHeritage(e){let{projectId:t,rootPath:r,source:n,node:i,checker:o}=e,a=[];for(let p of i.heritageClauses??[])for(let c of p.types){let l=o.getSymbolAtLocation(c.expression),m=l?.valueDeclaration??l?.declarations?.[0];if(!m)continue;let d=this.fromDeclaration({projectId:t,rootPath:r,source:n,sourceNode:c,declaration:m,expression:c.getText(n),kind:p.token===C.SyntaxKind.ExtendsKeyword?"EXTENDS":"IMPLEMENTS"});d&&a.push(d)}return a}fromDeclaration(e){let t=e.declaration.getSourceFile();if(t.isDeclarationFile)return null;let r=j(he(e.rootPath,ye(t.fileName)));if(r.startsWith("../")||r.includes("node_modules/"))return null;let n=H(t,e.declaration),i=Rr(e.declaration)??e.expression.split(".").at(-1),o=this.findGraphSymbol(e.projectId,r,n,i),a=j(he(e.rootPath,ye(e.source.fileName)));return{id:ht([e.projectId,a,H(e.source,e.sourceNode),e.kind,r,n].join(":")),projectId:e.projectId,kind:e.kind,sourceFile:a,sourceLine:H(e.source,e.sourceNode),expression:e.expression,targetFile:r,targetLine:n,targetName:i,targetQualifiedName:o?.qualifiedName,targetSymbolId:o?.id,confidence:o?"exact":"high",resolver:"typescript-checker"}}fallbackCall(e,t,r,n){let i=n.expression.getText(r).split(".").at(-1);if(!i)return null;let o=this.graph.findByName(e,i).filter(c=>c.type==="function"||c.type==="method");if(o.length!==1)return null;let a=o[0],p=j(he(t,ye(r.fileName)));return{id:ht(`${e}:${p}:${H(r,n)}:${a.id}`),projectId:e,kind:"CALL",sourceFile:p,sourceLine:H(r,n),expression:n.expression.getText(r),targetFile:a.filePath,targetLine:a.startLine,targetName:a.name,targetQualifiedName:a.qualifiedName,targetSymbolId:a.id,confidence:"fallback",resolver:"graph-fallback"}}findGraphSymbol(e,t,r,n){let o=this.graph.allSymbols(e).filter(a=>j(a.filePath)===j(t)).filter(a=>typeof a.startLine=="number"&&typeof a.endLine=="number"&&a.startLine<=r&&a.endLine>=r);if(n){let a=o.find(p=>p.name===n||(p.qualifiedName?.endsWith(`.${n}`)??!1));if(a)return a}return o.sort((a,p)=>(a.endLine??0)-(a.startLine??0)-((p.endLine??0)-(p.startLine??0)))[0]}loadConfig(e){let t=C.findConfigFile(e,C.sys.fileExists,"tsconfig.json");if(t){let n=C.readConfigFile(t,C.sys.readFile);if(n.error)throw new Error(C.flattenDiagnosticMessageText(n.error.messageText,`
|
|
6
|
+
`));return C.parseJsonConfigFileContent(n.config,C.sys,Lr(t))}return{fileNames:C.sys.readDirectory(e,[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],["node_modules",".git","dist","build","coverage"]),options:{allowJs:!0,checkJs:!1,target:C.ScriptTarget.ES2022,module:C.ModuleKind.NodeNext,moduleResolution:C.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noEmit:!0}}}};import{createHash as Tr}from"node:crypto";import{dirname as kr,relative as V,resolve as W}from"node:path";import*as S from"typescript";function R(s){return s.replaceAll("\\","/").replace(/^\.\//,"")}function Ye(...s){return Tr("sha256").update(s.join(":")).digest("hex").slice(0,24)}function Y(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}var Mr=new Set(["get","post","put","patch","delete","options","head"]),_r=new Set([S.SyntaxKind.EqualsToken,S.SyntaxKind.PlusEqualsToken,S.SyntaxKind.MinusEqualsToken,S.SyntaxKind.AsteriskEqualsToken,S.SyntaxKind.SlashEqualsToken,S.SyntaxKind.PercentEqualsToken,S.SyntaxKind.QuestionQuestionEqualsToken,S.SyntaxKind.AmpersandAmpersandEqualsToken,S.SyntaxKind.BarBarEqualsToken]),Se=class{constructor(e){this.graph=e}graph;enrich(e,t,r){let n={routes:0,tests:0,usesType:0,writes:0,callReferences:0,properties:0},i=this.loadConfig(t),o=S.createProgram({rootNames:i.fileNames,options:i.options}),a=o.getTypeChecker();for(let p of o.getSourceFiles()){if(p.isDeclarationFile)continue;let c=R(V(t,W(p.fileName)));if(c.startsWith("../")||c.includes("node_modules/"))continue;let l=this.fileNode(e,c);if(!l)continue;let m=d=>{if(S.isCallExpression(d)&&this.addRoute(e,t,p,l,d,a)&&n.routes++,S.isTypeReferenceNode(d)&&this.addTypeUse(e,t,p,d,a)&&n.usesType++,S.isBinaryExpression(d)&&_r.has(d.operatorToken.kind)){let f=this.addWrite(e,t,p,d.left,a);f.added&&(n.writes++,f.propertyCreated&&n.properties++)}if((S.isPrefixUnaryExpression(d)||S.isPostfixUnaryExpression(d))&&(d.operator===S.SyntaxKind.PlusPlusToken||d.operator===S.SyntaxKind.MinusMinusToken)){let f=this.addWrite(e,t,p,d.operand,a);f.added&&(n.writes++,f.propertyCreated&&n.properties++)}S.forEachChild(d,m)};m(p)}return n.tests+=this.addTestEdges(e),r&&(n.callReferences+=this.addResolvedCalls(e,r)),n}addRoute(e,t,r,n,i,o){if(!S.isPropertyAccessExpression(i.expression))return!1;let a=i.expression.name.text.toLowerCase();if(!Mr.has(a))return!1;let p=i.arguments[0];if(!p||!(S.isStringLiteral(p)||S.isNoSubstitutionTemplateLiteral(p)))return!1;let c=p.text;if(!c.startsWith("/"))return!1;let l=Y(r,i),m=Ye(e,r.fileName,l,a,c);this.graph.getSymbol(m)||(this.graph.addSymbol({id:m,projectId:e,name:`${a.toUpperCase()} ${c}`,qualifiedName:`${a.toUpperCase()} ${c}`,type:"route",filePath:n.filePath,startLine:l,endLine:l}),this.graph.addEdge(this.edge(e,n.id,"DEFINES",m)));let d=i.arguments.at(-1);if(d){let f=this.resolveNodeSymbol(e,t,d,o);f&&this.graph.addEdge(this.edge(e,m,"ROUTE",f.id,{method:a.toUpperCase(),path:c}))}return!0}addTypeUse(e,t,r,n,i){let o=this.resolveNodeSymbol(e,t,n.typeName,i);if(!o)return!1;let a=this.containingSymbol(e,R(V(t,W(r.fileName))),Y(r,n));return!a||a.id===o.id?!1:(this.graph.addEdge(this.edge(e,a.id,"USES_TYPE",o.id)),!0)}addWrite(e,t,r,n,i){let o=this.resolveTsSymbol(n,i),a=o?.valueDeclaration??o?.declarations?.[0];if(!a)return{added:!1,propertyCreated:!1};let p=a.getSourceFile();if(p.isDeclarationFile)return{added:!1,propertyCreated:!1};let c=R(V(t,W(p.fileName)));if(c.startsWith("../")||c.includes("node_modules/"))return{added:!1,propertyCreated:!1};let l=Y(p,a),m=this.findSymbolAt(e,c,l),d=!1;if(!m||m.type==="file"){let u=o?.getName()??n.getText(r),E=Ye(e,c,"property",u,l);if(m=this.graph.getSymbol(E),!m){m={id:E,projectId:e,name:u,qualifiedName:u,type:"property",filePath:c,startLine:l,endLine:l},this.graph.addSymbol(m);let h=this.fileNode(e,c);h&&this.graph.addEdge(this.edge(e,h.id,"DEFINES",m.id)),d=!0}}if(!m)return{added:!1,propertyCreated:d};let f=R(V(t,W(r.fileName))),y=this.containingSymbol(e,f,Y(r,n));return!y||y.id===m.id?{added:!1,propertyCreated:d}:(this.graph.addEdge(this.edge(e,y.id,"WRITES",m.id,{expression:n.getText(r)})),{added:!0,propertyCreated:d})}addTestEdges(e){let t=this.graph.allEdges(e),r=0;for(let n of t){if(n.type!=="IMPORTS")continue;let i=this.graph.getSymbol(n.from),o=this.graph.getSymbol(n.to);!i||!o||!this.isTestFile(i.filePath)||this.isTestFile(o.filePath)||(this.graph.addEdge(this.edge(e,i.id,"TESTS",o.id)),r++)}return r}addResolvedCalls(e,t){let r=0;for(let n of t.resolutions){if(n.kind!=="CALL"||!n.targetSymbolId)continue;let i=this.graph.getSymbol(n.targetSymbolId);if(!i)continue;let o=this.containingSymbol(e,n.sourceFile,n.sourceLine);!o||o.id===i.id||this.graph.allEdges(e).some(p=>p.type==="CALLS"&&p.from===o.id&&p.to===i.id)||(this.graph.addEdge(this.edge(e,o.id,"CALL_REFERENCE",i.id,{expression:n.expression,confidence:n.confidence,resolver:n.resolver})),r++)}return r}resolveNodeSymbol(e,t,r,n){let i=this.resolveTsSymbol(r,n),o=i?.valueDeclaration??i?.declarations?.[0];if(!o)return;let a=o.getSourceFile();if(a.isDeclarationFile)return;let p=R(V(t,W(a.fileName)));if(!(p.startsWith("../")||p.includes("node_modules/")))return this.findSymbolAt(e,p,Y(a,o),i?.getName())}resolveTsSymbol(e,t){let r=t.getSymbolAtLocation(e);if(r&&r.flags&S.SymbolFlags.Alias)try{r=t.getAliasedSymbol(r)}catch{}return r}containingSymbol(e,t,r){return this.graph.allSymbols(e).filter(n=>R(n.filePath)===R(t)&&typeof n.startLine=="number"&&typeof n.endLine=="number"&&n.startLine<=r&&n.endLine>=r).sort((n,i)=>(n.endLine??0)-(n.startLine??0)-((i.endLine??0)-(i.startLine??0)))[0]}findSymbolAt(e,t,r,n){let i=this.graph.allSymbols(e).filter(o=>R(o.filePath)===R(t)&&typeof o.startLine=="number"&&typeof o.endLine=="number"&&o.startLine<=r&&o.endLine>=r).sort((o,a)=>(o.endLine??0)-(o.startLine??0)-((a.endLine??0)-(a.startLine??0)));if(n){let o=i.find(a=>a.name===n||(a.qualifiedName?.endsWith(`.${n}`)??!1));if(o)return o}return i[0]}fileNode(e,t){return this.graph.allSymbols(e).find(r=>r.type==="file"&&R(r.filePath)===R(t))}isTestFile(e){let t=R(e).toLowerCase();return t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t)}edge(e,t,r,n,i){return{id:Ye(e,t,r,n,JSON.stringify(i??{})),projectId:e,from:t,to:n,type:r,metadata:i}}loadConfig(e){let t=S.findConfigFile(e,S.sys.fileExists,"tsconfig.json");if(t){let r=S.readConfigFile(t,S.sys.readFile);return S.parseJsonConfigFileContent(r.config,S.sys,kr(t))}return{fileNames:S.sys.readDirectory(e,[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],["node_modules",".git","dist","build","coverage"]),options:{allowJs:!0,noEmit:!0,skipLibCheck:!0,target:S.ScriptTarget.ES2022,module:S.ModuleKind.NodeNext,moduleResolution:S.ModuleResolutionKind.NodeNext}}}};function Nr(s){return s.replaceAll("\\","/").toLowerCase()}var D=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=[];for(let o of t){if(o.type!=="route"&&o.type!=="file")continue;let a=this.classify(o,r);a&&n.push({symbolId:o.id,filePath:o.filePath,name:o.name,kind:a.kind,score:a.score,reasons:a.reasons})}let i=new Map;for(let o of n){let a=o.kind==="route"?o.symbolId:o.filePath,p=i.get(a);(!p||o.score>p.score)&&i.set(a,o)}return[...i.values()].sort((o,a)=>a.score-o.score||o.filePath.localeCompare(a.filePath))}classify(e,t){let r=Nr(e.filePath),n=[];if(e.type==="route")return{kind:"route",score:100,reasons:["HTTP route"]};let i=null,o=0;if(r.startsWith("bin/"))i="cli",o=100,n.push("bin executable");else if(/(^|\/)(cli)\.[^.]+$/.test(r))i="cli",o=90,n.push("CLI entry file");else if(/(^|\/)(main|server)\.[^.]+$/.test(r))i="main",o=90,n.push("main/server file");else if(r.includes("/runtime/")&&/(^|\/)(bootstrap|index)\.[^.]+$/.test(r))i="runtime",o=75,n.push("runtime bootstrap");else if(/(^|\/)index\.[^.]+$/.test(r)){let p=t.filter(l=>l.to===e.id&&l.type!=="DEFINES").length,c=t.filter(l=>l.from===e.id&&l.type!=="DEFINES").length;(r.startsWith("packages/")||p===0||c>0)&&(i="package",o=r.startsWith("packages/")?70:55,n.push("package/public index"))}return i?(t.filter(p=>p.to===e.id&&p.type!=="DEFINES").length===0&&(o+=10,n.push("no incoming dependency")),{kind:i,score:o,reasons:n}):null}};var Or={CALL_REFERENCE:6,CALLS:4,IMPORTS:3,USES_TYPE:4,WRITES:5,ROUTE:4,TESTS:1,INHERITS:5,IMPLEMENTS:5,DEFINES:.25},Ee=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=new Map(t.map(c=>[c.id,c])),i=new Map,o=c=>{let l=i.get(c);return l||(l={symbols:0,incoming:0,outgoing:0,weightedIncoming:0,weightedOutgoing:0,writes:0,callReferences:0,crossFile:0},i.set(c,l)),l};for(let c of t)o(c.filePath).symbols++;for(let c of r){let l=n.get(c.from),m=n.get(c.to);if(!l||!m)continue;let d=Or[c.type]??1,f=o(l.filePath),y=o(m.filePath);f.outgoing++,y.incoming++,f.weightedOutgoing+=d,y.weightedIncoming+=d,c.type==="WRITES"&&f.writes++,c.type==="CALL_REFERENCE"&&f.callReferences++,l.filePath!==m.filePath&&(f.crossFile++,y.crossFile++)}let a=[...i.entries()].map(([c,l])=>{let m=Number((l.symbols*.4+l.weightedIncoming*1.75+l.weightedOutgoing*.65+l.crossFile*1.5+l.writes*3+l.callReferences*2).toFixed(2)),d=[];return l.incoming>=10&&d.push("high incoming dependency"),l.crossFile>=10&&d.push("high cross-file coupling"),l.callReferences>=5&&d.push("many exact call references"),l.writes>0&&d.push("contains write relationships"),l.symbols>=10&&d.push("high symbol density"),{filePath:c,score:m,symbols:l.symbols,incoming:l.incoming,outgoing:l.outgoing,reasons:d}}).filter(c=>c.score>0).sort((c,l)=>l.score-c.score||c.filePath.localeCompare(l.filePath));if(a.length===0)return[];let p=Math.max(1,Math.min(30,Math.ceil(a.length*.15)));return a.slice(0,p)}};function jr(s){return s.replaceAll("\\","/").toLowerCase()}var Dr={CALL_REFERENCE:6,CALLS:4,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:6,IMPLEMENTS:6,ROUTE:3,TESTS:1},ve=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=new Map(t.map(a=>[a.id,a])),i=[...new Set(t.map(a=>a.filePath))].sort(),o=new Map;for(let a of i)o.set(a,this.classifyPath(a));for(let a=0;a<3;a++){let p=!1;for(let c of i){let l=o.get(c);if(!l||l.layer!=="unknown")continue;let m=new Map;for(let f of r){let y=n.get(f.from),u=n.get(f.to);if(!y||!u||y.filePath===u.filePath)continue;let E=null;if(y.filePath===c?E=u.filePath:u.filePath===c&&(E=y.filePath),!E)continue;let h=o.get(E);if(!h||h.layer==="unknown"||h.layer==="tests")continue;let v=Dr[f.type]??1;m.set(h.layer,(m.get(h.layer)??0)+v)}let d=[...m.entries()].sort((f,y)=>y[1]-f[1]||f[0].localeCompare(y[0]))[0];d&&d[1]>=4&&(o.set(c,{filePath:c,layer:d[0],confidence:.65,reasons:[`graph-neighbor vote=${d[1]}`]}),p=!0)}if(!p)break}return i.map(a=>o.get(a))}classifyPath(e){let t=jr(e);return t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t)?{filePath:e,layer:"tests",confidence:1,reasons:["test path"]}:t.startsWith("bin/")||t.includes("/mcp/")||t.includes("/cli/")||t.includes("/api/")||t.includes("/routes/")||t.includes("/hooks/")?{filePath:e,layer:"interface",confidence:.9,reasons:["interface boundary"]}:t.includes("/runtime/")||t.includes("/processor/")||t.includes("/retrieval/")||t.includes("/snapshot/")||t.includes("/code-intelligence/")?{filePath:e,layer:"application",confidence:.85,reasons:["application orchestration"]}:t.includes("/core/")||t.includes("/memory/")||/(^|\/)types\.[^.]+$/.test(t)?{filePath:e,layer:"domain",confidence:.9,reasons:["domain/core logic"]}:t.includes("/storage/")||t.includes("/production/")||t.includes("/security/")||t.includes("/config/")||t.includes("/utils/")?{filePath:e,layer:"infrastructure",confidence:.85,reasons:["infrastructure boundary"]}:{filePath:e,layer:"unknown",confidence:.35,reasons:[]}}};import{createHash as $r}from"node:crypto";var Fr={CALL_REFERENCE:7,CALLS:3,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:7,IMPLEMENTS:7,ROUTE:4,TESTS:1};function Kr(s){return $r("sha256").update(s).digest("hex").slice(0,12)}function xe(s){return s.replaceAll("\\","/")}function Ur(s){let t=xe(s).split("/").filter(Boolean);return t[0]==="src"&&t[1]?`src/${t[1]}`:t[0]==="packages"&&t[1]?`packages/${t[1]}`:t[0]==="tests"?"tests":t[0]==="bin"?"bin":t[0]??"root"}function Gr(s){let e=s.replace(/^src\//,"").replace(/^packages\//,"");return{"code-intelligence":"Code Intelligence",memory:"Memory",storage:"Storage",retrieval:"Retrieval",runtime:"Runtime",mcp:"MCP",hooks:"Hooks",security:"Security",snapshot:"Snapshots",production:"Production",capture:"Capture",processor:"Processor",core:"Core",tests:"Tests",bin:"CLI",sdk:"SDK",cli:"CLI"}[e]??e}var we=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=new Map(t.map(d=>[d.id,d])),i=[...new Set(t.map(d=>xe(d.filePath)))].sort(),o=new Map,a=(d,f)=>{let y=[d,f].sort();return`${y[0]}\0${y[1]}`};for(let d of r){let f=n.get(d.from),y=n.get(d.to);if(!f||!y)continue;let u=xe(f.filePath),E=xe(y.filePath);if(u===E)continue;let h=Fr[d.type]??0;if(h<=0)continue;let v=a(u,E),b=o.get(v);b?b.weight+=h:o.set(v,{a:[u,E].sort()[0],b:[u,E].sort()[1],weight:h})}let p=new Map;for(let d of i){let f=Ur(d),y=p.get(f)??[];y.push(d),p.set(f,y)}let c=[];for(let[d,f]of p){if(f.sort(),f.length<=30){c.push({subsystem:d,files:f});continue}let y=new Set(f),u=new Map;for(let b of f)u.set(b,new Set);for(let b of o.values())!y.has(b.a)||!y.has(b.b)||b.weight>=8&&(u.get(b.a)?.add(b.b),u.get(b.b)?.add(b.a));let E=new Set,h=[];for(let b of f){if(E.has(b))continue;let x=[b],L=[];for(E.add(b);x.length>0;){let I=x.shift();L.push(I);for(let k of u.get(I)??[])E.has(k)||(E.add(k),x.push(k))}h.push(L.sort())}let v=[];for(let b of h)b.length>=2?c.push({subsystem:d,files:b}):v.push(...b);v.length>0&&c.push({subsystem:`${d}/residual`,files:v.sort()})}let l=c.map(d=>({subsystem:d.subsystem,files:[...d.files]}));for(let d=0;d<3;d++){let f=!1;e:for(let y=0;y<l.length;y++){let u=l[y];if(!(!u||u.files.length>3))for(let E=0;E<l.length;E++){if(y===E)continue;let h=l[E];if(!h)continue;let v=0,b=new Set(u.files),x=new Set(h.files);for(let L of o.values())(b.has(L.a)&&x.has(L.b)||b.has(L.b)&&x.has(L.a))&&(v+=L.weight);if(v>=20){h.files=[...new Set([...h.files,...u.files])].sort(),l.splice(y,1),f=!0;break e}}}if(!f)break}let m=[];for(let d of l){let f=new Set(d.files),y=0,u=0;for(let x of o.values()){let L=f.has(x.a),I=f.has(x.b);L&&I?y+=x.weight:(L||I)&&(u+=x.weight)}let E=y+u,h=d.subsystem.replace(/\/residual$/,""),v=Gr(h),b=d.subsystem.endsWith("/residual")?`${v} Misc`:v;m.push({id:`cluster-${Kr(`${d.subsystem}:${d.files.join("|")}`)}`,label:b,subsystem:h,files:d.files,size:d.files.length,internalWeight:y,externalWeight:u,cohesion:E>0?Number((y/E).toFixed(4)):0})}return m.sort((d,f)=>f.size-d.size||f.cohesion-d.cohesion||d.label.localeCompare(f.label))}};var Ce=class{constructor(e){this.graph=e;this.entryPoints=new D(e),this.hotspots=new Ee(e),this.layers=new ve(e),this.clusters=new we(e)}graph;entryPoints;hotspots;layers;clusters;analyze(e){let t=this.entryPoints.detect(e),r=this.hotspots.analyze(e),n=this.layers.detect(e),i=this.clusters.detect(e),o=new Set(this.graph.allSymbols(e).map(a=>a.filePath));return{version:1,projectId:e,updatedAt:new Date().toISOString(),summary:{files:o.size,entryPoints:t.length,hotspots:r.length,layers:n.length,clusters:i.length},entryPoints:t,hotspots:r,layers:n,clusters:i}}};var yt=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE","TESTS"]);function qe(s){return s.replaceAll("\\","/").toLowerCase()}function Br(s){let e=qe(s);return e.startsWith("tests/")||e.includes("/tests/")||e.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(e)}function zr(s){let e=qe(s.filePath);return e.startsWith("bin/")||/(^|\/)index\.[^.]+$/.test(e)||/(^|\/)(main|server|cli)\.[^.]+$/.test(e)}var Pe=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=new Set(new D(this.graph).detect(e).map(o=>o.symbolId)),i=[];for(let o of t){if(!["function","method","class","interface","property"].includes(o.type)||Br(o.filePath)||n.has(o.id)||zr(o)||r.filter(f=>f.to===o.id&&yt.has(f.type)).length>0)continue;let p=r.filter(f=>f.from===o.id&&yt.has(f.type)),c=["no incoming usage edge"],l=50;(o.type==="function"||o.type==="method")&&(l+=20,c.push("callable symbol")),o.type==="property"&&(l-=15),p.length===0&&(l+=10,c.push("no outgoing dependency")),qe(o.filePath).includes("/internal/")&&(l+=10,c.push("internal implementation")),o.name.startsWith("_")&&(l+=5);let d=l>=75?"high":l>=55?"medium":"low";i.push({symbolId:o.id,name:o.name,qualifiedName:o.qualifiedName,type:o.type,filePath:o.filePath,startLine:o.startLine,confidence:d,score:l,reasons:c})}return i.sort((o,a)=>a.score-o.score||o.filePath.localeCompare(a.filePath)||o.name.localeCompare(a.name))}};var Hr=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE"]),Ae=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e).filter(o=>Hr.has(o.type)),n=new Map(t.map(o=>[o.id,o]));return[...new Set(t.map(o=>o.filePath))].sort().map(o=>{let a=new Set,p=new Set,c=0,l=0;for(let m of r){let d=n.get(m.from),f=n.get(m.to);!d||!f||d.filePath===f.filePath||(d.filePath===o&&(a.add(f.filePath),c++),f.filePath===o&&(p.add(d.filePath),l++))}return{filePath:o,dependencies:[...a].sort(),dependents:[...p].sort(),outgoingEdges:c,incomingEdges:l}})}};var Ie=class{constructor(e){this.graph=e}graph;analyze(e){let t=new Pe(this.graph).analyze(e),r=new Ae(this.graph).analyze(e);return{version:1,projectId:e,updatedAt:new Date().toISOString(),summary:{deadCodeCandidates:t.length,highConfidenceDeadCode:t.filter(n=>n.confidence==="high").length,files:r.length},deadCode:t,dependencies:r}}};var Le=class{constructor(e){this.graph=e}graph;build(e,t,r){let n=this.graph.allSymbols(e),i=this.graph.allEdges(e),o=new Map(t?.layers.map(u=>[u.filePath,u.layer])??[]),a=new Map;for(let u of t?.clusters??[])for(let E of u.files)a.set(E,{id:u.id,label:u.label});let p=new Map(t?.hotspots.map(u=>[u.filePath,u.score])??[]),c=new Map(r?.deadCode.map(u=>[u.symbolId,{confidence:u.confidence,score:u.score}])??[]),l=new Map,m=new Map;for(let u of i)m.set(u.from,(m.get(u.from)??0)+1),l.set(u.to,(l.get(u.to)??0)+1);let d=n.map(u=>{let E=a.get(u.filePath);return{id:u.id,name:u.name,qualifiedName:u.qualifiedName,type:u.type,filePath:u.filePath,layer:o.get(u.filePath),cluster:E?.id,clusterLabel:E?.label,hotspotScore:p.get(u.filePath),deadCode:c.get(u.id),incoming:l.get(u.id)??0,outgoing:m.get(u.id)??0}}),f=new Set(d.map(u=>u.id)),y=i.filter(u=>f.has(u.from)&&f.has(u.to)).map(u=>({source:u.from,target:u.to,type:u.type,confidence:typeof u.metadata?.confidence=="string"?u.metadata.confidence:void 0,resolver:typeof u.metadata?.resolver=="string"?u.metadata.resolver:void 0}));return{version:1,projectId:e,generatedAt:new Date().toISOString(),summary:{nodes:d.length,links:y.length,files:new Set(d.map(u=>u.filePath)).size,clusters:new Set(d.map(u=>u.cluster).filter(Boolean)).size},nodes:d,links:y}}};import{homedir as fs}from"node:os";import{join as gs}from"node:path";import{DeleteObjectCommand as Vr,GetObjectCommand as Wr,HeadObjectCommand as Yr,ListObjectsV2Command as qr,PutObjectCommand as Jr,S3Client as Qr}from"@aws-sdk/client-s3";import{getSignedUrl as Zr}from"@aws-sdk/s3-request-presigner";var Re=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Qr({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,r="application/octet-stream"){let n=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Jr({Bucket:this.bucket,Key:e,Body:n,ContentType:r}))}async get(e){let t=await Zr(this.client,new Wr({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new Yr({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new Vr({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let n=await this.client.send(new qr({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let i of n.Contents??[])i.Key&&t.push({key:i.Key,size:i.Size,updatedAt:i.LastModified?.toISOString()});r=n.IsTruncated?n.NextContinuationToken:void 0}while(r);return t}};import{access as bt,mkdir as Xr,readFile as es,readdir as ts,rm as rs,stat as St,writeFile as ss}from"node:fs/promises";import{dirname as ns,join as os,relative as Et,resolve as is}from"node:path";var q=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return is(this.root,t)}async put(e,t){let r=this.path(e);await Xr(ns(r),{recursive:!0}),await ss(r,t)}async get(e){try{return await es(this.path(e))}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return null;throw t}}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await bt(this.path(e)),!0}catch{return!1}}async delete(e){await rs(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),r=[];try{await bt(t)}catch{return r}let n=async o=>{let a=await ts(o,{withFileTypes:!0});for(let p of a){let c=os(o,p.name);if(p.isDirectory()){await n(c);continue}let l=await St(c);r.push({key:Et(this.root,c),size:l.size,updatedAt:l.mtime.toISOString()})}},i=await St(t);return i.isDirectory()?await n(t):r.push({key:Et(this.root,t),size:i.size,updatedAt:i.mtime.toISOString()}),r}};import{DeleteObjectCommand as as,GetObjectCommand as cs,HeadObjectCommand as ls,ListObjectsV2Command as ds,PutObjectCommand as ps,S3Client as us}from"@aws-sdk/client-s3";import{getSignedUrl as ms}from"@aws-sdk/s3-request-presigner";var J=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new us({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,r="application/octet-stream"){let n=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new ps({Bucket:this.bucket,Key:e,Body:n,ContentType:r}))}async get(e){let t=await ms(this.client,new cs({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new ls({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new as({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let n=await this.client.send(new ds({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let i of n.Contents??[])i.Key&&t.push({key:i.Key,size:i.Size,updatedAt:i.LastModified?.toISOString()});r=n.IsTruncated?n.NextContinuationToken:void 0}while(r);return t}};function Je(s,e){return console.warn(e),new q(s)}function vt(s){let e=s.localRoot??gs(fs(),".toolnet-memory","storage");if(s.provider==="r2"){let t=s.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new J({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):Je(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(s.provider==="s3"){let t=s.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?new J({name:"s3",endpoint:t.endpoint,region:t.region??"us-east-1",bucket:t.bucket,forcePathStyle:t.forcePathStyle??!1,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):Je(e,"[storage] S3 credentials missing. Using local fallback.")}if(s.provider==="huggingface"){let t=s.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new Re({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):Je(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new q(e)}function hs(s){return new Promise(e=>setTimeout(e,s))}async function xt(s,e={}){let t=Math.max(1,e.attempts??3),r=e.baseDelayMs??150,n=e.maxDelayMs??2e3,i;for(let o=1;o<=t;o++)try{return await s()}catch(a){if(i=a,o>=t)break;let p=Math.min(n,r*2**(o-1)),c=Math.floor(Math.random()*Math.max(1,p*.2));await hs(p+c)}throw i}var ys=new Set(["put","get","getText","delete","list"]);function wt(s,e={}){return new Proxy(s,{get(t,r){let n=Reflect.get(t,r,t);return typeof n!="function"?n:ys.has(r)?(...i)=>xt(()=>Promise.resolve(n.apply(t,i)),e):n.bind(t)}})}function Ct(s){let e=s.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function Pt(s){let e=s.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let t=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(t)return`${t[1]}memory/records/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),t)return`${t[1]}memory/vectors/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),t)return`${t[1]}code/graph/${t[2]}`;let r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let n=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return n?`${n[1]}memory/records/${n[2]}`:(n=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),n?`${n[1]}memory/vectors/${n[2]}`:(n=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),n?`${n[1]}code/graph/${n[2]}`:e))}var Te=class{constructor(e,t,r,n){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=r,this.folder=Ct(n??r),this.sourcePrefix=`projects/${t}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,t=new Date().toISOString(),r=t,n=await this.provider.getText(e);if(n){let o;try{o=JSON.parse(n)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${a instanceof Error?a.message:String(a)}`)}if(typeof o.id=="string"&&o.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${o.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof o.createdAt=="string"&&(r=o.createdAt)}let i={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:t};await this.provider.put(e,JSON.stringify(i,null,2)+`
|
|
7
|
+
`,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=Pt(e),e===this.sourcePrefix)return this.targetPrefix;if(e.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+e.slice(this.sourcePrefix.length);if(e===this.targetPrefix||e.startsWith(`${this.targetPrefix}/`))return e;if(e.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${e}`].join(" "));return e}async put(e,t,r){return await this.ensureRegistered(),this.provider.put(this.key(e),t,r)}async get(e){return await this.ensureRegistered(),this.provider.get(this.key(e))}async getText(e){return await this.ensureRegistered(),this.provider.getText(this.key(e))}async delete(e){return await this.ensureRegistered(),this.provider.delete(this.key(e))}async exists(e){return await this.ensureRegistered(),this.provider.exists(this.key(e))}async list(e){return await this.ensureRegistered(),this.provider.list(this.key(e))}};var ke=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","resolution","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};var Me=class{constructor(e){this.storage=e}storage;base(e){return["projects",e,"code","architecture"].join("/")}async load(e){let t=await this.storage.getText(`${this.base(e)}/current.json`);return t?JSON.parse(t):null}async save(e){let t=this.base(e.projectId),r=n=>JSON.stringify({version:e.version,projectId:e.projectId,updatedAt:e.updatedAt,data:n},null,2);await Promise.all([this.storage.put(`${t}/current.json`,JSON.stringify(e,null,2),"application/json"),this.storage.put(`${t}/entry-points.json`,r(e.entryPoints),"application/json"),this.storage.put(`${t}/hotspots.json`,r(e.hotspots),"application/json"),this.storage.put(`${t}/layers.json`,r(e.layers),"application/json"),this.storage.put(`${t}/clusters.json`,r(e.clusters),"application/json")])}};var _e=class{constructor(e){this.storage=e}storage;base(e){return["projects",e,"code","analysis"].join("/")}async load(e){let t=await this.storage.getText(`${this.base(e)}/current.json`);return t?JSON.parse(t):null}async save(e){let t=this.base(e.projectId),r=n=>JSON.stringify({version:e.version,projectId:e.projectId,updatedAt:e.updatedAt,data:n},null,2);await Promise.all([this.storage.put(`${t}/current.json`,JSON.stringify(e,null,2),"application/json"),this.storage.put(`${t}/dead-code.json`,r(e.deadCode),"application/json"),this.storage.put(`${t}/dependencies.json`,r(e.dependencies),"application/json")])}};var Ne=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"code","visualization","graph.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e,null,2),"application/json")}};async function At(s,e={}){let t=Date.now();async function r(u,E,h){await e.onStage?.({id:u,title:E,state:"start"});let v=Date.now(),b=await h();return await e.onStage?.({id:u,title:E,state:"complete",durationMs:Date.now()-v}),b}let n=st(),i=wt(vt({provider:n.storage.provider,huggingface:n.storage.huggingface,localRoot:n.storage.localRoot}),{attempts:3}),o=new Te(i,s.id,s.name,s.remote??s.name),a=new z(o),p=await r("source-index","Source Index",async()=>{let u=await new de().index(s.id,s.rootPath,{onProgress:E=>{e.onSourceProgress?.(E)}});return await a.save({version:1,projectId:s.id,updatedAt:new Date().toISOString(),files:u.files,symbols:u.graph.allSymbols(s.id),edges:u.graph.allEdges(s.id)}),u}),c=p.graph,l=await r("type-resolution","Type Resolution",async()=>{let u=await new be(c).resolveProject(s.id,s.rootPath);return await new ke(o).save(u),u});await r("rich-graph","Rich Graph",async()=>{let u=new Se(c).enrich(s.id,s.rootPath,l),E=c.allSymbols(s.id),h=c.allEdges(s.id);return await a.save({version:1,projectId:s.id,updatedAt:new Date().toISOString(),files:E.filter(v=>v.type==="file").length,symbols:E,edges:h}),u});let m=await r("semantic-index","Semantic Code Index",async()=>new ge({projectId:s.id,rootPath:s.rootPath,model:process.env.HF_EMBEDDING_MODEL??"sentence-transformers/all-MiniLM-L6-v2",storage:o,embeddings:pt(),graph:c}).initialize()),d=await r("architecture","Architecture Intelligence",async()=>{let u=new Ce(c).analyze(s.id);return await new Me(o).save(u),u}),f=await r("analysis","Graph Analysis",async()=>{let u=new Ie(c).analyze(s.id);return await new _e(o).save(u),u}),y=await r("visualization","3D Visualization Dataset",async()=>{let u=new Le(c).build(s.id,d,f);return await new Ne(o).save(u),u});return{files:p.files,project:{id:s.id,name:s.name,remote:s.remote??s.name},storage:o.name,durationMs:Date.now()-t,graph:{symbols:c.allSymbols(s.id).length,edges:c.allEdges(s.id).length},resolution:{total:l.total,exact:l.exact,high:l.high,fallback:l.fallback},semantic:m,architecture:d.summary,analysis:f.summary,visualization:y.summary}}var Oe=["\u25C6","\u25C7"],A={save:"\x1B[s",restore:"\x1B[u",clearDown:"\x1B[J",hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",reset:"\x1B[0m",green:"\x1B[32m",gray:"\x1B[90m",white:"\x1B[97m",amber:"\x1B[38;5;214m",cyan:"\x1B[36m"};function Q(s){return new Intl.NumberFormat("en-US").format(s)}function Qe(s){return s<1e3?`${s}ms`:`${(s/1e3).toFixed(1)}s`}function bs(s,e,t=24){let r=e>0?Math.min(1,Math.max(0,s/e)):0,n=Math.round(r*t);return"\u2501".repeat(n)+"\u2500".repeat(Math.max(0,t-n))}var je=class{stream;interactive;enabled;rootPath;stages;timer;spinnerFrame=0;scanTotal;parseCurrent=0;parseTotal=0;startedAt=Date.now();lastPlainParseBucket=-1;constructor(e){this.stream=e.stream??process.stdout,this.enabled=e.enabled??!0,this.interactive=e.interactive??this.stream.isTTY===!0,this.rootPath=e.rootPath,this.stages=e.stages.map(t=>({...t,state:"pending"}))}start(){if(this.enabled){if(this.startedAt=Date.now(),!this.interactive){this.stream.write(`\u25C7 Initializing ToolNet Index
|
|
8
|
+
`),this.stream.write(`\u25C7 Initialized in ${this.rootPath}
|
|
9
|
+
`);return}this.stream.write(`${A.hideCursor}${A.save}`),this.render(),this.timer=setInterval(()=>{this.spinnerFrame=(this.spinnerFrame+1)%Oe.length,this.render()},160),this.timer.unref?.()}}scanningComplete(e){if(this.scanTotal=e,this.parseTotal=e,!!this.enabled){if(!this.interactive){this.stream.write(`\u25C6 Scanning files \u2014 ${Q(e)} found
|
|
10
|
+
`);return}this.render()}}parsingProgress(e,t){if(this.parseCurrent=e,this.parseTotal=t,!!this.enabled){if(!this.interactive){let r=t>0?Math.floor(e/t*100):100,n=r>=100?100:Math.floor(r/25)*25;n!==this.lastPlainParseBucket&&(this.lastPlainParseBucket=n,this.stream.write(`\u2192 Parsing code \u2014 ${r}%
|
|
11
|
+
`));return}this.render()}}startStage(e,t){let r=this.stages.find(n=>n.id===e);if(r&&(r.state="active",r.title=t),!!this.enabled){if(!this.interactive){e!=="source-index"&&this.stream.write(`\u2192 ${t}
|
|
12
|
+
`);return}this.render()}}completeStage(e,t,r=0){let n=this.stages.find(i=>i.id===e);if(n&&(n.state="done",n.title=t,n.durationMs=r),!!this.enabled){if(!this.interactive){e==="source-index"?this.stream.write(`\u2713 Parsing code \u2014 done
|
|
13
|
+
`):this.stream.write(`\u2713 ${t} (${Qe(r)})
|
|
14
|
+
`);return}this.render()}}finish(e){if(this.stopTimer(),!this.enabled)return;this.interactive&&(this.render(!0),this.stream.write(A.showCursor));let t=["",`\u25C6 Indexed ${Q(e.files)} files`,"",`\u25C7 ${Q(e.symbols)} symbols, ${Q(e.edges)} edges in ${Qe(e.durationMs)}`,`\u25C7 Storage: ${e.storage}`,"","Done",""];this.stream.write(t.join(`
|
|
15
|
+
`))}fail(e){this.stopTimer(),this.enabled&&(this.interactive&&this.stream.write(`${A.restore}${A.clearDown}${A.showCursor}`),this.stream.write(`\u2717 ${e}
|
|
16
|
+
`))}stopTimer(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}color(e,t){return!this.interactive||process.env.NO_COLOR!==void 0?e:`${t}${e}${A.reset}`}frame(e=!1){let t=[];t.push(this.color("\u25C7 Initializing ToolNet Index",A.white)),t.push(""),t.push(`${this.color("\u25C6",A.green)} Initialized in ${this.rootPath}`),t.push(this.color("\u2502",A.gray)),this.scanTotal!==void 0?t.push(`${this.color("\u251C",A.gray)} ${this.color("\u25C6",A.green)} Scanning files \u2014 ${Q(this.scanTotal)} found`):t.push(`${this.color("\u251C",A.gray)} ${this.color(Oe[this.spinnerFrame],A.amber)} Scanning files`);let r=this.parseTotal>0&&this.parseCurrent>=this.parseTotal;if(this.scanTotal!==void 0)if(r)t.push(`${this.color("\u251C",A.gray)} ${this.color("\u25C6",A.green)} Parsing code \u2014 done`);else{let n=this.parseTotal>0?Math.floor(this.parseCurrent/this.parseTotal*100):0,i=bs(this.parseCurrent,this.parseTotal);t.push(`${this.color("\u251C",A.gray)} ${this.color(Oe[this.spinnerFrame],A.amber)} Parsing code ${this.color(i,A.amber)} ${String(n).padStart(3)}%`)}for(let n of this.stages)if(n.id!=="source-index"&&!(n.state==="pending"&&!e)){if(n.state==="active"){t.push(`${this.color("\u251C",A.gray)} ${this.color(Oe[this.spinnerFrame],A.amber)} ${n.title}`);continue}n.state==="done"&&t.push(`${this.color("\u251C",A.gray)} ${this.color("\u25C6",A.green)} ${n.title} \u2014 done`)}return t.push(this.color("\u2502",A.gray)),t.push(`${this.color("\u25C7",A.cyan)} ${Qe(Date.now()-this.startedAt)}`),t.join(`
|
|
17
|
+
`)}render(e=!1){!this.enabled||!this.interactive||this.stream.write(`${A.restore}${A.clearDown}${this.frame(e)}`)}};var X=new te().detect(),rt=tt(X.rootPath,".toolnet"),Ze=tt(rt,"index.lock"),Cs=tt(rt,"last-index.json"),Xe=process.argv.includes("--json"),Ps=[{id:"source-index",title:"Source Index"},{id:"type-resolution",title:"Resolving refs"},{id:"rich-graph",title:"Building rich graph"},{id:"semantic-index",title:"Semantic index"},{id:"architecture",title:"Architecture intelligence"},{id:"analysis",title:"Graph analysis"},{id:"visualization",title:"Visualization dataset"}],N=new je({rootPath:X.rootPath,stages:Ps,enabled:!Xe});Es(rt,{recursive:!0});function De(s){ws(Cs,JSON.stringify(s,null,2)+`
|
|
18
|
+
`,{encoding:"utf8",mode:384})}var et;try{et=vs(Ze,"wx",384)}catch{console.error("\u274C Index already running for this project."),console.error(`Lock: ${Ze}`),process.exit(2)}var $e=new Date().toISOString(),Z=[];try{N.start(),De({version:2,state:"running",startedAt:$e,completedStages:Z,project:X});let s=await At(X,{onSourceProgress:e=>{if(e.phase==="scan"){N.scanningComplete(e.total);return}N.parsingProgress(e.current,e.total)},onStage:async e=>{e.state==="start"?N.startStage(e.id,e.title):(Z.push(e.id),N.completeStage(e.id,e.title,e.durationMs??0)),De({version:2,state:"running",startedAt:$e,currentStage:e.id,completedStages:[...Z],project:X})}});De({version:2,state:"complete",startedAt:$e,finishedAt:new Date().toISOString(),completedStages:Z,result:s}),Xe?console.log(JSON.stringify(s,null,2)):N.finish({files:s.files,symbols:s.graph.symbols,edges:s.graph.edges,durationMs:s.durationMs,storage:s.storage})}catch(s){let e=s instanceof Error?s.message:String(s);De({version:2,state:"failed",startedAt:$e,failedAt:new Date().toISOString(),completedStages:Z,error:e}),N.fail(`Full index failed: ${e}`),Xe&&console.error(e),process.exitCode=1}finally{et!==void 0&&Ss(et),xs(Ze,{force:!0})}
|
package/bundle/graph-index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"dotenv/config";import{existsSync as ce,readFileSync as le}from"node:fs";import{homedir as de}from"node:os";import{join as pe}from"node:path";function
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function
|
|
3
|
-
`,{encoding:"utf8",mode:384}),ye(o,r)}function J(s,e){return{id:s.id,name:s.name,remote:s.remote,rootPath:e,createdAt:s.createdAt,updatedAt:s.updatedAt,graphVersion:s.graphVersion,memoryVersion:s.memoryVersion,metadata:s.metadata}}var M=class{detect(e=process.cwd()){let t=k(e),r=we(t),n=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(f=>D(O(r,f))),i=ve(t,n?r:void 0);if(i){let f=G(i),m=Pe(f);return m.rootPath!==i&&(m.rootPath=i,m.updatedAt=new Date().toISOString(),Y(i,m)),J(m,i)}let d=new Date().toISOString(),g=be(r),l={version:1,id:Ce(r),name:g,remote:g,rootPath:r,createdAt:d,updatedAt:d,graphVersion:0,memoryVersion:0};return Y(r,l),J(l,r)}};import{readdir as Ae}from"node:fs/promises";import{extname as Le,join as Ne,relative as Ie}from"node:path";import{basename as Re}from"node:path";var Te=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),je=new Set([".pem",".key",".p12",".pfx"]);function Z(s){let e=Re(s).toLowerCase();if(Te.has(e))return!0;for(let t of je)if(e.endsWith(t))return!0;return!1}var Me=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),Oe=new Set(["node_modules",".git","dist","build","coverage",".next",".cache",".toolnet-memory"]);async function K(s){let e=[];async function t(r){let o=await Ae(r,{withFileTypes:!0});for(let n of o){if(Oe.has(n.name))continue;let i=Ne(r,n.name);if(n.isDirectory()){await t(i);continue}Me.has(Le(n.name))&&(Z(i)||e.push(Ie(s,i)))}}return await t(s),e.sort()}import{readFile as _e}from"node:fs/promises";import{join as Fe}from"node:path";import{createHash as $e}from"node:crypto";import*as c from"typescript";function X(s,e){return $e("sha256").update(`${s}:${e}`).digest("hex").slice(0,24)}function z(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}async function B(s,e,t){let r=Fe(e,t),o=await _e(r,"utf8"),n=c.createSourceFile(t,o,c.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?c.ScriptKind.TSX:c.ScriptKind.TS),i=[],d=[],g=[],l=[],f={id:X(s,`file:${t}`),projectId:s,name:t,qualifiedName:t,type:"file",filePath:t,startLine:1,endLine:n.getLineAndCharacterOfPosition(n.end).line+1};i.push(f);let m=[],x=[];function b(a,y,h,u){let C=X(s,`${t}:${h}:${u??y}:${a.pos}`);return i.push({id:C,projectId:s,name:y,qualifiedName:u??y,type:h,filePath:t,startLine:z(n,a),endLine:n.getLineAndCharacterOfPosition(a.end).line+1}),C}function N(a){if(!c.isStringLiteral(a.moduleSpecifier))return;let y=[],h=a.importClause;if(h?.name&&y.push({localName:h.name.text,importedName:"default",kind:"default"}),h?.namedBindings&&c.isNamedImports(h.namedBindings))for(let u of h.namedBindings.elements)y.push({localName:u.name.text,importedName:u.propertyName?.text??u.name.text,kind:"named"});h?.namedBindings&&c.isNamespaceImport(h.namedBindings)&&y.push({localName:h.namedBindings.name.text,importedName:"*",kind:"namespace"}),d.push({source:a.moduleSpecifier.text,bindings:y})}function v(a,y){for(let h of a.heritageClauses??[])for(let u of h.types){let C=u.expression.getText(n).split(".").at(-1)??"";C&&l.push({fromId:y,targetName:C,type:h.token===c.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function U(a){let y=!1,h=!1;if(c.isImportDeclaration(a)&&N(a),c.isInterfaceDeclaration(a)&&b(a,a.name.text,"interface",a.name.text),c.isClassDeclaration(a)&&a.name){let u=b(a,a.name.text,"class",a.name.text);v(a,u),x.push({id:u,name:a.name.text}),h=!0}if(c.isFunctionDeclaration(a)&&a.name){let u=b(a,a.name.text,"function",a.name.text);m.push(u),y=!0}if(c.isMethodDeclaration(a)&&a.name){let u=a.name.getText(n),C=x.at(-1)?.name,ae=b(a,u,"method",C?`${C}.${u}`:u);m.push(ae),y=!0}if(c.isCallExpression(a)&&(c.isIdentifier(a.expression)&&g.push({callerId:m.at(-1),calleeName:a.expression.text,line:z(n,a)}),c.isPropertyAccessExpression(a.expression))){let u=a.expression;g.push({callerId:m.at(-1),qualifier:u.expression.getText(n),calleeName:u.name.text,line:z(n,a)})}c.forEachChild(a,U),y&&m.pop(),h&&x.pop()}return U(n),{filePath:t,symbols:i,imports:d,calls:g,heritage:l}}import{createHash as De}from"node:crypto";import{dirname as Ge,extname as Ke,normalize as ze,posix as Be}from"node:path";var R=class{symbols=new Map;edges=new Map;addSymbol(e){this.symbols.set(e.id,e)}addEdge(e){this.edges.set(e.id,e)}getSymbol(e){return this.symbols.get(e)}findByName(e,t){return[...this.symbols.values()].filter(r=>r.projectId===e&&(r.name===t||r.qualifiedName===t))}allSymbols(e){return[...this.symbols.values()].filter(t=>t.projectId===e)}allEdges(e){return[...this.edges.values()].filter(t=>t.projectId===e)}import(e,t){for(let r of e)this.addSymbol(r);for(let r of t)this.addEdge(r)}clearProject(e){for(let[t,r]of this.symbols)r.projectId===e&&this.symbols.delete(t);for(let[t,r]of this.edges)r.projectId===e&&this.edges.delete(t)}};function We(s,e,t,r){return De("sha256").update(`${s}:${e}:${t}:${r}`).digest("hex").slice(0,24)}function E(s){return ze(s).replaceAll("\\","/")}function W(s,e,t){if(!e.startsWith("."))return;let r=E(Be.join(Ge(s),e)),o=Ke(r),n;if(o===".js"){let i=r.slice(0,-3);n=[`${i}.ts`,`${i}.tsx`,`${i}.js`,`${i}.jsx`]}else if(o===".mjs"){let i=r.slice(0,-4);n=[`${i}.mts`,`${i}.ts`,`${i}.mjs`]}else if(o===".cjs"){let i=r.slice(0,-4);n=[`${i}.cts`,`${i}.ts`,`${i}.cjs`]}else o?n=[r]:n=[`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}.js`,`${r}.jsx`,`${r}.mjs`,`${r}.cjs`,`${r}/index.ts`,`${r}/index.tsx`,`${r}/index.js`,`${r}/index.jsx`];return n.find(i=>t.has(E(i)))}var T=class{build(e,t){let r=new R,o=new Map;for(let i of t)for(let d of i.symbols)r.addSymbol(d),d.type==="file"&&o.set(E(i.filePath),d);let n=new Set(o.keys());for(let i of t){let d=E(i.filePath),g=o.get(d);if(g){for(let l of i.symbols)l.id!==g.id&&r.addEdge(this.edge(e,g.id,"DEFINES",l.id));for(let l of i.imports){let f=W(d,l.source,n);if(!f)continue;let m=o.get(f);m&&r.addEdge(this.edge(e,g.id,"IMPORTS",m.id,{source:l.source}))}for(let l of i.heritage){let f=r.findByName(e,l.targetName).filter(m=>m.type==="class"||m.type==="interface");for(let m of f)r.addEdge(this.edge(e,l.fromId,l.type,m.id))}for(let l of i.calls){if(!l.callerId)continue;let f=this.resolveCallTargets(e,i,l.calleeName,l.qualifier,t,r,n);for(let m of f)m.id!==l.callerId&&r.addEdge(this.edge(e,l.callerId,"CALLS",m.id,{line:l.line,qualifier:l.qualifier}))}}}return r}resolveCallTargets(e,t,r,o,n,i,d){let g=E(t.filePath),l=i.findByName(e,r).filter(f=>E(f.filePath)===g);if(!o&&l.length)return l;if(o)for(let f of t.imports){if(!f.bindings.find(b=>b.kind==="namespace"&&b.localName===o))continue;let x=W(g,f.source,d);if(x)return i.findByName(e,r).filter(b=>E(b.filePath)===x)}for(let f of t.imports){let m=f.bindings.find(v=>v.localName===r);if(!m)continue;let x=W(g,f.source,d);if(!x)continue;let b=m.importedName==="default"?r:m.importedName,N=i.findByName(e,b).filter(v=>E(v.filePath)===x);if(N.length)return N}return i.findByName(e,r).filter(f=>f.type==="function"||f.type==="method")}edge(e,t,r,o,n){return{id:We(e,t,r,o),projectId:e,from:t,to:o,type:r,metadata:n}}};var _=class{async index(e,t){let r=await K(t),o=[];for(let i of r)try{o.push(await B(e,t,i))}catch(d){console.warn(`[indexer] skipped ${i}:`,d instanceof Error?d.message:d)}let n=new T().build(e,o);return{files:o.length,symbols:n.allSymbols(e).length,edges:n.allEdges(e).length,graph:n}}};function ee(s,e){let t=s.allSymbols(e),r=s.allEdges(e),o=i=>t.filter(d=>d.type===i).length,n=i=>r.filter(d=>d.type===i).length;return{files:o("file"),classes:o("class"),interfaces:o("interface"),functions:o("function"),methods:o("method"),properties:o("property"),routes:o("route"),symbols:t.length,edges:r.length,calls:n("CALLS"),callReferences:n("CALL_REFERENCE"),imports:n("IMPORTS"),inherits:n("INHERITS"),implements:n("IMPLEMENTS"),usesType:n("USES_TYPE"),tests:n("TESTS"),routeEdges:n("ROUTE"),writes:n("WRITES")}}import{execFile as He}from"node:child_process";import{promisify as Ue}from"node:util";var Rr=Ue(He);var j=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};import*as S from"typescript";import*as p from"typescript";var Gs=new Set([p.SyntaxKind.EqualsToken,p.SyntaxKind.PlusEqualsToken,p.SyntaxKind.MinusEqualsToken,p.SyntaxKind.AsteriskEqualsToken,p.SyntaxKind.SlashEqualsToken,p.SyntaxKind.PercentEqualsToken,p.SyntaxKind.QuestionQuestionEqualsToken,p.SyntaxKind.AmpersandAmpersandEqualsToken,p.SyntaxKind.BarBarEqualsToken]);import{homedir as ht}from"node:os";import{join as yt}from"node:path";import{DeleteObjectCommand as Ye,GetObjectCommand as Je,HeadObjectCommand as qe,ListObjectsV2Command as Qe,PutObjectCommand as Ze,S3Client as Xe}from"@aws-sdk/client-s3";import{getSignedUrl as et}from"@aws-sdk/s3-request-presigner";var F=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Xe({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,r="application/octet-stream"){let o=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Ze({Bucket:this.bucket,Key:e,Body:o,ContentType:r}))}async get(e){let t=await et(this.client,new Je({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new qe({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new Ye({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let o=await this.client.send(new Qe({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let n of o.Contents??[])n.Key&&t.push({key:n.Key,size:n.Size,updatedAt:n.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return t}};import{access as te,mkdir as tt,readFile as rt,readdir as st,rm as ot,stat as re,writeFile as nt}from"node:fs/promises";import{dirname as it,join as at,relative as se,resolve as ct}from"node:path";var A=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return ct(this.root,t)}async put(e,t){let r=this.path(e);await tt(it(r),{recursive:!0}),await nt(r,t)}async get(e){try{return await rt(this.path(e))}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return null;throw t}}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await te(this.path(e)),!0}catch{return!1}}async delete(e){await ot(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),r=[];try{await te(t)}catch{return r}let o=async i=>{let d=await st(i,{withFileTypes:!0});for(let g of d){let l=at(i,g.name);if(g.isDirectory()){await o(l);continue}let f=await re(l);r.push({key:se(this.root,l),size:f.size,updatedAt:f.mtime.toISOString()})}},n=await re(t);return n.isDirectory()?await o(t):r.push({key:se(this.root,t),size:n.size,updatedAt:n.mtime.toISOString()}),r}};import{DeleteObjectCommand as lt,GetObjectCommand as dt,HeadObjectCommand as pt,ListObjectsV2Command as mt,PutObjectCommand as ft,S3Client as ut}from"@aws-sdk/client-s3";import{getSignedUrl as gt}from"@aws-sdk/s3-request-presigner";var L=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new ut({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,r="application/octet-stream"){let o=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new ft({Bucket:this.bucket,Key:e,Body:o,ContentType:r}))}async get(e){let t=await gt(this.client,new dt({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new pt({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new lt({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let o=await this.client.send(new mt({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let n of o.Contents??[])n.Key&&t.push({key:n.Key,size:n.Size,updatedAt:n.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return t}};function H(s,e){return console.warn(e),new A(s)}function oe(s){let e=s.localRoot??yt(ht(),".toolnet-memory","storage");if(s.provider==="r2"){let t=s.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new L({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):H(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(s.provider==="s3"){let t=s.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?new L({name:"s3",endpoint:t.endpoint,region:t.region??"us-east-1",bucket:t.bucket,forcePathStyle:t.forcePathStyle??!1,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):H(e,"[storage] S3 credentials missing. Using local fallback.")}if(s.provider==="huggingface"){let t=s.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new F({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):H(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new A(e)}function ne(s){let e=s.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function ie(s){let e=s.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let t=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(t)return`${t[1]}memory/records/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),t)return`${t[1]}memory/vectors/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),t)return`${t[1]}code/graph/${t[2]}`;let r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let o=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return o?`${o[1]}memory/records/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),o?`${o[1]}memory/vectors/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),o?`${o[1]}code/graph/${o[2]}`:e))}var $=class{constructor(e,t,r,o){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=r,this.folder=ne(o??r),this.sourcePrefix=`projects/${t}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,t=new Date().toISOString(),r=t,o=await this.provider.getText(e);if(o){let i;try{i=JSON.parse(o)}catch(d){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${d instanceof Error?d.message:String(d)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(r=i.createdAt)}let n={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:t};await this.provider.put(e,JSON.stringify(n,null,2)+`
|
|
4
|
-
`,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=ie(e),e===this.sourcePrefix)return this.targetPrefix;if(e.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+e.slice(this.sourcePrefix.length);if(e===this.targetPrefix||e.startsWith(`${this.targetPrefix}/`))return e;if(e.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${e}`].join(" "));return e}async put(e,t,r){return await this.ensureRegistered(),this.provider.put(this.key(e),t,r)}async get(e){return await this.ensureRegistered(),this.provider.get(this.key(e))}async getText(e){return await this.ensureRegistered(),this.provider.getText(this.key(e))}async delete(e){return await this.ensureRegistered(),this.provider.delete(this.key(e))}async exists(e){return await this.ensureRegistered(),this.provider.exists(this.key(e))}async list(e){return await this.ensureRegistered(),this.provider.list(this.key(e))}};async function St(){let s=V(),e=new
|
|
1
|
+
import"dotenv/config";import{existsSync as ce,readFileSync as le}from"node:fs";import{homedir as de}from"node:os";import{join as pe}from"node:path";function ue(s){let e=s.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function me(){let s=process.env.TOOLNET_GLOBAL_ENV??pe(de(),".config","toolnet-memory",".env");if(!ce(s))return;let e=le(s,"utf8");for(let t of e.split(/\r?\n/)){let r=t.trim();if(!r||r.startsWith("#"))continue;r.startsWith("export ")&&(r=r.slice(7));let o=r.indexOf("=");if(o<=0)continue;let n=r.slice(0,o).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)&&process.env[n]===void 0&&(process.env[n]=ue(r.slice(o+1)))}}me();function v(s,e){return s===void 0?e:["1","true","yes","on"].includes(s.toLowerCase())}function P(s,e){if(!s)return e;let t=Number(s);return Number.isFinite(t)?t:e}function V(){return{memory:{autoCapture:v(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:v(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:v(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:v(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:P(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:P(process.env.MEMORY_RERANK_TOP,10),finalContext:P(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:P(process.env.MEMORY_TOKEN_BUDGET,2e3)},storage:{provider:process.env.MEMORY_STORAGE_PROVIDER??"huggingface",r2:{accountId:process.env.R2_ACCOUNT_ID,bucket:process.env.R2_BUCKET,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY},s3:{endpoint:process.env.S3_ENDPOINT,region:process.env.S3_REGION,bucket:process.env.S3_BUCKET,accessKeyId:process.env.S3_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY,forcePathStyle:v(process.env.S3_FORCE_PATH_STYLE,!1)},huggingface:{namespace:process.env.HF_NAMESPACE,bucket:process.env.HF_BUCKET,accessKeyId:process.env.HF_S3_ACCESS_KEY_ID,secretAccessKey:process.env.HF_S3_SECRET_ACCESS_KEY},localRoot:process.env.MEMORY_LOCAL_STORAGE_PATH},cache:{maxMb:P(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as fe}from"node:crypto";import{existsSync as D,mkdirSync as ge,readFileSync as he,renameSync as ye,writeFileSync as Se}from"node:fs";import{basename as be,dirname as N,join as O,parse as J,resolve as k}from"node:path";var Q=".toolnet",xe="project.json";function Ce(s){return fe("sha256").update(s).digest("hex").slice(0,16)}function G(s){return O(s,Q,xe)}function Ee(s){return D(G(s))}function we(s,e){let t=k(s),r=J(t).root;for(;;){if(Ee(t))return t;if(t===r||e&&t===k(e))break;let o=N(t);if(o===t)break;t=o}return null}function ve(s){let e=k(s),t=J(e).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(n=>D(O(e,n))))return e;if(e===t)break;let o=N(e);if(o===e)break;e=o}return k(s)}function Pe(s){let e;try{e=JSON.parse(he(s,"utf8"))}catch(o){throw new Error(`Invalid ToolNet project manifest: ${s}: ${o instanceof Error?o.message:String(o)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${s}`);let t=e;if(typeof t.id!="string"||!t.id.trim())throw new Error(`ToolNet project manifest is missing id: ${s}`);if(typeof t.name!="string"||!t.name.trim())throw new Error(`ToolNet project manifest is missing name: ${s}`);let r=new Date().toISOString();return{version:1,id:t.id,name:t.name,remote:typeof t.remote=="string"&&t.remote.trim()?t.remote:t.name,rootPath:typeof t.rootPath=="string"?t.rootPath:N(N(s)),createdAt:typeof t.createdAt=="string"?t.createdAt:r,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:r,graphVersion:typeof t.graphVersion=="number"?t.graphVersion:0,memoryVersion:typeof t.memoryVersion=="number"?t.memoryVersion:0,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:void 0}}function Y(s,e){let t=O(s,Q);ge(t,{recursive:!0});let r=G(s),o=`${r}.tmp-${process.pid}`;Se(o,JSON.stringify(e,null,2)+`
|
|
3
|
+
`,{encoding:"utf8",mode:384}),ye(o,r)}function q(s,e){return{id:s.id,name:s.name,remote:s.remote,rootPath:e,createdAt:s.createdAt,updatedAt:s.updatedAt,graphVersion:s.graphVersion,memoryVersion:s.memoryVersion,metadata:s.metadata}}var I=class{detect(e=process.cwd()){let t=k(e),r=ve(t),n=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(m=>D(O(r,m))),i=we(t,n?r:void 0);if(i){let m=G(i),u=Pe(m);return u.rootPath!==i&&(u.rootPath=i,u.updatedAt=new Date().toISOString(),Y(i,u)),q(u,i)}let d=new Date().toISOString(),f=be(r),c={version:1,id:Ce(r),name:f,remote:f,rootPath:r,createdAt:d,updatedAt:d,graphVersion:0,memoryVersion:0};return Y(r,c),q(c,r)}};import{readdir as Ae}from"node:fs/promises";import{extname as Le,join as Me,relative as Ne}from"node:path";import{basename as Re}from"node:path";var Te=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),je=new Set([".pem",".key",".p12",".pfx"]);function Z(s){let e=Re(s).toLowerCase();if(Te.has(e))return!0;for(let t of je)if(e.endsWith(t))return!0;return!1}var Ie=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),Oe=new Set(["node_modules",".git","dist","build","coverage",".next",".cache",".toolnet-memory"]);async function K(s){let e=[];async function t(r){let o=await Ae(r,{withFileTypes:!0});for(let n of o){if(Oe.has(n.name))continue;let i=Me(r,n.name);if(n.isDirectory()){await t(i);continue}Ie.has(Le(n.name))&&(Z(i)||e.push(Ne(s,i)))}}return await t(s),e.sort()}import{readFile as _e}from"node:fs/promises";import{join as Fe}from"node:path";import{createHash as $e}from"node:crypto";import*as l from"typescript";function X(s,e){return $e("sha256").update(`${s}:${e}`).digest("hex").slice(0,24)}function z(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}async function B(s,e,t){let r=Fe(e,t),o=await _e(r,"utf8"),n=l.createSourceFile(t,o,l.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?l.ScriptKind.TSX:l.ScriptKind.TS),i=[],d=[],f=[],c=[],m={id:X(s,`file:${t}`),projectId:s,name:t,qualifiedName:t,type:"file",filePath:t,startLine:1,endLine:n.getLineAndCharacterOfPosition(n.end).line+1};i.push(m);let u=[],x=[];function b(a,y,h,g){let C=X(s,`${t}:${h}:${g??y}:${a.pos}`);return i.push({id:C,projectId:s,name:y,qualifiedName:g??y,type:h,filePath:t,startLine:z(n,a),endLine:n.getLineAndCharacterOfPosition(a.end).line+1}),C}function M(a){if(!l.isStringLiteral(a.moduleSpecifier))return;let y=[],h=a.importClause;if(h?.name&&y.push({localName:h.name.text,importedName:"default",kind:"default"}),h?.namedBindings&&l.isNamedImports(h.namedBindings))for(let g of h.namedBindings.elements)y.push({localName:g.name.text,importedName:g.propertyName?.text??g.name.text,kind:"named"});h?.namedBindings&&l.isNamespaceImport(h.namedBindings)&&y.push({localName:h.namedBindings.name.text,importedName:"*",kind:"namespace"}),d.push({source:a.moduleSpecifier.text,bindings:y})}function w(a,y){for(let h of a.heritageClauses??[])for(let g of h.types){let C=g.expression.getText(n).split(".").at(-1)??"";C&&c.push({fromId:y,targetName:C,type:h.token===l.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function U(a){let y=!1,h=!1;if(l.isImportDeclaration(a)&&M(a),l.isInterfaceDeclaration(a)&&b(a,a.name.text,"interface",a.name.text),l.isClassDeclaration(a)&&a.name){let g=b(a,a.name.text,"class",a.name.text);w(a,g),x.push({id:g,name:a.name.text}),h=!0}if(l.isFunctionDeclaration(a)&&a.name){let g=b(a,a.name.text,"function",a.name.text);u.push(g),y=!0}if(l.isMethodDeclaration(a)&&a.name){let g=a.name.getText(n),C=x.at(-1)?.name,ae=b(a,g,"method",C?`${C}.${g}`:g);u.push(ae),y=!0}if(l.isCallExpression(a)&&(l.isIdentifier(a.expression)&&f.push({callerId:u.at(-1),calleeName:a.expression.text,line:z(n,a)}),l.isPropertyAccessExpression(a.expression))){let g=a.expression;f.push({callerId:u.at(-1),qualifier:g.expression.getText(n),calleeName:g.name.text,line:z(n,a)})}l.forEachChild(a,U),y&&u.pop(),h&&x.pop()}return U(n),{filePath:t,symbols:i,imports:d,calls:f,heritage:c}}import{createHash as De}from"node:crypto";import{dirname as Ge,extname as Ke,normalize as ze,posix as Be}from"node:path";var R=class{symbols=new Map;edges=new Map;addSymbol(e){this.symbols.set(e.id,e)}addEdge(e){this.edges.set(e.id,e)}getSymbol(e){return this.symbols.get(e)}findByName(e,t){return[...this.symbols.values()].filter(r=>r.projectId===e&&(r.name===t||r.qualifiedName===t))}allSymbols(e){return[...this.symbols.values()].filter(t=>t.projectId===e)}allEdges(e){return[...this.edges.values()].filter(t=>t.projectId===e)}import(e,t){for(let r of e)this.addSymbol(r);for(let r of t)this.addEdge(r)}clearProject(e){for(let[t,r]of this.symbols)r.projectId===e&&this.symbols.delete(t);for(let[t,r]of this.edges)r.projectId===e&&this.edges.delete(t)}};function We(s,e,t,r){return De("sha256").update(`${s}:${e}:${t}:${r}`).digest("hex").slice(0,24)}function E(s){return ze(s).replaceAll("\\","/")}function W(s,e,t){if(!e.startsWith("."))return;let r=E(Be.join(Ge(s),e)),o=Ke(r),n;if(o===".js"){let i=r.slice(0,-3);n=[`${i}.ts`,`${i}.tsx`,`${i}.js`,`${i}.jsx`]}else if(o===".mjs"){let i=r.slice(0,-4);n=[`${i}.mts`,`${i}.ts`,`${i}.mjs`]}else if(o===".cjs"){let i=r.slice(0,-4);n=[`${i}.cts`,`${i}.ts`,`${i}.cjs`]}else o?n=[r]:n=[`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}.js`,`${r}.jsx`,`${r}.mjs`,`${r}.cjs`,`${r}/index.ts`,`${r}/index.tsx`,`${r}/index.js`,`${r}/index.jsx`];return n.find(i=>t.has(E(i)))}var T=class{build(e,t){let r=new R,o=new Map;for(let i of t)for(let d of i.symbols)r.addSymbol(d),d.type==="file"&&o.set(E(i.filePath),d);let n=new Set(o.keys());for(let i of t){let d=E(i.filePath),f=o.get(d);if(f){for(let c of i.symbols)c.id!==f.id&&r.addEdge(this.edge(e,f.id,"DEFINES",c.id));for(let c of i.imports){let m=W(d,c.source,n);if(!m)continue;let u=o.get(m);u&&r.addEdge(this.edge(e,f.id,"IMPORTS",u.id,{source:c.source}))}for(let c of i.heritage){let m=r.findByName(e,c.targetName).filter(u=>u.type==="class"||u.type==="interface");for(let u of m)r.addEdge(this.edge(e,c.fromId,c.type,u.id))}for(let c of i.calls){if(!c.callerId)continue;let m=this.resolveCallTargets(e,i,c.calleeName,c.qualifier,t,r,n);for(let u of m)u.id!==c.callerId&&r.addEdge(this.edge(e,c.callerId,"CALLS",u.id,{line:c.line,qualifier:c.qualifier}))}}}return r}resolveCallTargets(e,t,r,o,n,i,d){let f=E(t.filePath),c=i.findByName(e,r).filter(m=>E(m.filePath)===f);if(!o&&c.length)return c;if(o)for(let m of t.imports){if(!m.bindings.find(b=>b.kind==="namespace"&&b.localName===o))continue;let x=W(f,m.source,d);if(x)return i.findByName(e,r).filter(b=>E(b.filePath)===x)}for(let m of t.imports){let u=m.bindings.find(w=>w.localName===r);if(!u)continue;let x=W(f,m.source,d);if(!x)continue;let b=u.importedName==="default"?r:u.importedName,M=i.findByName(e,b).filter(w=>E(w.filePath)===x);if(M.length)return M}return i.findByName(e,r).filter(m=>m.type==="function"||m.type==="method")}edge(e,t,r,o,n){return{id:We(e,t,r,o),projectId:e,from:t,to:o,type:r,metadata:n}}};var _=class{async index(e,t,r={}){let o=await K(t);r.onProgress?.({phase:"scan",current:o.length,total:o.length});let n=[],i=0;for(let f of o)try{n.push(await B(e,t,f))}catch(c){console.warn(`[indexer] skipped ${f}:`,c instanceof Error?c.message:c)}finally{i+=1,r.onProgress?.({phase:"parse",current:i,total:o.length,file:f})}let d=new T().build(e,n);return{files:n.length,symbols:d.allSymbols(e).length,edges:d.allEdges(e).length,graph:d}}};function ee(s,e){let t=s.allSymbols(e),r=s.allEdges(e),o=i=>t.filter(d=>d.type===i).length,n=i=>r.filter(d=>d.type===i).length;return{files:o("file"),classes:o("class"),interfaces:o("interface"),functions:o("function"),methods:o("method"),properties:o("property"),routes:o("route"),symbols:t.length,edges:r.length,calls:n("CALLS"),callReferences:n("CALL_REFERENCE"),imports:n("IMPORTS"),inherits:n("INHERITS"),implements:n("IMPLEMENTS"),usesType:n("USES_TYPE"),tests:n("TESTS"),routeEdges:n("ROUTE"),writes:n("WRITES")}}import{execFile as He}from"node:child_process";import{promisify as Ue}from"node:util";var Nr=Ue(He);var j=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};import*as S from"typescript";import*as p from"typescript";var Us=new Set([p.SyntaxKind.EqualsToken,p.SyntaxKind.PlusEqualsToken,p.SyntaxKind.MinusEqualsToken,p.SyntaxKind.AsteriskEqualsToken,p.SyntaxKind.SlashEqualsToken,p.SyntaxKind.PercentEqualsToken,p.SyntaxKind.QuestionQuestionEqualsToken,p.SyntaxKind.AmpersandAmpersandEqualsToken,p.SyntaxKind.BarBarEqualsToken]);import{homedir as ht}from"node:os";import{join as yt}from"node:path";import{DeleteObjectCommand as Ye,GetObjectCommand as qe,HeadObjectCommand as Je,ListObjectsV2Command as Qe,PutObjectCommand as Ze,S3Client as Xe}from"@aws-sdk/client-s3";import{getSignedUrl as et}from"@aws-sdk/s3-request-presigner";var F=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Xe({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,r="application/octet-stream"){let o=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Ze({Bucket:this.bucket,Key:e,Body:o,ContentType:r}))}async get(e){let t=await et(this.client,new qe({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new Je({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new Ye({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let o=await this.client.send(new Qe({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let n of o.Contents??[])n.Key&&t.push({key:n.Key,size:n.Size,updatedAt:n.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return t}};import{access as te,mkdir as tt,readFile as rt,readdir as st,rm as ot,stat as re,writeFile as nt}from"node:fs/promises";import{dirname as it,join as at,relative as se,resolve as ct}from"node:path";var A=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return ct(this.root,t)}async put(e,t){let r=this.path(e);await tt(it(r),{recursive:!0}),await nt(r,t)}async get(e){try{return await rt(this.path(e))}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return null;throw t}}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await te(this.path(e)),!0}catch{return!1}}async delete(e){await ot(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),r=[];try{await te(t)}catch{return r}let o=async i=>{let d=await st(i,{withFileTypes:!0});for(let f of d){let c=at(i,f.name);if(f.isDirectory()){await o(c);continue}let m=await re(c);r.push({key:se(this.root,c),size:m.size,updatedAt:m.mtime.toISOString()})}},n=await re(t);return n.isDirectory()?await o(t):r.push({key:se(this.root,t),size:n.size,updatedAt:n.mtime.toISOString()}),r}};import{DeleteObjectCommand as lt,GetObjectCommand as dt,HeadObjectCommand as pt,ListObjectsV2Command as ut,PutObjectCommand as mt,S3Client as ft}from"@aws-sdk/client-s3";import{getSignedUrl as gt}from"@aws-sdk/s3-request-presigner";var L=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new ft({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,r="application/octet-stream"){let o=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new mt({Bucket:this.bucket,Key:e,Body:o,ContentType:r}))}async get(e){let t=await gt(this.client,new dt({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new pt({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new lt({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let o=await this.client.send(new ut({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let n of o.Contents??[])n.Key&&t.push({key:n.Key,size:n.Size,updatedAt:n.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return t}};function H(s,e){return console.warn(e),new A(s)}function oe(s){let e=s.localRoot??yt(ht(),".toolnet-memory","storage");if(s.provider==="r2"){let t=s.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new L({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):H(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(s.provider==="s3"){let t=s.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?new L({name:"s3",endpoint:t.endpoint,region:t.region??"us-east-1",bucket:t.bucket,forcePathStyle:t.forcePathStyle??!1,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):H(e,"[storage] S3 credentials missing. Using local fallback.")}if(s.provider==="huggingface"){let t=s.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new F({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):H(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new A(e)}function ne(s){let e=s.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function ie(s){let e=s.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let t=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(t)return`${t[1]}memory/records/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),t)return`${t[1]}memory/vectors/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),t)return`${t[1]}code/graph/${t[2]}`;let r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let o=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return o?`${o[1]}memory/records/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),o?`${o[1]}memory/vectors/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),o?`${o[1]}code/graph/${o[2]}`:e))}var $=class{constructor(e,t,r,o){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=r,this.folder=ne(o??r),this.sourcePrefix=`projects/${t}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,t=new Date().toISOString(),r=t,o=await this.provider.getText(e);if(o){let i;try{i=JSON.parse(o)}catch(d){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${d instanceof Error?d.message:String(d)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(r=i.createdAt)}let n={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:t};await this.provider.put(e,JSON.stringify(n,null,2)+`
|
|
4
|
+
`,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=ie(e),e===this.sourcePrefix)return this.targetPrefix;if(e.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+e.slice(this.sourcePrefix.length);if(e===this.targetPrefix||e.startsWith(`${this.targetPrefix}/`))return e;if(e.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${e}`].join(" "));return e}async put(e,t,r){return await this.ensureRegistered(),this.provider.put(this.key(e),t,r)}async get(e){return await this.ensureRegistered(),this.provider.get(this.key(e))}async getText(e){return await this.ensureRegistered(),this.provider.getText(this.key(e))}async delete(e){return await this.ensureRegistered(),this.provider.delete(this.key(e))}async exists(e){return await this.ensureRegistered(),this.provider.exists(this.key(e))}async list(e){return await this.ensureRegistered(),this.provider.list(this.key(e))}};async function St(){let s=V(),e=new I().detect(),t=oe({provider:s.storage.provider,huggingface:s.storage.huggingface,localRoot:s.storage.localRoot}),r=new $(t,e.id,e.name,e.remote??e.name),o=await new _().index(e.id,e.rootPath),n=ee(o.graph,e.id);await new j(r).save({version:1,projectId:e.id,updatedAt:new Date().toISOString(),files:o.files,symbols:o.graph.allSymbols(e.id),edges:o.graph.allEdges(e.id)}),console.log({ok:!0,storage:r.name,...n})}St().catch(s=>{console.error(s),process.exit(1)});
|