@cachly-dev/mcp-server 0.10.273 → 0.10.275

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/dist/src/index.js CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- import{setzeClientKennung as so}from"./herkunft.js";import{jwtExpiryMs as ro,checkJwt as io,handleApiError as ao,diagnoseAuth as Oe,planAuthHeal as Ze,readClientCredentialsFromEnv as co,buildClientCredentialsBody as lo,clientCredentialsTokenUrl as uo}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as po}from"./werkzeug-nutzung.js";import{istLieferung as mo,lieferSchluessel as fo,tokenDerAntwort as go,hatTreffer as ho,trefferSchluessel as Xe}from"./geliefert.js";import{notify as Qe}from"./notifier.js";import{fileURLToPath as et}from"node:url";import{createRequire as yo}from"node:module";import{execFile as Le}from"node:child_process";const bo=process.argv[1]!=null&&(process.argv[1]===et(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as tt}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as wo}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as vo}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ot,ErrorCode as te,ListPromptsRequestSchema as nt,ListResourceTemplatesRequestSchema as st,ListResourcesRequestSchema as rt,ListToolsRequestSchema as it,McpError as Z}from"@modelcontextprotocol/sdk/types.js";import{Redis as at}from"ioredis";let x=process.env.CACHLY_API_URL??"https://api.cachly.dev",A=Fe()??"";oe(A);const Fr=process.env.CACHLY_EMBED_MODEL??"",H=(()=>{try{const e=yo(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"})(),xo=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let P=Ee(process.env.CACHLY_BRAIN_INSTANCE_ID);function we(){return W()?xe()?.schluessel??"":A}function _o(){return W()?xe()?.instanzId??"":P}function X(){return A||Fe()||""}function U(){return Ee(process.env.CACHLY_BRAIN_INSTANCE_ID)||Ie()||""}let Q=0,ue=null,ct=!1;async function lt(){let e=[];try{q.getClientCapabilities()?.roots&&(e=(await q.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Hs({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:et})}function ie(){return ct?jt(process.env):!1}function He(e,t,n){!e||!ie()||Ps({instanzId:e,vomHook:n,verbindung:L,ausGit:o=>Je("brain_from_git",o,L,O),projektOrdner:t?async()=>t:lt,einbetten:o=>ft(o,{geduld:"lang"}),hatEinbettung:Bo,einbettenZweit:o=>ft(o,{geduld:"lang",modell:cn}),melde:o=>C("brain_from_git",{instance_id:e,total:o,auto:"startwissen"}),startvorrat:o=>Ke("brain_seed_starter",o,L,O),meldeStartvorrat:o=>C("brain_seed_starter",{instance_id:e,auto:!0},{seeded_count:o,auto:!0})})}function Me(){return ie()&&Ms()}const $o=7e3,ko=12e3,So=18e4;let ve=null;function ze(e){return ve||(ve=Ao(e).finally(()=>{ve=null})),ve}async function Ao(e){try{if(!A){const t=Date.now()+e;for(;!Te()&&As({})&&Date.now()<t;)await new Promise(s=>setTimeout(s,$s));const n=Te();if(!n)return!1;A=n,oe(n);const o=Ie();o&&!P&&(P=o,Q=0),await pe(n),o&&await me(o),C("instant_trial_started",{tool:"sessionstart-hook",...o?{instance_id:o}:{}})}if(ie()&&Rt()){const t=ks();t&&(Ye(t.instanzId,ie(),Me()),He(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!A}function Co(){if(!jt(process.env))return;const e=Date.now()+So,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}A&&!Rt()||ze(0)},500);t.unref(),ze(0)}async function To(){if(!A||W())return"";try{const e=await fetch(`${x}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${A}`,"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(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:H}),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:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function dt(){if(W())return _o();if(P)return P;if(!A)return"";if(ue)return ue;const e=Date.now();if(Q>0&&e-Q<3e4)return"";Q=e,ue=(async()=>{try{const t=await fetch(`${x}/api/v1/instances`,{headers:{Authorization:`Bearer ${A}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const o=(await t.json())?.data??[],s=o.find(c=>c.status==="running")??o.find(c=>c.status==="provisioning");if(s)return P=s.id,Q=0,P;const r=await To();if(r)return P=r,Q=0,Ye(r,ie(),Me()),me(r),He(r),P}}catch{}return""})();try{return await ue}finally{ue=null}}let De=0;const Io=6e4;let ae="";async function pe(e){try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),r=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!r)return;const c=[s(r,".claude","mcp.json"),s(r,".cursor","mcp.json"),s(r,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(c.map(async d=>{if(o(d))try{const u=await n(d,"utf-8"),l=JSON.parse(u),i=l?.mcpServers?.cachly;i?.env&&(i.env.CACHLY_JWT=e,await t(d,JSON.stringify(l,null,2),"utf-8"))}catch{}}))}catch{}}async function me(e){if(e){Ce(e,{apiKey:A});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),r=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!r)return;const c=[s(r,".claude","mcp.json"),s(r,".cursor","mcp.json"),s(r,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(c.map(async d=>{if(o(d))try{const u=JSON.parse(await n(d,"utf-8")),l=u?.mcpServers?.cachly;l?.env&&(l.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(d,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}}async function Eo(){try{const e=await fetch(`${x}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`},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?(A=t.key,oe(t.key),pe(t.key),C("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function Ue(){const e=Oe(A),t=Ze(e);if(t==="none")return ae="",!0;if(t==="refresh"){const n=Date.now();return n-De>=Io&&(De=n,await Eo())?(ae="",!0):(ae=e.message,e.usable)}return ae=e.message,!1}function ce(e,t){const n=(c,d)=>{try{t?.(c,d)}catch{}},o=c=>{c?n(!1,c.code??c.message):n(!0)},s=Yn(e);if(!s){n(!1,"keine-http-adresse");return}const r=Kn(s);try{process.platform==="win32"?Le("cmd",["/c","start","",r],{windowsHide:!0},o):process.platform==="darwin"?Le("open",[s],o):Le("xdg-open",[s],o)}catch(c){n(!1,c instanceof Error?c.message:"unknown")}}let K=null;async function Ro(){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(),n=t.verification_uri||j("/device","ambient-signin"),o=`${n}${n.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:o,pollInterval:(t.interval??5)*1e3,deadline:Date.now()+ut(t.expires_in),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()+ut(n.expires_in),polling:!1}}catch{return null}}function ut(e){const t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:600;return Math.min(t,3600)*1e3}function jo(){const e=ps(x);return e?{deviceCode:e.deviceCode,userCode:e.userCode,verifyUrl:e.verifyUrl,pollInterval:e.pollInterval,deadline:e.deadline,polling:!1}:null}async function No(e){if(Date.now()>e.deadline)return It(e.deviceCode),"expired";const t=async()=>{const o=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 o.ok?o.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 o=await t().catch(()=>null);if(o||(o=await n().catch(()=>null)),!o)return"pending";if(o.access_token){let s=o.access_token;try{const r=await fetch(`${x}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(r.ok){const c=await r.json();c.key&&(s=c.key)}}catch{}return A=s,oe(s),K=null,It(e.deviceCode),C("device_flow_completed"),pe(s),ne(s),Q=0,await dt(),P&&me(P),"done"}return o.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function pt(e){if(e.polling)return"pending";e.polling=!0;try{return await No(e)}finally{e.polling=!1}}function mt(e,t=pt,n=s=>K===s,o=Po){const s=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)&&o(s,e.pollInterval)}};o(s,e.pollInterval)}function Po(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as oe,computeEmbedding as ft,hasEmbedProvider as Bo,EMBED_PROVIDER as gt,erzwingeEmbedAnbieterRemote as Oo}from"./embeddings.js";import{istMehrmandant as W,setzeMehrmandant as Lo,mandantKontext as xe,imMandant as Ho,baueKontext as ht,poolSchluessel as Mo,leseBearer as zo,leseInstanzKopf as Do,BegrenzterSpeicher as Uo,baueZugangsAufloeser as Wo,ZugangAbgelehnt as yt,bauePruefGrenze as Jo,leseAufruferIp as Fo,imAufrufer as Yo,installiereApiKoepfe as Ko,ANLEITUNG_OHNE_KOPF as _e,istRemoteErlaubt as Go,nurLokalText as qo,bereinigeArgumente as Vo}from"./remote-zugang.js";import{leseOAuthEinstellungen as Zo,schutzMetadaten as Xo,wwwAuthenticate as Qo,baueJwtPruefer as en,TokenAbgelehnt as tn,tokenFehlerText as on,KEIN_BRAIN_TEXT as nn,brauchtAnmeldung as sn,WERKZEUG_BRAUCHT_ANMELDUNG as rn,MAX_RUMPF_OHNE_ANMELDUNG as an}from"./remote-oauth.js";import{ZWEIT_MODELL as cn}from"./rangfolge-stellschrauben.js";import{tokenize as ln,splitMultiQuery as dn,levenshtein as un,recencyBoost as pn,extractTimestamp as mn,STOPWORDS as fn,katakanaToRomaji as gn,arabicLightStem as hn,expandCrossLingual as yn,CROSS_LINGUAL_MAP as bn}from"./search.js";const fe=new Map,wn=200,vn=10*6e4,$e=new Uo({max:wn,ttlMs:vn,beiEntfernen:e=>{e.quit().catch(()=>e.disconnect())}});function We(){return[...fe.values(),...$e.werte()]}function xn(e){return e<=1?200:null}async function L(e){if(!e)throw new Z(te.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
2
+ import{setzeClientKennung as ro}from"./herkunft.js";import{jwtExpiryMs as io,checkJwt as ao,handleApiError as co,diagnoseAuth as Oe,planAuthHeal as Ze,readClientCredentialsFromEnv as lo,buildClientCredentialsBody as uo,clientCredentialsTokenUrl as po}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as mo}from"./werkzeug-nutzung.js";import{istLieferung as fo,lieferSchluessel as go,tokenDerAntwort as ho,hatTreffer as yo,trefferSchluessel as Xe}from"./geliefert.js";import{notify as Qe}from"./notifier.js";import{fileURLToPath as et}from"node:url";import{createRequire as bo}from"node:module";import{execFile as Le}from"node:child_process";const wo=process.argv[1]!=null&&(process.argv[1]===et(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as tt}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as vo}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as xo}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ot,ErrorCode as te,ListPromptsRequestSchema as nt,ListResourceTemplatesRequestSchema as st,ListResourcesRequestSchema as rt,ListToolsRequestSchema as it,McpError as Z}from"@modelcontextprotocol/sdk/types.js";import{Redis as at}from"ioredis";let x=process.env.CACHLY_API_URL??"https://api.cachly.dev",A=Fe()??"";oe(A);const Kr=process.env.CACHLY_EMBED_MODEL??"",H=(()=>{try{const e=bo(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"})(),_o=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let P=Ee(process.env.CACHLY_BRAIN_INSTANCE_ID);function we(){return W()?xe()?.schluessel??"":A}function $o(){return W()?xe()?.instanzId??"":P}function X(){return A||Fe()||""}function U(){return Ee(process.env.CACHLY_BRAIN_INSTANCE_ID)||Ie()||""}let Q=0,ue=null,ct=!1;async function lt(){let e=[];try{q.getClientCapabilities()?.roots&&(e=(await q.listRoots(void 0,{timeout:3e3})).roots)}catch{}return zs({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:et})}function ie(){return ct?Nt(process.env):!1}function He(e,t,n){!e||!ie()||Os({instanzId:e,vomHook:n,verbindung:L,ausGit:o=>Je("brain_from_git",o,L,O),projektOrdner:t?async()=>t:lt,einbetten:o=>ft(o,{geduld:"lang"}),hatEinbettung:Oo,einbettenZweit:o=>ft(o,{geduld:"lang",modell:dn}),melde:o=>C("brain_from_git",{instance_id:e,total:o,auto:"startwissen"}),startvorrat:o=>Ke("brain_seed_starter",o,L,O),meldeStartvorrat:o=>C("brain_seed_starter",{instance_id:e,auto:!0},{seeded_count:o,auto:!0})})}function Me(){return ie()&&Ds()}const ko=7e3,So=12e3,Ao=18e4;let ve=null;function ze(e){return ve||(ve=Co(e).finally(()=>{ve=null})),ve}async function Co(e){try{if(!A){const t=Date.now()+e;for(;!Te()&&Ts({})&&Date.now()<t;)await new Promise(s=>setTimeout(s,Ss));const n=Te();if(!n)return!1;A=n,oe(n);const o=Ie();o&&!P&&(P=o,Q=0),await pe(n),o&&await me(o),C("instant_trial_started",{tool:"sessionstart-hook",...o?{instance_id:o}:{}})}if(ie()&&jt()){const t=As();t&&(Ye(t.instanzId,ie(),Me()),He(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!A}function To(){if(!Nt(process.env))return;const e=Date.now()+Ao,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}A&&!jt()||ze(0)},500);t.unref(),ze(0)}async function Io(){if(!A||W())return"";try{const e=await fetch(`${x}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${A}`,"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(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:H}),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:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function dt(){if(W())return $o();if(P)return P;if(!A)return"";if(ue)return ue;const e=Date.now();if(Q>0&&e-Q<3e4)return"";Q=e,ue=(async()=>{try{const t=await fetch(`${x}/api/v1/instances`,{headers:{Authorization:`Bearer ${A}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const o=(await t.json())?.data??[],s=o.find(l=>l.status==="running")??o.find(l=>l.status==="provisioning");if(s)return P=s.id,Q=0,P;const r=await Io();if(r)return P=r,Q=0,Ye(r,ie(),Me()),me(r),He(r),P}}catch{}return""})();try{return await ue}finally{ue=null}}let De=0;const Eo=6e4;let ae="";async function pe(e){try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),r=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!r)return;const l=[s(r,".claude","mcp.json"),s(r,".cursor","mcp.json"),s(r,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(l.map(async d=>{if(o(d))try{const u=await n(d,"utf-8"),c=JSON.parse(u),i=c?.mcpServers?.cachly;i?.env&&(i.env.CACHLY_JWT=e,await t(d,JSON.stringify(c,null,2),"utf-8"))}catch{}}))}catch{}}async function me(e){if(e){Ce(e,{apiKey:A});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),r=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!r)return;const l=[s(r,".claude","mcp.json"),s(r,".cursor","mcp.json"),s(r,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(l.map(async d=>{if(o(d))try{const u=JSON.parse(await n(d,"utf-8")),c=u?.mcpServers?.cachly;c?.env&&(c.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(d,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}}async function Ro(){try{const e=await fetch(`${x}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`},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?(A=t.key,oe(t.key),pe(t.key),C("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function Ue(){const e=Oe(A),t=Ze(e);if(t==="none")return ae="",!0;if(t==="refresh"){const n=Date.now();return n-De>=Eo&&(De=n,await Ro())?(ae="",!0):(ae=e.message,e.usable)}return ae=e.message,!1}function ce(e,t){const n=(l,d)=>{try{t?.(l,d)}catch{}},o=l=>{l?n(!1,l.code??l.message):n(!0)},s=Gn(e);if(!s){n(!1,"keine-http-adresse");return}const r=qn(s);try{process.platform==="win32"?Le("cmd",["/c","start","",r],{windowsHide:!0},o):process.platform==="darwin"?Le("open",[s],o):Le("xdg-open",[s],o)}catch(l){n(!1,l instanceof Error?l.message:"unknown")}}let K=null;async function jo(){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(),n=t.verification_uri||j("/device","ambient-signin"),o=`${n}${n.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:o,pollInterval:(t.interval??5)*1e3,deadline:Date.now()+ut(t.expires_in),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()+ut(n.expires_in),polling:!1}}catch{return null}}function ut(e){const t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:600;return Math.min(t,3600)*1e3}function No(){const e=fs(x);return e?{deviceCode:e.deviceCode,userCode:e.userCode,verifyUrl:e.verifyUrl,pollInterval:e.pollInterval,deadline:e.deadline,polling:!1}:null}async function Po(e){if(Date.now()>e.deadline)return Et(e.deviceCode),"expired";const t=async()=>{const o=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 o.ok?o.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 o=await t().catch(()=>null);if(o||(o=await n().catch(()=>null)),!o)return"pending";if(o.access_token){let s=o.access_token;try{const r=await fetch(`${x}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(r.ok){const l=await r.json();l.key&&(s=l.key)}}catch{}return A=s,oe(s),K=null,Et(e.deviceCode),C("device_flow_completed"),pe(s),ne(s),Q=0,await dt(),P&&me(P),"done"}return o.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function pt(e){if(e.polling)return"pending";e.polling=!0;try{return await Po(e)}finally{e.polling=!1}}function mt(e,t=pt,n=s=>K===s,o=Bo){const s=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)&&o(s,e.pollInterval)}};o(s,e.pollInterval)}function Bo(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as oe,computeEmbedding as ft,hasEmbedProvider as Oo,EMBED_PROVIDER as gt,erzwingeEmbedAnbieterRemote as Lo}from"./embeddings.js";import{istMehrmandant as W,setzeMehrmandant as Ho,mandantKontext as xe,imMandant as Mo,baueKontext as ht,poolSchluessel as zo,leseBearer as Do,leseInstanzKopf as Uo,BegrenzterSpeicher as Wo,baueZugangsAufloeser as Jo,ZugangAbgelehnt as yt,bauePruefGrenze as Fo,leseAufruferIp as Yo,imAufrufer as Ko,installiereApiKoepfe as Go,ANLEITUNG_OHNE_KOPF as _e,istRemoteErlaubt as qo,nurLokalText as Vo,bereinigeArgumente as Zo}from"./remote-zugang.js";import{leseOAuthEinstellungen as Xo,schutzMetadaten as Qo,wwwAuthenticate as en,baueJwtPruefer as tn,TokenAbgelehnt as on,tokenFehlerText as nn,KEIN_BRAIN_TEXT as sn,brauchtAnmeldung as rn,WERKZEUG_BRAUCHT_ANMELDUNG as an,MAX_RUMPF_OHNE_ANMELDUNG as cn}from"./remote-oauth.js";import{serverInfo as bt,beantworteLogo as ln}from"./remote-logo.js";import{ZWEIT_MODELL as dn}from"./rangfolge-stellschrauben.js";import{tokenize as un,splitMultiQuery as pn,levenshtein as mn,recencyBoost as fn,extractTimestamp as gn,STOPWORDS as hn,katakanaToRomaji as yn,arabicLightStem as bn,expandCrossLingual as wn,CROSS_LINGUAL_MAP as vn}from"./search.js";const fe=new Map,xn=200,_n=10*6e4,$e=new Wo({max:xn,ttlMs:_n,beiEntfernen:e=>{e.quit().catch(()=>e.disconnect())}});function We(){return[...fe.values(),...$e.werte()]}function $n(e){return e<=1?200:null}async function L(e){if(!e)throw new Z(te.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=W()?xe():void 0;if(W()&&!t)throw new Z(te.InvalidRequest,_e);const n=t?Mo(t.schluessel,e):e,o=t?$e.get(n):fe.get(e);return o||Rs(_n,n,()=>$n(e,n,!!t))}const _n=new Map;async function $n(e,t=e,n=!1){Y("verbindung: Instanz abfragen");let o=await O(`/api/v1/instances/${e}`);if(Y(`verbindung: Instanz ${o.status}`),o=await Es(o,()=>O(`/api/v1/instances/${e}`),{fristMs:xo,melde:l=>Y(`verbindung: Instanz ${l.status}`)}),o.status!=="running"){n||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...A?{Authorization:`Bearer ${A}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:o.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let l;throw o.status==="provisioning"?l=`\u23F3 Brain instance "${o.name}" is still starting up.
9
+ \u2022 Reach us at support@cachly.dev.`);const t=W()?xe():void 0;if(W()&&!t)throw new Z(te.InvalidRequest,_e);const n=t?zo(t.schluessel,e):e,o=t?$e.get(n):fe.get(e);return o||Ns(kn,n,()=>Sn(e,n,!!t))}const kn=new Map;async function Sn(e,t=e,n=!1){Y("verbindung: Instanz abfragen");let o=await O(`/api/v1/instances/${e}`);if(Y(`verbindung: Instanz ${o.status}`),o=await js(o,()=>O(`/api/v1/instances/${e}`),{fristMs:_o,melde:c=>Y(`verbindung: Instanz ${c.status}`)}),o.status!=="running"){n||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...A?{Authorization:`Bearer ${A}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:o.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let c;throw o.status==="provisioning"?c=`\u23F3 Brain instance "${o.name}" is still starting up.
10
10
 
11
- First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:o.status==="failed"?l=`\u274C Brain instance "${o.name}" failed to start.
11
+ First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:o.status==="failed"?c=`\u274C Brain instance "${o.name}" failed to start.
12
12
 
13
13
  Our system will retry automatically. Check status at: ${j("/instances","instance-error")}
14
- If this persists, contact support@cachly.dev.`:o.status==="suspended"?l=`\u23F8 Brain instance "${o.name}" is suspended (billing issue).
14
+ If this persists, contact support@cachly.dev.`:o.status==="suspended"?c=`\u23F8 Brain instance "${o.name}" is suspended (billing issue).
15
15
 
16
- Update your payment method at: ${j("/billing","upgrade")}`:o.status==="pending_payment"?l=`\u{1F4B3} Brain instance "${o.name}" is waiting for payment.
16
+ Update your payment method at: ${j("/billing","upgrade")}`:o.status==="pending_payment"?c=`\u{1F4B3} Brain instance "${o.name}" is waiting for payment.
17
17
 
18
- Complete your checkout at: ${j("/instances","upgrade")}`:l=`Brain instance "${o.name}" is not reachable (status: ${o.status}).
18
+ Complete your checkout at: ${j("/instances","upgrade")}`:c=`Brain instance "${o.name}" is not reachable (status: ${o.status}).
19
19
 
20
20
  \u2022 View your instance at: ${j("/instances","instance-error")}
21
- \u2022 Run \`get_api_status\` for a full diagnostic.`,new Z(te.InvalidRequest,l)}if(!o.host||!o.port)throw new Z(te.InternalError,`Instance "${o.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let s,r;try{const l=await O(`/api/v1/instances/${e}/connection`);s=l.password??void 0,r=l,Y("verbindung: Zugangsdaten da")}catch(l){const i=l instanceof Error?l.message:String(l);if(i.includes("401")||i.includes("403")||i.includes("Unauthorized"))throw new Z(te.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const c=Ot({host:o.host,port:o.port,tls_enabled:o.tls_enabled},r),d=new at({host:c.host,port:c.port,password:s||void 0,commandTimeout:8e3,...c.tls?{tls:c.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:xn,maxRetriesPerRequest:1,keepAlive:15e3}),u=()=>{n?$e.vergissWenn(t,d):fe.delete(e),d.disconnect()};d.on("error",u),d.on("end",u);try{await d.connect()}catch(l){d.disconnect();const i=l instanceof Error?l.message:String(l);throw n||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...A?{Authorization:`Bearer ${A}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:o.host,port:o.port,error:i,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new Z(te.InternalError,`Could not reach Brain instance "${o.name}" (${o.host}:${o.port}).
21
+ \u2022 Run \`get_api_status\` for a full diagnostic.`,new Z(te.InvalidRequest,c)}if(!o.host||!o.port)throw new Z(te.InternalError,`Instance "${o.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let s,r;try{const c=await O(`/api/v1/instances/${e}/connection`);s=c.password??void 0,r=c,Y("verbindung: Zugangsdaten da")}catch(c){const i=c instanceof Error?c.message:String(c);if(i.includes("401")||i.includes("403")||i.includes("Unauthorized"))throw new Z(te.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const l=Lt({host:o.host,port:o.port,tls_enabled:o.tls_enabled},r),d=new at({host:l.host,port:l.port,password:s||void 0,commandTimeout:8e3,...l.tls?{tls:l.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:$n,maxRetriesPerRequest:1,keepAlive:15e3}),u=()=>{n?$e.vergissWenn(t,d):fe.delete(e),d.disconnect()};d.on("error",u),d.on("end",u);try{await d.connect()}catch(c){d.disconnect();const i=c instanceof Error?c.message:String(c);throw n||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...A?{Authorization:`Bearer ${A}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:o.host,port:o.port,error:i,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new Z(te.InternalError,`Could not reach Brain instance "${o.name}" (${o.host}:${o.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: ${i}`)}return n?$e.set(t,d):fe.set(e,d),Y("verbindung: Valkey verbunden"),d}async function O(e,t={},n=!1){!n&&!W()&&Ze(Oe(A))!=="none"&&await Ue();const o=we();io(o);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),r=await fetch(`${x}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,...t.headers}});if(!r.ok){if(r.status===401&&!n&&!W()&&(De=0,await Ue()))return O(e,t,!0);const d=(await r.json().catch(()=>({error:r.statusText}))).error??r.statusText;ao(r.status,d)}if(r.status!==204)return r.json()}import{handleBrainTool as kn}from"./handlers/brain.js";import{handleContextTool as Sn}from"./handlers/context.js";import{handleInstanceTool as An}from"./handlers/instances.js";import{handleCacheTool as Cn}from"./handlers/cache.js";import{handleTeamTool as Tn}from"./handlers/team.js";import{handleRoadmapTool as In}from"./handlers/roadmap.js";import{handleAdvancedTool as En}from"./handlers/advanced.js";import{handleSyndicateTool as Rn}from"./handlers/syndicate.js";import{handleFedbrainTool as Je,_lastBrainFromGitCounts as ke}from"./handlers/fedbrain.js";import{extractFirstRecallProof as jn,extractTopHit as Nn,fuersTerminal as bt,renderFirstRecallProof as Pn}from"./first-recall-proof.js";import{aussetzerLeise as Bn}from"./aussetzer.js";import{gitHookOrdner as On,installClsPostCommitHook as wt,CLS_HOOK_VERSION as vt}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as Ln,CLAUDE_MD_MARKER_END as Hn,EDITOR_FILES as Se,ANWEISUNGS_DATEIEN as Mn,buildClaudeMdBlock as xt,setzeAnweisungsblock as zn,sollSchreiben as Dn,globaleMcpDatei as Ae,globalerEditorDa as _t,diesesHeim as ge,mcpZiel as $t}from"./projektdateien.js";import{klassiereArgument as Un,leseFlag as kt,flagsOhneWert as Wn,pruefeInitEingaben as Jn}from"./cli-argumente.js";import{uninstallBefehl as Fn}from"./uninstall.js";import{gitLesen as St}from"./git-ohne-shell.js";import{browserAdresse as Yn,fuerCmd as Kn}from"./browser-adresse.js";import{installAmbientHooks as At,installCursorHooks as Gn,installCopilotHooks as qn,installCodexHooks as Vn,installGeminiHooks as Zn,AMBIENT_HOOK_VERSION as Ct,COPILOT_HOOKS_DATEI as Xn,CODEX_HOOKS_DATEI as Qn,GEMINI_SETTINGS_DATEI as es}from"./ambient-hooks.js";import{hookHauptlauf as ts,auffrischenHauptlauf as os,startwissenImportHauptlauf as ns}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as ss}from"./startwissen-hook.js";import{rahmeAntwort as rs}from"./antwort-rahmen.js";import{appendLedgerEntry as is,readLedger as Tt,defaultLedgerPath as as,reportLedgerEntry as cs,teileNachInstanz as ls}from"./ambient-ledger.js";import{installCodexMcp as ds,installGeminiMcp as us}from"./editor-mcp-eintrag.js";import{resolveApiKey as Fe,saveApiKey as ne,saveInstanceId as Ce,readSavedApiKey as Te,readInstanceId as Ie}from"./credentials.js";import{ladeLaufendeAnmeldung as ps,merkeAnmeldung as ms,vergissAnmeldung as It}from"./laufende-anmeldung.js";import{KEYCLOAK_BASIS as Et,istTestSchluessel as fs,waehleTestSchluessel as gs,starteKeycloakAnmeldung as hs,warteAufKeycloakAnmeldung as ys,uebernimm as bs,brainImKonto as ws,erfolgsText as vs,fehlerText as xs,ersetzeSchluessel as _s}from"./uebernahme.js";import{WARTE_TAKT_MS as $s,auftragLiegt as Rt,nimmAuftrag as ks,sichereKonto as Ss,sperreLiegt as As,startwissenEingeschaltet as jt}from"./konto-anlegen.js";import{sichereZugang as Cs,echterWert as Ee}from"./zugang.js";import{zeitpunkt as Y}from"./zeitmessung.js";import{autoSitzungsSchritt as Ts,SITZUNGS_WERKZEUGE as Is}from"./auto-sitzung.js";import{warteAufLaufendeInstanz as Es,gemeinsamerAufbau as Rs}from"./instanz-warten.js";import{merkeNeuesBrain as Ye,startetLautLetztemBlick as js,setzeCommitQuelle as Ns}from"./leeres-brain.js";import{starteStartwissen as Ps,startwissenGestartet as Bs,beanspruchStartwissen as Os,holeStartwissenHinweis as Ls,waehleProjektOrdner as Hs,startvorratErlaubt as Ms,projektCommits as zs}from"./startwissen.js";import{eigeneFassung as Ds,pruefeNeueFassung as Us,holeNeueFassungHinweis as Ws}from"./neue-fassung.js";import{beiStdinEnde as Js}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Fs,starteBrandWachhund as Ys}from"./brand-wachhund.js";import{sichtbareWerkzeuge as Ks,VERTEILER as Nt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as Gs}from"./pflichtfelder.js";import{buildLessonsMarkdown as qs,buildLessonsJsonl as Vs,vonRohLektion as Zs}from"./brain-export.js";import{detectEditor as Xs}from"./editor.js";import{milestoneSent as Pt,markMilestoneSent as Bt}from"./funnel-milestones.js";import{meldeKopf as Qs,meldeRumpf as er}from"./melde-weg.js";import{kostprobeUebrig as tr,kostprobeVerbrauchen as or,kostprobeHinweis as nr,kostprobePfadJeInstanz as sr,schrankeNachKostproben as rr}from"./kostprobe.js";import{netBalance as ir}from"./ambient-recall.js";import{handleShareTool as Ke}from"./handlers/share.js";import{handleVizTool as ar}from"./handlers/viz.js";import{commitArt as cr,istRueckbau as lr,zaehleLektionen as dr}from"./commit-art.js";import{TOOLS as le}from"./tools.js";import{verbindungsWeg as Ot}from"./brains-tls.js";let Lt=!1,Ht=!1,Re=!1;function Mt(){return Xs()}function C(e,t,n){process.env.CACHLY_NO_TELEMETRY!=="1"&&(W()||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:Qs(A),body:JSON.stringify(er({event:e,version:H,editor:Mt()},t,n)),signal:AbortSignal.timeout(3e3)}).catch(()=>{}))}function ur(e,t){return cs({apiUrl:x,jwt:A,instanceId:e},t)}async function pr(e){if(!(Lt||W())&&process.env.CACHLY_NO_TELEMETRY!=="1"){Lt=!0;try{await fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:H,editor:Mt(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const mr=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"]),fr={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."},zt=j("/billing","upgrade"),Dt=new Map;async function gr(e){const t=Dt.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const o=((await O(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),s={tier:o,isFree:o==="free"||o===""};return Dt.set(e,{info:s,expiresAt:Date.now()+6e4}),s}catch{return{tier:"unknown",isFree:!1}}}async function hr(e,t){if(!mr.has(e)||!t)return null;const{isFree:n}=await gr(t);if(!n)return null;const o=fr[e]??"A Premium intelligence feature.",s=W()?sr(t):void 0;if(tr(e,s)){const r=or(e,s);return{kostprobe:nr(e,r,zt)}}return{sperre:rr(e,o,zt)}}async function yr(e,t){try{await(await L(e)).hincrby(po(e),t,1)}catch{}}async function br(e,t,n){if(mo(t))try{const o=await L(e),s=ho(n);await o.incrby(fo(e),s?go(n):0),await o.hincrby(Xe(e),"abrufe",1),s&&await o.hincrby(Xe(e),"treffer",1)}catch{}}async function wr(e){const t=await Ro();return t?(K=t,ms({deviceCode:t.deviceCode,userCode:t.userCode,verifyUrl:t.verifyUrl,pollInterval:t.pollInterval,deadline:t.deadline,apiUrl:x}),C("device_flow_started",{tool:e}),ce(t.verifyUrl,(n,o)=>{if(n){C("device_browser_opened",{stelle:"tool"});return}C("device_browser_failed",{reason:o??"unknown",stelle:"tool"}),process.stderr.write(`
25
+ \u2022 Technical detail: ${i}`)}return n?$e.set(t,d):fe.set(e,d),Y("verbindung: Valkey verbunden"),d}async function O(e,t={},n=!1){!n&&!W()&&Ze(Oe(A))!=="none"&&await Ue();const o=we();ao(o);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),r=await fetch(`${x}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,...t.headers}});if(!r.ok){if(r.status===401&&!n&&!W()&&(De=0,await Ue()))return O(e,t,!0);const d=(await r.json().catch(()=>({error:r.statusText}))).error??r.statusText;co(r.status,d)}if(r.status!==204)return r.json()}import{handleBrainTool as An}from"./handlers/brain.js";import{handleContextTool as Cn}from"./handlers/context.js";import{handleInstanceTool as Tn}from"./handlers/instances.js";import{handleCacheTool as In}from"./handlers/cache.js";import{handleTeamTool as En}from"./handlers/team.js";import{handleRoadmapTool as Rn}from"./handlers/roadmap.js";import{handleAdvancedTool as jn}from"./handlers/advanced.js";import{handleSyndicateTool as Nn}from"./handlers/syndicate.js";import{handleFedbrainTool as Je,_lastBrainFromGitCounts as ke}from"./handlers/fedbrain.js";import{extractFirstRecallProof as Pn,extractTopHit as Bn,fuersTerminal as wt,renderFirstRecallProof as On}from"./first-recall-proof.js";import{aussetzerLeise as Ln}from"./aussetzer.js";import{gitHookOrdner as Hn,installClsPostCommitHook as vt,CLS_HOOK_VERSION as xt}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as Mn,CLAUDE_MD_MARKER_END as zn,EDITOR_FILES as Se,ANWEISUNGS_DATEIEN as Dn,buildClaudeMdBlock as _t,setzeAnweisungsblock as Un,sollSchreiben as Wn,globaleMcpDatei as Ae,globalerEditorDa as $t,diesesHeim as ge,mcpZiel as kt}from"./projektdateien.js";import{klassiereArgument as Jn,leseFlag as St,flagsOhneWert as Fn,pruefeInitEingaben as Yn}from"./cli-argumente.js";import{uninstallBefehl as Kn}from"./uninstall.js";import{gitLesen as At}from"./git-ohne-shell.js";import{browserAdresse as Gn,fuerCmd as qn}from"./browser-adresse.js";import{installAmbientHooks as Ct,installCursorHooks as Vn,installCopilotHooks as Zn,installCodexHooks as Xn,installGeminiHooks as Qn,AMBIENT_HOOK_VERSION as Tt,COPILOT_HOOKS_DATEI as es,CODEX_HOOKS_DATEI as ts,GEMINI_SETTINGS_DATEI as os}from"./ambient-hooks.js";import{hookHauptlauf as ns,auffrischenHauptlauf as ss,startwissenImportHauptlauf as rs}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as is}from"./startwissen-hook.js";import{rahmeAntwort as as}from"./antwort-rahmen.js";import{appendLedgerEntry as cs,readLedger as It,defaultLedgerPath as ls,reportLedgerEntry as ds,teileNachInstanz as us}from"./ambient-ledger.js";import{installCodexMcp as ps,installGeminiMcp as ms}from"./editor-mcp-eintrag.js";import{resolveApiKey as Fe,saveApiKey as ne,saveInstanceId as Ce,readSavedApiKey as Te,readInstanceId as Ie}from"./credentials.js";import{ladeLaufendeAnmeldung as fs,merkeAnmeldung as gs,vergissAnmeldung as Et}from"./laufende-anmeldung.js";import{KEYCLOAK_BASIS as Rt,istTestSchluessel as hs,waehleTestSchluessel as ys,starteKeycloakAnmeldung as bs,warteAufKeycloakAnmeldung as ws,uebernimm as vs,brainImKonto as xs,erfolgsText as _s,fehlerText as $s,ersetzeSchluessel as ks}from"./uebernahme.js";import{WARTE_TAKT_MS as Ss,auftragLiegt as jt,nimmAuftrag as As,sichereKonto as Cs,sperreLiegt as Ts,startwissenEingeschaltet as Nt}from"./konto-anlegen.js";import{sichereZugang as Is,echterWert as Ee}from"./zugang.js";import{zeitpunkt as Y}from"./zeitmessung.js";import{autoSitzungsSchritt as Es,SITZUNGS_WERKZEUGE as Rs}from"./auto-sitzung.js";import{warteAufLaufendeInstanz as js,gemeinsamerAufbau as Ns}from"./instanz-warten.js";import{merkeNeuesBrain as Ye,startetLautLetztemBlick as Ps,setzeCommitQuelle as Bs}from"./leeres-brain.js";import{starteStartwissen as Os,startwissenGestartet as Ls,beanspruchStartwissen as Hs,holeStartwissenHinweis as Ms,waehleProjektOrdner as zs,startvorratErlaubt as Ds,projektCommits as Us}from"./startwissen.js";import{eigeneFassung as Ws,pruefeNeueFassung as Js,holeNeueFassungHinweis as Fs}from"./neue-fassung.js";import{beiStdinEnde as Ys}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Ks,starteBrandWachhund as Gs}from"./brand-wachhund.js";import{sichtbareWerkzeuge as qs,VERTEILER as Pt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as Vs}from"./pflichtfelder.js";import{buildLessonsMarkdown as Zs,buildLessonsJsonl as Xs,vonRohLektion as Qs}from"./brain-export.js";import{detectEditor as er}from"./editor.js";import{milestoneSent as Bt,markMilestoneSent as Ot}from"./funnel-milestones.js";import{meldeKopf as tr,meldeRumpf as or}from"./melde-weg.js";import{kostprobeUebrig as nr,kostprobeVerbrauchen as sr,kostprobeHinweis as rr,kostprobePfadJeInstanz as ir,schrankeNachKostproben as ar}from"./kostprobe.js";import{netBalance as cr}from"./ambient-recall.js";import{handleShareTool as Ke}from"./handlers/share.js";import{handleVizTool as lr}from"./handlers/viz.js";import{commitArt as dr,istRueckbau as ur,zaehleLektionen as pr}from"./commit-art.js";import{TOOLS as le}from"./tools.js";import{verbindungsWeg as Lt}from"./brains-tls.js";let Ht=!1,Mt=!1,Re=!1;function zt(){return er()}function C(e,t,n){process.env.CACHLY_NO_TELEMETRY!=="1"&&(W()||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:tr(A),body:JSON.stringify(or({event:e,version:H,editor:zt()},t,n)),signal:AbortSignal.timeout(3e3)}).catch(()=>{}))}function mr(e,t){return ds({apiUrl:x,jwt:A,instanceId:e},t)}async function fr(e){if(!(Ht||W())&&process.env.CACHLY_NO_TELEMETRY!=="1"){Ht=!0;try{await fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:H,editor:zt(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const gr=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"]),hr={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."},Dt=j("/billing","upgrade"),Ut=new Map;async function yr(e){const t=Ut.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const o=((await O(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),s={tier:o,isFree:o==="free"||o===""};return Ut.set(e,{info:s,expiresAt:Date.now()+6e4}),s}catch{return{tier:"unknown",isFree:!1}}}async function br(e,t){if(!gr.has(e)||!t)return null;const{isFree:n}=await yr(t);if(!n)return null;const o=hr[e]??"A Premium intelligence feature.",s=W()?ir(t):void 0;if(nr(e,s)){const r=sr(e,s);return{kostprobe:rr(e,r,Dt)}}return{sperre:ar(e,o,Dt)}}async function wr(e,t){try{await(await L(e)).hincrby(mo(e),t,1)}catch{}}async function vr(e,t,n){if(fo(t))try{const o=await L(e),s=yo(n);await o.incrby(go(e),s?ho(n):0),await o.hincrby(Xe(e),"abrufe",1),s&&await o.hincrby(Xe(e),"treffer",1)}catch{}}async function xr(e){const t=await jo();return t?(K=t,gs({deviceCode:t.deviceCode,userCode:t.userCode,verifyUrl:t.verifyUrl,pollInterval:t.pollInterval,deadline:t.deadline,apiUrl:x}),C("device_flow_started",{tool:e}),ce(t.verifyUrl,(n,o)=>{if(n){C("device_browser_opened",{stelle:"tool"});return}C("device_browser_failed",{reason:o??"unknown",stelle:"tool"}),process.stderr.write(`
26
26
  cachly: could not open a browser (${o??"unknown"}).
27
27
  cachly: open this yourself to finish signing in:
28
28
  cachly: ${t.verifyUrl}
@@ -30,8 +30,8 @@ cachly: code ${t.userCode}
30
30
 
31
31
  `)}),mt(t),["\u{1F9E0} **cachly AI Brain \u2014 the user must sign in once.**","","**Show the following link and code to the user verbatim \u2014 they cannot","continue without them.**","",`\u{1F449} **${t.verifyUrl}**`,"",`Code: **${t.userCode}**`,"","A browser may have opened automatically with the code pre-filled. If it","did not, the link above is the whole step.","","Once signed in, the Brain activates on its own \u2014 no further action, no","restart. The next request arrives brain-powered.","",`\u2728 ${le.length} MCP tools \xB7 GDPR \xB7 EU servers \xB7 free tier, no credit card`].join(`
32
32
  `)):["\u{1F9E0} **cachly AI Brain \u2014 Setup required**","","Run the setup wizard once in your terminal:"," ```"," npx @cachly-dev/mcp-server@latest autopilot"," ```","",`Or get your API key at: ${j("/setup-ai","ambient-signin")}`,"","\u2728 Free tier includes: 1 Brain instance, persistent memory, semantic search."].join(`
33
- `)}async function vr(e){if(!e)return!0;if(Bs(e))return!1;try{return await Os(await L(e),"sitzungsstart")}catch{return!0}}async function J(e,t){if(W()&&!we())return _e;if(!we()&&await ze($o))return J(e,t);if(!we()){if(pr(e),!K){const a=jo();a&&(K=a,C("device_flow_resumed",{tool:e}),mt(a))}if(K){const a=await pt(K);return a==="done"?J(e,t):a==="expired"?(C("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 Cs({schluessel:A,konfigurierteInstanz:P,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{Y("sofort-test: Anfang");const a=await Ss({apiUrl:x,version:H,fristMs:ko}),g=a.art==="angelegt"?a.test:a.art==="vorhanden"&&a.instanzId?{apiKey:a.apiKey,instanzId:a.instanzId}:null;return Y(`sofort-test: ${g?"Brain angelegt":"kein Test"}`),g&&Ye(g.instanzId,ie(),Me()),g},ablagen:{setzeSchluessel:a=>{A=a},setEmbedJwt:oe,saveApiKey:a=>ne(a),persistApiKeyToConfig:pe,merkeInstanz:a=>{P=a,Q=0},persistInstanceIdToConfig:me},meldeEreignis:C,werkzeug:()=>J(e,t),anmelden:()=>wr(e),neuesBrain:He})}if(!t.instance_id){const a=await dt();a&&(t={...t,instance_id:a})}const n=await hr(e,t.instance_id);let o="";if(n!==null){if("sperre"in n)return C("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;o=n.kostprobe,C("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&yr(t.instance_id,e),Y(`werkzeug ${e}: Zugang und Tarif geklaert`);const s=await kn(e,t,L,O);if(Y(`werkzeug ${e}: Brain-Werkzeug fertig`),s!==null){typeof t.instance_id=="string"&&t.instance_id&&br(t.instance_id,e,String(s??"")),!Re&&A&&(Re=!0,Pt("first_call_success")||(Bt("first_call_success"),C("first_call_success",{tool:e,instance_id:t.instance_id??P??""})));const a=t.instance_id??P??"",g={instance_id:a};if(e==="recall_best_solution")C("recall_best_solution",g);else if(e==="learn_from_attempts")C("learn_from_attempts",g);else if(e==="session_start"){C("session_start",g,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const m=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),S=m.includes("Welcome! Your AI Brain is live.");if(!js(a)){if(!S&&m.length>100)C("recall_best_solution",g);else if(S&&t.workspace_path&&await vr(a))try{const k=await Je("brain_from_git",{instance_id:a,repo_path:t.workspace_path,limit:50},L,O);if(k!==null){C("brain_from_git",{...g,...ke??{}}),C("recall_best_solution",g);let R="";if((ke?.total??0)===0)try{const M=await Ke("brain_seed_starter",{instance_id:a},L,O);M&&(C("brain_seed_starter",{...g,auto:!0},{seeded_count:16,auto:!0}),R=`
33
+ `)}async function _r(e){if(!e)return!0;if(Ls(e))return!1;try{return await Hs(await L(e),"sitzungsstart")}catch{return!0}}async function J(e,t){if(W()&&!we())return _e;if(!we()&&await ze(ko))return J(e,t);if(!we()){if(fr(e),!K){const a=No();a&&(K=a,C("device_flow_resumed",{tool:e}),mt(a))}if(K){const a=await pt(K);return a==="done"?J(e,t):a==="expired"?(C("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 Is({schluessel:A,konfigurierteInstanz:P,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{Y("sofort-test: Anfang");const a=await Cs({apiUrl:x,version:H,fristMs:So}),g=a.art==="angelegt"?a.test:a.art==="vorhanden"&&a.instanzId?{apiKey:a.apiKey,instanzId:a.instanzId}:null;return Y(`sofort-test: ${g?"Brain angelegt":"kein Test"}`),g&&Ye(g.instanzId,ie(),Me()),g},ablagen:{setzeSchluessel:a=>{A=a},setEmbedJwt:oe,saveApiKey:a=>ne(a),persistApiKeyToConfig:pe,merkeInstanz:a=>{P=a,Q=0},persistInstanceIdToConfig:me},meldeEreignis:C,werkzeug:()=>J(e,t),anmelden:()=>xr(e),neuesBrain:He})}if(!t.instance_id){const a=await dt();a&&(t={...t,instance_id:a})}const n=await br(e,t.instance_id);let o="";if(n!==null){if("sperre"in n)return C("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;o=n.kostprobe,C("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&wr(t.instance_id,e),Y(`werkzeug ${e}: Zugang und Tarif geklaert`);const s=await An(e,t,L,O);if(Y(`werkzeug ${e}: Brain-Werkzeug fertig`),s!==null){typeof t.instance_id=="string"&&t.instance_id&&vr(t.instance_id,e,String(s??"")),!Re&&A&&(Re=!0,Bt("first_call_success")||(Ot("first_call_success"),C("first_call_success",{tool:e,instance_id:t.instance_id??P??""})));const a=t.instance_id??P??"",g={instance_id:a};if(e==="recall_best_solution")C("recall_best_solution",g);else if(e==="learn_from_attempts")C("learn_from_attempts",g);else if(e==="session_start"){C("session_start",g,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const m=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),S=m.includes("Welcome! Your AI Brain is live.");if(!Ps(a)){if(!S&&m.length>100)C("recall_best_solution",g);else if(S&&t.workspace_path&&await _r(a))try{const k=await Je("brain_from_git",{instance_id:a,repo_path:t.workspace_path,limit:50},L,O);if(k!==null){C("brain_from_git",{...g,...ke??{}}),C("recall_best_solution",g);let R="";if((ke?.total??0)===0)try{const M=await Ke("brain_seed_starter",{instance_id:a},L,O);M&&(C("brain_seed_starter",{...g,auto:!0},{seeded_count:16,auto:!0}),R=`
35
35
  ---
36
36
  `+String(M))}catch{}const I=String(k),$=ke?.total??0,E=$>0?`
37
37
  \u2705 **Brain bootstrapped from git \u2014 ${$} lesson${$===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(I||R||E)return String(s)+E+`
@@ -42,7 +42,7 @@ cachly: code ${t.userCode}
42
42
  > Run \`brain_from_git(instance_id="`+a+'", repo_path="'+String(t.workspace_path)+'")` manually to seed it.\n> Or try `brain_seed_starter` to load 16 universal engineering lessons instantly.'}}}else if(e==="session_end")C("session_end",g);else if(e==="smart_recall"){const m=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),S=m.length>50&&!m.includes("No lessons found")&&!m.includes("no lessons")&&!m.includes("No matches found");if(C("smart_recall",g,{hit:S,topic:String(t.query??"").slice(0,80)}),S&&C("recall_best_solution",g),ae&&typeof s=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${ae.split(`
43
43
  `)[0]}
44
44
 
45
- ${s}`}return s}const r=await Sn(e,t,L,O);if(r!==null)return!Re&&A&&(Re=!0,Pt("first_call_success")||(Bt("first_call_success"),C("first_call_success",{tool:e,instance_id:t.instance_id??P??""}))),r;const c=await An(e,t,L,O);if(c!==null)return c;const d=await Cn(e,t,L,O);if(d!==null)return d;const u=a=>o?a+o:a,l=await Tn(e,t,L,O);if(l!==null)return u(l);const i=await In(e,t,L,O);if(i!==null)return i;const p=await En(e,t,L,O);if(p!==null)return u(p);const f=await Rn(e,t,L,O);if(f!==null){if(e==="brain_predict"){const g={instance_id:t.instance_id??P??""};C("brain_predict",g)}return u(f)}const y=await Ke(e,t,L,O);if(y!==null)return y;const w=await ar(e,t,L,O);if(w!==null)return w;const h=await Je(e,t,L,O);if(h!==null){const g={instance_id:t.instance_id??P??""};if(e==="brain_from_git"){const m=ke;C("brain_from_git",{...g,...m??{}},m?{fixes:m.fixes,features:m.features,refactors:m.refactors,total:m.total}:void 0)}else e==="brain_predict_failures"&&C("brain_predict_failures",g);return h}switch(e){case"get_api_status":{let a="unknown";try{const k=await fetch(`${x}/health`,{signal:AbortSignal.timeout(8e3)});if(k.ok){const _=await k.json();a=`${_.status??"ok"} (db: ${_.db??"?"})`}else a=`HTTP ${k.status}`}catch(k){a=`unreachable: ${k.message}`}if(!A)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${x}`,` \u{1F493} Health: ${a}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${j("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
45
+ ${s}`}return s}const r=await Cn(e,t,L,O);if(r!==null)return!Re&&A&&(Re=!0,Bt("first_call_success")||(Ot("first_call_success"),C("first_call_success",{tool:e,instance_id:t.instance_id??P??""}))),r;const l=await Tn(e,t,L,O);if(l!==null)return l;const d=await In(e,t,L,O);if(d!==null)return d;const u=a=>o?a+o:a,c=await En(e,t,L,O);if(c!==null)return u(c);const i=await Rn(e,t,L,O);if(i!==null)return i;const p=await jn(e,t,L,O);if(p!==null)return u(p);const f=await Nn(e,t,L,O);if(f!==null){if(e==="brain_predict"){const g={instance_id:t.instance_id??P??""};C("brain_predict",g)}return u(f)}const y=await Ke(e,t,L,O);if(y!==null)return y;const w=await lr(e,t,L,O);if(w!==null)return w;const h=await Je(e,t,L,O);if(h!==null){const g={instance_id:t.instance_id??P??""};if(e==="brain_from_git"){const m=ke;C("brain_from_git",{...g,...m??{}},m?{fixes:m.fixes,features:m.features,refactors:m.refactors,total:m.total}:void 0)}else e==="brain_predict_failures"&&C("brain_predict_failures",g);return h}switch(e){case"get_api_status":{let a="unknown";try{const k=await fetch(`${x}/health`,{signal:AbortSignal.timeout(8e3)});if(k.ok){const _=await k.json();a=`${_.status??"ok"} (db: ${_.db??"?"})`}else a=`HTTP ${k.status}`}catch(k){a=`unreachable: ${k.message}`}if(!A)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${x}`,` \u{1F493} Health: ${a}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${j("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
46
46
  `);let g="\u274C invalid JWT format";try{const k=A.split(".");if(k.length===3){const _=JSON.parse(Buffer.from(k[1],"base64url").toString("utf-8")),R=_.sub??"(unknown)",I=_.iss??"(unknown)",$=I.includes("keycloak")?"Keycloak":"OIDC",E=_.exp?new Date(_.exp*1e3):null,M=E?E<new Date:!1;g=["\u2705 JWT decoded",` Sub (user ID): ${R}`,` Provider: ${$}`,` Issuer: ${I}`,` Expires: ${E?E.toISOString():"never"} ${M?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
47
47
  `)}}catch{g="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let m="";try{const _=(await O("/api/v1/instances")).data??[];if(_.length===0)m=`
48
48
 
@@ -53,7 +53,7 @@ ${s}`}return s}const r=await Sn(e,t,L,O);if(r!==null)return!Re&&A&&(Re=!0,Pt("fi
53
53
 
54
54
  \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${k.message}`}await Ue();const S=Oe(A),v=S.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":S.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${S.expiresInMs?` (${Math.round(S.expiresInMs/36e5)}h left)`:""}`:S.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${S.message.split(`
55
55
  `)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${x}`,` \u{1F493} Health: ${a}`,` ${v}`,"","\u{1F511} **Auth:**",g,m].join(`
56
- `)}default:throw new Ut(`Unknown tool: ${e}`)}}class Ut extends Error{}const Wt=`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.
56
+ `)}default:throw new Wt(`Unknown tool: ${e}`)}}class Wt extends Error{}const Jt=`REQUIRED FIRST STEP for every task in this project: before you read or edit any file, call the cachly tool smart_recall with one line describing the task (if it is not loaded yet, load it with your tool search first). It returns fixes, decisions and known traps from earlier sessions in THIS codebase. Do this even for small tasks.
57
57
 
58
58
  This project has a Cachly AI Brain \u2014 persistent, cross-session memory of past fixes, decisions, and gotchas for THIS codebase.
59
59
 
@@ -63,28 +63,28 @@ This project has a Cachly AI Brain \u2014 persistent, cross-session memory of pa
63
63
  - BEFORE a risky op (deploy, migration, dependency bump): call brain_predict.
64
64
 
65
65
  You do not need to pass instance_id: the server uses CACHLY_BRAIN_INSTANCE_ID if it is set, and otherwise the Brain saved by \`cachly setup\` in ~/.cachly/credentials.json.
66
- session_start gives a briefing at the start of a session; it does not replace smart_recall for a concrete task.`,Jt={tools:{},resources:{},prompts:{}},Ft=async()=>{const{katalog:e,unbekannteKernnamen:t}=Ks(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function Yt(){return{resources:[]}}async function Kt(){return{resourceTemplates:[]}}async function Gt(){return{prompts:[]}}function xr(e){e.setRequestHandler(it,Ft),e.setRequestHandler(ot,Xt),e.setRequestHandler(rt,Yt),e.setRequestHandler(st,Kt),e.setRequestHandler(nt,Gt)}function _r(){const e=new tt({name:"cachly-mcp",version:H},{capabilities:Jt,instructions:Wt});return xr(e),qt(e),e}function qt(e){const t=e.oninitialized;e.oninitialized=()=>{let n;try{n=e.getClientVersion(),so(n?.name,n?.version)}catch{}Ht||(Ht=!0,C("mcp_verbunden",{client:String(n?.name??"unbekannt").slice(0,60),client_version:String(n?.version??"").slice(0,30)})),t?.()}}const q=new tt({name:"cachly-mcp",version:H},{capabilities:Jt,instructions:Wt});qt(q),q.setRequestHandler(it,Ft),q.setRequestHandler(rt,Yt),q.setRequestHandler(st,Kt),q.setRequestHandler(nt,Gt);let je=null,de=!1,se=null,Vt=0;async function $r(e){if(!de){if(se){await se;return}se=(async()=>{de=!0,je=e;try{await J("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{se=null}})(),await se,Zt(e)}}function kr(e){de=!0,je=e}function Zt(e){process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await L(e),n=await t.get(`cachly:index:last_indexed:${e}`),o=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>o)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),await J("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code",hintergrund:!0}))})().catch(()=>{})}async function Ge(){if(!(!de||!je)){de=!1;try{await J("session_end",{instance_id:je,summary:`Auto-ended after ${Vt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Xt=async e=>{let{name:t,arguments:n}=e.params;if(t===Nt){const r=n??{},c=typeof r.tool=="string"?r.tool:"";if(!c)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const d=le.find(u=>u.name===c);if(!d)return{content:[{type:"text",text:`Kein Werkzeug namens "${c}". Die Liste steht in der Beschreibung von ${Nt}.`}],isError:!0};if(r.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:d.name,description:d.description,inputSchema:d.inputSchema},null,2)}]};t=c,n=r.arguments??{}}if(W()){const r=xe();if(!r)return{content:[{type:"text",text:_e}],isError:!0};if(!r.instanzId)return{content:[{type:"text",text:nn}],isError:!0};if(!Go(t))return{content:[{type:"text",text:qo(t)}],isError:!0};const c=Vo(n??{},r.instanzId);if("fehler"in c)return{content:[{type:"text",text:c.fehler}],isError:!0};n=c.args}if(!["learn_from_attempts","smart_recall","recall_feedback"].includes(t)){const r=le.find(d=>d.name===t),c=r?Gs(t,r.inputSchema,n??{}):null;if(c)return{content:[{type:"text",text:c}],isError:!0}}const o=Ee(n?.instance_id)||P||Ee(process.env.CACHLY_BRAIN_INSTANCE_ID)||"",s=W()?"nichts":Ts(t,{gestartet:de,startetGerade:se!==null,instanz:o});s==="starten"?await $r(o).catch(()=>{}):s==="abwarten"?await se?.catch(()=>{}):s==="als-gestartet-merken"&&kr(o),!W()&&!Is.has(t)&&Vt++;try{Fs(),Y(`werkzeug ${t}: Anfang`);const r=await J(t,n??{});return Y(`werkzeug ${t}: Antwort fertig`),s==="als-gestartet-merken"&&Zt(o),{content:[{type:"text",text:rs(t,r)+Ls()+Ws(t)}]}}catch(r){if(r instanceof Ut)return{content:[{type:"text",text:r.message}],isError:!0};if(r instanceof Z)throw r;const c=r.message??String(r);throw Qe("cachly","tool_error",{tool:t,error:c}).catch(()=>{}),new Z(te.InternalError,c)}};q.setRequestHandler(ot,Xt),process.on("SIGTERM",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await Ge().catch(()=>{});for(const e of We())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
+ session_start gives a briefing at the start of a session; it does not replace smart_recall for a concrete task.`,Ft={tools:{},resources:{},prompts:{}},Yt=async()=>{const{katalog:e,unbekannteKernnamen:t}=qs(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function Kt(){return{resources:[]}}async function Gt(){return{resourceTemplates:[]}}async function qt(){return{prompts:[]}}function $r(e){e.setRequestHandler(it,Yt),e.setRequestHandler(ot,Qt),e.setRequestHandler(rt,Kt),e.setRequestHandler(st,Gt),e.setRequestHandler(nt,qt)}function kr(){const e=new tt(bt(H),{capabilities:Ft,instructions:Jt});return $r(e),Vt(e),e}function Vt(e){const t=e.oninitialized;e.oninitialized=()=>{let n;try{n=e.getClientVersion(),ro(n?.name,n?.version)}catch{}Mt||(Mt=!0,C("mcp_verbunden",{client:String(n?.name??"unbekannt").slice(0,60),client_version:String(n?.version??"").slice(0,30)})),t?.()}}const q=new tt(bt(H),{capabilities:Ft,instructions:Jt});Vt(q),q.setRequestHandler(it,Yt),q.setRequestHandler(rt,Kt),q.setRequestHandler(st,Gt),q.setRequestHandler(nt,qt);let je=null,de=!1,se=null,Zt=0;async function Sr(e){if(!de){if(se){await se;return}se=(async()=>{de=!0,je=e;try{await J("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{se=null}})(),await se,Xt(e)}}function Ar(e){de=!0,je=e}function Xt(e){process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await L(e),n=await t.get(`cachly:index:last_indexed:${e}`),o=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>o)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),await J("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code",hintergrund:!0}))})().catch(()=>{})}async function Ge(){if(!(!de||!je)){de=!1;try{await J("session_end",{instance_id:je,summary:`Auto-ended after ${Zt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Qt=async e=>{let{name:t,arguments:n}=e.params;if(t===Pt){const r=n??{},l=typeof r.tool=="string"?r.tool:"";if(!l)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const d=le.find(u=>u.name===l);if(!d)return{content:[{type:"text",text:`Kein Werkzeug namens "${l}". Die Liste steht in der Beschreibung von ${Pt}.`}],isError:!0};if(r.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:d.name,description:d.description,inputSchema:d.inputSchema},null,2)}]};t=l,n=r.arguments??{}}if(W()){const r=xe();if(!r)return{content:[{type:"text",text:_e}],isError:!0};if(!r.instanzId)return{content:[{type:"text",text:sn}],isError:!0};if(!qo(t))return{content:[{type:"text",text:Vo(t)}],isError:!0};const l=Zo(n??{},r.instanzId);if("fehler"in l)return{content:[{type:"text",text:l.fehler}],isError:!0};n=l.args}if(!["learn_from_attempts","smart_recall","recall_feedback"].includes(t)){const r=le.find(d=>d.name===t),l=r?Vs(t,r.inputSchema,n??{}):null;if(l)return{content:[{type:"text",text:l}],isError:!0}}const o=Ee(n?.instance_id)||P||Ee(process.env.CACHLY_BRAIN_INSTANCE_ID)||"",s=W()?"nichts":Es(t,{gestartet:de,startetGerade:se!==null,instanz:o});s==="starten"?await Sr(o).catch(()=>{}):s==="abwarten"?await se?.catch(()=>{}):s==="als-gestartet-merken"&&Ar(o),!W()&&!Rs.has(t)&&Zt++;try{Ks(),Y(`werkzeug ${t}: Anfang`);const r=await J(t,n??{});return Y(`werkzeug ${t}: Antwort fertig`),s==="als-gestartet-merken"&&Xt(o),{content:[{type:"text",text:as(t,r)+Ms()+Fs(t)}]}}catch(r){if(r instanceof Wt)return{content:[{type:"text",text:r.message}],isError:!0};if(r instanceof Z)throw r;const l=r.message??String(r);throw Qe("cachly","tool_error",{tool:t,error:l}).catch(()=>{}),new Z(te.InternalError,l)}};q.setRequestHandler(ot,Qt),process.on("SIGTERM",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("unhandledRejection",e=>{const t=e instanceof Error?e.message:String(e);process.stderr.write(`[cachly-mcp] unhandledRejection: ${t}
67
67
  `)}),process.on("uncaughtException",e=>{process.stderr.write(`[cachly-mcp] uncaughtException: ${e?.stack??String(e)}
68
- `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function Sr(e,t){const n=Object.entries(t).map(([o,s])=>`${o}=${s}`);return e==="codex"?{befehl:`codex mcp add cachly ${n.map(o=>`--env ${o}`).join(" ")} -- npx -y @cachly-dev/mcp-server@latest`,wo:"~/.codex/config.toml"}:e==="gemini"?{befehl:`gemini mcp add -s project ${n.map(o=>`-e ${o}`).join(" ")} cachly npx -- -y @cachly-dev/mcp-server@latest`,wo:".gemini/settings.json"}:null}const Qt="https://api.cachly.dev";function ee(e,t,n={}){const o={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(o.CACHLY_JWT=e),x&&x!==Qt&&(o.CACHLY_API_URL=x),o}function Ar(e,t,n){return n==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:ee(e,t)}]}},null,2):n==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)},settings:{}}}},null,2):eo(n)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)}}},null,2)}function eo(e){return Se[e]===".vscode/mcp.json"}function he(e,t){fs(e)||ne(e,t)}async function to(e,t,n,o,s,r={}){const c={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(t,n)};if(!s.existsSync(e))return Ar(t,n,o);let d={};try{d=JSON.parse(await s.readFile(e,"utf-8"))}catch{try{const{rename:p}=await import("node:fs/promises");await p(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
69
- `)}catch{}}if(o==="continue"){const p=d.experimental??{},f=p.modelContextProtocolServers??[];let y;for(const h of f){const a=h.env??{};if(a.CACHLY_JWT){y=a.CACHLY_JWT;break}}y&&he(y,r);const w=f.filter(h=>{const a=h.env??{};return!a.CACHLY_JWT&&!a.CACHLY_BRAIN_INSTANCE_ID});return w.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:c.env}),d.experimental={...p,modelContextProtocolServers:w},JSON.stringify(d,null,2)}if(o==="zed"){const p=d.context_servers??{},y=p.cachly?.command?.env?.CACHLY_JWT;return y&&he(y,r),p.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:c.env},settings:{}},d.context_servers=p,JSON.stringify(d,null,2)}if(eo(o)){const p=d.mcpServers??void 0,y=p?.cachly?.env?.CACHLY_JWT;y&&he(y,r),p&&"cachly"in p&&(delete p.cachly,Object.keys(p).length===0&&delete d.mcpServers);const w=d.servers??{},h=w.cachly,a=h?.env?.CACHLY_JWT;return a&&he(a,r),w.cachly=h?.envFile?{type:"stdio",...c,envFile:h.envFile}:{type:"stdio",...c},d.servers=w,JSON.stringify(d,null,2)}const u=d.mcpServers??{},i=u.cachly?.env?.CACHLY_JWT;return i&&he(i,r),u.cachly=c,d.mcpServers=u,JSON.stringify(d,null,2)}async function oo(e,t,n,o){const{existsSync:s}=await import("node:fs"),{resolve:r}=await import("node:path"),{homedir:c}=await import("node:os"),d=n??c(),u=Mn.filter(p=>Dn(p,e,d,s,r,o)).map(p=>({path:r(e,...p.pfad),prefix:p.prefix})),l=xt(t),i={};for(const{path:p,prefix:f}of u)try{i[p]=await zn(p,l,f)}catch(y){i[p]=`failed:${y.message}`}return i}function no(e,t){return t.startsWith("failed:")?`\u26A0\uFE0F Could not write ${e}: ${t.slice(7)} (the rest of the setup continues)`:t==="unchanged"?`\u2713 Unchanged: ${e}`:`${t==="updated"?"\u2705 Updated":t==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${e}`}if(process.argv[2]==="digest"){const e=X(),t=U();(!e||!t)&&(console.log(`
68
+ `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function Cr(e,t){const n=Object.entries(t).map(([o,s])=>`${o}=${s}`);return e==="codex"?{befehl:`codex mcp add cachly ${n.map(o=>`--env ${o}`).join(" ")} -- npx -y @cachly-dev/mcp-server@latest`,wo:"~/.codex/config.toml"}:e==="gemini"?{befehl:`gemini mcp add -s project ${n.map(o=>`-e ${o}`).join(" ")} cachly npx -- -y @cachly-dev/mcp-server@latest`,wo:".gemini/settings.json"}:null}const eo="https://api.cachly.dev";function ee(e,t,n={}){const o={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(o.CACHLY_JWT=e),x&&x!==eo&&(o.CACHLY_API_URL=x),o}function Tr(e,t,n){return n==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:ee(e,t)}]}},null,2):n==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)},settings:{}}}},null,2):to(n)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(e,t)}}},null,2)}function to(e){return Se[e]===".vscode/mcp.json"}function he(e,t){hs(e)||ne(e,t)}async function oo(e,t,n,o,s,r={}){const l={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(t,n)};if(!s.existsSync(e))return Tr(t,n,o);let d={};try{d=JSON.parse(await s.readFile(e,"utf-8"))}catch{try{const{rename:p}=await import("node:fs/promises");await p(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
69
+ `)}catch{}}if(o==="continue"){const p=d.experimental??{},f=p.modelContextProtocolServers??[];let y;for(const h of f){const a=h.env??{};if(a.CACHLY_JWT){y=a.CACHLY_JWT;break}}y&&he(y,r);const w=f.filter(h=>{const a=h.env??{};return!a.CACHLY_JWT&&!a.CACHLY_BRAIN_INSTANCE_ID});return w.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:l.env}),d.experimental={...p,modelContextProtocolServers:w},JSON.stringify(d,null,2)}if(o==="zed"){const p=d.context_servers??{},y=p.cachly?.command?.env?.CACHLY_JWT;return y&&he(y,r),p.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:l.env},settings:{}},d.context_servers=p,JSON.stringify(d,null,2)}if(to(o)){const p=d.mcpServers??void 0,y=p?.cachly?.env?.CACHLY_JWT;y&&he(y,r),p&&"cachly"in p&&(delete p.cachly,Object.keys(p).length===0&&delete d.mcpServers);const w=d.servers??{},h=w.cachly,a=h?.env?.CACHLY_JWT;return a&&he(a,r),w.cachly=h?.envFile?{type:"stdio",...l,envFile:h.envFile}:{type:"stdio",...l},d.servers=w,JSON.stringify(d,null,2)}const u=d.mcpServers??{},i=u.cachly?.env?.CACHLY_JWT;return i&&he(i,r),u.cachly=l,d.mcpServers=u,JSON.stringify(d,null,2)}async function no(e,t,n,o){const{existsSync:s}=await import("node:fs"),{resolve:r}=await import("node:path"),{homedir:l}=await import("node:os"),d=n??l(),u=Dn.filter(p=>Wn(p,e,d,s,r,o)).map(p=>({path:r(e,...p.pfad),prefix:p.prefix})),c=_t(t),i={};for(const{path:p,prefix:f}of u)try{i[p]=await Un(p,c,f)}catch(y){i[p]=`failed:${y.message}`}return i}function so(e,t){return t.startsWith("failed:")?`\u26A0\uFE0F Could not write ${e}: ${t.slice(7)} (the rest of the setup continues)`:t==="unchanged"?`\u2713 Unchanged: ${e}`:`${t==="updated"?"\u2705 Updated":t==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${e}`}if(process.argv[2]==="digest"){const e=X(),t=U();(!e||!t)&&(console.log(`
70
70
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
71
71
  `),process.exit(1)),process.stdout.write(`
72
72
  \u{1F9E0} Fetching your weekly Brain digest...
73
73
 
74
- `);try{const n=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const o=await n.json(),s=o.lesson_count??0,r=o.total_recall_count??0,c=Math.round(o.iq_boost_pct??0),d=(o.top_lessons??[]).slice(0,5),u=o.team_authors??[],l=r*1200,i=s<10?"Junior Dev \u{1F527}":s<30?"Mid Dev \u26A1":s<60?"Senior Dev \u{1F9E0}":s<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",p=new Date,f=new Date(p);f.setDate(p.getDate()-7);const y=g=>g.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${y(f)} \u2013 ${y(p)}\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(s).padEnd(8)}\x1B[0m Brain level : \x1B[32m${i.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(l/1e3)+"K (est.)").padEnd(42)}\x1B[0m\u2502`),u.length>0&&(console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1F465} Team contributors:\x1B[0m ${u.slice(0,5).join(", ").slice(0,42).padEnd(42)} \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[33m\u{1F525} Most recalled lessons this week:\x1B[0m \u2502");for(const g of d){const m=`${g.topic}: ${g.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${m.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 w=d[0],h=[`\u{1F9E0} My AI Brain weekly digest (${y(f)} \u2013 ${y(p)}):`,"",` \u{1F4DA} ${s} lessons learned`,` \u{1F501} ${r} recalls \xB7 ~${Math.round(l/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${i}`,w?` \u{1F525} Top lesson: "${w.topic}: ${w.what_worked.slice(0,60)}${w.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
74
+ `);try{const n=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const o=await n.json(),s=o.lesson_count??0,r=o.total_recall_count??0,l=Math.round(o.iq_boost_pct??0),d=(o.top_lessons??[]).slice(0,5),u=o.team_authors??[],c=r*1200,i=s<10?"Junior Dev \u{1F527}":s<30?"Mid Dev \u26A1":s<60?"Senior Dev \u{1F9E0}":s<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",p=new Date,f=new Date(p);f.setDate(p.getDate()-7);const y=g=>g.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${y(f)} \u2013 ${y(p)}\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(s).padEnd(8)}\x1B[0m Brain level : \x1B[32m${i.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(r).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(l).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+Math.round(c/1e3)+"K (est.)").padEnd(42)}\x1B[0m\u2502`),u.length>0&&(console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1F465} Team contributors:\x1B[0m ${u.slice(0,5).join(", ").slice(0,42).padEnd(42)} \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[33m\u{1F525} Most recalled lessons this week:\x1B[0m \u2502");for(const g of d){const m=`${g.topic}: ${g.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${m.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 w=d[0],h=[`\u{1F9E0} My AI Brain weekly digest (${y(f)} \u2013 ${y(p)}):`,"",` \u{1F4DA} ${s} lessons learned`,` \u{1F501} ${r} recalls \xB7 ~${Math.round(c/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${i}`,w?` \u{1F525} Top lesson: "${w.topic}: ${w.what_worked.slice(0,60)}${w.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
75
75
  `),a="https://twitter.com/intent/tweet?text="+encodeURIComponent(h);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const g of h.split(`
76
76
  `))console.log(` ${g}`);console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m"),console.log(""),console.log(" \x1B[36m\u{1F426} Tweet this:\x1B[0m"),console.log(` \x1B[4m${a.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite <email>\x1B[0m"),console.log(" \x1B[2m Cron: 0 9 * * 1 npx @cachly-dev/mcp-server@latest digest\x1B[0m"),console.log("")}catch(n){console.log(`
77
77
  \u274C Could not fetch digest: ${n.message}
78
- `),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"),o=process.argv.slice(3),s=l=>{const i=o.indexOf(`--${l}`);return i!==-1?o[i+1]:void 0},r=s("format")??"both";r!=="md"&&r!=="jsonl"&&r!=="both"&&(console.log(`
78
+ `),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"),o=process.argv.slice(3),s=c=>{const i=o.indexOf(`--${c}`);return i!==-1?o[i+1]:void 0},r=s("format")??"both";r!=="md"&&r!=="jsonl"&&r!=="both"&&(console.log(`
79
79
  \u274C Unknown --format "${r}" \u2014 use md, jsonl, or both.
80
- `),process.exit(1));const c=n(s("out")??"."),d=A||Fe()||"",u=U();(!d||!u)&&(console.log(`
80
+ `),process.exit(1));const l=n(s("out")??"."),d=A||Fe()||"",u=U();(!d||!u)&&(console.log(`
81
81
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
82
82
  `),process.exit(1)),process.stdout.write(`
83
83
  \u{1F4E4} Exporting your Brain...
84
84
 
85
- `);try{let l=[],i="";const p=await fetch(`${x}/api/v1/instances/${u}/export`,{headers:{Authorization:`Bearer ${d}`},signal:AbortSignal.timeout(12e4)});if(p.ok){const y=await p.json();l=(y.lessons??[]).map(Zs).filter(w=>w!==null),y.complete===!1?i=y.note??"the server reported an incomplete read":typeof y.lesson_count=="number"&&l.length<y.lesson_count&&(i=`the server counts ${y.lesson_count} lessons, but only ${l.length} could be read as lessons`)}else if(p.status===404){const y=await fetch(`${x}/api/v1/instances/${u}/memory`,{headers:{Authorization:`Bearer ${d}`},signal:AbortSignal.timeout(8e3)});if(!y.ok)throw new Error(`memory HTTP ${y.status}`);l=((await y.json()).top_lessons??[]).map(h=>({topic:h.topic,outcome:h.outcome,severity:h.severity,tags:h.tags,whatWorked:h.what_worked,ts:h.ts,author:h.author,recallCount:h.recall_count})),i="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 ${p.status}`);l.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
86
- `),process.exit(0)),await t(c,{recursive:!0});const f=[];if(r==="md"||r==="both"){const y=n(c,"lessons.md");await e(y,qs(l),"utf-8"),f.push(`${l.length} lesson${l.length===1?"":"s"} \u2192 ${y}`)}if(r==="jsonl"||r==="both"){const y=n(c,"lessons.jsonl");await e(y,Vs(l),"utf-8"),f.push(`${l.length} lesson${l.length===1?"":"s"} \u2192 ${y}`)}i?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${i}`),console.log("")):console.log("\u2705 Export complete:");for(const y of f)console.log(` ${y}`);console.log("")}catch(l){console.log(`
87
- \u274C Could not export your Brain: ${l.message}
85
+ `);try{let c=[],i="";const p=await fetch(`${x}/api/v1/instances/${u}/export`,{headers:{Authorization:`Bearer ${d}`},signal:AbortSignal.timeout(12e4)});if(p.ok){const y=await p.json();c=(y.lessons??[]).map(Qs).filter(w=>w!==null),y.complete===!1?i=y.note??"the server reported an incomplete read":typeof y.lesson_count=="number"&&c.length<y.lesson_count&&(i=`the server counts ${y.lesson_count} lessons, but only ${c.length} could be read as lessons`)}else if(p.status===404){const y=await fetch(`${x}/api/v1/instances/${u}/memory`,{headers:{Authorization:`Bearer ${d}`},signal:AbortSignal.timeout(8e3)});if(!y.ok)throw new Error(`memory HTTP ${y.status}`);c=((await y.json()).top_lessons??[]).map(h=>({topic:h.topic,outcome:h.outcome,severity:h.severity,tags:h.tags,whatWorked:h.what_worked,ts:h.ts,author:h.author,recallCount:h.recall_count})),i="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 ${p.status}`);c.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
86
+ `),process.exit(0)),await t(l,{recursive:!0});const f=[];if(r==="md"||r==="both"){const y=n(l,"lessons.md");await e(y,Zs(c),"utf-8"),f.push(`${c.length} lesson${c.length===1?"":"s"} \u2192 ${y}`)}if(r==="jsonl"||r==="both"){const y=n(l,"lessons.jsonl");await e(y,Xs(c),"utf-8"),f.push(`${c.length} lesson${c.length===1?"":"s"} \u2192 ${y}`)}i?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${i}`),console.log("")):console.log("\u2705 Export complete:");for(const y of f)console.log(` ${y}`);console.log("")}catch(c){console.log(`
87
+ \u274C Could not export your Brain: ${c.message}
88
88
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=X(),t=(process.argv[3]??"").trim();(!t||t.startsWith("-"))&&(console.log(`
89
89
  Usage: npx @cachly-dev/mcp-server@latest invite <email>`),console.log(" Example: npx @cachly-dev/mcp-server@latest invite teammate@example.com"),console.log(` Your referral link: npx @cachly-dev/mcp-server@latest refer
90
90
  `),process.exit(1)),e||(console.log(`
@@ -97,20 +97,20 @@ Usage: npx @cachly-dev/mcp-server@latest invite <email>`),console.log(" Ex
97
97
  \u274C This Brain was not found in your account. Only the owner of a Brain can invite people.`),console.log(` Brain: ${n}
98
98
  `),process.exit(1)),o.status===409&&(console.log(`
99
99
  \u2139\uFE0F ${t} already has access to this Brain. Nothing was sent.
100
- `),process.exit(1)),!o.ok)throw new Error(`HTTP ${o.status}`);const s=await o.json(),r=s.invite_sent_to??t,c=s.instance?.name??n;console.log(""),console.log(` \u2705 Invitation sent to \x1B[1m${r}\x1B[0m`),console.log(` Brain: \x1B[1m${c}\x1B[0m`),console.log(""),console.log(" They get an email. They accept it in one of two ways:"),console.log(" \u2022 open the link in the email, or"),console.log(" \u2022 run the command from the email: npx @cachly-dev/mcp-server@latest join <token>"),console.log(""),console.log(" Members can read and learn. Deleting the Brain, rotating its password and billing stay with you."),console.log("")}catch(o){console.log(`
100
+ `),process.exit(1)),!o.ok)throw new Error(`HTTP ${o.status}`);const s=await o.json(),r=s.invite_sent_to??t,l=s.instance?.name??n;console.log(""),console.log(` \u2705 Invitation sent to \x1B[1m${r}\x1B[0m`),console.log(` Brain: \x1B[1m${l}\x1B[0m`),console.log(""),console.log(" They get an email. They accept it in one of two ways:"),console.log(" \u2022 open the link in the email, or"),console.log(" \u2022 run the command from the email: npx @cachly-dev/mcp-server@latest join <token>"),console.log(""),console.log(" Members can read and learn. Deleting the Brain, rotating its password and billing stay with you."),console.log("")}catch(o){console.log(`
101
101
  \u274C Could not send the invitation: ${o.message}
102
102
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="refer"){const e=X();e||(console.log(`
103
103
  \u26A0\uFE0F No cachly key found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
104
104
  `),process.exit(1));try{const t=await fetch(`${x}/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(),o=n.url??j(`/r/${n.code}`,"refer"),s=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.
105
105
 
106
- You get a free Brain: ${o}`,c=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
106
+ You get a free Brain: ${o}`,l=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
107
107
 
108
108
  Try it free: ${o}
109
109
 
110
110
  @cachlydev`);console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F9E0} Your cachly referral link \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 ${o.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"),s>0&&(console.log(`\u2502 \x1B[32m\u2713 ${s} developer${s===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 d of r.split(`
111
- `))console.log(`\u2502 \x1B[90m${d.slice(0,58).padEnd(58)}\x1B[0m \u2502`);console.log("\u2502 \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1D54F} Tweet:\x1B[0m https://twitter.com/intent/tweet?text=${c.slice(0,10)}... \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),console.log("\x1B[2m Each developer who signs up via your link earns you 1 month Pro.\x1B[0m"),console.log("\x1B[2m To give someone access to your Brain: npx @cachly-dev/mcp-server@latest invite <email>\x1B[0m"),console.log("")}catch(t){console.log(`
111
+ `))console.log(`\u2502 \x1B[90m${d.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=${l.slice(0,10)}... \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),console.log("\x1B[2m Each developer who signs up via your link earns you 1 month Pro.\x1B[0m"),console.log("\x1B[2m To give someone access to your Brain: npx @cachly-dev/mcp-server@latest invite <email>\x1B[0m"),console.log("")}catch(t){console.log(`
112
112
  \u274C Could not fetch referral link: ${t.message}
113
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s,dirname:r}=await import("node:path"),{homedir:c}=await import("node:os"),{createInterface:d}=await import("node:readline"),u=kt(process.argv,"brain"),l=u===void 0&&process.argv[3]&&!process.argv[3].startsWith("-")?process.argv[3]:"";!l&&!u&&(console.log(`
113
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s,dirname:r}=await import("node:path"),{homedir:l}=await import("node:os"),{createInterface:d}=await import("node:readline"),u=St(process.argv,"brain"),c=u===void 0&&process.argv[3]&&!process.argv[3].startsWith("-")?process.argv[3]:"";!c&&!u&&(console.log(`
114
114
  \u274C Usage: npx @cachly-dev/mcp-server@latest join <token>`),console.log(` npx @cachly-dev/mcp-server@latest join --brain <instance-id>
115
115
  `),console.log(" The token is in the invitation email. A teammate sends one with:"),console.log(` npx @cachly-dev/mcp-server@latest invite <email>
116
116
  `),process.exit(1));let i=A;if(!i){console.log(`
@@ -133,9 +133,9 @@ Try it free: ${o}
133
133
  `),process.exit(1));const S=await m.json();f=S.id??u,y=S.name??f}catch(m){console.log(`
134
134
  \u274C Network error: ${m.message}
135
135
  `),process.exit(1)}}else{console.log(`
136
- \u23F3 Accepting invitation...`);let m=null,S="";try{const _=await fetch(`${x}/api/v1/orgs/accept-invite`,{method:"POST",headers:{...p,"Content-Type":"application/json"},body:JSON.stringify({token:l}),signal:AbortSignal.timeout(15e3)});if(_.ok){const R=await _.json();m=R.data&&typeof R.data=="object"?R.data:R}else S=_.status===401?"your key was not accepted (HTTP 401)":`HTTP ${_.status}`}catch(_){console.log(`
136
+ \u23F3 Accepting invitation...`);let m=null,S="";try{const _=await fetch(`${x}/api/v1/orgs/accept-invite`,{method:"POST",headers:{...p,"Content-Type":"application/json"},body:JSON.stringify({token:c}),signal:AbortSignal.timeout(15e3)});if(_.ok){const R=await _.json();m=R.data&&typeof R.data=="object"?R.data:R}else S=_.status===401?"your key was not accepted (HTTP 401)":`HTTP ${_.status}`}catch(_){console.log(`
137
137
  \u274C Network error: ${_.message}
138
- `),process.exit(1)}if(!m){let _=!1;try{_=(await fetch(`${x}/api/invite/${encodeURIComponent(l)}`,{signal:AbortSignal.timeout(8e3)})).ok}catch{}_?(console.log(`
138
+ `),process.exit(1)}if(!m){let _=!1;try{_=(await fetch(`${x}/api/invite/${encodeURIComponent(c)}`,{signal:AbortSignal.timeout(8e3)})).ok}catch{}_?(console.log(`
139
139
  \u274C This old link type does not give access to the Brain.`),console.log(` Ask the owner for a new invitation: npx @cachly-dev/mcp-server@latest invite <your-email>
140
140
  `)):(console.log(`
141
141
  \u274C Could not accept the invitation: ${S}.`),console.log(` The token may be wrong, expired or already used. Ask for a new invitation.
@@ -146,7 +146,7 @@ Try it free: ${o}
146
146
  Cancelled.
147
147
  `),process.exit(1)),k=v[I-1]}f=k.id,y=k.name??k.id,console.log(`
148
148
  \u2705 Invitation accepted. Brain: \x1B[1m${y}\x1B[0m
149
- `)}i!==A&&ne(i);const w=process.cwd(),h=c(),a=[{label:".mcp.json (Claude Code project)",path:s(w,".mcp.json")},{label:".cursor/mcp.json",path:s(w,".cursor","mcp.json")},{label:"~/.codeium/windsurf/mcp_config.json (Windsurf)",path:Ae("windsurf",ge())},{label:"cline_mcp_settings.json (Cline)",path:Ae("cline",ge())},{label:".vscode/mcp.json (Copilot)",path:s(w,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:s(h,".claude","mcp.json"),global:!0}];let g=0;for(const{label:m,path:S,global:v}of a){const k=r(S);if(!(!v&&!o(k)&&!o(S)))try{await n(k,{recursive:!0});let _={};if(o(S))try{_=JSON.parse(await t(S,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(S,S+".bak")}catch{}}const R=_.mcpServers??{},I=R.cachly??{},$=I.env??{};$.CACHLY_BRAIN_INSTANCE_ID=f,i&&v&&!$.CACHLY_JWT&&($.CACHLY_JWT=i),x!==Qt&&($.CACHLY_API_URL=x),R.cachly={...I,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:$},_.mcpServers=R,await e(S,JSON.stringify(_,null,2),"utf-8"),console.log(` \u2705 ${m}`),g++}catch(_){_.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${m}: ${_.message}`)}}console.log(""),g===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${y}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
149
+ `)}i!==A&&ne(i);const w=process.cwd(),h=l(),a=[{label:".mcp.json (Claude Code project)",path:s(w,".mcp.json")},{label:".cursor/mcp.json",path:s(w,".cursor","mcp.json")},{label:"~/.codeium/windsurf/mcp_config.json (Windsurf)",path:Ae("windsurf",ge())},{label:"cline_mcp_settings.json (Cline)",path:Ae("cline",ge())},{label:".vscode/mcp.json (Copilot)",path:s(w,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:s(h,".claude","mcp.json"),global:!0}];let g=0;for(const{label:m,path:S,global:v}of a){const k=r(S);if(!(!v&&!o(k)&&!o(S)))try{await n(k,{recursive:!0});let _={};if(o(S))try{_=JSON.parse(await t(S,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(S,S+".bak")}catch{}}const R=_.mcpServers??{},I=R.cachly??{},$=I.env??{};$.CACHLY_BRAIN_INSTANCE_ID=f,i&&v&&!$.CACHLY_JWT&&($.CACHLY_JWT=i),x!==eo&&($.CACHLY_API_URL=x),R.cachly={...I,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:$},_.mcpServers=R,await e(S,JSON.stringify(_,null,2),"utf-8"),console.log(` \u2705 ${m}`),g++}catch(_){_.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${m}: ${_.message}`)}}console.log(""),g===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${y}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
150
150
  `),console.log(" \u{1F4DB} Add the badge to your README:"),console.log(` npx @cachly-dev/mcp-server@latest badge
151
151
  `)),process.exit(0)}if(process.argv[2]==="upgrade"){process.stdout.write(`
152
152
  \u23F3 Checking for updates...
@@ -154,26 +154,26 @@ Try it free: ${o}
154
154
  \u2705 Already on the latest version: \x1B[32mv${H}\x1B[0m
155
155
  `):(console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly update available\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Current : \x1B[31mv${H}\x1B[0m`),console.log(` Latest : \x1B[32mv${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(`
156
156
  \u274C Could not check for updates: ${e.message}
157
- `),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:o,runExternalBenchmark:s}=await import("./bench/external-corpus.js"),r=process.argv.includes("--json"),c=process.argv.slice(3).find(l=>!l.startsWith("--")),d=t(e(import.meta.url)),u=c?n(process.cwd(),c):n(d,"bench","external","sample-corpus.json");try{const l=await o(u),i=await s(l);r&&(console.log(JSON.stringify({corpus:l.name,lessons:i.corpusSize,queries:i.queryCount,cachly_p1:Math.round(i.cachly.precisionAt1*1e3)/10,flatfile_p1:Math.round(i.flatfile.precisionAt1*1e3)/10,cachly_mrr:Math.round(i.cachly.mrr*1e3)/10,flatfile_mrr:Math.round(i.flatfile.mrr*1e3)/10,p1_lift_vs_flatfile_pct:Math.round((i.cachly.precisionAt1-i.flatfile.precisionAt1)*1e3)/10,mrr_lift_vs_flatfile_pct:Math.round((i.cachly.mrr-i.flatfile.mrr)*1e3)/10},null,2)),process.exit(0));const p=((i.cachly.precisionAt1-i.flatfile.precisionAt1)*100).toFixed(1),f=((i.cachly.mrr-i.flatfile.mrr)*100).toFixed(1),y=((i.cachly.precisionAt1-i.baseline.precisionAt1)*100).toFixed(1),w=i.cachly.precisionAt1>=i.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",h=i.cachly.mrr>=i.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 : ${l.name??u}`),console.log(` Dataset: ${i.corpusSize} lessons \xB7 ${i.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${(i.flatfile.precisionAt1*100).toFixed(1)}%\x1B[0m (naive keyword overlap \u2014 no quality signal)`),console.log(` raw BM25 : \x1B[33m${(i.baseline.precisionAt1*100).toFixed(1)}%\x1B[0m (keyword ranking)`),console.log(` cachly : \x1B[1m\x1B[32m${(i.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${(i.flatfile.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` raw BM25 : \x1B[33m${(i.baseline.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` cachly : \x1B[1m\x1B[32m${(i.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 : ${w}${p}%\x1B[0m`),console.log(` MRR : ${h}${f}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${y}%\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 ${(i.cachly.precisionAt1*100).toFixed(1)}% (${w}${p}% vs flat-file memory, ${i.queryCount} queries)"\x1B[0m`),console.log(""),console.log(" Run on a custom corpus:"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench my-incidents.json\x1B[0m"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench --json # machine-readable\x1B[0m"),console.log(""),console.log(" \x1B[1m\u2192 Give your AI this recall quality on your own work (free, 1\u20135 min):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(" \x1B[90m Signs in, configures every editor, bootstraps from your git history.\x1B[0m"),console.log(` \x1B[90m Or create your Brain at: \x1B[36m${j("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(l){console.error(`
158
- \u274C bench failed: ${l.message}
157
+ `),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:o,runExternalBenchmark:s}=await import("./bench/external-corpus.js"),r=process.argv.includes("--json"),l=process.argv.slice(3).find(c=>!c.startsWith("--")),d=t(e(import.meta.url)),u=l?n(process.cwd(),l):n(d,"bench","external","sample-corpus.json");try{const c=await o(u),i=await s(c);r&&(console.log(JSON.stringify({corpus:c.name,lessons:i.corpusSize,queries:i.queryCount,cachly_p1:Math.round(i.cachly.precisionAt1*1e3)/10,flatfile_p1:Math.round(i.flatfile.precisionAt1*1e3)/10,cachly_mrr:Math.round(i.cachly.mrr*1e3)/10,flatfile_mrr:Math.round(i.flatfile.mrr*1e3)/10,p1_lift_vs_flatfile_pct:Math.round((i.cachly.precisionAt1-i.flatfile.precisionAt1)*1e3)/10,mrr_lift_vs_flatfile_pct:Math.round((i.cachly.mrr-i.flatfile.mrr)*1e3)/10},null,2)),process.exit(0));const p=((i.cachly.precisionAt1-i.flatfile.precisionAt1)*100).toFixed(1),f=((i.cachly.mrr-i.flatfile.mrr)*100).toFixed(1),y=((i.cachly.precisionAt1-i.baseline.precisionAt1)*100).toFixed(1),w=i.cachly.precisionAt1>=i.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",h=i.cachly.mrr>=i.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 : ${c.name??u}`),console.log(` Dataset: ${i.corpusSize} lessons \xB7 ${i.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${(i.flatfile.precisionAt1*100).toFixed(1)}%\x1B[0m (naive keyword overlap \u2014 no quality signal)`),console.log(` raw BM25 : \x1B[33m${(i.baseline.precisionAt1*100).toFixed(1)}%\x1B[0m (keyword ranking)`),console.log(` cachly : \x1B[1m\x1B[32m${(i.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${(i.flatfile.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` raw BM25 : \x1B[33m${(i.baseline.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` cachly : \x1B[1m\x1B[32m${(i.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 : ${w}${p}%\x1B[0m`),console.log(` MRR : ${h}${f}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${y}%\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 ${(i.cachly.precisionAt1*100).toFixed(1)}% (${w}${p}% vs flat-file memory, ${i.queryCount} queries)"\x1B[0m`),console.log(""),console.log(" Run on a custom corpus:"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench my-incidents.json\x1B[0m"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench --json # machine-readable\x1B[0m"),console.log(""),console.log(" \x1B[1m\u2192 Give your AI this recall quality on your own work (free, 1\u20135 min):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(" \x1B[90m Signs in, configures every editor, bootstraps from your git history.\x1B[0m"),console.log(` \x1B[90m Or create your Brain at: \x1B[36m${j("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(c){console.error(`
158
+ \u274C bench failed: ${c.message}
159
159
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{existsSync:e,readFileSync:t}=await import("node:fs"),{resolve:n,basename:o}=await import("node:path"),s=process.cwd();console.log(`
160
160
  \x1B[35m\u{1F9E0} cachly Brain \u2014 Live Demo\x1B[0m`),console.log(`\x1B[90mNo account needed. Reading your git history...\x1B[0m
161
161
  `),e(n(s,".git"))||(console.log("\u26A0\uFE0F No git repository found here."),console.log(` Run this command inside a project directory with git history.
162
162
  `),console.log(` Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo
163
- `),process.exit(0));let r="";try{r=St(s,["config","user.name"]).trim().split(" ")[0]??""}catch{}let c=o(s);try{const $=JSON.parse(t(n(s,"package.json"),"utf-8"));$.name&&(c=$.name.replace(/^@[^/]+\//,""))}catch{}let d="";try{d=St(s,["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.
163
+ `),process.exit(0));let r="";try{r=At(s,["config","user.name"]).trim().split(" ")[0]??""}catch{}let l=o(s);try{const $=JSON.parse(t(n(s,"package.json"),"utf-8"));$.name&&(l=$.name.replace(/^@[^/]+\//,""))}catch{}let d="";try{d=At(s,["log","HEAD","--pretty=format:%H|||%s|||%ad|||%an","--date=short","--no-merges","-n","200"],{timeoutMs:3e4})}catch{console.log(`\u26A0\uFE0F Could not read git log. Make sure you have commits.
164
164
  `),process.exit(0)}const u=d.trim().split(`
165
165
  `).filter(Boolean).map($=>{const[E,M,Be,re]=$.split("|||");return{sha:(E??"").trim().slice(0,8),subject:(M??"").trim(),date:(Be??"").trim(),author:(re??"").trim()}});u.length===0&&(console.log(`\u26A0\uFE0F No commits found.
166
- `),process.exit(0));const l=new Map,i=[],p=[],f=[],y=new Set;let w=0;for(const $ of u){const E=cr($.subject);l.set(E,(l.get(E)??0)+1),lr($.subject)&&w++,E==="fix"&&i.length<5&&i.push($.subject.slice(0,72)),E==="feat"&&p.length<5&&p.push($.subject.slice(0,72)),E==="security"&&f.length<3&&f.push($.subject.slice(0,72)),$.author&&y.add($.author)}const h=dr(u.map($=>$.subject)),a=`${u[u.length-1]?.date??"?"} \u2192 ${u[0]?.date??"?"}`,g=h>=501?"Oracle":h>=201?"Architect":h>=51?"Expert":h>=11?"Explorer":"Apprentice",S=`${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} ${S.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(u.length).padEnd(6)}\x1B[0m Date range: \x1B[90m${a.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(h).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(y.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${g.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(w).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 v=[...l.entries()].filter(([$])=>$!=="chore").sort(($,E)=>E[1]-$[1]),k=($,E)=>"\u2588".repeat(Math.round($/E*20)).padEnd(20),_=Math.max(...v.map(([,$])=>$),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[$,E]of v){const M={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[$]??"\u2022";console.log(`\u2502 ${M} \x1B[36m${$.padEnd(10)}\x1B[0m \x1B[35m${k(E,_)}\x1B[0m \x1B[33m${String(E).padStart(3)}\x1B[0m \u2502`)}if(f.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[31m\u{1F512} Security fixes your AI would know:\x1B[0m \u2502");for(const $ of f)console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(i.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 i.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(p.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 p.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 R=new URLSearchParams({repo:c,commits:String(u.length),lessons:String(h),level:g,authors:String(y.size),reverts:String(w)}),I=j(`/preview?${R.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=X(),t=U();(!e||!t)&&(console.log(`
166
+ `),process.exit(0));const c=new Map,i=[],p=[],f=[],y=new Set;let w=0;for(const $ of u){const E=dr($.subject);c.set(E,(c.get(E)??0)+1),ur($.subject)&&w++,E==="fix"&&i.length<5&&i.push($.subject.slice(0,72)),E==="feat"&&p.length<5&&p.push($.subject.slice(0,72)),E==="security"&&f.length<3&&f.push($.subject.slice(0,72)),$.author&&y.add($.author)}const h=pr(u.map($=>$.subject)),a=`${u[u.length-1]?.date??"?"} \u2192 ${u[0]?.date??"?"}`,g=h>=501?"Oracle":h>=201?"Architect":h>=51?"Expert":h>=11?"Explorer":"Apprentice",S=`${r?`Hey ${r} \u2014 `:""}here's what your AI would know about ${l}`;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} ${S.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(u.length).padEnd(6)}\x1B[0m Date range: \x1B[90m${a.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(h).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(y.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${g.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(w).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 v=[...c.entries()].filter(([$])=>$!=="chore").sort(($,E)=>E[1]-$[1]),k=($,E)=>"\u2588".repeat(Math.round($/E*20)).padEnd(20),_=Math.max(...v.map(([,$])=>$),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[$,E]of v){const M={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[$]??"\u2022";console.log(`\u2502 ${M} \x1B[36m${$.padEnd(10)}\x1B[0m \x1B[35m${k(E,_)}\x1B[0m \x1B[33m${String(E).padStart(3)}\x1B[0m \u2502`)}if(f.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[31m\u{1F512} Security fixes your AI would know:\x1B[0m \u2502");for(const $ of f)console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(i.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 i.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(p.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 p.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 R=new URLSearchParams({repo:l,commits:String(u.length),lessons:String(h),level:g,authors:String(y.size),reverts:String(w)}),I=j(`/preview?${R.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=X(),t=U();(!e||!t)&&(console.log(`
167
167
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
168
168
  `),process.exit(1)),process.stdout.write(`
169
169
  \u{1F9E0} Fetching your Brain stats...
170
- `);try{const n=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);const o=await n.json(),s=o.lesson_count??0,r=o.total_recall_count??0,c=Math.round(o.iq_boost_pct??0),d=r*1200,u=s===0?"Intern \u{1F331}":s<10?"Junior Dev \u{1F527}":s<30?"Mid Dev \u26A1":s<60?"Senior Dev \u{1F9E0}":s<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(s).padEnd(8)}\x1B[0m Brain level: \x1B[32m${u.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${("~"+(d/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 l=j("/","share"),i=`\u{1F9E0} My AI coding assistant now has persistent memory.
170
+ `);try{const n=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);const o=await n.json(),s=o.lesson_count??0,r=o.total_recall_count??0,l=Math.round(o.iq_boost_pct??0),d=r*1200,u=s===0?"Intern \u{1F331}":s<10?"Junior Dev \u{1F527}":s<30?"Mid Dev \u26A1":s<60?"Senior Dev \u{1F9E0}":s<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(s).padEnd(8)}\x1B[0m Brain level: \x1B[32m${u.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(r).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(l).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${("~"+(d/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 c=j("/","share"),i=`\u{1F9E0} My AI coding assistant now has persistent memory.
171
171
 
172
172
  ${s} lessons stored \xB7 ${r} recalls \xB7 ${u}
173
173
 
174
174
  Fix a bug once \u2192 AI remembers forever. Across Claude Code, Cursor, Windsurf, Copilot.
175
175
 
176
- ${l}
176
+ ${c}
177
177
 
178
178
  #AIMemory #ClaudeCode #Cursor #DeveloperTools`;console.log(" \x1B[1m\u{1F4CB} Share on Twitter/X (copy this):\x1B[0m"),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(i.split(`
179
179
  `).map(p=>` ${p}`).join(`
@@ -183,7 +183,7 @@ ${l}
183
183
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
184
184
  `),process.exit(1));const n=process.argv.indexOf("--title"),o=n!==-1?process.argv[n+1]??"My Brain Snapshot":"My Brain Snapshot",s=process.argv.includes("--public");process.stdout.write(`
185
185
  \u{1F9E0} Publishing Brain snapshot...
186
- `);try{const r=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let c=0,d=0;if(r.ok){const f=await r.json();c=f.lesson_count??0,d=f.total_recall_count??0}const u=await fetch(`${x}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:o,visibility:s?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!u.ok)throw new Error(`HTTP ${u.status}`);const i=(await u.json()).share_id??"unavailable",p=j(`/brain/share/${i}`,"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${o.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(c).padEnd(10)}\x1B[0m Recalls: \x1B[36m${String(d).padEnd(26)}\x1B[0m\u2502`),console.log(`\u2502 Visibility: \x1B[${s?"32":"33"}m${(s?"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${p.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="${i.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(` ${p}`),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="${i.slice(0,24)}...")`),console.log("")}catch(r){console.log(`
186
+ `);try{const r=await fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let l=0,d=0;if(r.ok){const f=await r.json();l=f.lesson_count??0,d=f.total_recall_count??0}const u=await fetch(`${x}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:o,visibility:s?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!u.ok)throw new Error(`HTTP ${u.status}`);const i=(await u.json()).share_id??"unavailable",p=j(`/brain/share/${i}`,"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${o.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(l).padEnd(10)}\x1B[0m Recalls: \x1B[36m${String(d).padEnd(26)}\x1B[0m\u2502`),console.log(`\u2502 Visibility: \x1B[${s?"32":"33"}m${(s?"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${p.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="${i.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(` ${p}`),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="${i.slice(0,24)}...")`),console.log("")}catch(r){console.log(`
187
187
  \u274C Could not publish Brain: ${r.message}
188
188
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="tool-specs"||process.argv[2]==="openapi"){const{renderToolSpecs:e}=await import("./toolspecs.js");let t="openapi";if(process.argv[2]!=="openapi"){const o=process.argv.find(s=>s.startsWith("--format="));if(o)t=o.slice(9);else{const s=process.argv.indexOf("--format");s!==-1&&(t=process.argv[s+1]??"openapi")}}const n=["openapi","openai","anthropic","langchain"];n.includes(t)||(process.stderr.write(`
189
189
  \u274C Unknown format "${t}". Use one of: ${n.join(", ")}
@@ -191,60 +191,60 @@ ${l}
191
191
  `),process.exit(1)),process.stdout.write(e(le,t,H)+`
192
192
  `,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=U();e||(console.log(`
193
193
  \u26A0\uFE0F No Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
194
- `),process.exit(1));const t=`${x}/api/v1/badge/${e}`,n=j("/","badge"),o=`[![cachly Brain](${t})](${n})`,s=`<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${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(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${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(" Badge URL (live, updates every hour):"),console.log(` \x1B[90m${t}\x1B[0m`),console.log(""),console.log(" \x1B[2mThe badge shows your current lesson count \u2014 no auth required,"),console.log(" safe to embed in public repos. Updates hourly.\x1B[0m"),console.log(""),process.exit(0)}const ye=Un(process.argv[2],process.stdin.isTTY===!0&&process.stdout.isTTY===!0);if(ye==="version"&&(process.stdout.write(`${H}
194
+ `),process.exit(1));const t=`${x}/api/v1/badge/${e}`,n=j("/","badge"),o=`[![cachly Brain](${t})](${n})`,s=`<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${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(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${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(" Badge URL (live, updates every hour):"),console.log(` \x1B[90m${t}\x1B[0m`),console.log(""),console.log(" \x1B[2mThe badge shows your current lesson count \u2014 no auth required,"),console.log(" safe to embed in public repos. Updates hourly.\x1B[0m"),console.log(""),process.exit(0)}const ye=Jn(process.argv[2],process.stdin.isTTY===!0&&process.stdout.isTTY===!0);if(ye==="version"&&(process.stdout.write(`${H}
195
195
  `,()=>process.exit(0)),await new Promise(()=>{})),ye==="unbekannt"&&console.error(`
196
- Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||ye==="hilfe"||ye==="unbekannt"){console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly \u2014 Persistent AI Memory for Developers\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Stop re-teaching your AI every morning."),console.log(" cachly gives it a permanent brain \u2014 pre-briefed every session."),console.log("");const e=(t,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 <email>","Share your Brain with a teammate (sends an email)"),e("join <token>","Accept an invitation to a shared Brain"),e("join --brain <id>","Connect a Brain you already have access to"),e("refer","Your referral link for new users"),e("share","Share your Brain stats"),e("publish","Publish an importable Brain snapshot"),e("badge","README badge for your Brain"),console.log(" \x1B[1mMore:\x1B[0m"),e("bench","Recall quality vs flat-file memory"),e("tool-specs | openapi","Tool definitions for other agent frameworks"),console.log(""),console.log(" \x1B[90mWorks with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 GitHub Copilot \xB7 Cline \xB7 Zed\x1B[0m"),console.log(` \x1B[90mGDPR \xB7 German servers \xB7 ${le.length} MCP tools\x1B[0m`),console.log(""),process.exit(ye==="unbekannt"?1:0)}const Cr={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:Xn,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:Qn,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:es,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function Tr(e,t,n){if(!t)return;const{datei:o,name:s,wie:r}=Cr[e];if(t.hooks==="skipped"){console.log(`\u26A0\uFE0F ${n}${o} ${t.grund??"is not valid JSON"} \u2014 left untouched, ${s} hooks not wired`);return}const c=t.hooks==="unchanged"?"\u2713 ":"\u2705 ",d=t.hooks==="written"?"Written":t.hooks==="merged"?"Merged":"Already wired";console.log(`${c}${n}${d}: ${o} (Ambient Recall for ${s} \u2014 ${r})`)}async function qe(e,t,n,o){const s=e==="codex"?"Codex":"Gemini CLI",r=await(e==="codex"?ds:us)(t,n).catch(()=>null);if(!r||r.status==="skipped"){const u=Sr(e,n);console.log(`\u26A0\uFE0F ${o}${r?`${r.datei} ${r.grund??"could not be read"} \u2014 left untouched.`:`${s} MCP entry could not be written.`} Register cachly yourself:`),u&&console.log(` ${o}${u.befehl}`);return}const c=r.status==="unchanged"?"\u2713 ":"\u2705 ",d=r.status==="written"?"Written":r.status==="updated"?"Updated":"Already configured";console.log(`${c}${o}${d}: ${r.datei} (MCP server cachly for ${s} \u2014 it asks once to trust this folder; until then the server stays off)`)}async function be(e,t,n,o){const s={cursor:Gn,copilot:qn,codex:Vn,gemini:Zn}[e];Tr(e,await s(t,n).catch(()=>null),o)}if(process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:n,readFile:o}=await import("node:fs/promises"),{resolve:s,dirname:r,relative:c}=await import("node:path"),d=process.argv.slice(3),u=v=>kt(d,v),l=Wn(d,["instance-id","api-key","editor","project-dir","api-url"]);l.length>0&&(console.error(`
197
- Missing value for ${l.map(v=>`--${v}`).join(", ")}. Nothing was written.
196
+ Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||ye==="hilfe"||ye==="unbekannt"){console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly \u2014 Persistent AI Memory for Developers\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Stop re-teaching your AI every morning."),console.log(" cachly gives it a permanent brain \u2014 pre-briefed every session."),console.log("");const e=(t,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 <email>","Share your Brain with a teammate (sends an email)"),e("join <token>","Accept an invitation to a shared Brain"),e("join --brain <id>","Connect a Brain you already have access to"),e("refer","Your referral link for new users"),e("share","Share your Brain stats"),e("publish","Publish an importable Brain snapshot"),e("badge","README badge for your Brain"),console.log(" \x1B[1mMore:\x1B[0m"),e("bench","Recall quality vs flat-file memory"),e("tool-specs | openapi","Tool definitions for other agent frameworks"),console.log(""),console.log(" \x1B[90mWorks with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 GitHub Copilot \xB7 Cline \xB7 Zed\x1B[0m"),console.log(` \x1B[90mGDPR \xB7 German servers \xB7 ${le.length} MCP tools\x1B[0m`),console.log(""),process.exit(ye==="unbekannt"?1:0)}const Ir={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:es,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:ts,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:os,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function Er(e,t,n){if(!t)return;const{datei:o,name:s,wie:r}=Ir[e];if(t.hooks==="skipped"){console.log(`\u26A0\uFE0F ${n}${o} ${t.grund??"is not valid JSON"} \u2014 left untouched, ${s} hooks not wired`);return}const l=t.hooks==="unchanged"?"\u2713 ":"\u2705 ",d=t.hooks==="written"?"Written":t.hooks==="merged"?"Merged":"Already wired";console.log(`${l}${n}${d}: ${o} (Ambient Recall for ${s} \u2014 ${r})`)}async function qe(e,t,n,o){const s=e==="codex"?"Codex":"Gemini CLI",r=await(e==="codex"?ps:ms)(t,n).catch(()=>null);if(!r||r.status==="skipped"){const u=Cr(e,n);console.log(`\u26A0\uFE0F ${o}${r?`${r.datei} ${r.grund??"could not be read"} \u2014 left untouched.`:`${s} MCP entry could not be written.`} Register cachly yourself:`),u&&console.log(` ${o}${u.befehl}`);return}const l=r.status==="unchanged"?"\u2713 ":"\u2705 ",d=r.status==="written"?"Written":r.status==="updated"?"Updated":"Already configured";console.log(`${l}${o}${d}: ${r.datei} (MCP server cachly for ${s} \u2014 it asks once to trust this folder; until then the server stays off)`)}async function be(e,t,n,o){const s={cursor:Vn,copilot:Zn,codex:Xn,gemini:Qn}[e];Er(e,await s(t,n).catch(()=>null),o)}if(process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:n,readFile:o}=await import("node:fs/promises"),{resolve:s,dirname:r,relative:l}=await import("node:path"),d=process.argv.slice(3),u=v=>St(d,v),c=Fn(d,["instance-id","api-key","editor","project-dir","api-url"]);c.length>0&&(console.error(`
197
+ Missing value for ${c.map(v=>`--${v}`).join(", ")}. Nothing was written.
198
198
  `),process.exit(1));let i=u("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,p=u("api-key")??process.env.CACHLY_JWT;const f=(u("editor")??"claude").toLowerCase(),y=s(u("project-dir")??"."),w=u("api-url");if(w&&(x=w.replace(/\/+$/,"")),!i||!p){const v=Te(),k=Ie();v&&k&&(p??=v,i??=k,p===v&&i===k&&console.log("\u2713 Reusing credentials from ~/.cachly/credentials.json (saved by a prior setup)"))}if(!i||!p)try{const{existsSync:v}=await import("node:fs"),k=process.env.HOME??process.env.USERPROFILE??"",_=k?s(k,".claude","mcp.json"):"";if(_&&v(_)){const I=JSON.parse(await o(_,"utf-8")).mcpServers?.cachly?.env??{};p??=I.CACHLY_JWT,i??=I.CACHLY_BRAIN_INSTANCE_ID,p&&i&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!i||!p)&&(console.error(`
199
199
  Usage: npx @cachly-dev/mcp-server@latest init --instance-id <uuid> --api-key <cky_live_...> [--editor claude|cursor|windsurf|copilot|continue|cline|zed|codex|gemini] [--all-editors] [--project-dir /path] [--api-url https://your-self-hosted-backend]
200
200
  `),console.error(`First time? Run the zero-config wizard (signs you in, auto-provisions): npx @cachly-dev/mcp-server@latest autopilot
201
201
  `),console.error(`Get your credentials from: ${j("/setup-ai","init")}
202
- `),process.exit(1));const h=Jn({instanceId:i,apiKey:p,editor:f},[...Object.keys(Se),"codex","gemini"]);if(h.length>0){console.error(`
202
+ `),process.exit(1));const h=Yn({instanceId:i,apiKey:p,editor:f},[...Object.keys(Se),"codex","gemini"]);if(h.length>0){console.error(`
203
203
  Nothing was written:`);for(const v of h)console.error(` - ${v}`);console.error(""),process.exit(1)}try{const v=await fetch(`${x}/api/v1/instances/${i}/memory`,{headers:{Authorization:`Bearer ${p}`},signal:AbortSignal.timeout(8e3)});(v.status===401||v.status===403||v.status===404)&&(console.error(`
204
204
  The server does not accept this key and instance (HTTP ${v.status}). Nothing was written.`),console.error(`Get your credentials from: ${j("/setup-ai","init")}
205
- `),process.exit(1))}catch{console.log("\u26A0\uFE0F Could not reach the server to check the key \u2014 writing the config anyway.")}const a=()=>{ne(p),Ie()||Ce(i,{apiKey:p})};if(f==="codex"||f==="gemini")a(),console.log(""),await qe(f,y,ee(p,i),"");else{const v=$t(f,y),k=v.anzeige,_=v.pfad;await n(r(_),{recursive:!0});const{existsSync:R}=await import("node:fs"),I=R(_),$=I?await o(_,"utf-8").catch(()=>""):"";a();const E=await to(_,p,i,v.format,{readFile:o,existsSync:R});E!==$?(await t(_,E,"utf-8"),console.log(`
205
+ `),process.exit(1))}catch{console.log("\u26A0\uFE0F Could not reach the server to check the key \u2014 writing the config anyway.")}const a=()=>{ne(p),Ie()||Ce(i,{apiKey:p})};if(f==="codex"||f==="gemini")a(),console.log(""),await qe(f,y,ee(p,i),"");else{const v=kt(f,y),k=v.anzeige,_=v.pfad;await n(r(_),{recursive:!0});const{existsSync:R}=await import("node:fs"),I=R(_),$=I?await o(_,"utf-8").catch(()=>""):"";a();const E=await oo(_,p,i,v.format,{readFile:o,existsSync:R});E!==$?(await t(_,E,"utf-8"),console.log(`
206
206
  \u2705 ${I?"Updated":"Written"}: ${k}`)):console.log(`
207
- \u2713 Already configured: ${k} (no change)`)}const g=d.includes("--all-editors"),m=await oo(y,i,void 0,g?void 0:f);for(const[v,k]of Object.entries(m))console.log(no(v.split(/[\\/]/).pop()??v,k));try{const v=await wt(y,i),k=c(y,s(On(y),"post-commit")).replace(/\\/g,"/");v==="written"?console.log(`\u2705 Written: ${k} (CLS hook)`):v==="upgraded"?console.log(`\u2705 Upgraded: ${k} (CLS hook \u2192 ${vt})`):v==="appended"?console.log(`\u2705 Appended: ${k} (CLS hook)`):v==="unchanged"&&console.log(`\u2713 CLS hook already current in ${k}`)}catch{}if(f==="claude")try{const v=await At(y,i);if(v.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${v.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const k=v.scripts==="written"?"\u2705 Written":v.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${Ct})`:"\u2713 Unchanged";console.log(`${k}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),v.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):v.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{}(f==="cursor"||f==="copilot"||f==="codex"||f==="gemini")&&await be(f,y,i,"");const S=((Date.now()-e)/1e3).toFixed(1);console.log(`
207
+ \u2713 Already configured: ${k} (no change)`)}const g=d.includes("--all-editors"),m=await no(y,i,void 0,g?void 0:f);for(const[v,k]of Object.entries(m))console.log(so(v.split(/[\\/]/).pop()??v,k));try{const v=await vt(y,i),k=l(y,s(Hn(y),"post-commit")).replace(/\\/g,"/");v==="written"?console.log(`\u2705 Written: ${k} (CLS hook)`):v==="upgraded"?console.log(`\u2705 Upgraded: ${k} (CLS hook \u2192 ${xt})`):v==="appended"?console.log(`\u2705 Appended: ${k} (CLS hook)`):v==="unchanged"&&console.log(`\u2713 CLS hook already current in ${k}`)}catch{}if(f==="claude")try{const v=await Ct(y,i);if(v.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${v.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const k=v.scripts==="written"?"\u2705 Written":v.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${Tt})`:"\u2713 Unchanged";console.log(`${k}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),v.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):v.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{}(f==="cursor"||f==="copilot"||f==="codex"||f==="gemini")&&await be(f,y,i,"");const S=((Date.now()-e)/1e3).toFixed(1);console.log(`
208
208
  \u{1F9E0} Cachly AI Brain configured for ${f==="claude"?"Claude Code":f}! (${S}s)`),console.log(f==="codex"||f==="gemini"?` Start ${f} 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(`
209
209
  \u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
210
210
  `),process.exit(0)}if(process.argv[2]==="status"){const e=X(),t=U();(!e||!t)&&(console.log(`
211
211
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
212
- `),process.exit(1));try{const[n,o]=await Promise.all([fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${x}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)})]);if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const s=await n.json(),r=o.ok?await o.json():null,c=s.lesson_count??0,d=s.total_recall_count??0,u=Math.round(s.iq_boost_pct??0),l=s.team_authors??[],i=r?.referral_count??0,p=r?.url??"",f=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}",y=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 ${y} \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${f.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Recalls : \x1B[36m${String(d).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(u).padEnd(3)}%\x1B[0m \u2502`),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");const w=l.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(l.length).padEnd(2)} developer${l.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-w.length))} \u2502`),console.log(`\u2502 ${w.slice(0,56).padEnd(56)} \u2502`)}if(p){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 w=`${p.slice(0,44)}${p.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Referral link\x1B[0m \xB7 ${i>0?`\x1B[32m${i} joined\x1B[0m`:"share to invite new users"}${" ".repeat(Math.max(0,35-String(i).length))} \u2502`),console.log(`\u2502 \x1B[2m${w.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(`
212
+ `),process.exit(1));try{const[n,o]=await Promise.all([fetch(`${x}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${x}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)})]);if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const s=await n.json(),r=o.ok?await o.json():null,l=s.lesson_count??0,d=s.total_recall_count??0,u=Math.round(s.iq_boost_pct??0),c=s.team_authors??[],i=r?.referral_count??0,p=r?.url??"",f=l===0?"Intern \u{1F331}":l<10?"Junior Dev \u{1F527}":l<30?"Mid Dev \u26A1":l<60?"Senior Dev \u{1F9E0}":l<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",y=l>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 ${y} \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(l).padEnd(8)}\x1B[0m Level : \x1B[32m${f.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Recalls : \x1B[36m${String(d).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(u).padEnd(3)}%\x1B[0m \u2502`),c.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 w=c.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(c.length).padEnd(2)} developer${c.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-w.length))} \u2502`),console.log(`\u2502 ${w.slice(0,56).padEnd(56)} \u2502`)}if(p){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 w=`${p.slice(0,44)}${p.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Referral link\x1B[0m \xB7 ${i>0?`\x1B[32m${i} joined\x1B[0m`:"share to invite new users"}${" ".repeat(Math.max(0,35-String(i).length))} \u2502`),console.log(`\u2502 \x1B[2m${w.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(""),l===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(`
213
213
  \u274C Could not fetch status: ${n.message}
214
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="health"){const{existsSync:e}=await import("node:fs"),{readFile:t}=await import("node:fs/promises"),{resolve:n}=await import("node:path"),o=process.cwd();let s=0,r=0;const c=h=>{console.log(` \u2705 ${h}`),s++},d=h=>{console.log(` \u26A0\uFE0F ${h}`)},u=h=>{console.log(` \u274C ${h}`),r++};console.log(`
214
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="health"){const{existsSync:e}=await import("node:fs"),{readFile:t}=await import("node:fs/promises"),{resolve:n}=await import("node:path"),o=process.cwd();let s=0,r=0;const l=h=>{console.log(` \u2705 ${h}`),s++},d=h=>{console.log(` \u26A0\uFE0F ${h}`)},u=h=>{console.log(` \u274C ${h}`),r++};console.log(`
215
215
  \u{1F9E0} cachly health check
216
- `),console.log("\u{1F511} Auth token");const l=X();if(!l)u("No cachly key found (environment or ~/.cachly/credentials.json) \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(l.startsWith("cky_"))c("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const h=l.split(".");if(h.length!==3)throw new Error("not a JWT");const a=JSON.parse(Buffer.from(h[1],"base64url").toString("utf-8")),g=a.exp?a.exp*1e3:null,m=g?Math.floor((g-Date.now())/6e4):null;g&&g<Date.now()?u(`JWT expired ${Math.abs(m)} minute(s) ago \u2014 get a new one: ${j("/setup-ai","health")}`):m!==null&&m<30?d(`JWT expires in ${m} minute(s) \u2014 refresh soon at ${j("/setup-ai","health")}`):c(`JWT valid${m!==null?` (expires in ${Math.floor(m/60)}h ${m%60}m)`:""}`)}catch{u("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
217
- \u{1F310} Brain API`);const i=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const h=await fetch(`${i}/health`,{signal:AbortSignal.timeout(5e3)});if(h.ok){const a=await h.json();c(`${i} reachable (status: ${a.status??"ok"})`)}else h.status===401||h.status===403?c(`${i} reachable (auth required \u2014 expected)`):u(`${i}/health returned HTTP ${h.status}`)}catch(h){u(`${i} unreachable \u2014 ${h.message}`)}console.log(`
218
- \u{1F9E0} Brain instance`);const p=U();if(!p)d("No Brain instance found (environment or ~/.cachly/credentials.json) \u2014 will auto-resolve on first tool call");else if(l)try{const h=await fetch(`${i}/api/v1/instances/${p}`,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(h.ok){const a=await h.json();if(a.status==="running")if(c(`Instance "${a.name}" (${p.slice(0,8)}\u2026) is running`),console.log(`
219
- \u{1F50C} Redis connectivity`),a.host&&a.port)try{let g,m;try{const _=await fetch(`${i}/api/v1/instances/${p}/connection`,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(_.ok){const R=await _.json();g=R.password,m=R}}catch{}const S=Ot({host:a.host,port:a.port,tls_enabled:a.tls_enabled},m),v=new at({host:S.host,port:S.port,password:g,...S.tls?{tls:S.tls}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await v.connect();const k=await v.ping();v.disconnect(),k==="PONG"?c(`Redis PING \u2192 PONG (${S.host}:${S.port}, ${S.art==="klartext"?"unencrypted":"TLS"})`):d(`Redis responded but not PONG: ${k}`)}catch(g){u(`Redis unreachable \u2014 ${g.message}`)}else d("Instance has no host/port yet");else d(`Instance "${a.name}" status: ${a.status}`)}else u(`Instance ${p.slice(0,8)}\u2026 not found (HTTP ${h.status})`)}catch(h){u(`Could not check instance \u2014 ${h.message}`)}console.log(`
220
- \u{1F6E0} Editor configs (project dir)`);const f=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:Ae("windsurf",ge())},{editor:"Cline",path:Ae("cline",ge())},{editor:"Copilot",path:".vscode/mcp.json"},{editor:"Zed",path:".zed/settings.json"},{editor:"Continue.dev",path:".continue/config.json"},{editor:"Codex",path:".codex/config.toml"},{editor:"Gemini CLI",path:".gemini/settings.json"}];let y=0;for(const{editor:h,path:a}of f){const g=n(o,a);if(e(g))try{const m=await t(g,"utf-8");m.includes("@cachly-dev/mcp-server")||m.includes("cachly")?(c(`${h}: ${a}`),y++):d(`${h}: ${a} exists but cachly not found inside`)}catch{d(`${h}: ${a} exists but could not read`)}}y===0&&u("No editor MCP configs found in this folder \u2014 run: npx @cachly-dev/mcp-server@latest init (add --editor cursor|copilot|codex|gemini if needed)"),console.log(`
221
- \u{1FA9D} Git hook (ambient learning)`);const w=n(o,".git","hooks","post-commit");if(!e(n(o,".git")))d("Not in a git repository \u2014 skip");else if(e(w))try{(await t(w,"utf-8")).includes("cachly")?c(".git/hooks/post-commit (cachly CLS hook present)"):d(".git/hooks/post-commit exists but cachly hook not found \u2014 run setup to add it")}catch{d(".git/hooks/post-commit exists but could not read")}else d(".git/hooks/post-commit not found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");console.log(`
222
- \u{1F9EC} Embedding provider (semantic search)`);{const h=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],a=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase();if(a&&a!=="cachly"){const g=h.find(([,m])=>m===a)?.[0];g&&process.env[g]?c(`BYOK: ${a} (key present in ${g})`):d(`CACHLY_EMBED_PROVIDER=${a} but its key env var is not set \u2014 semantic search will fail`)}else{gt==="ollama"?c("Local Ollama (OLLAMA_BASE_URL) \u2014 text stays on your machine"):gt==="cachly"?c("Server-side embeddings (cachly, EU) \u2014 no key needed, uses your JWT"):d("No embedding provider active \u2014 sign in (CACHLY_JWT) for EU-hosted embeddings; search runs on words until then");for(const[g,m]of h)m!=="ollama"&&process.env[g]&&c(`${g} is set but not used \u2014 ${m} runs only if you name it with CACHLY_EMBED_PROVIDER=${m}`)}}console.log(`
216
+ `),console.log("\u{1F511} Auth token");const c=X();if(!c)u("No cachly key found (environment or ~/.cachly/credentials.json) \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(c.startsWith("cky_"))l("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const h=c.split(".");if(h.length!==3)throw new Error("not a JWT");const a=JSON.parse(Buffer.from(h[1],"base64url").toString("utf-8")),g=a.exp?a.exp*1e3:null,m=g?Math.floor((g-Date.now())/6e4):null;g&&g<Date.now()?u(`JWT expired ${Math.abs(m)} minute(s) ago \u2014 get a new one: ${j("/setup-ai","health")}`):m!==null&&m<30?d(`JWT expires in ${m} minute(s) \u2014 refresh soon at ${j("/setup-ai","health")}`):l(`JWT valid${m!==null?` (expires in ${Math.floor(m/60)}h ${m%60}m)`:""}`)}catch{u("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
217
+ \u{1F310} Brain API`);const i=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const h=await fetch(`${i}/health`,{signal:AbortSignal.timeout(5e3)});if(h.ok){const a=await h.json();l(`${i} reachable (status: ${a.status??"ok"})`)}else h.status===401||h.status===403?l(`${i} reachable (auth required \u2014 expected)`):u(`${i}/health returned HTTP ${h.status}`)}catch(h){u(`${i} unreachable \u2014 ${h.message}`)}console.log(`
218
+ \u{1F9E0} Brain instance`);const p=U();if(!p)d("No Brain instance found (environment or ~/.cachly/credentials.json) \u2014 will auto-resolve on first tool call");else if(c)try{const h=await fetch(`${i}/api/v1/instances/${p}`,{headers:{Authorization:`Bearer ${c}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(h.ok){const a=await h.json();if(a.status==="running")if(l(`Instance "${a.name}" (${p.slice(0,8)}\u2026) is running`),console.log(`
219
+ \u{1F50C} Redis connectivity`),a.host&&a.port)try{let g,m;try{const _=await fetch(`${i}/api/v1/instances/${p}/connection`,{headers:{Authorization:`Bearer ${c}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(_.ok){const R=await _.json();g=R.password,m=R}}catch{}const S=Lt({host:a.host,port:a.port,tls_enabled:a.tls_enabled},m),v=new at({host:S.host,port:S.port,password:g,...S.tls?{tls:S.tls}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await v.connect();const k=await v.ping();v.disconnect(),k==="PONG"?l(`Redis PING \u2192 PONG (${S.host}:${S.port}, ${S.art==="klartext"?"unencrypted":"TLS"})`):d(`Redis responded but not PONG: ${k}`)}catch(g){u(`Redis unreachable \u2014 ${g.message}`)}else d("Instance has no host/port yet");else d(`Instance "${a.name}" status: ${a.status}`)}else u(`Instance ${p.slice(0,8)}\u2026 not found (HTTP ${h.status})`)}catch(h){u(`Could not check instance \u2014 ${h.message}`)}console.log(`
220
+ \u{1F6E0} Editor configs (project dir)`);const f=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:Ae("windsurf",ge())},{editor:"Cline",path:Ae("cline",ge())},{editor:"Copilot",path:".vscode/mcp.json"},{editor:"Zed",path:".zed/settings.json"},{editor:"Continue.dev",path:".continue/config.json"},{editor:"Codex",path:".codex/config.toml"},{editor:"Gemini CLI",path:".gemini/settings.json"}];let y=0;for(const{editor:h,path:a}of f){const g=n(o,a);if(e(g))try{const m=await t(g,"utf-8");m.includes("@cachly-dev/mcp-server")||m.includes("cachly")?(l(`${h}: ${a}`),y++):d(`${h}: ${a} exists but cachly not found inside`)}catch{d(`${h}: ${a} exists but could not read`)}}y===0&&u("No editor MCP configs found in this folder \u2014 run: npx @cachly-dev/mcp-server@latest init (add --editor cursor|copilot|codex|gemini if needed)"),console.log(`
221
+ \u{1FA9D} Git hook (ambient learning)`);const w=n(o,".git","hooks","post-commit");if(!e(n(o,".git")))d("Not in a git repository \u2014 skip");else if(e(w))try{(await t(w,"utf-8")).includes("cachly")?l(".git/hooks/post-commit (cachly CLS hook present)"):d(".git/hooks/post-commit exists but cachly hook not found \u2014 run setup to add it")}catch{d(".git/hooks/post-commit exists but could not read")}else d(".git/hooks/post-commit not found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");console.log(`
222
+ \u{1F9EC} Embedding provider (semantic search)`);{const h=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],a=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase();if(a&&a!=="cachly"){const g=h.find(([,m])=>m===a)?.[0];g&&process.env[g]?l(`BYOK: ${a} (key present in ${g})`):d(`CACHLY_EMBED_PROVIDER=${a} but its key env var is not set \u2014 semantic search will fail`)}else{gt==="ollama"?l("Local Ollama (OLLAMA_BASE_URL) \u2014 text stays on your machine"):gt==="cachly"?l("Server-side embeddings (cachly, EU) \u2014 no key needed, uses your JWT"):d("No embedding provider active \u2014 sign in (CACHLY_JWT) for EU-hosted embeddings; search runs on words until then");for(const[g,m]of h)m!=="ollama"&&process.env[g]&&l(`${g} is set but not used \u2014 ${m} runs only if you name it with CACHLY_EMBED_PROVIDER=${m}`)}}console.log(`
223
223
  ${"\u2500".repeat(40)}`),r===0?console.log(`\u2705 All checks passed (${s} ok)
224
224
  `):(console.log(`\u274C ${r} check(s) failed, ${s} passed
225
225
  `),console.log(`\u{1F4A1} Fix issues with: npx @cachly-dev/mcp-server@latest autopilot
226
- `),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:o}=await import("node:path"),{homedir:s}=await import("node:os"),r=a=>{const g=process.argv.indexOf(`--${a}`);return g!==-1?process.argv[g+1]:void 0};x=(r("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const c=(r("auth-url")??Et).replace(/\/+$/,"");console.log(`
226
+ `),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:o}=await import("node:path"),{homedir:s}=await import("node:os"),r=a=>{const g=process.argv.indexOf(`--${a}`);return g!==-1?process.argv[g+1]:void 0};x=(r("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const l=(r("auth-url")??Rt).replace(/\/+$/,"");console.log(`
227
227
  \u{1F9E0} cachly \u2014 keep your test Brain in your own account
228
- `),(x!=="https://api.cachly.dev"||c!==Et)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${x}, sign-in ${c}
229
- `);const d=gs({argument:r("key"),credentials:Te()});d||(console.log("No test key (cky_trial_\u2026) was found in ~/.cachly/credentials.json."),console.log("If you already use your own cachly account, there is nothing to claim."),console.log(`Otherwise pass the key: npx @cachly-dev/mcp-server@latest claim --key cky_trial_\u2026
230
- `),process.exit(1));const u=d.schluessel,l={argument:"--key",credentials:"~/.cachly/credentials.json"}[d.quelle];console.log(`Test key: ${u.slice(0,14)}\u2026 (from ${l})
228
+ `),(x!=="https://api.cachly.dev"||l!==Rt)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${x}, sign-in ${l}
229
+ `);const d=ys({argument:r("key"),credentials:Te()});d||(console.log("No test key (cky_trial_\u2026) was found in ~/.cachly/credentials.json."),console.log("If you already use your own cachly account, there is nothing to claim."),console.log(`Otherwise pass the key: npx @cachly-dev/mcp-server@latest claim --key cky_trial_\u2026
230
+ `),process.exit(1));const u=d.schluessel,c={argument:"--key",credentials:"~/.cachly/credentials.json"}[d.quelle];console.log(`Test key: ${u.slice(0,14)}\u2026 (from ${c})
231
231
  `);let i="";try{console.log(`Step 1: Sign in to your cachly account
232
- `);const a=await hs(fetch,c);console.log(` Code: \x1B[1;33m${a.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${a.adresse}
232
+ `);const a=await bs(fetch,l);console.log(` Code: \x1B[1;33m${a.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${a.adresse}
233
233
  `),ce(a.adresse,(g,m)=>{g||console.log(`
234
- \u2139\uFE0F No browser could be opened here (${m??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),i=await ys(fetch,a,{basis:c,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
234
+ \u2139\uFE0F No browser could be opened here (${m??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),i=await ws(fetch,a,{basis:l,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
235
235
  `)}catch(a){console.error(`
236
236
 
237
237
  ${a.message}. Nothing was changed.
238
- `),process.exit(1)}process.stdout.write("Step 2: Moving the test Brain into your account (it restarts once, up to a minute)\u2026");let p;try{p=await bs(fetch,x,i,u,"mcp",`cachly-mcp/${H}`),console.log(` \x1B[32m\u2713\x1B[0m
238
+ `),process.exit(1)}process.stdout.write("Step 2: Moving the test Brain into your account (it restarts once, up to a minute)\u2026");let p;try{p=await vs(fetch,x,i,u,"mcp",`cachly-mcp/${H}`),console.log(` \x1B[32m\u2713\x1B[0m
239
239
  `)}catch(a){console.error(`
240
240
 
241
- ${xs(a)}
242
- `),process.exit(1)}A=p.apiKey,ne(p.apiKey),Ce(p.instanceId,{apiKey:p.apiKey}),await pe(p.apiKey),await me(p.instanceId);const f=s(),y=new Set([...Object.values(Se).map(a=>o(process.cwd(),a)),o(f,".claude.json"),o(f,".claude","mcp.json"),o(f,".cursor","mcp.json"),o(f,".codeium","windsurf","mcp_config.json")]);let w=0;for(const a of y)if(n(a))try{const g=_s(await e(a,"utf-8"),u,p.apiKey);g.ersetzt&&(await t(a,g.text,"utf-8"),w++)}catch{}const h=await ws(fetch,x,p.apiKey,p.instanceId);console.log(vs(p,h)),console.log(`
241
+ ${$s(a)}
242
+ `),process.exit(1)}A=p.apiKey,ne(p.apiKey),Ce(p.instanceId,{apiKey:p.apiKey}),await pe(p.apiKey),await me(p.instanceId);const f=s(),y=new Set([...Object.values(Se).map(a=>o(process.cwd(),a)),o(f,".claude.json"),o(f,".claude","mcp.json"),o(f,".cursor","mcp.json"),o(f,".codeium","windsurf","mcp_config.json")]);let w=0;for(const a of y)if(n(a))try{const g=ks(await e(a,"utf-8"),u,p.apiKey);g.ersetzt&&(await t(a,g.text,"utf-8"),w++)}catch{}const h=await xs(fetch,x,p.apiKey,p.instanceId);console.log(_s(p,h)),console.log(`
243
243
  New key stored in ~/.cachly/credentials.json${w?` and in ${w} 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.
244
- `),process.exit(0)}const Ne=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||Ne){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s,dirname:r}=await import("node:path"),{createInterface:c}=await import("node:readline"),d=Date.now(),u=Ne?"autopilot":"setup";Bn();const l=process.argv.indexOf("--api-url");l!==-1&&process.argv[l+1]&&(x=process.argv[l+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${x}
244
+ `),process.exit(0)}const Ne=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||Ne){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s,dirname:r}=await import("node:path"),{createInterface:l}=await import("node:readline"),d=Date.now(),u=Ne?"autopilot":"setup";Ln();const c=process.argv.indexOf("--api-url");c!==-1&&process.argv[c+1]&&(x=process.argv[c+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${x}
245
245
  `)),C("setup_started");const i=process.stdin.isTTY===!0,p=Ne||process.argv.includes("--yes")||process.argv.includes("-y")||!i;Ne?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
246
246
  `):!i&&!process.argv.includes("--yes")&&!process.argv.includes("-y")&&console.log(`\u2139\uFE0F Non-interactive terminal detected \u2014 running in automatic mode (no prompts).
247
- `);const f=c({input:process.stdin,output:process.stdout}),y=(b,T="")=>p?(console.log(`${b}${T}`),Promise.resolve(T)):new Promise(N=>f.question(b,z=>N(z.trim()||T)));console.log(`
247
+ `);const f=l({input:process.stdin,output:process.stdout}),y=(b,T="")=>p?(console.log(`${b}${T}`),Promise.resolve(T)):new Promise(N=>f.question(b,z=>N(z.trim()||T)));console.log(`
248
248
  \u{1F9E0} cachly AI Brain \u2014 Setup`),console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
249
249
  `);let w=process.env.CACHLY_JWT??"";if(w)console.log(`\u2713 Using token from CACHLY_JWT env var
250
250
  `);else{console.log(`Step 1: Sign in to cachly (free, no credit card)
@@ -275,19 +275,19 @@ Failed to fetch instances: ${T}`),T.includes("401")&&(console.error(`Token rejec
275
275
  Could not create an instance automatically. Opening ${j("/instances",u)} \u2026
276
276
  `),ce(j("/instances",u)),f.close(),process.exit(1))}const a=h[0];h.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${a.name}`),console.log(` (Run with --instance-id <id> to use a different one)
277
277
  `)),console.log(`\u2713 Instance: ${a.name} (${a.id.slice(0,8)}\u2026)
278
- `),C("setup_instance_ready",{instance_id:a.id});const g=process.cwd(),m=[],{homedir:S}=await import("node:os"),v=S();m.push("claude"),o(s(g,".cursor"))&&m.push("cursor");const k=ge();(o(s(g,".windsurf"))||_t("windsurf",k,o))&&m.push("windsurf"),o(s(g,".vscode"))&&m.push("copilot"),o(s(g,".continue"))&&m.push("continue"),_t("cline",k,o)&&m.push("cline");const _=process.platform==="darwin"?s(v,"Library/Application Support/Zed"):s(v,".config/zed");o(_)&&m.push("zed");const R=b=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[b]??b,I=m;console.log(`\u{1F527} Configuring for: ${I.map(R).join(", ")}
279
- `);const{existsSync:$}=await import("node:fs"),E=[];let M=0;ne(w),Ce(a.id,{apiKey:w});for(const b of I){const T=$t(b,g),N=T.anzeige,z=T.pfad;try{await t(r(z),{recursive:!0});const F=$(z),G=await to(z,w,a.id,T.format,{readFile:n,existsSync:$});await e(z,G,"utf-8"),console.log(`\u2705 ${F?"Updated":"Written"}: ${N}`),M++}catch(F){const G=F.message;console.log(`\u26A0\uFE0F Could not write ${N}: ${G}`),console.log(" Fix permissions or run with sudo, then re-run setup."),E.push({file:N,reason:G})}}const Be=await oo(g,a.id);for(const[b,T]of Object.entries(Be)){const{relative:N}=await import("node:path");console.log(no(N(g,b)||b,T))}A=w;let re=0;if(o(s(g,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const b=await J("brain_from_git",{instance_id:a.id,repo_path:g,limit:100});if(b.startsWith("\u274C"))console.log(` (skipped: ${bt(b.replace(/^❌\s*/,"")).split(`
280
- `)[0].slice(0,160)})`);else{const T=b.match(/Ingested: \*\*(\d+)\*\*/);re=T?parseInt(T[1],10):0,console.log(` \u2713 ${re} lesson${re===1?"":"s"} extracted from git history`);const N=jn(b);N&&(console.log(""),console.log(bt(N)))}}catch(b){console.log(` (skipped: ${b.message.slice(0,80)})`)}}if(re===0){process.stdout.write("\u{1F331} Seeding 16 universal engineering lessons (first recall works instantly)...");try{await J("brain_seed_starter",{instance_id:a.id}),console.log(" \u2713");try{const b=await J("smart_recall",{instance_id:a.id,query:"docker build slow"}),T=Nn(b);T&&(console.log(""),console.log(Pn(T.topic,T.what)))}catch{}}catch(b){console.log(` (skipped: ${b.message.slice(0,60)})`)}}try{const b=await fetch(`${x}/api/v1/instances/${a.id}/memory`,{headers:{Authorization:`Bearer ${w}`},signal:AbortSignal.timeout(6e3)});if(b.ok){const N=(await b.json()).lesson_count??0;console.log(N===0?`
278
+ `),C("setup_instance_ready",{instance_id:a.id});const g=process.cwd(),m=[],{homedir:S}=await import("node:os"),v=S();m.push("claude"),o(s(g,".cursor"))&&m.push("cursor");const k=ge();(o(s(g,".windsurf"))||$t("windsurf",k,o))&&m.push("windsurf"),o(s(g,".vscode"))&&m.push("copilot"),o(s(g,".continue"))&&m.push("continue"),$t("cline",k,o)&&m.push("cline");const _=process.platform==="darwin"?s(v,"Library/Application Support/Zed"):s(v,".config/zed");o(_)&&m.push("zed");const R=b=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[b]??b,I=m;console.log(`\u{1F527} Configuring for: ${I.map(R).join(", ")}
279
+ `);const{existsSync:$}=await import("node:fs"),E=[];let M=0;ne(w),Ce(a.id,{apiKey:w});for(const b of I){const T=kt(b,g),N=T.anzeige,z=T.pfad;try{await t(r(z),{recursive:!0});const F=$(z),G=await oo(z,w,a.id,T.format,{readFile:n,existsSync:$});await e(z,G,"utf-8"),console.log(`\u2705 ${F?"Updated":"Written"}: ${N}`),M++}catch(F){const G=F.message;console.log(`\u26A0\uFE0F Could not write ${N}: ${G}`),console.log(" Fix permissions or run with sudo, then re-run setup."),E.push({file:N,reason:G})}}const Be=await no(g,a.id);for(const[b,T]of Object.entries(Be)){const{relative:N}=await import("node:path");console.log(so(N(g,b)||b,T))}A=w;let re=0;if(o(s(g,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const b=await J("brain_from_git",{instance_id:a.id,repo_path:g,limit:100});if(b.startsWith("\u274C"))console.log(` (skipped: ${wt(b.replace(/^❌\s*/,"")).split(`
280
+ `)[0].slice(0,160)})`);else{const T=b.match(/Ingested: \*\*(\d+)\*\*/);re=T?parseInt(T[1],10):0,console.log(` \u2713 ${re} lesson${re===1?"":"s"} extracted from git history`);const N=Pn(b);N&&(console.log(""),console.log(wt(N)))}}catch(b){console.log(` (skipped: ${b.message.slice(0,80)})`)}}if(re===0){process.stdout.write("\u{1F331} Seeding 16 universal engineering lessons (first recall works instantly)...");try{await J("brain_seed_starter",{instance_id:a.id}),console.log(" \u2713");try{const b=await J("smart_recall",{instance_id:a.id,query:"docker build slow"}),T=Bn(b);T&&(console.log(""),console.log(On(T.topic,T.what)))}catch{}}catch(b){console.log(` (skipped: ${b.message.slice(0,60)})`)}}try{const b=await fetch(`${x}/api/v1/instances/${a.id}/memory`,{headers:{Authorization:`Bearer ${w}`},signal:AbortSignal.timeout(6e3)});if(b.ok){const N=(await b.json()).lesson_count??0;console.log(N===0?`
281
281
  \u{1F9E0} Your Brain is empty. It learns from your fixes and commits from now on.`:`
282
282
  \u{1F9E0} Your Brain now holds ${N} lesson${N===1?"":"s"}.`)}}catch{}if(!p)try{if(console.log(`
283
283
  \u{1F451} Governance (optional \u2014 role model: admin \xB7 reviewer \xB7 contributor \xB7 viewer)`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),(await y(" Set yourself as the first admin? (y/N): ","N")).toLowerCase()==="y"){const T=await y(' Your handle (e.g. "alice"): ');T.trim()&&await J("team_assign_role",{instance_id:a.id,handle:T.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${T.trim()} is now admin. Invite teammates:
284
284
  `),console.log(` team_assign_role(instance_id="${a.id}", handle="<teammate>", role="contributor", assigned_by="${T.trim()}")
285
285
  `))}else console.log(` Skipped \u2014 run team_assign_role at any time.
286
286
  `)}catch{}if(!p){const b=await y(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(b&&b.includes("@"))try{await fetch(`${x}/api/newsletter/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:b.trim().toLowerCase(),source:"mcp-setup"}),signal:AbortSignal.timeout(5e3)}),console.log(` \u2705 Subscribed \u2014 you'll only hear from us when it matters.
287
- `)}catch{}}try{const b=await wt(process.cwd(),a.id);b==="written"?console.log(`
287
+ `)}catch{}}try{const b=await vt(process.cwd(),a.id);b==="written"?console.log(`
288
288
  \u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):b==="upgraded"?console.log(`
289
- \u2705 CLS git hook upgraded to ${vt}.`):b==="appended"&&console.log(`
290
- \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(I.includes("claude"))try{const b=await At(process.cwd(),a.id);if(b.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${b.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const T=b.scripts==="written"?"\u2705 Written":b.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${Ct})`:"\u2713 Unchanged";console.log(`${T}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),b.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):b.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 be("cursor",process.cwd(),a.id," "),I.includes("copilot")&&await be("copilot",process.cwd(),a.id," "),(o(s(v,".codex"))||o(s(g,".codex")))&&(await be("codex",process.cwd(),a.id," "),await qe("codex",process.cwd(),ee("",a.id)," ")),(o(s(v,".gemini"))||o(s(g,".gemini")))&&(await be("gemini",process.cwd(),a.id," "),await qe("gemini",process.cwd(),ee("",a.id)," ")),A=w;const Ve=Math.round((Date.now()-d)/1e3);if(E.length>0&&C("setup_config_write_failed",{instance_id:a.id,failed:E.length,succeeded:M}),C("setup_completed",{instance_id:a.id,elapsed_s:Ve,config_failures:E.length}),E.length>0&&M===0){console.log(`
289
+ \u2705 CLS git hook upgraded to ${xt}.`):b==="appended"&&console.log(`
290
+ \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(I.includes("claude"))try{const b=await Ct(process.cwd(),a.id);if(b.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${b.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const T=b.scripts==="written"?"\u2705 Written":b.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${Tt})`:"\u2713 Unchanged";console.log(`${T}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),b.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):b.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 be("cursor",process.cwd(),a.id," "),I.includes("copilot")&&await be("copilot",process.cwd(),a.id," "),(o(s(v,".codex"))||o(s(g,".codex")))&&(await be("codex",process.cwd(),a.id," "),await qe("codex",process.cwd(),ee("",a.id)," ")),(o(s(v,".gemini"))||o(s(g,".gemini")))&&(await be("gemini",process.cwd(),a.id," "),await qe("gemini",process.cwd(),ee("",a.id)," ")),A=w;const Ve=Math.round((Date.now()-d)/1e3);if(E.length>0&&C("setup_config_write_failed",{instance_id:a.id,failed:E.length,succeeded:M}),C("setup_completed",{instance_id:a.id,elapsed_s:Ve,config_failures:E.length}),E.length>0&&M===0){console.log(`
291
291
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557`),console.log("\u2551 \u26A0\uFE0F Setup incomplete \u2014 no editor config was written \u2551"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(`
292
292
  Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const b of E)console.log(` \u2022 ${b.file} \u2014 ${b.reason}`);console.log(`
293
293
  Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${w.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${a.id}`),console.log(` Docs: ${j("/docs/mcp",u)}
@@ -296,32 +296,32 @@ Could not create an instance automatically. Opening ${j("/instances",u)} \u2026
296
296
  \u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const b of E)console.log(` \u2022 ${b.file} \u2014 ${b.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(`
297
297
  \u{1F449} Next: restart your editor, start a new chat and ask:`),console.log(" What does my cachly Brain know about this project?"),console.log(` Your AI should call the cachly tool smart_recall and answer from your Brain.
298
298
  `),console.log(` Dashboard: ${j(`/instances/${a.id}`,u)}`),console.log(` Step-by-step guide: ${j("/docs/setup",u)}
299
- `),f.close(),await new Promise(b=>setTimeout(b,300)),process.exit(0)}if(process.argv[2]==="index"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=d=>{const u=t.indexOf(`--${d}`);return u!==-1?t[u+1]:void 0},o=e(n("dir")??t.find(d=>!d.startsWith("--"))??"."),s=n("instance-id")||U(),r=parseInt(n("max-files")??"500",10),c=n("namespace")??"cachly:sem:code";(!s||!A)&&(console.error(`
299
+ `),f.close(),await new Promise(b=>setTimeout(b,300)),process.exit(0)}if(process.argv[2]==="index"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=d=>{const u=t.indexOf(`--${d}`);return u!==-1?t[u+1]:void 0},o=e(n("dir")??t.find(d=>!d.startsWith("--"))??"."),s=n("instance-id")||U(),r=parseInt(n("max-files")??"500",10),l=n("namespace")??"cachly:sem:code";(!s||!A)&&(console.error(`
300
300
  \u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
301
301
  `),console.error(" export CACHLY_BRAIN_INSTANCE_ID=<uuid>"),console.error(" export CACHLY_JWT=<cky_live_...>"),console.error(` npx @cachly-dev/mcp-server@latest index ./my-project
302
302
  `),process.exit(1)),console.log(`
303
303
  \u{1F4C2} Indexing: ${o}`),console.log(` Instance: ${s.slice(0,8)}\u2026 Max files: ${r}
304
- `);try{const d=await J("index_project",{instance_id:s,dir:o,max_files:r,ttl:604800,namespace:c});console.log(d),console.log(`
304
+ `);try{const d=await J("index_project",{instance_id:s,dir:o,max_files:r,ttl:604800,namespace:l});console.log(d),console.log(`
305
305
  \u2705 Indexing complete.
306
306
  `)}catch(d){console.error(`
307
307
  \u274C Indexing failed: ${d.message}
308
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="learn-git"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=c=>{const d=t.indexOf(`--${c}`);return d!==-1?t[d+1]:void 0},o=e(n("dir")??t.find(c=>!c.startsWith("--"))??"."),s=n("instance-id")||U(),r=parseInt(n("max-commits")??"50",10);(!s||!A)&&(console.error(`
308
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="learn-git"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=l=>{const d=t.indexOf(`--${l}`);return d!==-1?t[d+1]:void 0},o=e(n("dir")??t.find(l=>!l.startsWith("--"))??"."),s=n("instance-id")||U(),r=parseInt(n("max-commits")??"50",10);(!s||!A)&&(console.error(`
309
309
  \u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
310
310
  `),console.error(" export CACHLY_BRAIN_INSTANCE_ID=<uuid>"),console.error(" export CACHLY_JWT=<cky_live_...>"),console.error(` npx @cachly-dev/mcp-server@latest learn-git .
311
311
  `),process.exit(1)),console.log(`
312
312
  \u{1F9E0} Learning from git history: ${o}`),console.log(` Instance: ${s.slice(0,8)}\u2026 Max commits: ${r}
313
- `);try{const c=await J("brain_from_git",{instance_id:s,repo_path:o,limit:r});console.log(c),C("brain_from_git",{instance_id:s}),console.log(`
313
+ `);try{const l=await J("brain_from_git",{instance_id:s,repo_path:o,limit:r});console.log(l),C("brain_from_git",{instance_id:s}),console.log(`
314
314
  \u2705 Brain learned from your commits.
315
- `),await new Promise(d=>setTimeout(d,300))}catch(c){console.error(`
316
- \u274C learn-git failed: ${c.message}
317
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await ts(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await os(),process.argv[2]===ss&&await ns(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,o={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n,instanz:U()||void 0};await is(o),await ur(process.env.CACHLY_BRAIN_INSTANCE_ID??P,o),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=U(),t=ls(await Tt(),e||void 0),n=t.eigene,o=ir(n),s=n.slice(-5);if(console.log(`
315
+ `),await new Promise(d=>setTimeout(d,300))}catch(l){console.error(`
316
+ \u274C learn-git failed: ${l.message}
317
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await ns(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await ss(),process.argv[2]===is&&await rs(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,o={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n,instanz:U()||void 0};await cs(o),await mr(process.env.CACHLY_BRAIN_INSTANCE_ID??P,o),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=U(),t=us(await It(),e||void 0),n=t.eigene,o=cr(n),s=n.slice(-5);if(console.log(`
318
318
  \u{1F9E0} Ambient Recall \u2014 net-token ledger
319
319
  `),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: ${o.injected}`),console.log(` Prevented tokens: ${o.prevented} (agent-reported via ambient-credit)`),console.log(` NET: ${o.net>=0?"+":""}${o.net} tokens`),s.length>0){console.log(`
320
- Last entries:`);for(const r of s){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(`
321
- Not counted above:`),t.ohneInstanz>0&&console.log(` \u2022 ${t.ohneInstanz} older entries without an instance (before 0.10.207)`),t.andereInstanzen>0&&console.log(` \u2022 entries of ${t.andereInstanzen} other instance${t.andereInstanzen===1?"":"s"} on this computer`)),console.log(""),process.exit(0)}if(process.argv[2]==="uninstall"){const{homedir:e,tmpdir:t}=await import("node:os"),{resolve:n}=await import("node:path"),{createInterface:o}=await import("node:readline/promises"),s=process.argv.slice(3),c={projekt:n((d=>{const u=s.indexOf(`--${d}`);return u!==-1?s[u+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:X(),instanz:U(),apiUrl:x,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:d=>console.log(d),frage:async d=>{const u=o({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await u.question(d)).trim())}finally{u.close()}}};process.exit(await Fn(s,c))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:o,checkInstance:s,checkVectorCoverage:r,inspectAmbientHooks:c,checkHooks:d,checkLedger:u,renderDoctorReport:l,doctorExitCode:i}=await import("./doctor.js"),p=[e(),t(A),await n(x),await o(x,A),s(U()||P),await r(x,A,U()||P),d(c(process.cwd())),u(await Tt(),as())];console.log(l(p)),process.exit(i(p))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!A)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??P;(!n||!t.source)&&process.exit(0),await J("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!A){const e=co();if(e)try{const t=await fetch(uo(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:lo(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(A=n.access_token,oe(n.access_token),C("m2m_auth_completed",{grant:"client_credentials",client_id:e.clientId}),process.stderr.write(`\u{1F916} cachly: authenticated via client_credentials (M2M, headless).
320
+ Last entries:`);for(const r of s){const l=r.prevented>0?`+${r.prevented} prevented`:`-${r.injected} injected`;console.log(` \u2022 ${r.ts.slice(0,19)} ${r.event}: ${l}${r.note?` (${r.note})`:""}`)}}(t.ohneInstanz>0||t.andereInstanzen>0)&&(console.log(`
321
+ Not counted above:`),t.ohneInstanz>0&&console.log(` \u2022 ${t.ohneInstanz} older entries without an instance (before 0.10.207)`),t.andereInstanzen>0&&console.log(` \u2022 entries of ${t.andereInstanzen} other instance${t.andereInstanzen===1?"":"s"} on this computer`)),console.log(""),process.exit(0)}if(process.argv[2]==="uninstall"){const{homedir:e,tmpdir:t}=await import("node:os"),{resolve:n}=await import("node:path"),{createInterface:o}=await import("node:readline/promises"),s=process.argv.slice(3),l={projekt:n((d=>{const u=s.indexOf(`--${d}`);return u!==-1?s[u+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:X(),instanz:U(),apiUrl:x,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:d=>console.log(d),frage:async d=>{const u=o({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await u.question(d)).trim())}finally{u.close()}}};process.exit(await Kn(s,l))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:o,checkInstance:s,checkVectorCoverage:r,inspectAmbientHooks:l,checkHooks:d,checkLedger:u,renderDoctorReport:c,doctorExitCode:i}=await import("./doctor.js"),p=[e(),t(A),await n(x),await o(x,A),s(U()||P),await r(x,A,U()||P),d(l(process.cwd())),u(await It(),ls())];console.log(c(p)),process.exit(i(p))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!A)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??P;(!n||!t.source)&&process.exit(0),await J("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!A){const e=lo();if(e)try{const t=await fetch(po(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:uo(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(A=n.access_token,oe(n.access_token),C("m2m_auth_completed",{grant:"client_credentials",client_id:e.clientId}),process.stderr.write(`\u{1F916} cachly: authenticated via client_credentials (M2M, headless).
322
322
  `))}else process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth failed (${t.status}). Check CACHLY_CLIENT_ID / CACHLY_CLIENT_SECRET.
323
323
  `),C("m2m_auth_failed",{status:t.status})}catch(t){process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth error: ${t.message}
324
- `),C("m2m_auth_failed",{reason:"network"})}}const Ir=["demo","share","publish","health","autosetup","setup","autopilot","init","digest","invite","refer","badge","join","upgrade","bench","tool-specs","openapi","ambient-credit","ambient-stats","doctor","uninstall"];if(!A&&!Ir.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&bo){const o=`
324
+ `),C("m2m_auth_failed",{reason:"network"})}}const Rr=["demo","share","publish","health","autosetup","setup","autopilot","init","digest","invite","refer","badge","join","upgrade","bench","tool-specs","openapi","ambient-credit","ambient-stats","doctor","uninstall"];if(!A&&!Rr.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&wo){const o=`
325
325
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
326
326
  \u2551 \u{1F9E0} cachly AI Brain \u2014 Setup required \u2551
327
327
  \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
@@ -341,7 +341,7 @@ Could not create an instance automatically. Opening ${j("/instances",u)} \u2026
341
341
  \u{1F9E0} cachly: no API key yet \u2014 the first cachly tool call opens the browser once to sign in (GitHub, Google or e-mail).
342
342
  (Own account: npx @cachly-dev/mcp-server@latest autopilot)
343
343
 
344
- `);else{const e=ro(A);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
344
+ `);else{const e=io(A);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
345
345
  \u26A0\uFE0F cachly: CACHLY_JWT expired ${Math.abs(t)} minute(s) ago.
346
346
  All tool calls will fail. Get a fresh token at ${j("/setup-ai","jwt-expiry")}
347
347
 
@@ -349,9 +349,9 @@ Could not create an instance automatically. Opening ${j("/instances",u)} \u2026
349
349
  \u26A0\uFE0F cachly: CACHLY_JWT expires in ${t} minute(s).
350
350
  Refresh it soon at ${j("/setup-ai","jwt-expiry")} to avoid interruptions.
351
351
 
352
- `)}}process.env.PORT||Us({aktuelle:Ds(H)});const Pe=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(Pe){Lo(!0),A="",P="",oe(""),Oo();const e=Ko(x,process.env.MCP_INTERNAL_SECRET?.trim());process.stderr.write(`cachly-mcp HTTP: API ${x}, Aufrufer-Weitergabe ${e?"an":"aus (MCP_INTERNAL_SECRET fehlt oder zu kurz)"}
353
- `);const t=Wo(async(u,l)=>{const i=await fetch(`${x}${u}`,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)}),p=i.ok?await i.json().catch(()=>null):null,f=Number(i.headers.get("retry-after"));return{status:i.status,body:p,retryAfterS:Number.isFinite(f)&&f>0?f:void 0}},{grenze:Jo()}),n=Zo(),o=en(n);process.stderr.write(`cachly-mcp HTTP: OAuth ${n.resource} -> ${n.aussteller}, Unterschrift ${n.jwksUrl?"hier geprueft":"nur in der API geprueft (MCP_OAUTH_JWKS_URL=aus)"}
354
- `);const{createServer:s}=await import("node:http"),r=(u,l,i,p,f)=>{u.headersSent||(u.writeHead(l,{"Content-Type":"application/json",...l===429&&p?{"Retry-After":String(p)}:{},...l===401?{"WWW-Authenticate":Qo(n,"invalid_token",f)}:{}}),u.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:i},id:null})))},c=async(u,l)=>{const i=[];let p=0;for await(const f of u){const y=f;if(p+=y.length,p>l)return;i.push(y)}return Buffer.concat(i).toString("utf8")};s((u,l)=>{const i=new URL(u.url??"/",`http://localhost:${Pe}`);if(i.pathname==="/health"){l.writeHead(200,{"Content-Type":"application/json"}),l.end(JSON.stringify({status:"ok",version:H,mode:"http-remote"}));return}if(n.metadatenPfade.includes(i.pathname)){if(u.method==="OPTIONS"){l.writeHead(204,{Allow:"GET, HEAD, OPTIONS"}),l.end();return}if(u.method!=="GET"&&u.method!=="HEAD"){l.writeHead(405,{Allow:"GET, HEAD, OPTIONS"}),l.end();return}l.writeHead(200,{"Content-Type":"application/json","Cache-Control":"public, max-age=300"}),l.end(u.method==="HEAD"?void 0:JSON.stringify(Xo(n)));return}if(i.pathname==="/mcp"||i.pathname==="/"){const p=Fo(u.headers["x-real-ip"],u.socket.remoteAddress);Yo(p,async()=>{const f=zo(u.headersDistinct?.authorization??u.headers.authorization,{aussteller:n.aussteller});if(f.art==="abgelehnt"){const m=f.grund==="zu-lang"?"Der Authorization-Kopf ist zu lang.":f.grund==="mehrfach"?"Der Authorization-Kopf darf nur einmal vorkommen.":f.grund==="kein-bearer"?'Nur "Authorization: Bearer <Schluessel oder Token>" wird akzeptiert.':f.grund==="aussteller"?on("aussteller"):"Das ist kein cachly-API-Schluessel (er beginnt mit cky_). Neuen holen: "+j("/setup-ai","setup");return r(l,401,m)}let y;if(f.art==="fehlt"&&u.method==="POST"&&String(u.headers["content-type"]??"").includes("application/json")){const m=await c(u,an);if(m===void 0){l.writeHead(413,{"Content-Type":"application/json"}),l.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32600,message:"Request too large"},id:null}));return}try{y=JSON.parse(m)}catch{l.writeHead(400,{"Content-Type":"application/json"}),l.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error: Invalid JSON"},id:null}));return}if(sn(y))return r(l,401,_e,void 0,rn)}const w=Do(u.headers["x-cachly-instance"]);if(w.art==="abgelehnt")return r(l,400,"X-Cachly-Instance muss eine Instanz-ID (UUID) sein.");const h=w.art==="ok"?w.instanzId:void 0;let a;if(f.art==="ok")try{const m=await t.loese(f.schluessel,h,p);a=ht(f.schluessel,m)}catch(m){return m instanceof yt?r(l,m.httpStatus,m.message,m.retryAfterS):r(l,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}if(f.art==="jwt")try{const m=await o.pruefe(f.token),S=await t.loese(f.token,h,p,{anmeldung:!0,bisMs:m.bisMs});a=ht(f.token,S,m.sub)}catch(m){return m instanceof tn?m.grund==="jwks-fehlt"?r(l,502,m.message):r(l,401,m.message):m instanceof yt?r(l,m.httpStatus,m.message,m.retryAfterS):r(l,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}const g=async()=>{const m=_r(),S=new vo({sessionIdGenerator:void 0});l.on("close",()=>{S.close().catch(()=>{}),m.close().catch(()=>{})});try{await m.connect(S),await S.handleRequest(u,l,y)}catch(v){process.stderr.write(`cachly-mcp HTTP: ${v.message}
355
- `),l.headersSent||(l.writeHead(500,{"Content-Type":"application/json"}),l.end(JSON.stringify({error:v.message})))}};await(a?Ho(a,g):g())});return}l.writeHead(404),l.end("not found")}).listen(Pe,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${Pe}
356
- `)})}else{const e=new wo;Y("start: Module geladen, stdio verbinden"),await q.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(ct=!0,Ns(()=>zs(lt)),Co(),Ys(),Js(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 session over, server exits too
357
- `),(async()=>{await Ge().catch(()=>{});for(const o of We())await o.quit().catch(()=>{});process.exit(0)})()}))}Qe("cachly","startup",{version:H,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{Hn as CLAUDE_MD_MARKER_END,Ln as CLAUDE_MD_MARKER_START,bn as CROSS_LINGUAL_MAP,Se as EDITOR_FILES,fn as STOPWORDS,no as anweisungsZeile,hn as arabicLightStem,xt as buildClaudeMdBlock,Ar as buildMcpConfig,ee as buildServerEnv,yn as expandCrossLingual,mn as extractTimestamp,ut as fristMs,gn as katakanaToRomaji,un as levenshtein,Sr as mcpAddBefehl,to as mergeMcpConfig,pn as recencyBoost,xn as reconnectOnce,dn as splitMultiQuery,mt as startBackgroundDevicePoll,ln as tokenize,oo as writeInstructions};
352
+ `)}}process.env.PORT||Js({aktuelle:Ws(H)});const Pe=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(Pe){Ho(!0),A="",P="",oe(""),Lo();const e=Go(x,process.env.MCP_INTERNAL_SECRET?.trim());process.stderr.write(`cachly-mcp HTTP: API ${x}, Aufrufer-Weitergabe ${e?"an":"aus (MCP_INTERNAL_SECRET fehlt oder zu kurz)"}
353
+ `);const t=Jo(async(u,c)=>{const i=await fetch(`${x}${u}`,{headers:{Authorization:`Bearer ${c}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)}),p=i.ok?await i.json().catch(()=>null):null,f=Number(i.headers.get("retry-after"));return{status:i.status,body:p,retryAfterS:Number.isFinite(f)&&f>0?f:void 0}},{grenze:Fo()}),n=Xo(),o=tn(n);process.stderr.write(`cachly-mcp HTTP: OAuth ${n.resource} -> ${n.aussteller}, Unterschrift ${n.jwksUrl?"hier geprueft":"nur in der API geprueft (MCP_OAUTH_JWKS_URL=aus)"}
354
+ `);const{createServer:s}=await import("node:http"),r=(u,c,i,p,f)=>{u.headersSent||(u.writeHead(c,{"Content-Type":"application/json",...c===429&&p?{"Retry-After":String(p)}:{},...c===401?{"WWW-Authenticate":en(n,"invalid_token",f)}:{}}),u.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:i},id:null})))},l=async(u,c)=>{const i=[];let p=0;for await(const f of u){const y=f;if(p+=y.length,p>c)return;i.push(y)}return Buffer.concat(i).toString("utf8")};s((u,c)=>{const i=new URL(u.url??"/",`http://localhost:${Pe}`);if(i.pathname==="/health"){c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({status:"ok",version:H,mode:"http-remote"}));return}if(!ln(u,c,i.pathname)){if(n.metadatenPfade.includes(i.pathname)){if(u.method==="OPTIONS"){c.writeHead(204,{Allow:"GET, HEAD, OPTIONS"}),c.end();return}if(u.method!=="GET"&&u.method!=="HEAD"){c.writeHead(405,{Allow:"GET, HEAD, OPTIONS"}),c.end();return}c.writeHead(200,{"Content-Type":"application/json","Cache-Control":"public, max-age=300"}),c.end(u.method==="HEAD"?void 0:JSON.stringify(Qo(n)));return}if(i.pathname==="/mcp"||i.pathname==="/"){const p=Yo(u.headers["x-real-ip"],u.socket.remoteAddress);Ko(p,async()=>{const f=Do(u.headersDistinct?.authorization??u.headers.authorization,{aussteller:n.aussteller});if(f.art==="abgelehnt"){const m=f.grund==="zu-lang"?"Der Authorization-Kopf ist zu lang.":f.grund==="mehrfach"?"Der Authorization-Kopf darf nur einmal vorkommen.":f.grund==="kein-bearer"?'Nur "Authorization: Bearer <Schluessel oder Token>" wird akzeptiert.':f.grund==="aussteller"?nn("aussteller"):"Das ist kein cachly-API-Schluessel (er beginnt mit cky_). Neuen holen: "+j("/setup-ai","setup");return r(c,401,m)}let y;if(f.art==="fehlt"&&u.method==="POST"&&String(u.headers["content-type"]??"").includes("application/json")){const m=await l(u,cn);if(m===void 0){c.writeHead(413,{"Content-Type":"application/json"}),c.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32600,message:"Request too large"},id:null}));return}try{y=JSON.parse(m)}catch{c.writeHead(400,{"Content-Type":"application/json"}),c.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error: Invalid JSON"},id:null}));return}if(rn(y))return r(c,401,_e,void 0,an)}const w=Uo(u.headers["x-cachly-instance"]);if(w.art==="abgelehnt")return r(c,400,"X-Cachly-Instance muss eine Instanz-ID (UUID) sein.");const h=w.art==="ok"?w.instanzId:void 0;let a;if(f.art==="ok")try{const m=await t.loese(f.schluessel,h,p);a=ht(f.schluessel,m)}catch(m){return m instanceof yt?r(c,m.httpStatus,m.message,m.retryAfterS):r(c,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}if(f.art==="jwt")try{const m=await o.pruefe(f.token),S=await t.loese(f.token,h,p,{anmeldung:!0,bisMs:m.bisMs});a=ht(f.token,S,m.sub)}catch(m){return m instanceof on?m.grund==="jwks-fehlt"?r(c,502,m.message):r(c,401,m.message):m instanceof yt?r(c,m.httpStatus,m.message,m.retryAfterS):r(c,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}const g=async()=>{const m=kr(),S=new xo({sessionIdGenerator:void 0});c.on("close",()=>{S.close().catch(()=>{}),m.close().catch(()=>{})});try{await m.connect(S),await S.handleRequest(u,c,y)}catch(v){process.stderr.write(`cachly-mcp HTTP: ${v.message}
355
+ `),c.headersSent||(c.writeHead(500,{"Content-Type":"application/json"}),c.end(JSON.stringify({error:v.message})))}};await(a?Mo(a,g):g())});return}c.writeHead(404),c.end("not found")}}).listen(Pe,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${Pe}
356
+ `)})}else{const e=new vo;Y("start: Module geladen, stdio verbinden"),await q.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(ct=!0,Bs(()=>Us(lt)),To(),Gs(),Ys(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 session over, server exits too
357
+ `),(async()=>{await Ge().catch(()=>{});for(const o of We())await o.quit().catch(()=>{});process.exit(0)})()}))}Qe("cachly","startup",{version:H,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{zn as CLAUDE_MD_MARKER_END,Mn as CLAUDE_MD_MARKER_START,vn as CROSS_LINGUAL_MAP,Se as EDITOR_FILES,hn as STOPWORDS,so as anweisungsZeile,bn as arabicLightStem,_t as buildClaudeMdBlock,Tr as buildMcpConfig,ee as buildServerEnv,wn as expandCrossLingual,gn as extractTimestamp,ut as fristMs,yn as katakanaToRomaji,mn as levenshtein,Cr as mcpAddBefehl,oo as mergeMcpConfig,fn as recencyBoost,$n as reconnectOnce,pn as splitMultiQuery,mt as startBackgroundDevicePoll,un as tokenize,no as writeInstructions};
@@ -0,0 +1,6 @@
1
+ const i=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none">
2
+ <rect width="32" height="32" rx="8" fill="#F59E0B"/>
3
+ <path d="M20.6 10.4A7.6 7.6 0 1 0 20.6 21.6" stroke="#292524" stroke-width="5.2" stroke-linecap="round"/>
4
+ <circle cx="25.4" cy="23.4" r="2.7" fill="#292524"/>
5
+ </svg>
6
+ `;function n(t){return{name:"cachly-mcp",version:t,title:"cachly",websiteUrl:"https://cachly.dev",icons:[{src:"https://cachly.dev/favicon.svg",mimeType:"image/svg+xml",sizes:["any"]}]}}function c(t,e,o){return o!=="/favicon.svg"&&o!=="/favicon.ico"?!1:t.method!=="GET"&&t.method!=="HEAD"?(e.writeHead(405,{Allow:"GET, HEAD"}),e.end(),!0):o==="/favicon.ico"?(e.writeHead(301,{Location:"/favicon.svg","Cache-Control":"public, max-age=86400"}),e.end(),!0):(e.writeHead(200,{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}),e.end(t.method==="HEAD"?void 0:i),!0)}export{i as LOGO_SVG,c as beantworteLogo,n as serverInfo};
@@ -1,2 +1,2 @@
1
- import{constants as y,createPublicKey as T,verify as m}from"node:crypto";const P="https://mcp.cachly.dev/mcp",x="https://auth.cachly.dev/realms/cachly",D=["profile","email"],O="https://cachly.dev/docs/remote-mcp",_="https://cachly.dev/instances",g="/.well-known/oauth-protected-resource";function k(e){return e.replace(/\/+$/,"")}function w(e,t){return(e??"").split(t).map(n=>n.trim()).filter(n=>n!=="")}function A(e,t){let n;try{n=new URL(t)}catch{throw new Error(`${e} ist keine URL: "${t}"`)}const s=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&s))throw new Error(`${e} muss mit https:// beginnen (http nur fuer localhost): "${t}"`);if(n.search||n.hash)throw new Error(`${e} darf weder ? noch # enthalten: "${t}"`);return n}function J(e=process.env){const t=k(e.MCP_OAUTH_RESOURCE?.trim()||P),n=k(e.MCP_OAUTH_ISSUER?.trim()||x),s=A("MCP_OAUTH_RESOURCE",t);A("MCP_OAUTH_ISSUER",n);const r=w(e.MCP_OAUTH_AUDIENCE,/,/),i=e.MCP_OAUTH_JWKS_URL?.trim()??"";let c;i.toLowerCase()==="aus"||i.toLowerCase()==="off"?c=null:i?c=A("MCP_OAUTH_JWKS_URL",i).href:c=`${n}/protocol/openid-connect/certs`;const f=w(e.MCP_OAUTH_SCOPES,/[\s,]+/),u=f.length>0?f:[...D],o=s.pathname==="/"?"":s.pathname,a=o?[`${g}${o}`,g]:[g];return{resource:t,aussteller:n,zielgruppen:r.length>0?r:[t],jwksUrl:c,scopes:u,metadatenUrl:`${s.origin}${a[0]}`,metadatenPfade:a}}function G(e){return{resource:e.resource,authorization_servers:[e.aussteller],bearer_methods_supported:["header"],...e.scopes.length>0?{scopes_supported:[...e.scopes]}:{},resource_name:"cachly",resource_documentation:O}}function v(e,t,n){const s=['Bearer realm="cachly"'];return t&&s.push(`error="${t}"`),t&&n&&s.push(`error_description="${n.replace(/[^\x20-\x7e]|"/g,"")}"`),s.push(`resource_metadata="${e.metadatenUrl}"`),e.scopes.length>0&&s.push(`scope="${e.scopes.join(" ")}"`),s.join(", ")}const W="Authentication required for this tool",Z=4*1024*1024;function V(e){return(Array.isArray(e)?e:[e]).some(n=>!!n&&typeof n=="object"&&n.method==="tools/call")}const C=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;function M(e){return C.test(e)}function E(e){try{const t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function $(e){if(!M(e))return;const[t,n,s]=e.split("."),r=E(t),i=E(n);if(!(!r||!i))return{kopf:r,ansprueche:i,signiert:`${t}.${n}`,unterschrift:Buffer.from(s,"base64url")}}const U=30;function j(e,t,n){if(e.iss!==t.aussteller)return{fehler:"aussteller"};if(typeof e.exp!="number"||!Number.isFinite(e.exp))return{fehler:"form"};if(e.exp*1e3+U*1e3<=n)return{fehler:"abgelaufen"};if(typeof e.nbf=="number"&&e.nbf*1e3-U*1e3>n)return{fehler:"noch-nicht-gueltig"};const s=typeof e.aud=="string"?[e.aud]:Array.isArray(e.aud)?e.aud.filter(r=>typeof r=="string"):[];return t.zielgruppen.length>0&&!s.some(r=>t.zielgruppen.includes(r))?{fehler:"zielgruppe"}:typeof e.typ=="string"&&e.typ.toLowerCase()!=="bearer"?{fehler:"typ"}:typeof e.sub!="string"||e.sub===""?{fehler:"inhaber"}:{sub:e.sub,iss:e.iss,bisMs:e.exp*1e3}}function L(e){switch(e){case"aussteller":return"Das Token stammt nicht vom cachly-Anmeldedienst.";case"abgelaufen":return"Die Anmeldung ist abgelaufen. Bitte neu anmelden.";case"noch-nicht-gueltig":return"Das Token ist noch nicht gueltig (Uhrzeit pruefen).";case"zielgruppe":return"Das Token ist nicht fuer diesen MCP-Server ausgestellt (Zielgruppe passt nicht).";case"typ":return"Das ist kein Zugangstoken.";case"inhaber":return"Dem Token fehlt der Inhaber.";case"algorithmus":return"Das Token ist mit einem nicht erlaubten Verfahren unterschrieben.";case"schluessel-unbekannt":return"Der Schluessel, mit dem das Token unterschrieben ist, ist unbekannt.";case"unterschrift":return"Die Unterschrift des Tokens ist ungueltig.";case"jwks-fehlt":return"Der cachly-Anmeldedienst ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.";default:return"Das Token hat keine gueltige Form."}}class l extends Error{grund;constructor(t){super(L(t)),this.grund=t,this.name="TokenAbgelehnt"}}const b={RS256:{familie:"RS",hash:"sha256"},RS384:{familie:"RS",hash:"sha384"},RS512:{familie:"RS",hash:"sha512"},PS256:{familie:"PS",hash:"sha256"},PS384:{familie:"PS",hash:"sha384"},PS512:{familie:"PS",hash:"sha512"},ES256:{familie:"ES",hash:"sha256"},ES384:{familie:"ES",hash:"sha384"},ES512:{familie:"ES",hash:"sha512"}};function N(e,t,n,s){const r=b[e];if(!r)return!1;const i=t.asymmetricKeyType,c=Buffer.from(n,"utf8");try{return r.familie==="RS"?i==="rsa"&&m(r.hash,c,t,s):r.familie==="PS"?(i==="rsa"||i==="rsa-pss")&&m(r.hash,c,{key:t,padding:y.RSA_PKCS1_PSS_PADDING,saltLength:y.RSA_PSS_SALTLEN_DIGEST},s):i==="ec"&&m(r.hash,c,{key:t,dsaEncoding:"ieee-p1363"},s)}catch{return!1}}const H=10*6e4,B=3e4;function z(e){const t=e?.keys;if(!Array.isArray(t))return[];const n=[];for(const s of t)if(!(!s||typeof s!="object")&&!(s.use!==void 0&&s.use!=="sig")&&!(s.kty!=="RSA"&&s.kty!=="EC"))try{const r=T({key:s,format:"jwk"});n.push({kid:typeof s.kid=="string"?s.kid:void 0,alg:typeof s.alg=="string"?s.alg:void 0,schluessel:r})}catch{}return n}function X(e,t){const n=t?.jetzt??Date.now,s=t?.abruf??(async u=>{const o=await fetch(u,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)});return{status:o.status,body:o.ok?await o.json().catch(()=>null):null}});let r,i;const c=()=>{if(!e.jwksUrl)return Promise.resolve([]);if(!i){const u=e.jwksUrl;i=s(u).then(o=>{const a=o.status===200?z(o.body):[];if(a.length===0)throw new l("jwks-fehlt");return r={schluessel:a,um:n()},a}).catch(o=>{throw o instanceof l?o:new l("jwks-fehlt")}).finally(()=>{i=void 0})}return i},f=(u,o,a)=>u.find(h=>(o===void 0||h.kid===o)&&(h.alg===void 0||h.alg===a));return{async pruefe(u){const o=$(u);if(!o)throw new l("form");const a=j(o.ansprueche,e,n());if("fehler"in a)throw new l(a.fehler);if(!e.jwksUrl)return a;const h=typeof o.kopf.alg=="string"?o.kopf.alg:"";if(!b[h])throw new l("algorithmus");const d=typeof o.kopf.kid=="string"?o.kopf.kid:void 0,S=r&&n()-r.um<H;let p=S?f(r.schluessel,d,h):void 0;if(!p&&(!r||!S||n()-r.um>=B))try{p=f(await c(),d,h)}catch(R){if(p=r?f(r.schluessel,d,h):void 0,!p)throw R}if(!p)throw new l("schluessel-unbekannt");if(!N(h,p.schluessel,o.signiert,o.unterschrift))throw new l("unterschrift");return a}}}const I=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function q(e){const t=e?.data;if(!Array.isArray(t))return"";const n=r=>{const i=typeof r=="string"?Date.parse(r):NaN;return Number.isFinite(i)?i:-1/0};return t.filter(r=>r&&typeof r.id=="string"&&I.test(r.id)&&r.status==="running").map(r=>({id:r.id.toLowerCase(),t:n(r.created_at)})).sort((r,i)=>i.t-r.t||(r.id<i.id?-1:r.id>i.id?1:0))[0]?.id??""}const Y=["Zu deinem cachly-Konto gehoert noch kein laufendes Brain.",`Lege eines an oder starte es im Dashboard: ${_}`,"Danach geht es hier ohne neue Anmeldung weiter (spaetestens nach einer Minute).","","Your cachly account has no running Brain yet.",`Create or start one in the dashboard: ${_}`].join(`
1
+ import{constants as S,createPublicKey as T,verify as m}from"node:crypto";const P="https://mcp.cachly.dev/mcp",x="https://auth.cachly.dev/realms/cachly",D=["profile","email","cachly-mcp"],O="https://cachly.dev/docs/remote-mcp",_="https://cachly.dev/instances",g="/.well-known/oauth-protected-resource";function k(e){return e.replace(/\/+$/,"")}function w(e,t){return(e??"").split(t).map(n=>n.trim()).filter(n=>n!=="")}function y(e,t){let n;try{n=new URL(t)}catch{throw new Error(`${e} ist keine URL: "${t}"`)}const s=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&s))throw new Error(`${e} muss mit https:// beginnen (http nur fuer localhost): "${t}"`);if(n.search||n.hash)throw new Error(`${e} darf weder ? noch # enthalten: "${t}"`);return n}function J(e=process.env){const t=k(e.MCP_OAUTH_RESOURCE?.trim()||P),n=k(e.MCP_OAUTH_ISSUER?.trim()||x),s=y("MCP_OAUTH_RESOURCE",t);y("MCP_OAUTH_ISSUER",n);const r=w(e.MCP_OAUTH_AUDIENCE,/,/),i=e.MCP_OAUTH_JWKS_URL?.trim()??"";let c;i.toLowerCase()==="aus"||i.toLowerCase()==="off"?c=null:i?c=y("MCP_OAUTH_JWKS_URL",i).href:c=`${n}/protocol/openid-connect/certs`;const f=w(e.MCP_OAUTH_SCOPES,/[\s,]+/),u=f.length>0?f:[...D],o=s.pathname==="/"?"":s.pathname,a=o?[`${g}${o}`,g]:[g];return{resource:t,aussteller:n,zielgruppen:r.length>0?r:[t],jwksUrl:c,scopes:u,metadatenUrl:`${s.origin}${a[0]}`,metadatenPfade:a}}function G(e){return{resource:e.resource,authorization_servers:[e.aussteller],bearer_methods_supported:["header"],...e.scopes.length>0?{scopes_supported:[...e.scopes]}:{},resource_name:"cachly",resource_documentation:O}}function v(e,t,n){const s=['Bearer realm="cachly"'];return t&&s.push(`error="${t}"`),t&&n&&s.push(`error_description="${n.replace(/[^\x20-\x7e]|"/g,"")}"`),s.push(`resource_metadata="${e.metadatenUrl}"`),e.scopes.length>0&&s.push(`scope="${e.scopes.join(" ")}"`),s.join(", ")}const W="Authentication required for this tool",Z=4*1024*1024;function V(e){return(Array.isArray(e)?e:[e]).some(n=>!!n&&typeof n=="object"&&n.method==="tools/call")}const C=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;function M(e){return C.test(e)}function E(e){try{const t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function $(e){if(!M(e))return;const[t,n,s]=e.split("."),r=E(t),i=E(n);if(!(!r||!i))return{kopf:r,ansprueche:i,signiert:`${t}.${n}`,unterschrift:Buffer.from(s,"base64url")}}const U=30;function j(e,t,n){if(e.iss!==t.aussteller)return{fehler:"aussteller"};if(typeof e.exp!="number"||!Number.isFinite(e.exp))return{fehler:"form"};if(e.exp*1e3+U*1e3<=n)return{fehler:"abgelaufen"};if(typeof e.nbf=="number"&&e.nbf*1e3-U*1e3>n)return{fehler:"noch-nicht-gueltig"};const s=typeof e.aud=="string"?[e.aud]:Array.isArray(e.aud)?e.aud.filter(r=>typeof r=="string"):[];return t.zielgruppen.length>0&&!s.some(r=>t.zielgruppen.includes(r))?{fehler:"zielgruppe"}:typeof e.typ=="string"&&e.typ.toLowerCase()!=="bearer"?{fehler:"typ"}:typeof e.sub!="string"||e.sub===""?{fehler:"inhaber"}:{sub:e.sub,iss:e.iss,bisMs:e.exp*1e3}}function L(e){switch(e){case"aussteller":return"Das Token stammt nicht vom cachly-Anmeldedienst.";case"abgelaufen":return"Die Anmeldung ist abgelaufen. Bitte neu anmelden.";case"noch-nicht-gueltig":return"Das Token ist noch nicht gueltig (Uhrzeit pruefen).";case"zielgruppe":return"Das Token ist nicht fuer diesen MCP-Server ausgestellt (Zielgruppe passt nicht).";case"typ":return"Das ist kein Zugangstoken.";case"inhaber":return"Dem Token fehlt der Inhaber.";case"algorithmus":return"Das Token ist mit einem nicht erlaubten Verfahren unterschrieben.";case"schluessel-unbekannt":return"Der Schluessel, mit dem das Token unterschrieben ist, ist unbekannt.";case"unterschrift":return"Die Unterschrift des Tokens ist ungueltig.";case"jwks-fehlt":return"Der cachly-Anmeldedienst ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.";default:return"Das Token hat keine gueltige Form."}}class l extends Error{grund;constructor(t){super(L(t)),this.grund=t,this.name="TokenAbgelehnt"}}const b={RS256:{familie:"RS",hash:"sha256"},RS384:{familie:"RS",hash:"sha384"},RS512:{familie:"RS",hash:"sha512"},PS256:{familie:"PS",hash:"sha256"},PS384:{familie:"PS",hash:"sha384"},PS512:{familie:"PS",hash:"sha512"},ES256:{familie:"ES",hash:"sha256"},ES384:{familie:"ES",hash:"sha384"},ES512:{familie:"ES",hash:"sha512"}};function N(e,t,n,s){const r=b[e];if(!r)return!1;const i=t.asymmetricKeyType,c=Buffer.from(n,"utf8");try{return r.familie==="RS"?i==="rsa"&&m(r.hash,c,t,s):r.familie==="PS"?(i==="rsa"||i==="rsa-pss")&&m(r.hash,c,{key:t,padding:S.RSA_PKCS1_PSS_PADDING,saltLength:S.RSA_PSS_SALTLEN_DIGEST},s):i==="ec"&&m(r.hash,c,{key:t,dsaEncoding:"ieee-p1363"},s)}catch{return!1}}const H=10*6e4,B=3e4;function z(e){const t=e?.keys;if(!Array.isArray(t))return[];const n=[];for(const s of t)if(!(!s||typeof s!="object")&&!(s.use!==void 0&&s.use!=="sig")&&!(s.kty!=="RSA"&&s.kty!=="EC"))try{const r=T({key:s,format:"jwk"});n.push({kid:typeof s.kid=="string"?s.kid:void 0,alg:typeof s.alg=="string"?s.alg:void 0,schluessel:r})}catch{}return n}function X(e,t){const n=t?.jetzt??Date.now,s=t?.abruf??(async u=>{const o=await fetch(u,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)});return{status:o.status,body:o.ok?await o.json().catch(()=>null):null}});let r,i;const c=()=>{if(!e.jwksUrl)return Promise.resolve([]);if(!i){const u=e.jwksUrl;i=s(u).then(o=>{const a=o.status===200?z(o.body):[];if(a.length===0)throw new l("jwks-fehlt");return r={schluessel:a,um:n()},a}).catch(o=>{throw o instanceof l?o:new l("jwks-fehlt")}).finally(()=>{i=void 0})}return i},f=(u,o,a)=>u.find(h=>(o===void 0||h.kid===o)&&(h.alg===void 0||h.alg===a));return{async pruefe(u){const o=$(u);if(!o)throw new l("form");const a=j(o.ansprueche,e,n());if("fehler"in a)throw new l(a.fehler);if(!e.jwksUrl)return a;const h=typeof o.kopf.alg=="string"?o.kopf.alg:"";if(!b[h])throw new l("algorithmus");const d=typeof o.kopf.kid=="string"?o.kopf.kid:void 0,A=r&&n()-r.um<H;let p=A?f(r.schluessel,d,h):void 0;if(!p&&(!r||!A||n()-r.um>=B))try{p=f(await c(),d,h)}catch(R){if(p=r?f(r.schluessel,d,h):void 0,!p)throw R}if(!p)throw new l("schluessel-unbekannt");if(!N(h,p.schluessel,o.signiert,o.unterschrift))throw new l("unterschrift");return a}}}const I=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function q(e){const t=e?.data;if(!Array.isArray(t))return"";const n=r=>{const i=typeof r=="string"?Date.parse(r):NaN;return Number.isFinite(i)?i:-1/0};return t.filter(r=>r&&typeof r.id=="string"&&I.test(r.id)&&r.status==="running").map(r=>({id:r.id.toLowerCase(),t:n(r.created_at)})).sort((r,i)=>i.t-r.t||(r.id<i.id?-1:r.id>i.id?1:0))[0]?.id??""}const Y=["Zu deinem cachly-Konto gehoert noch kein laufendes Brain.",`Lege eines an oder starte es im Dashboard: ${_}`,"Danach geht es hier ohne neue Anmeldung weiter (spaetestens nach einer Minute).","","Your cachly account has no running Brain yet.",`Create or start one in the dashboard: ${_}`].join(`
2
2
  `);export{_ as DASHBOARD_URL,B as JWKS_MINDESTABSTAND_MS,H as JWKS_TTL_MS,Y as KEIN_BRAIN_TEXT,Z as MAX_RUMPF_OHNE_ANMELDUNG,O as OAUTH_DOKU,x as OAUTH_VORGABE_ISSUER,P as OAUTH_VORGABE_RESOURCE,D as OAUTH_VORGABE_SCOPES,l as TokenAbgelehnt,U as UHR_SPIELRAUM_S,W as WERKZEUG_BRAUCHT_ANMELDUNG,X as baueJwtPruefer,V as brauchtAnmeldung,J as leseOAuthEinstellungen,j as pruefeAnsprueche,G as schutzMetadaten,M as siehtAusWieJwt,L as tokenFehlerText,N as unterschriftStimmt,q as waehleStandardBrain,v as wwwAuthenticate,$ as zerlegeJwt};
package/glama.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://glama.ai/mcp/schemas/server.json",
3
- "version": "0.10.273",
3
+ "version": "0.10.275",
4
4
  "maintainers": [
5
5
  "HeinrichNebula"
6
6
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cachly-dev/mcp-server",
3
- "version": "0.10.273",
3
+ "version": "0.10.275",
4
4
  "mcpName": "io.github.cachly-dev/mcp-server",
5
5
  "description": "Explain it once. Every AI knows it. cachly keeps the rules, decisions and fixes you explain to your AI and gives them back in every session: Claude Code, Cursor, Copilot, Windsurf, Codex, Gemini CLI. Hosted in the EU.",
6
6
  "type": "module",
package/server.json CHANGED
@@ -17,12 +17,12 @@
17
17
  "url": "https://github.com/cachly-dev/cachly-mcp",
18
18
  "source": "github"
19
19
  },
20
- "version": "0.10.273",
20
+ "version": "0.10.275",
21
21
  "packages": [
22
22
  {
23
23
  "registryType": "npm",
24
24
  "identifier": "@cachly-dev/mcp-server",
25
- "version": "0.10.273",
25
+ "version": "0.10.275",
26
26
  "runtimeHint": "npx",
27
27
  "transport": {
28
28
  "type": "stdio"