@cachly-dev/mcp-server 0.10.225 → 0.10.226
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 +7 -3
- package/dist/src/aussetzer.js +1 -1
- package/dist/src/embeddings.js +4 -4
- package/dist/src/first-recall-proof.js +4 -4
- package/dist/src/git-startpunkt.js +1 -0
- package/dist/src/handlers/advanced.js +1 -1
- package/dist/src/handlers/brain.js +58 -63
- package/dist/src/handlers/fedbrain.js +37 -37
- package/dist/src/handlers/share.js +16 -16
- package/dist/src/handlers/syndicate.js +2 -2
- package/dist/src/handlers/team.js +24 -24
- package/dist/src/index.js +131 -135
- package/dist/src/pflichtfelder.js +1 -0
- package/dist/src/schreibtor.js +1 -1
- package/dist/src/tuersteher.js +1 -1
- package/dist/src/wirkungsspur.js +1 -1
- package/glama.json +1 -1
- package/hooks/cachly-ambient-einblendung.mjs +17 -17
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/src/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{setzeClientKennung as Dt}from"./herkunft.js";import{jwtExpiryMs as zt,checkJwt as Ut,handleApiError as Jt,diagnoseAuth as Se,planAuthHeal as ze,readClientCredentialsFromEnv as Wt,buildClientCredentialsBody as Ft,clientCredentialsTokenUrl as Yt}from"./auth.js";import{cachlyUrl as E}from"./cachly-url.js";import{nutzungsSchluessel as Kt}from"./werkzeug-nutzung.js";import{istLieferung as qt,lieferSchluessel as Gt,tokenDerAntwort as Vt,hatTreffer as Zt,trefferSchluessel as Ue}from"./geliefert.js";import{notify as Je}from"./notifier.js";import{fileURLToPath as We}from"node:url";import{createRequire as Qt}from"node:module";import{execFile as Ae}from"node:child_process";const Xt=process.argv[1]!=null&&(process.argv[1]===We(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as Fe}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as eo}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as to}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Ye,ErrorCode as ie,ListPromptsRequestSchema as Ke,ListResourceTemplatesRequestSchema as qe,ListResourcesRequestSchema as Ge,ListToolsRequestSchema as Ve,McpError as oe}from"@modelcontextprotocol/sdk/types.js";import{Redis as Ze}from"ioredis";let x=process.env.CACHLY_API_URL??"https://api.cachly.dev",y=Le()??"";le(y);const Us=process.env.CACHLY_EMBED_MODEL??"",D=(()=>{try{const e=Qt(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"})(),oo=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let P=xe(process.env.CACHLY_BRAIN_INSTANCE_ID);function ne(){return y||Le()||""}function W(){return xe(process.env.CACHLY_BRAIN_INSTANCE_ID)||pt()||""}let Q=0,de=null,Qe=!1;async function Xe(){let e=[];try{V.getClientCapabilities()?.roots&&(e=(await V.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Hn({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:We})}function re(){return Qe?ft(process.env):!1}function Ce(e,t,s){!e||!re()||Bn({instanzId:e,vomHook:s,verbindung:H,ausGit:n=>je("brain_from_git",n,H,O),projektOrdner:t?async()=>t:Xe,einbetten:n=>ot(n,{geduld:"lang"}),hatEinbettung:ho,einbettenZweit:n=>ot(n,{geduld:"lang",modell:yo}),melde:n=>S("brain_from_git",{...y?{api_key:y}:{},instance_id:e,total:n,auto:"startwissen"}),startvorrat:n=>Ne("brain_seed_starter",n,H,O),meldeStartvorrat:n=>S("brain_seed_starter",{...y?{api_key:y}:{},instance_id:e,auto:!0},{seeded_count:n,auto:!0})})}function Te(){return re()&&Mn()}const no=7e3,so=12e3,io=18e4;let ve=null;function Ie(e){return ve||(ve=ro(e).finally(()=>{ve=null})),ve}async function ro(e){try{if(!y){const t=Date.now()+e;for(;!Be()&&Tn({})&&Date.now()<t;)await new Promise(o=>setTimeout(o,Sn));const s=Be();if(!s)return!1;y=s,le(s);const n=pt();n&&!P&&(P=n,Q=0),await ue(s),n&&await pe(n),S("instant_trial_started",{tool:"sessionstart-hook",...n?{instance_id:n}:{}})}if(re()&>()){const t=An();t&&(Pe(t.instanzId,re(),Te()),Ce(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!y}function ao(){if(!ft(process.env))return;const e=Date.now()+io,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}y&&!gt()||Ie(0)},500);t.unref(),Ie(0)}async function co(){if(!y)return"";try{const e=await fetch(`${x}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${y}`,"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(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:D}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:D}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function et(){if(P)return P;if(!y)return"";if(de)return de;const e=Date.now();if(Q>0&&e-Q<3e4)return"";Q=e,de=(async()=>{try{const t=await fetch(`${x}/api/v1/instances`,{headers:{Authorization:`Bearer ${y}`,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 P=o.id,Q=0,P;const r=await co();if(r)return P=r,Q=0,Pe(r,re(),Te()),pe(r),Ce(r),P}}catch{}return""})();try{return await de}finally{de=null}}let Ee=0;const lo=6e4;let ae="";async function ue(e){try{const{writeFile:t,mkdir:s,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:r,dirname:c}=await import("node:path"),a=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!a)return;const d=r(a,".claude","mcp.json");let g={};if(o(d))try{g=JSON.parse(await n(d,"utf-8"))}catch{}g.mcpServers??={};const l=g.mcpServers.cachly;if(l)l.env??={},l.env.CACHLY_JWT=e;else{const v={};v.CACHLY_JWT=e,g.mcpServers.cachly={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:v}}await s(c(d),{recursive:!0}),await t(d,JSON.stringify(g,null,2),"utf-8");const m=[r(a,".cursor","mcp.json"),r(a,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(m.map(async v=>{if(o(v))try{const w=await n(v,"utf-8"),b=JSON.parse(w),u=b?.mcpServers?.cachly;u?.env&&(u.env.CACHLY_JWT=e,await t(v,JSON.stringify(b,null,2),"utf-8"))}catch{}}))}catch{}}async function pe(e){if(e){ut(e,{apiKey:y});try{const{writeFile:t,readFile:s}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:o}=await import("node:path"),r=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!r)return;const c=[o(r,".claude","mcp.json"),o(r,".cursor","mcp.json"),o(r,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(c.map(async a=>{if(n(a))try{const d=JSON.parse(await s(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 uo(){try{const e=await fetch(`${x}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},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?(y=t.key,le(t.key),ue(t.key),S("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function Re(){const e=Se(y),t=ze(e);if(t==="none")return ae="",!0;if(t==="refresh"){const s=Date.now();return s-Ee>=lo&&(Ee=s,await uo())?(ae="",!0):(ae=e.message,e.usable)}return ae=e.message,!1}function ce(e,t){const s=(c,a)=>{try{t?.(c,a)}catch{}},n=c=>{c?s(!1,c.code??c.message):s(!0)},o=Go(e);if(!o){s(!1,"keine-http-adresse");return}const r=Vo(o);try{process.platform==="win32"?Ae("cmd",["/c","start","",r],{windowsHide:!0},n):process.platform==="darwin"?Ae("open",[o],n):Ae("xdg-open",[o],n)}catch(c){s(!1,c instanceof Error?c.message:"unknown")}}let G=null;async function po(){try{const e=await fetch(`${x}/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||E("/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 mo(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const n=await fetch(`${x}/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 r=await fetch(`${x}/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(r.ok){const c=await r.json();c.key&&(o=c.key)}}catch{}return y=o,le(o),G=null,S("device_flow_completed"),ue(o),X(o),Q=0,await et(),P&&pe(P),"done"}return n.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function tt(e){if(e.polling)return"pending";e.polling=!0;try{return await mo(e)}finally{e.polling=!1}}function go(e,t=tt,s=o=>G===o,n=fo){const o=async()=>{if(!s(e))return;let r="pending";try{r=await t(e)}catch{}if(r!=="done"){if(r==="expired"){s(e)&&(G=null);return}s(e)&&n(o,e.pollInterval)}};n(o,e.pollInterval)}function fo(e,t){const s=setTimeout(e,t);typeof s.unref=="function"&&s.unref()}import{setEmbedJwt as le,computeEmbedding as ot,hasEmbedProvider as ho,EMBED_PROVIDER as nt}from"./embeddings.js";import{ZWEIT_MODELL as yo}from"./rangfolge-stellschrauben.js";import{tokenize as bo,splitMultiQuery as vo,levenshtein as wo,recencyBoost as xo,extractTimestamp as _o,STOPWORDS as $o,katakanaToRomaji as ko,arabicLightStem as So,expandCrossLingual as Ao,CROSS_LINGUAL_MAP as Co,ZERO_RESULTS_LOG as To,zeroResultsTotal as Io}from"./search.js";const se=new Map;function Eo(e){return e<=1?200:null}async function H(e){if(!e)throw new oe(ie.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
|
|
2
|
+
import{setzeClientKennung as Dt}from"./herkunft.js";import{jwtExpiryMs as zt,checkJwt as Ut,handleApiError as Jt,diagnoseAuth as Se,planAuthHeal as Ue,readClientCredentialsFromEnv as Wt,buildClientCredentialsBody as Ft,clientCredentialsTokenUrl as Yt}from"./auth.js";import{cachlyUrl as E}from"./cachly-url.js";import{nutzungsSchluessel as Kt}from"./werkzeug-nutzung.js";import{istLieferung as qt,lieferSchluessel as Gt,tokenDerAntwort as Vt,hatTreffer as Zt,trefferSchluessel as Je}from"./geliefert.js";import{notify as We}from"./notifier.js";import{fileURLToPath as Fe}from"node:url";import{createRequire as Qt}from"node:module";import{execFile as Ae}from"node:child_process";const Xt=process.argv[1]!=null&&(process.argv[1]===Fe(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as Ye}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as eo}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as to}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Ke,ErrorCode as se,ListPromptsRequestSchema as qe,ListResourceTemplatesRequestSchema as Ge,ListResourcesRequestSchema as Ve,ListToolsRequestSchema as Ze,McpError as ee}from"@modelcontextprotocol/sdk/types.js";import{Redis as Qe}from"ioredis";let v=process.env.CACHLY_API_URL??"https://api.cachly.dev",y=Be()??"";ce(y);const Js=process.env.CACHLY_EMBED_MODEL??"",M=(()=>{try{const e=Qt(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"})(),oo=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let B=xe(process.env.CACHLY_BRAIN_INSTANCE_ID);function te(){return y||Be()||""}function J(){return xe(process.env.CACHLY_BRAIN_INSTANCE_ID)||Pe()||""}let V=0,de=null,Xe=!1;async function et(){let e=[];try{q.getClientCapabilities()?.roots&&(e=(await q.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Dn({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:Fe})}function ie(){return Xe?ft(process.env):!1}function Ce(e,t,n){!e||!ie()||On({instanzId:e,vomHook:n,verbindung:H,ausGit:s=>je("brain_from_git",s,H,N),projektOrdner:t?async()=>t:et,einbetten:s=>nt(s,{geduld:"lang"}),hatEinbettung:ho,einbettenZweit:s=>nt(s,{geduld:"lang",modell:yo}),melde:s=>$("brain_from_git",{...y?{api_key:y}:{},instance_id:e,total:s,auto:"startwissen"}),startvorrat:s=>Ne("brain_seed_starter",s,H,N),meldeStartvorrat:s=>$("brain_seed_starter",{...y?{api_key:y}:{},instance_id:e,auto:!0},{seeded_count:s,auto:!0})})}function Te(){return ie()&&zn()}const no=7e3,so=12e3,io=18e4;let be=null;function Ie(e){return be||(be=ro(e).finally(()=>{be=null})),be}async function ro(e){try{if(!y){const t=Date.now()+e;for(;!ve()&&En({})&&Date.now()<t;)await new Promise(o=>setTimeout(o,Cn));const n=ve();if(!n)return!1;y=n,ce(n);const s=Pe();s&&!B&&(B=s,V=0),await ue(n),s&&await pe(s),$("instant_trial_started",{tool:"sessionstart-hook",...s?{instance_id:s}:{}})}if(ie()&>()){const t=Tn();t&&(Oe(t.instanzId,ie(),Te()),Ce(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!y}function ao(){if(!ft(process.env))return;const e=Date.now()+io,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}y&&!gt()||Ie(0)},500);t.unref(),Ie(0)}async function co(){if(!y)return"";try{const e=await fetch(`${v}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${y}`,"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(`${v}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${v}/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 tt(){if(B)return B;if(!y)return"";if(de)return de;const e=Date.now();if(V>0&&e-V<3e4)return"";V=e,de=(async()=>{try{const t=await fetch(`${v}/api/v1/instances`,{headers:{Authorization:`Bearer ${y}`,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 B=o.id,V=0,B;const r=await co();if(r)return B=r,V=0,Oe(r,ie(),Te()),pe(r),Ce(r),B}}catch{}return""})();try{return await de}finally{de=null}}let Ee=0;const lo=6e4;let re="";async function ue(e){try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o}=await import("node:path"),r=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!r)return;const c=[o(r,".claude","mcp.json"),o(r,".cursor","mcp.json"),o(r,".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 pe(e){if(e){Le(e,{apiKey:y});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o}=await import("node:path"),r=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!r)return;const c=[o(r,".claude","mcp.json"),o(r,".cursor","mcp.json"),o(r,".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 uo(){try{const e=await fetch(`${v}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},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?(y=t.key,ce(t.key),ue(t.key),$("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function Re(){const e=Se(y),t=Ue(e);if(t==="none")return re="",!0;if(t==="refresh"){const n=Date.now();return n-Ee>=lo&&(Ee=n,await uo())?(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=Zo(e);if(!o){n(!1,"keine-http-adresse");return}const r=Qo(o);try{process.platform==="win32"?Ae("cmd",["/c","start","",r],{windowsHide:!0},s):process.platform==="darwin"?Ae("open",[o],s):Ae("xdg-open",[o],s)}catch(c){n(!1,c instanceof Error?c.message:"unknown")}}let K=null;async function po(){try{const e=await fetch(`${v}/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||E("/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 mo(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const s=await fetch(`${v}/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 r=await fetch(`${v}/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(r.ok){const c=await r.json();c.key&&(o=c.key)}}catch{}return y=o,ce(o),K=null,$("device_flow_completed"),ue(o),Z(o),V=0,await tt(),B&&pe(B),"done"}return s.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function ot(e){if(e.polling)return"pending";e.polling=!0;try{return await mo(e)}finally{e.polling=!1}}function go(e,t=ot,n=o=>K===o,s=fo){const o=async()=>{if(!n(e))return;let r="pending";try{r=await t(e)}catch{}if(r!=="done"){if(r==="expired"){n(e)&&(K=null);return}n(e)&&s(o,e.pollInterval)}};s(o,e.pollInterval)}function fo(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as ce,computeEmbedding as nt,hasEmbedProvider as ho,EMBED_PROVIDER as st}from"./embeddings.js";import{ZWEIT_MODELL as yo}from"./rangfolge-stellschrauben.js";import{tokenize as bo,splitMultiQuery as wo,levenshtein as vo,recencyBoost as xo,extractTimestamp as _o,STOPWORDS as $o,katakanaToRomaji as ko,arabicLightStem as So,expandCrossLingual as Ao,CROSS_LINGUAL_MAP as Co,ZERO_RESULTS_LOG as To,zeroResultsTotal as Io}from"./search.js";const oe=new Map;function Eo(e){return e<=1?200:null}async function H(e){if(!e)throw new ee(se.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=oe.get(e);return t||Bn(Ro,e,()=>jo(e))}const Ro=new Map;async function jo(e){Y("verbindung: Instanz abfragen");let t=await N(`/api/v1/instances/${e}`);if(Y(`verbindung: Instanz ${t.status}`),t=await jn(t,()=>N(`/api/v1/instances/${e}`),{fristMs:oo,melde:a=>Y(`verbindung: Instanz ${a.status}`)}),t.status!=="running"){fetch(`${v}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...y?{Authorization:`Bearer ${y}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:t.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let a;throw t.status==="provisioning"?a=`\u23F3 Brain instance "${t.name}" is still starting up.
|
|
10
10
|
|
|
11
11
|
First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:t.status==="failed"?a=`\u274C Brain instance "${t.name}" failed to start.
|
|
12
12
|
|
|
@@ -18,41 +18,41 @@ Update your payment method at: ${E("/billing","upgrade")}`:t.status==="pending_p
|
|
|
18
18
|
Complete your checkout at: ${E("/instances","upgrade")}`:a=`Brain instance "${t.name}" is not reachable (status: ${t.status}).
|
|
19
19
|
|
|
20
20
|
\u2022 View your instance at: ${E("/instances","instance-error")}
|
|
21
|
-
\u2022 Run \`get_api_status\` for a full diagnostic.`,new
|
|
21
|
+
\u2022 Run \`get_api_status\` for a full diagnostic.`,new ee(se.InvalidRequest,a)}if(!t.host||!t.port)throw new ee(se.InternalError,`Instance "${t.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let n,s;try{const a=await N(`/api/v1/instances/${e}/connection`);n=a.password??void 0,s=a,Y("verbindung: Zugangsdaten da")}catch(a){const d=a instanceof Error?a.message:String(a);if(d.includes("401")||d.includes("403")||d.includes("Unauthorized"))throw new ee(se.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const o=wt({host:t.host,port:t.port,tls_enabled:t.tls_enabled},s),r=new Qe({host:o.host,port:o.port,password:n||void 0,commandTimeout:8e3,...o.tls?{tls:o.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:Eo,maxRetriesPerRequest:1,keepAlive:15e3}),c=()=>{oe.delete(e),r.disconnect()};r.on("error",c),r.on("end",c);try{await r.connect()}catch(a){r.disconnect();const d=a instanceof Error?a.message:String(a);throw fetch(`${v}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...y?{Authorization:`Bearer ${y}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:t.host,port:t.port,error:d,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new ee(se.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 oe.set(e,r),Y("verbindung: Valkey verbunden"),r}async function N(e,t={},n=!1){n||Ue(Se(y))!=="none"&&await Re(),Ut(y);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),o=await fetch(`${v}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`,...t.headers}});if(!o.ok){if(o.status===401&&!n&&(Ee=0,await Re()))return N(e,t,!0);const c=(await o.json().catch(()=>({error:o.statusText}))).error??o.statusText;Jt(o.status,c)}if(o.status!==204)return o.json()}import{handleBrainTool as Bo}from"./handlers/brain.js";import{handleContextTool as Lo}from"./handlers/context.js";import{handleInstanceTool as Po}from"./handlers/instances.js";import{handleCacheTool as Oo}from"./handlers/cache.js";import{handleTeamTool as No}from"./handlers/team.js";import{handleRoadmapTool as Ho}from"./handlers/roadmap.js";import{handleAdvancedTool as Mo}from"./handlers/advanced.js";import{handleSyndicateTool as Do}from"./handlers/syndicate.js";import{handleFedbrainTool as je,_lastBrainFromGitCounts as we}from"./handlers/fedbrain.js";import{extractFirstRecallProof as zo,extractTopHit as Uo,fuersTerminal as it,renderFirstRecallProof as Jo}from"./first-recall-proof.js";import{aussetzerLeise as Wo}from"./aussetzer.js";import{installClsPostCommitHook as rt,CLS_HOOK_VERSION as at}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as Fo,CLAUDE_MD_MARKER_END as Yo,EDITOR_FILES as me,ANWEISUNGS_DATEIEN as Ko,buildClaudeMdBlock as ct,setzeAnweisungsblock as qo,sollSchreiben as Go}from"./projektdateien.js";import{uninstallBefehl as Vo}from"./uninstall.js";import{gitLesen as lt}from"./git-ohne-shell.js";import{browserAdresse as Zo,fuerCmd as Qo}from"./browser-adresse.js";import{installAmbientHooks as dt,installCursorHooks as Xo,installCopilotHooks as en,installCodexHooks as tn,installGeminiHooks as on,AMBIENT_HOOK_VERSION as ut,COPILOT_HOOKS_DATEI as nn,CODEX_HOOKS_DATEI as sn,GEMINI_SETTINGS_DATEI as rn}from"./ambient-hooks.js";import{hookHauptlauf as an,auffrischenHauptlauf as cn,startwissenImportHauptlauf as ln}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as dn}from"./startwissen-hook.js";import{rahmeAntwort as un}from"./antwort-rahmen.js";import{appendLedgerEntry as pn,readLedger as pt,defaultLedgerPath as mn,reportLedgerEntry as gn,teileNachInstanz as fn}from"./ambient-ledger.js";import{installCodexMcp as hn,installGeminiMcp as yn}from"./editor-mcp-eintrag.js";import{resolveApiKey as Be,saveApiKey as Z,saveInstanceId as Le,readSavedApiKey as ve,readInstanceId as Pe}from"./credentials.js";import{KEYCLOAK_BASIS as mt,istTestSchluessel as bn,waehleTestSchluessel as wn,starteKeycloakAnmeldung as vn,warteAufKeycloakAnmeldung as xn,uebernimm as _n,brainImKonto as $n,erfolgsText as kn,fehlerText as Sn,ersetzeSchluessel as An}from"./uebernahme.js";import{WARTE_TAKT_MS as Cn,auftragLiegt as gt,nimmAuftrag as Tn,sichereKonto as In,sperreLiegt as En,startwissenEingeschaltet as ft}from"./konto-anlegen.js";import{sichereZugang as Rn,echterWert as xe}from"./zugang.js";import{zeitpunkt as Y}from"./zeitmessung.js";import{warteAufLaufendeInstanz as jn,gemeinsamerAufbau as Bn}from"./instanz-warten.js";import{merkeNeuesBrain as Oe,startetLautLetztemBlick as Ln,setzeCommitQuelle as Pn}from"./leeres-brain.js";import{starteStartwissen as On,startwissenGestartet as Nn,beanspruchStartwissen as Hn,holeStartwissenHinweis as Mn,waehleProjektOrdner as Dn,startvorratErlaubt as zn,projektCommits as Un}from"./startwissen.js";import{eigeneFassung as Jn,pruefeNeueFassung as Wn,holeNeueFassungHinweis as Fn}from"./neue-fassung.js";import{beiStdinEnde as Yn}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Kn,starteBrandWachhund as qn}from"./brand-wachhund.js";import{sichtbareWerkzeuge as Gn,VERTEILER as ht}from"./werkzeug-auswahl.js";import{buildLessonsMarkdown as Vn,buildLessonsJsonl as Zn,vonRohLektion as Qn}from"./brain-export.js";import{detectEditor as Xn}from"./editor.js";import{milestoneSent as yt,markMilestoneSent as bt}from"./funnel-milestones.js";import{kostprobeUebrig as es,kostprobeVerbrauchen as ts,kostprobeHinweis as os,schrankeNachKostproben as ns}from"./kostprobe.js";import{netBalance as ss}from"./ambient-recall.js";import{handleShareTool as Ne}from"./handlers/share.js";import{handleVizTool as is}from"./handlers/viz.js";import{commitArt as rs,istRueckbau as as,zaehleLektionen as cs}from"./commit-art.js";import{TOOLS as ge}from"./tools.js";import{verbindungsWeg as wt}from"./brains-tls.js";let vt=!1,xt=!1,_e=!1;function _t(){return Xn()}function ls(e){try{const t=e.split(".");if(t.length!==3)return;const n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf-8"));if(!n.sub)return;let s=2166136261;for(let o=0;o<n.sub.length;o++)s^=n.sub.charCodeAt(o),s=s*16777619>>>0;return s.toString(16).padStart(8,"0")+n.sub.length.toString(16).padStart(4,"0")}catch{return}}function $(e,t,n){if(process.env.CACHLY_NO_TELEMETRY==="1")return;const s=y?ls(y):void 0;fetch(`${v}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:e,version:M,editor:_t(),...y?{jwt:y}:{},...s?{user_fingerprint:s}:{},...n?{metrics:n}:{},...t}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}function ds(e,t){return gn({apiUrl:v,jwt:y,instanceId:e},t)}async function us(e){if(!vt&&process.env.CACHLY_NO_TELEMETRY!=="1"){vt=!0;try{await fetch(`${v}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:M,editor:_t(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const ps=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"]),ms={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."},$t=E("/billing","upgrade"),kt=new Map;async function gs(e){const t=kt.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const s=((await N(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),o={tier:s,isFree:s==="free"||s===""};return kt.set(e,{info:o,expiresAt:Date.now()+6e4}),o}catch{return{tier:"unknown",isFree:!1}}}async function fs(e,t){if(!ps.has(e)||!t)return null;const{isFree:n}=await gs(t);if(!n)return null;const s=ms[e]??"A Premium intelligence feature.";if(es(e)){const o=ts(e);return{kostprobe:os(e,o,$t)}}return{sperre:ns(e,s,$t)}}async function hs(e,t){try{await(await H(e)).hincrby(Kt(e),t,1)}catch{}}async function ys(e,t,n){if(qt(t))try{const s=await H(e),o=Zt(n);await s.incrby(Gt(e),o?Vt(n):0),await s.hincrby(Je(e),"abrufe",1),o&&await s.hincrby(Je(e),"treffer",1)}catch{}}async function bs(e){const t=await po();return t?(K=t,$("device_flow_started",{tool:e}),ae(t.verifyUrl,(n,s)=>{if(n){$("device_browser_opened",{stelle:"tool"});return}$("device_browser_failed",{reason:s??"unknown",stelle:"tool"}),process.stderr.write(`
|
|
26
|
+
cachly: could not open a browser (${s??"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
31
|
`)}),go(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 ${ge.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: ${E("/setup-ai","ambient-signin")}`,"","\u2728 Free tier includes: 1 Brain instance, persistent memory, semantic search."].join(`
|
|
33
|
-
`)}async function
|
|
34
|
-
`)}return
|
|
33
|
+
`)}async function ws(e){if(!e)return!0;if(Nn(e))return!1;try{return await Hn(await H(e),"sitzungsstart")}catch{return!0}}async function W(e,t){if(!y&&await Ie(no))return W(e,t);if(!y){if(us(e),K){const i=await ot(K);return i==="done"?W(e,t):i==="expired"?($("device_flow_failed",{reason:"timeout"}),K=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: **${K.verifyUrl}**`,`Code: **${K.userCode}**`,"","This completes automatically once you sign in \u2014 no need to come back here."].join(`
|
|
34
|
+
`)}return Rn({schluessel:y,konfigurierteInstanz:B,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{Y("sofort-test: Anfang");const i=await In({apiUrl:v,version:M,fristMs:so}),p=i.art==="angelegt"?i.test:i.art==="vorhanden"&&i.instanzId?{apiKey:i.apiKey,instanzId:i.instanzId}:null;return Y(`sofort-test: ${p?"Brain angelegt":"kein Test"}`),p&&Oe(p.instanzId,ie(),Te()),p},ablagen:{setzeSchluessel:i=>{y=i},setEmbedJwt:ce,saveApiKey:i=>Z(i),persistApiKeyToConfig:ue,merkeInstanz:i=>{B=i,V=0},persistInstanceIdToConfig:pe},meldeEreignis:$,werkzeug:()=>W(e,t),anmelden:()=>bs(e),neuesBrain:Ce})}if(!t.instance_id){const i=await tt();i&&(t={...t,instance_id:i})}const n=await fs(e,t.instance_id);let s="";if(n!==null){if("sperre"in n)return $("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;s=n.kostprobe,$("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&hs(t.instance_id,e),Y(`werkzeug ${e}: Zugang und Tarif geklaert`);const o=await Bo(e,t,H,N);if(Y(`werkzeug ${e}: Brain-Werkzeug fertig`),o!==null){typeof t.instance_id=="string"&&t.instance_id&&ys(t.instance_id,e,String(o??"")),!_e&&y&&(_e=!0,yt("first_call_success")||(bt("first_call_success"),$("first_call_success",{tool:e,instance_id:t.instance_id??B??""})));const i=t.instance_id??B??"",p=y?{api_key:y,instance_id:i}:{instance_id:i};if(e==="recall_best_solution")$("recall_best_solution",p);else if(e==="learn_from_attempts")$("learn_from_attempts",p);else if(e==="session_start"){$("session_start",p,{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??""),T=h.includes("Welcome! Your AI Brain is live.");if(!Ln(i)){if(!T&&h.length>100)$("recall_best_solution",p);else if(T&&t.workspace_path&&await ws(i))try{const R=await je("brain_from_git",{instance_id:i,repo_path:t.workspace_path,limit:50},H,N);if(R!==null){$("brain_from_git",{...p,...we??{}}),$("recall_best_solution",p);let C="";if((we?.total??0)===0)try{const L=await Ne("brain_seed_starter",{instance_id:i},H,N);L&&($("brain_seed_starter",{...p,auto:!0},{seeded_count:16,auto:!0}),C=`
|
|
35
35
|
---
|
|
36
|
-
`+String(
|
|
36
|
+
`+String(L))}catch{}const I=String(R),_=we?.total??0,k=_>0?`
|
|
37
37
|
\u2705 **Brain bootstrapped from git \u2014 ${_} lesson${_===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(I||C||k)return String(o)+k+`
|
|
38
38
|
---
|
|
39
|
-
`+I+C}}catch(
|
|
39
|
+
`+I+C}}catch(R){return $("brain_from_git_failed",{...p,reason:R instanceof Error?R.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="`+i+'", 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")
|
|
42
|
+
> Run \`brain_from_git(instance_id="`+i+'", 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")$("session_end",p);else if(e==="smart_recall"){const h=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),T=h.length>50&&!h.includes("No lessons found")&&!h.includes("no lessons")&&!h.includes("No matches found");if($("smart_recall",p,{hit:T,topic:String(t.query??"").slice(0,80)}),T&&$("recall_best_solution",p),re&&typeof o=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${re.split(`
|
|
43
43
|
`)[0]}
|
|
44
44
|
|
|
45
|
-
${o}`}return o}const r=await
|
|
46
|
-
`);let p="\u274C invalid JWT format";try{const
|
|
47
|
-
`)}}catch{p="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let h="";try{const A=(await
|
|
45
|
+
${o}`}return o}const r=await Lo(e,t,H,N);if(r!==null)return!_e&&y&&(_e=!0,yt("first_call_success")||(bt("first_call_success"),$("first_call_success",{tool:e,instance_id:t.instance_id??B??""}))),r;const c=await Po(e,t,H,N);if(c!==null)return c;const a=await Oo(e,t,H,N);if(a!==null)return a;const d=i=>s?i+s:i,g=await No(e,t,H,N);if(g!==null)return d(g);const l=await Ho(e,t,H,N);if(l!==null)return l;const m=await Mo(e,t,H,N);if(m!==null)return d(m);const x=await Do(e,t,H,N);if(x!==null){if(e==="brain_predict"){const i=t.instance_id??B??"";$("brain_predict",y?{api_key:y,instance_id:i}:{instance_id:i})}return d(x)}const w=await Ne(e,t,H,N);if(w!==null)return w;const b=await is(e,t,H,N);if(b!==null)return b;const u=await je(e,t,H,N);if(u!==null){const i=t.instance_id??B??"",p=y?{api_key:y,instance_id:i}:{instance_id:i};if(e==="brain_from_git"){const h=we;$("brain_from_git",{...p,...h??{}},h?{fixes:h.fixes,features:h.features,refactors:h.refactors,total:h.total}:void 0)}else e==="brain_predict_failures"&&$("brain_predict_failures",p);return u}switch(e){case"get_api_status":{let i="unknown";try{const R=await fetch(`${v}/health`,{signal:AbortSignal.timeout(8e3)});if(R.ok){const A=await R.json();i=`${A.status??"ok"} (db: ${A.db??"?"})`}else i=`HTTP ${R.status}`}catch(R){i=`unreachable: ${R.message}`}if(!y)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${v}`,` \u{1F493} Health: ${i}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${E("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
|
|
46
|
+
`);let p="\u274C invalid JWT format";try{const R=y.split(".");if(R.length===3){const A=JSON.parse(Buffer.from(R[1],"base64url").toString("utf-8")),C=A.sub??"(unknown)",I=A.iss??"(unknown)",_=I.includes("keycloak")?"Keycloak":"OIDC",k=A.exp?new Date(A.exp*1e3):null,L=k?k<new Date:!1;p=["\u2705 JWT decoded",` Sub (user ID): ${C}`,` Provider: ${_}`,` Issuer: ${I}`,` Expires: ${k?k.toISOString():"never"} ${L?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
|
|
47
|
+
`)}}catch{p="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let h="";try{const A=(await N("/api/v1/instances")).data??[];if(A.length===0)h=`
|
|
48
48
|
|
|
49
49
|
\u{1F9E0} **Brain Instances:** none \u2014 create one at ${E("/instances","api-status")}`;else{const C=[`
|
|
50
50
|
|
|
51
|
-
\u{1F9E0} **Brain Instances:**`];for(const I of A){const _=I.status==="running"?"\u{1F7E2}":I.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",k=I.id===
|
|
52
|
-
`)}}catch(
|
|
51
|
+
\u{1F9E0} **Brain Instances:**`];for(const I of A){const _=I.status==="running"?"\u{1F7E2}":I.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",k=I.id===B?" \u2190 active":"";if(C.push(` ${_} **${I.name}** (\`${I.id}\`) \xB7 ${I.status}${k}`),I.status==="running"&&I.host){const L=oe.get(I.id);if(L)try{await L.ping(),C.push(" \u{1F493} Redis: connected")}catch{C.push(" \u26A0\uFE0F Redis: pooled but ping failed \u2014 will reconnect on next use")}else C.push(" \u{1F4A4} Redis: not connected yet (connects on first tool use)")}else I.status==="provisioning"?C.push(" \u23F3 Still provisioning \u2014 check back in ~30 s"):I.status!=="running"&&C.push(` \u274C Not reachable (status: ${I.status})`)}h=C.join(`
|
|
52
|
+
`)}}catch(R){h=`
|
|
53
53
|
|
|
54
|
-
\u{1F9E0} **Brain Instances:** could not fetch \u2014 ${
|
|
55
|
-
`)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${
|
|
54
|
+
\u{1F9E0} **Brain Instances:** could not fetch \u2014 ${R.message}`}await Re();const T=Se(y),P=T.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":T.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${T.expiresInMs?` (${Math.round(T.expiresInMs/36e5)}h left)`:""}`:T.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${T.message.split(`
|
|
55
|
+
`)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${v}`,` \u{1F493} Health: ${i}`,` ${P}`,"","\u{1F511} **Auth:**",p,h].join(`
|
|
56
56
|
`)}default:throw new St(`Unknown tool: ${e}`)}}class St extends Error{}const At=`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.
|
|
@@ -62,44 +62,44 @@ This project has a Cachly AI Brain \u2014 persistent, cross-session memory of pa
|
|
|
62
62
|
- AFTER a fix, deploy, or discovery: call learn_from_attempts so the knowledge persists.
|
|
63
63
|
- BEFORE a risky op (deploy, migration, dependency bump): call brain_predict.
|
|
64
64
|
|
|
65
|
-
The Brain instance id comes from the CACHLY_BRAIN_INSTANCE_ID environment variable.`,Ct={tools:{},resources:{},prompts:{}},Tt=async()=>{const{katalog:e,unbekannteKernnamen:t}=
|
|
65
|
+
The Brain instance id comes from the CACHLY_BRAIN_INSTANCE_ID environment variable.`,Ct={tools:{},resources:{},prompts:{}},Tt=async()=>{const{katalog:e,unbekannteKernnamen:t}=Gn(ge);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function It(){return{resources:[]}}async function Et(){return{resourceTemplates:[]}}async function Rt(){return{prompts:[]}}function vs(e){e.setRequestHandler(Ze,Tt),e.setRequestHandler(Ke,Lt),e.setRequestHandler(Ve,It),e.setRequestHandler(Ge,Et),e.setRequestHandler(qe,Rt)}function xs(){const e=new Ye({name:"cachly-mcp",version:M},{capabilities:Ct,instructions:At});return vs(e),jt(e),e}function jt(e){const t=e.oninitialized;e.oninitialized=()=>{let n;try{n=e.getClientVersion(),Dt(n?.name,n?.version)}catch{}xt||(xt=!0,$("mcp_verbunden",{client:String(n?.name??"unbekannt").slice(0,60),client_version:String(n?.version??"").slice(0,30)})),t?.()}}const q=new Ye({name:"cachly-mcp",version:M},{capabilities:Ct,instructions:At});jt(q),q.setRequestHandler(Ze,Tt),q.setRequestHandler(Ve,It),q.setRequestHandler(Ge,Et),q.setRequestHandler(qe,Rt);let He=null,fe=!1,Q=null,Bt=0;async function _s(e){if(!fe){if(Q){await Q;return}Q=(async()=>{fe=!0,He=e;try{await W("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{Q=null}})(),await Q,process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await H(e),n=await t.get(`cachly:index:last_indexed:${e}`),s=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>s)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),await W("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code",hintergrund:!0}))})().catch(()=>{})}}async function Me(){if(!(!fe||!He)){fe=!1;try{await W("session_end",{instance_id:He,summary:`Auto-ended after ${Bt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Lt=async e=>{let{name:t,arguments:n}=e.params;if(t===ht){const o=n??{},r=typeof o.tool=="string"?o.tool:"";if(!r)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const c=ge.find(a=>a.name===r);if(!c)return{content:[{type:"text",text:`Kein Werkzeug namens "${r}". Die Liste steht in der Beschreibung von ${ht}.`}],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=r,n=o.arguments??{}}const s=new Set(["session_start","session_start_summary","session_end","auto_learn_session"]);if(!s.has(t)&&!fe&&!Q){const o=xe(n?.instance_id)||B||xe(process.env.CACHLY_BRAIN_INSTANCE_ID);o&&await _s(o).catch(()=>{})}else Q&&await Q.catch(()=>{});s.has(t)||Bt++;try{Kn(),Y(`werkzeug ${t}: Anfang`);const o=await W(t,n??{});return Y(`werkzeug ${t}: Antwort fertig`),{content:[{type:"text",text:un(t,o)+Mn()+Fn(t)}]}}catch(o){if(o instanceof St)return{content:[{type:"text",text:o.message}],isError:!0};if(o instanceof ee)throw o;const r=o.message??String(o);throw We("cachly","tool_error",{tool:t,error:r}).catch(()=>{}),new ee(se.InternalError,r)}};q.setRequestHandler(Ke,Lt),process.on("SIGTERM",async()=>{await Me().catch(()=>{});for(const[,e]of oe)await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await Me().catch(()=>{});for(const[,e]of oe)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}
|
|
66
66
|
`)}),process.on("uncaughtException",e=>{process.stderr.write(`[cachly-mcp] uncaughtException: ${e?.stack??String(e)}
|
|
67
|
-
`)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function
|
|
68
|
-
`)}catch{}}if(
|
|
67
|
+
`)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function $s(e,t){const n=Object.entries(t).map(([s,o])=>`${s}=${o}`);return e==="codex"?{befehl:`codex mcp add cachly ${n.map(s=>`--env ${s}`).join(" ")} -- npx -y @cachly-dev/mcp-server@latest`,wo:"~/.codex/config.toml"}:e==="gemini"?{befehl:`gemini mcp add -s project ${n.map(s=>`-e ${s}`).join(" ")} cachly npx -- -y @cachly-dev/mcp-server@latest`,wo:".gemini/settings.json"}:null}const Pt="https://api.cachly.dev";function X(e,t,n={}){const s={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(s.CACHLY_JWT=e),v&&v!==Pt&&(s.CACHLY_API_URL=v),s}function ks(e,t,n){return n==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:X(e,t)}]}},null,2):n==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:X(e,t)},settings:{}}}},null,2):Ot(n)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:X(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:X(e,t)}}},null,2)}function Ot(e){return me[e]===".vscode/mcp.json"}function he(e,t){bn(e)||Z(e,t)}async function Nt(e,t,n,s,o,r={}){const c={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:X(t,n)};if(!o.existsSync(e))return ks(t,n,s);let a={};try{a=JSON.parse(await o.readFile(e,"utf-8"))}catch{try{const{rename:m}=await import("node:fs/promises");await m(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
|
|
68
|
+
`)}catch{}}if(s==="continue"){const m=a.experimental??{},x=m.modelContextProtocolServers??[];let w;for(const u of x){const i=u.env??{};if(i.CACHLY_JWT){w=i.CACHLY_JWT;break}}w&&he(w,r);const b=x.filter(u=>{const i=u.env??{};return!i.CACHLY_JWT&&!i.CACHLY_BRAIN_INSTANCE_ID});return b.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:c.env}),a.experimental={...m,modelContextProtocolServers:b},JSON.stringify(a,null,2)}if(s==="zed"){const m=a.context_servers??{},w=m.cachly?.command?.env?.CACHLY_JWT;return w&&he(w,r),m.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:c.env},settings:{}},a.context_servers=m,JSON.stringify(a,null,2)}if(Ot(s)){const m=a.mcpServers??void 0,w=m?.cachly?.env?.CACHLY_JWT;w&&he(w,r),m&&"cachly"in m&&(delete m.cachly,Object.keys(m).length===0&&delete a.mcpServers);const b=a.servers??{},u=b.cachly,i=u?.env?.CACHLY_JWT;return i&&he(i,r),b.cachly=u?.envFile?{type:"stdio",...c,envFile:u.envFile}:{type:"stdio",...c},a.servers=b,JSON.stringify(a,null,2)}const d=a.mcpServers??{},l=d.cachly?.env?.CACHLY_JWT;return l&&he(l,r),d.cachly=c,a.mcpServers=d,JSON.stringify(a,null,2)}async function Ht(e,t,n){const{existsSync:s}=await import("node:fs"),{resolve:o}=await import("node:path"),{homedir:r}=await import("node:os"),c=n??r(),a=Ko.filter(l=>Go(l,e,c,s,o)).map(l=>({path:o(e,...l.pfad),prefix:l.prefix})),d=ct(t),g={};for(const{path:l,prefix:m}of a)try{g[l]=await qo(l,d,m)}catch(x){g[l]=`failed:${x.message}`}return g}function Mt(e,t){return t.startsWith("failed:")?`\u26A0\uFE0F Could not write ${e}: ${t.slice(7)} (the rest of the setup continues)`:`${t==="updated"?"\u2705 Updated":t==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${e}`}if(process.argv[2]==="digest"){const e=te(),t=J();(!e||!t)&&(console.log(`
|
|
69
69
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
70
70
|
`),process.exit(1)),process.stdout.write(`
|
|
71
71
|
\u{1F9E0} Fetching your weekly Brain digest...
|
|
72
72
|
|
|
73
|
-
`);try{const
|
|
73
|
+
`);try{const n=await fetch(`${v}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,r=s.total_recall_count??0,c=Math.round(s.iq_boost_pct??0),a=(s.top_lessons??[]).slice(0,5),d=s.team_authors??[],g=r*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}",m=new Date,x=new Date(m);x.setDate(m.getDate()-7);const w=p=>p.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(x)} \u2013 ${w(m)}\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(r).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(c).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+Math.round(g/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`)),a.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 p of a){const h=`${p.topic}: ${p.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 b=a[0],u=[`\u{1F9E0} My AI Brain weekly digest (${w(x)} \u2013 ${w(m)}):`,"",` \u{1F4DA} ${o} lessons learned`,` \u{1F501} ${r} recalls \xB7 ~${Math.round(g/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${l}`,b?` \u{1F525} Top lesson: "${b.topic}: ${b.what_worked.slice(0,60)}${b.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
|
|
74
74
|
`),i="https://twitter.com/intent/tweet?text="+encodeURIComponent(u);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const p of u.split(`
|
|
75
|
-
`))console.log(` ${p}`);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${i.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite\x1B[0m"),console.log(" \x1B[2m Cron: 0 9 * * 1 npx @cachly-dev/mcp-server@latest digest\x1B[0m"),console.log("")}catch(
|
|
76
|
-
\u274C Could not fetch digest: ${
|
|
77
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="export"){const{writeFile:e,mkdir:t}=await import("node:fs/promises"),{resolve:
|
|
75
|
+
`))console.log(` ${p}`);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${i.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite\x1B[0m"),console.log(" \x1B[2m Cron: 0 9 * * 1 npx @cachly-dev/mcp-server@latest digest\x1B[0m"),console.log("")}catch(n){console.log(`
|
|
76
|
+
\u274C Could not fetch digest: ${n.message}
|
|
77
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="export"){const{writeFile:e,mkdir:t}=await import("node:fs/promises"),{resolve:n}=await import("node:path"),s=process.argv.slice(3),o=g=>{const l=s.indexOf(`--${g}`);return l!==-1?s[l+1]:void 0},r=o("format")??"both";r!=="md"&&r!=="jsonl"&&r!=="both"&&(console.log(`
|
|
78
78
|
\u274C Unknown --format "${r}" \u2014 use md, jsonl, or both.
|
|
79
|
-
`),process.exit(1));const c=
|
|
79
|
+
`),process.exit(1));const c=n(o("out")??"."),a=y||Be()||"",d=J();(!a||!d)&&(console.log(`
|
|
80
80
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
81
81
|
`),process.exit(1)),process.stdout.write(`
|
|
82
82
|
\u{1F4E4} Exporting your Brain...
|
|
83
83
|
|
|
84
|
-
`);try{let g=[],l="";const m=await fetch(`${
|
|
85
|
-
`),process.exit(0)),await t(c,{recursive:!0});const
|
|
84
|
+
`);try{let g=[],l="";const m=await fetch(`${v}/api/v1/instances/${d}/export`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(12e4)});if(m.ok){const w=await m.json();g=(w.lessons??[]).map(Qn).filter(b=>b!==null),w.complete===!1&&(l=w.note??"the server reported an incomplete read")}else if(m.status===404){const w=await fetch(`${v}/api/v1/instances/${d}/memory`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(8e3)});if(!w.ok)throw new Error(`memory HTTP ${w.status}`);g=((await w.json()).top_lessons??[]).map(u=>({topic:u.topic,outcome:u.outcome,severity:u.severity,tags:u.tags,whatWorked:u.what_worked,ts:u.ts,author:u.author,recallCount:u.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 ${m.status}`);g.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
|
|
85
|
+
`),process.exit(0)),await t(c,{recursive:!0});const x=[];if(r==="md"||r==="both"){const w=n(c,"lessons.md");await e(w,Vn(g),"utf-8"),x.push(`${g.length} lesson${g.length===1?"":"s"} \u2192 ${w}`)}if(r==="jsonl"||r==="both"){const w=n(c,"lessons.jsonl");await e(w,Zn(g),"utf-8"),x.push(`${g.length} lesson${g.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 x)console.log(` ${w}`);console.log("")}catch(g){console.log(`
|
|
86
86
|
\u274C Could not export your Brain: ${g.message}
|
|
87
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=
|
|
87
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=te();e||(console.log(`
|
|
88
88
|
\u26A0\uFE0F No cachly key found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
89
|
-
`),process.exit(1));try{const t=await fetch(`${
|
|
89
|
+
`),process.exit(1));try{const t=await fetch(`${v}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json(),s=n.url??E(`/r/${n.code}`,"invite"),o=n.referral_count??0,r=`Hey, I've been using cachly to give my AI persistent memory across sessions \u2014 no more re-explaining my stack every morning.
|
|
90
90
|
|
|
91
|
-
You get a free Brain: ${
|
|
91
|
+
You get a free Brain: ${s}`,c=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
|
|
92
92
|
|
|
93
|
-
Try it free: ${
|
|
93
|
+
Try it free: ${s}
|
|
94
94
|
|
|
95
|
-
@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 Brain invite 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 ${
|
|
95
|
+
@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 Brain invite 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 ${s.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 a of r.split(`
|
|
96
96
|
`))console.log(`\u2502 \x1B[90m${a.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("")}catch(t){console.log(`
|
|
97
97
|
\u274C Could not fetch invite link: ${t.message}
|
|
98
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:
|
|
98
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:r}=await import("node:path"),{homedir:c}=await import("node:os"),{createInterface:a}=await import("node:readline"),d=process.argv[3]??"";d||(console.log(`
|
|
99
99
|
\u274C Usage: npx @cachly-dev/mcp-server@latest join <token>
|
|
100
100
|
`),console.log(` Get a token from a teammate: npx @cachly-dev/mcp-server@latest invite
|
|
101
101
|
`),process.exit(1)),console.log(`
|
|
102
|
-
\u23F3 Looking up invite...`);let g;try{const A=await fetch(`${
|
|
102
|
+
\u23F3 Looking up invite...`);let g;try{const A=await fetch(`${v}/api/invite/${d}`,{signal:AbortSignal.timeout(8e3)});A.status===404&&(console.log(`
|
|
103
103
|
\u274C Invite not found \u2014 the link may be invalid.
|
|
104
104
|
`),process.exit(1)),A.status===410&&(console.log(`
|
|
105
105
|
\u274C This invite link has expired (7-day limit).
|
|
@@ -107,38 +107,38 @@ Try it free: ${n}
|
|
|
107
107
|
\u274C Could not fetch invite: HTTP ${A.status}
|
|
108
108
|
`),process.exit(1)),g=await A.json()}catch(A){console.log(`
|
|
109
109
|
\u274C Network error: ${A.message}
|
|
110
|
-
`),process.exit(1)}const{instance_id:l,instance_name:m,tier:
|
|
110
|
+
`),process.exit(1)}const{instance_id:l,instance_name:m,tier:x,label:w}=g,b=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${m}\x1B[0m`),console.log(` Tier : ${x}`),w&&console.log(` Note : ${w}`),console.log(` Expires : ${b}`),console.log("");const u=a({input:process.stdin,output:process.stdout}),i=await new Promise(A=>{u.question(" Join this Brain? [Y/n] ",C=>{u.close(),A(C.trim().toLowerCase()||"y")})});i!=="y"&&i!=="yes"&&(console.log(`
|
|
111
111
|
Cancelled.
|
|
112
112
|
`),process.exit(0));let p=y;if(!p){console.log(`
|
|
113
113
|
No API key found \u2014 starting sign-in (10 seconds)...
|
|
114
|
-
`);try{const A=await fetch(`${
|
|
115
|
-
`);const I=(C.interval??5)*1e3;for(let _=0;_<24;_++){await new Promise(k=>setTimeout(k,I));try{const k=await fetch(`${
|
|
114
|
+
`);try{const A=await fetch(`${v}/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(A.ok){const C=await A.json();console.log(` \u{1F449} Open: \x1B[36m${C.verification_uri}\x1B[0m`),console.log(` Code: \x1B[1m${C.user_code}\x1B[0m
|
|
115
|
+
`);const I=(C.interval??5)*1e3;for(let _=0;_<24;_++){await new Promise(k=>setTimeout(k,I));try{const k=await fetch(`${v}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:C.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(k.ok){const L=await k.json();if(L.access_token){p=L.access_token;break}}}catch{}}p||(console.log(`
|
|
116
116
|
\u274C Sign-in timed out. Run the command again.
|
|
117
117
|
`),process.exit(1)),console.log(` \u2705 Signed in!
|
|
118
118
|
`)}}catch(A){console.log(`
|
|
119
119
|
\u26A0\uFE0F Could not start sign-in: ${A.message}`),console.log(` Set CACHLY_JWT manually from ${E("/setup-ai","join")}
|
|
120
|
-
`),process.exit(1)}}p&&p!==y&&
|
|
120
|
+
`),process.exit(1)}}p&&p!==y&&Z(p);const h=process.cwd(),T=c(),P=[{label:".mcp.json (Claude Code project)",path:o(h,".mcp.json")},{label:".cursor/mcp.json",path:o(h,".cursor","mcp.json")},{label:".windsurf/mcp.json",path:o(h,".windsurf","mcp.json")},{label:".vscode/mcp.json (Copilot/Cline)",path:o(h,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:o(T,".claude","mcp.json"),global:!0}];let R=0;for(const{label:A,path:C,global:I}of P){const _=r(C);if(!(!I&&!s(_)&&!s(C)))try{await n(_,{recursive:!0});let k={};if(s(C))try{k=JSON.parse(await t(C,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(C,C+".bak")}catch{}}const L=k.mcpServers??{},ne=L.cachly??{},F=ne.env??{};F.CACHLY_BRAIN_INSTANCE_ID=l,p&&I&&!F.CACHLY_JWT&&(F.CACHLY_JWT=p),v!==Pt&&(F.CACHLY_API_URL=v),L.cachly={...ne,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:F},k.mcpServers=L,await e(C,JSON.stringify(k,null,2),"utf-8"),console.log(` \u2705 ${A}`),R++}catch(k){k.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${A}: ${k.message}`)}}console.log(""),R===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${m}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
|
|
121
121
|
`),console.log(" \u{1F4DB} Add the badge to your README:"),console.log(` npx @cachly-dev/mcp-server@latest badge
|
|
122
122
|
`)),process.exit(0)}if(process.argv[2]==="upgrade"){process.stdout.write(`
|
|
123
123
|
\u23F3 Checking for updates...
|
|
124
|
-
`);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
|
|
125
|
-
\u2705 Already on the latest version: \x1B[32mv${
|
|
126
|
-
`):(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${
|
|
124
|
+
`);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 n=(await e.json()).version;if(!n||!/^\d+\.\d+\.\d+/.test(n))throw new Error("npm registry returned unexpected response");n===M?console.log(`
|
|
125
|
+
\u2705 Already on the latest version: \x1B[32mv${M}\x1B[0m
|
|
126
|
+
`):(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${M}\x1B[0m`),console.log(` Latest : \x1B[32mv${n}\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(`
|
|
127
127
|
\u274C Could not check for updates: ${e.message}
|
|
128
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:
|
|
128
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:n}=await import("node:path"),{loadExternalCorpus:s,runExternalBenchmark:o}=await import("./bench/external-corpus.js"),r=process.argv.includes("--json"),c=process.argv.slice(3).find(g=>!g.startsWith("--")),a=t(e(import.meta.url)),d=c?n(process.cwd(),c):n(a,"bench","external","sample-corpus.json");try{const g=await s(d),l=await o(g);r&&(console.log(JSON.stringify({corpus:g.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 m=((l.cachly.precisionAt1-l.flatfile.precisionAt1)*100).toFixed(1),x=((l.cachly.mrr-l.flatfile.mrr)*100).toFixed(1),w=((l.cachly.precisionAt1-l.baseline.precisionAt1)*100).toFixed(1),b=l.cachly.precisionAt1>=l.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",u=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 : ${g.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 : ${b}${m}%\x1B[0m`),console.log(` MRR : ${u}${x}%\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)}% (${b}${m}% 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${E("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(g){console.error(`
|
|
129
129
|
\u274C bench failed: ${g.message}
|
|
130
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{existsSync:e,readFileSync:t}=await import("node:fs"),{resolve:
|
|
130
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{existsSync:e,readFileSync:t}=await import("node:fs"),{resolve:n,basename:s}=await import("node:path"),o=process.cwd();console.log(`
|
|
131
131
|
\x1B[35m\u{1F9E0} cachly Brain \u2014 Live Demo\x1B[0m`),console.log(`\x1B[90mNo account needed. Reading your git history...\x1B[0m
|
|
132
|
-
`),e(
|
|
132
|
+
`),e(n(o,".git"))||(console.log("\u26A0\uFE0F No git repository found here."),console.log(` Run this command inside a project directory with git history.
|
|
133
133
|
`),console.log(` Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo
|
|
134
|
-
`),process.exit(0));let r="";try{r=
|
|
134
|
+
`),process.exit(0));let r="";try{r=lt(o,["config","user.name"]).trim().split(" ")[0]??""}catch{}let c=s(o);try{const _=JSON.parse(t(n(o,"package.json"),"utf-8"));_.name&&(c=_.name.replace(/^@[^/]+\//,""))}catch{}let a="";try{a=lt(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.
|
|
135
135
|
`),process.exit(0)}const d=a.trim().split(`
|
|
136
|
-
`).filter(Boolean).map(_=>{const[k,
|
|
137
|
-
`),process.exit(0));const g=new Map,l=[],m=[],
|
|
136
|
+
`).filter(Boolean).map(_=>{const[k,L,ne,F]=_.split("|||");return{sha:(k??"").trim().slice(0,8),subject:(L??"").trim(),date:(ne??"").trim(),author:(F??"").trim()}});d.length===0&&(console.log(`\u26A0\uFE0F No commits found.
|
|
137
|
+
`),process.exit(0));const g=new Map,l=[],m=[],x=[],w=new Set;let b=0;for(const _ of d){const k=rs(_.subject);g.set(k,(g.get(k)??0)+1),as(_.subject)&&b++,k==="fix"&&l.length<5&&l.push(_.subject.slice(0,72)),k==="feat"&&m.length<5&&m.push(_.subject.slice(0,72)),k==="security"&&x.length<3&&x.push(_.subject.slice(0,72)),_.author&&w.add(_.author)}const u=cs(d.map(_=>_.subject)),i=`${d[d.length-1]?.date??"?"} \u2192 ${d[0]?.date??"?"}`,p=u>=501?"Oracle":u>=201?"Architect":u>=51?"Expert":u>=11?"Explorer":"Apprentice",T=`${r?`Hey ${r} \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} ${T.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${i.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(u).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(w.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${p.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(b).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 P=[...g.entries()].filter(([_])=>_!=="chore").sort((_,k)=>k[1]-_[1]),R=(_,k)=>"\u2588".repeat(Math.round(_/k*20)).padEnd(20),A=Math.max(...P.map(([,_])=>_),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[_,k]of P){const L={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[_]??"\u2022";console.log(`\u2502 ${L} \x1B[36m${_.padEnd(10)}\x1B[0m \x1B[35m${R(k,A)}\x1B[0m \x1B[33m${String(k).padStart(3)}\x1B[0m \u2502`)}if(x.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 x)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(m.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 m.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 C=new URLSearchParams({repo:c,commits:String(d.length),lessons:String(u),level:p,authors:String(w.size),reverts:String(b)}),I=E(`/preview?${C.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${I}\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=te(),t=J();(!e||!t)&&(console.log(`
|
|
138
138
|
\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)
|
|
139
139
|
`),process.exit(1)),process.stdout.write(`
|
|
140
140
|
\u{1F9E0} Fetching your Brain stats...
|
|
141
|
-
`);try{const
|
|
141
|
+
`);try{const n=await fetch(`${v}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,r=s.total_recall_count??0,c=Math.round(s.iq_boost_pct??0),a=r*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(r).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(c).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+(a/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 g=E("/","share"),l=`\u{1F9E0} My AI coding assistant now has persistent memory.
|
|
142
142
|
|
|
143
143
|
${o} lessons stored \xB7 ${r} recalls \xB7 ${d}
|
|
144
144
|
|
|
@@ -148,148 +148,144 @@ ${g}
|
|
|
148
148
|
|
|
149
149
|
#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(`
|
|
150
150
|
`).map(m=>` ${m}`).join(`
|
|
151
|
-
`)),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(
|
|
152
|
-
\u274C Could not fetch stats: ${
|
|
153
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="publish"){const e=
|
|
151
|
+
`)),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(n){console.log(`
|
|
152
|
+
\u274C Could not fetch stats: ${n.message}
|
|
153
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="publish"){const e=te(),t=J();(!e||!t)&&(console.log(`
|
|
154
154
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
155
|
-
`),process.exit(1));const
|
|
155
|
+
`),process.exit(1));const n=process.argv.indexOf("--title"),s=n!==-1?process.argv[n+1]??"My Brain Snapshot":"My Brain Snapshot",o=process.argv.includes("--public");process.stdout.write(`
|
|
156
156
|
\u{1F9E0} Publishing Brain snapshot...
|
|
157
|
-
`);try{const r=await fetch(`${
|
|
157
|
+
`);try{const r=await fetch(`${v}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let c=0,a=0;if(r.ok){const x=await r.json();c=x.lesson_count??0,a=x.total_recall_count??0}const d=await fetch(`${v}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:s,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",m=E(`/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${s.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(c).padEnd(10)}\x1B[0m Recalls: \x1B[36m${String(a).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${m.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(` ${m}`),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(r){console.log(`
|
|
158
158
|
\u274C Could not publish Brain: ${r.message}
|
|
159
|
-
`),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
|
|
160
|
-
\u274C Unknown format "${t}". Use one of: ${
|
|
159
|
+
`),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 s=process.argv.find(o=>o.startsWith("--format="));if(s)t=s.slice(9);else{const o=process.argv.indexOf("--format");o!==-1&&(t=process.argv[o+1]??"openapi")}}const n=["openapi","openai","anthropic","langchain"];n.includes(t)||(process.stderr.write(`
|
|
160
|
+
\u274C Unknown format "${t}". Use one of: ${n.join(", ")}
|
|
161
161
|
|
|
162
|
-
`),process.exit(1)),process.stdout.write(e(ge,t,
|
|
163
|
-
`,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=
|
|
162
|
+
`),process.exit(1)),process.stdout.write(e(ge,t,M)+`
|
|
163
|
+
`,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=J();e||(console.log(`
|
|
164
164
|
\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)
|
|
165
|
-
`),process.exit(1));const t=`${
|
|
165
|
+
`),process.exit(1));const t=`${v}/api/v1/badge/${e}`,n=E("/","badge"),s=`[](${n})`,o=`<a href="${n}"><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${s}\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)}if(!process.argv[2]&&process.stdout.isTTY){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,n)=>console.log(` \x1B[36m ${t.padEnd(22)}\x1B[0m ${n}`);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","Invite a teammate"),e("join <token>","Accept a Brain invite"),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 ${ge.length} MCP tools\x1B[0m`),console.log(""),process.exit(0)}const Ss={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:nn,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:sn,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:rn,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function As(e,t,n){if(!t)return;const{datei:s,name:o,wie:r}=Ss[e];if(t.hooks==="skipped"){console.log(`\u26A0\uFE0F ${n}${s} ${t.grund??"is not valid JSON"} \u2014 left untouched, ${o} hooks not wired`);return}const c=t.hooks==="unchanged"?"\u2713 ":"\u2705 ",a=t.hooks==="written"?"Written":t.hooks==="merged"?"Merged":"Already wired";console.log(`${c}${n}${a}: ${s} (Ambient Recall for ${o} \u2014 ${r})`)}async function De(e,t,n,s){const o=e==="codex"?"Codex":"Gemini CLI",r=await(e==="codex"?hn:yn)(t,n).catch(()=>null);if(!r||r.status==="skipped"){const d=$s(e,n);console.log(`\u26A0\uFE0F ${s}${r?`${r.datei} ${r.grund??"could not be read"} \u2014 left untouched.`:`${o} MCP entry could not be written.`} Register cachly yourself:`),d&&console.log(` ${s}${d.befehl}`);return}const c=r.status==="unchanged"?"\u2713 ":"\u2705 ",a=r.status==="written"?"Written":r.status==="updated"?"Updated":"Already configured";console.log(`${c}${s}${a}: ${r.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,n,s){const o={cursor:Xo,copilot:en,codex:tn,gemini:on}[e];As(e,await o(t,n).catch(()=>null),s)}if(process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:n,readFile:s}=await import("node:fs/promises"),{resolve:o,dirname:r}=await import("node:path"),c=process.argv.slice(3),a=u=>{const i=c.indexOf(`--${u}`);return i!==-1?c[i+1]:void 0};let d=a("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,g=a("api-key")??process.env.CACHLY_JWT;const l=(a("editor")??"claude").toLowerCase(),m=o(a("project-dir")??"."),x=a("api-url");if(x&&(v=x.replace(/\/+$/,"")),!d||!g){const u=ve(),i=Pe();u&&i&&(g??=u,d??=i,g===u&&d===i&&console.log("\u2713 Reusing credentials from ~/.cachly/credentials.json (saved by a prior setup)"))}if(!d||!g)try{const{existsSync:u}=await import("node:fs"),i=process.env.HOME??process.env.USERPROFILE??"",p=i?o(i,".claude","mcp.json"):"";if(p&&u(p)){const T=JSON.parse(await s(p,"utf-8")).mcpServers?.cachly?.env??{};g??=T.CACHLY_JWT,d??=T.CACHLY_BRAIN_INSTANCE_ID,g&&d&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}if((!d||!g)&&(console.error(`
|
|
166
166
|
Usage: npx @cachly-dev/mcp-server@latest init --instance-id <uuid> --api-key <cky_live_...> [--editor claude|cursor|windsurf|copilot|continue|codex|gemini] [--project-dir /path] [--api-url https://your-self-hosted-backend]
|
|
167
167
|
`),console.error(`First time? Run the zero-config wizard (signs you in, auto-provisions): npx @cachly-dev/mcp-server@latest autopilot
|
|
168
168
|
`),console.error(`Get your credentials from: ${E("/setup-ai","init")}
|
|
169
|
-
`),process.exit(1)),l==="codex"||l==="gemini")
|
|
169
|
+
`),process.exit(1)),l==="codex"||l==="gemini")Z(g),console.log(""),await De(l,m,X(g,d),"");else{const u=me[l]??".mcp.json",i=o(m,u);await n(r(i),{recursive:!0});const{existsSync:p}=await import("node:fs"),h=p(i),T=h?await s(i,"utf-8").catch(()=>""):"";Z(g);const P=await Nt(i,g,d,l,{readFile:s,existsSync:p});P!==T?(await t(i,P,"utf-8"),console.log(`
|
|
170
170
|
\u2705 ${h?"Updated":"Written"}: ${u}`)):console.log(`
|
|
171
|
-
\u2713 Already configured: ${u} (no change)`)}const w=await Ht(m,d);for(const[u,i]of Object.entries(w))console.log(Mt(u.split(/[\\/]/).pop()??u,i));try{const u=await
|
|
171
|
+
\u2713 Already configured: ${u} (no change)`)}const w=await Ht(m,d);for(const[u,i]of Object.entries(w))console.log(Mt(u.split(/[\\/]/).pop()??u,i));try{const u=await rt(m,d);u==="written"?console.log("\u2705 Written: .git/hooks/post-commit (CLS hook)"):u==="upgraded"?console.log(`\u2705 Upgraded: .git/hooks/post-commit (CLS hook \u2192 ${at})`):u==="appended"?console.log("\u2705 Appended: .git/hooks/post-commit (CLS hook)"):u==="unchanged"&&console.log("\u2713 CLS hook already current in .git/hooks/post-commit")}catch{}if(l==="claude")try{const u=await dt(m,d);if(u.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${u.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const i=u.scripts==="written"?"\u2705 Written":u.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${ut})`:"\u2713 Unchanged";console.log(`${i}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),u.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):u.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{}(l==="cursor"||l==="copilot"||l==="codex"||l==="gemini")&&await ye(l,m,d,"");const b=((Date.now()-e)/1e3).toFixed(1);console.log(`
|
|
172
172
|
\u{1F9E0} Cachly AI Brain configured for ${l==="claude"?"Claude Code":l}! (${b}s)`),console.log(l==="codex"||l==="gemini"?` Start ${l} 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(`
|
|
173
173
|
\u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
|
|
174
|
-
`),process.exit(0)}if(process.argv[2]==="status"){const e=
|
|
174
|
+
`),process.exit(0)}if(process.argv[2]==="status"){const e=te(),t=J();(!e||!t)&&(console.log(`
|
|
175
175
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
176
|
-
`),process.exit(1));try{const[s
|
|
177
|
-
\u274C Could not fetch status: ${
|
|
178
|
-
`),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:
|
|
176
|
+
`),process.exit(1));try{const[n,s]=await Promise.all([fetch(`${v}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${v}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)})]);if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const o=await n.json(),r=s.ok?await s.json():null,c=o.lesson_count??0,a=o.total_recall_count??0,d=Math.round(o.iq_boost_pct??0),g=o.team_authors??[],l=r?.referral_count??0,m=r?.url??"",x=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${x.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Recalls : \x1B[36m${String(a).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(d).padEnd(3)}%\x1B[0m \u2502`),g.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 b=g.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(g.length).padEnd(2)} developer${g.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-b.length))} \u2502`),console.log(`\u2502 ${b.slice(0,56).padEnd(56)} \u2502`)}if(m){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 b=`${m.slice(0,44)}${m.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Invite link\x1B[0m \xB7 ${l>0?`\x1B[32m${l} joined\x1B[0m`:"share to grow your team"}${" ".repeat(Math.max(0,35-String(l).length))} \u2502`),console.log(`\u2502 \x1B[2m${b.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(n){console.log(`
|
|
177
|
+
\u274C Could not fetch status: ${n.message}
|
|
178
|
+
`),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:n}=await import("node:path"),s=process.cwd();let o=0,r=0;const c=u=>{console.log(` \u2705 ${u}`),o++},a=u=>{console.log(` \u26A0\uFE0F ${u}`)},d=u=>{console.log(` \u274C ${u}`),r++};console.log(`
|
|
179
179
|
\u{1F9E0} cachly health check
|
|
180
|
-
`),console.log("\u{1F511} Auth token");const g=
|
|
180
|
+
`),console.log("\u{1F511} Auth token");const g=te();if(!g)d("No cachly key found (environment or ~/.cachly/credentials.json) \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(g.startsWith("cky_"))c("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const u=g.split(".");if(u.length!==3)throw new Error("not a JWT");const i=JSON.parse(Buffer.from(u[1],"base64url").toString("utf-8")),p=i.exp?i.exp*1e3:null,h=p?Math.floor((p-Date.now())/6e4):null;p&&p<Date.now()?d(`JWT expired ${Math.abs(h)} minute(s) ago \u2014 get a new one: ${E("/setup-ai","health")}`):h!==null&&h<30?a(`JWT expires in ${h} minute(s) \u2014 refresh soon at ${E("/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(`
|
|
181
181
|
\u{1F310} Brain API`);const l=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const u=await fetch(`${l}/health`,{signal:AbortSignal.timeout(5e3)});if(u.ok){const i=await u.json();c(`${l} reachable (status: ${i.status??"ok"})`)}else u.status===401||u.status===403?c(`${l} reachable (auth required \u2014 expected)`):d(`${l}/health returned HTTP ${u.status}`)}catch(u){d(`${l} unreachable \u2014 ${u.message}`)}console.log(`
|
|
182
|
-
\u{1F9E0} Brain instance`);const m=
|
|
183
|
-
\u{1F50C} Redis connectivity`),i.host&&i.port)try{let p,h;try{const A=await fetch(`${l}/api/v1/instances/${m}/connection`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(A.ok){const C=await A.json();p=C.password,h=C}}catch{}const T=
|
|
184
|
-
\u{1F6E0} Editor configs (project dir)`);const
|
|
185
|
-
\u{1FA9D} Git hook (ambient learning)`);const b=s
|
|
186
|
-
\u{1F9EC} Embedding provider (semantic search)`);{const u=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],i=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase();if(i&&i!=="cachly"){const p=u.find(([,h])=>h===i)?.[0];p&&process.env[p]?c(`BYOK: ${i} (key present in ${p})`):a(`CACHLY_EMBED_PROVIDER=${i} but its key env var is not set \u2014 semantic search will fail`)}else{
|
|
182
|
+
\u{1F9E0} Brain instance`);const m=J();if(!m)a("No Brain instance found (environment or ~/.cachly/credentials.json) \u2014 will auto-resolve on first tool call");else if(g)try{const u=await fetch(`${l}/api/v1/instances/${m}`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(u.ok){const i=await u.json();if(i.status==="running")if(c(`Instance "${i.name}" (${m.slice(0,8)}\u2026) is running`),console.log(`
|
|
183
|
+
\u{1F50C} Redis connectivity`),i.host&&i.port)try{let p,h;try{const A=await fetch(`${l}/api/v1/instances/${m}/connection`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(A.ok){const C=await A.json();p=C.password,h=C}}catch{}const T=wt({host:i.host,port:i.port,tls_enabled:i.tls_enabled},h),P=new Qe({host:T.host,port:T.port,password:p,...T.tls?{tls:T.tls}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await P.connect();const R=await P.ping();P.disconnect(),R==="PONG"?c(`Redis PING \u2192 PONG (${T.host}:${T.port}, ${T.art==="klartext"?"unencrypted":"TLS"})`):a(`Redis responded but not PONG: ${R}`)}catch(p){d(`Redis unreachable \u2014 ${p.message}`)}else a("Instance has no host/port yet");else a(`Instance "${i.name}" status: ${i.status}`)}else d(`Instance ${m.slice(0,8)}\u2026 not found (HTTP ${u.status})`)}catch(u){d(`Could not check instance \u2014 ${u.message}`)}console.log(`
|
|
184
|
+
\u{1F6E0} Editor configs (project dir)`);const x=[{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"}];let w=0;for(const{editor:u,path:i}of x){const p=n(s,i);if(e(p))try{const h=await t(p,"utf-8");h.includes("@cachly-dev/mcp-server")||h.includes("cachly")?(c(`${u}: ${i}`),w++):a(`${u}: ${i} exists but cachly not found inside`)}catch{a(`${u}: ${i} exists but could not read`)}}w===0&&d("No editor MCP configs found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot"),console.log(`
|
|
185
|
+
\u{1FA9D} Git hook (ambient learning)`);const b=n(s,".git","hooks","post-commit");if(!e(n(s,".git")))a("Not in a git repository \u2014 skip");else if(e(b))try{(await t(b,"utf-8")).includes("cachly")?c(".git/hooks/post-commit (cachly CLS hook present)"):a(".git/hooks/post-commit exists but cachly hook not found \u2014 run setup to add it")}catch{a(".git/hooks/post-commit exists but could not read")}else a(".git/hooks/post-commit not found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");console.log(`
|
|
186
|
+
\u{1F9EC} Embedding provider (semantic search)`);{const u=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],i=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase();if(i&&i!=="cachly"){const p=u.find(([,h])=>h===i)?.[0];p&&process.env[p]?c(`BYOK: ${i} (key present in ${p})`):a(`CACHLY_EMBED_PROVIDER=${i} but its key env var is not set \u2014 semantic search will fail`)}else{st==="ollama"?c("Local Ollama (OLLAMA_BASE_URL) \u2014 text stays on your machine"):st==="cachly"?c("Server-side embeddings (cachly, EU) \u2014 no key needed, uses your JWT"):a("No embedding provider active \u2014 sign in (CACHLY_JWT) for EU-hosted embeddings; search runs on words until then");for(const[p,h]of u)h!=="ollama"&&process.env[p]&&c(`${p} is set but not used \u2014 ${h} runs only if you name it with CACHLY_EMBED_PROVIDER=${h}`)}}console.log(`
|
|
187
187
|
${"\u2500".repeat(40)}`),r===0?console.log(`\u2705 All checks passed (${o} ok)
|
|
188
188
|
`):(console.log(`\u274C ${r} check(s) failed, ${o} passed
|
|
189
189
|
`),console.log(`\u{1F4A1} Fix issues with: npx @cachly-dev/mcp-server@latest autopilot
|
|
190
|
-
`),process.exit(1)),process.exit(0)}if(process.argv[2]==="claim"){const{readFile:e,writeFile:t}=await import("node:fs/promises"),{existsSync:
|
|
190
|
+
`),process.exit(1)),process.exit(0)}if(process.argv[2]==="claim"){const{readFile:e,writeFile:t}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:s}=await import("node:path"),{homedir:o}=await import("node:os"),r=i=>{const p=process.argv.indexOf(`--${i}`);return p!==-1?process.argv[p+1]:void 0};v=(r("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const c=(r("auth-url")??mt).replace(/\/+$/,"");console.log(`
|
|
191
191
|
\u{1F9E0} cachly \u2014 keep your test Brain in your own account
|
|
192
|
-
`),(
|
|
193
|
-
`);const a=
|
|
192
|
+
`),(v!=="https://api.cachly.dev"||c!==mt)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${v}, sign-in ${c}
|
|
193
|
+
`);const a=wn({argument:r("key"),credentials:ve()});a||(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
|
|
194
194
|
`),process.exit(1));const d=a.schluessel,g={argument:"--key",credentials:"~/.cachly/credentials.json"}[a.quelle];console.log(`Test key: ${d.slice(0,14)}\u2026 (from ${g})
|
|
195
195
|
`);let l="";try{console.log(`Step 1: Sign in to your cachly account
|
|
196
|
-
`);const i=await
|
|
197
|
-
`),
|
|
198
|
-
\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
|
|
196
|
+
`);const i=await vn(fetch,c);console.log(` Code: \x1B[1;33m${i.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${i.adresse}
|
|
197
|
+
`),ae(i.adresse,(p,h)=>{p||console.log(`
|
|
198
|
+
\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 xn(fetch,i,{basis:c,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
|
|
199
199
|
`)}catch(i){console.error(`
|
|
200
200
|
|
|
201
201
|
${i.message}. Nothing was changed.
|
|
202
|
-
`),process.exit(1)}process.stdout.write("Step 2: Moving the test Brain into your account (it restarts once, up to a minute)\u2026");let m;try{m=await
|
|
202
|
+
`),process.exit(1)}process.stdout.write("Step 2: Moving the test Brain into your account (it restarts once, up to a minute)\u2026");let m;try{m=await _n(fetch,v,l,d,"mcp",`cachly-mcp/${M}`),console.log(` \x1B[32m\u2713\x1B[0m
|
|
203
203
|
`)}catch(i){console.error(`
|
|
204
204
|
|
|
205
|
-
${
|
|
206
|
-
`),process.exit(1)}y=m.apiKey,
|
|
205
|
+
${Sn(i)}
|
|
206
|
+
`),process.exit(1)}y=m.apiKey,Z(m.apiKey),Le(m.instanceId,{apiKey:m.apiKey}),await ue(m.apiKey),await pe(m.instanceId);const x=o(),w=new Set([...Object.values(me).map(i=>s(process.cwd(),i)),s(x,".claude.json"),s(x,".claude","mcp.json"),s(x,".cursor","mcp.json"),s(x,".codeium","windsurf","mcp_config.json")]);let b=0;for(const i of w)if(n(i))try{const p=An(await e(i,"utf-8"),d,m.apiKey);p.ersetzt&&(await t(i,p.text,"utf-8"),b++)}catch{}const u=await $n(fetch,v,m.apiKey,m.instanceId);console.log(kn(m,u)),console.log(`
|
|
207
207
|
New key stored in ~/.cachly/credentials.json${b?` and in ${b} 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.
|
|
208
|
-
`),process.exit(0)}const $e=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||$e){const{writeFile:e,mkdir:t,readFile:
|
|
209
|
-
`))
|
|
208
|
+
`),process.exit(0)}const $e=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||$e){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:r}=await import("node:path"),{createInterface:c}=await import("node:readline"),a=Date.now(),d=$e?"autopilot":"setup";Wo();const g=process.argv.indexOf("--api-url");g!==-1&&process.argv[g+1]&&(v=process.argv[g+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${v}
|
|
209
|
+
`)),$("setup_started");const l=process.stdin.isTTY===!0,m=$e||process.argv.includes("--yes")||process.argv.includes("-y")||!l;$e?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
|
|
210
210
|
`):!l&&!process.argv.includes("--yes")&&!process.argv.includes("-y")&&console.log(`\u2139\uFE0F Non-interactive terminal detected \u2014 running in automatic mode (no prompts).
|
|
211
|
-
`);const
|
|
211
|
+
`);const x=c({input:process.stdin,output:process.stdout}),w=(f,S="")=>m?(console.log(`${f}${S}`),Promise.resolve(S)):new Promise(j=>x.question(f,z=>j(z.trim()||S)));console.log(`
|
|
212
212
|
\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
|
|
213
213
|
`);let b=process.env.CACHLY_JWT??"";if(b)console.log(`\u2713 Using token from CACHLY_JWT env var
|
|
214
214
|
`);else{console.log(`Step 1: Sign in to cachly (free, no credit card)
|
|
215
|
-
`)
|
|
216
|
-
`),
|
|
217
|
-
`)}),process.stdout.write(" Waiting for authorization");const
|
|
218
|
-
`)
|
|
219
|
-
Auth error: ${
|
|
220
|
-
`),
|
|
215
|
+
`),$("setup_auth_started");let f="",S="",j="",z=5e3,U=!1,le="cachly";try{const G=await fetch(`${v}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(G.ok){const O=await G.json();f=O.device_code,S=O.user_code;const D=O.verification_uri||E("/device",d);j=`${D}${D.includes("?")?"&":"?"}code=${encodeURIComponent(S)}`,z=(O.interval??5)*1e3,U=!!f}}catch{}if(!U)try{const O=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(O.ok){const D=await O.json();f=D.device_code,S=D.user_code,j=D.verification_uri_complete,z=(D.interval??5)*1e3,U=!0,le="keycloak"}}catch{}if(U&&f){console.log(` Code: \x1B[1;33m${S}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${j}
|
|
216
|
+
`),ae(j,(O,D)=>{if(O){$("device_browser_opened",{stelle:"setup"});return}$("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.
|
|
217
|
+
`)}),process.stdout.write(" Waiting for authorization");const G=Date.now()+600*1e3;for(;Date.now()<G;){await new Promise(O=>setTimeout(O,z)),process.stdout.write(".");try{let O=null;if(le==="cachly")try{const D=await fetch(`${v}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:f}),signal:AbortSignal.timeout(8e3)});D.status<500&&(O=await D.json())}catch{}else{const D="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{O=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=${f}`,signal:AbortSignal.timeout(8e3)})).json()}catch{}}if(O?.access_token){b=O.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
|
|
218
|
+
`),$("setup_auth_completed"),$("device_flow_completed");break}O?.error==="slow_down"?z=Math.min(z+2e3,15e3):O?.error&&O.error!=="authorization_pending"&&($("device_flow_failed",{reason:O.error}),console.error(`
|
|
219
|
+
Auth error: ${O.error}. Aborting.
|
|
220
|
+
`),x.close(),process.exit(1))}catch{}}b||($("device_flow_failed",{reason:"timeout"}),console.error(`
|
|
221
221
|
Timed out waiting for authorization. Aborting.
|
|
222
|
-
`),
|
|
223
|
-
`),console.log(` URL: \x1B[36m${
|
|
224
|
-
`),
|
|
222
|
+
`),x.close(),process.exit(1)),console.log("")}else{$("device_flow_failed",{reason:"device_flow_unavailable"});const G=E("/setup-ai",d);console.log(` \u26A0\uFE0F Could not start automatic sign-in. Opening browser for web sign-in...
|
|
223
|
+
`),console.log(` URL: \x1B[36m${G}\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_...)
|
|
224
|
+
`),ae(G),m?($("device_flow_failed",{reason:"non_interactive_no_key"}),console.error(`
|
|
225
225
|
\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:
|
|
226
226
|
`),console.error(` \x1B[1mCACHLY_JWT=cky_live_xxx npx @cachly-dev/mcp-server@latest autopilot\x1B[0m
|
|
227
227
|
`),console.error(` Or add it to your editor's MCP config under env.CACHLY_JWT.
|
|
228
|
-
`),
|
|
228
|
+
`),x.close(),process.exit(1)):(b=await w(" Paste API key (cky_live_...): "),b||(console.error(`
|
|
229
229
|
API key is required. Aborting.
|
|
230
|
-
`),
|
|
230
|
+
`),x.close(),process.exit(1)),$("setup_auth_completed"),console.log(""))}}if(b.startsWith("eyJ")){process.stdout.write("\u23F3 Generating your API key...");try{const f=await fetch(`${v}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify({name:"cachly-mcp-setup",scope:"read_write"})});if(!f.ok)throw new Error(`HTTP ${f.status}`);const S=await f.json();if(!S.key)throw new Error("no key in response");b=S.key,console.log(` \u2713
|
|
231
231
|
`)}catch{console.log(` (skipped)
|
|
232
|
-
`)}}process.stdout.write("\u23F3 Fetching your instances...");let u=[];try{const f=await fetch(`${
|
|
232
|
+
`)}}process.stdout.write("\u23F3 Fetching your instances...");let u=[];try{const f=await fetch(`${v}/api/v1/instances`,{headers:{Authorization:`Bearer ${b}`}});if(!f.ok)throw new Error(`HTTP ${f.status}`);u=((await f.json()).data??[]).filter(j=>j.status==="running")}catch(f){const S=f.message;console.error(`
|
|
233
233
|
|
|
234
|
-
Failed to fetch instances: ${
|
|
235
|
-
`),
|
|
236
|
-
`),u.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const f=await fetch(`${
|
|
237
|
-
`),process.stdout.write("\u23F3 Waiting for instance to start");for(let z=0;z<45;z++){await new Promise(U=>setTimeout(U,3e3)),process.stdout.write(".");try{const U=await fetch(`${
|
|
234
|
+
Failed to fetch instances: ${S}`),S.includes("401")&&(console.error(`Token rejected. Get a valid token at ${E("/setup-ai",d)}
|
|
235
|
+
`),ae(E("/setup-ai",d))),x.close(),process.exit(1)}if(console.log(` found ${u.length}
|
|
236
|
+
`),u.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const f=await fetch(`${v}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${b}`,"Content-Type":"application/json"}});if(!f.ok)throw new Error(`HTTP ${f.status}`);const S=await f.json();if(S.instance)u=[S.instance];else if(S.instance_id){const j=S.instance_id;console.log(` \u2713 created (${j.slice(0,8)}\u2026)
|
|
237
|
+
`),process.stdout.write("\u23F3 Waiting for instance to start");for(let z=0;z<45;z++){await new Promise(U=>setTimeout(U,3e3)),process.stdout.write(".");try{const U=await fetch(`${v}/api/v1/instances/${j}`,{headers:{Authorization:`Bearer ${b}`}});if(U.ok){const le=await U.json();if(le.status==="running"){u=[le];break}}}catch{}}console.log("")}}catch(f){console.log(` failed: ${f.message}
|
|
238
238
|
`)}u.length===0&&(console.error(`
|
|
239
239
|
Could not create an instance automatically. Opening ${E("/instances",d)} \u2026
|
|
240
|
-
`),
|
|
240
|
+
`),ae(E("/instances",d)),x.close(),process.exit(1))}const i=u[0];u.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${i.name}`),console.log(` (Run with --instance-id <id> to use a different one)
|
|
241
241
|
`)),console.log(`\u2713 Instance: ${i.name} (${i.id.slice(0,8)}\u2026)
|
|
242
|
-
`)
|
|
243
|
-
`);const{existsSync:_}=await import("node:fs"),k=[];let
|
|
244
|
-
\
|
|
245
|
-
|
|
246
|
-
\
|
|
247
|
-
`).
|
|
248
|
-
`),console.log(
|
|
249
|
-
\u{1F389} Your AI just got a permanent brain.`),console.log(` Restart your editor \u2014 from this session on, it arrives pre-briefed.
|
|
250
|
-
`),console.log(` No more re-explaining your stack. No repeated mistakes.
|
|
251
|
-
`),console.log(` Dashboard: ${E(`/instances/${i.id}`,d)}`),console.log(`
|
|
252
|
-
\u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
|
|
253
|
-
`),!m)try{if(console.log(`
|
|
254
|
-
\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 $=await w(' Your handle (e.g. "alice"): ');$.trim()&&await J("team_assign_role",{instance_id:i.id,handle:$.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${$.trim()} is now admin. Invite teammates:
|
|
255
|
-
`),console.log(` team_assign_role(instance_id="${i.id}", handle="<teammate>", role="contributor", assigned_by="${$.trim()}")
|
|
242
|
+
`),$("setup_instance_ready",{instance_id:i.id});const p=process.cwd(),h=[],{homedir:T}=await import("node:os"),P=T();h.push("claude"),s(o(p,".cursor"))&&h.push("cursor"),s(o(p,".windsurf"))&&h.push("windsurf"),s(o(p,".vscode"))&&h.push("copilot"),s(o(p,".continue"))&&h.push("continue");const R=process.platform==="darwin"?o(P,"Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev"):o(P,".vscode/extensions");(s(R)&&!h.includes("copilot")||s(R))&&h.push("cline");const A=process.platform==="darwin"?o(P,"Library/Application Support/Zed"):o(P,".config/zed");s(A)&&h.push("zed");const C=f=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[f]??f,I=h;console.log(`\u{1F527} Configuring for: ${I.map(C).join(", ")}
|
|
243
|
+
`);const{existsSync:_}=await import("node:fs"),k=[];let L=0;Z(b),Le(i.id,{apiKey:b});for(const f of I){const S=me[f]??".mcp.json",j=o(p,S);try{await t(r(j),{recursive:!0});const z=_(j),U=await Nt(j,b,i.id,f,{readFile:n,existsSync:_});await e(j,U,"utf-8"),console.log(`\u2705 ${z?"Updated":"Written"}: ${S}`),L++}catch(z){const U=z.message;console.log(`\u26A0\uFE0F Could not write ${S}: ${U}`),console.log(" Fix permissions or run with sudo, then re-run setup."),k.push({file:S,reason:U})}}const ne=await Ht(p,i.id);for(const[f,S]of Object.entries(ne)){const{relative:j}=await import("node:path");console.log(Mt(j(p,f)||f,S))}y=b;let F=0;if(s(o(p,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const f=await W("brain_from_git",{instance_id:i.id,repo_path:p,limit:100});if(f.startsWith("\u274C"))console.log(` (skipped: ${it(f.replace(/^❌\s*/,"")).split(`
|
|
244
|
+
`)[0].slice(0,160)})`);else{const S=f.match(/Ingested: \*\*(\d+)\*\*/);F=S?parseInt(S[1],10):0,console.log(` \u2713 ${F} lesson${F===1?"":"s"} extracted from git history`);const j=zo(f);j&&(console.log(""),console.log(it(j)))}}catch(f){console.log(` (skipped: ${f.message.slice(0,80)})`)}}if(F===0){process.stdout.write("\u{1F331} Seeding 16 universal engineering lessons (first recall works instantly)...");try{await W("brain_seed_starter",{instance_id:i.id}),console.log(" \u2713");try{const f=await W("smart_recall",{instance_id:i.id,query:"docker build slow"}),S=Uo(f);S&&(console.log(""),console.log(Jo(S.topic,S.what)))}catch{}}catch(f){console.log(` (skipped: ${f.message.slice(0,60)})`)}}try{const f=await fetch(`${v}/api/v1/instances/${i.id}/memory`,{headers:{Authorization:`Bearer ${b}`},signal:AbortSignal.timeout(6e3)});if(f.ok){const j=(await f.json()).lesson_count??0;console.log(j===0?`
|
|
245
|
+
\u{1F9E0} Your Brain is empty. It learns from your fixes and commits from now on.`:`
|
|
246
|
+
\u{1F9E0} Your Brain now holds ${j} lesson${j===1?"":"s"}.`)}}catch{}if(!m)try{if(console.log(`
|
|
247
|
+
\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 S=await w(' Your handle (e.g. "alice"): ');S.trim()&&await W("team_assign_role",{instance_id:i.id,handle:S.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${S.trim()} is now admin. Invite teammates:
|
|
248
|
+
`),console.log(` team_assign_role(instance_id="${i.id}", handle="<teammate>", role="contributor", assigned_by="${S.trim()}")
|
|
256
249
|
`))}else console.log(` Skipped \u2014 run team_assign_role at any time.
|
|
257
|
-
`)}catch{}if(!m){const f=await w(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(f&&f.includes("@"))try{await fetch(`${
|
|
258
|
-
`)}catch{}}try{const f=await
|
|
250
|
+
`)}catch{}if(!m){const f=await w(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(f&&f.includes("@"))try{await fetch(`${v}/api/newsletter/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:f.trim().toLowerCase(),source:"mcp-setup"}),signal:AbortSignal.timeout(5e3)}),console.log(` \u2705 Subscribed \u2014 you'll only hear from us when it matters.
|
|
251
|
+
`)}catch{}}try{const f=await rt(process.cwd(),i.id);f==="written"?console.log(`
|
|
259
252
|
\u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):f==="upgraded"?console.log(`
|
|
260
|
-
\u2705 CLS git hook upgraded to ${
|
|
261
|
-
\u2705 CLS git hook appended to existing post-commit.`)}catch{}if(I.includes("claude"))try{const f=await
|
|
253
|
+
\u2705 CLS git hook upgraded to ${at}.`):f==="appended"&&console.log(`
|
|
254
|
+
\u2705 CLS git hook appended to existing post-commit.`)}catch{}if(I.includes("claude"))try{const f=await dt(process.cwd(),i.id);if(f.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${f.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const S=f.scripts==="written"?"\u2705 Written":f.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${ut})`:"\u2713 Unchanged";console.log(`${S}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),f.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):f.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{}I.includes("cursor")&&await ye("cursor",process.cwd(),i.id," "),I.includes("copilot")&&await ye("copilot",process.cwd(),i.id," "),(s(o(P,".codex"))||s(o(p,".codex")))&&(await ye("codex",process.cwd(),i.id," "),await De("codex",process.cwd(),X("",i.id)," ")),(s(o(P,".gemini"))||s(o(p,".gemini")))&&(await ye("gemini",process.cwd(),i.id," "),await De("gemini",process.cwd(),X("",i.id)," ")),y=b;const ze=Math.round((Date.now()-a)/1e3);if(k.length>0&&$("setup_config_write_failed",{instance_id:i.id,failed:k.length,succeeded:L}),$("setup_completed",{instance_id:i.id,elapsed_s:ze,config_failures:k.length}),k.length>0&&L===0){console.log(`
|
|
262
255
|
\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(`
|
|
263
256
|
Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const f of k)console.log(` \u2022 ${f.file} \u2014 ${f.reason}`);console.log(`
|
|
264
257
|
Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${b.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${i.id}`),console.log(` Docs: ${E("/docs/mcp",d)}
|
|
265
|
-
`),
|
|
266
|
-
\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 ${(
|
|
267
|
-
\u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const f of k)console.log(` \u2022 ${f.file} \u2014 ${f.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(
|
|
258
|
+
`),x.close(),await new Promise(f=>setTimeout(f,300)),process.exit(1)}if(console.log(`
|
|
259
|
+
\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"),k.length>0){console.log(`
|
|
260
|
+
\u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const f of k)console.log(` \u2022 ${f.file} \u2014 ${f.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(`
|
|
261
|
+
\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.
|
|
262
|
+
`),console.log(` Dashboard: ${E(`/instances/${i.id}`,d)}`),console.log(` Step-by-step guide: ${E("/docs/setup",d)}
|
|
263
|
+
`),x.close(),await new Promise(f=>setTimeout(f,300)),process.exit(0)}if(process.argv[2]==="index"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=a=>{const d=t.indexOf(`--${a}`);return d!==-1?t[d+1]:void 0},s=e(n("dir")??t.find(a=>!a.startsWith("--"))??"."),o=n("instance-id")||J(),r=parseInt(n("max-files")??"500",10),c=n("namespace")??"cachly:sem:code";(!o||!y)&&(console.error(`
|
|
268
264
|
\u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
|
|
269
265
|
`),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
|
|
270
266
|
`),process.exit(1)),console.log(`
|
|
271
|
-
\u{1F4C2} Indexing: ${
|
|
272
|
-
`);try{const a=await
|
|
267
|
+
\u{1F4C2} Indexing: ${s}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max files: ${r}
|
|
268
|
+
`);try{const a=await W("index_project",{instance_id:o,dir:s,max_files:r,ttl:604800,namespace:c});console.log(a),console.log(`
|
|
273
269
|
\u2705 Indexing complete.
|
|
274
270
|
`)}catch(a){console.error(`
|
|
275
271
|
\u274C Indexing failed: ${a.message}
|
|
276
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="learn-git"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),
|
|
272
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="learn-git"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=c=>{const a=t.indexOf(`--${c}`);return a!==-1?t[a+1]:void 0},s=e(n("dir")??t.find(c=>!c.startsWith("--"))??"."),o=n("instance-id")||J(),r=parseInt(n("max-commits")??"50",10);(!o||!y)&&(console.error(`
|
|
277
273
|
\u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
|
|
278
274
|
`),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 .
|
|
279
275
|
`),process.exit(1)),console.log(`
|
|
280
|
-
\u{1F9E0} Learning from git history: ${
|
|
281
|
-
`);try{const c=await
|
|
276
|
+
\u{1F9E0} Learning from git history: ${s}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max commits: ${r}
|
|
277
|
+
`);try{const c=await W("brain_from_git",{instance_id:o,repo_path:s,limit:r});console.log(c),$("brain_from_git",{api_key:y,instance_id:o}),console.log(`
|
|
282
278
|
\u2705 Brain learned from your commits.
|
|
283
279
|
`),await new Promise(a=>setTimeout(a,300))}catch(c){console.error(`
|
|
284
280
|
\u274C learn-git failed: ${c.message}
|
|
285
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await
|
|
281
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await an(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await cn(),process.argv[2]===dn&&await ln(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),n=process.argv.slice(4).join(" ").slice(0,200)||void 0,s={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n,instanz:J()||void 0};await pn(s),await ds(process.env.CACHLY_BRAIN_INSTANCE_ID??B,s),console.log(`\u2705 ambient credit recorded: ${t} tokens${n?` (${n})`:""}`)}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=J(),t=fn(await pt(),e||void 0),n=t.eigene,s=ss(n),o=n.slice(-5);if(console.log(`
|
|
286
282
|
\u{1F9E0} Ambient Recall \u2014 net-token ledger
|
|
287
|
-
`),console.log(` Instance: ${e?`${e.slice(0,8)}\u2026`:"(none set \u2014 showing every entry on this computer)"}`),console.log(` Turns recorded: ${
|
|
283
|
+
`),console.log(` Instance: ${e?`${e.slice(0,8)}\u2026`:"(none set \u2014 showing every entry on this computer)"}`),console.log(` Turns recorded: ${n.length}`),console.log(` Injected tokens: ${s.injected}`),console.log(` Prevented tokens: ${s.prevented} (agent-reported via ambient-credit)`),console.log(` NET: ${s.net>=0?"+":""}${s.net} tokens`),o.length>0){console.log(`
|
|
288
284
|
Last entries:`);for(const r of o){const c=r.prevented>0?`+${r.prevented} prevented`:`-${r.injected} injected`;console.log(` \u2022 ${r.ts.slice(0,19)} ${r.event}: ${c}${r.note?` (${r.note})`:""}`)}}(t.ohneInstanz>0||t.andereInstanzen>0)&&(console.log(`
|
|
289
|
-
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:
|
|
285
|
+
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:n}=await import("node:path"),{createInterface:s}=await import("node:readline/promises"),o=process.argv.slice(3),c={projekt:n((a=>{const d=o.indexOf(`--${a}`);return d!==-1?o[d+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:te(),instanz:J(),apiUrl:v,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:a=>console.log(a),frage:async a=>{const d=s({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await d.question(a)).trim())}finally{d.close()}}};process.exit(await Vo(o,c))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:s,checkInstance:o,checkVectorCoverage:r,inspectAmbientHooks:c,checkHooks:a,checkLedger:d,renderDoctorReport:g,doctorExitCode:l}=await import("./doctor.js"),m=[e(),t(y),await n(v),await s(v,y),o(J()||B),await r(v,y,J()||B),a(c(process.cwd())),d(await pt(),mn())];console.log(g(m)),process.exit(l(m))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!y)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??B;(!n||!t.source)&&process.exit(0),await W("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!y){const e=Wt();if(e)try{const t=await fetch(Yt(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Ft(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(y=n.access_token,ce(n.access_token),$("m2m_auth_completed",{grant:"client_credentials",client_id:e.clientId}),process.stderr.write(`\u{1F916} cachly: authenticated via client_credentials (M2M, headless).
|
|
290
286
|
`))}else process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth failed (${t.status}). Check CACHLY_CLIENT_ID / CACHLY_CLIENT_SECRET.
|
|
291
|
-
`)
|
|
292
|
-
`)
|
|
287
|
+
`),$("m2m_auth_failed",{status:t.status})}catch(t){process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth error: ${t.message}
|
|
288
|
+
`),$("m2m_auth_failed",{reason:"network"})}}const Cs=["demo","share","publish","health","autosetup","setup","autopilot","init","digest","invite","badge","join","upgrade","bench","tool-specs","openapi","ambient-credit","ambient-stats","doctor","uninstall"];if(!y&&!Cs.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&Xt){const s=`
|
|
293
289
|
\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
|
|
294
290
|
\u2551 \u{1F9E0} cachly AI Brain \u2014 Setup required \u2551
|
|
295
291
|
\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
|
|
@@ -305,7 +301,7 @@ Could not create an instance automatically. Opening ${E("/instances",d)} \u2026
|
|
|
305
301
|
\u2551 Free tier \u2014 no credit card required. \u2551
|
|
306
302
|
\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
|
|
307
303
|
|
|
308
|
-
`;process.stdout.write(
|
|
304
|
+
`;process.stdout.write(s),process.exit(0)}else process.stderr.write(`
|
|
309
305
|
\u{1F9E0} cachly: no API key yet \u2014 the first cachly tool call creates a test Brain on EU servers, no sign-up.
|
|
310
306
|
(Own account: npx @cachly-dev/mcp-server@latest autopilot)
|
|
311
307
|
|
|
@@ -317,7 +313,7 @@ Could not create an instance automatically. Opening ${E("/instances",d)} \u2026
|
|
|
317
313
|
\u26A0\uFE0F cachly: CACHLY_JWT expires in ${t} minute(s).
|
|
318
314
|
Refresh it soon at ${E("/setup-ai","jwt-expiry")} to avoid interruptions.
|
|
319
315
|
|
|
320
|
-
`)}}process.env.PORT||
|
|
321
|
-
`),
|
|
322
|
-
`)})}else{const e=new eo;
|
|
323
|
-
`),(async()=>{await
|
|
316
|
+
`)}}process.env.PORT||Wn({aktuelle:Jn(M)});const ke=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(ke){const{createServer:e}=await import("node:http");e((n,s)=>{const o=new URL(n.url??"/",`http://localhost:${ke}`);if(o.pathname==="/health"){s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({status:"ok",version:M,zeroResults:{total:Io,last10:To.slice(-10).map(r=>({query:r.query,ts:new Date(r.ts).toISOString()}))}}));return}if(o.pathname==="/mcp"||o.pathname==="/"){(async()=>{const r=xs(),c=new to({sessionIdGenerator:void 0});s.on("close",()=>{c.close().catch(()=>{}),r.close().catch(()=>{})});try{await r.connect(c),await c.handleRequest(n,s)}catch(a){process.stderr.write(`cachly-mcp HTTP: ${a.message}
|
|
317
|
+
`),s.headersSent||(s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:a.message})))}})();return}s.writeHead(404),s.end("not found")}).listen(ke,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${ke}
|
|
318
|
+
`)})}else{const e=new eo;Y("start: Module geladen, stdio verbinden"),await q.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(Xe=!0,Pn(()=>Un(et)),ao(),qn(),Yn(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 Session zu Ende, Server geht mit
|
|
319
|
+
`),(async()=>{await Me().catch(()=>{});for(const[,s]of oe)await s.quit().catch(()=>{});process.exit(0)})()}))}We("cachly","startup",{version:M,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{Yo as CLAUDE_MD_MARKER_END,Fo as CLAUDE_MD_MARKER_START,Co as CROSS_LINGUAL_MAP,me as EDITOR_FILES,$o as STOPWORDS,Mt as anweisungsZeile,So as arabicLightStem,ct as buildClaudeMdBlock,ks as buildMcpConfig,X as buildServerEnv,Ao as expandCrossLingual,_o as extractTimestamp,ko as katakanaToRomaji,vo as levenshtein,$s as mcpAddBefehl,Nt as mergeMcpConfig,xo as recencyBoost,Eo as reconnectOnce,wo as splitMultiQuery,go as startBackgroundDevicePoll,bo as tokenize,Ht as writeInstructions};
|