toolnet-memory 0.2.16 → 0.2.18
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/bin/toolnet-memory +18 -0
- package/bundle/agy-hook.js +45 -29
- package/bundle/auto-integrate.js +64 -14
- package/bundle/codex-context.js +39 -45
- package/bundle/codex.js +60 -43
- package/bundle/context-runtime.js +95 -22
- package/bundle/doctor.js +1 -1
- package/bundle/handoff-refresh.js +12 -0
- package/bundle/mcp.js +50 -7
- package/bundle/memory-agent.js +49 -0
- package/bundle/memory-query.js +7 -0
- package/bundle/opencode.js +82 -34
- package/bundle/provider.js +1 -1
- package/bundle/setup.js +66 -16
- package/package.json +1 -2
package/bundle/provider.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import"dotenv/config";var f=[{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 u(e){let o=f.find(r=>r.id===e);if(!o)throw new Error(`Unsupported AI provider: ${e}`);return o}function E(e){return f.some(o=>o.id===e)}function n(e){return process.env[e]?.trim()||void 0}function a(...e){return e.find(o=>!!o?.trim())}function M(){if(n("GROQ_API_KEY"))return"groq";if(n("DEEPSEEK_API_KEY"))return"deepseek";if(n("NVIDIA_API_KEY")||n("NVIDIA_NIM_API_KEY"))return"nvidia";if(n("OPENROUTER_API_KEY"))return"openrouter";if(n("ALIBABA_API_KEY")||n("DASHSCOPE_API_KEY"))return"alibaba";if(n("GEMINI_API_KEY")||n("GOOGLE_API_KEY"))return"gemini";if(n("CLOUDFLARE_API_TOKEN")&&n("CLOUDFLARE_ACCOUNT_ID"))return"cloudflare";if(n("HF_TOKEN"))return"huggingface";if(n("OLLAMA_MODEL")||n("OLLAMA_BASE_URL"))return"ollama"}function w(){let e=n("TOOLNET_LLM_PROVIDER");return e&&E(e)?e:M()??"openai-compatible"}function b(e){let o=u(e);switch(e){case"alibaba":return{provider:e,apiKey:a(n("ALIBABA_API_KEY"),n("DASHSCOPE_API_KEY")),baseUrl:a(n("ALIBABA_BASE_URL"),n("DASHSCOPE_BASE_URL"),o.defaultBaseUrl),model:a(n("ALIBABA_MODEL"),n("DASHSCOPE_MODEL"))};case"openrouter":return{provider:e,apiKey:n("OPENROUTER_API_KEY"),baseUrl:a(n("OPENROUTER_BASE_URL"),o.defaultBaseUrl),model:n("OPENROUTER_MODEL")};case"groq":return{provider:e,apiKey:n("GROQ_API_KEY"),baseUrl:a(n("GROQ_BASE_URL"),o.defaultBaseUrl),model:n("GROQ_MODEL")};case"deepseek":return{provider:e,apiKey:n("DEEPSEEK_API_KEY"),baseUrl:a(n("DEEPSEEK_BASE_URL"),o.defaultBaseUrl),model:a(n("DEEPSEEK_MODEL"),o.defaultModel)};case"nvidia":return{provider:e,apiKey:a(n("NVIDIA_API_KEY"),n("NVIDIA_NIM_API_KEY")),baseUrl:a(n("NVIDIA_BASE_URL"),n("NVIDIA_NIM_BASE_URL"),o.defaultBaseUrl),model:a(n("NVIDIA_MODEL"),n("NVIDIA_NIM_MODEL"),o.defaultModel)};case"gemini":return{provider:e,apiKey:a(n("GEMINI_API_KEY"),n("GOOGLE_API_KEY")),baseUrl:a(n("GEMINI_BASE_URL"),o.defaultBaseUrl),model:n("GEMINI_MODEL")};case"huggingface":return{provider:e,apiKey:n("HF_TOKEN"),baseUrl:a(n("HF_INFERENCE_BASE_URL"),o.defaultBaseUrl),model:a(n("HF_LLM_MODEL"),n("HF_MODEL"))};case"ollama":return{provider:e,apiKey:n("OLLAMA_API_KEY"),baseUrl:a(n("OLLAMA_BASE_URL"),o.defaultBaseUrl),model:n("OLLAMA_MODEL")};case"cloudflare":return{provider:e,accountId:n("CLOUDFLARE_ACCOUNT_ID"),apiKey:n("CLOUDFLARE_API_TOKEN"),baseUrl:n("CLOUDFLARE_AI_BASE_URL"),model:n("CLOUDFLARE_MODEL")};case"custom":return{provider:e,apiKey:n("CUSTOM_AI_API_KEY"),baseUrl:n("CUSTOM_AI_BASE_URL"),model:n("CUSTOM_AI_MODEL")};default:return{provider:"openai-compatible",apiKey:a(n("OPENAI_API_KEY"),n("MODEL_API_KEY")),baseUrl:a(n("OPENAI_BASE_URL"),n("MODEL_BASE_URL")),model:a(n("OPENAI_MODEL"),n("MODEL_NAME"))}}}function k(){let e=n("TOOLNET_LLM_PROVIDER"),o=e&&E(e)?e:w(),r=u(o),t=b(o);return{provider:o,apiKey:a(n("TOOLNET_LLM_API_KEY"),t.apiKey),baseUrl:a(n("TOOLNET_LLM_BASE_URL"),t.baseUrl,r.defaultBaseUrl),model:a(n("TOOLNET_LLM_MODEL"),t.model,r.defaultModel),accountId:a(n("TOOLNET_LLM_ACCOUNT_ID"),t.accountId)}}function $(){let e=n("TOOLNET_EMBEDDING_PROVIDER");return e==="local"?"local":e&&E(e)?e:n("HF_TOKEN")||n("HF_EMBEDDING_MODEL")?"huggingface":"local"}function S(){let e=$();if(e==="local")return{provider:"local",model:a(n("TOOLNET_EMBEDDING_MODEL"),n("LOCAL_EMBEDDING_MODEL"))};let o=u(e),r,t,i,s;switch(e){case"huggingface":r=n("HF_TOKEN"),t=n("HF_INFERENCE_BASE_URL"),i=n("HF_EMBEDDING_MODEL");break;case"openai-compatible":r=n("OPENAI_API_KEY"),t=n("OPENAI_BASE_URL"),i=n("OPENAI_EMBEDDING_MODEL");break;case"cloudflare":r=n("CLOUDFLARE_API_TOKEN"),t=n("CLOUDFLARE_AI_BASE_URL"),i=n("CLOUDFLARE_EMBEDDING_MODEL"),s=n("CLOUDFLARE_ACCOUNT_ID");break;default:r=b(e).apiKey,t=b(e).baseUrl,i=n(`${e.toUpperCase().replace(/-/g,"_")}_EMBEDDING_MODEL`)}let l=a(n("TOOLNET_EMBEDDING_ACCOUNT_ID"),s),d=a(n("TOOLNET_EMBEDDING_BASE_URL"),t,o.defaultBaseUrl),c=e==="cloudflare"&&!d&&l?`https://api.cloudflare.com/client/v4/accounts/${l}/ai/v1`:d;return{provider:e,apiKey:a(n("TOOLNET_EMBEDDING_API_KEY"),r),baseUrl:c,model:a(n("TOOLNET_EMBEDDING_MODEL"),i),accountId:l}}function p(){let e=k(),o=S();return{llm:e,embedding:o,legacy:{llm:!n("TOOLNET_LLM_PROVIDER")&&!!M(),embedding:!n("TOOLNET_EMBEDDING_PROVIDER")&&!!(n("HF_TOKEN")||n("HF_EMBEDDING_MODEL"))}}}function R(e=w()){let o=p().llm;if(e===o.provider)return{id:e,apiKey:o.apiKey,baseUrl:o.baseUrl,model:o.model,accountId:o.accountId};let r=b(e);return{id:e,apiKey:r.apiKey,baseUrl:r.baseUrl,model:r.model,accountId:r.accountId}}var P=class extends Error{status;constructor(o,r){super(o),this.name="AiHttpError",this.status=r}};async function g(e,o,r=3e4){let t=new AbortController,i=setTimeout(()=>t.abort(),r);i.unref?.();try{let s=await fetch(e,{...o,signal:t.signal}),l=await s.text();if(!s.ok){let d=l;try{let c=JSON.parse(l);d=c.error?.message??c.message??l}catch{}throw new P(d||`HTTP ${s.status}`,s.status)}return l.trim()?JSON.parse(l):{}}finally{clearTimeout(i)}}function A(e,o){return`${e.replace(/\/+$/,"")}/${o.replace(/^\/+/,"")}`}var y=class{constructor(o){this.config=o}config;id="cloudflare";model(){let o=this.config.model?.trim();if(!o)throw new Error("cloudflare: MODEL is not configured");return o}async generate(o){let r=this.config.accountId?.trim(),t=this.config.apiKey?.trim();if(!r)throw new Error("cloudflare: ACCOUNT ID is not configured");if(!t)throw new Error("cloudflare: API TOKEN is not configured");let i=this.model(),l=`${(this.config.baseUrl?.trim()||`https://api.cloudflare.com/client/v4/accounts/${r}/ai/run`).replace(/\/+$/,"")}/${i}`,d=await g(l,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json",...this.config.headers},body:JSON.stringify({messages:o.messages,temperature:o.temperature,max_tokens:o.maxTokens})}),c=d.result?.response?.trim();if(!c)throw new Error(d.errors?.[0]?.message??"cloudflare: empty model response");return{text:c,provider:"cloudflare",model:i}}async healthCheck(){let o=Date.now();try{return{ok:!0,provider:"cloudflare",model:(await this.generate({messages:[{role:"user",content:"Reply exactly: OK"}],temperature:0,maxTokens:8})).model,message:"Provider reachable",latencyMs:Date.now()-o}}catch(r){return{ok:!1,provider:"cloudflare",model:this.config.model,message:r instanceof Error?r.message:String(r),latencyMs:Date.now()-o}}}};var _=class{constructor(o){this.config=o}config;id="gemini";model(){let o=this.config.model?.trim();if(!o)throw new Error("gemini: MODEL is not configured");return o.replace(/^models\//,"")}async generate(o){let r=this.config.apiKey?.trim();if(!r)throw new Error("gemini: API KEY is not configured");let t=this.config.baseUrl?.trim()||"https://generativelanguage.googleapis.com/v1beta",i=this.model(),s=o.messages.filter(m=>m.role==="system"),l=o.messages.filter(m=>m.role!=="system").map(m=>({role:m.role==="assistant"?"model":"user",parts:[{text:m.content}]})),d=`${A(t,`models/${encodeURIComponent(i)}:generateContent`)}?key=${encodeURIComponent(r)}`,c=await g(d,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({...s.length?{systemInstruction:{parts:[{text:s.map(m=>m.content).join(`
|
|
2
2
|
|
|
3
|
-
`)}]}}:{},contents:l,generationConfig:{temperature:o.temperature,maxOutputTokens:o.maxTokens}})}),D=c.candidates?.[0]?.content?.parts?.map(m=>m.text??"").join("").trim();if(!D)throw new Error("gemini: empty model response");return{text:D,provider:"gemini",model:i,usage:c.usageMetadata?{inputTokens:c.usageMetadata.promptTokenCount,outputTokens:c.usageMetadata.candidatesTokenCount,totalTokens:c.usageMetadata.totalTokenCount}:void 0}}async healthCheck(){let o=Date.now();try{return{ok:!0,provider:"gemini",model:(await this.generate({messages:[{role:"user",content:"Reply exactly: OK"}],temperature:0,maxTokens:8})).model,message:"Provider reachable",latencyMs:Date.now()-o}}catch(r){return{ok:!1,provider:"gemini",model:this.config.model,message:r instanceof Error?r.message:String(r),latencyMs:Date.now()-o}}}};var h=class{constructor(o){this.config=o;this.id=o.id}config;id;baseUrl(){let o=this.config.baseUrl?.trim();if(!o)throw new Error(`${this.id}: BASE URL is not configured`);return o}model(){let o=this.config.model?.trim();if(!o)throw new Error(`${this.id}: MODEL is not configured`);return o}headers(){let o={"content-type":"application/json",...this.config.headers};return this.config.apiKey&&(o.authorization=`Bearer ${this.config.apiKey}`),o}async generate(o){let r=this.model(),t=await g(A(this.baseUrl(),"chat/completions"),{method:"POST",headers:this.headers(),body:JSON.stringify({model:r,messages:o.messages,temperature:o.temperature,max_tokens:o.maxTokens})}),i=t.choices?.[0]?.message?.content?.trim();if(!i)throw new Error(`${this.id}: empty model response`);return{text:i,provider:this.id,model:r,usage:t.usage?{inputTokens:t.usage.prompt_tokens,outputTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens}:void 0}}async healthCheck(){let o=Date.now();try{let r=await this.generate({messages:[{role:"user",content:"Reply exactly: OK"}],temperature:0,maxTokens:8});return{ok:!0,provider:this.id,model:r.model,message:"Provider reachable",latencyMs:Date.now()-o}}catch(r){return{ok:!1,provider:this.id,model:this.config.model,message:r instanceof Error?r.message:String(r),latencyMs:Date.now()-o}}}};function N(e=R()){switch(u(e.id).transport){case"gemini":return new _(e);case"cloudflare":return new y(e);default:return new h(e)}}var v=class{constructor(o){this.options=o}options;name="gemini";async embed(o){let r=this.options.model.replace(/^models\//,""),i=`${this.options.baseUrl?.replace(/\/+$/,"")||"https://generativelanguage.googleapis.com/v1beta"}/models/${encodeURIComponent(r)}:embedContent?key=${encodeURIComponent(this.options.apiKey)}`,s=await fetch(i,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:`models/${r}`,content:{parts:[{text:o}]}})});if(!s.ok)throw new Error(`Gemini embedding failed: ${s.status} ${await s.text()}`);let d=(await s.json()).embedding?.values;if(!Array.isArray(d)||d.length===0)throw new Error("Gemini embedding returned invalid response");return d}async embedMany(o){let r=[];for(let t of o)r.push(await this.embed(t));return r}};import{createHash as x}from"node:crypto";var O=class{name="hash-fallback";dimensions=128;async embed(o){let r=new Array(this.dimensions).fill(0),t=o.toLowerCase().split(/\s+/).filter(Boolean);for(let i of t){let l=x("sha256").update(i).digest().readUInt32BE(0)%this.dimensions;r[l]+=1}return G(r)}async embedMany(o){return Promise.all(o.map(r=>this.embed(r)))}};function G(e){let o=Math.sqrt(e.reduce((r,t)=>r+t*t,0));return o===0?e:e.map(r=>r/o)}var I=class{constructor(o){this.options=o;this.dimensions=o.dimensions}options;name="openai-compatible";dimensions;async embed(o){let[r]=await this.embedMany([o]);return r}async embedMany(o){if(o.length===0)return[];let r=this.options.baseUrl.replace(/\/+$/,""),t=await fetch(`${r}/embeddings`,{method:"POST",headers:{"content-type":"application/json",...this.options.apiKey?{authorization:`Bearer ${this.options.apiKey}`}:{}},body:JSON.stringify({model:this.options.model,input:o})});if(!t.ok)throw new Error(`Embedding failed: ${t.status} ${await t.text()}`);let s=(await t.json()).data?.sort((l,d)=>(l.index??0)-(d.index??0)).map(l=>l.embedding);if(!s||s.length!==o.length||s.some(l=>!Array.isArray(l)))throw new Error("Embedding provider returned invalid response");return s}};var L=class{constructor(o){this.options=o}options;name="huggingface";dimensions=384;async embed(o){let[r]=await this.embedMany([o]);return r}async embedMany(o){if(o.length===0)return[];let r=`https://router.huggingface.co/hf-inference/models/${this.options.model}/pipeline/feature-extraction`,t=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.options.token}`,"Content-Type":"application/json"},body:JSON.stringify({inputs:o,options:{wait_for_model:!0}})});if(!t.ok)throw new Error(`HF embedding failed: ${t.status} ${await t.text()}`);let i=await t.json();if(!Array.isArray(i))throw new Error("HF embedding returned invalid response");return i.map(s=>F(s))}};function F(e){if(!Array.isArray(e))throw new Error("Invalid embedding");if(e.length>0&&typeof e[0]=="number")return e;if(e.length>0&&Array.isArray(e[0])){let o=e;if(o.length===0)return[];let r=o[0].length,t=new Array(r).fill(0);for(let i of o)for(let s=0;s<r;s++)t[s]+=i[s]??0;for(let i=0;i<r;i++)t[i]/=o.length;return t}throw new Error("Unsupported embedding shape")}var U=class{constructor(o,r=new O){this.primary=o;this.fallback=r}primary;fallback;name="resilient";async embed(o){if(this.primary)try{return await this.primary.embed(o)}catch(r){console.warn("[embedding] primary failed, fallback enabled:",r instanceof Error?r.message:r)}return this.fallback.embed(o)}async embedMany(o){if(this.primary)try{return await this.primary.embedMany(o)}catch(r){console.warn("[embedding] primary failed, fallback enabled:",r instanceof Error?r.message:r)}return this.fallback.embedMany(o)}};function H(e){return`https://api.cloudflare.com/client/v4/accounts/${e}/ai/v1`}function Y(){let e=p().embedding;if(e.provider==="local")return null;if(e.provider==="huggingface")return!e.apiKey||!e.model?null:new L({token:e.apiKey,model:e.model});if(e.provider==="gemini")return!e.apiKey||!e.model?null:new v({apiKey:e.apiKey,model:e.model,baseUrl:e.baseUrl});let o=e.baseUrl;return e.provider==="cloudflare"&&!o&&e.accountId&&(o=H(e.accountId)),o&&e.model?new I({apiKey:e.apiKey,baseUrl:o,model:e.model}):null}function T(){return new U(Y())}function K(e){return e?e.length<=8?"********":`${e.slice(0,4)}...${e.slice(-4)}`:"not configured"}function j(){console.log(""),console.log("ToolNet AI Providers"),console.log("===================="),console.log("");for(let e of f)console.log(`- ${e.label}`),console.log(` id : ${e.id}`),console.log(` protocol : ${e.transport}`),e.defaultBaseUrl&&console.log(` base URL : ${e.defaultBaseUrl}`),e.defaultModel&&console.log(` model : ${e.defaultModel}`),console.log("");console.log("- Local / Hash embedding"),console.log(" id : local"),console.log(" protocol : local"),console.log("")}function q(){let e=p();console.log(""),console.log("ToolNet Provider Status"),console.log("======================="),console.log(""),console.log("LLM"),console.log(` Provider : ${e.llm.provider}`),console.log(` Model : ${e.llm.model??"not configured"}`),console.log(` Base URL : ${e.llm.baseUrl??"default/provider native"}`),console.log(` API Key : ${K(e.llm.apiKey)}`),e.llm.accountId&&console.log(` Account : ${e.llm.accountId}`),console.log(` Legacy : ${e.legacy.llm?"yes":"no"}`),console.log(""),console.log("Embedding"),console.log(` Provider : ${e.embedding.provider}`),console.log(` Model : ${e.embedding.model??(e.embedding.provider==="local"?"local hash":"not configured")}`),console.log(` Base URL : ${e.embedding.baseUrl??(e.embedding.provider==="local"?"local":"default/provider native")}`),console.log(` API Key : ${e.embedding.provider==="local"?"not required":K(e.embedding.apiKey)}`),e.embedding.accountId&&console.log(` Account : ${e.embedding.accountId}`),console.log(` Legacy : ${e.legacy.embedding?"yes":"no"}`),console.log("")}async function C(){let e=p().llm;console.log(""),console.log("Testing LLM"),console.log("-----------"),console.log(`Provider : ${e.provider}`),console.log(`Model : ${e.model??"not configured"}`);try{let r=await N({id:e.provider,apiKey:e.apiKey,baseUrl:e.baseUrl,model:e.model,accountId:e.accountId}).healthCheck();return r.ok?(console.log("\u2713 Provider reachable"),r.latencyMs!==void 0&&console.log(`\u2713 Latency: ${r.latencyMs} ms`),console.log(""),!0):(console.log(`\u2717 ${r.message}`),!1)}catch(o){return console.log(`\u2717 ${o instanceof Error?o.message:String(o)}`),console.log(""),!1}}async function B(){let e=p().embedding;console.log(""),console.log("Testing Embedding"),console.log("-----------------"),console.log(`Provider : ${e.provider}`),console.log(`Model : ${e.model??(e.provider==="local"?"local hash":"not configured")}`);try{let r=await T().embed("ToolNet Memory provider health check");if(!Array.isArray(r)||r.length===0)throw new Error("Empty embedding vector");return console.log("\u2713 Embedding ready"),console.log(`\u2713 Dimensions: ${r.length}`),console.log(""),!0}catch(o){return console.log(`\u2717 ${o instanceof Error?o.message:String(o)}`),console.log(""),!1}}async function V(){let e=await C(),o=await B();return console.log(""),console.log("Provider Test Summary"),console.log("====================="),console.log(`LLM : ${e?"READY":"FAILED"}`),console.log(`Embedding : ${o?"READY":"FAILED"}`),console.log(""),e&&o}async function J(){let e=process.argv[2]??"status";if(e==="list"){j();return}if(e==="status"){q();return}if(e==="test"){let o=process.argv[3]??"all",r=!1;o==="llm"?r=await C():o==="embedding"?r=await B():r=await V(),process.exitCode=r?0:1;return}console.error(`Unknown provider command: ${e}`),console.error(""),console.error("Usage:"),console.error(" toolnet-memory provider:list"),console.error(" toolnet-memory provider:status"),console.error(" toolnet-memory provider:test"),console.error(" toolnet-memory provider:test llm"),console.error(" toolnet-memory provider:test embedding"),process.exitCode=1}J().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|
|
3
|
+
`)}]}}:{},contents:l,generationConfig:{temperature:o.temperature,maxOutputTokens:o.maxTokens}})}),D=c.candidates?.[0]?.content?.parts?.map(m=>m.text??"").join("").trim();if(!D)throw new Error("gemini: empty model response");return{text:D,provider:"gemini",model:i,usage:c.usageMetadata?{inputTokens:c.usageMetadata.promptTokenCount,outputTokens:c.usageMetadata.candidatesTokenCount,totalTokens:c.usageMetadata.totalTokenCount}:void 0}}async healthCheck(){let o=Date.now();try{return{ok:!0,provider:"gemini",model:(await this.generate({messages:[{role:"user",content:"Reply exactly: OK"}],temperature:0,maxTokens:8})).model,message:"Provider reachable",latencyMs:Date.now()-o}}catch(r){return{ok:!1,provider:"gemini",model:this.config.model,message:r instanceof Error?r.message:String(r),latencyMs:Date.now()-o}}}};var h=class{constructor(o){this.config=o;this.id=o.id}config;id;baseUrl(){let o=this.config.baseUrl?.trim();if(!o)throw new Error(`${this.id}: BASE URL is not configured`);return o}model(){let o=this.config.model?.trim();if(!o)throw new Error(`${this.id}: MODEL is not configured`);return o}headers(){let o={"content-type":"application/json",...this.config.headers};return this.config.apiKey&&(o.authorization=`Bearer ${this.config.apiKey}`),o}async generate(o){let r=this.model(),t=await g(A(this.baseUrl(),"chat/completions"),{method:"POST",headers:this.headers(),body:JSON.stringify({model:r,messages:o.messages,temperature:o.temperature,max_tokens:o.maxTokens,...this.id==="alibaba"?{enable_thinking:!1}:{}})}),i=t.choices?.[0]?.message?.content?.trim();if(!i)throw new Error(`${this.id}: empty model response`);return{text:i,provider:this.id,model:r,usage:t.usage?{inputTokens:t.usage.prompt_tokens,outputTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens}:void 0}}async healthCheck(){let o=Date.now();try{let r=await this.generate({messages:[{role:"user",content:"Reply exactly: OK"}],temperature:0,maxTokens:8});return{ok:!0,provider:this.id,model:r.model,message:"Provider reachable",latencyMs:Date.now()-o}}catch(r){return{ok:!1,provider:this.id,model:this.config.model,message:r instanceof Error?r.message:String(r),latencyMs:Date.now()-o}}}};function N(e=R()){switch(u(e.id).transport){case"gemini":return new _(e);case"cloudflare":return new y(e);default:return new h(e)}}var v=class{constructor(o){this.options=o}options;name="gemini";async embed(o){let r=this.options.model.replace(/^models\//,""),i=`${this.options.baseUrl?.replace(/\/+$/,"")||"https://generativelanguage.googleapis.com/v1beta"}/models/${encodeURIComponent(r)}:embedContent?key=${encodeURIComponent(this.options.apiKey)}`,s=await fetch(i,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:`models/${r}`,content:{parts:[{text:o}]}})});if(!s.ok)throw new Error(`Gemini embedding failed: ${s.status} ${await s.text()}`);let d=(await s.json()).embedding?.values;if(!Array.isArray(d)||d.length===0)throw new Error("Gemini embedding returned invalid response");return d}async embedMany(o){let r=[];for(let t of o)r.push(await this.embed(t));return r}};import{createHash as x}from"node:crypto";var O=class{name="hash-fallback";dimensions=128;async embed(o){let r=new Array(this.dimensions).fill(0),t=o.toLowerCase().split(/\s+/).filter(Boolean);for(let i of t){let l=x("sha256").update(i).digest().readUInt32BE(0)%this.dimensions;r[l]+=1}return G(r)}async embedMany(o){return Promise.all(o.map(r=>this.embed(r)))}};function G(e){let o=Math.sqrt(e.reduce((r,t)=>r+t*t,0));return o===0?e:e.map(r=>r/o)}var I=class{constructor(o){this.options=o;this.dimensions=o.dimensions}options;name="openai-compatible";dimensions;async embed(o){let[r]=await this.embedMany([o]);return r}async embedMany(o){if(o.length===0)return[];let r=this.options.baseUrl.replace(/\/+$/,""),t=await fetch(`${r}/embeddings`,{method:"POST",headers:{"content-type":"application/json",...this.options.apiKey?{authorization:`Bearer ${this.options.apiKey}`}:{}},body:JSON.stringify({model:this.options.model,input:o})});if(!t.ok)throw new Error(`Embedding failed: ${t.status} ${await t.text()}`);let s=(await t.json()).data?.sort((l,d)=>(l.index??0)-(d.index??0)).map(l=>l.embedding);if(!s||s.length!==o.length||s.some(l=>!Array.isArray(l)))throw new Error("Embedding provider returned invalid response");return s}};var L=class{constructor(o){this.options=o}options;name="huggingface";dimensions=384;async embed(o){let[r]=await this.embedMany([o]);return r}async embedMany(o){if(o.length===0)return[];let r=`https://router.huggingface.co/hf-inference/models/${this.options.model}/pipeline/feature-extraction`,t=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.options.token}`,"Content-Type":"application/json"},body:JSON.stringify({inputs:o,options:{wait_for_model:!0}})});if(!t.ok)throw new Error(`HF embedding failed: ${t.status} ${await t.text()}`);let i=await t.json();if(!Array.isArray(i))throw new Error("HF embedding returned invalid response");return i.map(s=>F(s))}};function F(e){if(!Array.isArray(e))throw new Error("Invalid embedding");if(e.length>0&&typeof e[0]=="number")return e;if(e.length>0&&Array.isArray(e[0])){let o=e;if(o.length===0)return[];let r=o[0].length,t=new Array(r).fill(0);for(let i of o)for(let s=0;s<r;s++)t[s]+=i[s]??0;for(let i=0;i<r;i++)t[i]/=o.length;return t}throw new Error("Unsupported embedding shape")}var U=class{constructor(o,r=new O){this.primary=o;this.fallback=r}primary;fallback;name="resilient";async embed(o){if(this.primary)try{return await this.primary.embed(o)}catch(r){console.warn("[embedding] primary failed, fallback enabled:",r instanceof Error?r.message:r)}return this.fallback.embed(o)}async embedMany(o){if(this.primary)try{return await this.primary.embedMany(o)}catch(r){console.warn("[embedding] primary failed, fallback enabled:",r instanceof Error?r.message:r)}return this.fallback.embedMany(o)}};function H(e){return`https://api.cloudflare.com/client/v4/accounts/${e}/ai/v1`}function Y(){let e=p().embedding;if(e.provider==="local")return null;if(e.provider==="huggingface")return!e.apiKey||!e.model?null:new L({token:e.apiKey,model:e.model});if(e.provider==="gemini")return!e.apiKey||!e.model?null:new v({apiKey:e.apiKey,model:e.model,baseUrl:e.baseUrl});let o=e.baseUrl;return e.provider==="cloudflare"&&!o&&e.accountId&&(o=H(e.accountId)),o&&e.model?new I({apiKey:e.apiKey,baseUrl:o,model:e.model}):null}function T(){return new U(Y())}function K(e){return e?e.length<=8?"********":`${e.slice(0,4)}...${e.slice(-4)}`:"not configured"}function j(){console.log(""),console.log("ToolNet AI Providers"),console.log("===================="),console.log("");for(let e of f)console.log(`- ${e.label}`),console.log(` id : ${e.id}`),console.log(` protocol : ${e.transport}`),e.defaultBaseUrl&&console.log(` base URL : ${e.defaultBaseUrl}`),e.defaultModel&&console.log(` model : ${e.defaultModel}`),console.log("");console.log("- Local / Hash embedding"),console.log(" id : local"),console.log(" protocol : local"),console.log("")}function q(){let e=p();console.log(""),console.log("ToolNet Provider Status"),console.log("======================="),console.log(""),console.log("LLM"),console.log(` Provider : ${e.llm.provider}`),console.log(` Model : ${e.llm.model??"not configured"}`),console.log(` Base URL : ${e.llm.baseUrl??"default/provider native"}`),console.log(` API Key : ${K(e.llm.apiKey)}`),e.llm.accountId&&console.log(` Account : ${e.llm.accountId}`),console.log(` Legacy : ${e.legacy.llm?"yes":"no"}`),console.log(""),console.log("Embedding"),console.log(` Provider : ${e.embedding.provider}`),console.log(` Model : ${e.embedding.model??(e.embedding.provider==="local"?"local hash":"not configured")}`),console.log(` Base URL : ${e.embedding.baseUrl??(e.embedding.provider==="local"?"local":"default/provider native")}`),console.log(` API Key : ${e.embedding.provider==="local"?"not required":K(e.embedding.apiKey)}`),e.embedding.accountId&&console.log(` Account : ${e.embedding.accountId}`),console.log(` Legacy : ${e.legacy.embedding?"yes":"no"}`),console.log("")}async function C(){let e=p().llm;console.log(""),console.log("Testing LLM"),console.log("-----------"),console.log(`Provider : ${e.provider}`),console.log(`Model : ${e.model??"not configured"}`);try{let r=await N({id:e.provider,apiKey:e.apiKey,baseUrl:e.baseUrl,model:e.model,accountId:e.accountId}).healthCheck();return r.ok?(console.log("\u2713 Provider reachable"),r.latencyMs!==void 0&&console.log(`\u2713 Latency: ${r.latencyMs} ms`),console.log(""),!0):(console.log(`\u2717 ${r.message}`),!1)}catch(o){return console.log(`\u2717 ${o instanceof Error?o.message:String(o)}`),console.log(""),!1}}async function B(){let e=p().embedding;console.log(""),console.log("Testing Embedding"),console.log("-----------------"),console.log(`Provider : ${e.provider}`),console.log(`Model : ${e.model??(e.provider==="local"?"local hash":"not configured")}`);try{let r=await T().embed("ToolNet Memory provider health check");if(!Array.isArray(r)||r.length===0)throw new Error("Empty embedding vector");return console.log("\u2713 Embedding ready"),console.log(`\u2713 Dimensions: ${r.length}`),console.log(""),!0}catch(o){return console.log(`\u2717 ${o instanceof Error?o.message:String(o)}`),console.log(""),!1}}async function V(){let e=await C(),o=await B();return console.log(""),console.log("Provider Test Summary"),console.log("====================="),console.log(`LLM : ${e?"READY":"FAILED"}`),console.log(`Embedding : ${o?"READY":"FAILED"}`),console.log(""),e&&o}async function J(){let e=process.argv[2]??"status";if(e==="list"){j();return}if(e==="status"){q();return}if(e==="test"){let o=process.argv[3]??"all",r=!1;o==="llm"?r=await C():o==="embedding"?r=await B():r=await V(),process.exitCode=r?0:1;return}console.error(`Unknown provider command: ${e}`),console.error(""),console.error("Usage:"),console.error(" toolnet-memory provider:list"),console.error(" toolnet-memory provider:status"),console.error(" toolnet-memory provider:test"),console.error(" toolnet-memory provider:test llm"),console.error(" toolnet-memory provider:test embedding"),process.exitCode=1}J().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|
package/bundle/setup.js
CHANGED
|
@@ -1,7 +1,53 @@
|
|
|
1
|
-
import
|
|
1
|
+
import A from"node:fs";import ne from"node:os";import P from"node:path";import vo from"node:readline/promises";import{stdin as T,stdout as b}from"node:process";import{HeadBucketCommand as Vo,S3Client as Jo}from"@aws-sdk/client-s3";var le=[{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 S(e){let o=le.find(t=>t.id===e);if(!o)throw new Error(`Unsupported AI provider: ${e}`);return o}function U(e){return le.some(o=>o.id===e)}function c(e){return process.env[e]?.trim()||void 0}function f(...e){return e.find(o=>!!o?.trim())}function ge(){if(c("GROQ_API_KEY"))return"groq";if(c("DEEPSEEK_API_KEY"))return"deepseek";if(c("NVIDIA_API_KEY")||c("NVIDIA_NIM_API_KEY"))return"nvidia";if(c("OPENROUTER_API_KEY"))return"openrouter";if(c("ALIBABA_API_KEY")||c("DASHSCOPE_API_KEY"))return"alibaba";if(c("GEMINI_API_KEY")||c("GOOGLE_API_KEY"))return"gemini";if(c("CLOUDFLARE_API_TOKEN")&&c("CLOUDFLARE_ACCOUNT_ID"))return"cloudflare";if(c("HF_TOKEN"))return"huggingface";if(c("OLLAMA_MODEL")||c("OLLAMA_BASE_URL"))return"ollama"}function de(){let e=c("TOOLNET_LLM_PROVIDER");return e&&U(e)?e:ge()??"openai-compatible"}function B(e){let o=S(e);switch(e){case"alibaba":return{provider:e,apiKey:f(c("ALIBABA_API_KEY"),c("DASHSCOPE_API_KEY")),baseUrl:f(c("ALIBABA_BASE_URL"),c("DASHSCOPE_BASE_URL"),o.defaultBaseUrl),model:f(c("ALIBABA_MODEL"),c("DASHSCOPE_MODEL"))};case"openrouter":return{provider:e,apiKey:c("OPENROUTER_API_KEY"),baseUrl:f(c("OPENROUTER_BASE_URL"),o.defaultBaseUrl),model:c("OPENROUTER_MODEL")};case"groq":return{provider:e,apiKey:c("GROQ_API_KEY"),baseUrl:f(c("GROQ_BASE_URL"),o.defaultBaseUrl),model:c("GROQ_MODEL")};case"deepseek":return{provider:e,apiKey:c("DEEPSEEK_API_KEY"),baseUrl:f(c("DEEPSEEK_BASE_URL"),o.defaultBaseUrl),model:f(c("DEEPSEEK_MODEL"),o.defaultModel)};case"nvidia":return{provider:e,apiKey:f(c("NVIDIA_API_KEY"),c("NVIDIA_NIM_API_KEY")),baseUrl:f(c("NVIDIA_BASE_URL"),c("NVIDIA_NIM_BASE_URL"),o.defaultBaseUrl),model:f(c("NVIDIA_MODEL"),c("NVIDIA_NIM_MODEL"),o.defaultModel)};case"gemini":return{provider:e,apiKey:f(c("GEMINI_API_KEY"),c("GOOGLE_API_KEY")),baseUrl:f(c("GEMINI_BASE_URL"),o.defaultBaseUrl),model:c("GEMINI_MODEL")};case"huggingface":return{provider:e,apiKey:c("HF_TOKEN"),baseUrl:f(c("HF_INFERENCE_BASE_URL"),o.defaultBaseUrl),model:f(c("HF_LLM_MODEL"),c("HF_MODEL"))};case"ollama":return{provider:e,apiKey:c("OLLAMA_API_KEY"),baseUrl:f(c("OLLAMA_BASE_URL"),o.defaultBaseUrl),model:c("OLLAMA_MODEL")};case"cloudflare":return{provider:e,accountId:c("CLOUDFLARE_ACCOUNT_ID"),apiKey:c("CLOUDFLARE_API_TOKEN"),baseUrl:c("CLOUDFLARE_AI_BASE_URL"),model:c("CLOUDFLARE_MODEL")};case"custom":return{provider:e,apiKey:c("CUSTOM_AI_API_KEY"),baseUrl:c("CUSTOM_AI_BASE_URL"),model:c("CUSTOM_AI_MODEL")};default:return{provider:"openai-compatible",apiKey:f(c("OPENAI_API_KEY"),c("MODEL_API_KEY")),baseUrl:f(c("OPENAI_BASE_URL"),c("MODEL_BASE_URL")),model:f(c("OPENAI_MODEL"),c("MODEL_NAME"))}}}function Je(){let e=c("TOOLNET_LLM_PROVIDER"),o=e&&U(e)?e:de(),t=S(o),n=B(o);return{provider:o,apiKey:f(c("TOOLNET_LLM_API_KEY"),n.apiKey),baseUrl:f(c("TOOLNET_LLM_BASE_URL"),n.baseUrl,t.defaultBaseUrl),model:f(c("TOOLNET_LLM_MODEL"),n.model,t.defaultModel),accountId:f(c("TOOLNET_LLM_ACCOUNT_ID"),n.accountId)}}function We(){let e=c("TOOLNET_EMBEDDING_PROVIDER");return e==="local"?"local":e&&U(e)?e:c("HF_TOKEN")||c("HF_EMBEDDING_MODEL")?"huggingface":"local"}function Xe(){let e=We();if(e==="local")return{provider:"local",model:f(c("TOOLNET_EMBEDDING_MODEL"),c("LOCAL_EMBEDDING_MODEL"))};let o=S(e),t,n,r,i;switch(e){case"huggingface":t=c("HF_TOKEN"),n=c("HF_INFERENCE_BASE_URL"),r=c("HF_EMBEDDING_MODEL");break;case"openai-compatible":t=c("OPENAI_API_KEY"),n=c("OPENAI_BASE_URL"),r=c("OPENAI_EMBEDDING_MODEL");break;case"cloudflare":t=c("CLOUDFLARE_API_TOKEN"),n=c("CLOUDFLARE_AI_BASE_URL"),r=c("CLOUDFLARE_EMBEDDING_MODEL"),i=c("CLOUDFLARE_ACCOUNT_ID");break;default:t=B(e).apiKey,n=B(e).baseUrl,r=c(`${e.toUpperCase().replace(/-/g,"_")}_EMBEDDING_MODEL`)}let s=f(c("TOOLNET_EMBEDDING_ACCOUNT_ID"),i),a=f(c("TOOLNET_EMBEDDING_BASE_URL"),n,o.defaultBaseUrl),l=e==="cloudflare"&&!a&&s?`https://api.cloudflare.com/client/v4/accounts/${s}/ai/v1`:a;return{provider:e,apiKey:f(c("TOOLNET_EMBEDDING_API_KEY"),t),baseUrl:l,model:f(c("TOOLNET_EMBEDDING_MODEL"),r),accountId:s}}function ze(){let e=Je(),o=Xe();return{llm:e,embedding:o,legacy:{llm:!c("TOOLNET_LLM_PROVIDER")&&!!ge(),embedding:!c("TOOLNET_EMBEDDING_PROVIDER")&&!!(c("HF_TOKEN")||c("HF_EMBEDDING_MODEL"))}}}function Ee(e=de()){let o=ze().llm;if(e===o.provider)return{id:e,apiKey:o.apiKey,baseUrl:o.baseUrl,model:o.model,accountId:o.accountId};let t=B(e);return{id:e,apiKey:t.apiKey,baseUrl:t.baseUrl,model:t.model,accountId:t.accountId}}var v=class extends Error{status;constructor(o,t){super(o),this.name="AiHttpError",this.status=t}};async function R(e,o,t=3e4){let n=new AbortController,r=setTimeout(()=>n.abort(),t);r.unref?.();try{let i=await fetch(e,{...o,signal:n.signal}),s=await i.text();if(!i.ok){let a=s;try{let l=JSON.parse(s);a=l.error?.message??l.message??s}catch{}throw new v(a||`HTTP ${i.status}`,i.status)}return s.trim()?JSON.parse(s):{}}finally{clearTimeout(r)}}function w(e,o){return`${e.replace(/\/+$/,"")}/${o.replace(/^\/+/,"")}`}var k=class{constructor(o){this.config=o}config;id="cloudflare";model(){let o=this.config.model?.trim();if(!o)throw new Error("cloudflare: MODEL is not configured");return o}async generate(o){let t=this.config.accountId?.trim(),n=this.config.apiKey?.trim();if(!t)throw new Error("cloudflare: ACCOUNT ID is not configured");if(!n)throw new Error("cloudflare: API TOKEN is not configured");let r=this.model(),s=`${(this.config.baseUrl?.trim()||`https://api.cloudflare.com/client/v4/accounts/${t}/ai/run`).replace(/\/+$/,"")}/${r}`,a=await R(s,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json",...this.config.headers},body:JSON.stringify({messages:o.messages,temperature:o.temperature,max_tokens:o.maxTokens})}),l=a.result?.response?.trim();if(!l)throw new Error(a.errors?.[0]?.message??"cloudflare: empty model response");return{text:l,provider:"cloudflare",model:r}}async healthCheck(){let o=Date.now();try{return{ok:!0,provider:"cloudflare",model:(await this.generate({messages:[{role:"user",content:"Reply exactly: OK"}],temperature:0,maxTokens:8})).model,message:"Provider reachable",latencyMs:Date.now()-o}}catch(t){return{ok:!1,provider:"cloudflare",model:this.config.model,message:t instanceof Error?t.message:String(t),latencyMs:Date.now()-o}}}};var Y=class{constructor(o){this.config=o}config;id="gemini";model(){let o=this.config.model?.trim();if(!o)throw new Error("gemini: MODEL is not configured");return o.replace(/^models\//,"")}async generate(o){let t=this.config.apiKey?.trim();if(!t)throw new Error("gemini: API KEY is not configured");let n=this.config.baseUrl?.trim()||"https://generativelanguage.googleapis.com/v1beta",r=this.model(),i=o.messages.filter(E=>E.role==="system"),s=o.messages.filter(E=>E.role!=="system").map(E=>({role:E.role==="assistant"?"model":"user",parts:[{text:E.content}]})),a=`${w(n,`models/${encodeURIComponent(r)}:generateContent`)}?key=${encodeURIComponent(t)}`,l=await R(a,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({...i.length?{systemInstruction:{parts:[{text:i.map(E=>E.content).join(`
|
|
2
2
|
|
|
3
|
-
`)}]}}:{},contents:s,generationConfig:{temperature:o.temperature,maxOutputTokens:o.maxTokens}})}),
|
|
4
|
-
`,{encoding:"utf8",mode:384}),o}import{existsSync as
|
|
3
|
+
`)}]}}:{},contents:s,generationConfig:{temperature:o.temperature,maxOutputTokens:o.maxTokens}})}),g=l.candidates?.[0]?.content?.parts?.map(E=>E.text??"").join("").trim();if(!g)throw new Error("gemini: empty model response");return{text:g,provider:"gemini",model:r,usage:l.usageMetadata?{inputTokens:l.usageMetadata.promptTokenCount,outputTokens:l.usageMetadata.candidatesTokenCount,totalTokens:l.usageMetadata.totalTokenCount}:void 0}}async healthCheck(){let o=Date.now();try{return{ok:!0,provider:"gemini",model:(await this.generate({messages:[{role:"user",content:"Reply exactly: OK"}],temperature:0,maxTokens:8})).model,message:"Provider reachable",latencyMs:Date.now()-o}}catch(t){return{ok:!1,provider:"gemini",model:this.config.model,message:t instanceof Error?t.message:String(t),latencyMs:Date.now()-o}}}};var $=class{constructor(o){this.config=o;this.id=o.id}config;id;baseUrl(){let o=this.config.baseUrl?.trim();if(!o)throw new Error(`${this.id}: BASE URL is not configured`);return o}model(){let o=this.config.model?.trim();if(!o)throw new Error(`${this.id}: MODEL is not configured`);return o}headers(){let o={"content-type":"application/json",...this.config.headers};return this.config.apiKey&&(o.authorization=`Bearer ${this.config.apiKey}`),o}async generate(o){let t=this.model(),n=await R(w(this.baseUrl(),"chat/completions"),{method:"POST",headers:this.headers(),body:JSON.stringify({model:t,messages:o.messages,temperature:o.temperature,max_tokens:o.maxTokens,...this.id==="alibaba"?{enable_thinking:!1}:{}})}),r=n.choices?.[0]?.message?.content?.trim();if(!r)throw new Error(`${this.id}: empty model response`);return{text:r,provider:this.id,model:t,usage:n.usage?{inputTokens:n.usage.prompt_tokens,outputTokens:n.usage.completion_tokens,totalTokens:n.usage.total_tokens}:void 0}}async healthCheck(){let o=Date.now();try{let t=await this.generate({messages:[{role:"user",content:"Reply exactly: OK"}],temperature:0,maxTokens:8});return{ok:!0,provider:this.id,model:t.model,message:"Provider reachable",latencyMs:Date.now()-o}}catch(t){return{ok:!1,provider:this.id,model:this.config.model,message:t instanceof Error?t.message:String(t),latencyMs:Date.now()-o}}}};function _e(e=Ee()){switch(S(e.id).transport){case"gemini":return new Y(e);case"cloudflare":return new k(e);default:return new $(e)}}import{existsSync as z}from"node:fs";import{homedir as Q}from"node:os";import{join as Z}from"node:path";import{spawnSync as $o}from"node:child_process";import{existsSync as Qe,mkdirSync as Ze,readFileSync as eo,writeFileSync as oo}from"node:fs";import{homedir as to}from"node:os";import{dirname as no,join as ro}from"node:path";function io(e){return`'${e.replace(/'/g,"'\\''")}'`}function Oe(e={}){let o=e.hooksFile??ro(to(),".gemini","config","hooks.json");Ze(no(o),{recursive:!0});let t={};if(Qe(o))try{t=JSON.parse(eo(o,"utf8"))}catch(i){throw new Error(`Invalid existing Agy hooks.json: ${i instanceof Error?i.message:String(i)}`)}let n=e.binary??"toolnet-memory",r=`${io(n)} session:agy-hook`;return t["toolnet-memory"]={enabled:!0,PreInvocation:[{type:"command",command:`${r} pre`,timeout:15}],PostInvocation:[{type:"command",command:`${r} post`,timeout:15}],Stop:[{type:"command",command:`${r} stop`,timeout:30}]},oo(o,JSON.stringify(t,null,2)+`
|
|
4
|
+
`,{encoding:"utf8",mode:384}),o}import{existsSync as so,mkdirSync as co,readFileSync as ao,renameSync as lo,writeFileSync as go}from"node:fs";import{homedir as Eo}from"node:os";import{dirname as _o,join as Oo}from"node:path";function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fo(e,o){co(_o(e),{recursive:!0});let t=`${e}.tmp-${process.pid}-${Date.now()}`;go(t,`${JSON.stringify(o,null,2)}
|
|
5
|
+
`,{encoding:"utf8",mode:384}),lo(t,e)}function fe(e){if(!so(e))return{};let o=ao(e,"utf8").trim();if(!o)return{};let t;try{t=JSON.parse(o)}catch(n){throw new Error(`Invalid existing Agy MCP config: ${n instanceof Error?n.message:String(n)}`)}if(!D(t))throw new Error("Invalid existing Agy MCP config: root must be a JSON object.");return t}function me(e,o){return D(e)?e.command===o&&Array.isArray(e.args)&&e.args.length===1&&e.args[0]==="mcp":!1}function ue(e={}){let o=e.configFile??Oo(Eo(),".gemini","config","mcp_config.json"),t=e.binary??process.env.TOOLNET_MEMORY_BIN??"toolnet-memory",n=e.serverName??"toolnet-memory",r=fe(o),i=r.mcpServers;if(i!==void 0&&!D(i))throw new Error("Invalid existing Agy MCP config: mcpServers must be an object.");let s=D(i)?{...i}:{},a=s[n];if(me(a,t))return{installed:!0,changed:!1,configFile:o,serverName:n,command:t,args:["mcp"]};s[n]={command:t,args:["mcp"]};let l={...r,mcpServers:s};fo(o,l);let E=fe(o).mcpServers;if(!D(E)||!me(E[n],t))throw new Error("Agy MCP configuration was written but verification failed.");return{installed:!0,changed:!0,configFile:o,serverName:n,command:t,args:["mcp"]}}import{existsSync as uo,mkdirSync as Te,readFileSync as Lo,writeFileSync as Ae}from"node:fs";import{homedir as J}from"node:os";import{join as F}from"node:path";var mo="memory_agent_ask";function Le(){return`
|
|
6
|
+
[TOOLNET MEMORY AGENT]
|
|
7
|
+
|
|
8
|
+
Tool available:
|
|
9
|
+
- ${mo}
|
|
10
|
+
|
|
11
|
+
Use it automatically BEFORE guessing when:
|
|
12
|
+
|
|
13
|
+
- The user asks to continue, resume, or pick up previous work.
|
|
14
|
+
- The user says things like:
|
|
15
|
+
- "ti\u1EBFp t\u1EE5c task l\xFAc n\xE3y"
|
|
16
|
+
- "l\xE0m ti\u1EBFp ph\u1EA7n \u0111ang d\u1EDF"
|
|
17
|
+
- "agent tr\u01B0\u1EDBc \u0111ang l\xE0m g\xEC?"
|
|
18
|
+
- "d\u1EEBng \u1EDF \u0111\xE2u?"
|
|
19
|
+
- "todo n\xE0o ch\u01B0a xong?"
|
|
20
|
+
- "continue the previous task"
|
|
21
|
+
- "resume the last session"
|
|
22
|
+
- Previous-agent state, unfinished work, blockers,
|
|
23
|
+
decisions, touched files, or next actions are unclear.
|
|
24
|
+
- Fast startup context is not enough to safely continue.
|
|
25
|
+
|
|
26
|
+
Preferred mode:
|
|
27
|
+
|
|
28
|
+
- mode="local"
|
|
29
|
+
for direct factual questions such as:
|
|
30
|
+
current task, last file, blocker, completed TODOs.
|
|
31
|
+
|
|
32
|
+
- mode="ai"
|
|
33
|
+
for composite or ambiguous continuity questions
|
|
34
|
+
that benefit from ToolNet Memory Agent reasoning.
|
|
35
|
+
|
|
36
|
+
Do NOT call it automatically when:
|
|
37
|
+
|
|
38
|
+
- Normal startup context already gives enough information.
|
|
39
|
+
- The question is unrelated to previous project work.
|
|
40
|
+
- The answer is obvious from current repository evidence.
|
|
41
|
+
|
|
42
|
+
Rules:
|
|
43
|
+
|
|
44
|
+
- Never invent previous work.
|
|
45
|
+
- Current repository evidence overrides stale memory.
|
|
46
|
+
- Do not dump raw transcripts or full memory.
|
|
47
|
+
- After receiving the ToolNet answer, continue the task
|
|
48
|
+
instead of asking the user to repeat known context.
|
|
49
|
+
- If ToolNet says information is not recorded, say so.
|
|
50
|
+
`.trim()}var pe="<!-- TOOLNET_MEMORY_BOOTSTRAP_START -->",V="<!-- TOOLNET_MEMORY_BOOTSTRAP_END -->";function po(){let e=F(J(),".config","opencode","AGENTS.md");Te(F(J(),".config","opencode"),{recursive:!0});let o=`${pe}
|
|
5
51
|
## ToolNet Memory
|
|
6
52
|
|
|
7
53
|
ToolNet Memory is available for projects that already contain a valid \`.toolnet/project.json\`.
|
|
@@ -16,10 +62,13 @@ Rules:
|
|
|
16
62
|
6. Raw transcripts must not be injected into prompts.
|
|
17
63
|
7. Current repository evidence has priority over stale memory when they conflict.
|
|
18
64
|
|
|
19
|
-
${q}`,t=qe(e)?Ve(e,"utf8"):"",n=t.indexOf(ge),r=t.indexOf(q);return n>=0&&r>=n?t=t.slice(0,n)+o+t.slice(r+q.length):(t=t.trimEnd(),t&&(t+=`
|
|
20
65
|
|
|
21
|
-
|
|
22
|
-
|
|
66
|
+
${Le()}
|
|
67
|
+
|
|
68
|
+
${V}`,t=uo(e)?Lo(e,"utf8"):"",n=t.indexOf(pe),r=t.indexOf(V);return n>=0&&r>=n?t=t.slice(0,n)+o+t.slice(r+V.length):(t=t.trimEnd(),t&&(t+=`
|
|
69
|
+
|
|
70
|
+
`),t+=o),Ae(e,t.trimEnd()+`
|
|
71
|
+
`,{encoding:"utf8",mode:384}),e}function Me(e={}){let o=e.directory??F(J(),".config","opencode","plugins");Te(o,{recursive:!0}),po();let t=F(o,"toolnet-memory.js"),n=e.binary??process.env.TOOLNET_MEMORY_BIN??"toolnet-memory",r=`
|
|
23
72
|
// Generated by ToolNet Memory.
|
|
24
73
|
// OpenCode integration:
|
|
25
74
|
// - project gated
|
|
@@ -647,17 +696,18 @@ export const ToolNetMemoryPlugin =
|
|
|
647
696
|
},
|
|
648
697
|
}
|
|
649
698
|
}
|
|
650
|
-
`;return
|
|
651
|
-
|
|
652
|
-
`)
|
|
699
|
+
`;return Ae(t,r.trimStart(),{encoding:"utf8",mode:384}),t}import{existsSync as Ce,mkdirSync as To,readFileSync as Ao,renameSync as Mo,writeFileSync as Io}from"node:fs";import{homedir as No}from"node:os";import{dirname as Se,join as x}from"node:path";function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Co(){let e=process.env.XDG_CONFIG_HOME?.trim();return e?x(e,"opencode"):x(No(),".config","opencode")}function So(){return x(Co(),"opencode.json")}function Ro(e,o){To(Se(e),{recursive:!0});let t=`${e}.tmp-${process.pid}-${Date.now()}`;Io(t,`${JSON.stringify(o,null,2)}
|
|
700
|
+
`,{encoding:"utf8",mode:384}),Mo(t,e)}function Ie(e){if(!Ce(e))return{};let o=Ao(e,"utf8").trim();if(!o)return{};let t;try{t=JSON.parse(o)}catch(n){throw new Error(`Invalid existing OpenCode opencode.json: ${n instanceof Error?n.message:String(n)}`)}if(!h(t))throw new Error("Invalid existing OpenCode opencode.json: root must be a JSON object.");return t}function Ne(e,o){if(!h(e))return!1;let t=e.command;return e.type==="local"&&e.enabled!==!1&&Array.isArray(t)&&t.length===2&&t[0]===o&&t[1]==="mcp"}function Re(e={}){let o=e.configFile??So(),t=e.binary??process.env.TOOLNET_MEMORY_BIN??"toolnet-memory",n=e.serverName??"toolnet-memory",r=x(Se(o),"opencode.jsonc"),i=Ce(r)?r:void 0,s=Ie(o),a=s.mcp;if(a!==void 0&&!h(a))throw new Error("Invalid existing OpenCode config: mcp must be an object.");let l=h(a)?{...a}:{},g=l[n];if(Ne(g,t))return{installed:!0,changed:!1,configFile:o,serverName:n,command:[t,"mcp"],preservedJsonc:i};l[n]={type:"local",command:[t,"mcp"],enabled:!0};let E={...s,mcp:l};Ro(o,E);let u=Ie(o);if(!h(u.mcp)||!Ne(u.mcp[n],t))throw new Error("OpenCode MCP configuration was written but verification failed.");return{installed:!0,changed:!0,configFile:o,serverName:n,command:[t,"mcp"],preservedJsonc:i}}import{existsSync as yo,mkdirSync as ye,readFileSync as Do,writeFileSync as De}from"node:fs";import{homedir as he}from"node:os";import{dirname as be,join as W}from"node:path";function ho(e){let o=[],t=/"((?:\\.|[^"\\])*)"|'([^']*)'/g,n;for(;n=t.exec(e);){let r=n[1]??n[2]??"";try{o.push(n[1]!==void 0?JSON.parse(`"${r}"`):r)}catch{o.push(r)}}return o}function Pe(e={}){let o=e.configFile??W(process.env.CODEX_HOME??W(he(),".codex"),"config.toml"),t=e.previousFile??W(he(),".config","toolnet-memory","codex-notify-previous.json");ye(be(o),{recursive:!0}),ye(be(t),{recursive:!0});let n=yo(o)?Do(o,"utf8"):"",r=e.binary??"toolnet-memory",i=`notify = [${JSON.stringify(r)}, "session:codex-notify"]`,s=n.split(`
|
|
701
|
+
`),a=s.findIndex(O=>/^\s*\[/.test(O));a<0&&(a=s.length);let l=-1,g=-1;for(let O=0;O<a;O+=1)if(/^\s*notify\s*=/.test(s[O])){if(l=O,g=O,s[O].includes("[")&&!s[O].includes("]"))for(;g+1<a&&(g+=1,!s[g].includes("]")););break}let E=[];if(l>=0){let O=s.slice(l,g+1).join(`
|
|
702
|
+
`);E=ho(O),s.splice(l,g-l+1,i)}else a=s.findIndex(O=>/^\s*\[/.test(O)),a<0&&(a=s.length),s.splice(a,0,i);let u=E.length>=2&&E[E.length-1]==="session:codex-notify";return E.length>0&&!u&&De(t,JSON.stringify(E,null,2)+`
|
|
653
703
|
`,{encoding:"utf8",mode:384}),n=s.join(`
|
|
654
704
|
`),n.endsWith(`
|
|
655
705
|
`)||(n+=`
|
|
656
|
-
`),
|
|
657
|
-
`,{encoding:"utf8",mode:384}),o}function X(e){return no("sh",["-lc",`command -v ${JSON.stringify(e)} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}function ro(){return X("agy")||W(J(v(),".gemini"))}function io(){return X("opencode")||W(J(v(),".config","opencode"))}function so(){return X("codex")||W(process.env.CODEX_HOME??J(v(),".codex"))}function z(e={}){let o=e.binary??process.env.TOOLNET_MEMORY_BIN??"toolnet-memory",t=[];if(!(e.force===!0||ro()))t.push({agent:"agy",detected:!1,installed:!1,targets:[]});else try{let r=Ee({binary:o});t.push({agent:"agy",detected:!0,installed:!0,targets:[r]})}catch(r){t.push({agent:"agy",detected:!0,installed:!1,targets:[],error:r instanceof Error?r.message:String(r)})}if(!(e.force===!0||io()))t.push({agent:"opencode",detected:!1,installed:!1,targets:[]});else try{let r=Oe({binary:o});t.push({agent:"opencode",detected:!0,installed:!0,targets:[r]})}catch(r){t.push({agent:"opencode",detected:!0,installed:!1,targets:[],error:r instanceof Error?r.message:String(r)})}if(!(e.force===!0||so()))t.push({agent:"codex",detected:!1,installed:!1,targets:[]});else try{let r=Te({binary:o}),i=pe({binary:o}),s=[r.configFile,i];r.preservedPrevious&&s.push(r.previousFile),t.push({agent:"codex",detected:!0,installed:!0,targets:s})}catch(r){t.push({agent:"codex",detected:!0,installed:!1,targets:[],error:r instanceof Error?r.message:String(r)})}return t}function co(e){console.log(""),console.log("ToolNet Memory AI Integrations"),console.log("=============================="),console.log("");for(let o of e){let t=o.agent==="agy"?"Agy / Antigravity":o.agent==="opencode"?"OpenCode":"Codex";if(!o.detected){console.log(`- ${t}: not detected`);continue}if(o.installed){console.log(`\u2713 ${t}: automatic memory enabled`);continue}console.log(`\u2717 ${t}: integration failed`),o.error&&console.log(` ${o.error}`)}console.log("")}async function ao(){let e=process.argv.slice(2),o=e.includes("--all"),t=e.includes("--json"),n=z({force:o});if(t){console.log(JSON.stringify(n,null,2));return}co(n)}var lo=process.argv[1]&&(process.argv[1].endsWith("auto-integrate.js")||process.argv[1].endsWith("auto-integrate.ts"));lo&&ao().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});var Q=h.join(Z.homedir(),".config","toolnet-memory"),u=h.join(Q,".env"),Oo=new Set(["MEMORY_STORAGE_PROVIDER","R2_ACCOUNT_ID","R2_BUCKET","R2_ACCESS_KEY_ID","R2_SECRET_ACCESS_KEY","S3_ENDPOINT","S3_REGION","S3_BUCKET","S3_ACCESS_KEY_ID","S3_SECRET_ACCESS_KEY","S3_FORCE_PATH_STYLE","HF_NAMESPACE","HF_BUCKET","HF_S3_ACCESS_KEY_ID","HF_S3_SECRET_ACCESS_KEY","HF_URL","HF_TOKEN","HF_EMBEDDING_MODEL","TOOLNET_LLM_PROVIDER","TOOLNET_LLM_API_KEY","TOOLNET_LLM_BASE_URL","TOOLNET_LLM_MODEL","TOOLNET_LLM_FALLBACK_1_PROVIDER","TOOLNET_LLM_FALLBACK_1_API_KEY","TOOLNET_LLM_FALLBACK_1_BASE_URL","TOOLNET_LLM_FALLBACK_1_MODEL","TOOLNET_LLM_FALLBACK_1_ACCOUNT_ID","TOOLNET_LLM_FALLBACK_2_PROVIDER","TOOLNET_LLM_FALLBACK_2_API_KEY","TOOLNET_LLM_FALLBACK_2_BASE_URL","TOOLNET_LLM_FALLBACK_2_MODEL","TOOLNET_LLM_FALLBACK_2_ACCOUNT_ID","TOOLNET_LLM_FALLBACK_COOLDOWN_MS","TOOLNET_LLM_MAX_RETRIES","TOOLNET_LLM_ACCOUNT_ID","TOOLNET_EMBEDDING_PROVIDER","TOOLNET_EMBEDDING_API_KEY","TOOLNET_EMBEDDING_BASE_URL","TOOLNET_EMBEDDING_MODEL","TOOLNET_EMBEDDING_ACCOUNT_ID","MEMORY_LOCAL_STORAGE_PATH","MEMORY_LOCAL_CACHE_MB","MEMORY_AUTO_CAPTURE","MEMORY_AUTO_RETRIEVE","MEMORY_AUTO_SUMMARIZE","MEMORY_AUTO_SYNC","MEMORY_MAX_CANDIDATES","MEMORY_RERANK_TOP","MEMORY_FINAL_CONTEXT","MEMORY_TOKEN_BUDGET","TOOLNET_SESSION_LEARNING","TOOLNET_WORK_CONTINUITY","TOOLNET_SEMANTIC_CONTINUITY","TOOLNET_SMART_HANDOFF"]);function Lo(e){let o=new Map;for(let t of e.split(/\r?\n/)){let n=t.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(r===-1)continue;let i=n.slice(0,r).trim(),s=n.slice(r+1).trim();i&&o.set(i,s)}return o}function N(e){let o=e.get("MEMORY_STORAGE_PROVIDER")?.trim();return o==="r2"||o==="s3"||o==="local"||o==="huggingface"?o:e.get("R2_ACCOUNT_ID")&&e.get("R2_BUCKET")?"r2":e.get("S3_BUCKET")?"s3":e.get("HF_BUCKET")&&e.get("HF_S3_ACCESS_KEY_ID")?"huggingface":e.get("MEMORY_LOCAL_STORAGE_PATH")?"local":"r2"}function P(e){switch(e){case"r2":return"Cloudflare R2";case"s3":return"S3 / S3-compatible";case"huggingface":return"Hugging Face S3";case"local":return"Local";default:return e}}function Se(e){switch(e){case"r2":return["R2_ACCOUNT_ID","R2_BUCKET","R2_ACCESS_KEY_ID","R2_SECRET_ACCESS_KEY"];case"s3":return["S3_BUCKET","S3_ACCESS_KEY_ID","S3_SECRET_ACCESS_KEY"];case"huggingface":return["HF_BUCKET","HF_S3_ACCESS_KEY_ID","HF_S3_SECRET_ACCESS_KEY"];case"local":return[];default:return[]}}function Ce(e){let o=N(e);return o==="local"?!0:Se(o).every(t=>!!e.get(t)?.trim())}function ee(e){return e?e.length<=8?"configured":`${e.slice(0,4)}\u2022\u2022\u2022\u2022${e.slice(-3)}`:"not configured"}function fo(e){let t=["# ==========================================================","# TOOLNET MEMORY","# Generated by: toolnet-memory setup","# Do not commit this file.","# ==========================================================","",`MEMORY_STORAGE_PROVIDER=${N(e)}`,"","# ----------------------------------------------------------","# Cloudflare R2","# ----------------------------------------------------------",`R2_ACCOUNT_ID=${e.get("R2_ACCOUNT_ID")??""}`,`R2_BUCKET=${e.get("R2_BUCKET")??"toolnet-memory"}`,`R2_ACCESS_KEY_ID=${e.get("R2_ACCESS_KEY_ID")??""}`,`R2_SECRET_ACCESS_KEY=${e.get("R2_SECRET_ACCESS_KEY")??""}`,"","# ----------------------------------------------------------","# Generic S3 / S3-compatible","# ----------------------------------------------------------",`S3_ENDPOINT=${e.get("S3_ENDPOINT")??""}`,`S3_REGION=${e.get("S3_REGION")??"us-east-1"}`,`S3_BUCKET=${e.get("S3_BUCKET")??"toolnet-memory"}`,`S3_ACCESS_KEY_ID=${e.get("S3_ACCESS_KEY_ID")??""}`,`S3_SECRET_ACCESS_KEY=${e.get("S3_SECRET_ACCESS_KEY")??""}`,`S3_FORCE_PATH_STYLE=${e.get("S3_FORCE_PATH_STYLE")??"false"}`,"","# ----------------------------------------------------------","# Hugging Face S3","# ----------------------------------------------------------",`HF_NAMESPACE=${e.get("HF_NAMESPACE")??""}`,`HF_BUCKET=${e.get("HF_BUCKET")??"toolnet-memory"}`,`HF_S3_ACCESS_KEY_ID=${e.get("HF_S3_ACCESS_KEY_ID")??""}`,`HF_S3_SECRET_ACCESS_KEY=${e.get("HF_S3_SECRET_ACCESS_KEY")??""}`,`HF_URL=${e.get("HF_URL")??""}`,"","# ----------------------------------------------------------","# AI / LLM - canonical ToolNet configuration","# ----------------------------------------------------------",`TOOLNET_LLM_PROVIDER=${e.get("TOOLNET_LLM_PROVIDER")??""}`,`TOOLNET_LLM_API_KEY=${e.get("TOOLNET_LLM_API_KEY")??""}`,`TOOLNET_LLM_BASE_URL=${e.get("TOOLNET_LLM_BASE_URL")??""}`,`TOOLNET_LLM_MODEL=${e.get("TOOLNET_LLM_MODEL")??""}`,`TOOLNET_LLM_ACCOUNT_ID=${e.get("TOOLNET_LLM_ACCOUNT_ID")??""}`,"","# ----------------------------------------------------------","# LLM fallback chain","# ----------------------------------------------------------",`TOOLNET_LLM_FALLBACK_1_PROVIDER=${e.get("TOOLNET_LLM_FALLBACK_1_PROVIDER")??""}`,`TOOLNET_LLM_FALLBACK_1_API_KEY=${e.get("TOOLNET_LLM_FALLBACK_1_API_KEY")??""}`,`TOOLNET_LLM_FALLBACK_1_BASE_URL=${e.get("TOOLNET_LLM_FALLBACK_1_BASE_URL")??""}`,`TOOLNET_LLM_FALLBACK_1_MODEL=${e.get("TOOLNET_LLM_FALLBACK_1_MODEL")??""}`,`TOOLNET_LLM_FALLBACK_1_ACCOUNT_ID=${e.get("TOOLNET_LLM_FALLBACK_1_ACCOUNT_ID")??""}`,`TOOLNET_LLM_FALLBACK_2_PROVIDER=${e.get("TOOLNET_LLM_FALLBACK_2_PROVIDER")??""}`,`TOOLNET_LLM_FALLBACK_2_API_KEY=${e.get("TOOLNET_LLM_FALLBACK_2_API_KEY")??""}`,`TOOLNET_LLM_FALLBACK_2_BASE_URL=${e.get("TOOLNET_LLM_FALLBACK_2_BASE_URL")??""}`,`TOOLNET_LLM_FALLBACK_2_MODEL=${e.get("TOOLNET_LLM_FALLBACK_2_MODEL")??""}`,`TOOLNET_LLM_FALLBACK_2_ACCOUNT_ID=${e.get("TOOLNET_LLM_FALLBACK_2_ACCOUNT_ID")??""}`,`TOOLNET_LLM_FALLBACK_COOLDOWN_MS=${e.get("TOOLNET_LLM_FALLBACK_COOLDOWN_MS")??"60000"}`,`TOOLNET_LLM_MAX_RETRIES=${e.get("TOOLNET_LLM_MAX_RETRIES")??"1"}`,"","# ----------------------------------------------------------","# Embedding - canonical ToolNet configuration","# ----------------------------------------------------------",`TOOLNET_EMBEDDING_PROVIDER=${e.get("TOOLNET_EMBEDDING_PROVIDER")??""}`,`TOOLNET_EMBEDDING_API_KEY=${e.get("TOOLNET_EMBEDDING_API_KEY")??""}`,`TOOLNET_EMBEDDING_BASE_URL=${e.get("TOOLNET_EMBEDDING_BASE_URL")??""}`,`TOOLNET_EMBEDDING_MODEL=${e.get("TOOLNET_EMBEDDING_MODEL")??""}`,`TOOLNET_EMBEDDING_ACCOUNT_ID=${e.get("TOOLNET_EMBEDDING_ACCOUNT_ID")??""}`,"","# ----------------------------------------------------------","# Embedding - legacy/current compatibility","# ----------------------------------------------------------",`HF_TOKEN=${e.get("HF_TOKEN")??""}`,`HF_EMBEDDING_MODEL=${e.get("HF_EMBEDDING_MODEL")??"sentence-transformers/all-MiniLM-L6-v2"}`,"","# ----------------------------------------------------------","# Local storage/cache","# ----------------------------------------------------------",`MEMORY_LOCAL_STORAGE_PATH=${e.get("MEMORY_LOCAL_STORAGE_PATH")??""}`,`MEMORY_LOCAL_CACHE_MB=${e.get("MEMORY_LOCAL_CACHE_MB")??"200"}`,"","# ----------------------------------------------------------","# Automation","# ----------------------------------------------------------",`MEMORY_AUTO_CAPTURE=${e.get("MEMORY_AUTO_CAPTURE")??"true"}`,`MEMORY_AUTO_RETRIEVE=${e.get("MEMORY_AUTO_RETRIEVE")??"true"}`,`MEMORY_AUTO_SUMMARIZE=${e.get("MEMORY_AUTO_SUMMARIZE")??"true"}`,`MEMORY_AUTO_SYNC=${e.get("MEMORY_AUTO_SYNC")??"true"}`,"","# ----------------------------------------------------------","# Retrieval","# ----------------------------------------------------------",`MEMORY_MAX_CANDIDATES=${e.get("MEMORY_MAX_CANDIDATES")??"50"}`,`MEMORY_RERANK_TOP=${e.get("MEMORY_RERANK_TOP")??"10"}`,`MEMORY_FINAL_CONTEXT=${e.get("MEMORY_FINAL_CONTEXT")??"5"}`,`MEMORY_TOKEN_BUDGET=${e.get("MEMORY_TOKEN_BUDGET")??"2000"}`,"","# ----------------------------------------------------------","# Automatic Session Memory","# ----------------------------------------------------------",`TOOLNET_SESSION_LEARNING=${e.get("TOOLNET_SESSION_LEARNING")??"1"}`,`TOOLNET_WORK_CONTINUITY=${e.get("TOOLNET_WORK_CONTINUITY")??"1"}`,`TOOLNET_SEMANTIC_CONTINUITY=${e.get("TOOLNET_SEMANTIC_CONTINUITY")??"1"}`,`TOOLNET_SMART_HANDOFF=${e.get("TOOLNET_SMART_HANDOFF")??"1"}`],n=[...e.entries()].filter(([r])=>!Oo.has(r));if(n.length>0){t.push("","# ----------------------------------------------------------","# Preserved settings","# ----------------------------------------------------------");for(let[r,i]of n)t.push(`${r}=${i}`)}return`${t.join(`
|
|
706
|
+
`),De(o,n,{encoding:"utf8",mode:384}),{configFile:o,previousFile:t,preservedPrevious:E.length>0&&!u}}import{existsSync as bo,mkdirSync as Po,readFileSync as Ko,writeFileSync as Uo}from"node:fs";import{homedir as Bo}from"node:os";import{dirname as wo,join as Ke}from"node:path";function ko(e){return`'${e.replace(/'/g,"'\\''")}'`}function Ue(e={}){let o=e.hooksFile??Ke(process.env.CODEX_HOME??Ke(Bo(),".codex"),"hooks.json");Po(wo(o),{recursive:!0});let t={};if(bo(o))try{t=JSON.parse(Ko(o,"utf8"))}catch(a){throw new Error(`Invalid existing Codex hooks.json: ${a instanceof Error?a.message:String(a)}`)}let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{};t.hooks=n;let i=(Array.isArray(n.SessionStart)?n.SessionStart:[]).filter(a=>{try{return!JSON.stringify(a).includes("session:codex-context")}catch{return!0}}),s=e.binary??"toolnet-memory";return i.push({matcher:"startup|resume|clear|compact",hooks:[{type:"command",command:`${ko(s)} session:codex-context`,timeout:15,additionalContextLimit:1e3,statusMessage:"Loading ToolNet project continuity"}]}),n.SessionStart=i,Uo(o,JSON.stringify(t,null,2)+`
|
|
707
|
+
`,{encoding:"utf8",mode:384}),o}import{spawnSync as Yo}from"node:child_process";function X(e,o){return Yo(e,o,{encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Be(e,o){let t=X(e,["mcp","get",o,"--json"]);if(t.status!==0||!t.stdout)return null;try{return JSON.parse(t.stdout)}catch{return null}}function we(e,o){return e.enabled!==!1&&e.transport?.type==="stdio"&&e.transport?.command===o&&Array.isArray(e.transport?.args)&&e.transport?.args.length===1&&e.transport.args[0]==="mcp"}function ke(e={}){let o=e.binary??process.env.TOOLNET_MEMORY_BIN??"toolnet-memory",t=e.codexBinary??"codex",n=e.serverName??"toolnet-memory",r=Be(t,n);if(r&&we(r,o))return{installed:!0,changed:!1,serverName:n,command:o,args:["mcp"]};if(r){let a=X(t,["mcp","remove",n]);if(a.status!==0)return{installed:!1,changed:!1,serverName:n,command:o,args:["mcp"],error:(a.stderr||a.stdout||"Unable to remove old ToolNet MCP configuration.").trim()}}let i=X(t,["mcp","add",n,"--",o,"mcp"]);if(i.status!==0)return{installed:!1,changed:!1,serverName:n,command:o,args:["mcp"],error:(i.stderr||i.stdout||"Unable to register ToolNet MCP.").trim()};let s=Be(t,n);return!s||!we(s,o)?{installed:!1,changed:!0,serverName:n,command:o,args:["mcp"],error:"Codex accepted MCP registration but verification did not match expected ToolNet command."}:{installed:!0,changed:!0,serverName:n,command:o,args:["mcp"]}}function ee(e){return $o("sh",["-lc",`command -v ${JSON.stringify(e)} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}function Fo(){return ee("agy")||z(Z(Q(),".gemini"))}function xo(){return ee("opencode")||z(Z(Q(),".config","opencode"))}function Go(){return ee("codex")||z(process.env.CODEX_HOME??Z(Q(),".codex"))}function oe(e={}){let o=e.binary??process.env.TOOLNET_MEMORY_BIN??"toolnet-memory",t=[];if(!(e.force===!0||Fo()))t.push({agent:"agy",detected:!1,installed:!1,targets:[]});else try{let r=Oe({binary:o}),i=ue({binary:o});t.push({agent:"agy",detected:!0,installed:!0,targets:[r,i.configFile]})}catch(r){t.push({agent:"agy",detected:!0,installed:!1,targets:[],error:r instanceof Error?r.message:String(r)})}if(!(e.force===!0||xo()))t.push({agent:"opencode",detected:!1,installed:!1,targets:[]});else try{let r=Me({binary:o}),i=Re({binary:o});t.push({agent:"opencode",detected:!0,installed:!0,targets:[r,i.configFile,`mcp:${i.serverName}`]})}catch(r){t.push({agent:"opencode",detected:!0,installed:!1,targets:[],error:r instanceof Error?r.message:String(r)})}if(!(e.force===!0||Go()))t.push({agent:"codex",detected:!1,installed:!1,targets:[]});else try{let r=Pe({binary:o}),i=Ue({binary:o}),s=ke({binary:o});if(!s.installed)throw new Error(s.error??"Codex MCP registration failed");let a=[r.configFile,i,`mcp:${s.serverName}`];r.preservedPrevious&&a.push(r.previousFile),t.push({agent:"codex",detected:!0,installed:!0,targets:a})}catch(r){t.push({agent:"codex",detected:!0,installed:!1,targets:[],error:r instanceof Error?r.message:String(r)})}return t}function Ho(e){console.log(""),console.log("ToolNet Memory AI Integrations"),console.log("=============================="),console.log("");for(let o of e){let t=o.agent==="agy"?"Agy / Antigravity":o.agent==="opencode"?"OpenCode":"Codex";if(!o.detected){console.log(`- ${t}: not detected`);continue}if(o.installed){console.log(`\u2713 ${t}: automatic memory enabled`);continue}console.log(`\u2717 ${t}: integration failed`),o.error&&console.log(` ${o.error}`)}console.log("")}async function qo(){let e=process.argv.slice(2),o=e.includes("--all"),t=e.includes("--json"),n=oe({force:o});if(t){console.log(JSON.stringify(n,null,2));return}Ho(n)}var jo=process.argv[1]&&(process.argv[1].endsWith("auto-integrate.js")||process.argv[1].endsWith("auto-integrate.ts"));jo&&qo().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});var te=P.join(ne.homedir(),".config","toolnet-memory"),L=P.join(te,".env"),Wo=new Set(["MEMORY_STORAGE_PROVIDER","R2_ACCOUNT_ID","R2_BUCKET","R2_ACCESS_KEY_ID","R2_SECRET_ACCESS_KEY","S3_ENDPOINT","S3_REGION","S3_BUCKET","S3_ACCESS_KEY_ID","S3_SECRET_ACCESS_KEY","S3_FORCE_PATH_STYLE","HF_NAMESPACE","HF_BUCKET","HF_S3_ACCESS_KEY_ID","HF_S3_SECRET_ACCESS_KEY","HF_URL","HF_TOKEN","HF_EMBEDDING_MODEL","TOOLNET_LLM_PROVIDER","TOOLNET_LLM_API_KEY","TOOLNET_LLM_BASE_URL","TOOLNET_LLM_MODEL","TOOLNET_LLM_FALLBACK_1_PROVIDER","TOOLNET_LLM_FALLBACK_1_API_KEY","TOOLNET_LLM_FALLBACK_1_BASE_URL","TOOLNET_LLM_FALLBACK_1_MODEL","TOOLNET_LLM_FALLBACK_1_ACCOUNT_ID","TOOLNET_LLM_FALLBACK_2_PROVIDER","TOOLNET_LLM_FALLBACK_2_API_KEY","TOOLNET_LLM_FALLBACK_2_BASE_URL","TOOLNET_LLM_FALLBACK_2_MODEL","TOOLNET_LLM_FALLBACK_2_ACCOUNT_ID","TOOLNET_LLM_FALLBACK_COOLDOWN_MS","TOOLNET_LLM_MAX_RETRIES","TOOLNET_LLM_ACCOUNT_ID","TOOLNET_EMBEDDING_PROVIDER","TOOLNET_EMBEDDING_API_KEY","TOOLNET_EMBEDDING_BASE_URL","TOOLNET_EMBEDDING_MODEL","TOOLNET_EMBEDDING_ACCOUNT_ID","MEMORY_LOCAL_STORAGE_PATH","MEMORY_LOCAL_CACHE_MB","MEMORY_AUTO_CAPTURE","MEMORY_AUTO_RETRIEVE","MEMORY_AUTO_SUMMARIZE","MEMORY_AUTO_SYNC","MEMORY_MAX_CANDIDATES","MEMORY_RERANK_TOP","MEMORY_FINAL_CONTEXT","MEMORY_TOKEN_BUDGET","TOOLNET_SESSION_LEARNING","TOOLNET_WORK_CONTINUITY","TOOLNET_SEMANTIC_CONTINUITY","TOOLNET_SMART_HANDOFF"]);function Xo(e){let o=new Map;for(let t of e.split(/\r?\n/)){let n=t.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(r===-1)continue;let i=n.slice(0,r).trim(),s=n.slice(r+1).trim();i&&o.set(i,s)}return o}function N(e){let o=e.get("MEMORY_STORAGE_PROVIDER")?.trim();return o==="r2"||o==="s3"||o==="local"||o==="huggingface"?o:e.get("R2_ACCOUNT_ID")&&e.get("R2_BUCKET")?"r2":e.get("S3_BUCKET")?"s3":e.get("HF_BUCKET")&&e.get("HF_S3_ACCESS_KEY_ID")?"huggingface":e.get("MEMORY_LOCAL_STORAGE_PATH")?"local":"r2"}function K(e){switch(e){case"r2":return"Cloudflare R2";case"s3":return"S3 / S3-compatible";case"huggingface":return"Hugging Face S3";case"local":return"Local";default:return e}}function xe(e){switch(e){case"r2":return["R2_ACCOUNT_ID","R2_BUCKET","R2_ACCESS_KEY_ID","R2_SECRET_ACCESS_KEY"];case"s3":return["S3_BUCKET","S3_ACCESS_KEY_ID","S3_SECRET_ACCESS_KEY"];case"huggingface":return["HF_BUCKET","HF_S3_ACCESS_KEY_ID","HF_S3_SECRET_ACCESS_KEY"];case"local":return[];default:return[]}}function Ge(e){let o=N(e);return o==="local"?!0:xe(o).every(t=>!!e.get(t)?.trim())}function re(e){return e?e.length<=8?"configured":`${e.slice(0,4)}\u2022\u2022\u2022\u2022${e.slice(-3)}`:"not configured"}function zo(e){let t=["# ==========================================================","# TOOLNET MEMORY","# Generated by: toolnet-memory setup","# Do not commit this file.","# ==========================================================","",`MEMORY_STORAGE_PROVIDER=${N(e)}`,"","# ----------------------------------------------------------","# Cloudflare R2","# ----------------------------------------------------------",`R2_ACCOUNT_ID=${e.get("R2_ACCOUNT_ID")??""}`,`R2_BUCKET=${e.get("R2_BUCKET")??"toolnet-memory"}`,`R2_ACCESS_KEY_ID=${e.get("R2_ACCESS_KEY_ID")??""}`,`R2_SECRET_ACCESS_KEY=${e.get("R2_SECRET_ACCESS_KEY")??""}`,"","# ----------------------------------------------------------","# Generic S3 / S3-compatible","# ----------------------------------------------------------",`S3_ENDPOINT=${e.get("S3_ENDPOINT")??""}`,`S3_REGION=${e.get("S3_REGION")??"us-east-1"}`,`S3_BUCKET=${e.get("S3_BUCKET")??"toolnet-memory"}`,`S3_ACCESS_KEY_ID=${e.get("S3_ACCESS_KEY_ID")??""}`,`S3_SECRET_ACCESS_KEY=${e.get("S3_SECRET_ACCESS_KEY")??""}`,`S3_FORCE_PATH_STYLE=${e.get("S3_FORCE_PATH_STYLE")??"false"}`,"","# ----------------------------------------------------------","# Hugging Face S3","# ----------------------------------------------------------",`HF_NAMESPACE=${e.get("HF_NAMESPACE")??""}`,`HF_BUCKET=${e.get("HF_BUCKET")??"toolnet-memory"}`,`HF_S3_ACCESS_KEY_ID=${e.get("HF_S3_ACCESS_KEY_ID")??""}`,`HF_S3_SECRET_ACCESS_KEY=${e.get("HF_S3_SECRET_ACCESS_KEY")??""}`,`HF_URL=${e.get("HF_URL")??""}`,"","# ----------------------------------------------------------","# AI / LLM - canonical ToolNet configuration","# ----------------------------------------------------------",`TOOLNET_LLM_PROVIDER=${e.get("TOOLNET_LLM_PROVIDER")??""}`,`TOOLNET_LLM_API_KEY=${e.get("TOOLNET_LLM_API_KEY")??""}`,`TOOLNET_LLM_BASE_URL=${e.get("TOOLNET_LLM_BASE_URL")??""}`,`TOOLNET_LLM_MODEL=${e.get("TOOLNET_LLM_MODEL")??""}`,`TOOLNET_LLM_ACCOUNT_ID=${e.get("TOOLNET_LLM_ACCOUNT_ID")??""}`,"","# ----------------------------------------------------------","# LLM fallback chain","# ----------------------------------------------------------",`TOOLNET_LLM_FALLBACK_1_PROVIDER=${e.get("TOOLNET_LLM_FALLBACK_1_PROVIDER")??""}`,`TOOLNET_LLM_FALLBACK_1_API_KEY=${e.get("TOOLNET_LLM_FALLBACK_1_API_KEY")??""}`,`TOOLNET_LLM_FALLBACK_1_BASE_URL=${e.get("TOOLNET_LLM_FALLBACK_1_BASE_URL")??""}`,`TOOLNET_LLM_FALLBACK_1_MODEL=${e.get("TOOLNET_LLM_FALLBACK_1_MODEL")??""}`,`TOOLNET_LLM_FALLBACK_1_ACCOUNT_ID=${e.get("TOOLNET_LLM_FALLBACK_1_ACCOUNT_ID")??""}`,`TOOLNET_LLM_FALLBACK_2_PROVIDER=${e.get("TOOLNET_LLM_FALLBACK_2_PROVIDER")??""}`,`TOOLNET_LLM_FALLBACK_2_API_KEY=${e.get("TOOLNET_LLM_FALLBACK_2_API_KEY")??""}`,`TOOLNET_LLM_FALLBACK_2_BASE_URL=${e.get("TOOLNET_LLM_FALLBACK_2_BASE_URL")??""}`,`TOOLNET_LLM_FALLBACK_2_MODEL=${e.get("TOOLNET_LLM_FALLBACK_2_MODEL")??""}`,`TOOLNET_LLM_FALLBACK_2_ACCOUNT_ID=${e.get("TOOLNET_LLM_FALLBACK_2_ACCOUNT_ID")??""}`,`TOOLNET_LLM_FALLBACK_COOLDOWN_MS=${e.get("TOOLNET_LLM_FALLBACK_COOLDOWN_MS")??"60000"}`,`TOOLNET_LLM_MAX_RETRIES=${e.get("TOOLNET_LLM_MAX_RETRIES")??"1"}`,"","# ----------------------------------------------------------","# Embedding - canonical ToolNet configuration","# ----------------------------------------------------------",`TOOLNET_EMBEDDING_PROVIDER=${e.get("TOOLNET_EMBEDDING_PROVIDER")??""}`,`TOOLNET_EMBEDDING_API_KEY=${e.get("TOOLNET_EMBEDDING_API_KEY")??""}`,`TOOLNET_EMBEDDING_BASE_URL=${e.get("TOOLNET_EMBEDDING_BASE_URL")??""}`,`TOOLNET_EMBEDDING_MODEL=${e.get("TOOLNET_EMBEDDING_MODEL")??""}`,`TOOLNET_EMBEDDING_ACCOUNT_ID=${e.get("TOOLNET_EMBEDDING_ACCOUNT_ID")??""}`,"","# ----------------------------------------------------------","# Embedding - legacy/current compatibility","# ----------------------------------------------------------",`HF_TOKEN=${e.get("HF_TOKEN")??""}`,`HF_EMBEDDING_MODEL=${e.get("HF_EMBEDDING_MODEL")??"sentence-transformers/all-MiniLM-L6-v2"}`,"","# ----------------------------------------------------------","# Local storage/cache","# ----------------------------------------------------------",`MEMORY_LOCAL_STORAGE_PATH=${e.get("MEMORY_LOCAL_STORAGE_PATH")??""}`,`MEMORY_LOCAL_CACHE_MB=${e.get("MEMORY_LOCAL_CACHE_MB")??"200"}`,"","# ----------------------------------------------------------","# Automation","# ----------------------------------------------------------",`MEMORY_AUTO_CAPTURE=${e.get("MEMORY_AUTO_CAPTURE")??"true"}`,`MEMORY_AUTO_RETRIEVE=${e.get("MEMORY_AUTO_RETRIEVE")??"true"}`,`MEMORY_AUTO_SUMMARIZE=${e.get("MEMORY_AUTO_SUMMARIZE")??"true"}`,`MEMORY_AUTO_SYNC=${e.get("MEMORY_AUTO_SYNC")??"true"}`,"","# ----------------------------------------------------------","# Retrieval","# ----------------------------------------------------------",`MEMORY_MAX_CANDIDATES=${e.get("MEMORY_MAX_CANDIDATES")??"50"}`,`MEMORY_RERANK_TOP=${e.get("MEMORY_RERANK_TOP")??"10"}`,`MEMORY_FINAL_CONTEXT=${e.get("MEMORY_FINAL_CONTEXT")??"5"}`,`MEMORY_TOKEN_BUDGET=${e.get("MEMORY_TOKEN_BUDGET")??"2000"}`,"","# ----------------------------------------------------------","# Automatic Session Memory","# ----------------------------------------------------------",`TOOLNET_SESSION_LEARNING=${e.get("TOOLNET_SESSION_LEARNING")??"1"}`,`TOOLNET_WORK_CONTINUITY=${e.get("TOOLNET_WORK_CONTINUITY")??"1"}`,`TOOLNET_SEMANTIC_CONTINUITY=${e.get("TOOLNET_SEMANTIC_CONTINUITY")??"1"}`,`TOOLNET_SMART_HANDOFF=${e.get("TOOLNET_SMART_HANDOFF")??"1"}`],n=[...e.entries()].filter(([r])=>!Wo.has(r));if(n.length>0){t.push("","# ----------------------------------------------------------","# Preserved settings","# ----------------------------------------------------------");for(let[r,i]of n)t.push(`${r}=${i}`)}return`${t.join(`
|
|
658
708
|
`)}
|
|
659
|
-
`}function
|
|
660
|
-
`),e.resume(),t(n))},s=
|
|
661
|
-
`){i();return}if(
|
|
662
|
-
`),process.exit(130)),
|
|
663
|
-
`,{encoding:"utf8",mode:384}),p.unlinkSync(t),{ok:!0,message:`Writable: ${o}`}}catch(n){return{ok:!1,message:n instanceof Error?n.message:String(n)}}}async function po(e,o){switch(e){case"r2":return uo(o);case"s3":return mo(o);case"huggingface":return To(o);case"local":return Ao(o)}}async function Mo(e,o){console.log(""),console.log(`Testing ${P(e)}...`);let t=await po(e,o);return t.ok?console.log(`\u2713 ${t.message}`):(console.log("\u2717 Connection test failed"),console.log(` ${t.message}`)),console.log(""),t}function Io(){console.log(""),console.log("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log("\u2551 TOOLNET MEMORY SETUP \u2551"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log("")}function No(e){let o=N(e);console.log("Current configuration"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(`Storage : ${P(o)} ${Ce(e)?"\u2713":"\u26A0 incomplete"}`);let t=e.get("TOOLNET_LLM_PROVIDER"),n=e.get("TOOLNET_LLM_MODEL"),r=e.get("TOOLNET_EMBEDDING_PROVIDER");console.log(`LLM : ${t?`${M(t)}${n?` / ${n}`:""}`:"not configured"}`),console.log(`Embedding: ${r||"legacy/default"}`),console.log("")}async function So(e){console.log("Setup"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" 1. Storage"),console.log(" 2. AI Model"),console.log(" 3. Finish & Save"),console.log(" 0. Exit without saving"),console.log("");let o=(await e.question("Choose [1-3]: ")).trim();return o==="1"?"storage":o==="2"?"ai":o==="0"?"exit":"finish"}async function Co(e,o){console.log(""),console.log("Storage"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` 1. Cloudflare R2${o==="r2"?" \u2713 current":""}`),console.log(` 2. S3 / S3-compatible${o==="s3"?" \u2713 current":""}`),console.log(` 3. Hugging Face S3${o==="huggingface"?" \u2713 current":""}`),console.log(` 4. Local${o==="local"?" \u2713 current":""}`),console.log(""),console.log(" 0. Back"),console.log("");let t=(await e.question("Choose storage: ")).trim();return t==="0"?"back":t==="2"?"s3":t==="3"?"huggingface":t==="4"?"local":"r2"}async function Ro(e,o){console.log(""),console.log("Cloudflare R2"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=await e.question(o.get("R2_ACCOUNT_ID")?`ACCOUNT ID [${o.get("R2_ACCOUNT_ID")}]: `:"ACCOUNT ID: "),n=await e.question(o.get("R2_ACCESS_KEY_ID")?`ACCESS KEY ID [${ee(o.get("R2_ACCESS_KEY_ID"))}]: `:"ACCESS KEY ID: "),r=await e.question(`BUCKET [${o.get("R2_BUCKET")||"toolnet-memory"}]: `);T(o,"R2_ACCOUNT_ID",t),T(o,"R2_ACCESS_KEY_ID",n),T(o,"R2_BUCKET",r,"toolnet-memory");let i=o.get("R2_ACCOUNT_ID")?.trim();i&&console.log(`URL: ${Re(i)}`);let s=await y(e,o.get("R2_SECRET_ACCESS_KEY")?"SECRET ACCESS KEY [configured, Enter = keep]: ":"SECRET ACCESS KEY: ");s.trim()&&o.set("R2_SECRET_ACCESS_KEY",s.trim())}async function yo(e,o){console.log(""),console.log("S3 / S3-compatible"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=await e.question(o.get("S3_ENDPOINT")?`URL / ENDPOINT [${o.get("S3_ENDPOINT")}]: `:"URL / ENDPOINT [blank = AWS S3]: "),n=await e.question(`REGION [${o.get("S3_REGION")||"us-east-1"}]: `),r=await e.question(o.get("S3_ACCESS_KEY_ID")?`ACCESS KEY ID [${ee(o.get("S3_ACCESS_KEY_ID"))}]: `:"ACCESS KEY ID: "),i=await e.question(`BUCKET [${o.get("S3_BUCKET")||"toolnet-memory"}]: `),s=o.get("S3_FORCE_PATH_STYLE")==="true",l=await e.question(`FORCE PATH STYLE [${s?"Y":"N"}] (y/n): `);if(t.trim()&&o.set("S3_ENDPOINT",S(t)),T(o,"S3_REGION",n,"us-east-1"),T(o,"S3_ACCESS_KEY_ID",r),T(o,"S3_BUCKET",i,"toolnet-memory"),l.trim()){let E=l.trim().toLowerCase();o.set("S3_FORCE_PATH_STYLE",E==="y"||E==="yes"?"true":"false")}else o.has("S3_FORCE_PATH_STYLE")||o.set("S3_FORCE_PATH_STYLE","false");let a=await y(e,o.get("S3_SECRET_ACCESS_KEY")?"SECRET ACCESS KEY [configured, Enter = keep]: ":"SECRET ACCESS KEY: ");a.trim()&&o.set("S3_SECRET_ACCESS_KEY",a.trim())}async function Do(e,o){console.log(""),console.log("Hugging Face S3"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=await e.question(o.get("HF_NAMESPACE")?`NAMESPACE [${o.get("HF_NAMESPACE")}]: `:"NAMESPACE [optional]: "),n=await e.question(o.get("HF_S3_ACCESS_KEY_ID")?`ACCESS KEY ID [${ee(o.get("HF_S3_ACCESS_KEY_ID"))}]: `:"ACCESS KEY ID: "),r=await e.question(`BUCKET [${o.get("HF_BUCKET")||"toolnet-memory"}]: `),i=await e.question(o.get("HF_URL")?`URL [${o.get("HF_URL")}]: `:"URL / S3 ENDPOINT: ");T(o,"HF_NAMESPACE",t),T(o,"HF_S3_ACCESS_KEY_ID",n),T(o,"HF_BUCKET",r,"toolnet-memory"),i.trim()&&o.set("HF_URL",S(i));let s=await y(e,o.get("HF_S3_SECRET_ACCESS_KEY")?"SECRET ACCESS KEY [configured, Enter = keep]: ":"SECRET ACCESS KEY: ");s.trim()&&o.set("HF_S3_SECRET_ACCESS_KEY",s.trim())}async function ho(e,o){console.log(""),console.log("Local Storage"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=o.get("MEMORY_LOCAL_STORAGE_PATH")??h.join(Z.homedir(),".local","share","toolnet-memory"),n=await e.question(`LOCAL PATH [${t}]: `);T(o,"MEMORY_LOCAL_STORAGE_PATH",n,t)}async function Po(e,o){let t=new Map(o);for(;;){let n=await Co(e,N(o));if(n==="back")return;let r=new Map(o);o.set("MEMORY_STORAGE_PROVIDER",n),n==="r2"?await Ro(e,o):n==="s3"?await yo(e,o):n==="huggingface"?await Do(e,o):await ho(e,o);let i=Se(n).filter(a=>!o.get(a)?.trim());if(i.length){console.log(""),console.log("\u26A0 Missing required fields:");for(let E of i)console.log(` - ${E}`);console.log(""),console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let a=(await e.question("Choose [1]: ")).trim()||"1";if(a==="2"){f(o),console.log(""),console.log("\u26A0 Saved with incomplete configuration"),console.log("");return}if(a==="3"){o.clear();for(let[E,d]of r)o.set(E,d);continue}if(a==="4"){o.clear();for(let[E,d]of t)o.set(E,d);console.log(""),console.log("Storage changes cancelled."),console.log("");return}continue}if((await Mo(n,o)).ok){f(o),console.log(`\u2713 ${P(n)} configuration saved`),console.log(` ${u}`),console.log("");return}console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let l=(await e.question("Choose [1]: ")).trim()||"1";if(l==="2"){f(o),console.log(""),console.log("\u26A0 Saved even though connection test failed"),console.log("");return}if(l==="3"){o.clear();for(let[a,E]of r)o.set(a,E);continue}if(l==="4"){o.clear();for(let[a,E]of t)o.set(a,E);console.log(""),console.log("Storage changes cancelled."),console.log("");return}}}var I=[{id:"openai-compatible",label:"OpenAI-compatible",apiKeyRequired:!0,baseUrlRequired:!0},{id:"alibaba",label:"Alibaba / DashScope",baseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",suggestedModel:"qwen3.6-flash",apiKeyRequired:!0},{id:"openrouter",label:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyRequired:!0},{id:"groq",label:"Groq",baseUrl:"https://api.groq.com/openai/v1",apiKeyRequired:!0},{id:"deepseek",label:"DeepSeek",baseUrl:"https://api.deepseek.com",suggestedModel:"deepseek-v4-flash",apiKeyRequired:!0},{id:"nvidia",label:"NVIDIA NIM",baseUrl:"https://integrate.api.nvidia.com/v1",suggestedModel:"deepseek-ai/deepseek-v4-pro",apiKeyRequired:!0},{id:"gemini",label:"Gemini",baseUrl:"https://generativelanguage.googleapis.com/v1beta",suggestedModel:"gemini-3.6-flash",apiKeyRequired:!0},{id:"huggingface",label:"Hugging Face",baseUrl:"https://router.huggingface.co/v1",apiKeyRequired:!0},{id:"ollama",label:"Ollama / Local",baseUrl:"http://127.0.0.1:11434/v1",apiKeyRequired:!1},{id:"custom",label:"Custom endpoint",apiKeyRequired:!1,baseUrlRequired:!0},{id:"cloudflare",label:"Cloudflare Workers AI",suggestedModel:"@cf/meta/llama-3.1-8b-instruct",apiKeyRequired:!0,accountIdRequired:!0}];function bo(e){return I.find(o=>o.id===e)}function M(e){return bo(e)?.label??e??"not configured"}function ye(e){let o=e.get("TOOLNET_LLM_PROVIDER")?.trim();return I.some(t=>t.id===o)?o:void 0}async function te(e,o){console.log(""),console.log("AI Model"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),I.forEach((r,i)=>{console.log(` ${i+1}. ${r.label}${o===r.id?" \u2713 current":""}`)}),console.log(""),console.log(" 0. Back"),console.log("");let t=(await e.question("Choose provider: ")).trim();if(t==="0")return"back";let n=Number(t)-1;return Number.isInteger(n)&&n>=0&&n<I.length?I[n].id:(console.log(""),console.log("\u26A0 Invalid provider selection"),te(e,o))}function Ko(e,o){return!(!e.get("TOOLNET_LLM_MODEL")?.trim()||o.apiKeyRequired&&!e.get("TOOLNET_LLM_API_KEY")?.trim()||o.accountIdRequired&&!e.get("TOOLNET_LLM_ACCOUNT_ID")?.trim()||o.baseUrlRequired&&!e.get("TOOLNET_LLM_BASE_URL")?.trim())}function Uo(e){e.delete("TOOLNET_LLM_API_KEY"),e.delete("TOOLNET_LLM_BASE_URL"),e.delete("TOOLNET_LLM_MODEL"),e.delete("TOOLNET_LLM_ACCOUNT_ID")}async function Bo(e,o,t){console.log(""),console.log(t.label),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let n=o.get("TOOLNET_LLM_PROVIDER");if(n&&n!==t.id&&Uo(o),o.set("TOOLNET_LLM_PROVIDER",t.id),t.accountIdRequired){let a=o.get("TOOLNET_LLM_ACCOUNT_ID"),E=await e.question(a?`ACCOUNT ID [${a}]: `:"ACCOUNT ID: ");T(o,"TOOLNET_LLM_ACCOUNT_ID",E)}else o.delete("TOOLNET_LLM_ACCOUNT_ID");if(t.apiKeyRequired||t.id==="custom"){let a=o.get("TOOLNET_LLM_API_KEY"),E=await y(e,a?"API KEY [configured, Enter = keep]: ":t.apiKeyRequired?"API KEY: ":"API KEY [optional]: ");E.trim()&&o.set("TOOLNET_LLM_API_KEY",E.trim())}else o.delete("TOOLNET_LLM_API_KEY");if(t.id!=="cloudflare"){let E=o.get("TOOLNET_LLM_BASE_URL")||t.baseUrl||"",m=(await e.question(E?`BASE URL [${E}]: `:t.baseUrlRequired?"BASE URL: ":"BASE URL [optional]: ")).trim()||E;m?o.set("TOOLNET_LLM_BASE_URL",S(m)):o.delete("TOOLNET_LLM_BASE_URL")}else o.delete("TOOLNET_LLM_BASE_URL");let i=o.get("TOOLNET_LLM_MODEL")||t.suggestedModel||"",l=(await e.question(i?`MODEL [${i}]: `:"MODEL: ")).trim()||i;l&&o.set("TOOLNET_LLM_MODEL",l)}function wo(e){let o=ye(e);if(!o)throw new Error("AI provider is not configured");return{id:o,apiKey:e.get("TOOLNET_LLM_API_KEY")?.trim()||void 0,baseUrl:e.get("TOOLNET_LLM_BASE_URL")?.trim()||void 0,model:e.get("TOOLNET_LLM_MODEL")?.trim()||void 0,accountId:e.get("TOOLNET_LLM_ACCOUNT_ID")?.trim()||void 0}}async function Yo(e){let o=wo(e);console.log(""),console.log(`Testing ${M(o.id)}...`);try{let n=await le(o).healthCheck();return n.ok?(console.log(`\u2713 Provider reachable${n.latencyMs?` (${n.latencyMs} ms)`:""}`),console.log(`\u2713 Model: ${n.model??o.model??"configured"}`),console.log(""),{ok:!0,message:n.message}):(console.log("\u2717 AI provider test failed"),console.log(` ${n.message}`),console.log(""),{ok:!1,message:n.message})}catch(t){let n=t instanceof Error?t.message:String(t);return console.log("\u2717 AI provider test failed"),console.log(` ${n}`),console.log(""),{ok:!1,message:n}}}var F=[{id:"local",label:"Local / Hash",apiKeyRequired:!1},{id:"huggingface",label:"Hugging Face",suggestedModel:"sentence-transformers/all-MiniLM-L6-v2",apiKeyRequired:!0},{id:"openai-compatible",label:"OpenAI-compatible",apiKeyRequired:!0,baseUrlRequired:!0},{id:"alibaba",label:"Alibaba / DashScope",baseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",suggestedModel:"text-embedding-v4",apiKeyRequired:!0},{id:"openrouter",label:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyRequired:!0},{id:"nvidia",label:"NVIDIA NIM",baseUrl:"https://integrate.api.nvidia.com/v1",apiKeyRequired:!0},{id:"ollama",label:"Ollama / Local",baseUrl:"http://127.0.0.1:11434/v1",apiKeyRequired:!1},{id:"gemini",label:"Gemini",baseUrl:"https://generativelanguage.googleapis.com/v1beta",suggestedModel:"gemini-embedding-001",apiKeyRequired:!0},{id:"cloudflare",label:"Cloudflare Workers AI",suggestedModel:"@cf/baai/bge-base-en-v1.5",apiKeyRequired:!0,accountIdRequired:!0},{id:"custom",label:"Custom OpenAI-compatible endpoint",apiKeyRequired:!1,baseUrlRequired:!0}];function ne(e){return F.find(o=>o.id===e)?.label??e??"not configured"}async function De(e,o){console.log(""),console.log("Embedding Model"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),F.forEach((r,i)=>{console.log(` ${i+1}. ${r.label}${o===r.id?" \u2713 current":""}`)}),console.log(""),console.log(" 0. Back"),console.log("");let t=(await e.question("Choose embedding provider: ")).trim();if(t==="0")return"back";let n=Number(t)-1;return Number.isInteger(n)&&n>=0&&n<F.length?F[n]:(console.log(""),console.log("\u26A0 Invalid selection"),De(e,o))}function Me(e){e.delete("TOOLNET_EMBEDDING_API_KEY"),e.delete("TOOLNET_EMBEDDING_BASE_URL"),e.delete("TOOLNET_EMBEDDING_MODEL"),e.delete("TOOLNET_EMBEDDING_ACCOUNT_ID")}async function $o(e,o,t){let n=o.get("TOOLNET_EMBEDDING_PROVIDER");if(n&&n!==t.id&&Me(o),o.set("TOOLNET_EMBEDDING_PROVIDER",t.id),console.log(""),console.log(t.label),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),t.id==="local"){Me(o),console.log("\u2713 Local embedding selected"),console.log(" No API key required.");return}if(t.accountIdRequired){let a=o.get("TOOLNET_EMBEDDING_ACCOUNT_ID"),E=await e.question(a?`ACCOUNT ID [${a}]: `:"ACCOUNT ID: ");T(o,"TOOLNET_EMBEDDING_ACCOUNT_ID",E)}else o.delete("TOOLNET_EMBEDDING_ACCOUNT_ID");if(t.apiKeyRequired||t.id==="custom"){let a=o.get("TOOLNET_EMBEDDING_API_KEY"),E=await y(e,a?"API KEY [configured, Enter = keep]: ":t.apiKeyRequired?"API KEY: ":"API KEY [optional]: ");E.trim()&&o.set("TOOLNET_EMBEDDING_API_KEY",E.trim())}else o.delete("TOOLNET_EMBEDDING_API_KEY");if(t.id==="cloudflare"){let a=o.get("TOOLNET_EMBEDDING_ACCOUNT_ID")?.trim();if(a){let E=`https://api.cloudflare.com/client/v4/accounts/${a}/ai/v1`;o.set("TOOLNET_EMBEDDING_BASE_URL",E),console.log(`BASE URL: ${E}`)}}else{let E=o.get("TOOLNET_EMBEDDING_BASE_URL")||t.baseUrl||"",m=(await e.question(E?`BASE URL [${E}]: `:t.baseUrlRequired?"BASE URL: ":"BASE URL [optional]: ")).trim()||E;m&&o.set("TOOLNET_EMBEDDING_BASE_URL",S(m))}let i=o.get("TOOLNET_EMBEDDING_MODEL")||t.suggestedModel||"",l=(await e.question(i?`MODEL [${i}]: `:"MODEL: ")).trim()||i;l&&o.set("TOOLNET_EMBEDDING_MODEL",l)}function ko(e,o){return o.id==="local"?!0:o.apiKeyRequired&&!e.get("TOOLNET_EMBEDDING_API_KEY")?.trim()||o.accountIdRequired&&!e.get("TOOLNET_EMBEDDING_ACCOUNT_ID")?.trim()||o.baseUrlRequired&&!e.get("TOOLNET_EMBEDDING_BASE_URL")?.trim()?!1:!!e.get("TOOLNET_EMBEDDING_MODEL")?.trim()}async function he(e){let o=e.get("TOOLNET_EMBEDDING_PROVIDER")?.trim();if(console.log(""),console.log(`Testing embedding: ${ne(o)}...`),o==="local")return console.log("\u2713 Local embedding ready"),console.log(""),!0;let t=e.get("TOOLNET_EMBEDDING_API_KEY")?.trim(),n=e.get("TOOLNET_EMBEDDING_MODEL")?.trim(),r=e.get("TOOLNET_EMBEDDING_BASE_URL")?.trim();try{if(!n)throw new Error("Embedding model is missing");if(o==="huggingface"){if(!t)throw new Error("API key is missing");let i=await fetch(`https://router.huggingface.co/hf-inference/models/${n}/pipeline/feature-extraction`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({inputs:["toolnet memory test"]})});if(!i.ok)throw new Error(`HTTP ${i.status}: ${await i.text()}`)}else if(o==="gemini"){if(!t)throw new Error("API key is missing");let i=n.replace(/^models\//,"");r=r||"https://generativelanguage.googleapis.com/v1beta";let s=await fetch(`${r.replace(/\/+$/,"")}/models/${encodeURIComponent(i)}:embedContent?key=${encodeURIComponent(t)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:`models/${i}`,content:{parts:[{text:"toolnet memory test"}]}})});if(!s.ok)throw new Error(`HTTP ${s.status}: ${await s.text()}`)}else{if(!r)throw new Error("BASE URL is missing");let i=await fetch(`${r.replace(/\/+$/,"")}/embeddings`,{method:"POST",headers:{"content-type":"application/json",...t?{authorization:`Bearer ${t}`}:{}},body:JSON.stringify({model:n,input:["toolnet memory test"]})});if(!i.ok)throw new Error(`HTTP ${i.status}: ${await i.text()}`);let s=await i.json();if(!Array.isArray(s.data)||!Array.isArray(s.data[0]?.embedding))throw new Error("Invalid embedding response")}return console.log("\u2713 Embedding provider reachable"),console.log(`\u2713 Model: ${n}`),console.log(""),!0}catch(i){return console.log("\u2717 Embedding test failed"),console.log(` ${i instanceof Error?i.message:String(i)}`),console.log(""),!1}}async function Fo(e,o){let t=new Map(o);for(;;){let n=await De(e,o.get("TOOLNET_EMBEDDING_PROVIDER"));if(n==="back")return;if(await $o(e,o,n),!ko(o,n)){console.log(""),console.log("\u26A0 Embedding configuration is incomplete."),console.log(""),console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let s=(await e.question("Choose [1]: ")).trim()||"1";if(s==="2"){f(o);return}if(s==="3")continue;if(s==="4"){o.clear();for(let[l,a]of t)o.set(l,a);return}continue}if(await he(o)){f(o),console.log(`\u2713 ${n.label} embedding configuration saved`),console.log(` ${u}`),console.log("");return}console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let i=(await e.question("Choose [1]: ")).trim()||"1";if(i==="2"){f(o);return}if(i!=="3"&&i==="4"){o.clear();for(let[s,l]of t)o.set(s,l);return}}}async function xo(e,o){let t=o.get("TOOLNET_LLM_PROVIDER")?.trim();if(!t){console.log(""),console.log("\u26A0 Configure LLM first."),console.log("");return}if(t==="deepseek"||t==="groq"){console.log(""),console.log(`\u26A0 ${M(t)} is configured as LLM-only.`),console.log("Choose Embedding separately."),console.log("");return}o.set("TOOLNET_EMBEDDING_PROVIDER",t);let n=o.get("TOOLNET_LLM_API_KEY"),r=o.get("TOOLNET_LLM_BASE_URL"),i=o.get("TOOLNET_LLM_ACCOUNT_ID");n&&o.set("TOOLNET_EMBEDDING_API_KEY",n),r&&o.set("TOOLNET_EMBEDDING_BASE_URL",r),i&&o.set("TOOLNET_EMBEDDING_ACCOUNT_ID",i);let s="";t==="alibaba"?s="text-embedding-v4":t==="gemini"?s="gemini-embedding-001":t==="cloudflare"?s="@cf/baai/bge-base-en-v1.5":t==="huggingface"&&(s="sentence-transformers/all-MiniLM-L6-v2");let a=(await e.question(s?`EMBEDDING MODEL [${s}]: `:"EMBEDDING MODEL: ")).trim()||s;if(!a){console.log(""),console.log("\u26A0 Embedding model is required."),console.log("");return}if(o.set("TOOLNET_EMBEDDING_MODEL",a),!await he(o)){let d=(await e.question("Save anyway? (y/N): ")).trim().toLowerCase();if(d!=="y"&&d!=="yes")return}f(o),console.log(""),console.log("\u2713 LLM credentials reused for Embedding"),console.log(`\u2713 Embedding model: ${a}`),console.log("")}function x(e){return`TOOLNET_LLM_FALLBACK_${e}`}function G(e,o){let t=x(o);for(let n of["PROVIDER","API_KEY","BASE_URL","MODEL","ACCOUNT_ID"])e.delete(`${t}_${n}`)}function Ie(e,o){let t=x(o),n=e.get(`${t}_PROVIDER`);if(!n)return"not configured";let r=e.get(`${t}_MODEL`);return`${M(n)}${r?` / ${r}`:""}`}async function Ne(e,o,t){console.log(""),console.log(`Fallback ${t}`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let n=await te(e,void 0);if(n==="back")return;let r=o.get("TOOLNET_LLM_PROVIDER");if(n===r){console.log(""),console.log("\u26A0 Fallback cannot be the same provider as Primary."),console.log("");return}let i=t===1?2:1,s=o.get(`${x(i)}_PROVIDER`);if(n===s){console.log(""),console.log("\u26A0 This provider is already used by the other fallback."),console.log("");return}let l=I.find(O=>O.id===n);if(!l)return;let a=x(t);if(G(o,t),o.set(`${a}_PROVIDER`,n),l.accountIdRequired){let O=await e.question("ACCOUNT ID: ");O.trim()&&o.set(`${a}_ACCOUNT_ID`,O.trim())}if(l.apiKeyRequired||n==="custom"){let O=await y(e,l.apiKeyRequired?"API KEY: ":"API KEY [optional]: ");O.trim()&&o.set(`${a}_API_KEY`,O.trim())}if(n==="cloudflare"){let O=o.get(`${a}_ACCOUNT_ID`);O&&o.set(`${a}_BASE_URL`,`https://api.cloudflare.com/client/v4/accounts/${O}/ai`)}else{let O=l.baseUrl??"",re=(await e.question(O?`BASE URL [${O}]: `:l.baseUrlRequired?"BASE URL: ":"BASE URL [optional]: ")).trim()||O;re&&o.set(`${a}_BASE_URL`,S(re))}let E=l.suggestedModel??"",m=(await e.question(E?`MODEL [${E}]: `:"MODEL: ")).trim()||E;if(!m){console.log(""),console.log("\u26A0 MODEL is required."),console.log(""),G(o,t);return}o.set(`${a}_MODEL`,m),f(o),console.log(""),console.log(`\u2713 Fallback ${t} saved`),console.log(` ${M(n)} / ${m}`),console.log("")}async function Go(e,o){let t=o.get("TOOLNET_LLM_FALLBACK_COOLDOWN_MS")||"60000",n=o.get("TOOLNET_LLM_MAX_RETRIES")||"1";console.log(""),console.log("Fallback Policy"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let r=await e.question(`COOLDOWN MS [${t}]: `);if(r.trim()){let s=Number(r.trim());Number.isFinite(s)&&s>=0?o.set("TOOLNET_LLM_FALLBACK_COOLDOWN_MS",String(Math.floor(s))):console.log("\u26A0 Invalid cooldown; keeping previous value.")}let i=await e.question(`MAX RETRIES [${n}]: `);if(i.trim()){let s=Number(i.trim());Number.isFinite(s)&&s>=0&&s<=5?o.set("TOOLNET_LLM_MAX_RETRIES",String(Math.floor(s))):console.log("\u26A0 MAX RETRIES must be between 0 and 5.")}f(o),console.log(""),console.log("\u2713 Fallback policy saved"),console.log("")}async function Ho(e,o){for(;;){console.log(""),console.log("LLM Fallback"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Primary : ${o.get("TOOLNET_LLM_PROVIDER")?`${M(o.get("TOOLNET_LLM_PROVIDER"))} / ${o.get("TOOLNET_LLM_MODEL")||"model not configured"}`:"not configured"}`),console.log(` Fallback 1 : ${Ie(o,1)}`),console.log(` Fallback 2 : ${Ie(o,2)}`),console.log(` Cooldown : ${o.get("TOOLNET_LLM_FALLBACK_COOLDOWN_MS")||"60000"} ms`),console.log(` Retries : ${o.get("TOOLNET_LLM_MAX_RETRIES")||"1"}`),console.log(""),console.log(" 1. Configure Fallback 1"),console.log(" 2. Configure Fallback 2"),console.log(" 3. Remove Fallback 1"),console.log(" 4. Remove Fallback 2"),console.log(" 5. Retry / cooldown settings"),console.log(" 0. Back"),console.log("");let t=(await e.question("Choose: ")).trim();if(t==="0")return;if(t==="1"){await Ne(e,o,1);continue}if(t==="2"){await Ne(e,o,2);continue}if(t==="3"){G(o,1),f(o),console.log(""),console.log("\u2713 Fallback 1 removed"),console.log("");continue}if(t==="4"){G(o,2),f(o),console.log(""),console.log("\u2713 Fallback 2 removed"),console.log("");continue}if(t==="5"){await Go(e,o);continue}console.log(""),console.log("\u26A0 Invalid selection")}}async function qo(e,o){for(;;){console.log(""),console.log("AI Model"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=o.get("TOOLNET_LLM_PROVIDER"),n=o.get("TOOLNET_EMBEDDING_PROVIDER");console.log(` LLM : ${t?`${M(t)} / ${o.get("TOOLNET_LLM_MODEL")||"model not configured"}`:"not configured"}`),console.log(` Embedding : ${n?`${ne(n)} / ${o.get("TOOLNET_EMBEDDING_MODEL")||(n==="local"?"local hash":"model not configured")}`:"legacy/default"}`),console.log(""),console.log(" 1. Configure LLM"),console.log(" 2. Configure Embedding"),console.log(" 3. Use LLM provider credentials for Embedding"),console.log(" 4. Configure LLM Fallbacks"),console.log(" 0. Back"),console.log("");let r=(await e.question("Choose: ")).trim();if(r==="0")return;if(r==="1"){await Vo(e,o);continue}if(r==="2"){await Fo(e,o);continue}if(r==="3"){await xo(e,o);continue}if(r==="4"){await Ho(e,o);continue}console.log(""),console.log("\u26A0 Invalid selection")}}async function Vo(e,o){let t=new Map(o);for(;;){let n=await te(e,ye(o));if(n==="back")return;let r=I.find(l=>l.id===n);if(!r)continue;if(await Bo(e,o,r),!Ko(o,r)){console.log(""),console.log("\u26A0 AI configuration is incomplete."),console.log(""),console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let l=(await e.question("Choose [1]: ")).trim()||"1";if(l==="2"){f(o),console.log(""),console.log("\u26A0 AI configuration saved without validation"),console.log(` ${u}`),console.log("");return}if(l==="3")continue;if(l==="4"){o.clear();for(let[a,E]of t)o.set(a,E);console.log(""),console.log("AI changes cancelled."),console.log("");return}continue}if((await Yo(o)).ok){f(o),console.log(`\u2713 ${r.label} configuration saved`),console.log(` ${u}`),console.log("");return}console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let s=(await e.question("Choose [1]: ")).trim()||"1";if(s==="2"){f(o),console.log(""),console.log("\u26A0 AI configuration saved even though provider test failed"),console.log(` ${u}`),console.log("");return}if(s!=="3"&&s==="4"){o.clear();for(let[l,a]of t)o.set(l,a);console.log(""),console.log("AI changes cancelled."),console.log("");return}}}function jo(){try{let o=z().filter(t=>t.installed);if(o.length===0)return;console.log(""),console.log("Automatic AI memory");for(let t of o){let n=t.agent==="agy"?"Agy / Antigravity":t.agent==="opencode"?"OpenCode":t.agent==="codex"?"Codex":t.agent;console.log(` \u2713 ${n}`)}}catch{}}function g(e,...o){for(let t of o){let n=e.get(t)?.trim();if(n)return n}}function _(e,o,t){t&&!e.get(o)?.trim()&&e.set(o,t)}function Wo(e){let o=!1,t=JSON.stringify([...e.entries()]);if(!e.get("TOOLNET_LLM_PROVIDER")?.trim()){let i;g(e,"GROQ_API_KEY")?i="groq":g(e,"DEEPSEEK_API_KEY")?i="deepseek":g(e,"NVIDIA_API_KEY","NVIDIA_NIM_API_KEY")?i="nvidia":g(e,"OPENROUTER_API_KEY")?i="openrouter":g(e,"ALIBABA_API_KEY","DASHSCOPE_API_KEY")?i="alibaba":g(e,"GEMINI_API_KEY","GOOGLE_API_KEY")?i="gemini":g(e,"CLOUDFLARE_API_TOKEN")&&g(e,"CLOUDFLARE_ACCOUNT_ID")?i="cloudflare":g(e,"HF_TOKEN")?i="huggingface":g(e,"OLLAMA_MODEL","OLLAMA_BASE_URL")?i="ollama":g(e,"OPENAI_API_KEY","MODEL_API_KEY")&&(i="openai-compatible"),i&&e.set("TOOLNET_LLM_PROVIDER",i)}switch(e.get("TOOLNET_LLM_PROVIDER")?.trim()){case"groq":_(e,"TOOLNET_LLM_API_KEY",g(e,"GROQ_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",g(e,"GROQ_BASE_URL")||"https://api.groq.com/openai/v1"),_(e,"TOOLNET_LLM_MODEL",g(e,"GROQ_MODEL"));break;case"deepseek":_(e,"TOOLNET_LLM_API_KEY",g(e,"DEEPSEEK_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",g(e,"DEEPSEEK_BASE_URL")||"https://api.deepseek.com"),_(e,"TOOLNET_LLM_MODEL",g(e,"DEEPSEEK_MODEL")||"deepseek-v4-flash");break;case"nvidia":_(e,"TOOLNET_LLM_API_KEY",g(e,"NVIDIA_API_KEY","NVIDIA_NIM_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",g(e,"NVIDIA_BASE_URL","NVIDIA_NIM_BASE_URL")||"https://integrate.api.nvidia.com/v1"),_(e,"TOOLNET_LLM_MODEL",g(e,"NVIDIA_MODEL","NVIDIA_NIM_MODEL"));break;case"openrouter":_(e,"TOOLNET_LLM_API_KEY",g(e,"OPENROUTER_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",g(e,"OPENROUTER_BASE_URL")||"https://openrouter.ai/api/v1"),_(e,"TOOLNET_LLM_MODEL",g(e,"OPENROUTER_MODEL"));break;case"alibaba":_(e,"TOOLNET_LLM_API_KEY",g(e,"ALIBABA_API_KEY","DASHSCOPE_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",g(e,"ALIBABA_BASE_URL","DASHSCOPE_BASE_URL")),_(e,"TOOLNET_LLM_MODEL",g(e,"ALIBABA_MODEL","DASHSCOPE_MODEL"));break;case"gemini":_(e,"TOOLNET_LLM_API_KEY",g(e,"GEMINI_API_KEY","GOOGLE_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",g(e,"GEMINI_BASE_URL")||"https://generativelanguage.googleapis.com/v1beta"),_(e,"TOOLNET_LLM_MODEL",g(e,"GEMINI_MODEL"));break;case"huggingface":_(e,"TOOLNET_LLM_API_KEY",g(e,"HF_TOKEN")),_(e,"TOOLNET_LLM_BASE_URL",g(e,"HF_INFERENCE_BASE_URL")||"https://router.huggingface.co/v1"),_(e,"TOOLNET_LLM_MODEL",g(e,"HF_LLM_MODEL","HF_MODEL"));break;case"ollama":_(e,"TOOLNET_LLM_API_KEY",g(e,"OLLAMA_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",g(e,"OLLAMA_BASE_URL")||"http://127.0.0.1:11434/v1"),_(e,"TOOLNET_LLM_MODEL",g(e,"OLLAMA_MODEL"));break;case"cloudflare":_(e,"TOOLNET_LLM_API_KEY",g(e,"CLOUDFLARE_API_TOKEN")),_(e,"TOOLNET_LLM_ACCOUNT_ID",g(e,"CLOUDFLARE_ACCOUNT_ID")),_(e,"TOOLNET_LLM_MODEL",g(e,"CLOUDFLARE_MODEL"));break;case"openai-compatible":_(e,"TOOLNET_LLM_API_KEY",g(e,"OPENAI_API_KEY","MODEL_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",g(e,"OPENAI_BASE_URL","MODEL_BASE_URL")),_(e,"TOOLNET_LLM_MODEL",g(e,"OPENAI_MODEL","MODEL_NAME"));break}!e.get("TOOLNET_EMBEDDING_PROVIDER")?.trim()&&g(e,"HF_TOKEN")&&(e.set("TOOLNET_EMBEDDING_PROVIDER","huggingface"),_(e,"TOOLNET_EMBEDDING_API_KEY",g(e,"HF_TOKEN")),_(e,"TOOLNET_EMBEDDING_MODEL",g(e,"HF_EMBEDDING_MODEL")||"sentence-transformers/all-MiniLM-L6-v2"));let r=JSON.stringify([...e.entries()]);return o=t!==r,o}function k(e,o="not configured"){return e?.trim()||o}function vo(e){let o=P(N(e)),t=e.get("TOOLNET_LLM_PROVIDER"),n=e.get("TOOLNET_LLM_MODEL"),r=e.get("TOOLNET_EMBEDDING_PROVIDER"),i=e.get("TOOLNET_EMBEDDING_MODEL"),s=e.get("TOOLNET_LLM_FALLBACK_1_PROVIDER"),l=e.get("TOOLNET_LLM_FALLBACK_2_PROVIDER");console.log(""),console.log("TOOLNET MEMORY READY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(`Storage : ${o}`),console.log(`LLM : ${t?`${M(t)} / ${k(n)}`:"not configured"}`),console.log(`Fallback 1 : ${s?`${M(s)} / ${k(e.get("TOOLNET_LLM_FALLBACK_1_MODEL"))}`:"none"}`),console.log(`Fallback 2 : ${l?`${M(l)} / ${k(e.get("TOOLNET_LLM_FALLBACK_2_MODEL"))}`:"none"}`),console.log(`Embedding : ${r?`${r==="local"?"Local / Hash":ne(r)} / ${k(i,r==="local"?"local hash":"not configured")}`:"legacy/default"}`),console.log(""),console.log(`Config : ${u}`),console.log(`Permissions: ${p.statSync(u).mode.toString(8).slice(-3)}`),console.log(""),console.log("Secrets : hidden"),console.log("Config mode: canonical TOOLNET_*"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}function Pe(e){Wo(e),e.has("TOOLNET_LLM_FALLBACK_COOLDOWN_MS")||e.set("TOOLNET_LLM_FALLBACK_COOLDOWN_MS","60000"),e.has("TOOLNET_LLM_MAX_RETRIES")||e.set("TOOLNET_LLM_MAX_RETRIES","1"),e.has("MEMORY_STORAGE_PROVIDER")||e.set("MEMORY_STORAGE_PROVIDER",N(e)),e.has("MEMORY_LOCAL_CACHE_MB")||e.set("MEMORY_LOCAL_CACHE_MB","200"),e.has("MEMORY_AUTO_CAPTURE")||e.set("MEMORY_AUTO_CAPTURE","true"),e.has("MEMORY_AUTO_RETRIEVE")||e.set("MEMORY_AUTO_RETRIEVE","true"),e.has("MEMORY_AUTO_SUMMARIZE")||e.set("MEMORY_AUTO_SUMMARIZE","true"),e.has("MEMORY_AUTO_SYNC")||e.set("MEMORY_AUTO_SYNC","true"),e.has("MEMORY_MAX_CANDIDATES")||e.set("MEMORY_MAX_CANDIDATES","50"),e.has("MEMORY_RERANK_TOP")||e.set("MEMORY_RERANK_TOP","10"),e.has("MEMORY_FINAL_CONTEXT")||e.set("MEMORY_FINAL_CONTEXT","5"),e.has("MEMORY_TOKEN_BUDGET")||e.set("MEMORY_TOKEN_BUDGET","2000"),e.has("TOOLNET_SESSION_LEARNING")||e.set("TOOLNET_SESSION_LEARNING","1"),e.has("TOOLNET_WORK_CONTINUITY")||e.set("TOOLNET_WORK_CONTINUITY","1"),e.has("TOOLNET_SEMANTIC_CONTINUITY")||e.set("TOOLNET_SEMANTIC_CONTINUITY","1"),e.has("TOOLNET_SMART_HANDOFF")||e.set("TOOLNET_SMART_HANDOFF","1")}async function Jo(e,o){Pe(e),o||f(e),console.log("TOOLNET MEMORY SETUP"),console.log(""),console.log("Interactive terminal not detected."),console.log(`Config: ${u}`),console.log(`Storage: ${P(N(e))}`),console.log(""),console.log("Run from an interactive terminal to configure providers:"),console.log(" toolnet-memory setup")}async function Xo(){let e=p.existsSync(u),o=e?Lo(p.readFileSync(u,"utf8")):new Map,t=new Map(o);if(Pe(t),!A.isTTY||!D.isTTY){await Jo(t,e);return}let n=Eo.createInterface({input:A,output:D}),r=!1;try{for(;;){Io(),No(t);let i=await So(n);if(i==="storage"){let s=JSON.stringify([...t.entries()]);await Po(n,t),r=r||s!==JSON.stringify([...t.entries()]);continue}if(i==="ai"){let s=JSON.stringify([...t.entries()]);await qo(n,t),r=r||s!==JSON.stringify([...t.entries()]);continue}if(i==="exit"){if(!r){console.log(""),console.log("No changes made.");return}console.log("");let s=(await n.question("Discard unsaved changes? (y/N): ")).trim().toLowerCase();if(s==="y"||s==="yes"){console.log(""),console.log("Changes discarded.");return}continue}f(t),Ce(t)||(console.log(""),console.log("\u26A0 Storage configuration is incomplete.")),jo(),vo(t),console.log(""),console.log("Validate:"),console.log(" toolnet-memory provider:status"),console.log(" toolnet-memory provider:test"),console.log(" toolnet-memory doctor"),console.log("");return}}finally{n.close()}}Xo().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|
|
709
|
+
`}function m(e){A.mkdirSync(te,{recursive:!0,mode:448});let o=`${L}.tmp-${process.pid}`;A.writeFileSync(o,zo(e),{encoding:"utf8",mode:384}),A.renameSync(o,L),A.chmodSync(te,448),A.chmodSync(L,384)}function p(e,o,t,n){let r=t.trim();if(r){e.set(o,r);return}!e.get(o)&&n!==void 0&&e.set(o,n)}async function y(e,o){return T.isTTY?(e.pause(),b.write(o),new Promise(t=>{let n="",r=!1,i=()=>{r||(r=!0,T.off("data",s),T.setRawMode?.(!1),T.pause(),b.write(`
|
|
710
|
+
`),e.resume(),t(n))},s=a=>{for(let l of a.toString("utf8")){if(l==="\r"||l===`
|
|
711
|
+
`){i();return}if(l===""&&(T.off("data",s),T.setRawMode?.(!1),b.write(`
|
|
712
|
+
`),process.exit(130)),l==="\x7F"){n=n.slice(0,-1);continue}n+=l}};T.resume(),T.setRawMode?.(!0),T.on("data",s)})):""}function C(e){return e.trim().replace(/\/+$/,"")}function He(e){return`https://${e}.r2.cloudflarestorage.com`}async function ie(e){let o=new AbortController,t=setTimeout(()=>o.abort(),15e3);t.unref?.();let n=new Jo({region:e.region,endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}});try{return await n.send(new Vo({Bucket:e.bucket}),{abortSignal:o.signal}),{ok:!0,message:`Bucket "${e.bucket}" reachable`}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}finally{clearTimeout(t),n.destroy()}}async function Qo(e){let o=e.get("R2_ACCOUNT_ID")?.trim()??"",t=e.get("R2_BUCKET")?.trim()??"",n=e.get("R2_ACCESS_KEY_ID")?.trim()??"",r=e.get("R2_SECRET_ACCESS_KEY")?.trim()??"";return!o||!t||!n||!r?{ok:!1,message:"R2 configuration is incomplete"}:ie({endpoint:He(o),region:"auto",bucket:t,accessKeyId:n,secretAccessKey:r})}async function Zo(e){let o=C(e.get("S3_ENDPOINT")??""),t=e.get("S3_REGION")?.trim()||"us-east-1",n=e.get("S3_BUCKET")?.trim()??"",r=e.get("S3_ACCESS_KEY_ID")?.trim()??"",i=e.get("S3_SECRET_ACCESS_KEY")?.trim()??"";return!n||!r||!i?{ok:!1,message:"S3 configuration is incomplete"}:ie({endpoint:o||void 0,region:t,bucket:n,accessKeyId:r,secretAccessKey:i,forcePathStyle:e.get("S3_FORCE_PATH_STYLE")==="true"})}async function et(e){let o=C(e.get("HF_URL")??""),t=e.get("HF_BUCKET")?.trim()??"",n=e.get("HF_S3_ACCESS_KEY_ID")?.trim()??"",r=e.get("HF_S3_SECRET_ACCESS_KEY")?.trim()??"";return o?!t||!n||!r?{ok:!1,message:"Hugging Face S3 configuration is incomplete"}:ie({endpoint:o,region:"us-east-1",bucket:t,accessKeyId:n,secretAccessKey:r,forcePathStyle:!0}):{ok:!1,message:"HF_URL / S3 endpoint is required for connection test"}}async function ot(e){let o=e.get("MEMORY_LOCAL_STORAGE_PATH")?.trim()||P.join(ne.homedir(),".local","share","toolnet-memory"),t=P.join(o,`.toolnet-test-${process.pid}-${Date.now()}`);try{return A.mkdirSync(o,{recursive:!0,mode:448}),A.writeFileSync(t,`toolnet-memory
|
|
713
|
+
`,{encoding:"utf8",mode:384}),A.unlinkSync(t),{ok:!0,message:`Writable: ${o}`}}catch(n){return{ok:!1,message:n instanceof Error?n.message:String(n)}}}async function tt(e,o){switch(e){case"r2":return Qo(o);case"s3":return Zo(o);case"huggingface":return et(o);case"local":return ot(o)}}async function nt(e,o){console.log(""),console.log(`Testing ${K(e)}...`);let t=await tt(e,o);return t.ok?console.log(`\u2713 ${t.message}`):(console.log("\u2717 Connection test failed"),console.log(` ${t.message}`)),console.log(""),t}function rt(){console.log(""),console.log("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log("\u2551 TOOLNET MEMORY SETUP \u2551"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log("")}function it(e){let o=N(e);console.log("Current configuration"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(`Storage : ${K(o)} ${Ge(e)?"\u2713":"\u26A0 incomplete"}`);let t=e.get("TOOLNET_LLM_PROVIDER"),n=e.get("TOOLNET_LLM_MODEL"),r=e.get("TOOLNET_EMBEDDING_PROVIDER");console.log(`LLM : ${t?`${M(t)}${n?` / ${n}`:""}`:"not configured"}`),console.log(`Embedding: ${r||"legacy/default"}`),console.log("")}async function st(e){console.log("Setup"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" 1. Storage"),console.log(" 2. AI Model"),console.log(" 3. Finish & Save"),console.log(" 0. Exit without saving"),console.log("");let o=(await e.question("Choose [1-3]: ")).trim();return o==="1"?"storage":o==="2"?"ai":o==="0"?"exit":"finish"}async function ct(e,o){console.log(""),console.log("Storage"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` 1. Cloudflare R2${o==="r2"?" \u2713 current":""}`),console.log(` 2. S3 / S3-compatible${o==="s3"?" \u2713 current":""}`),console.log(` 3. Hugging Face S3${o==="huggingface"?" \u2713 current":""}`),console.log(` 4. Local${o==="local"?" \u2713 current":""}`),console.log(""),console.log(" 0. Back"),console.log("");let t=(await e.question("Choose storage: ")).trim();return t==="0"?"back":t==="2"?"s3":t==="3"?"huggingface":t==="4"?"local":"r2"}async function at(e,o){console.log(""),console.log("Cloudflare R2"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=await e.question(o.get("R2_ACCOUNT_ID")?`ACCOUNT ID [${o.get("R2_ACCOUNT_ID")}]: `:"ACCOUNT ID: "),n=await e.question(o.get("R2_ACCESS_KEY_ID")?`ACCESS KEY ID [${re(o.get("R2_ACCESS_KEY_ID"))}]: `:"ACCESS KEY ID: "),r=await e.question(`BUCKET [${o.get("R2_BUCKET")||"toolnet-memory"}]: `);p(o,"R2_ACCOUNT_ID",t),p(o,"R2_ACCESS_KEY_ID",n),p(o,"R2_BUCKET",r,"toolnet-memory");let i=o.get("R2_ACCOUNT_ID")?.trim();i&&console.log(`URL: ${He(i)}`);let s=await y(e,o.get("R2_SECRET_ACCESS_KEY")?"SECRET ACCESS KEY [configured, Enter = keep]: ":"SECRET ACCESS KEY: ");s.trim()&&o.set("R2_SECRET_ACCESS_KEY",s.trim())}async function lt(e,o){console.log(""),console.log("S3 / S3-compatible"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=await e.question(o.get("S3_ENDPOINT")?`URL / ENDPOINT [${o.get("S3_ENDPOINT")}]: `:"URL / ENDPOINT [blank = AWS S3]: "),n=await e.question(`REGION [${o.get("S3_REGION")||"us-east-1"}]: `),r=await e.question(o.get("S3_ACCESS_KEY_ID")?`ACCESS KEY ID [${re(o.get("S3_ACCESS_KEY_ID"))}]: `:"ACCESS KEY ID: "),i=await e.question(`BUCKET [${o.get("S3_BUCKET")||"toolnet-memory"}]: `),s=o.get("S3_FORCE_PATH_STYLE")==="true",a=await e.question(`FORCE PATH STYLE [${s?"Y":"N"}] (y/n): `);if(t.trim()&&o.set("S3_ENDPOINT",C(t)),p(o,"S3_REGION",n,"us-east-1"),p(o,"S3_ACCESS_KEY_ID",r),p(o,"S3_BUCKET",i,"toolnet-memory"),a.trim()){let g=a.trim().toLowerCase();o.set("S3_FORCE_PATH_STYLE",g==="y"||g==="yes"?"true":"false")}else o.has("S3_FORCE_PATH_STYLE")||o.set("S3_FORCE_PATH_STYLE","false");let l=await y(e,o.get("S3_SECRET_ACCESS_KEY")?"SECRET ACCESS KEY [configured, Enter = keep]: ":"SECRET ACCESS KEY: ");l.trim()&&o.set("S3_SECRET_ACCESS_KEY",l.trim())}async function gt(e,o){console.log(""),console.log("Hugging Face S3"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=await e.question(o.get("HF_NAMESPACE")?`NAMESPACE [${o.get("HF_NAMESPACE")}]: `:"NAMESPACE [optional]: "),n=await e.question(o.get("HF_S3_ACCESS_KEY_ID")?`ACCESS KEY ID [${re(o.get("HF_S3_ACCESS_KEY_ID"))}]: `:"ACCESS KEY ID: "),r=await e.question(`BUCKET [${o.get("HF_BUCKET")||"toolnet-memory"}]: `),i=await e.question(o.get("HF_URL")?`URL [${o.get("HF_URL")}]: `:"URL / S3 ENDPOINT: ");p(o,"HF_NAMESPACE",t),p(o,"HF_S3_ACCESS_KEY_ID",n),p(o,"HF_BUCKET",r,"toolnet-memory"),i.trim()&&o.set("HF_URL",C(i));let s=await y(e,o.get("HF_S3_SECRET_ACCESS_KEY")?"SECRET ACCESS KEY [configured, Enter = keep]: ":"SECRET ACCESS KEY: ");s.trim()&&o.set("HF_S3_SECRET_ACCESS_KEY",s.trim())}async function dt(e,o){console.log(""),console.log("Local Storage"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=o.get("MEMORY_LOCAL_STORAGE_PATH")??P.join(ne.homedir(),".local","share","toolnet-memory"),n=await e.question(`LOCAL PATH [${t}]: `);p(o,"MEMORY_LOCAL_STORAGE_PATH",n,t)}async function Et(e,o){let t=new Map(o);for(;;){let n=await ct(e,N(o));if(n==="back")return;let r=new Map(o);o.set("MEMORY_STORAGE_PROVIDER",n),n==="r2"?await at(e,o):n==="s3"?await lt(e,o):n==="huggingface"?await gt(e,o):await dt(e,o);let i=xe(n).filter(l=>!o.get(l)?.trim());if(i.length){console.log(""),console.log("\u26A0 Missing required fields:");for(let g of i)console.log(` - ${g}`);console.log(""),console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let l=(await e.question("Choose [1]: ")).trim()||"1";if(l==="2"){m(o),console.log(""),console.log("\u26A0 Saved with incomplete configuration"),console.log("");return}if(l==="3"){o.clear();for(let[g,E]of r)o.set(g,E);continue}if(l==="4"){o.clear();for(let[g,E]of t)o.set(g,E);console.log(""),console.log("Storage changes cancelled."),console.log("");return}continue}if((await nt(n,o)).ok){m(o),console.log(`\u2713 ${K(n)} configuration saved`),console.log(` ${L}`),console.log("");return}console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let a=(await e.question("Choose [1]: ")).trim()||"1";if(a==="2"){m(o),console.log(""),console.log("\u26A0 Saved even though connection test failed"),console.log("");return}if(a==="3"){o.clear();for(let[l,g]of r)o.set(l,g);continue}if(a==="4"){o.clear();for(let[l,g]of t)o.set(l,g);console.log(""),console.log("Storage changes cancelled."),console.log("");return}}}var I=[{id:"openai-compatible",label:"OpenAI-compatible",apiKeyRequired:!0,baseUrlRequired:!0},{id:"alibaba",label:"Alibaba / DashScope",baseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",suggestedModel:"qwen3.6-flash",apiKeyRequired:!0},{id:"openrouter",label:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyRequired:!0},{id:"groq",label:"Groq",baseUrl:"https://api.groq.com/openai/v1",apiKeyRequired:!0},{id:"deepseek",label:"DeepSeek",baseUrl:"https://api.deepseek.com",suggestedModel:"deepseek-v4-flash",apiKeyRequired:!0},{id:"nvidia",label:"NVIDIA NIM",baseUrl:"https://integrate.api.nvidia.com/v1",suggestedModel:"deepseek-ai/deepseek-v4-pro",apiKeyRequired:!0},{id:"gemini",label:"Gemini",baseUrl:"https://generativelanguage.googleapis.com/v1beta",suggestedModel:"gemini-3.6-flash",apiKeyRequired:!0},{id:"huggingface",label:"Hugging Face",baseUrl:"https://router.huggingface.co/v1",apiKeyRequired:!0},{id:"ollama",label:"Ollama / Local",baseUrl:"http://127.0.0.1:11434/v1",apiKeyRequired:!1},{id:"custom",label:"Custom endpoint",apiKeyRequired:!1,baseUrlRequired:!0},{id:"cloudflare",label:"Cloudflare Workers AI",suggestedModel:"@cf/meta/llama-3.1-8b-instruct",apiKeyRequired:!0,accountIdRequired:!0}];function _t(e){return I.find(o=>o.id===e)}function M(e){return _t(e)?.label??e??"not configured"}function qe(e){let o=e.get("TOOLNET_LLM_PROVIDER")?.trim();return I.some(t=>t.id===o)?o:void 0}async function se(e,o){console.log(""),console.log("AI Model"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),I.forEach((r,i)=>{console.log(` ${i+1}. ${r.label}${o===r.id?" \u2713 current":""}`)}),console.log(""),console.log(" 0. Back"),console.log("");let t=(await e.question("Choose provider: ")).trim();if(t==="0")return"back";let n=Number(t)-1;return Number.isInteger(n)&&n>=0&&n<I.length?I[n].id:(console.log(""),console.log("\u26A0 Invalid provider selection"),se(e,o))}function Ot(e,o){return!(!e.get("TOOLNET_LLM_MODEL")?.trim()||o.apiKeyRequired&&!e.get("TOOLNET_LLM_API_KEY")?.trim()||o.accountIdRequired&&!e.get("TOOLNET_LLM_ACCOUNT_ID")?.trim()||o.baseUrlRequired&&!e.get("TOOLNET_LLM_BASE_URL")?.trim())}function ft(e){e.delete("TOOLNET_LLM_API_KEY"),e.delete("TOOLNET_LLM_BASE_URL"),e.delete("TOOLNET_LLM_MODEL"),e.delete("TOOLNET_LLM_ACCOUNT_ID")}async function mt(e,o,t){console.log(""),console.log(t.label),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let n=o.get("TOOLNET_LLM_PROVIDER");if(n&&n!==t.id&&ft(o),o.set("TOOLNET_LLM_PROVIDER",t.id),t.accountIdRequired){let l=o.get("TOOLNET_LLM_ACCOUNT_ID"),g=await e.question(l?`ACCOUNT ID [${l}]: `:"ACCOUNT ID: ");p(o,"TOOLNET_LLM_ACCOUNT_ID",g)}else o.delete("TOOLNET_LLM_ACCOUNT_ID");if(t.apiKeyRequired||t.id==="custom"){let l=o.get("TOOLNET_LLM_API_KEY"),g=await y(e,l?"API KEY [configured, Enter = keep]: ":t.apiKeyRequired?"API KEY: ":"API KEY [optional]: ");g.trim()&&o.set("TOOLNET_LLM_API_KEY",g.trim())}else o.delete("TOOLNET_LLM_API_KEY");if(t.id!=="cloudflare"){let g=o.get("TOOLNET_LLM_BASE_URL")||t.baseUrl||"",u=(await e.question(g?`BASE URL [${g}]: `:t.baseUrlRequired?"BASE URL: ":"BASE URL [optional]: ")).trim()||g;u?o.set("TOOLNET_LLM_BASE_URL",C(u)):o.delete("TOOLNET_LLM_BASE_URL")}else o.delete("TOOLNET_LLM_BASE_URL");let i=o.get("TOOLNET_LLM_MODEL")||t.suggestedModel||"",a=(await e.question(i?`MODEL [${i}]: `:"MODEL: ")).trim()||i;a&&o.set("TOOLNET_LLM_MODEL",a)}function ut(e){let o=qe(e);if(!o)throw new Error("AI provider is not configured");return{id:o,apiKey:e.get("TOOLNET_LLM_API_KEY")?.trim()||void 0,baseUrl:e.get("TOOLNET_LLM_BASE_URL")?.trim()||void 0,model:e.get("TOOLNET_LLM_MODEL")?.trim()||void 0,accountId:e.get("TOOLNET_LLM_ACCOUNT_ID")?.trim()||void 0}}async function Lt(e){let o=ut(e);console.log(""),console.log(`Testing ${M(o.id)}...`);try{let n=await _e(o).healthCheck();return n.ok?(console.log(`\u2713 Provider reachable${n.latencyMs?` (${n.latencyMs} ms)`:""}`),console.log(`\u2713 Model: ${n.model??o.model??"configured"}`),console.log(""),{ok:!0,message:n.message}):(console.log("\u2717 AI provider test failed"),console.log(` ${n.message}`),console.log(""),{ok:!1,message:n.message})}catch(t){let n=t instanceof Error?t.message:String(t);return console.log("\u2717 AI provider test failed"),console.log(` ${n}`),console.log(""),{ok:!1,message:n}}}var H=[{id:"local",label:"Local / Hash",apiKeyRequired:!1},{id:"huggingface",label:"Hugging Face",suggestedModel:"sentence-transformers/all-MiniLM-L6-v2",apiKeyRequired:!0},{id:"openai-compatible",label:"OpenAI-compatible",apiKeyRequired:!0,baseUrlRequired:!0},{id:"alibaba",label:"Alibaba / DashScope",baseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",suggestedModel:"text-embedding-v4",apiKeyRequired:!0},{id:"openrouter",label:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyRequired:!0},{id:"nvidia",label:"NVIDIA NIM",baseUrl:"https://integrate.api.nvidia.com/v1",apiKeyRequired:!0},{id:"ollama",label:"Ollama / Local",baseUrl:"http://127.0.0.1:11434/v1",apiKeyRequired:!1},{id:"gemini",label:"Gemini",baseUrl:"https://generativelanguage.googleapis.com/v1beta",suggestedModel:"gemini-embedding-001",apiKeyRequired:!0},{id:"cloudflare",label:"Cloudflare Workers AI",suggestedModel:"@cf/baai/bge-base-en-v1.5",apiKeyRequired:!0,accountIdRequired:!0},{id:"custom",label:"Custom OpenAI-compatible endpoint",apiKeyRequired:!1,baseUrlRequired:!0}];function ce(e){return H.find(o=>o.id===e)?.label??e??"not configured"}async function je(e,o){console.log(""),console.log("Embedding Model"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),H.forEach((r,i)=>{console.log(` ${i+1}. ${r.label}${o===r.id?" \u2713 current":""}`)}),console.log(""),console.log(" 0. Back"),console.log("");let t=(await e.question("Choose embedding provider: ")).trim();if(t==="0")return"back";let n=Number(t)-1;return Number.isInteger(n)&&n>=0&&n<H.length?H[n]:(console.log(""),console.log("\u26A0 Invalid selection"),je(e,o))}function Ye(e){e.delete("TOOLNET_EMBEDDING_API_KEY"),e.delete("TOOLNET_EMBEDDING_BASE_URL"),e.delete("TOOLNET_EMBEDDING_MODEL"),e.delete("TOOLNET_EMBEDDING_ACCOUNT_ID")}async function pt(e,o,t){let n=o.get("TOOLNET_EMBEDDING_PROVIDER");if(n&&n!==t.id&&Ye(o),o.set("TOOLNET_EMBEDDING_PROVIDER",t.id),console.log(""),console.log(t.label),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),t.id==="local"){Ye(o),console.log("\u2713 Local embedding selected"),console.log(" No API key required.");return}if(t.accountIdRequired){let l=o.get("TOOLNET_EMBEDDING_ACCOUNT_ID"),g=await e.question(l?`ACCOUNT ID [${l}]: `:"ACCOUNT ID: ");p(o,"TOOLNET_EMBEDDING_ACCOUNT_ID",g)}else o.delete("TOOLNET_EMBEDDING_ACCOUNT_ID");if(t.apiKeyRequired||t.id==="custom"){let l=o.get("TOOLNET_EMBEDDING_API_KEY"),g=await y(e,l?"API KEY [configured, Enter = keep]: ":t.apiKeyRequired?"API KEY: ":"API KEY [optional]: ");g.trim()&&o.set("TOOLNET_EMBEDDING_API_KEY",g.trim())}else o.delete("TOOLNET_EMBEDDING_API_KEY");if(t.id==="cloudflare"){let l=o.get("TOOLNET_EMBEDDING_ACCOUNT_ID")?.trim();if(l){let g=`https://api.cloudflare.com/client/v4/accounts/${l}/ai/v1`;o.set("TOOLNET_EMBEDDING_BASE_URL",g),console.log(`BASE URL: ${g}`)}}else{let g=o.get("TOOLNET_EMBEDDING_BASE_URL")||t.baseUrl||"",u=(await e.question(g?`BASE URL [${g}]: `:t.baseUrlRequired?"BASE URL: ":"BASE URL [optional]: ")).trim()||g;u&&o.set("TOOLNET_EMBEDDING_BASE_URL",C(u))}let i=o.get("TOOLNET_EMBEDDING_MODEL")||t.suggestedModel||"",a=(await e.question(i?`MODEL [${i}]: `:"MODEL: ")).trim()||i;a&&o.set("TOOLNET_EMBEDDING_MODEL",a)}function Tt(e,o){return o.id==="local"?!0:o.apiKeyRequired&&!e.get("TOOLNET_EMBEDDING_API_KEY")?.trim()||o.accountIdRequired&&!e.get("TOOLNET_EMBEDDING_ACCOUNT_ID")?.trim()||o.baseUrlRequired&&!e.get("TOOLNET_EMBEDDING_BASE_URL")?.trim()?!1:!!e.get("TOOLNET_EMBEDDING_MODEL")?.trim()}async function ve(e){let o=e.get("TOOLNET_EMBEDDING_PROVIDER")?.trim();if(console.log(""),console.log(`Testing embedding: ${ce(o)}...`),o==="local")return console.log("\u2713 Local embedding ready"),console.log(""),!0;let t=e.get("TOOLNET_EMBEDDING_API_KEY")?.trim(),n=e.get("TOOLNET_EMBEDDING_MODEL")?.trim(),r=e.get("TOOLNET_EMBEDDING_BASE_URL")?.trim();try{if(!n)throw new Error("Embedding model is missing");if(o==="huggingface"){if(!t)throw new Error("API key is missing");let i=await fetch(`https://router.huggingface.co/hf-inference/models/${n}/pipeline/feature-extraction`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({inputs:["toolnet memory test"]})});if(!i.ok)throw new Error(`HTTP ${i.status}: ${await i.text()}`)}else if(o==="gemini"){if(!t)throw new Error("API key is missing");let i=n.replace(/^models\//,"");r=r||"https://generativelanguage.googleapis.com/v1beta";let s=await fetch(`${r.replace(/\/+$/,"")}/models/${encodeURIComponent(i)}:embedContent?key=${encodeURIComponent(t)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:`models/${i}`,content:{parts:[{text:"toolnet memory test"}]}})});if(!s.ok)throw new Error(`HTTP ${s.status}: ${await s.text()}`)}else{if(!r)throw new Error("BASE URL is missing");let i=await fetch(`${r.replace(/\/+$/,"")}/embeddings`,{method:"POST",headers:{"content-type":"application/json",...t?{authorization:`Bearer ${t}`}:{}},body:JSON.stringify({model:n,input:["toolnet memory test"]})});if(!i.ok)throw new Error(`HTTP ${i.status}: ${await i.text()}`);let s=await i.json();if(!Array.isArray(s.data)||!Array.isArray(s.data[0]?.embedding))throw new Error("Invalid embedding response")}return console.log("\u2713 Embedding provider reachable"),console.log(`\u2713 Model: ${n}`),console.log(""),!0}catch(i){return console.log("\u2717 Embedding test failed"),console.log(` ${i instanceof Error?i.message:String(i)}`),console.log(""),!1}}async function At(e,o){let t=new Map(o);for(;;){let n=await je(e,o.get("TOOLNET_EMBEDDING_PROVIDER"));if(n==="back")return;if(await pt(e,o,n),!Tt(o,n)){console.log(""),console.log("\u26A0 Embedding configuration is incomplete."),console.log(""),console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let s=(await e.question("Choose [1]: ")).trim()||"1";if(s==="2"){m(o);return}if(s==="3")continue;if(s==="4"){o.clear();for(let[a,l]of t)o.set(a,l);return}continue}if(await ve(o)){m(o),console.log(`\u2713 ${n.label} embedding configuration saved`),console.log(` ${L}`),console.log("");return}console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let i=(await e.question("Choose [1]: ")).trim()||"1";if(i==="2"){m(o);return}if(i!=="3"&&i==="4"){o.clear();for(let[s,a]of t)o.set(s,a);return}}}async function Mt(e,o){let t=o.get("TOOLNET_LLM_PROVIDER")?.trim();if(!t){console.log(""),console.log("\u26A0 Configure LLM first."),console.log("");return}if(t==="deepseek"||t==="groq"){console.log(""),console.log(`\u26A0 ${M(t)} is configured as LLM-only.`),console.log("Choose Embedding separately."),console.log("");return}o.set("TOOLNET_EMBEDDING_PROVIDER",t);let n=o.get("TOOLNET_LLM_API_KEY"),r=o.get("TOOLNET_LLM_BASE_URL"),i=o.get("TOOLNET_LLM_ACCOUNT_ID");n&&o.set("TOOLNET_EMBEDDING_API_KEY",n),r&&o.set("TOOLNET_EMBEDDING_BASE_URL",r),i&&o.set("TOOLNET_EMBEDDING_ACCOUNT_ID",i);let s="";t==="alibaba"?s="text-embedding-v4":t==="gemini"?s="gemini-embedding-001":t==="cloudflare"?s="@cf/baai/bge-base-en-v1.5":t==="huggingface"&&(s="sentence-transformers/all-MiniLM-L6-v2");let l=(await e.question(s?`EMBEDDING MODEL [${s}]: `:"EMBEDDING MODEL: ")).trim()||s;if(!l){console.log(""),console.log("\u26A0 Embedding model is required."),console.log("");return}if(o.set("TOOLNET_EMBEDDING_MODEL",l),!await ve(o)){let E=(await e.question("Save anyway? (y/N): ")).trim().toLowerCase();if(E!=="y"&&E!=="yes")return}m(o),console.log(""),console.log("\u2713 LLM credentials reused for Embedding"),console.log(`\u2713 Embedding model: ${l}`),console.log("")}function q(e){return`TOOLNET_LLM_FALLBACK_${e}`}function j(e,o){let t=q(o);for(let n of["PROVIDER","API_KEY","BASE_URL","MODEL","ACCOUNT_ID"])e.delete(`${t}_${n}`)}function $e(e,o){let t=q(o),n=e.get(`${t}_PROVIDER`);if(!n)return"not configured";let r=e.get(`${t}_MODEL`);return`${M(n)}${r?` / ${r}`:""}`}async function Fe(e,o,t){console.log(""),console.log(`Fallback ${t}`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let n=await se(e,void 0);if(n==="back")return;let r=o.get("TOOLNET_LLM_PROVIDER");if(n===r){console.log(""),console.log("\u26A0 Fallback cannot be the same provider as Primary."),console.log("");return}let i=t===1?2:1,s=o.get(`${q(i)}_PROVIDER`);if(n===s){console.log(""),console.log("\u26A0 This provider is already used by the other fallback."),console.log("");return}let a=I.find(O=>O.id===n);if(!a)return;let l=q(t);if(j(o,t),o.set(`${l}_PROVIDER`,n),a.accountIdRequired){let O=await e.question("ACCOUNT ID: ");O.trim()&&o.set(`${l}_ACCOUNT_ID`,O.trim())}if(a.apiKeyRequired||n==="custom"){let O=await y(e,a.apiKeyRequired?"API KEY: ":"API KEY [optional]: ");O.trim()&&o.set(`${l}_API_KEY`,O.trim())}if(n==="cloudflare"){let O=o.get(`${l}_ACCOUNT_ID`);O&&o.set(`${l}_BASE_URL`,`https://api.cloudflare.com/client/v4/accounts/${O}/ai`)}else{let O=a.baseUrl??"",ae=(await e.question(O?`BASE URL [${O}]: `:a.baseUrlRequired?"BASE URL: ":"BASE URL [optional]: ")).trim()||O;ae&&o.set(`${l}_BASE_URL`,C(ae))}let g=a.suggestedModel??"",u=(await e.question(g?`MODEL [${g}]: `:"MODEL: ")).trim()||g;if(!u){console.log(""),console.log("\u26A0 MODEL is required."),console.log(""),j(o,t);return}o.set(`${l}_MODEL`,u),m(o),console.log(""),console.log(`\u2713 Fallback ${t} saved`),console.log(` ${M(n)} / ${u}`),console.log("")}async function It(e,o){let t=o.get("TOOLNET_LLM_FALLBACK_COOLDOWN_MS")||"60000",n=o.get("TOOLNET_LLM_MAX_RETRIES")||"1";console.log(""),console.log("Fallback Policy"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let r=await e.question(`COOLDOWN MS [${t}]: `);if(r.trim()){let s=Number(r.trim());Number.isFinite(s)&&s>=0?o.set("TOOLNET_LLM_FALLBACK_COOLDOWN_MS",String(Math.floor(s))):console.log("\u26A0 Invalid cooldown; keeping previous value.")}let i=await e.question(`MAX RETRIES [${n}]: `);if(i.trim()){let s=Number(i.trim());Number.isFinite(s)&&s>=0&&s<=5?o.set("TOOLNET_LLM_MAX_RETRIES",String(Math.floor(s))):console.log("\u26A0 MAX RETRIES must be between 0 and 5.")}m(o),console.log(""),console.log("\u2713 Fallback policy saved"),console.log("")}async function Nt(e,o){for(;;){console.log(""),console.log("LLM Fallback"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Primary : ${o.get("TOOLNET_LLM_PROVIDER")?`${M(o.get("TOOLNET_LLM_PROVIDER"))} / ${o.get("TOOLNET_LLM_MODEL")||"model not configured"}`:"not configured"}`),console.log(` Fallback 1 : ${$e(o,1)}`),console.log(` Fallback 2 : ${$e(o,2)}`),console.log(` Cooldown : ${o.get("TOOLNET_LLM_FALLBACK_COOLDOWN_MS")||"60000"} ms`),console.log(` Retries : ${o.get("TOOLNET_LLM_MAX_RETRIES")||"1"}`),console.log(""),console.log(" 1. Configure Fallback 1"),console.log(" 2. Configure Fallback 2"),console.log(" 3. Remove Fallback 1"),console.log(" 4. Remove Fallback 2"),console.log(" 5. Retry / cooldown settings"),console.log(" 0. Back"),console.log("");let t=(await e.question("Choose: ")).trim();if(t==="0")return;if(t==="1"){await Fe(e,o,1);continue}if(t==="2"){await Fe(e,o,2);continue}if(t==="3"){j(o,1),m(o),console.log(""),console.log("\u2713 Fallback 1 removed"),console.log("");continue}if(t==="4"){j(o,2),m(o),console.log(""),console.log("\u2713 Fallback 2 removed"),console.log("");continue}if(t==="5"){await It(e,o);continue}console.log(""),console.log("\u26A0 Invalid selection")}}async function Ct(e,o){for(;;){console.log(""),console.log("AI Model"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let t=o.get("TOOLNET_LLM_PROVIDER"),n=o.get("TOOLNET_EMBEDDING_PROVIDER");console.log(` LLM : ${t?`${M(t)} / ${o.get("TOOLNET_LLM_MODEL")||"model not configured"}`:"not configured"}`),console.log(` Embedding : ${n?`${ce(n)} / ${o.get("TOOLNET_EMBEDDING_MODEL")||(n==="local"?"local hash":"model not configured")}`:"legacy/default"}`),console.log(""),console.log(" 1. Configure LLM"),console.log(" 2. Configure Embedding"),console.log(" 3. Use LLM provider credentials for Embedding"),console.log(" 4. Configure LLM Fallbacks"),console.log(" 0. Back"),console.log("");let r=(await e.question("Choose: ")).trim();if(r==="0")return;if(r==="1"){await St(e,o);continue}if(r==="2"){await At(e,o);continue}if(r==="3"){await Mt(e,o);continue}if(r==="4"){await Nt(e,o);continue}console.log(""),console.log("\u26A0 Invalid selection")}}async function St(e,o){let t=new Map(o);for(;;){let n=await se(e,qe(o));if(n==="back")return;let r=I.find(a=>a.id===n);if(!r)continue;if(await mt(e,o,r),!Ot(o,r)){console.log(""),console.log("\u26A0 AI configuration is incomplete."),console.log(""),console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let a=(await e.question("Choose [1]: ")).trim()||"1";if(a==="2"){m(o),console.log(""),console.log("\u26A0 AI configuration saved without validation"),console.log(` ${L}`),console.log("");return}if(a==="3")continue;if(a==="4"){o.clear();for(let[l,g]of t)o.set(l,g);console.log(""),console.log("AI changes cancelled."),console.log("");return}continue}if((await Lt(o)).ok){m(o),console.log(`\u2713 ${r.label} configuration saved`),console.log(` ${L}`),console.log("");return}console.log(" 1. Retry"),console.log(" 2. Save anyway"),console.log(" 3. Choose another provider"),console.log(" 4. Cancel"),console.log("");let s=(await e.question("Choose [1]: ")).trim()||"1";if(s==="2"){m(o),console.log(""),console.log("\u26A0 AI configuration saved even though provider test failed"),console.log(` ${L}`),console.log("");return}if(s!=="3"&&s==="4"){o.clear();for(let[a,l]of t)o.set(a,l);console.log(""),console.log("AI changes cancelled."),console.log("");return}}}function Rt(){try{let o=oe().filter(t=>t.installed);if(o.length===0)return;console.log(""),console.log("Automatic AI memory");for(let t of o){let n=t.agent==="agy"?"Agy / Antigravity":t.agent==="opencode"?"OpenCode":t.agent==="codex"?"Codex":t.agent;console.log(` \u2713 ${n}`)}}catch{}}function d(e,...o){for(let t of o){let n=e.get(t)?.trim();if(n)return n}}function _(e,o,t){t&&!e.get(o)?.trim()&&e.set(o,t)}function yt(e){let o=!1,t=JSON.stringify([...e.entries()]);if(!e.get("TOOLNET_LLM_PROVIDER")?.trim()){let i;d(e,"GROQ_API_KEY")?i="groq":d(e,"DEEPSEEK_API_KEY")?i="deepseek":d(e,"NVIDIA_API_KEY","NVIDIA_NIM_API_KEY")?i="nvidia":d(e,"OPENROUTER_API_KEY")?i="openrouter":d(e,"ALIBABA_API_KEY","DASHSCOPE_API_KEY")?i="alibaba":d(e,"GEMINI_API_KEY","GOOGLE_API_KEY")?i="gemini":d(e,"CLOUDFLARE_API_TOKEN")&&d(e,"CLOUDFLARE_ACCOUNT_ID")?i="cloudflare":d(e,"HF_TOKEN")?i="huggingface":d(e,"OLLAMA_MODEL","OLLAMA_BASE_URL")?i="ollama":d(e,"OPENAI_API_KEY","MODEL_API_KEY")&&(i="openai-compatible"),i&&e.set("TOOLNET_LLM_PROVIDER",i)}switch(e.get("TOOLNET_LLM_PROVIDER")?.trim()){case"groq":_(e,"TOOLNET_LLM_API_KEY",d(e,"GROQ_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",d(e,"GROQ_BASE_URL")||"https://api.groq.com/openai/v1"),_(e,"TOOLNET_LLM_MODEL",d(e,"GROQ_MODEL"));break;case"deepseek":_(e,"TOOLNET_LLM_API_KEY",d(e,"DEEPSEEK_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",d(e,"DEEPSEEK_BASE_URL")||"https://api.deepseek.com"),_(e,"TOOLNET_LLM_MODEL",d(e,"DEEPSEEK_MODEL")||"deepseek-v4-flash");break;case"nvidia":_(e,"TOOLNET_LLM_API_KEY",d(e,"NVIDIA_API_KEY","NVIDIA_NIM_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",d(e,"NVIDIA_BASE_URL","NVIDIA_NIM_BASE_URL")||"https://integrate.api.nvidia.com/v1"),_(e,"TOOLNET_LLM_MODEL",d(e,"NVIDIA_MODEL","NVIDIA_NIM_MODEL"));break;case"openrouter":_(e,"TOOLNET_LLM_API_KEY",d(e,"OPENROUTER_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",d(e,"OPENROUTER_BASE_URL")||"https://openrouter.ai/api/v1"),_(e,"TOOLNET_LLM_MODEL",d(e,"OPENROUTER_MODEL"));break;case"alibaba":_(e,"TOOLNET_LLM_API_KEY",d(e,"ALIBABA_API_KEY","DASHSCOPE_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",d(e,"ALIBABA_BASE_URL","DASHSCOPE_BASE_URL")),_(e,"TOOLNET_LLM_MODEL",d(e,"ALIBABA_MODEL","DASHSCOPE_MODEL"));break;case"gemini":_(e,"TOOLNET_LLM_API_KEY",d(e,"GEMINI_API_KEY","GOOGLE_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",d(e,"GEMINI_BASE_URL")||"https://generativelanguage.googleapis.com/v1beta"),_(e,"TOOLNET_LLM_MODEL",d(e,"GEMINI_MODEL"));break;case"huggingface":_(e,"TOOLNET_LLM_API_KEY",d(e,"HF_TOKEN")),_(e,"TOOLNET_LLM_BASE_URL",d(e,"HF_INFERENCE_BASE_URL")||"https://router.huggingface.co/v1"),_(e,"TOOLNET_LLM_MODEL",d(e,"HF_LLM_MODEL","HF_MODEL"));break;case"ollama":_(e,"TOOLNET_LLM_API_KEY",d(e,"OLLAMA_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",d(e,"OLLAMA_BASE_URL")||"http://127.0.0.1:11434/v1"),_(e,"TOOLNET_LLM_MODEL",d(e,"OLLAMA_MODEL"));break;case"cloudflare":_(e,"TOOLNET_LLM_API_KEY",d(e,"CLOUDFLARE_API_TOKEN")),_(e,"TOOLNET_LLM_ACCOUNT_ID",d(e,"CLOUDFLARE_ACCOUNT_ID")),_(e,"TOOLNET_LLM_MODEL",d(e,"CLOUDFLARE_MODEL"));break;case"openai-compatible":_(e,"TOOLNET_LLM_API_KEY",d(e,"OPENAI_API_KEY","MODEL_API_KEY")),_(e,"TOOLNET_LLM_BASE_URL",d(e,"OPENAI_BASE_URL","MODEL_BASE_URL")),_(e,"TOOLNET_LLM_MODEL",d(e,"OPENAI_MODEL","MODEL_NAME"));break}!e.get("TOOLNET_EMBEDDING_PROVIDER")?.trim()&&d(e,"HF_TOKEN")&&(e.set("TOOLNET_EMBEDDING_PROVIDER","huggingface"),_(e,"TOOLNET_EMBEDDING_API_KEY",d(e,"HF_TOKEN")),_(e,"TOOLNET_EMBEDDING_MODEL",d(e,"HF_EMBEDDING_MODEL")||"sentence-transformers/all-MiniLM-L6-v2"));let r=JSON.stringify([...e.entries()]);return o=t!==r,o}function G(e,o="not configured"){return e?.trim()||o}function Dt(e){let o=K(N(e)),t=e.get("TOOLNET_LLM_PROVIDER"),n=e.get("TOOLNET_LLM_MODEL"),r=e.get("TOOLNET_EMBEDDING_PROVIDER"),i=e.get("TOOLNET_EMBEDDING_MODEL"),s=e.get("TOOLNET_LLM_FALLBACK_1_PROVIDER"),a=e.get("TOOLNET_LLM_FALLBACK_2_PROVIDER");console.log(""),console.log("TOOLNET MEMORY READY"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(`Storage : ${o}`),console.log(`LLM : ${t?`${M(t)} / ${G(n)}`:"not configured"}`),console.log(`Fallback 1 : ${s?`${M(s)} / ${G(e.get("TOOLNET_LLM_FALLBACK_1_MODEL"))}`:"none"}`),console.log(`Fallback 2 : ${a?`${M(a)} / ${G(e.get("TOOLNET_LLM_FALLBACK_2_MODEL"))}`:"none"}`),console.log(`Embedding : ${r?`${r==="local"?"Local / Hash":ce(r)} / ${G(i,r==="local"?"local hash":"not configured")}`:"legacy/default"}`),console.log(""),console.log(`Config : ${L}`),console.log(`Permissions: ${A.statSync(L).mode.toString(8).slice(-3)}`),console.log(""),console.log("Secrets : hidden"),console.log("Config mode: canonical TOOLNET_*"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")}function Ve(e){yt(e),e.has("TOOLNET_LLM_FALLBACK_COOLDOWN_MS")||e.set("TOOLNET_LLM_FALLBACK_COOLDOWN_MS","60000"),e.has("TOOLNET_LLM_MAX_RETRIES")||e.set("TOOLNET_LLM_MAX_RETRIES","1"),e.has("MEMORY_STORAGE_PROVIDER")||e.set("MEMORY_STORAGE_PROVIDER",N(e)),e.has("MEMORY_LOCAL_CACHE_MB")||e.set("MEMORY_LOCAL_CACHE_MB","200"),e.has("MEMORY_AUTO_CAPTURE")||e.set("MEMORY_AUTO_CAPTURE","true"),e.has("MEMORY_AUTO_RETRIEVE")||e.set("MEMORY_AUTO_RETRIEVE","true"),e.has("MEMORY_AUTO_SUMMARIZE")||e.set("MEMORY_AUTO_SUMMARIZE","true"),e.has("MEMORY_AUTO_SYNC")||e.set("MEMORY_AUTO_SYNC","true"),e.has("MEMORY_MAX_CANDIDATES")||e.set("MEMORY_MAX_CANDIDATES","50"),e.has("MEMORY_RERANK_TOP")||e.set("MEMORY_RERANK_TOP","10"),e.has("MEMORY_FINAL_CONTEXT")||e.set("MEMORY_FINAL_CONTEXT","5"),e.has("MEMORY_TOKEN_BUDGET")||e.set("MEMORY_TOKEN_BUDGET","2000"),e.has("TOOLNET_SESSION_LEARNING")||e.set("TOOLNET_SESSION_LEARNING","1"),e.has("TOOLNET_WORK_CONTINUITY")||e.set("TOOLNET_WORK_CONTINUITY","1"),e.has("TOOLNET_SEMANTIC_CONTINUITY")||e.set("TOOLNET_SEMANTIC_CONTINUITY","1"),e.has("TOOLNET_SMART_HANDOFF")||e.set("TOOLNET_SMART_HANDOFF","1")}async function ht(e,o){Ve(e),o||m(e),console.log("TOOLNET MEMORY SETUP"),console.log(""),console.log("Interactive terminal not detected."),console.log(`Config: ${L}`),console.log(`Storage: ${K(N(e))}`),console.log(""),console.log("Run from an interactive terminal to configure providers:"),console.log(" toolnet-memory setup")}async function bt(){let e=A.existsSync(L),o=e?Xo(A.readFileSync(L,"utf8")):new Map,t=new Map(o);if(Ve(t),!T.isTTY||!b.isTTY){await ht(t,e);return}let n=vo.createInterface({input:T,output:b}),r=!1;try{for(;;){rt(),it(t);let i=await st(n);if(i==="storage"){let s=JSON.stringify([...t.entries()]);await Et(n,t),r=r||s!==JSON.stringify([...t.entries()]);continue}if(i==="ai"){let s=JSON.stringify([...t.entries()]);await Ct(n,t),r=r||s!==JSON.stringify([...t.entries()]);continue}if(i==="exit"){if(!r){console.log(""),console.log("No changes made.");return}console.log("");let s=(await n.question("Discard unsaved changes? (y/N): ")).trim().toLowerCase();if(s==="y"||s==="yes"){console.log(""),console.log("Changes discarded.");return}continue}m(t),Ge(t)||(console.log(""),console.log("\u26A0 Storage configuration is incomplete.")),Rt(),Dt(t),console.log(""),console.log("Validate:"),console.log(" toolnet-memory provider:status"),console.log(" toolnet-memory provider:test"),console.log(" toolnet-memory doctor"),console.log("");return}}finally{n.close()}}bt().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toolnet-memory",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.18",
|
|
4
4
|
"description": "Persistent project memory, work continuity, and code intelligence for AI coding agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -89,7 +89,6 @@
|
|
|
89
89
|
"eslint": "^10.8.1",
|
|
90
90
|
"eslint-config-prettier": "^10.1.8",
|
|
91
91
|
"eslint-plugin-prettier": "^5.5.6",
|
|
92
|
-
"prettier": "^3.9.6",
|
|
93
92
|
"tsx": "^4.20.0",
|
|
94
93
|
"vitest": "^3.2.0"
|
|
95
94
|
},
|