@cachly-dev/mcp-server 0.10.231 → 0.10.233
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -4
- package/dist/src/cli-argumente.js +1 -1
- package/dist/src/handlers/brain.js +31 -31
- package/dist/src/index.js +207 -179
- package/dist/src/rueckfall-daten.js +1 -0
- package/dist/src/rueckfall.js +3 -0
- package/glama.json +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/src/index.js
CHANGED
|
@@ -1,59 +1,59 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{setzeClientKennung as zt}from"./herkunft.js";import{jwtExpiryMs as Ut,checkJwt as Jt,handleApiError as Wt,diagnoseAuth as Te,planAuthHeal as Je,readClientCredentialsFromEnv as Ft,buildClientCredentialsBody as Yt,clientCredentialsTokenUrl as Kt}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as qt}from"./werkzeug-nutzung.js";import{istLieferung as Gt,lieferSchluessel as Vt,tokenDerAntwort as Zt,hatTreffer as Qt,trefferSchluessel as We}from"./geliefert.js";import{notify as Fe}from"./notifier.js";import{fileURLToPath as Ye}from"node:url";import{createRequire as Xt}from"node:module";import{execFile as Ie}from"node:child_process";const eo=process.argv[1]!=null&&(process.argv[1]===Ye(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as Ke}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as to}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as oo}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as qe,ErrorCode as se,ListPromptsRequestSchema as Ge,ListResourceTemplatesRequestSchema as Ve,ListResourcesRequestSchema as Ze,ListToolsRequestSchema as Qe,McpError as X}from"@modelcontextprotocol/sdk/types.js";import{Redis as Xe}from"ioredis";let _=process.env.CACHLY_API_URL??"https://api.cachly.dev",b=Ne()??"";ce(b);const Vs=process.env.CACHLY_EMBED_MODEL??"",M=(()=>{try{const e=Xt(import.meta.url);for(const t of["../../package.json","../package.json"])try{const n=e(t);if(n.name==="@cachly-dev/mcp-server"&&n.version)return n.version}catch{}}catch{}return"0.10.100"})(),no=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let L=ke(process.env.CACHLY_BRAIN_INSTANCE_ID);function ee(){return b||Ne()||""}function J(){return ke(process.env.CACHLY_BRAIN_INSTANCE_ID)||$e()||""}let V=0,pe=null,et=!1;async function tt(){let e=[];try{q.getClientCapabilities()?.roots&&(e=(await q.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Yn({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:Ye})}function ie(){return et?ht(process.env):!1}function Ee(e,t,n){!e||!ie()||Un({instanzId:e,vomHook:n,verbindung:H,ausGit:s=>Pe("brain_from_git",s,H,O),projektOrdner:t?async()=>t:tt,einbetten:s=>st(s,{geduld:"lang"}),hatEinbettung:yo,einbettenZweit:s=>st(s,{geduld:"lang",modell:bo}),melde:s=>k("brain_from_git",{...b?{api_key:b}:{},instance_id:e,total:s,auto:"startwissen"}),startvorrat:s=>He("brain_seed_starter",s,H,O),meldeStartvorrat:s=>k("brain_seed_starter",{...b?{api_key:b}:{},instance_id:e,auto:!0},{seeded_count:s,auto:!0})})}function Re(){return ie()&&Kn()}const so=7e3,io=12e3,ro=18e4;let we=null;function je(e){return we||(we=ao(e).finally(()=>{we=null})),we}async function ao(e){try{if(!b){const t=Date.now()+e;for(;!_e()&&Nn({})&&Date.now()<t;)await new Promise(o=>setTimeout(o,Bn));const n=_e();if(!n)return!1;b=n,ce(n);const s=$e();s&&!L&&(L=s,V=0),await me(n),s&&await ge(s),k("instant_trial_started",{tool:"sessionstart-hook",...s?{instance_id:s}:{}})}if(ie()&&ft()){const t=Ln();t&&(Oe(t.instanzId,ie(),Re()),Ee(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!b}function co(){if(!ht(process.env))return;const e=Date.now()+ro,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}b&&!ft()||je(0)},500);t.unref(),je(0)}async function lo(){if(!b)return"";try{const e=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${b}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(12e3)});if(e.ok){const t=await e.json(),n=t.instance?.id??t.instance_id;if(n)return n}else fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function ot(){if(L)return L;if(!b)return"";if(pe)return pe;const e=Date.now();if(V>0&&e-V<3e4)return"";V=e,pe=(async()=>{try{const t=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const s=(await t.json())?.data??[],o=s.find(c=>c.status==="running")??s.find(c=>c.status==="provisioning");if(o)return L=o.id,V=0,L;const i=await lo();if(i)return L=i,V=0,Oe(i,ie(),Re()),ge(i),Ee(i),L}}catch{}return""})();try{return await pe}finally{pe=null}}let Be=0;const uo=6e4;let re="";async function me(e){try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const c=[o(i,".claude","mcp.json"),o(i,".cursor","mcp.json"),o(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(c.map(async a=>{if(s(a))try{const d=await n(a,"utf-8"),g=JSON.parse(d),l=g?.mcpServers?.cachly;l?.env&&(l.env.CACHLY_JWT=e,await t(a,JSON.stringify(g,null,2),"utf-8"))}catch{}}))}catch{}}async function ge(e){if(e){xe(e,{apiKey:b});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const c=[o(i,".claude","mcp.json"),o(i,".cursor","mcp.json"),o(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(c.map(async a=>{if(s(a))try{const d=JSON.parse(await n(a,"utf-8")),g=d?.mcpServers?.cachly;g?.env&&(g.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(a,JSON.stringify(d,null,2),"utf-8"))}catch{}}))}catch{}}}async function po(){try{const e=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify({name:"cachly-mcp-selfheal",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(!e.ok)return!1;const t=await e.json();return t.key?(b=t.key,ce(t.key),me(t.key),k("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function Le(){const e=Te(b),t=Je(e);if(t==="none")return re="",!0;if(t==="refresh"){const n=Date.now();return n-Be>=uo&&(Be=n,await po())?(re="",!0):(re=e.message,e.usable)}return re=e.message,!1}function ae(e,t){const n=(c,a)=>{try{t?.(c,a)}catch{}},s=c=>{c?n(!1,c.code??c.message):n(!0)},o=nn(e);if(!o){n(!1,"keine-http-adresse");return}const i=sn(o);try{process.platform==="win32"?Ie("cmd",["/c","start","",i],{windowsHide:!0},s):process.platform==="darwin"?Ie("open",[o],s):Ie("xdg-open",[o],s)}catch(c){n(!1,c instanceof Error?c.message:"unknown")}}let K=null;async function mo(){try{const e=await fetch(`${_}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(e.ok){const t=await e.json(),n=t.verification_uri||j("/device","ambient-signin"),s=`${n}${n.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:s,pollInterval:(t.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}}catch{}try{const t=await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/auth/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id=cachly-cli&scope=openid",signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;const n=await t.json();return{deviceCode:n.device_code,userCode:n.user_code,verifyUrl:n.verification_uri_complete,pollInterval:(n.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}catch{return null}}async function go(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const s=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e.deviceCode}),signal:AbortSignal.timeout(8e3)});return s.ok?s.json():null},n=async()=>(await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`client_id=cachly-cli&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=${e.deviceCode}`,signal:AbortSignal.timeout(8e3)})).json();try{let s=await t().catch(()=>null);if(s||(s=await n().catch(()=>null)),!s)return"pending";if(s.access_token){let o=s.access_token;try{const i=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(i.ok){const c=await i.json();c.key&&(o=c.key)}}catch{}return b=o,ce(o),K=null,k("device_flow_completed"),me(o),oe(o),V=0,await ot(),L&&ge(L),"done"}return s.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function nt(e){if(e.polling)return"pending";e.polling=!0;try{return await go(e)}finally{e.polling=!1}}function fo(e,t=nt,n=o=>K===o,s=ho){const o=async()=>{if(!n(e))return;let i="pending";try{i=await t(e)}catch{}if(i!=="done"){if(i==="expired"){n(e)&&(K=null);return}n(e)&&s(o,e.pollInterval)}};s(o,e.pollInterval)}function ho(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as ce,computeEmbedding as st,hasEmbedProvider as yo,EMBED_PROVIDER as it}from"./embeddings.js";import{ZWEIT_MODELL as bo}from"./rangfolge-stellschrauben.js";import{tokenize as wo,splitMultiQuery as vo,levenshtein as xo,recencyBoost as _o,extractTimestamp as $o,STOPWORDS as ko,katakanaToRomaji as So,arabicLightStem as Ao,expandCrossLingual as Co,CROSS_LINGUAL_MAP as To,ZERO_RESULTS_LOG as Io,zeroResultsTotal as Eo}from"./search.js";const te=new Map;function Ro(e){return e<=1?200:null}async function H(e){if(!e)throw new X(se.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
|
|
2
|
+
import{setzeClientKennung as zt}from"./herkunft.js";import{jwtExpiryMs as Wt,checkJwt as Jt,handleApiError as Ft,diagnoseAuth as Te,planAuthHeal as We,readClientCredentialsFromEnv as Yt,buildClientCredentialsBody as Kt,clientCredentialsTokenUrl as qt}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as Gt}from"./werkzeug-nutzung.js";import{istLieferung as Vt,lieferSchluessel as Zt,tokenDerAntwort as Qt,hatTreffer as Xt,trefferSchluessel as Je}from"./geliefert.js";import{notify as Fe}from"./notifier.js";import{fileURLToPath as Ye}from"node:url";import{createRequire as eo}from"node:module";import{execFile as Ie}from"node:child_process";const to=process.argv[1]!=null&&(process.argv[1]===Ye(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as Ke}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as oo}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as no}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as qe,ErrorCode as ne,ListPromptsRequestSchema as Ge,ListResourceTemplatesRequestSchema as Ve,ListResourcesRequestSchema as Ze,ListToolsRequestSchema as Qe,McpError as X}from"@modelcontextprotocol/sdk/types.js";import{Redis as Xe}from"ioredis";let _=process.env.CACHLY_API_URL??"https://api.cachly.dev",v=Le()??"";ae(v);const Vs=process.env.CACHLY_EMBED_MODEL??"",H=(()=>{try{const e=eo(import.meta.url);for(const t of["../../package.json","../package.json"])try{const s=e(t);if(s.name==="@cachly-dev/mcp-server"&&s.version)return s.version}catch{}}catch{}return"0.10.100"})(),so=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let N=$e(process.env.CACHLY_BRAIN_INSTANCE_ID);function G(){return v||Le()||""}function U(){return $e(process.env.CACHLY_BRAIN_INSTANCE_ID)||_e()||""}let V=0,ue=null,et=!1;async function tt(){let e=[];try{K.getClientCapabilities()?.roots&&(e=(await K.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Yn({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:Ye})}function se(){return et?yt(process.env):!1}function Ee(e,t,s){!e||!se()||zn({instanzId:e,vomHook:s,verbindung:O,ausGit:n=>Pe("brain_from_git",n,O,L),projektOrdner:t?async()=>t:tt,einbetten:n=>st(n,{geduld:"lang"}),hatEinbettung:bo,einbettenZweit:n=>st(n,{geduld:"lang",modell:wo}),melde:n=>A("brain_from_git",{...v?{api_key:v}:{},instance_id:e,total:n,auto:"startwissen"}),startvorrat:n=>He("brain_seed_starter",n,O,L),meldeStartvorrat:n=>A("brain_seed_starter",{...v?{api_key:v}:{},instance_id:e,auto:!0},{seeded_count:n,auto:!0})})}function Re(){return se()&&Kn()}const io=7e3,ro=12e3,ao=18e4;let be=null;function je(e){return be||(be=co(e).finally(()=>{be=null})),be}async function co(e){try{if(!v){const t=Date.now()+e;for(;!xe()&&Ln({})&&Date.now()<t;)await new Promise(o=>setTimeout(o,Bn));const s=xe();if(!s)return!1;v=s,ae(s);const n=_e();n&&!N&&(N=n,V=0),await pe(s),n&&await me(n),A("instant_trial_started",{tool:"sessionstart-hook",...n?{instance_id:n}:{}})}if(se()&&ft()){const t=Nn();t&&(Oe(t.instanzId,se(),Re()),Ee(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!v}function lo(){if(!yt(process.env))return;const e=Date.now()+ao,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}v&&!ft()||je(0)},500);t.unref(),je(0)}async function uo(){if(!v)return"";try{const e=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${v}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(12e3)});if(e.ok){const t=await e.json(),s=t.instance?.id??t.instance_id;if(s)return s}else fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function ot(){if(N)return N;if(!v)return"";if(ue)return ue;const e=Date.now();if(V>0&&e-V<3e4)return"";V=e,ue=(async()=>{try{const t=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const n=(await t.json())?.data??[],o=n.find(c=>c.status==="running")??n.find(c=>c.status==="provisioning");if(o)return N=o.id,V=0,N;const i=await uo();if(i)return N=i,V=0,Oe(i,se(),Re()),me(i),Ee(i),N}}catch{}return""})();try{return await ue}finally{ue=null}}let Be=0;const po=6e4;let ie="";async function pe(e){try{const{writeFile:t,readFile:s}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:o}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const c=[o(i,".claude","mcp.json"),o(i,".cursor","mcp.json"),o(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(c.map(async r=>{if(n(r))try{const d=await s(r,"utf-8"),f=JSON.parse(d),l=f?.mcpServers?.cachly;l?.env&&(l.env.CACHLY_JWT=e,await t(r,JSON.stringify(f,null,2),"utf-8"))}catch{}}))}catch{}}async function me(e){if(e){ve(e,{apiKey:v});try{const{writeFile:t,readFile:s}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:o}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const c=[o(i,".claude","mcp.json"),o(i,".cursor","mcp.json"),o(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(c.map(async r=>{if(n(r))try{const d=JSON.parse(await s(r,"utf-8")),f=d?.mcpServers?.cachly;f?.env&&(f.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(r,JSON.stringify(d,null,2),"utf-8"))}catch{}}))}catch{}}}async function mo(){try{const e=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`},body:JSON.stringify({name:"cachly-mcp-selfheal",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(!e.ok)return!1;const t=await e.json();return t.key?(v=t.key,ae(t.key),pe(t.key),A("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function Ne(){const e=Te(v),t=We(e);if(t==="none")return ie="",!0;if(t==="refresh"){const s=Date.now();return s-Be>=po&&(Be=s,await mo())?(ie="",!0):(ie=e.message,e.usable)}return ie=e.message,!1}function re(e,t){const s=(c,r)=>{try{t?.(c,r)}catch{}},n=c=>{c?s(!1,c.code??c.message):s(!0)},o=nn(e);if(!o){s(!1,"keine-http-adresse");return}const i=sn(o);try{process.platform==="win32"?Ie("cmd",["/c","start","",i],{windowsHide:!0},n):process.platform==="darwin"?Ie("open",[o],n):Ie("xdg-open",[o],n)}catch(c){s(!1,c instanceof Error?c.message:"unknown")}}let Y=null;async function go(){try{const e=await fetch(`${_}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(e.ok){const t=await e.json(),s=t.verification_uri||j("/device","ambient-signin"),n=`${s}${s.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:n,pollInterval:(t.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}}catch{}try{const t=await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/auth/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id=cachly-cli&scope=openid",signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;const s=await t.json();return{deviceCode:s.device_code,userCode:s.user_code,verifyUrl:s.verification_uri_complete,pollInterval:(s.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}catch{return null}}async function ho(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const n=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e.deviceCode}),signal:AbortSignal.timeout(8e3)});return n.ok?n.json():null},s=async()=>(await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`client_id=cachly-cli&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=${e.deviceCode}`,signal:AbortSignal.timeout(8e3)})).json();try{let n=await t().catch(()=>null);if(n||(n=await s().catch(()=>null)),!n)return"pending";if(n.access_token){let o=n.access_token;try{const i=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(i.ok){const c=await i.json();c.key&&(o=c.key)}}catch{}return v=o,ae(o),Y=null,A("device_flow_completed"),pe(o),te(o),V=0,await ot(),N&&me(N),"done"}return n.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function nt(e){if(e.polling)return"pending";e.polling=!0;try{return await ho(e)}finally{e.polling=!1}}function fo(e,t=nt,s=o=>Y===o,n=yo){const o=async()=>{if(!s(e))return;let i="pending";try{i=await t(e)}catch{}if(i!=="done"){if(i==="expired"){s(e)&&(Y=null);return}s(e)&&n(o,e.pollInterval)}};n(o,e.pollInterval)}function yo(e,t){const s=setTimeout(e,t);typeof s.unref=="function"&&s.unref()}import{setEmbedJwt as ae,computeEmbedding as st,hasEmbedProvider as bo,EMBED_PROVIDER as it}from"./embeddings.js";import{ZWEIT_MODELL as wo}from"./rangfolge-stellschrauben.js";import{tokenize as vo,splitMultiQuery as xo,levenshtein as _o,recencyBoost as $o,extractTimestamp as ko,STOPWORDS as So,katakanaToRomaji as Ao,arabicLightStem as Co,expandCrossLingual as To,CROSS_LINGUAL_MAP as Io,ZERO_RESULTS_LOG as Eo,zeroResultsTotal as Ro}from"./search.js";const ee=new Map;function jo(e){return e<=1?200:null}async function O(e){if(!e)throw new X(ne.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
|
|
3
3
|
|
|
4
4
|
This usually resolves in a few seconds \u2014 just call the tool again and it will connect automatically.
|
|
5
5
|
|
|
6
6
|
If it keeps happening:
|
|
7
7
|
\u2022 Run \`list_instances\` to check your instances, or
|
|
8
8
|
\u2022 Set CACHLY_BRAIN_INSTANCE_ID in your MCP config, or
|
|
9
|
-
\u2022 Reach us at support@cachly.dev.`);const t=
|
|
9
|
+
\u2022 Reach us at support@cachly.dev.`);const t=ee.get(e);return t||Mn(Bo,e,()=>No(e))}const Bo=new Map;async function No(e){F("verbindung: Instanz abfragen");let t=await L(`/api/v1/instances/${e}`);if(F(`verbindung: Instanz ${t.status}`),t=await Hn(t,()=>L(`/api/v1/instances/${e}`),{fristMs:so,melde:r=>F(`verbindung: Instanz ${r.status}`)}),t.status!=="running"){fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...v?{Authorization:`Bearer ${v}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:t.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let r;throw t.status==="provisioning"?r=`\u23F3 Brain instance "${t.name}" is still starting up.
|
|
10
10
|
|
|
11
|
-
First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:t.status==="failed"?
|
|
11
|
+
First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:t.status==="failed"?r=`\u274C Brain instance "${t.name}" failed to start.
|
|
12
12
|
|
|
13
13
|
Our system will retry automatically. Check status at: ${j("/instances","instance-error")}
|
|
14
|
-
If this persists, contact support@cachly.dev.`:t.status==="suspended"?
|
|
14
|
+
If this persists, contact support@cachly.dev.`:t.status==="suspended"?r=`\u23F8 Brain instance "${t.name}" is suspended (billing issue).
|
|
15
15
|
|
|
16
|
-
Update your payment method at: ${j("/billing","upgrade")}`:t.status==="pending_payment"?
|
|
16
|
+
Update your payment method at: ${j("/billing","upgrade")}`:t.status==="pending_payment"?r=`\u{1F4B3} Brain instance "${t.name}" is waiting for payment.
|
|
17
17
|
|
|
18
|
-
Complete your checkout at: ${j("/instances","upgrade")}`:
|
|
18
|
+
Complete your checkout at: ${j("/instances","upgrade")}`:r=`Brain instance "${t.name}" is not reachable (status: ${t.status}).
|
|
19
19
|
|
|
20
20
|
\u2022 View your instance at: ${j("/instances","instance-error")}
|
|
21
|
-
\u2022 Run \`get_api_status\` for a full diagnostic.`,new X(
|
|
21
|
+
\u2022 Run \`get_api_status\` for a full diagnostic.`,new X(ne.InvalidRequest,r)}if(!t.host||!t.port)throw new X(ne.InternalError,`Instance "${t.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let s,n;try{const r=await L(`/api/v1/instances/${e}/connection`);s=r.password??void 0,n=r,F("verbindung: Zugangsdaten da")}catch(r){const d=r instanceof Error?r.message:String(r);if(d.includes("401")||d.includes("403")||d.includes("Unauthorized"))throw new X(ne.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const o=xt({host:t.host,port:t.port,tls_enabled:t.tls_enabled},n),i=new Xe({host:o.host,port:o.port,password:s||void 0,commandTimeout:8e3,...o.tls?{tls:o.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:jo,maxRetriesPerRequest:1,keepAlive:15e3}),c=()=>{ee.delete(e),i.disconnect()};i.on("error",c),i.on("end",c);try{await i.connect()}catch(r){i.disconnect();const d=r instanceof Error?r.message:String(r);throw fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...v?{Authorization:`Bearer ${v}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:t.host,port:t.port,error:d,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new X(ne.InternalError,`Could not reach Brain instance "${t.name}" (${t.host}:${t.port}).
|
|
22
22
|
|
|
23
23
|
\u2022 Check your network connection
|
|
24
24
|
\u2022 Run \`get_api_status\` to verify instance status
|
|
25
|
-
\u2022 Technical detail: ${d}`)}return
|
|
26
|
-
cachly: could not open a browser (${
|
|
25
|
+
\u2022 Technical detail: ${d}`)}return ee.set(e,i),F("verbindung: Valkey verbunden"),i}async function L(e,t={},s=!1){s||We(Te(v))!=="none"&&await Ne(),Jt(v);const n=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),o=await fetch(`${_}${e}`,{...t,signal:AbortSignal.timeout(n),headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`,...t.headers}});if(!o.ok){if(o.status===401&&!s&&(Be=0,await Ne()))return L(e,t,!0);const c=(await o.json().catch(()=>({error:o.statusText}))).error??o.statusText;Ft(o.status,c)}if(o.status!==204)return o.json()}import{handleBrainTool as Po}from"./handlers/brain.js";import{handleContextTool as Lo}from"./handlers/context.js";import{handleInstanceTool as Oo}from"./handlers/instances.js";import{handleCacheTool as Ho}from"./handlers/cache.js";import{handleTeamTool as Mo}from"./handlers/team.js";import{handleRoadmapTool as Do}from"./handlers/roadmap.js";import{handleAdvancedTool as Uo}from"./handlers/advanced.js";import{handleSyndicateTool as zo}from"./handlers/syndicate.js";import{handleFedbrainTool as Pe,_lastBrainFromGitCounts as we}from"./handlers/fedbrain.js";import{extractFirstRecallProof as Wo,extractTopHit as Jo,fuersTerminal as rt,renderFirstRecallProof as Fo}from"./first-recall-proof.js";import{aussetzerLeise as Yo}from"./aussetzer.js";import{gitHookOrdner as Ko,installClsPostCommitHook as at,CLS_HOOK_VERSION as ct}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as qo,CLAUDE_MD_MARKER_END as Go,EDITOR_FILES as ce,ANWEISUNGS_DATEIEN as Vo,buildClaudeMdBlock as lt,setzeAnweisungsblock as Zo,sollSchreiben as Qo}from"./projektdateien.js";import{klassiereArgument as Xo,leseFlag as dt,flagsOhneWert as en,pruefeInitEingaben as tn}from"./cli-argumente.js";import{uninstallBefehl as on}from"./uninstall.js";import{gitLesen as ut}from"./git-ohne-shell.js";import{browserAdresse as nn,fuerCmd as sn}from"./browser-adresse.js";import{installAmbientHooks as pt,installCursorHooks as rn,installCopilotHooks as an,installCodexHooks as cn,installGeminiHooks as ln,AMBIENT_HOOK_VERSION as mt,COPILOT_HOOKS_DATEI as dn,CODEX_HOOKS_DATEI as un,GEMINI_SETTINGS_DATEI as pn}from"./ambient-hooks.js";import{hookHauptlauf as mn,auffrischenHauptlauf as gn,startwissenImportHauptlauf as hn}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as fn}from"./startwissen-hook.js";import{rahmeAntwort as yn}from"./antwort-rahmen.js";import{appendLedgerEntry as bn,readLedger as gt,defaultLedgerPath as wn,reportLedgerEntry as vn,teileNachInstanz as xn}from"./ambient-ledger.js";import{installCodexMcp as _n,installGeminiMcp as $n}from"./editor-mcp-eintrag.js";import{resolveApiKey as Le,saveApiKey as te,saveInstanceId as ve,readSavedApiKey as xe,readInstanceId as _e}from"./credentials.js";import{KEYCLOAK_BASIS as ht,istTestSchluessel as kn,waehleTestSchluessel as Sn,starteKeycloakAnmeldung as An,warteAufKeycloakAnmeldung as Cn,uebernimm as Tn,brainImKonto as In,erfolgsText as En,fehlerText as Rn,ersetzeSchluessel as jn}from"./uebernahme.js";import{WARTE_TAKT_MS as Bn,auftragLiegt as ft,nimmAuftrag as Nn,sichereKonto as Pn,sperreLiegt as Ln,startwissenEingeschaltet as yt}from"./konto-anlegen.js";import{sichereZugang as On,echterWert as $e}from"./zugang.js";import{zeitpunkt as F}from"./zeitmessung.js";import{warteAufLaufendeInstanz as Hn,gemeinsamerAufbau as Mn}from"./instanz-warten.js";import{merkeNeuesBrain as Oe,startetLautLetztemBlick as Dn,setzeCommitQuelle as Un}from"./leeres-brain.js";import{starteStartwissen as zn,startwissenGestartet as Wn,beanspruchStartwissen as Jn,holeStartwissenHinweis as Fn,waehleProjektOrdner as Yn,startvorratErlaubt as Kn,projektCommits as qn}from"./startwissen.js";import{eigeneFassung as Gn,pruefeNeueFassung as Vn,holeNeueFassungHinweis as Zn}from"./neue-fassung.js";import{beiStdinEnde as Qn}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Xn,starteBrandWachhund as es}from"./brand-wachhund.js";import{sichtbareWerkzeuge as ts,VERTEILER as bt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as os}from"./pflichtfelder.js";import{buildLessonsMarkdown as ns,buildLessonsJsonl as ss,vonRohLektion as is}from"./brain-export.js";import{detectEditor as rs}from"./editor.js";import{milestoneSent as wt,markMilestoneSent as vt}from"./funnel-milestones.js";import{kostprobeUebrig as as,kostprobeVerbrauchen as cs,kostprobeHinweis as ls,schrankeNachKostproben as ds}from"./kostprobe.js";import{netBalance as us}from"./ambient-recall.js";import{handleShareTool as He}from"./handlers/share.js";import{handleVizTool as ps}from"./handlers/viz.js";import{commitArt as ms,istRueckbau as gs,zaehleLektionen as hs}from"./commit-art.js";import{TOOLS as le}from"./tools.js";import{verbindungsWeg as xt}from"./brains-tls.js";let _t=!1,$t=!1,ke=!1;function kt(){return rs()}function fs(e){try{const t=e.split(".");if(t.length!==3)return;const s=JSON.parse(Buffer.from(t[1],"base64url").toString("utf-8"));if(!s.sub)return;let n=2166136261;for(let o=0;o<s.sub.length;o++)n^=s.sub.charCodeAt(o),n=n*16777619>>>0;return n.toString(16).padStart(8,"0")+s.sub.length.toString(16).padStart(4,"0")}catch{return}}function A(e,t,s){if(process.env.CACHLY_NO_TELEMETRY==="1")return;const n=v?fs(v):void 0;fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:e,version:H,editor:kt(),...v?{jwt:v}:{},...n?{user_fingerprint:n}:{},...s?{metrics:s}:{},...t}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}function ys(e,t){return vn({apiUrl:_,jwt:v,instanceId:e},t)}async function bs(e){if(!_t&&process.env.CACHLY_NO_TELEMETRY!=="1"){_t=!0;try{await fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:H,editor:kt(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const ws=new Set(["causal_trace","brain_predict","brain_plan","brain_predict_failures","team_learn","team_confirm","team_recall","team_synthesize","team_crystallize","global_learn","global_recall"]),vs={causal_trace:"Causal root-cause tracing \u2014 follow the failure chain to the real cause, not just the symptom.",brain_predict:"Predictive risk \u2014 your Brain warns you what will break *before* you run it.",brain_plan:"Generative planning \u2014 turn a goal into an ordered, risk-aware plan from your own history.",brain_predict_failures:"Failure prediction \u2014 catch CI/build breakage before it happens.",team_learn:"Team Brain \u2014 one shared memory across your whole team.",team_confirm:"Team Brain \u2014 peer + senior review that raises lesson trust.",team_recall:"Team Brain \u2014 recall everything your teammates have already solved.",team_synthesize:"Team Brain \u2014 synthesize collective knowledge across authors.",team_crystallize:"Team Brain \u2014 compress your team's wisdom into a shareable crystal.",global_learn:"Team Brain \u2014 contribute to your organization's shared memory.",global_recall:"Team Brain \u2014 recall across your entire organization."},St=j("/billing","upgrade"),At=new Map;async function xs(e){const t=At.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const n=((await L(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),o={tier:n,isFree:n==="free"||n===""};return At.set(e,{info:o,expiresAt:Date.now()+6e4}),o}catch{return{tier:"unknown",isFree:!1}}}async function _s(e,t){if(!ws.has(e)||!t)return null;const{isFree:s}=await xs(t);if(!s)return null;const n=vs[e]??"A Premium intelligence feature.";if(as(e)){const o=cs(e);return{kostprobe:ls(e,o,St)}}return{sperre:ds(e,n,St)}}async function $s(e,t){try{await(await O(e)).hincrby(Gt(e),t,1)}catch{}}async function ks(e,t,s){if(Vt(t))try{const n=await O(e),o=Xt(s);await n.incrby(Zt(e),o?Qt(s):0),await n.hincrby(Je(e),"abrufe",1),o&&await n.hincrby(Je(e),"treffer",1)}catch{}}async function Ss(e){const t=await go();return t?(Y=t,A("device_flow_started",{tool:e}),re(t.verifyUrl,(s,n)=>{if(s){A("device_browser_opened",{stelle:"tool"});return}A("device_browser_failed",{reason:n??"unknown",stelle:"tool"}),process.stderr.write(`
|
|
26
|
+
cachly: could not open a browser (${n??"unknown"}).
|
|
27
27
|
cachly: open this yourself to finish signing in:
|
|
28
28
|
cachly: ${t.verifyUrl}
|
|
29
29
|
cachly: code ${t.userCode}
|
|
30
30
|
|
|
31
|
-
`)}),fo(t),["\u{1F9E0} **cachly AI Brain \u2014 the user must sign in once.**","","**Show the following link and code to the user verbatim \u2014 they cannot","continue without them.**","",`\u{1F449} **${t.verifyUrl}**`,"",`Code: **${t.userCode}**`,"","A browser may have opened automatically with the code pre-filled. If it","did not, the link above is the whole step.","","Once signed in, the Brain activates on its own \u2014 no further action, no","restart. The next request arrives brain-powered.","",`\u2728 ${
|
|
31
|
+
`)}),fo(t),["\u{1F9E0} **cachly AI Brain \u2014 the user must sign in once.**","","**Show the following link and code to the user verbatim \u2014 they cannot","continue without them.**","",`\u{1F449} **${t.verifyUrl}**`,"",`Code: **${t.userCode}**`,"","A browser may have opened automatically with the code pre-filled. If it","did not, the link above is the whole step.","","Once signed in, the Brain activates on its own \u2014 no further action, no","restart. The next request arrives brain-powered.","",`\u2728 ${le.length} MCP tools \xB7 GDPR \xB7 EU servers \xB7 free tier, no credit card`].join(`
|
|
32
32
|
`)):["\u{1F9E0} **cachly AI Brain \u2014 Setup required**","","Run the setup wizard once in your terminal:"," ```"," npx @cachly-dev/mcp-server@latest autopilot"," ```","",`Or get your API key at: ${j("/setup-ai","ambient-signin")}`,"","\u2728 Free tier includes: 1 Brain instance, persistent memory, semantic search."].join(`
|
|
33
|
-
`)}async function As(e){if(!e)return!0;if(
|
|
34
|
-
`)}return On({schluessel:
|
|
33
|
+
`)}async function As(e){if(!e)return!0;if(Wn(e))return!1;try{return await Jn(await O(e),"sitzungsstart")}catch{return!0}}async function J(e,t){if(!v&&await je(io))return J(e,t);if(!v){if(bs(e),Y){const a=await nt(Y);return a==="done"?J(e,t):a==="expired"?(A("device_flow_failed",{reason:"timeout"}),Y=null,"\u231B **Authentication timed out.** Please call any tool again to restart the sign-in flow."):["\u23F3 **Signing you in\u2026**","",`Finish in your browser: **${Y.verifyUrl}**`,`Code: **${Y.userCode}**`,"","This completes automatically once you sign in \u2014 no need to come back here."].join(`
|
|
34
|
+
`)}return On({schluessel:v,konfigurierteInstanz:N,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{F("sofort-test: Anfang");const a=await Pn({apiUrl:_,version:H,fristMs:ro}),m=a.art==="angelegt"?a.test:a.art==="vorhanden"&&a.instanzId?{apiKey:a.apiKey,instanzId:a.instanzId}:null;return F(`sofort-test: ${m?"Brain angelegt":"kein Test"}`),m&&Oe(m.instanzId,se(),Re()),m},ablagen:{setzeSchluessel:a=>{v=a},setEmbedJwt:ae,saveApiKey:a=>te(a),persistApiKeyToConfig:pe,merkeInstanz:a=>{N=a,V=0},persistInstanceIdToConfig:me},meldeEreignis:A,werkzeug:()=>J(e,t),anmelden:()=>Ss(e),neuesBrain:Ee})}if(!t.instance_id){const a=await ot();a&&(t={...t,instance_id:a})}const s=await _s(e,t.instance_id);let n="";if(s!==null){if("sperre"in s)return A("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),s.sperre;n=s.kostprobe,A("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&$s(t.instance_id,e),F(`werkzeug ${e}: Zugang und Tarif geklaert`);const o=await Po(e,t,O,L);if(F(`werkzeug ${e}: Brain-Werkzeug fertig`),o!==null){typeof t.instance_id=="string"&&t.instance_id&&ks(t.instance_id,e,String(o??"")),!ke&&v&&(ke=!0,wt("first_call_success")||(vt("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""})));const a=t.instance_id??N??"",m=v?{api_key:v,instance_id:a}:{instance_id:a};if(e==="recall_best_solution")A("recall_best_solution",m);else if(e==="learn_from_attempts")A("learn_from_attempts",m);else if(e==="session_start"){A("session_start",m,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const h=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),p=h.includes("Welcome! Your AI Brain is live.");if(!Dn(a)){if(!p&&h.length>100)A("recall_best_solution",m);else if(p&&t.workspace_path&&await As(a))try{const C=await Pe("brain_from_git",{instance_id:a,repo_path:t.workspace_path,limit:50},O,L);if(C!==null){A("brain_from_git",{...m,...we??{}}),A("recall_best_solution",m);let I="";if((we?.total??0)===0)try{const M=await He("brain_seed_starter",{instance_id:a},O,L);M&&(A("brain_seed_starter",{...m,auto:!0},{seeded_count:16,auto:!0}),I=`
|
|
35
35
|
---
|
|
36
|
-
`+String(
|
|
37
|
-
\u2705 **Brain bootstrapped from git \u2014 ${$} lesson${$===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(
|
|
36
|
+
`+String(M))}catch{}const E=String(C),$=we?.total??0,R=$>0?`
|
|
37
|
+
\u2705 **Brain bootstrapped from git \u2014 ${$} lesson${$===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(E||I||R)return String(o)+R+`
|
|
38
38
|
---
|
|
39
|
-
`+
|
|
39
|
+
`+E+I}}catch(C){return A("brain_from_git_failed",{...m,reason:C instanceof Error?C.message.slice(0,120):"unknown"}),String(o)+`
|
|
40
40
|
|
|
41
41
|
> \u26A0\uFE0F **Auto-bootstrap from git history failed** \u2014 your Brain is live but starts empty.
|
|
42
|
-
> Run \`brain_from_git(instance_id="`+
|
|
42
|
+
> Run \`brain_from_git(instance_id="`+a+'", repo_path="'+String(t.workspace_path)+'")` manually to seed it.\n> Or try `brain_seed_starter` to load 16 universal engineering lessons instantly.'}}}else if(e==="session_end")A("session_end",m);else if(e==="smart_recall"){const h=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),p=h.length>50&&!h.includes("No lessons found")&&!h.includes("no lessons")&&!h.includes("No matches found");if(A("smart_recall",m,{hit:p,topic:String(t.query??"").slice(0,80)}),p&&A("recall_best_solution",m),ie&&typeof o=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${ie.split(`
|
|
43
43
|
`)[0]}
|
|
44
44
|
|
|
45
|
-
${o}`}return o}const i=await
|
|
46
|
-
`);let
|
|
47
|
-
`)}}catch{
|
|
45
|
+
${o}`}return o}const i=await Lo(e,t,O,L);if(i!==null)return!ke&&v&&(ke=!0,wt("first_call_success")||(vt("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""}))),i;const c=await Oo(e,t,O,L);if(c!==null)return c;const r=await Ho(e,t,O,L);if(r!==null)return r;const d=a=>n?a+n:a,f=await Mo(e,t,O,L);if(f!==null)return d(f);const l=await Do(e,t,O,L);if(l!==null)return l;const u=await Uo(e,t,O,L);if(u!==null)return d(u);const b=await zo(e,t,O,L);if(b!==null){if(e==="brain_predict"){const a=t.instance_id??N??"";A("brain_predict",v?{api_key:v,instance_id:a}:{instance_id:a})}return d(b)}const w=await He(e,t,O,L);if(w!==null)return w;const x=await ps(e,t,O,L);if(x!==null)return x;const g=await Pe(e,t,O,L);if(g!==null){const a=t.instance_id??N??"",m=v?{api_key:v,instance_id:a}:{instance_id:a};if(e==="brain_from_git"){const h=we;A("brain_from_git",{...m,...h??{}},h?{fixes:h.fixes,features:h.features,refactors:h.refactors,total:h.total}:void 0)}else e==="brain_predict_failures"&&A("brain_predict_failures",m);return g}switch(e){case"get_api_status":{let a="unknown";try{const C=await fetch(`${_}/health`,{signal:AbortSignal.timeout(8e3)});if(C.ok){const k=await C.json();a=`${k.status??"ok"} (db: ${k.db??"?"})`}else a=`HTTP ${C.status}`}catch(C){a=`unreachable: ${C.message}`}if(!v)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${a}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${j("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
|
|
46
|
+
`);let m="\u274C invalid JWT format";try{const C=v.split(".");if(C.length===3){const k=JSON.parse(Buffer.from(C[1],"base64url").toString("utf-8")),I=k.sub??"(unknown)",E=k.iss??"(unknown)",$=E.includes("keycloak")?"Keycloak":"OIDC",R=k.exp?new Date(k.exp*1e3):null,M=R?R<new Date:!1;m=["\u2705 JWT decoded",` Sub (user ID): ${I}`,` Provider: ${$}`,` Issuer: ${E}`,` Expires: ${R?R.toISOString():"never"} ${M?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
|
|
47
|
+
`)}}catch{m="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let h="";try{const k=(await L("/api/v1/instances")).data??[];if(k.length===0)h=`
|
|
48
48
|
|
|
49
49
|
\u{1F9E0} **Brain Instances:** none \u2014 create one at ${j("/instances","api-status")}`;else{const I=[`
|
|
50
50
|
|
|
51
|
-
\u{1F9E0} **Brain Instances:**`];for(const
|
|
52
|
-
`)}}catch(
|
|
51
|
+
\u{1F9E0} **Brain Instances:**`];for(const E of k){const $=E.status==="running"?"\u{1F7E2}":E.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",R=E.id===N?" \u2190 active":"";if(I.push(` ${$} **${E.name}** (\`${E.id}\`) \xB7 ${E.status}${R}`),E.status==="running"&&E.host){const M=ee.get(E.id);if(M)try{await M.ping(),I.push(" \u{1F493} Redis: connected")}catch{I.push(" \u26A0\uFE0F Redis: pooled but ping failed \u2014 will reconnect on next use")}else I.push(" \u{1F4A4} Redis: not connected yet (connects on first tool use)")}else E.status==="provisioning"?I.push(" \u23F3 Still provisioning \u2014 check back in ~30 s"):E.status!=="running"&&I.push(` \u274C Not reachable (status: ${E.status})`)}h=I.join(`
|
|
52
|
+
`)}}catch(C){h=`
|
|
53
53
|
|
|
54
|
-
\u{1F9E0} **Brain Instances:** could not fetch \u2014 ${
|
|
55
|
-
`)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${
|
|
56
|
-
`)}default:throw new
|
|
54
|
+
\u{1F9E0} **Brain Instances:** could not fetch \u2014 ${C.message}`}await Ne();const p=Te(v),S=p.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":p.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${p.expiresInMs?` (${Math.round(p.expiresInMs/36e5)}h left)`:""}`:p.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${p.message.split(`
|
|
55
|
+
`)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${a}`,` ${S}`,"","\u{1F511} **Auth:**",m,h].join(`
|
|
56
|
+
`)}default:throw new Ct(`Unknown tool: ${e}`)}}class Ct extends Error{}const Tt=`REQUIRED FIRST STEP for every task in this project: before you read or edit any file, call the cachly tool smart_recall with one line describing the task (if it is not loaded yet, load it with your tool search first). It returns fixes, decisions and known traps from earlier sessions in THIS codebase. Do this even for small tasks.
|
|
57
57
|
|
|
58
58
|
This project has a Cachly AI Brain \u2014 persistent, cross-session memory of past fixes, decisions, and gotchas for THIS codebase.
|
|
59
59
|
|
|
@@ -63,237 +63,265 @@ This project has a Cachly AI Brain \u2014 persistent, cross-session memory of pa
|
|
|
63
63
|
- BEFORE a risky op (deploy, migration, dependency bump): call brain_predict.
|
|
64
64
|
|
|
65
65
|
You do not need to pass instance_id: the server uses CACHLY_BRAIN_INSTANCE_ID if it is set, and otherwise the Brain saved by \`cachly setup\` in ~/.cachly/credentials.json.
|
|
66
|
-
session_start gives a briefing at the start of a session; it does not replace smart_recall for a concrete task.`,
|
|
66
|
+
session_start gives a briefing at the start of a session; it does not replace smart_recall for a concrete task.`,It={tools:{},resources:{},prompts:{}},Et=async()=>{const{katalog:e,unbekannteKernnamen:t}=ts(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function Rt(){return{resources:[]}}async function jt(){return{resourceTemplates:[]}}async function Bt(){return{prompts:[]}}function Cs(e){e.setRequestHandler(Qe,Et),e.setRequestHandler(qe,Lt),e.setRequestHandler(Ze,Rt),e.setRequestHandler(Ve,jt),e.setRequestHandler(Ge,Bt)}function Ts(){const e=new Ke({name:"cachly-mcp",version:H},{capabilities:It,instructions:Tt});return Cs(e),Nt(e),e}function Nt(e){const t=e.oninitialized;e.oninitialized=()=>{let s;try{s=e.getClientVersion(),zt(s?.name,s?.version)}catch{}$t||($t=!0,A("mcp_verbunden",{client:String(s?.name??"unbekannt").slice(0,60),client_version:String(s?.version??"").slice(0,30)})),t?.()}}const K=new Ke({name:"cachly-mcp",version:H},{capabilities:It,instructions:Tt});Nt(K),K.setRequestHandler(Qe,Et),K.setRequestHandler(Ze,Rt),K.setRequestHandler(Ve,jt),K.setRequestHandler(Ge,Bt);let Me=null,ge=!1,Z=null,Pt=0;async function Is(e){if(!ge){if(Z){await Z;return}Z=(async()=>{ge=!0,Me=e;try{await J("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{Z=null}})(),await Z,process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await O(e),s=await t.get(`cachly:index:last_indexed:${e}`),n=1440*60*1e3;(!s||Date.now()-parseInt(s,10)>n)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),await J("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code",hintergrund:!0}))})().catch(()=>{})}}async function De(){if(!(!ge||!Me)){ge=!1;try{await J("session_end",{instance_id:Me,summary:`Auto-ended after ${Pt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Lt=async e=>{let{name:t,arguments:s}=e.params;if(t===bt){const o=s??{},i=typeof o.tool=="string"?o.tool:"";if(!i)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const c=le.find(r=>r.name===i);if(!c)return{content:[{type:"text",text:`Kein Werkzeug namens "${i}". Die Liste steht in der Beschreibung von ${bt}.`}],isError:!0};if(o.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:c.name,description:c.description,inputSchema:c.inputSchema},null,2)}]};t=i,s=o.arguments??{}}if(!["learn_from_attempts","smart_recall","recall_feedback"].includes(t)){const o=le.find(c=>c.name===t),i=o?os(t,o.inputSchema,s??{}):null;if(i)return{content:[{type:"text",text:i}],isError:!0}}const n=new Set(["session_start","session_start_summary","session_end","auto_learn_session"]);if(!n.has(t)&&!ge&&!Z){const o=$e(s?.instance_id)||N||$e(process.env.CACHLY_BRAIN_INSTANCE_ID);o&&await Is(o).catch(()=>{})}else Z&&await Z.catch(()=>{});n.has(t)||Pt++;try{Xn(),F(`werkzeug ${t}: Anfang`);const o=await J(t,s??{});return F(`werkzeug ${t}: Antwort fertig`),{content:[{type:"text",text:yn(t,o)+Fn()+Zn(t)}]}}catch(o){if(o instanceof Ct)return{content:[{type:"text",text:o.message}],isError:!0};if(o instanceof X)throw o;const i=o.message??String(o);throw Fe("cachly","tool_error",{tool:t,error:i}).catch(()=>{}),new X(ne.InternalError,i)}};K.setRequestHandler(qe,Lt),process.on("SIGTERM",async()=>{await De().catch(()=>{});for(const[,e]of ee)await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await De().catch(()=>{});for(const[,e]of ee)await e.quit().catch(()=>{});process.exit(0)}),process.on("unhandledRejection",e=>{const t=e instanceof Error?e.message:String(e);process.stderr.write(`[cachly-mcp] unhandledRejection: ${t}
|
|
67
67
|
`)}),process.on("uncaughtException",e=>{process.stderr.write(`[cachly-mcp] uncaughtException: ${e?.stack??String(e)}
|
|
68
|
-
`)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function Es(e,t){const
|
|
69
|
-
`)}catch{}}if(
|
|
68
|
+
`)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function Es(e,t){const s=Object.entries(t).map(([n,o])=>`${n}=${o}`);return e==="codex"?{befehl:`codex mcp add cachly ${s.map(n=>`--env ${n}`).join(" ")} -- npx -y @cachly-dev/mcp-server@latest`,wo:"~/.codex/config.toml"}:e==="gemini"?{befehl:`gemini mcp add -s project ${s.map(n=>`-e ${n}`).join(" ")} cachly npx -- -y @cachly-dev/mcp-server@latest`,wo:".gemini/settings.json"}:null}const Ot="https://api.cachly.dev";function Q(e,t,s={}){const n={CACHLY_BRAIN_INSTANCE_ID:t};return s.includeApiKey&&(n.CACHLY_JWT=e),_&&_!==Ot&&(n.CACHLY_API_URL=_),n}function Rs(e,t,s){return s==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:Q(e,t)}]}},null,2):s==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:Q(e,t)},settings:{}}}},null,2):Ht(s)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:Q(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:Q(e,t)}}},null,2)}function Ht(e){return ce[e]===".vscode/mcp.json"}function he(e,t){kn(e)||te(e,t)}async function Mt(e,t,s,n,o,i={}){const c={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:Q(t,s)};if(!o.existsSync(e))return Rs(t,s,n);let r={};try{r=JSON.parse(await o.readFile(e,"utf-8"))}catch{try{const{rename:u}=await import("node:fs/promises");await u(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
|
|
69
|
+
`)}catch{}}if(n==="continue"){const u=r.experimental??{},b=u.modelContextProtocolServers??[];let w;for(const g of b){const a=g.env??{};if(a.CACHLY_JWT){w=a.CACHLY_JWT;break}}w&&he(w,i);const x=b.filter(g=>{const a=g.env??{};return!a.CACHLY_JWT&&!a.CACHLY_BRAIN_INSTANCE_ID});return x.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:c.env}),r.experimental={...u,modelContextProtocolServers:x},JSON.stringify(r,null,2)}if(n==="zed"){const u=r.context_servers??{},w=u.cachly?.command?.env?.CACHLY_JWT;return w&&he(w,i),u.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:c.env},settings:{}},r.context_servers=u,JSON.stringify(r,null,2)}if(Ht(n)){const u=r.mcpServers??void 0,w=u?.cachly?.env?.CACHLY_JWT;w&&he(w,i),u&&"cachly"in u&&(delete u.cachly,Object.keys(u).length===0&&delete r.mcpServers);const x=r.servers??{},g=x.cachly,a=g?.env?.CACHLY_JWT;return a&&he(a,i),x.cachly=g?.envFile?{type:"stdio",...c,envFile:g.envFile}:{type:"stdio",...c},r.servers=x,JSON.stringify(r,null,2)}const d=r.mcpServers??{},l=d.cachly?.env?.CACHLY_JWT;return l&&he(l,i),d.cachly=c,r.mcpServers=d,JSON.stringify(r,null,2)}async function Dt(e,t,s){const{existsSync:n}=await import("node:fs"),{resolve:o}=await import("node:path"),{homedir:i}=await import("node:os"),c=s??i(),r=Vo.filter(l=>Qo(l,e,c,n,o)).map(l=>({path:o(e,...l.pfad),prefix:l.prefix})),d=lt(t),f={};for(const{path:l,prefix:u}of r)try{f[l]=await Zo(l,d,u)}catch(b){f[l]=`failed:${b.message}`}return f}function Ut(e,t){return t.startsWith("failed:")?`\u26A0\uFE0F Could not write ${e}: ${t.slice(7)} (the rest of the setup continues)`:t==="unchanged"?`\u2713 Unchanged: ${e}`:`${t==="updated"?"\u2705 Updated":t==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${e}`}if(process.argv[2]==="digest"){const e=G(),t=U();(!e||!t)&&(console.log(`
|
|
70
70
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
71
71
|
`),process.exit(1)),process.stdout.write(`
|
|
72
72
|
\u{1F9E0} Fetching your weekly Brain digest...
|
|
73
73
|
|
|
74
|
-
`);try{const
|
|
75
|
-
`),
|
|
76
|
-
`))console.log(` ${
|
|
77
|
-
\u274C Could not fetch digest: ${
|
|
78
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="export"){const{writeFile:e,mkdir:t}=await import("node:fs/promises"),{resolve:
|
|
74
|
+
`);try{const s=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`stats HTTP ${s.status}`);const n=await s.json(),o=n.lesson_count??0,i=n.total_recall_count??0,c=Math.round(n.iq_boost_pct??0),r=(n.top_lessons??[]).slice(0,5),d=n.team_authors??[],f=i*1200,l=o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",u=new Date,b=new Date(u);b.setDate(u.getDate()-7);const w=m=>m.toLocaleDateString("en-US",{month:"short",day:"numeric"});if(console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 \x1B[1m\u{1F9E0} Brain Weekly Digest\x1B[0m \x1B[90m${w(b)} \u2013 ${w(u)}\x1B[0m \u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total lessons : \x1B[33m${String(o).padEnd(8)}\x1B[0m Brain level : \x1B[32m${l.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(i).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(c).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+Math.round(f/1e3)+"K (est.)").padEnd(42)}\x1B[0m\u2502`),d.length>0&&(console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1F465} Team contributors:\x1B[0m ${d.slice(0,5).join(", ").slice(0,42).padEnd(42)} \u2502`)),r.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F525} Most recalled lessons this week:\x1B[0m \u2502");for(const m of r){const h=`${m.topic}: ${m.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${h.padEnd(58)}\x1B[0m\u2502`)}}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("");const x=r[0],g=[`\u{1F9E0} My AI Brain weekly digest (${w(b)} \u2013 ${w(u)}):`,"",` \u{1F4DA} ${o} lessons learned`,` \u{1F501} ${i} recalls \xB7 ~${Math.round(f/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${l}`,x?` \u{1F525} Top lesson: "${x.topic}: ${x.what_worked.slice(0,60)}${x.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
|
|
75
|
+
`),a="https://twitter.com/intent/tweet?text="+encodeURIComponent(g);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const m of g.split(`
|
|
76
|
+
`))console.log(` ${m}`);console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m"),console.log(""),console.log(" \x1B[36m\u{1F426} Tweet this:\x1B[0m"),console.log(` \x1B[4m${a.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite <email>\x1B[0m"),console.log(" \x1B[2m Cron: 0 9 * * 1 npx @cachly-dev/mcp-server@latest digest\x1B[0m"),console.log("")}catch(s){console.log(`
|
|
77
|
+
\u274C Could not fetch digest: ${s.message}
|
|
78
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="export"){const{writeFile:e,mkdir:t}=await import("node:fs/promises"),{resolve:s}=await import("node:path"),n=process.argv.slice(3),o=f=>{const l=n.indexOf(`--${f}`);return l!==-1?n[l+1]:void 0},i=o("format")??"both";i!=="md"&&i!=="jsonl"&&i!=="both"&&(console.log(`
|
|
79
79
|
\u274C Unknown --format "${i}" \u2014 use md, jsonl, or both.
|
|
80
|
-
`),process.exit(1));const c=
|
|
80
|
+
`),process.exit(1));const c=s(o("out")??"."),r=v||Le()||"",d=U();(!r||!d)&&(console.log(`
|
|
81
81
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
82
82
|
`),process.exit(1)),process.stdout.write(`
|
|
83
83
|
\u{1F4E4} Exporting your Brain...
|
|
84
84
|
|
|
85
|
-
`);try{let
|
|
86
|
-
`),process.exit(0)),await t(c,{recursive:!0});const
|
|
87
|
-
\u274C Could not export your Brain: ${
|
|
88
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=
|
|
85
|
+
`);try{let f=[],l="";const u=await fetch(`${_}/api/v1/instances/${d}/export`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(12e4)});if(u.ok){const w=await u.json();f=(w.lessons??[]).map(is).filter(x=>x!==null),w.complete===!1?l=w.note??"the server reported an incomplete read":typeof w.lesson_count=="number"&&f.length<w.lesson_count&&(l=`the server counts ${w.lesson_count} lessons, but only ${f.length} could be read as lessons`)}else if(u.status===404){const w=await fetch(`${_}/api/v1/instances/${d}/memory`,{headers:{Authorization:`Bearer ${r}`},signal:AbortSignal.timeout(8e3)});if(!w.ok)throw new Error(`memory HTTP ${w.status}`);f=((await w.json()).top_lessons??[]).map(g=>({topic:g.topic,outcome:g.outcome,severity:g.severity,tags:g.tags,whatWorked:g.what_worked,ts:g.ts,author:g.author,recallCount:g.recall_count})),l="this server has no /export endpoint yet, so this is the DASHBOARD SUMMARY: at most 50 lessons, each shortened to 120 characters. Update the server for a full export."}else throw new Error(`export HTTP ${u.status}`);f.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
|
|
86
|
+
`),process.exit(0)),await t(c,{recursive:!0});const b=[];if(i==="md"||i==="both"){const w=s(c,"lessons.md");await e(w,ns(f),"utf-8"),b.push(`${f.length} lesson${f.length===1?"":"s"} \u2192 ${w}`)}if(i==="jsonl"||i==="both"){const w=s(c,"lessons.jsonl");await e(w,ss(f),"utf-8"),b.push(`${f.length} lesson${f.length===1?"":"s"} \u2192 ${w}`)}l?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${l}`),console.log("")):console.log("\u2705 Export complete:");for(const w of b)console.log(` ${w}`);console.log("")}catch(f){console.log(`
|
|
87
|
+
\u274C Could not export your Brain: ${f.message}
|
|
88
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=G(),t=(process.argv[3]??"").trim();(!t||t.startsWith("-"))&&(console.log(`
|
|
89
|
+
Usage: npx @cachly-dev/mcp-server@latest invite <email>`),console.log(" Example: npx @cachly-dev/mcp-server@latest invite teammate@example.com"),console.log(` Your referral link: npx @cachly-dev/mcp-server@latest refer
|
|
90
|
+
`),process.exit(1)),e||(console.log(`
|
|
89
91
|
\u26A0\uFE0F No cachly key found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
90
|
-
`),process.exit(1));
|
|
92
|
+
`),process.exit(1));const s=U();s||(console.log(`
|
|
93
|
+
\u26A0\uFE0F No Brain selected. Set CACHLY_BRAIN_INSTANCE_ID or run:`),console.log(` npx @cachly-dev/mcp-server@latest setup
|
|
94
|
+
`),process.exit(1));try{const n=await fetch(`${_}/api/v1/instances/${encodeURIComponent(s)}/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({email:t}),signal:AbortSignal.timeout(15e3)});if(n.status===400&&(console.log(`
|
|
95
|
+
\u274C "${t}" is not a valid email address.
|
|
96
|
+
`),process.exit(1)),n.status===404&&(console.log(`
|
|
97
|
+
\u274C This Brain was not found in your account. Only the owner of a Brain can invite people.`),console.log(` Brain: ${s}
|
|
98
|
+
`),process.exit(1)),n.status===409&&(console.log(`
|
|
99
|
+
\u2139\uFE0F ${t} already has access to this Brain. Nothing was sent.
|
|
100
|
+
`),process.exit(1)),!n.ok)throw new Error(`HTTP ${n.status}`);const o=await n.json(),i=o.invite_sent_to??t,c=o.instance?.name??s;console.log(""),console.log(` \u2705 Invitation sent to \x1B[1m${i}\x1B[0m`),console.log(` Brain: \x1B[1m${c}\x1B[0m`),console.log(""),console.log(" They get an email. They accept it in one of two ways:"),console.log(" \u2022 open the link in the email, or"),console.log(" \u2022 run the command from the email: npx @cachly-dev/mcp-server@latest join <token>"),console.log(""),console.log(" Members can read and learn. Deleting the Brain, rotating its password and billing stay with you."),console.log("")}catch(n){console.log(`
|
|
101
|
+
\u274C Could not send the invitation: ${n.message}
|
|
102
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="refer"){const e=G();e||(console.log(`
|
|
103
|
+
\u26A0\uFE0F No cachly key found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
104
|
+
`),process.exit(1));try{const t=await fetch(`${_}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!t.ok)throw new Error(`HTTP ${t.status}`);const s=await t.json(),n=s.url??j(`/r/${s.code}`,"refer"),o=s.referral_count??0,i=`Hey, I've been using cachly to give my AI persistent memory across sessions \u2014 no more re-explaining my stack every morning.
|
|
91
105
|
|
|
92
|
-
You get a free Brain: ${
|
|
106
|
+
You get a free Brain: ${n}`,c=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
|
|
93
107
|
|
|
94
|
-
Try it free: ${
|
|
108
|
+
Try it free: ${n}
|
|
95
109
|
|
|
96
|
-
@cachlydev`);console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F9E0} Your cachly
|
|
97
|
-
`))console.log(`\u2502 \x1B[90m${
|
|
98
|
-
\u274C Could not fetch
|
|
99
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:
|
|
100
|
-
\u274C Usage: npx @cachly-dev/mcp-server@latest join <token>
|
|
101
|
-
`),console.log(
|
|
102
|
-
`),process.exit(1))
|
|
103
|
-
\u23F3 Looking up invite...`);let g;try{const T=await fetch(`${_}/api/invite/${d}`,{signal:AbortSignal.timeout(8e3)});T.status===404&&(console.log(`
|
|
104
|
-
\u274C Invite not found \u2014 the link may be invalid.
|
|
105
|
-
`),process.exit(1)),T.status===410&&(console.log(`
|
|
106
|
-
\u274C This invite link has expired (7-day limit).
|
|
107
|
-
`),process.exit(1)),T.ok||(console.log(`
|
|
108
|
-
\u274C Could not fetch invite: HTTP ${T.status}
|
|
109
|
-
`),process.exit(1)),g=await T.json()}catch(T){console.log(`
|
|
110
|
-
\u274C Network error: ${T.message}
|
|
111
|
-
`),process.exit(1)}const{instance_id:l,instance_name:u,tier:h,label:y}=g,x=new Date(g.expires_at).toLocaleDateString();console.log(""),console.log(" \x1B[35m\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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log(" \x1B[35m\u2551\x1B[0m \x1B[1m\u{1F9E0} Brain Invite\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log(" \x1B[35m\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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Brain : \x1B[1m${u}\x1B[0m`),console.log(` Tier : ${h}`),y&&console.log(` Note : ${y}`),console.log(` Expires : ${x}`),console.log("");const m=a({input:process.stdin,output:process.stdout}),r=await new Promise(T=>{m.question(" Join this Brain? [Y/n] ",I=>{m.close(),T(I.trim().toLowerCase()||"y")})});r!=="y"&&r!=="yes"&&(console.log(`
|
|
112
|
-
Cancelled.
|
|
113
|
-
`),process.exit(0));let p=b;if(!p){console.log(`
|
|
110
|
+
@cachlydev`);console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F9E0} Your cachly referral link \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 ${n.padEnd(61)}\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),o>0&&(console.log(`\u2502 \x1B[32m\u2713 ${o} developer${o===1?"":"s"} joined via your link so far\x1B[0m`.padEnd(72)+"\u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524")),console.log("\u2502 \x1B[33mSlack / DM message:\x1B[0m \u2502"),console.log("\u2502 \u2502");for(const r of i.split(`
|
|
111
|
+
`))console.log(`\u2502 \x1B[90m${r.slice(0,58).padEnd(58)}\x1B[0m \u2502`);console.log("\u2502 \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1D54F} Tweet:\x1B[0m https://twitter.com/intent/tweet?text=${c.slice(0,10)}... \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),console.log("\x1B[2m Each developer who signs up via your link earns you 1 month Pro.\x1B[0m"),console.log("\x1B[2m To give someone access to your Brain: npx @cachly-dev/mcp-server@latest invite <email>\x1B[0m"),console.log("")}catch(t){console.log(`
|
|
112
|
+
\u274C Could not fetch referral link: ${t.message}
|
|
113
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:s}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:o,dirname:i}=await import("node:path"),{homedir:c}=await import("node:os"),{createInterface:r}=await import("node:readline"),d=dt(process.argv,"brain"),f=d===void 0&&process.argv[3]&&!process.argv[3].startsWith("-")?process.argv[3]:"";!f&&!d&&(console.log(`
|
|
114
|
+
\u274C Usage: npx @cachly-dev/mcp-server@latest join <token>`),console.log(` npx @cachly-dev/mcp-server@latest join --brain <instance-id>
|
|
115
|
+
`),console.log(" The token is in the invitation email. A teammate sends one with:"),console.log(` npx @cachly-dev/mcp-server@latest invite <email>
|
|
116
|
+
`),process.exit(1));let l=v;if(!l){console.log(`
|
|
114
117
|
No API key found \u2014 starting sign-in (10 seconds)...
|
|
115
|
-
`);try{const
|
|
116
|
-
`);const
|
|
118
|
+
`);try{const h=await fetch(`${_}/api/v1/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(1e4)});if(h.ok){const p=await h.json();console.log(` \u{1F449} Open: \x1B[36m${p.verification_uri}\x1B[0m`),console.log(` Code: \x1B[1m${p.user_code}\x1B[0m
|
|
119
|
+
`);const S=(p.interval??5)*1e3;for(let C=0;C<24;C++){await new Promise(k=>setTimeout(k,S));try{const k=await fetch(`${_}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:p.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(k.ok){const I=await k.json();if(I.access_token){l=I.access_token;break}}}catch{}}l||(console.log(`
|
|
117
120
|
\u274C Sign-in timed out. Run the command again.
|
|
118
121
|
`),process.exit(1)),console.log(` \u2705 Signed in!
|
|
119
|
-
`)}}catch(
|
|
120
|
-
\u26A0\uFE0F Could not start sign-in: ${
|
|
121
|
-
`),process.exit(1)}}
|
|
122
|
+
`)}}catch(h){console.log(`
|
|
123
|
+
\u26A0\uFE0F Could not start sign-in: ${h.message}`),console.log(` Set CACHLY_JWT manually from ${j("/setup-ai","join")}
|
|
124
|
+
`),process.exit(1)}}l||(console.log(`
|
|
125
|
+
\u274C Sign-in did not return a key. Run the command again.
|
|
126
|
+
`),process.exit(1));const u={Authorization:`Bearer ${l}`};let b="",w="";if(d){console.log(`
|
|
127
|
+
\u23F3 Checking access to Brain ${d}...`);try{const h=await fetch(`${_}/api/v1/instances/${encodeURIComponent(d)}`,{headers:u,signal:AbortSignal.timeout(1e4)});h.status===401&&(console.log(`
|
|
128
|
+
\u274C Your key was not accepted. Sign in again: npx @cachly-dev/mcp-server@latest autopilot
|
|
129
|
+
`),process.exit(1)),(h.status===403||h.status===404)&&(console.log(`
|
|
130
|
+
\u274C You do not have access to this Brain (or it does not exist).`),console.log(` Ask the owner for an invitation: invite <your-email>. Accept it, then run this command again.
|
|
131
|
+
`),process.exit(1)),h.ok||(console.log(`
|
|
132
|
+
\u274C Could not check the Brain: HTTP ${h.status}
|
|
133
|
+
`),process.exit(1));const p=await h.json();b=p.id??d,w=p.name??b}catch(h){console.log(`
|
|
134
|
+
\u274C Network error: ${h.message}
|
|
135
|
+
`),process.exit(1)}}else{console.log(`
|
|
136
|
+
\u23F3 Accepting invitation...`);let h=null,p="";try{const k=await fetch(`${_}/api/v1/orgs/accept-invite`,{method:"POST",headers:{...u,"Content-Type":"application/json"},body:JSON.stringify({token:f}),signal:AbortSignal.timeout(15e3)});if(k.ok){const I=await k.json();h=I.data&&typeof I.data=="object"?I.data:I}else p=k.status===401?"your key was not accepted (HTTP 401)":`HTTP ${k.status}`}catch(k){console.log(`
|
|
137
|
+
\u274C Network error: ${k.message}
|
|
138
|
+
`),process.exit(1)}if(!h){let k=!1;try{k=(await fetch(`${_}/api/invite/${encodeURIComponent(f)}`,{signal:AbortSignal.timeout(8e3)})).ok}catch{}k?(console.log(`
|
|
139
|
+
\u274C This old link type does not give access to the Brain.`),console.log(` Ask the owner for a new invitation: npx @cachly-dev/mcp-server@latest invite <your-email>
|
|
140
|
+
`)):(console.log(`
|
|
141
|
+
\u274C Could not accept the invitation: ${p}.`),console.log(` The token may be wrong, expired or already used. Ask for a new invitation.
|
|
142
|
+
`)),process.exit(1)}const S=(h.instances??[]).filter(k=>k&&k.id);S.length===0&&(console.log(`
|
|
143
|
+
\u2705 Invitation accepted, but this organisation has no Brain yet.`),console.log(` When the owner adds one, connect it with: npx @cachly-dev/mcp-server@latest join --brain <instance-id>
|
|
144
|
+
`),process.exit(0));let C=S[0];if(S.length>1){console.log(`
|
|
145
|
+
This organisation has several Brains:`),S.forEach(($,R)=>console.log(` ${R+1}) ${$.name??$.id} (${$.id})`));const k=r({input:process.stdin,output:process.stdout}),I=await new Promise($=>{k.question(" Which one? [1] ",R=>{k.close(),$(R.trim()||"1")})}),E=Number.parseInt(I,10);(!Number.isInteger(E)||E<1||E>S.length)&&(console.log(`
|
|
146
|
+
Cancelled.
|
|
147
|
+
`),process.exit(1)),C=S[E-1]}b=C.id,w=C.name??C.id,console.log(`
|
|
148
|
+
\u2705 Invitation accepted. Brain: \x1B[1m${w}\x1B[0m
|
|
149
|
+
`)}l!==v&&te(l);const x=process.cwd(),g=c(),a=[{label:".mcp.json (Claude Code project)",path:o(x,".mcp.json")},{label:".cursor/mcp.json",path:o(x,".cursor","mcp.json")},{label:".windsurf/mcp.json",path:o(x,".windsurf","mcp.json")},{label:".vscode/mcp.json (Copilot/Cline)",path:o(x,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:o(g,".claude","mcp.json"),global:!0}];let m=0;for(const{label:h,path:p,global:S}of a){const C=i(p);if(!(!S&&!n(C)&&!n(p)))try{await s(C,{recursive:!0});let k={};if(n(p))try{k=JSON.parse(await t(p,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(p,p+".bak")}catch{}}const I=k.mcpServers??{},E=I.cachly??{},$=E.env??{};$.CACHLY_BRAIN_INSTANCE_ID=b,l&&S&&!$.CACHLY_JWT&&($.CACHLY_JWT=l),_!==Ot&&($.CACHLY_API_URL=_),I.cachly={...E,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:$},k.mcpServers=I,await e(p,JSON.stringify(k,null,2),"utf-8"),console.log(` \u2705 ${h}`),m++}catch(k){k.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${h}: ${k.message}`)}}console.log(""),m===0?console.log(" \u26A0\uFE0F No editor configs found \u2014 run `cachly setup` first.\n"):(console.log(` \u{1F9E0} You're now sharing Brain: \x1B[1m${w}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
|
|
122
150
|
`),console.log(" \u{1F4DB} Add the badge to your README:"),console.log(` npx @cachly-dev/mcp-server@latest badge
|
|
123
151
|
`)),process.exit(0)}if(process.argv[2]==="upgrade"){process.stdout.write(`
|
|
124
152
|
\u23F3 Checking for updates...
|
|
125
|
-
`);try{const e=await fetch("https://registry.npmjs.org/@cachly-dev/mcp-server/latest",{signal:AbortSignal.timeout(8e3)});if(!e.ok)throw new Error(`registry HTTP ${e.status}`);const
|
|
126
|
-
\u2705 Already on the latest version: \x1B[32mv${
|
|
127
|
-
`):(console.log(""),console.log("\x1B[35m \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly update available\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Current : \x1B[31mv${
|
|
153
|
+
`);try{const e=await fetch("https://registry.npmjs.org/@cachly-dev/mcp-server/latest",{signal:AbortSignal.timeout(8e3)});if(!e.ok)throw new Error(`registry HTTP ${e.status}`);const s=(await e.json()).version;if(!s||!/^\d+\.\d+\.\d+/.test(s))throw new Error("npm registry returned unexpected response");s===H?console.log(`
|
|
154
|
+
\u2705 Already on the latest version: \x1B[32mv${H}\x1B[0m
|
|
155
|
+
`):(console.log(""),console.log("\x1B[35m \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly update available\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Current : \x1B[31mv${H}\x1B[0m`),console.log(` Latest : \x1B[32mv${s}\x1B[0m`),console.log(""),console.log(" Update your editor configs to pick up the new version:"),console.log(""),console.log(" \x1B[32m npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(""),console.log(" \x1B[2m(npx always fetches the latest when @latest is specified)\x1B[0m"),console.log(""))}catch(e){console.log(`
|
|
128
156
|
\u274C Could not check for updates: ${e.message}
|
|
129
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:
|
|
130
|
-
\u274C bench failed: ${
|
|
131
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{existsSync:e,readFileSync:t}=await import("node:fs"),{resolve:
|
|
157
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:s}=await import("node:path"),{loadExternalCorpus:n,runExternalBenchmark:o}=await import("./bench/external-corpus.js"),i=process.argv.includes("--json"),c=process.argv.slice(3).find(f=>!f.startsWith("--")),r=t(e(import.meta.url)),d=c?s(process.cwd(),c):s(r,"bench","external","sample-corpus.json");try{const f=await n(d),l=await o(f);i&&(console.log(JSON.stringify({corpus:f.name,lessons:l.corpusSize,queries:l.queryCount,cachly_p1:Math.round(l.cachly.precisionAt1*1e3)/10,flatfile_p1:Math.round(l.flatfile.precisionAt1*1e3)/10,cachly_mrr:Math.round(l.cachly.mrr*1e3)/10,flatfile_mrr:Math.round(l.flatfile.mrr*1e3)/10,p1_lift_vs_flatfile_pct:Math.round((l.cachly.precisionAt1-l.flatfile.precisionAt1)*1e3)/10,mrr_lift_vs_flatfile_pct:Math.round((l.cachly.mrr-l.flatfile.mrr)*1e3)/10},null,2)),process.exit(0));const u=((l.cachly.precisionAt1-l.flatfile.precisionAt1)*100).toFixed(1),b=((l.cachly.mrr-l.flatfile.mrr)*100).toFixed(1),w=((l.cachly.precisionAt1-l.baseline.precisionAt1)*100).toFixed(1),x=l.cachly.precisionAt1>=l.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",g=l.cachly.mrr>=l.flatfile.mrr?"\x1B[32m+":"\x1B[31m";console.log(""),console.log("\x1B[35m \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\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\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly recall quality benchmark\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \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\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\x1B[0m"),console.log(""),console.log(` Corpus : ${f.name??d}`),console.log(` Dataset: ${l.corpusSize} lessons \xB7 ${l.queryCount} queries \xB7 10 engineering domains`),console.log(" (k8s, DB, auth, CI, frontend, API, payments, observability, Node.js, infra)"),console.log(""),console.log(" \x1B[1mPrecision@1\x1B[0m (finds the right lesson at rank #1):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.precisionAt1*100).toFixed(1)}%\x1B[0m (naive keyword overlap \u2014 no quality signal)`),console.log(` raw BM25 : \x1B[33m${(l.baseline.precisionAt1*100).toFixed(1)}%\x1B[0m (keyword ranking)`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.precisionAt1*100).toFixed(1)}%\x1B[0m (BM25 + quality reranking)`),console.log(""),console.log(" \x1B[1mMean Reciprocal Rank\x1B[0m (average rank of the right answer):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` raw BM25 : \x1B[33m${(l.baseline.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.mrr*100).toFixed(1)}%\x1B[0m`),console.log(""),console.log(" \x1B[1mLift vs flat-file memory\x1B[0m (what you get by switching from plain memory files):"),console.log(` Precision@1 : ${x}${u}%\x1B[0m`),console.log(` MRR : ${g}${b}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${w}%\x1B[0m Precision@1 (quality reranking on top of keyword search)`),console.log(""),console.log(" \x1B[2mFlat-file = lexical overlap over raw text files (how Anthropic/Claude Memory works).\x1B[0m"),console.log(" \x1B[2mAdversarial distractors included \u2014 failure lessons that share the exact query vocabulary.\x1B[0m"),console.log(" \x1B[2mcachly ignores them because they have low confidence / failed outcome.\x1B[0m"),console.log(""),console.log(" Share your results:"),console.log(` \x1B[36m"My Brain: Precision@1 ${(l.cachly.precisionAt1*100).toFixed(1)}% (${x}${u}% vs flat-file memory, ${l.queryCount} queries)"\x1B[0m`),console.log(""),console.log(" Run on a custom corpus:"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench my-incidents.json\x1B[0m"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench --json # machine-readable\x1B[0m"),console.log(""),console.log(" \x1B[1m\u2192 Give your AI this recall quality on your own work (free, 1\u20135 min):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(" \x1B[90m Signs in, configures every editor, bootstraps from your git history.\x1B[0m"),console.log(` \x1B[90m Or create your Brain at: \x1B[36m${j("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(f){console.error(`
|
|
158
|
+
\u274C bench failed: ${f.message}
|
|
159
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{existsSync:e,readFileSync:t}=await import("node:fs"),{resolve:s,basename:n}=await import("node:path"),o=process.cwd();console.log(`
|
|
132
160
|
\x1B[35m\u{1F9E0} cachly Brain \u2014 Live Demo\x1B[0m`),console.log(`\x1B[90mNo account needed. Reading your git history...\x1B[0m
|
|
133
|
-
`),e(
|
|
161
|
+
`),e(s(o,".git"))||(console.log("\u26A0\uFE0F No git repository found here."),console.log(` Run this command inside a project directory with git history.
|
|
134
162
|
`),console.log(` Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo
|
|
135
|
-
`),process.exit(0));let i="";try{i=
|
|
136
|
-
`),process.exit(0)}const d=
|
|
137
|
-
`).filter(Boolean).map($=>{const[
|
|
138
|
-
`),process.exit(0));const
|
|
163
|
+
`),process.exit(0));let i="";try{i=ut(o,["config","user.name"]).trim().split(" ")[0]??""}catch{}let c=n(o);try{const $=JSON.parse(t(s(o,"package.json"),"utf-8"));$.name&&(c=$.name.replace(/^@[^/]+\//,""))}catch{}let r="";try{r=ut(o,["log","HEAD","--pretty=format:%H|||%s|||%ad|||%an","--date=short","--no-merges","-n","200"],{timeoutMs:3e4})}catch{console.log(`\u26A0\uFE0F Could not read git log. Make sure you have commits.
|
|
164
|
+
`),process.exit(0)}const d=r.trim().split(`
|
|
165
|
+
`).filter(Boolean).map($=>{const[R,M,Ce,oe]=$.split("|||");return{sha:(R??"").trim().slice(0,8),subject:(M??"").trim(),date:(Ce??"").trim(),author:(oe??"").trim()}});d.length===0&&(console.log(`\u26A0\uFE0F No commits found.
|
|
166
|
+
`),process.exit(0));const f=new Map,l=[],u=[],b=[],w=new Set;let x=0;for(const $ of d){const R=ms($.subject);f.set(R,(f.get(R)??0)+1),gs($.subject)&&x++,R==="fix"&&l.length<5&&l.push($.subject.slice(0,72)),R==="feat"&&u.length<5&&u.push($.subject.slice(0,72)),R==="security"&&b.length<3&&b.push($.subject.slice(0,72)),$.author&&w.add($.author)}const g=hs(d.map($=>$.subject)),a=`${d[d.length-1]?.date??"?"} \u2192 ${d[0]?.date??"?"}`,m=g>=501?"Oracle":g>=201?"Architect":g>=51?"Expert":g>=11?"Explorer":"Apprentice",p=`${i?`Hey ${i} \u2014 `:""}here's what your AI would know about ${c}`;process.stdout.write("\x1B[2K\r"),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 \x1B[1m\u{1F9E0} ${p.slice(0,58).padEnd(58)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Commits analysed : \x1B[33m${String(d.length).padEnd(6)}\x1B[0m Date range: \x1B[90m${a.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(g).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(w.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${m.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(x).padEnd(21)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const S=[...f.entries()].filter(([$])=>$!=="chore").sort(($,R)=>R[1]-$[1]),C=($,R)=>"\u2588".repeat(Math.round($/R*20)).padEnd(20),k=Math.max(...S.map(([,$])=>$),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[$,R]of S){const M={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[$]??"\u2022";console.log(`\u2502 ${M} \x1B[36m${$.padEnd(10)}\x1B[0m \x1B[35m${C(R,k)}\x1B[0m \x1B[33m${String(R).padStart(3)}\x1B[0m \u2502`)}if(b.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[31m\u{1F512} Security fixes your AI would know:\x1B[0m \u2502");for(const $ of b)console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(l.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F527} Bug fixes your AI would never repeat:\x1B[0m \u2502");for(const $ of l.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(u.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[32m\u2728 Features & decisions it would recall:\x1B[0m \u2502");for(const $ of u.slice(0,3))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[32m\u{1F4A1} With cachly, your AI arrives pre-briefed every session.\x1B[0m \u2502"),console.log("\u2502 \x1B[32m No more re-explaining. No more repeated mistakes.\x1B[0m \u2502"),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("");const I=new URLSearchParams({repo:c,commits:String(d.length),lessons:String(g),level:m,authors:String(w.size),reverts:String(x)}),E=j(`/preview?${I.toString()}`,"demo");console.log(" \x1B[1mMake this permanent (free, 1\u20135 minutes):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(""),console.log(` \x1B[90m\u{1F517} Shareable preview:\x1B[0m \x1B[36m${E}\x1B[0m`),console.log(""),console.log(" Works with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 Copilot \xB7 Cline \xB7 Zed"),console.log(" GDPR \xB7 German servers \xB7 free tier, no credit card"),console.log(""),process.exit(0)}if(process.argv[2]==="share"){const e=G(),t=U();(!e||!t)&&(console.log(`
|
|
139
167
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
|
|
140
168
|
`),process.exit(1)),process.stdout.write(`
|
|
141
169
|
\u{1F9E0} Fetching your Brain stats...
|
|
142
|
-
`);try{const
|
|
170
|
+
`);try{const s=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`HTTP ${s.status}`);const n=await s.json(),o=n.lesson_count??0,i=n.total_recall_count??0,c=Math.round(n.iq_boost_pct??0),r=i*1200,d=o===0?"Intern \u{1F331}":o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}";console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F9E0} My AI Brain \xB7 powered by \x1B[35mcachly.dev\x1B[0m \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Lessons stored : \x1B[33m${String(o).padEnd(8)}\x1B[0m Brain level: \x1B[32m${d.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(i).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(c).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+(r/1e3).toFixed(0)+"K (est.)").padEnd(42)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 Works with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 Copilot \u2502"),console.log("\u2502 Free \xB7 GDPR \xB7 German servers \u2502"),console.log("\u2502 \x1B[35mnpx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2502"),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("");const f=j("/","share"),l=`\u{1F9E0} My AI coding assistant now has persistent memory.
|
|
143
171
|
|
|
144
172
|
${o} lessons stored \xB7 ${i} recalls \xB7 ${d}
|
|
145
173
|
|
|
146
174
|
Fix a bug once \u2192 AI remembers forever. Across Claude Code, Cursor, Windsurf, Copilot.
|
|
147
175
|
|
|
148
|
-
${
|
|
176
|
+
${f}
|
|
149
177
|
|
|
150
178
|
#AIMemory #ClaudeCode #Cursor #DeveloperTools`;console.log(" \x1B[1m\u{1F4CB} Share on Twitter/X (copy this):\x1B[0m"),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"),console.log(l.split(`
|
|
151
179
|
`).map(u=>` ${u}`).join(`
|
|
152
|
-
`)),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"),console.log(""),console.log(" \x1B[2mPro tip: add a screenshot of your Brain panel for 3x more engagement\x1B[0m"),console.log(" \x1B[2mAlso add a live badge to your README:\x1B[0m"),console.log(" \x1B[90m npx @cachly-dev/mcp-server@latest badge\x1B[0m"),console.log("")}catch(
|
|
153
|
-
\u274C Could not fetch stats: ${
|
|
154
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="publish"){const e=
|
|
180
|
+
`)),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"),console.log(""),console.log(" \x1B[2mPro tip: add a screenshot of your Brain panel for 3x more engagement\x1B[0m"),console.log(" \x1B[2mAlso add a live badge to your README:\x1B[0m"),console.log(" \x1B[90m npx @cachly-dev/mcp-server@latest badge\x1B[0m"),console.log("")}catch(s){console.log(`
|
|
181
|
+
\u274C Could not fetch stats: ${s.message}
|
|
182
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="publish"){const e=G(),t=U();(!e||!t)&&(console.log(`
|
|
155
183
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
156
|
-
`),process.exit(1));const
|
|
184
|
+
`),process.exit(1));const s=process.argv.indexOf("--title"),n=s!==-1?process.argv[s+1]??"My Brain Snapshot":"My Brain Snapshot",o=process.argv.includes("--public");process.stdout.write(`
|
|
157
185
|
\u{1F9E0} Publishing Brain snapshot...
|
|
158
|
-
`);try{const i=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let c=0,
|
|
186
|
+
`);try{const i=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let c=0,r=0;if(i.ok){const b=await i.json();c=b.lesson_count??0,r=b.total_recall_count??0}const d=await fetch(`${_}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:n,visibility:o?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!d.ok)throw new Error(`HTTP ${d.status}`);const l=(await d.json()).share_id??"unavailable",u=j(`/brain/share/${l}`,"publish");console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F4E4} Brain Published \xB7 powered by \x1B[35mcachly.dev\x1B[0m \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Title : \x1B[33m${n.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(c).padEnd(10)}\x1B[0m Recalls: \x1B[36m${String(r).padEnd(26)}\x1B[0m\u2502`),console.log(`\u2502 Visibility: \x1B[${o?"32":"33"}m${(o?"public (discoverable)":"unlisted (link only)").padEnd(44)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[1mShare URL:\x1B[0m \x1B[36m${u.padEnd(51)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[2mAnyone can import with:\x1B[0m \u2502"),console.log(`\u2502 \x1B[90m brain_import(instance_id="...", share_id="${l.slice(0,17)}")\x1B[0m\u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),console.log(" \x1B[1m\u{1F4CB} Share this with your team:\x1B[0m"),console.log(` ${u}`),console.log(""),console.log(` \x1B[2mTo list all your shares:\x1B[0m brain_share_list(instance_id="${t.slice(0,24)}...")`),console.log(` \x1B[2mTo revoke this share:\x1B[0m brain_unshare(share_id="${l.slice(0,24)}...")`),console.log("")}catch(i){console.log(`
|
|
159
187
|
\u274C Could not publish Brain: ${i.message}
|
|
160
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="tool-specs"||process.argv[2]==="openapi"){const{renderToolSpecs:e}=await import("./toolspecs.js");let t="openapi";if(process.argv[2]!=="openapi"){const
|
|
161
|
-
\u274C Unknown format "${t}". Use one of: ${
|
|
188
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="tool-specs"||process.argv[2]==="openapi"){const{renderToolSpecs:e}=await import("./toolspecs.js");let t="openapi";if(process.argv[2]!=="openapi"){const n=process.argv.find(o=>o.startsWith("--format="));if(n)t=n.slice(9);else{const o=process.argv.indexOf("--format");o!==-1&&(t=process.argv[o+1]??"openapi")}}const s=["openapi","openai","anthropic","langchain"];s.includes(t)||(process.stderr.write(`
|
|
189
|
+
\u274C Unknown format "${t}". Use one of: ${s.join(", ")}
|
|
162
190
|
|
|
163
|
-
`),process.exit(1)),process.stdout.write(e(
|
|
164
|
-
`,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=
|
|
191
|
+
`),process.exit(1)),process.stdout.write(e(le,t,H)+`
|
|
192
|
+
`,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=U();e||(console.log(`
|
|
165
193
|
\u26A0\uFE0F No Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
|
|
166
|
-
`),process.exit(1));const t=`${_}/api/v1/badge/${e}`,
|
|
167
|
-
`,()=>process.exit(0)),await new Promise(()=>{})),
|
|
168
|
-
Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||
|
|
169
|
-
Missing value for ${
|
|
170
|
-
`),process.exit(1));let l=d("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,u=d("api-key")??process.env.CACHLY_JWT;const
|
|
194
|
+
`),process.exit(1));const t=`${_}/api/v1/badge/${e}`,s=j("/","badge"),n=`[](${s})`,o=`<a href="${s}"><img src="${t}" alt="cachly Brain" /></a>`;console.log(""),console.log("\x1B[35m \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly Brain Badge\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Paste into your README.md:"),console.log(""),console.log(` \x1B[32m${n}\x1B[0m`),console.log(""),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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${o}\x1B[0m`),console.log(""),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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Badge URL (live, updates every hour):"),console.log(` \x1B[90m${t}\x1B[0m`),console.log(""),console.log(" \x1B[2mThe badge shows your current lesson count \u2014 no auth required,"),console.log(" safe to embed in public repos. Updates hourly.\x1B[0m"),console.log(""),process.exit(0)}const fe=Xo(process.argv[2],process.stdin.isTTY===!0&&process.stdout.isTTY===!0);if(fe==="version"&&(process.stdout.write(`${H}
|
|
195
|
+
`,()=>process.exit(0)),await new Promise(()=>{})),fe==="unbekannt"&&console.error(`
|
|
196
|
+
Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||fe==="hilfe"||fe==="unbekannt"){console.log(""),console.log("\x1B[35m \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly \u2014 Persistent AI Memory for Developers\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Stop re-teaching your AI every morning."),console.log(" cachly gives it a permanent brain \u2014 pre-briefed every session."),console.log("");const e=(t,s)=>console.log(` \x1B[36m ${t.padEnd(22)}\x1B[0m ${s}`);console.log(" \x1B[1mStart:\x1B[0m \x1B[1m\x1B[32mnpx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2190 \x1B[1mOne command, fully ready\x1B[0m"),console.log(" Every command below runs as: npx @cachly-dev/mcp-server@latest <command>"),console.log(""),console.log(" \x1B[1mEvery day:\x1B[0m"),e("status","Lessons, recalls and team at a glance"),e("ambient-stats","Tokens injected vs saved \u2014 the honest net, even when negative"),e("doctor","Diagnose a broken or missing install"),e("health","Check key, API, editor configs and git hook"),e("digest","What your Brain learned this week"),console.log(" \x1B[1mSet up:\x1B[0m"),e("demo","Try it first (no account)"),e("setup","Interactive setup (pick editors)"),e("init","Write the config for one editor (flags)"),e("claim","Keep a test Brain in your own account"),e("upgrade","Check for updates"),e("uninstall","Take cachly out of this project (--dry-run first)"),console.log(" \x1B[1mYour data:\x1B[0m"),e("export","Write your lessons to disk (md / jsonl)"),e("index [dir]","Index a project into the Brain (CI)"),e("learn-git [repo]","Learn lessons from recent commits (CI)"),console.log(" \x1B[1mTeam & sharing:\x1B[0m"),e("invite <email>","Share your Brain with a teammate (sends an email)"),e("join <token>","Accept an invitation to a shared Brain"),e("join --brain <id>","Connect a Brain you already have access to"),e("refer","Your referral link for new users"),e("share","Share your Brain stats"),e("publish","Publish an importable Brain snapshot"),e("badge","README badge for your Brain"),console.log(" \x1B[1mMore:\x1B[0m"),e("bench","Recall quality vs flat-file memory"),e("tool-specs | openapi","Tool definitions for other agent frameworks"),console.log(""),console.log(" \x1B[90mWorks with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 GitHub Copilot \xB7 Cline \xB7 Zed\x1B[0m"),console.log(` \x1B[90mGDPR \xB7 German servers \xB7 ${le.length} MCP tools\x1B[0m`),console.log(""),process.exit(fe==="unbekannt"?1:0)}const js={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:dn,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:un,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:pn,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function Bs(e,t,s){if(!t)return;const{datei:n,name:o,wie:i}=js[e];if(t.hooks==="skipped"){console.log(`\u26A0\uFE0F ${s}${n} ${t.grund??"is not valid JSON"} \u2014 left untouched, ${o} hooks not wired`);return}const c=t.hooks==="unchanged"?"\u2713 ":"\u2705 ",r=t.hooks==="written"?"Written":t.hooks==="merged"?"Merged":"Already wired";console.log(`${c}${s}${r}: ${n} (Ambient Recall for ${o} \u2014 ${i})`)}async function Ue(e,t,s,n){const o=e==="codex"?"Codex":"Gemini CLI",i=await(e==="codex"?_n:$n)(t,s).catch(()=>null);if(!i||i.status==="skipped"){const d=Es(e,s);console.log(`\u26A0\uFE0F ${n}${i?`${i.datei} ${i.grund??"could not be read"} \u2014 left untouched.`:`${o} MCP entry could not be written.`} Register cachly yourself:`),d&&console.log(` ${n}${d.befehl}`);return}const c=i.status==="unchanged"?"\u2713 ":"\u2705 ",r=i.status==="written"?"Written":i.status==="updated"?"Updated":"Already configured";console.log(`${c}${n}${r}: ${i.datei} (MCP server cachly for ${o} \u2014 it asks once to trust this folder; until then the server stays off)`)}async function ye(e,t,s,n){const o={cursor:rn,copilot:an,codex:cn,gemini:ln}[e];Bs(e,await o(t,s).catch(()=>null),n)}if(process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:s,readFile:n}=await import("node:fs/promises"),{resolve:o,dirname:i,relative:c}=await import("node:path"),r=process.argv.slice(3),d=p=>dt(r,p),f=en(r,["instance-id","api-key","editor","project-dir","api-url"]);f.length>0&&(console.error(`
|
|
197
|
+
Missing value for ${f.map(p=>`--${p}`).join(", ")}. Nothing was written.
|
|
198
|
+
`),process.exit(1));let l=d("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,u=d("api-key")??process.env.CACHLY_JWT;const b=(d("editor")??"claude").toLowerCase(),w=o(d("project-dir")??"."),x=d("api-url");if(x&&(_=x.replace(/\/+$/,"")),!l||!u){const p=xe(),S=_e();p&&S&&(u??=p,l??=S,u===p&&l===S&&console.log("\u2713 Reusing credentials from ~/.cachly/credentials.json (saved by a prior setup)"))}if(!l||!u)try{const{existsSync:p}=await import("node:fs"),S=process.env.HOME??process.env.USERPROFILE??"",C=S?o(S,".claude","mcp.json"):"";if(C&&p(C)){const I=JSON.parse(await n(C,"utf-8")).mcpServers?.cachly?.env??{};u??=I.CACHLY_JWT,l??=I.CACHLY_BRAIN_INSTANCE_ID,u&&l&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!l||!u)&&(console.error(`
|
|
171
199
|
Usage: npx @cachly-dev/mcp-server@latest init --instance-id <uuid> --api-key <cky_live_...> [--editor claude|cursor|windsurf|copilot|continue|cline|zed|codex|gemini] [--project-dir /path] [--api-url https://your-self-hosted-backend]
|
|
172
200
|
`),console.error(`First time? Run the zero-config wizard (signs you in, auto-provisions): npx @cachly-dev/mcp-server@latest autopilot
|
|
173
201
|
`),console.error(`Get your credentials from: ${j("/setup-ai","init")}
|
|
174
|
-
`),process.exit(1));const
|
|
175
|
-
Nothing was written:`);for(const
|
|
176
|
-
The server does not accept this key and instance (HTTP ${
|
|
177
|
-
`),process.exit(1))}catch{console.log("\u26A0\uFE0F Could not reach the server to check the key \u2014 writing the config anyway.")}const
|
|
178
|
-
\u2705 ${
|
|
179
|
-
\u2713 Already configured: ${
|
|
180
|
-
\u{1F9E0} Cachly AI Brain configured for ${
|
|
202
|
+
`),process.exit(1));const g=tn({instanceId:l,apiKey:u,editor:b},[...Object.keys(ce),"codex","gemini"]);if(g.length>0){console.error(`
|
|
203
|
+
Nothing was written:`);for(const p of g)console.error(` - ${p}`);console.error(""),process.exit(1)}try{const p=await fetch(`${_}/api/v1/instances/${l}/memory`,{headers:{Authorization:`Bearer ${u}`},signal:AbortSignal.timeout(8e3)});(p.status===401||p.status===403||p.status===404)&&(console.error(`
|
|
204
|
+
The server does not accept this key and instance (HTTP ${p.status}). Nothing was written.`),console.error(`Get your credentials from: ${j("/setup-ai","init")}
|
|
205
|
+
`),process.exit(1))}catch{console.log("\u26A0\uFE0F Could not reach the server to check the key \u2014 writing the config anyway.")}const a=()=>{te(u),_e()||ve(l,{apiKey:u})};if(b==="codex"||b==="gemini")a(),console.log(""),await Ue(b,w,Q(u,l),"");else{const p=ce[b]??".mcp.json",S=o(w,p);await s(i(S),{recursive:!0});const{existsSync:C}=await import("node:fs"),k=C(S),I=k?await n(S,"utf-8").catch(()=>""):"";a();const E=await Mt(S,u,l,b,{readFile:n,existsSync:C});E!==I?(await t(S,E,"utf-8"),console.log(`
|
|
206
|
+
\u2705 ${k?"Updated":"Written"}: ${p}`)):console.log(`
|
|
207
|
+
\u2713 Already configured: ${p} (no change)`)}const m=await Dt(w,l);for(const[p,S]of Object.entries(m))console.log(Ut(p.split(/[\\/]/).pop()??p,S));try{const p=await at(w,l),S=c(w,o(Ko(w),"post-commit")).replace(/\\/g,"/");p==="written"?console.log(`\u2705 Written: ${S} (CLS hook)`):p==="upgraded"?console.log(`\u2705 Upgraded: ${S} (CLS hook \u2192 ${ct})`):p==="appended"?console.log(`\u2705 Appended: ${S} (CLS hook)`):p==="unchanged"&&console.log(`\u2713 CLS hook already current in ${S}`)}catch{}if(b==="claude")try{const p=await pt(w,l);if(p.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${p.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const S=p.scripts==="written"?"\u2705 Written":p.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${mt})`:"\u2713 Unchanged";console.log(`${S}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),p.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):p.settings==="merged"?console.log("\u2705 Merged: .claude/settings.json (Ambient Recall hooks wired)"):console.log("\u2713 Ambient Recall hooks already wired in .claude/settings.json")}}catch{}(b==="cursor"||b==="copilot"||b==="codex"||b==="gemini")&&await ye(b,w,l,"");const h=((Date.now()-e)/1e3).toFixed(1);console.log(`
|
|
208
|
+
\u{1F9E0} Cachly AI Brain configured for ${b==="claude"?"Claude Code":b}! (${h}s)`),console.log(b==="codex"||b==="gemini"?` Start ${b} in this folder and trust it when asked \u2014 the \`cachly\` MCP tools will appear.`:" Restart your editor \u2014 the `cachly` MCP tools will appear."),console.log(" Re-run `init` anytime \u2014 it's idempotent (only writes what changed)."),console.log(`
|
|
181
209
|
\u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
|
|
182
|
-
`),process.exit(0)}if(process.argv[2]==="status"){const e=
|
|
210
|
+
`),process.exit(0)}if(process.argv[2]==="status"){const e=G(),t=U();(!e||!t)&&(console.log(`
|
|
183
211
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
184
|
-
`),process.exit(1));try{const[n
|
|
185
|
-
\u274C Could not fetch status: ${
|
|
186
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="health"){const{existsSync:e}=await import("node:fs"),{readFile:t}=await import("node:fs/promises"),{resolve:
|
|
212
|
+
`),process.exit(1));try{const[s,n]=await Promise.all([fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${_}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)})]);if(!s.ok)throw new Error(`stats HTTP ${s.status}`);const o=await s.json(),i=n.ok?await n.json():null,c=o.lesson_count??0,r=o.total_recall_count??0,d=Math.round(o.iq_boost_pct??0),f=o.team_authors??[],l=i?.referral_count??0,u=i?.url??"",b=c===0?"Intern \u{1F331}":c<10?"Junior Dev \u{1F527}":c<30?"Mid Dev \u26A1":c<60?"Senior Dev \u{1F9E0}":c<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",w=c>0?"\x1B[32m\u25CF\x1B[0m":"\x1B[33m\u25CF\x1B[0m";if(console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 ${w} \x1B[1mBrain status\x1B[0m \xB7 instance ${t.slice(0,8)}... \u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Lessons : \x1B[33m${String(c).padEnd(8)}\x1B[0m Level : \x1B[32m${b.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Recalls : \x1B[36m${String(r).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(d).padEnd(3)}%\x1B[0m \u2502`),f.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const x=f.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(f.length).padEnd(2)} developer${f.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-x.length))} \u2502`),console.log(`\u2502 ${x.slice(0,56).padEnd(56)} \u2502`)}if(u){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const x=`${u.slice(0,44)}${u.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Referral link\x1B[0m \xB7 ${l>0?`\x1B[32m${l} joined\x1B[0m`:"share to invite new users"}${" ".repeat(Math.max(0,35-String(l).length))} \u2502`),console.log(`\u2502 \x1B[2m${x.padEnd(56)}\x1B[0m \u2502`)}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),c===0&&(console.log(" \x1B[33m\u{1F4A1} No lessons yet.\x1B[0m Run a session with cachly connected to start learning."),console.log(""))}catch(s){console.log(`
|
|
213
|
+
\u274C Could not fetch status: ${s.message}
|
|
214
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="health"){const{existsSync:e}=await import("node:fs"),{readFile:t}=await import("node:fs/promises"),{resolve:s}=await import("node:path"),n=process.cwd();let o=0,i=0;const c=g=>{console.log(` \u2705 ${g}`),o++},r=g=>{console.log(` \u26A0\uFE0F ${g}`)},d=g=>{console.log(` \u274C ${g}`),i++};console.log(`
|
|
187
215
|
\u{1F9E0} cachly health check
|
|
188
|
-
`),console.log("\u{1F511} Auth token");const
|
|
189
|
-
\u{1F310} Brain API`);const l=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const
|
|
190
|
-
\u{1F9E0} Brain instance`);const u=
|
|
191
|
-
\u{1F50C} Redis connectivity`),
|
|
192
|
-
\u{1F6E0} Editor configs (project dir)`);const
|
|
193
|
-
\u{1FA9D} Git hook (ambient learning)`);const x=n
|
|
194
|
-
\u{1F9EC} Embedding provider (semantic search)`);{const
|
|
216
|
+
`),console.log("\u{1F511} Auth token");const f=G();if(!f)d("No cachly key found (environment or ~/.cachly/credentials.json) \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(f.startsWith("cky_"))c("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const g=f.split(".");if(g.length!==3)throw new Error("not a JWT");const a=JSON.parse(Buffer.from(g[1],"base64url").toString("utf-8")),m=a.exp?a.exp*1e3:null,h=m?Math.floor((m-Date.now())/6e4):null;m&&m<Date.now()?d(`JWT expired ${Math.abs(h)} minute(s) ago \u2014 get a new one: ${j("/setup-ai","health")}`):h!==null&&h<30?r(`JWT expires in ${h} minute(s) \u2014 refresh soon at ${j("/setup-ai","health")}`):c(`JWT valid${h!==null?` (expires in ${Math.floor(h/60)}h ${h%60}m)`:""}`)}catch{d("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
|
|
217
|
+
\u{1F310} Brain API`);const l=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const g=await fetch(`${l}/health`,{signal:AbortSignal.timeout(5e3)});if(g.ok){const a=await g.json();c(`${l} reachable (status: ${a.status??"ok"})`)}else g.status===401||g.status===403?c(`${l} reachable (auth required \u2014 expected)`):d(`${l}/health returned HTTP ${g.status}`)}catch(g){d(`${l} unreachable \u2014 ${g.message}`)}console.log(`
|
|
218
|
+
\u{1F9E0} Brain instance`);const u=U();if(!u)r("No Brain instance found (environment or ~/.cachly/credentials.json) \u2014 will auto-resolve on first tool call");else if(f)try{const g=await fetch(`${l}/api/v1/instances/${u}`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(g.ok){const a=await g.json();if(a.status==="running")if(c(`Instance "${a.name}" (${u.slice(0,8)}\u2026) is running`),console.log(`
|
|
219
|
+
\u{1F50C} Redis connectivity`),a.host&&a.port)try{let m,h;try{const k=await fetch(`${l}/api/v1/instances/${u}/connection`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(k.ok){const I=await k.json();m=I.password,h=I}}catch{}const p=xt({host:a.host,port:a.port,tls_enabled:a.tls_enabled},h),S=new Xe({host:p.host,port:p.port,password:m,...p.tls?{tls:p.tls}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await S.connect();const C=await S.ping();S.disconnect(),C==="PONG"?c(`Redis PING \u2192 PONG (${p.host}:${p.port}, ${p.art==="klartext"?"unencrypted":"TLS"})`):r(`Redis responded but not PONG: ${C}`)}catch(m){d(`Redis unreachable \u2014 ${m.message}`)}else r("Instance has no host/port yet");else r(`Instance "${a.name}" status: ${a.status}`)}else d(`Instance ${u.slice(0,8)}\u2026 not found (HTTP ${g.status})`)}catch(g){d(`Could not check instance \u2014 ${g.message}`)}console.log(`
|
|
220
|
+
\u{1F6E0} Editor configs (project dir)`);const b=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:".windsurf/mcp.json"},{editor:"Copilot / Cline",path:".vscode/mcp.json"},{editor:"Zed",path:".zed/settings.json"},{editor:"Continue.dev",path:".continue/config.json"},{editor:"Codex",path:".codex/config.toml"},{editor:"Gemini CLI",path:".gemini/settings.json"}];let w=0;for(const{editor:g,path:a}of b){const m=s(n,a);if(e(m))try{const h=await t(m,"utf-8");h.includes("@cachly-dev/mcp-server")||h.includes("cachly")?(c(`${g}: ${a}`),w++):r(`${g}: ${a} exists but cachly not found inside`)}catch{r(`${g}: ${a} exists but could not read`)}}w===0&&d("No editor MCP configs found in this folder \u2014 run: npx @cachly-dev/mcp-server@latest init (add --editor cursor|copilot|codex|gemini if needed)"),console.log(`
|
|
221
|
+
\u{1FA9D} Git hook (ambient learning)`);const x=s(n,".git","hooks","post-commit");if(!e(s(n,".git")))r("Not in a git repository \u2014 skip");else if(e(x))try{(await t(x,"utf-8")).includes("cachly")?c(".git/hooks/post-commit (cachly CLS hook present)"):r(".git/hooks/post-commit exists but cachly hook not found \u2014 run setup to add it")}catch{r(".git/hooks/post-commit exists but could not read")}else r(".git/hooks/post-commit not found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");console.log(`
|
|
222
|
+
\u{1F9EC} Embedding provider (semantic search)`);{const g=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],a=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase();if(a&&a!=="cachly"){const m=g.find(([,h])=>h===a)?.[0];m&&process.env[m]?c(`BYOK: ${a} (key present in ${m})`):r(`CACHLY_EMBED_PROVIDER=${a} but its key env var is not set \u2014 semantic search will fail`)}else{it==="ollama"?c("Local Ollama (OLLAMA_BASE_URL) \u2014 text stays on your machine"):it==="cachly"?c("Server-side embeddings (cachly, EU) \u2014 no key needed, uses your JWT"):r("No embedding provider active \u2014 sign in (CACHLY_JWT) for EU-hosted embeddings; search runs on words until then");for(const[m,h]of g)h!=="ollama"&&process.env[m]&&c(`${m} is set but not used \u2014 ${h} runs only if you name it with CACHLY_EMBED_PROVIDER=${h}`)}}console.log(`
|
|
195
223
|
${"\u2500".repeat(40)}`),i===0?console.log(`\u2705 All checks passed (${o} ok)
|
|
196
224
|
`):(console.log(`\u274C ${i} check(s) failed, ${o} passed
|
|
197
225
|
`),console.log(`\u{1F4A1} Fix issues with: npx @cachly-dev/mcp-server@latest autopilot
|
|
198
|
-
`),process.exit(1)),process.exit(0)}if(process.argv[2]==="claim"){const{readFile:e,writeFile:t}=await import("node:fs/promises"),{existsSync:
|
|
226
|
+
`),process.exit(1)),process.exit(0)}if(process.argv[2]==="claim"){const{readFile:e,writeFile:t}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:n}=await import("node:path"),{homedir:o}=await import("node:os"),i=a=>{const m=process.argv.indexOf(`--${a}`);return m!==-1?process.argv[m+1]:void 0};_=(i("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const c=(i("auth-url")??ht).replace(/\/+$/,"");console.log(`
|
|
199
227
|
\u{1F9E0} cachly \u2014 keep your test Brain in your own account
|
|
200
|
-
`),(_!=="https://api.cachly.dev"||c!==
|
|
201
|
-
`);const
|
|
202
|
-
`),process.exit(1));const d=
|
|
228
|
+
`),(_!=="https://api.cachly.dev"||c!==ht)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${_}, sign-in ${c}
|
|
229
|
+
`);const r=Sn({argument:i("key"),credentials:xe()});r||(console.log("No test key (cky_trial_\u2026) was found in ~/.cachly/credentials.json."),console.log("If you already use your own cachly account, there is nothing to claim."),console.log(`Otherwise pass the key: npx @cachly-dev/mcp-server@latest claim --key cky_trial_\u2026
|
|
230
|
+
`),process.exit(1));const d=r.schluessel,f={argument:"--key",credentials:"~/.cachly/credentials.json"}[r.quelle];console.log(`Test key: ${d.slice(0,14)}\u2026 (from ${f})
|
|
203
231
|
`);let l="";try{console.log(`Step 1: Sign in to your cachly account
|
|
204
|
-
`);const
|
|
205
|
-
`),
|
|
206
|
-
\u2139\uFE0F No browser could be opened here (${
|
|
207
|
-
`)}catch(
|
|
232
|
+
`);const a=await An(fetch,c);console.log(` Code: \x1B[1;33m${a.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${a.adresse}
|
|
233
|
+
`),re(a.adresse,(m,h)=>{m||console.log(`
|
|
234
|
+
\u2139\uFE0F No browser could be opened here (${h??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),l=await Cn(fetch,a,{basis:c,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
|
|
235
|
+
`)}catch(a){console.error(`
|
|
208
236
|
|
|
209
|
-
${
|
|
210
|
-
`),process.exit(1)}process.stdout.write("Step 2: Moving the test Brain into your account (it restarts once, up to a minute)\u2026");let u;try{u=await Tn(fetch,_,l,d,"mcp",`cachly-mcp/${
|
|
211
|
-
`)}catch(
|
|
237
|
+
${a.message}. Nothing was changed.
|
|
238
|
+
`),process.exit(1)}process.stdout.write("Step 2: Moving the test Brain into your account (it restarts once, up to a minute)\u2026");let u;try{u=await Tn(fetch,_,l,d,"mcp",`cachly-mcp/${H}`),console.log(` \x1B[32m\u2713\x1B[0m
|
|
239
|
+
`)}catch(a){console.error(`
|
|
212
240
|
|
|
213
|
-
${Rn(
|
|
214
|
-
`),process.exit(1)}
|
|
241
|
+
${Rn(a)}
|
|
242
|
+
`),process.exit(1)}v=u.apiKey,te(u.apiKey),ve(u.instanceId,{apiKey:u.apiKey}),await pe(u.apiKey),await me(u.instanceId);const b=o(),w=new Set([...Object.values(ce).map(a=>n(process.cwd(),a)),n(b,".claude.json"),n(b,".claude","mcp.json"),n(b,".cursor","mcp.json"),n(b,".codeium","windsurf","mcp_config.json")]);let x=0;for(const a of w)if(s(a))try{const m=jn(await e(a,"utf-8"),d,u.apiKey);m.ersetzt&&(await t(a,m.text,"utf-8"),x++)}catch{}const g=await In(fetch,_,u.apiKey,u.instanceId);console.log(En(u,g)),console.log(`
|
|
215
243
|
New key stored in ~/.cachly/credentials.json${x?` and in ${x} editor config file(s) that held the test key`:""}.`),console.log(`Restart your editor (or reload its MCP servers) so it uses the new key.
|
|
216
|
-
`),process.exit(0)}const
|
|
217
|
-
`)),
|
|
244
|
+
`),process.exit(0)}const Se=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||Se){const{writeFile:e,mkdir:t,readFile:s}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:o,dirname:i}=await import("node:path"),{createInterface:c}=await import("node:readline"),r=Date.now(),d=Se?"autopilot":"setup";Yo();const f=process.argv.indexOf("--api-url");f!==-1&&process.argv[f+1]&&(_=process.argv[f+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${_}
|
|
245
|
+
`)),A("setup_started");const l=process.stdin.isTTY===!0,u=Se||process.argv.includes("--yes")||process.argv.includes("-y")||!l;Se?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
|
|
218
246
|
`):!l&&!process.argv.includes("--yes")&&!process.argv.includes("-y")&&console.log(`\u2139\uFE0F Non-interactive terminal detected \u2014 running in automatic mode (no prompts).
|
|
219
|
-
`);const
|
|
247
|
+
`);const b=c({input:process.stdin,output:process.stdout}),w=(y,T="")=>u?(console.log(`${y}${T}`),Promise.resolve(T)):new Promise(B=>b.question(y,z=>B(z.trim()||T)));console.log(`
|
|
220
248
|
\u{1F9E0} cachly AI Brain \u2014 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\u2500\u2500
|
|
221
249
|
`);let x=process.env.CACHLY_JWT??"";if(x)console.log(`\u2713 Using token from CACHLY_JWT env var
|
|
222
250
|
`);else{console.log(`Step 1: Sign in to cachly (free, no credit card)
|
|
223
|
-
`),
|
|
224
|
-
`),
|
|
225
|
-
`)}),process.stdout.write(" Waiting for authorization");const
|
|
226
|
-
`),
|
|
227
|
-
Auth error: ${
|
|
228
|
-
`),
|
|
251
|
+
`),A("setup_auth_started");let y="",T="",B="",z=5e3,W=!1,de="cachly";try{const q=await fetch(`${_}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(q.ok){const P=await q.json();y=P.device_code,T=P.user_code;const D=P.verification_uri||j("/device",d);B=`${D}${D.includes("?")?"&":"?"}code=${encodeURIComponent(T)}`,z=(P.interval??5)*1e3,W=!!y}}catch{}if(!W)try{const P=await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/auth/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id=cachly-cli&scope=openid",signal:AbortSignal.timeout(8e3)});if(P.ok){const D=await P.json();y=D.device_code,T=D.user_code,B=D.verification_uri_complete,z=(D.interval??5)*1e3,W=!0,de="keycloak"}}catch{}if(W&&y){console.log(` Code: \x1B[1;33m${T}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${B}
|
|
252
|
+
`),re(B,(P,D)=>{if(P){A("device_browser_opened",{stelle:"setup"});return}A("device_browser_failed",{reason:D??"unknown",stelle:"setup"}),console.log(` \u2139\uFE0F No browser could be opened here (${D??"unknown"}) \u2014 please open the URL yourself.
|
|
253
|
+
`)}),process.stdout.write(" Waiting for authorization");const q=Date.now()+600*1e3;for(;Date.now()<q;){await new Promise(P=>setTimeout(P,z)),process.stdout.write(".");try{let P=null;if(de==="cachly")try{const D=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:y}),signal:AbortSignal.timeout(8e3)});D.status<500&&(P=await D.json())}catch{}else{const D="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{P=await(await fetch(`${D}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`client_id=cachly-cli&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=${y}`,signal:AbortSignal.timeout(8e3)})).json()}catch{}}if(P?.access_token){x=P.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
|
|
254
|
+
`),A("setup_auth_completed"),A("device_flow_completed");break}P?.error==="slow_down"?z=Math.min(z+2e3,15e3):P?.error&&P.error!=="authorization_pending"&&(A("device_flow_failed",{reason:P.error}),console.error(`
|
|
255
|
+
Auth error: ${P.error}. Aborting.
|
|
256
|
+
`),b.close(),process.exit(1))}catch{}}x||(A("device_flow_failed",{reason:"timeout"}),console.error(`
|
|
229
257
|
Timed out waiting for authorization. Aborting.
|
|
230
|
-
`),
|
|
231
|
-
`),console.log(` URL: \x1B[36m${
|
|
232
|
-
`),
|
|
258
|
+
`),b.close(),process.exit(1)),console.log("")}else{A("device_flow_failed",{reason:"device_flow_unavailable"});const q=j("/setup-ai",d);console.log(` \u26A0\uFE0F Could not start automatic sign-in. Opening browser for web sign-in...
|
|
259
|
+
`),console.log(` URL: \x1B[36m${q}\x1B[0m`),console.log(" 1. Sign up / log in at the URL above"),console.log(" 2. Go to Settings \u2192 API Keys \u2192 Create new key"),console.log(` 3. Copy the key (starts with cky_live_...)
|
|
260
|
+
`),re(q),u?(A("device_flow_failed",{reason:"non_interactive_no_key"}),console.error(`
|
|
233
261
|
\u26A0\uFE0F This terminal is non-interactive, so the key cannot be pasted here.`),console.error(` Get your key at the URL above, then set it and re-run setup:
|
|
234
262
|
`),console.error(` \x1B[1mCACHLY_JWT=cky_live_xxx npx @cachly-dev/mcp-server@latest autopilot\x1B[0m
|
|
235
263
|
`),console.error(` Or add it to your editor's MCP config under env.CACHLY_JWT.
|
|
236
|
-
`),
|
|
264
|
+
`),b.close(),process.exit(1)):(x=await w(" Paste API key (cky_live_...): "),x||(console.error(`
|
|
237
265
|
API key is required. Aborting.
|
|
238
|
-
`),
|
|
266
|
+
`),b.close(),process.exit(1)),A("setup_auth_completed"),console.log(""))}}if(x.startsWith("eyJ")){process.stdout.write("\u23F3 Generating your API key...");try{const y=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`},body:JSON.stringify({name:"cachly-mcp-setup",scope:"read_write"})});if(!y.ok)throw new Error(`HTTP ${y.status}`);const T=await y.json();if(!T.key)throw new Error("no key in response");x=T.key,console.log(` \u2713
|
|
239
267
|
`)}catch{console.log(` (skipped)
|
|
240
|
-
`)}}process.stdout.write("\u23F3 Fetching your instances...");let
|
|
268
|
+
`)}}process.stdout.write("\u23F3 Fetching your instances...");let g=[];try{const y=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${x}`}});if(!y.ok)throw new Error(`HTTP ${y.status}`);g=((await y.json()).data??[]).filter(B=>B.status==="running")}catch(y){const T=y.message;console.error(`
|
|
241
269
|
|
|
242
|
-
Failed to fetch instances: ${
|
|
243
|
-
`),
|
|
244
|
-
`),
|
|
245
|
-
`),process.stdout.write("\u23F3 Waiting for instance to start");for(let z=0;z<45;z++){await new Promise(
|
|
246
|
-
`)}
|
|
270
|
+
Failed to fetch instances: ${T}`),T.includes("401")&&(console.error(`Token rejected. Get a valid token at ${j("/setup-ai",d)}
|
|
271
|
+
`),re(j("/setup-ai",d))),b.close(),process.exit(1)}if(console.log(` found ${g.length}
|
|
272
|
+
`),g.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const y=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${x}`,"Content-Type":"application/json"}});if(!y.ok)throw new Error(`HTTP ${y.status}`);const T=await y.json();if(T.instance)g=[T.instance];else if(T.instance_id){const B=T.instance_id;console.log(` \u2713 created (${B.slice(0,8)}\u2026)
|
|
273
|
+
`),process.stdout.write("\u23F3 Waiting for instance to start");for(let z=0;z<45;z++){await new Promise(W=>setTimeout(W,3e3)),process.stdout.write(".");try{const W=await fetch(`${_}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${x}`}});if(W.ok){const de=await W.json();if(de.status==="running"){g=[de];break}}}catch{}}console.log("")}}catch(y){console.log(` failed: ${y.message}
|
|
274
|
+
`)}g.length===0&&(console.error(`
|
|
247
275
|
Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
|
|
248
|
-
`),
|
|
249
|
-
`)),console.log(`\u2713 Instance: ${
|
|
250
|
-
`),
|
|
251
|
-
`);const{existsSync:$}=await import("node:fs"),
|
|
252
|
-
`)[0].slice(0,160)})`);else{const
|
|
276
|
+
`),re(j("/instances",d)),b.close(),process.exit(1))}const a=g[0];g.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${a.name}`),console.log(` (Run with --instance-id <id> to use a different one)
|
|
277
|
+
`)),console.log(`\u2713 Instance: ${a.name} (${a.id.slice(0,8)}\u2026)
|
|
278
|
+
`),A("setup_instance_ready",{instance_id:a.id});const m=process.cwd(),h=[],{homedir:p}=await import("node:os"),S=p();h.push("claude"),n(o(m,".cursor"))&&h.push("cursor"),n(o(m,".windsurf"))&&h.push("windsurf"),n(o(m,".vscode"))&&h.push("copilot"),n(o(m,".continue"))&&h.push("continue");const C=process.platform==="darwin"?o(S,"Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev"):o(S,".vscode/extensions");(n(C)&&!h.includes("copilot")||n(C))&&h.push("cline");const k=process.platform==="darwin"?o(S,"Library/Application Support/Zed"):o(S,".config/zed");n(k)&&h.push("zed");const I=y=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[y]??y,E=h;console.log(`\u{1F527} Configuring for: ${E.map(I).join(", ")}
|
|
279
|
+
`);const{existsSync:$}=await import("node:fs"),R=[];let M=0;te(x),ve(a.id,{apiKey:x});for(const y of E){const T=ce[y]??".mcp.json",B=o(m,T);try{await t(i(B),{recursive:!0});const z=$(B),W=await Mt(B,x,a.id,y,{readFile:s,existsSync:$});await e(B,W,"utf-8"),console.log(`\u2705 ${z?"Updated":"Written"}: ${T}`),M++}catch(z){const W=z.message;console.log(`\u26A0\uFE0F Could not write ${T}: ${W}`),console.log(" Fix permissions or run with sudo, then re-run setup."),R.push({file:T,reason:W})}}const Ce=await Dt(m,a.id);for(const[y,T]of Object.entries(Ce)){const{relative:B}=await import("node:path");console.log(Ut(B(m,y)||y,T))}v=x;let oe=0;if(n(o(m,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const y=await J("brain_from_git",{instance_id:a.id,repo_path:m,limit:100});if(y.startsWith("\u274C"))console.log(` (skipped: ${rt(y.replace(/^❌\s*/,"")).split(`
|
|
280
|
+
`)[0].slice(0,160)})`);else{const T=y.match(/Ingested: \*\*(\d+)\*\*/);oe=T?parseInt(T[1],10):0,console.log(` \u2713 ${oe} lesson${oe===1?"":"s"} extracted from git history`);const B=Wo(y);B&&(console.log(""),console.log(rt(B)))}}catch(y){console.log(` (skipped: ${y.message.slice(0,80)})`)}}if(oe===0){process.stdout.write("\u{1F331} Seeding 16 universal engineering lessons (first recall works instantly)...");try{await J("brain_seed_starter",{instance_id:a.id}),console.log(" \u2713");try{const y=await J("smart_recall",{instance_id:a.id,query:"docker build slow"}),T=Jo(y);T&&(console.log(""),console.log(Fo(T.topic,T.what)))}catch{}}catch(y){console.log(` (skipped: ${y.message.slice(0,60)})`)}}try{const y=await fetch(`${_}/api/v1/instances/${a.id}/memory`,{headers:{Authorization:`Bearer ${x}`},signal:AbortSignal.timeout(6e3)});if(y.ok){const B=(await y.json()).lesson_count??0;console.log(B===0?`
|
|
253
281
|
\u{1F9E0} Your Brain is empty. It learns from your fixes and commits from now on.`:`
|
|
254
282
|
\u{1F9E0} Your Brain now holds ${B} lesson${B===1?"":"s"}.`)}}catch{}if(!u)try{if(console.log(`
|
|
255
|
-
\u{1F451} Governance (optional \u2014 role model: admin \xB7 reviewer \xB7 contributor \xB7 viewer)`),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\u2500\u2500"),(await
|
|
256
|
-
`),console.log(` team_assign_role(instance_id="${
|
|
283
|
+
\u{1F451} Governance (optional \u2014 role model: admin \xB7 reviewer \xB7 contributor \xB7 viewer)`),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\u2500\u2500"),(await w(" Set yourself as the first admin? (y/N): ","N")).toLowerCase()==="y"){const T=await w(' Your handle (e.g. "alice"): ');T.trim()&&await J("team_assign_role",{instance_id:a.id,handle:T.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${T.trim()} is now admin. Invite teammates:
|
|
284
|
+
`),console.log(` team_assign_role(instance_id="${a.id}", handle="<teammate>", role="contributor", assigned_by="${T.trim()}")
|
|
257
285
|
`))}else console.log(` Skipped \u2014 run team_assign_role at any time.
|
|
258
|
-
`)}catch{}if(!u){const
|
|
259
|
-
`)}catch{}}try{const
|
|
260
|
-
\u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):
|
|
261
|
-
\u2705 CLS git hook upgraded to ${ct}.`):
|
|
262
|
-
\u2705 CLS git hook appended to existing post-commit.`)}catch{}if(
|
|
286
|
+
`)}catch{}if(!u){const y=await w(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(y&&y.includes("@"))try{await fetch(`${_}/api/newsletter/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:y.trim().toLowerCase(),source:"mcp-setup"}),signal:AbortSignal.timeout(5e3)}),console.log(` \u2705 Subscribed \u2014 you'll only hear from us when it matters.
|
|
287
|
+
`)}catch{}}try{const y=await at(process.cwd(),a.id);y==="written"?console.log(`
|
|
288
|
+
\u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):y==="upgraded"?console.log(`
|
|
289
|
+
\u2705 CLS git hook upgraded to ${ct}.`):y==="appended"&&console.log(`
|
|
290
|
+
\u2705 CLS git hook appended to existing post-commit.`)}catch{}if(E.includes("claude"))try{const y=await pt(process.cwd(),a.id);if(y.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${y.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const T=y.scripts==="written"?"\u2705 Written":y.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${mt})`:"\u2713 Unchanged";console.log(`${T}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),y.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):y.settings==="merged"?console.log("\u2705 Merged: .claude/settings.json (Ambient Recall hooks wired)"):console.log("\u2713 Ambient Recall hooks already wired in .claude/settings.json")}}catch{}E.includes("cursor")&&await ye("cursor",process.cwd(),a.id," "),E.includes("copilot")&&await ye("copilot",process.cwd(),a.id," "),(n(o(S,".codex"))||n(o(m,".codex")))&&(await ye("codex",process.cwd(),a.id," "),await Ue("codex",process.cwd(),Q("",a.id)," ")),(n(o(S,".gemini"))||n(o(m,".gemini")))&&(await ye("gemini",process.cwd(),a.id," "),await Ue("gemini",process.cwd(),Q("",a.id)," ")),v=x;const ze=Math.round((Date.now()-r)/1e3);if(R.length>0&&A("setup_config_write_failed",{instance_id:a.id,failed:R.length,succeeded:M}),A("setup_completed",{instance_id:a.id,elapsed_s:ze,config_failures:R.length}),R.length>0&&M===0){console.log(`
|
|
263
291
|
\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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557`),console.log("\u2551 \u26A0\uFE0F Setup incomplete \u2014 no editor config was written \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(`
|
|
264
|
-
Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const
|
|
265
|
-
Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${x.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${
|
|
266
|
-
`),
|
|
267
|
-
\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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557`),console.log("\u2551 \u{1F680} Brain is ready. \u2551"),console.log(`\u2551 \u23F1\uFE0F Setup completed in ${(
|
|
268
|
-
\u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const
|
|
292
|
+
Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const y of R)console.log(` \u2022 ${y.file} \u2014 ${y.reason}`);console.log(`
|
|
293
|
+
Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${x.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${a.id}`),console.log(` Docs: ${j("/docs/mcp",d)}
|
|
294
|
+
`),b.close(),await new Promise(y=>setTimeout(y,300)),process.exit(1)}if(console.log(`
|
|
295
|
+
\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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557`),console.log("\u2551 \u{1F680} Brain is ready. \u2551"),console.log(`\u2551 \u23F1\uFE0F Setup completed in ${(ze+"s").padEnd(5)} \u2014 restart your editor \u2551`),console.log("\u2551 and your AI arrives pre-briefed every session. \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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),R.length>0){console.log(`
|
|
296
|
+
\u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const y of R)console.log(` \u2022 ${y.file} \u2014 ${y.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(`
|
|
269
297
|
\u{1F449} Next: restart your editor, start a new chat and ask:`),console.log(" What does my cachly Brain know about this project?"),console.log(` Your AI should call the cachly tool smart_recall and answer from your Brain.
|
|
270
|
-
`),console.log(` Dashboard: ${j(`/instances/${
|
|
271
|
-
`),
|
|
298
|
+
`),console.log(` Dashboard: ${j(`/instances/${a.id}`,d)}`),console.log(` Step-by-step guide: ${j("/docs/setup",d)}
|
|
299
|
+
`),b.close(),await new Promise(y=>setTimeout(y,300)),process.exit(0)}if(process.argv[2]==="index"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),s=r=>{const d=t.indexOf(`--${r}`);return d!==-1?t[d+1]:void 0},n=e(s("dir")??t.find(r=>!r.startsWith("--"))??"."),o=s("instance-id")||U(),i=parseInt(s("max-files")??"500",10),c=s("namespace")??"cachly:sem:code";(!o||!v)&&(console.error(`
|
|
272
300
|
\u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
|
|
273
301
|
`),console.error(" export CACHLY_BRAIN_INSTANCE_ID=<uuid>"),console.error(" export CACHLY_JWT=<cky_live_...>"),console.error(` npx @cachly-dev/mcp-server@latest index ./my-project
|
|
274
302
|
`),process.exit(1)),console.log(`
|
|
275
|
-
\u{1F4C2} Indexing: ${
|
|
276
|
-
`);try{const
|
|
303
|
+
\u{1F4C2} Indexing: ${n}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max files: ${i}
|
|
304
|
+
`);try{const r=await J("index_project",{instance_id:o,dir:n,max_files:i,ttl:604800,namespace:c});console.log(r),console.log(`
|
|
277
305
|
\u2705 Indexing complete.
|
|
278
|
-
`)}catch(
|
|
279
|
-
\u274C Indexing failed: ${
|
|
280
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="learn-git"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),
|
|
306
|
+
`)}catch(r){console.error(`
|
|
307
|
+
\u274C Indexing failed: ${r.message}
|
|
308
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="learn-git"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),s=c=>{const r=t.indexOf(`--${c}`);return r!==-1?t[r+1]:void 0},n=e(s("dir")??t.find(c=>!c.startsWith("--"))??"."),o=s("instance-id")||U(),i=parseInt(s("max-commits")??"50",10);(!o||!v)&&(console.error(`
|
|
281
309
|
\u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
|
|
282
310
|
`),console.error(" export CACHLY_BRAIN_INSTANCE_ID=<uuid>"),console.error(" export CACHLY_JWT=<cky_live_...>"),console.error(` npx @cachly-dev/mcp-server@latest learn-git .
|
|
283
311
|
`),process.exit(1)),console.log(`
|
|
284
|
-
\u{1F9E0} Learning from git history: ${
|
|
285
|
-
`);try{const c=await
|
|
312
|
+
\u{1F9E0} Learning from git history: ${n}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max commits: ${i}
|
|
313
|
+
`);try{const c=await J("brain_from_git",{instance_id:o,repo_path:n,limit:i});console.log(c),A("brain_from_git",{api_key:v,instance_id:o}),console.log(`
|
|
286
314
|
\u2705 Brain learned from your commits.
|
|
287
|
-
`),await new Promise(
|
|
315
|
+
`),await new Promise(r=>setTimeout(r,300))}catch(c){console.error(`
|
|
288
316
|
\u274C learn-git failed: ${c.message}
|
|
289
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await mn(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await gn(),process.argv[2]===
|
|
317
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await mn(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await gn(),process.argv[2]===fn&&await hn(process.argv[3]??""),process.argv[2]==="ambient-credit"){try{const e=Math.round(Number(process.argv[3]));if(Number.isFinite(e)&&e>0){const t=Math.min(e,2e4),s=process.argv.slice(4).join(" ").slice(0,200)||void 0,n={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:s,instanz:U()||void 0};await bn(n),await ys(process.env.CACHLY_BRAIN_INSTANCE_ID??N,n),console.log(`\u2705 ambient credit recorded: ${t} tokens${s?` (${s})`:""}`)}else console.error("Usage: npx @cachly-dev/mcp-server@latest ambient-credit <tokens-saved> [note]")}catch{}process.exit(0)}if(process.argv[2]==="ambient-stats"){const e=U(),t=xn(await gt(),e||void 0),s=t.eigene,n=us(s),o=s.slice(-5);if(console.log(`
|
|
290
318
|
\u{1F9E0} Ambient Recall \u2014 net-token ledger
|
|
291
|
-
`),console.log(` Instance: ${e?`${e.slice(0,8)}\u2026`:"(none set \u2014 showing every entry on this computer)"}`),console.log(` Turns recorded: ${
|
|
319
|
+
`),console.log(` Instance: ${e?`${e.slice(0,8)}\u2026`:"(none set \u2014 showing every entry on this computer)"}`),console.log(` Turns recorded: ${s.length}`),console.log(` Injected tokens: ${n.injected}`),console.log(` Prevented tokens: ${n.prevented} (agent-reported via ambient-credit)`),console.log(` NET: ${n.net>=0?"+":""}${n.net} tokens`),o.length>0){console.log(`
|
|
292
320
|
Last entries:`);for(const i of o){const c=i.prevented>0?`+${i.prevented} prevented`:`-${i.injected} injected`;console.log(` \u2022 ${i.ts.slice(0,19)} ${i.event}: ${c}${i.note?` (${i.note})`:""}`)}}(t.ohneInstanz>0||t.andereInstanzen>0)&&(console.log(`
|
|
293
|
-
Not counted above:`),t.ohneInstanz>0&&console.log(` \u2022 ${t.ohneInstanz} older entries without an instance (before 0.10.207)`),t.andereInstanzen>0&&console.log(` \u2022 entries of ${t.andereInstanzen} other instance${t.andereInstanzen===1?"":"s"} on this computer`)),console.log(""),process.exit(0)}if(process.argv[2]==="uninstall"){const{homedir:e,tmpdir:t}=await import("node:os"),{resolve:
|
|
321
|
+
Not counted above:`),t.ohneInstanz>0&&console.log(` \u2022 ${t.ohneInstanz} older entries without an instance (before 0.10.207)`),t.andereInstanzen>0&&console.log(` \u2022 entries of ${t.andereInstanzen} other instance${t.andereInstanzen===1?"":"s"} on this computer`)),console.log(""),process.exit(0)}if(process.argv[2]==="uninstall"){const{homedir:e,tmpdir:t}=await import("node:os"),{resolve:s}=await import("node:path"),{createInterface:n}=await import("node:readline/promises"),o=process.argv.slice(3),c={projekt:s((r=>{const d=o.indexOf(`--${r}`);return d!==-1?o[d+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:G(),instanz:U(),apiUrl:_,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:r=>console.log(r),frage:async r=>{const d=n({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await d.question(r)).trim())}finally{d.close()}}};process.exit(await on(o,c))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:s,checkAuthAccepted:n,checkInstance:o,checkVectorCoverage:i,inspectAmbientHooks:c,checkHooks:r,checkLedger:d,renderDoctorReport:f,doctorExitCode:l}=await import("./doctor.js"),u=[e(),t(v),await s(_),await n(_,v),o(U()||N),await i(_,v,U()||N),r(c(process.cwd())),d(await gt(),wn())];console.log(f(u)),process.exit(l(u))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!v)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const s=t.instance_id??N;(!s||!t.source)&&process.exit(0),await J("cls_ingest",{instance_id:s,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!v){const e=Yt();if(e)try{const t=await fetch(qt(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Kt(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const s=await t.json();s.access_token&&(v=s.access_token,ae(s.access_token),A("m2m_auth_completed",{grant:"client_credentials",client_id:e.clientId}),process.stderr.write(`\u{1F916} cachly: authenticated via client_credentials (M2M, headless).
|
|
294
322
|
`))}else process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth failed (${t.status}). Check CACHLY_CLIENT_ID / CACHLY_CLIENT_SECRET.
|
|
295
|
-
`),
|
|
296
|
-
`),
|
|
323
|
+
`),A("m2m_auth_failed",{status:t.status})}catch(t){process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth error: ${t.message}
|
|
324
|
+
`),A("m2m_auth_failed",{reason:"network"})}}const Ns=["demo","share","publish","health","autosetup","setup","autopilot","init","digest","invite","refer","badge","join","upgrade","bench","tool-specs","openapi","ambient-credit","ambient-stats","doctor","uninstall"];if(!v&&!Ns.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&to){const n=`
|
|
297
325
|
\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\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
|
|
298
326
|
\u2551 \u{1F9E0} cachly AI Brain \u2014 Setup required \u2551
|
|
299
327
|
\u2560\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\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\u2563
|
|
@@ -309,11 +337,11 @@ Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
|
|
|
309
337
|
\u2551 Free tier \u2014 no credit card required. \u2551
|
|
310
338
|
\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\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
|
|
311
339
|
|
|
312
|
-
`;process.stdout.write(
|
|
340
|
+
`;process.stdout.write(n),process.exit(0)}else process.stderr.write(`
|
|
313
341
|
\u{1F9E0} cachly: no API key yet \u2014 the first cachly tool call creates a test Brain on EU servers, no sign-up.
|
|
314
342
|
(Own account: npx @cachly-dev/mcp-server@latest autopilot)
|
|
315
343
|
|
|
316
|
-
`);else{const e=
|
|
344
|
+
`);else{const e=Wt(v);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
|
|
317
345
|
\u26A0\uFE0F cachly: CACHLY_JWT expired ${Math.abs(t)} minute(s) ago.
|
|
318
346
|
All tool calls will fail. Get a fresh token at ${j("/setup-ai","jwt-expiry")}
|
|
319
347
|
|
|
@@ -321,7 +349,7 @@ Could not create an instance automatically. Opening ${j("/instances",d)} \u2026
|
|
|
321
349
|
\u26A0\uFE0F cachly: CACHLY_JWT expires in ${t} minute(s).
|
|
322
350
|
Refresh it soon at ${j("/setup-ai","jwt-expiry")} to avoid interruptions.
|
|
323
351
|
|
|
324
|
-
`)}}process.env.PORT||Vn({aktuelle:Gn(
|
|
325
|
-
`),
|
|
326
|
-
`)})}else{const e=new
|
|
327
|
-
`),(async()=>{await De().catch(()=>{});for(const[,
|
|
352
|
+
`)}}process.env.PORT||Vn({aktuelle:Gn(H)});const Ae=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(Ae){const{createServer:e}=await import("node:http");e((s,n)=>{const o=new URL(s.url??"/",`http://localhost:${Ae}`);if(o.pathname==="/health"){n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({status:"ok",version:H,zeroResults:{total:Ro,last10:Eo.slice(-10).map(i=>({query:i.query,ts:new Date(i.ts).toISOString()}))}}));return}if(o.pathname==="/mcp"||o.pathname==="/"){(async()=>{const i=Ts(),c=new no({sessionIdGenerator:void 0});n.on("close",()=>{c.close().catch(()=>{}),i.close().catch(()=>{})});try{await i.connect(c),await c.handleRequest(s,n)}catch(r){process.stderr.write(`cachly-mcp HTTP: ${r.message}
|
|
353
|
+
`),n.headersSent||(n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:r.message})))}})();return}n.writeHead(404),n.end("not found")}).listen(Ae,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${Ae}
|
|
354
|
+
`)})}else{const e=new oo;F("start: Module geladen, stdio verbinden"),await K.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(et=!0,Un(()=>qn(tt)),lo(),es(),Qn(process.stdin,s=>{process.stderr.write(`[cachly-mcp] ${s} \u2014 session over, server exits too
|
|
355
|
+
`),(async()=>{await De().catch(()=>{});for(const[,n]of ee)await n.quit().catch(()=>{});process.exit(0)})()}))}Fe("cachly","startup",{version:H,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{Go as CLAUDE_MD_MARKER_END,qo as CLAUDE_MD_MARKER_START,Io as CROSS_LINGUAL_MAP,ce as EDITOR_FILES,So as STOPWORDS,Ut as anweisungsZeile,Co as arabicLightStem,lt as buildClaudeMdBlock,Rs as buildMcpConfig,Q as buildServerEnv,To as expandCrossLingual,ko as extractTimestamp,Ao as katakanaToRomaji,_o as levenshtein,Es as mcpAddBefehl,Mt as mergeMcpConfig,$o as recencyBoost,jo as reconnectOnce,xo as splitMultiQuery,fo as startBackgroundDevicePoll,vo as tokenize,Dt as writeInstructions};
|