@cachly-dev/mcp-server 0.10.178 → 0.10.179

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.
@@ -1 +1 @@
1
- import{existsSync as o,mkdirSync as f,writeFileSync as p,renameSync as l,chmodSync as y,readFileSync as s}from"node:fs";import{resolve as a,dirname as m}from"node:path";function h(){return process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??""}function S(e){return/^\$\{[^}]*\}$/.test(e.trim())}function r(e){if(!(typeof e!="string"||e.length===0))return S(e)?void 0:e}function u(e={}){const n=e.home??h();return a(n,".cachly","credentials.json")}function I(e,n={}){const t=i(n),c=t?.apiKey===e?r(t.instanceId):void 0;d({apiKey:e,...c?{instanceId:c}:{}},n)}function x(e,n){const t=i(n);!r(e)||!t?.apiKey||t.apiKey!==n.apiKey||t.instanceId!==e&&d({...t,instanceId:e},n)}function P(e={}){return r(i(e)?.instanceId)}function i(e){try{const n=u(e);if(!o(n))return null;const t=JSON.parse(s(n,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function d(e,n){try{const t=u(n);f(m(t),{recursive:!0});const c=`${t}.${process.pid}-${Date.now()}.tmp`;p(c,JSON.stringify(e,null,2),"utf8");try{y(c,384)}catch{}l(c,t)}catch{}}function v(e){return r(i(e)?.apiKey)}function C(e){try{const n=a(e.cwd??process.cwd(),".mcp.json");if(!o(n))return;const t=JSON.parse(s(n,"utf8"));return r(t.mcpServers?.cachly?.env?.CACHLY_JWT)}catch{return}}function H(e={}){const n=e.env??process.env;return r(n.CACHLY_JWT)??r(n.CACHLY_API_KEY)??v(e)??C(e)}export{u as credentialsPath,S as istPlatzhalter,P as readInstanceId,H as resolveApiKey,I as saveApiKey,x as saveInstanceId};
1
+ import{existsSync as o,mkdirSync as p,writeFileSync as f,renameSync as y,chmodSync as l,readFileSync as a}from"node:fs";import{resolve as s,dirname as m}from"node:path";function h(){return process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??""}function K(e){return/^\$\{[^}]*\}$/.test(e.trim())}function r(e){if(!(typeof e!="string"||e.length===0))return K(e)?void 0:e}function u(e={}){const n=e.home??h();return s(n,".cachly","credentials.json")}function x(e,n={}){const t=i(n),c=t?.apiKey===e?r(t.instanceId):void 0;d({apiKey:e,...c?{instanceId:c}:{}},n)}function I(e,n){const t=i(n);!r(e)||!t?.apiKey||t.apiKey!==n.apiKey||t.instanceId!==e&&d({...t,instanceId:e},n)}function P(e={}){return r(i(e)?.instanceId)}function H(e={}){return r(i(e)?.apiKey)}function i(e){try{const n=u(e);if(!o(n))return null;const t=JSON.parse(a(n,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function d(e,n){try{const t=u(n);p(m(t),{recursive:!0});const c=`${t}.${process.pid}-${Date.now()}.tmp`;f(c,JSON.stringify(e,null,2),"utf8");try{l(c,384)}catch{}y(c,t)}catch{}}function S(e){return r(i(e)?.apiKey)}function v(e){try{const n=s(e.cwd??process.cwd(),".mcp.json");if(!o(n))return;const t=JSON.parse(a(n,"utf8"));return r(t.mcpServers?.cachly?.env?.CACHLY_JWT)}catch{return}}function g(e={}){const n=e.env??process.env;return r(n.CACHLY_JWT)??r(n.CACHLY_API_KEY)??S(e)??v(e)}export{u as credentialsPath,K as istPlatzhalter,P as readInstanceId,H as readSavedApiKey,g as resolveApiKey,x as saveApiKey,I as saveInstanceId};
package/dist/src/index.js CHANGED
@@ -1,69 +1,69 @@
1
1
  #!/usr/bin/env node
2
- import{setzeClientKennung as xt}from"./herkunft.js";import{jwtExpiryMs as _t,checkJwt as $t,handleApiError as Ct,diagnoseAuth as fe,planAuthHeal as Ie,readClientCredentialsFromEnv as At,buildClientCredentialsBody as St,clientCredentialsTokenUrl as kt}from"./auth.js";import{cachlyUrl as R}from"./cachly-url.js";import{nutzungsSchluessel as Tt}from"./werkzeug-nutzung.js";import{istLieferung as It,lieferSchluessel as Et,tokenDerAntwort as Rt,hatTreffer as Nt,trefferSchluessel as Ee}from"./geliefert.js";import{notify as Re}from"./notifier.js";import{fileURLToPath as Ne}from"node:url";import{createRequire as Lt}from"node:module";import{execFile as he}from"node:child_process";const Bt=process.argv[1]!=null&&(process.argv[1]===Ne(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as Le}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as jt}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as Ht}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Be,ErrorCode as ne,ListPromptsRequestSchema as je,ListResourceTemplatesRequestSchema as He,ListResourcesRequestSchema as Pe,ListToolsRequestSchema as Oe,McpError as X}from"@modelcontextprotocol/sdk/types.js";import{Redis as De}from"ioredis";let _=process.env.CACHLY_API_URL??"https://api.cachly.dev",x=Ke()??"";ce(x);const Bn=process.env.CACHLY_EMBED_MODEL??"",M=(()=>{try{const e=Lt(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"})(),Pt=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let B=$e(process.env.CACHLY_BRAIN_INSTANCE_ID),ee=0,ie=null,Me=!1;async function Ot(){let e=[];try{V.getClientCapabilities()?.roots&&(e=(await V.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Ho({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:Ne})}function ye(){return Me?!/^(0|false|off|no|nein)$/i.test((process.env.CACHLY_STARTWISSEN??"").trim()):!1}function Je(e){!e||!ye()||No({instanzId:e,verbindung:D,ausGit:t=>_e("brain_from_git",t,D,P),projektOrdner:Ot,einbetten:t=>zt(t,{geduld:"lang"}),hatEinbettung:qt,melde:t=>A("brain_from_git",{...x?{api_key:x}:{},instance_id:e,total:t,auto:"startwissen"})})}async function Dt(){if(!x)return"";try{const e=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${x}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(12e3)});if(e.ok){const t=await e.json(),n=t.instance?.id??t.instance_id;if(n)return n}else fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function Ye(){if(B)return B;if(!x)return"";if(ie)return ie;const e=Date.now();if(ee>0&&e-ee<3e4)return"";ee=e,ie=(async()=>{try{const t=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const s=(await t.json())?.data??[],o=s.find(r=>r.status==="running")??s.find(r=>r.status==="provisioning");if(o)return B=o.id,ee=0,B;const c=await Dt();if(c)return B=c,ee=0,Ve(c,ye()),we(c),Je(c),B}}catch{}return""})();try{return await ie}finally{ie=null}}let be=0;const Mt=6e4;let se="";async function ve(e){try{const{writeFile:t,mkdir:n,readFile:s}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:c,dirname:r}=await import("node:path"),a=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!a)return;const u=c(a,".claude","mcp.json");let d={};if(o(u))try{d=JSON.parse(await s(u,"utf-8"))}catch{}d.mcpServers??={};const l=d.mcpServers.cachly;if(l)l.env??={},l.env.CACHLY_JWT=e;else{const y={};y.CACHLY_JWT=e,d.mcpServers.cachly={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:y}}await n(r(u),{recursive:!0}),await t(u,JSON.stringify(d,null,2),"utf-8");const g=[c(a,".cursor","mcp.json"),c(a,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(g.map(async y=>{if(o(y))try{const v=await s(y,"utf-8"),h=JSON.parse(v),p=h?.mcpServers?.cachly;p?.env&&(p.env.CACHLY_JWT=e,await t(y,JSON.stringify(h,null,2),"utf-8"))}catch{}}))}catch{}}async function we(e){if(e){So(e,{apiKey:x});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o}=await import("node:path"),c=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!c)return;const r=[o(c,".claude","mcp.json"),o(c,".cursor","mcp.json"),o(c,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(s(a))try{const u=JSON.parse(await n(a,"utf-8")),d=u?.mcpServers?.cachly;d?.env&&(d.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(a,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}}async function Jt(){try{const e=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`},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?(x=t.key,ce(t.key),ve(t.key),A("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function xe(){const e=fe(x),t=Ie(e);if(t==="none")return se="",!0;if(t==="refresh"){const n=Date.now();return n-be>=Mt&&(be=n,await Jt())?(se="",!0):(se=e.message,e.usable)}return se=e.message,!1}function ae(e,t){const n=(o,c)=>{try{t?.(o,c)}catch{}},s=o=>{o?n(!1,o.code??o.message):n(!0)};try{process.platform==="win32"?he("cmd",["/c","start","",e],{windowsHide:!0},s):process.platform==="darwin"?he("open",[e],s):he("xdg-open",[e],s)}catch(o){n(!1,o instanceof Error?o.message:"unknown")}}let G=null;async function Yt(){try{const e=await fetch(`${_}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(e.ok){const t=await e.json(),n=t.verification_uri||R("/device","ambient-signin"),s=`${n}${n.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:s,pollInterval:(t.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}}catch{}try{const t=await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/auth/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id=cachly-cli&scope=openid",signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;const n=await t.json();return{deviceCode:n.device_code,userCode:n.user_code,verifyUrl:n.verification_uri_complete,pollInterval:(n.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}catch{return null}}async function Ut(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const s=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e.deviceCode}),signal:AbortSignal.timeout(8e3)});return s.ok?s.json():null},n=async()=>(await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`client_id=cachly-cli&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=${e.deviceCode}`,signal:AbortSignal.timeout(8e3)})).json();try{let s=await t().catch(()=>null);if(s||(s=await n().catch(()=>null)),!s)return"pending";if(s.access_token){let o=s.access_token;try{const c=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(c.ok){const r=await c.json();r.key&&(o=r.key)}}catch{}if(x=o,ce(o),G=null,A("device_flow_completed"),ve(o),K(o),ee=0,await Ye(),B)try{const c=await fetch(`${_}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"},signal:AbortSignal.timeout(4e3)});if(c.ok){const r=await c.json();if(r.status==="provisioning"){const a=Date.now()+2e4;for(;r.status==="provisioning"&&Date.now()<a;){await new Promise(d=>setTimeout(d,Ro));const u=await fetch(`${_}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"},signal:AbortSignal.timeout(4e3)}).catch(()=>null);if(u?.ok){const d=await u.json();r.status=d.status}else break}}}}catch{}return B&&we(B),"done"}return s.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function Ue(e){if(e.polling)return"pending";e.polling=!0;try{return await Ut(e)}finally{e.polling=!1}}function Wt(e,t=Ue,n=o=>G===o,s=Ft){const o=async()=>{if(!n(e))return;let c="pending";try{c=await t(e)}catch{}if(c!=="done"){if(c==="expired"){n(e)&&(G=null);return}n(e)&&s(o,e.pollInterval)}};s(o,e.pollInterval)}function Ft(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as ce,computeEmbedding as zt,hasEmbedProvider as qt}from"./embeddings.js";import{tokenize as Gt,splitMultiQuery as Kt,levenshtein as Vt,recencyBoost as Zt,extractTimestamp as Qt,STOPWORDS as Xt,katakanaToRomaji as eo,arabicLightStem as to,expandCrossLingual as oo,CROSS_LINGUAL_MAP as no,ZERO_RESULTS_LOG as so,zeroResultsTotal as ro}from"./search.js";const te=new Map;function io(e){return e<=1?200:null}async function D(e){if(!e)throw new X(ne.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
2
+ import{setzeClientKennung as At}from"./herkunft.js";import{jwtExpiryMs as Ct,checkJwt as St,handleApiError as kt,diagnoseAuth as ve,planAuthHeal as Ee,readClientCredentialsFromEnv as Tt,buildClientCredentialsBody as It,clientCredentialsTokenUrl as Et}from"./auth.js";import{cachlyUrl as R}from"./cachly-url.js";import{nutzungsSchluessel as Rt}from"./werkzeug-nutzung.js";import{istLieferung as Nt,lieferSchluessel as Lt,tokenDerAntwort as Bt,hatTreffer as jt,trefferSchluessel as Re}from"./geliefert.js";import{notify as Ne}from"./notifier.js";import{fileURLToPath as Le}from"node:url";import{createRequire as Pt}from"node:module";import{execFile as we}from"node:child_process";const Ht=process.argv[1]!=null&&(process.argv[1]===Le(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as Be}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Ot}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as Dt}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as je,ErrorCode as oe,ListPromptsRequestSchema as Pe,ListResourceTemplatesRequestSchema as He,ListResourcesRequestSchema as Oe,ListToolsRequestSchema as De,McpError as Q}from"@modelcontextprotocol/sdk/types.js";import{Redis as Me}from"ioredis";let _=process.env.CACHLY_API_URL??"https://api.cachly.dev",x=Ve()??"";ce(x);const Kn=process.env.CACHLY_EMBED_MODEL??"",M=(()=>{try{const e=Pt(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"})(),Mt=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let B=Ce(process.env.CACHLY_BRAIN_INSTANCE_ID),X=0,ae=null,Je=!1;async function Jt(){let e=[];try{G.getClientCapabilities()?.roots&&(e=(await G.listRoots(void 0,{timeout:3e3})).roots)}catch{}return Ko({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:Le})}function xe(){return Je?!/^(0|false|off|no|nein)$/i.test((process.env.CACHLY_STARTWISSEN??"").trim()):!1}function Ye(e){!e||!xe()||Wo({instanzId:e,verbindung:D,ausGit:t=>Ae("brain_from_git",t,D,H),projektOrdner:Jt,einbetten:t=>Gt(t,{geduld:"lang"}),hatEinbettung:Vt,melde:t=>C("brain_from_git",{...x?{api_key:x}:{},instance_id:e,total:t,auto:"startwissen"})})}async function Yt(){if(!x)return"";try{const e=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${x}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(12e3)});if(e.ok){const t=await e.json(),n=t.instance?.id??t.instance_id;if(n)return n}else fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`},body:JSON.stringify({event:"auto_provision_failed",status:e.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function Ue(){if(B)return B;if(!x)return"";if(ae)return ae;const e=Date.now();if(X>0&&e-X<3e4)return"";X=e,ae=(async()=>{try{const t=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const s=(await t.json())?.data??[],o=s.find(i=>i.status==="running")??s.find(i=>i.status==="provisioning");if(o)return B=o.id,X=0,B;const c=await Yt();if(c)return B=c,X=0,Xe(c,xe()),me(c),Ye(c),B}}catch{}return""})();try{return await ae}finally{ae=null}}let _e=0;const Ut=6e4;let ne="";async function ue(e){try{const{writeFile:t,mkdir:n,readFile:s}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:c,dirname:i}=await import("node:path"),a=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!a)return;const m=c(a,".claude","mcp.json");let d={};if(o(m))try{d=JSON.parse(await s(m,"utf-8"))}catch{}d.mcpServers??={};const l=d.mcpServers.cachly;if(l)l.env??={},l.env.CACHLY_JWT=e;else{const y={};y.CACHLY_JWT=e,d.mcpServers.cachly={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:y}}await n(i(m),{recursive:!0}),await t(m,JSON.stringify(d,null,2),"utf-8");const p=[c(a,".cursor","mcp.json"),c(a,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(p.map(async y=>{if(o(y))try{const w=await s(y,"utf-8"),f=JSON.parse(w),u=f?.mcpServers?.cachly;u?.env&&(u.env.CACHLY_JWT=e,await t(y,JSON.stringify(f,null,2),"utf-8"))}catch{}}))}catch{}}async function me(e){if(e){Ze(e,{apiKey:x});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o}=await import("node:path"),c=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!c)return;const i=[o(c,".claude","mcp.json"),o(c,".cursor","mcp.json"),o(c,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(i.map(async a=>{if(s(a))try{const m=JSON.parse(await n(a,"utf-8")),d=m?.mcpServers?.cachly;d?.env&&(d.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(a,JSON.stringify(m,null,2),"utf-8"))}catch{}}))}catch{}}}async function Wt(){try{const e=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`},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?(x=t.key,ce(t.key),ue(t.key),C("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function $e(){const e=ve(x),t=Ee(e);if(t==="none")return ne="",!0;if(t==="refresh"){const n=Date.now();return n-_e>=Ut&&(_e=n,await Wt())?(ne="",!0):(ne=e.message,e.usable)}return ne=e.message,!1}function se(e,t){const n=(o,c)=>{try{t?.(o,c)}catch{}},s=o=>{o?n(!1,o.code??o.message):n(!0)};try{process.platform==="win32"?we("cmd",["/c","start","",e],{windowsHide:!0},s):process.platform==="darwin"?we("open",[e],s):we("xdg-open",[e],s)}catch(o){n(!1,o instanceof Error?o.message:"unknown")}}let K=null;async function Ft(){try{const e=await fetch(`${_}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(e.ok){const t=await e.json(),n=t.verification_uri||R("/device","ambient-signin"),s=`${n}${n.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:s,pollInterval:(t.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}}catch{}try{const t=await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/auth/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id=cachly-cli&scope=openid",signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;const n=await t.json();return{deviceCode:n.device_code,userCode:n.user_code,verifyUrl:n.verification_uri_complete,pollInterval:(n.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}catch{return null}}async function zt(e){if(Date.now()>e.deadline)return"expired";const t=async()=>{const s=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:e.deviceCode}),signal:AbortSignal.timeout(8e3)});return s.ok?s.json():null},n=async()=>(await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`client_id=cachly-cli&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=${e.deviceCode}`,signal:AbortSignal.timeout(8e3)})).json();try{let s=await t().catch(()=>null);if(s||(s=await n().catch(()=>null)),!s)return"pending";if(s.access_token){let o=s.access_token;try{const c=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({name:"cachly-mcp-smithery",scope:"read_write"}),signal:AbortSignal.timeout(8e3)});if(c.ok){const i=await c.json();i.key&&(o=i.key)}}catch{}if(x=o,ce(o),K=null,C("device_flow_completed"),ue(o),re(o),X=0,await Ue(),B)try{const c=await fetch(`${_}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"},signal:AbortSignal.timeout(4e3)});if(c.ok){const i=await c.json();if(i.status==="provisioning"){const a=Date.now()+2e4;for(;i.status==="provisioning"&&Date.now()<a;){await new Promise(d=>setTimeout(d,Uo));const m=await fetch(`${_}/api/v1/instances/${B}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"},signal:AbortSignal.timeout(4e3)}).catch(()=>null);if(m?.ok){const d=await m.json();i.status=d.status}else break}}}}catch{}return B&&me(B),"done"}return s.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function We(e){if(e.polling)return"pending";e.polling=!0;try{return await zt(e)}finally{e.polling=!1}}function qt(e,t=We,n=o=>K===o,s=Kt){const o=async()=>{if(!n(e))return;let c="pending";try{c=await t(e)}catch{}if(c!=="done"){if(c==="expired"){n(e)&&(K=null);return}n(e)&&s(o,e.pollInterval)}};s(o,e.pollInterval)}function Kt(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as ce,computeEmbedding as Gt,hasEmbedProvider as Vt}from"./embeddings.js";import{tokenize as Zt,splitMultiQuery as Qt,levenshtein as Xt,recencyBoost as eo,extractTimestamp as to,STOPWORDS as oo,katakanaToRomaji as no,arabicLightStem as so,expandCrossLingual as ro,CROSS_LINGUAL_MAP as io,ZERO_RESULTS_LOG as ao,zeroResultsTotal as co}from"./search.js";const ee=new Map;function lo(e){return e<=1?200:null}async function D(e){if(!e)throw new Q(oe.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=te.get(e);return t||Eo(ao,e,()=>co(e))}const ao=new Map;async function co(e){W("verbindung: Instanz abfragen");let t=await P(`/api/v1/instances/${e}`);if(W(`verbindung: Instanz ${t.status}`),t=await Io(t,()=>P(`/api/v1/instances/${e}`),{fristMs:Pt,melde:r=>W(`verbindung: Instanz ${r.status}`)}),t.status!=="running"){fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...x?{Authorization:`Bearer ${x}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:t.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let r;throw t.status==="provisioning"?r=`\u23F3 Brain instance "${t.name}" is still starting up.
9
+ \u2022 Reach us at support@cachly.dev.`);const t=ee.get(e);return t||Yo(po,e,()=>uo(e))}const po=new Map;async function uo(e){W("verbindung: Instanz abfragen");let t=await H(`/api/v1/instances/${e}`);if(W(`verbindung: Instanz ${t.status}`),t=await Jo(t,()=>H(`/api/v1/instances/${e}`),{fristMs:Mt,melde:i=>W(`verbindung: Instanz ${i.status}`)}),t.status!=="running"){fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...x?{Authorization:`Bearer ${x}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:t.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let i;throw t.status==="provisioning"?i=`\u23F3 Brain instance "${t.name}" is still starting up.
10
10
 
11
- First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:t.status==="failed"?r=`\u274C Brain instance "${t.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.`:t.status==="failed"?i=`\u274C Brain instance "${t.name}" failed to start.
12
12
 
13
13
  Our system will retry automatically. Check status at: ${R("/instances","instance-error")}
14
- If this persists, contact support@cachly.dev.`:t.status==="suspended"?r=`\u23F8 Brain instance "${t.name}" is suspended (billing issue).
14
+ If this persists, contact support@cachly.dev.`:t.status==="suspended"?i=`\u23F8 Brain instance "${t.name}" is suspended (billing issue).
15
15
 
16
- Update your payment method at: ${R("/billing","upgrade")}`:t.status==="pending_payment"?r=`\u{1F4B3} Brain instance "${t.name}" is waiting for payment.
16
+ Update your payment method at: ${R("/billing","upgrade")}`:t.status==="pending_payment"?i=`\u{1F4B3} Brain instance "${t.name}" is waiting for payment.
17
17
 
18
- Complete your checkout at: ${R("/instances","upgrade")}`:r=`Brain instance "${t.name}" is not reachable (status: ${t.status}).
18
+ Complete your checkout at: ${R("/instances","upgrade")}`:i=`Brain instance "${t.name}" is not reachable (status: ${t.status}).
19
19
 
20
20
  \u2022 View your instance at: ${R("/instances","instance-error")}
21
- \u2022 Run \`get_api_status\` for a full diagnostic.`,new X(ne.InvalidRequest,r)}if(!t.host||!t.port)throw new X(ne.InternalError,`Instance "${t.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let n,s=t.tls_enabled!==!1;try{const r=await P(`/api/v1/instances/${e}/connection`);n=r.password??void 0,s=r.tls_enabled!==!1,W("verbindung: Zugangsdaten da")}catch(r){const a=r instanceof Error?r.message:String(r);if(a.includes("401")||a.includes("403")||a.includes("Unauthorized"))throw new X(ne.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const o=new De({host:t.host,port:t.port,password:n||void 0,commandTimeout:8e3,...s?{tls:{}}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:io,maxRetriesPerRequest:1,keepAlive:15e3}),c=()=>{te.delete(e),o.disconnect()};o.on("error",c),o.on("end",c);try{await o.connect()}catch(r){o.disconnect();const a=r instanceof Error?r.message:String(r);throw fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...x?{Authorization:`Bearer ${x}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:t.host,port:t.port,error:a,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new X(ne.InternalError,`Could not reach Brain instance "${t.name}" (${t.host}:${t.port}).
21
+ \u2022 Run \`get_api_status\` for a full diagnostic.`,new Q(oe.InvalidRequest,i)}if(!t.host||!t.port)throw new Q(oe.InternalError,`Instance "${t.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);let n,s=t.tls_enabled!==!1;try{const i=await H(`/api/v1/instances/${e}/connection`);n=i.password??void 0,s=i.tls_enabled!==!1,W("verbindung: Zugangsdaten da")}catch(i){const a=i instanceof Error?i.message:String(i);if(a.includes("401")||a.includes("403")||a.includes("Unauthorized"))throw new Q(oe.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const o=new Me({host:t.host,port:t.port,password:n||void 0,commandTimeout:8e3,...s?{tls:{}}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:lo,maxRetriesPerRequest:1,keepAlive:15e3}),c=()=>{ee.delete(e),o.disconnect()};o.on("error",c),o.on("end",c);try{await o.connect()}catch(i){o.disconnect();const a=i instanceof Error?i.message:String(i);throw fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...x?{Authorization:`Bearer ${x}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:t.host,port:t.port,error:a,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new Q(oe.InternalError,`Could not reach Brain instance "${t.name}" (${t.host}:${t.port}).
22
22
 
23
23
  \u2022 Check your network connection
24
24
  \u2022 Run \`get_api_status\` to verify instance status
25
- \u2022 Technical detail: ${a}`)}return te.set(e,o),W("verbindung: Valkey verbunden"),o}async function P(e,t={},n=!1){n||Ie(fe(x))!=="none"&&await xe(),$t(x);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),o=await fetch(`${_}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`,...t.headers}});if(!o.ok){if(o.status===401&&!n&&(be=0,await xe()))return P(e,t,!0);const r=(await o.json().catch(()=>({error:o.statusText}))).error??o.statusText;Ct(o.status,r)}if(o.status!==204)return o.json()}import{handleBrainTool as lo}from"./handlers/brain.js";import{handleContextTool as po}from"./handlers/context.js";import{handleInstanceTool as uo}from"./handlers/instances.js";import{handleCacheTool as mo}from"./handlers/cache.js";import{handleTeamTool as go}from"./handlers/team.js";import{handleRoadmapTool as fo}from"./handlers/roadmap.js";import{handleAdvancedTool as ho}from"./handlers/advanced.js";import{handleSyndicateTool as yo}from"./handlers/syndicate.js";import{handleFedbrainTool as _e,_lastBrainFromGitCounts as pe}from"./handlers/fedbrain.js";import{extractFirstRecallProof as bo,renderFirstRecallProof as vo}from"./first-recall-proof.js";import{installClsPostCommitHook as We,CLS_HOOK_VERSION as Fe}from"./cls-hook.js";import{installAmbientHooks as ze,AMBIENT_HOOK_VERSION as qe}from"./ambient-hooks.js";import{hookHauptlauf as wo,auffrischenHauptlauf as xo}from"./ambient-hook.js";import{rahmeAntwort as _o}from"./antwort-rahmen.js";import{appendLedgerEntry as $o,readLedger as Ge,defaultLedgerPath as Co,reportLedgerEntry as Ao}from"./ambient-ledger.js";import{resolveApiKey as Ke,saveApiKey as K,saveInstanceId as So}from"./credentials.js";import{holeSofortTest as ko}from"./sofort-test.js";import{sichereZugang as To,echterWert as $e}from"./zugang.js";import{zeitpunkt as W}from"./zeitmessung.js";import{warteAufLaufendeInstanz as Io,gemeinsamerAufbau as Eo,PROVISION_TAKT_MS as Ro}from"./instanz-warten.js";import{merkeNeuesBrain as Ve}from"./leeres-brain.js";import{starteStartwissen as No,startwissenGestartet as Lo,beanspruchStartwissen as Bo,holeStartwissenHinweis as jo,waehleProjektOrdner as Ho}from"./startwissen.js";import{beiStdinEnde as Po}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Oo,starteBrandWachhund as Do}from"./brand-wachhund.js";import{sichtbareWerkzeuge as Mo,VERTEILER as Ze}from"./werkzeug-auswahl.js";import{buildLessonsMarkdown as Jo,buildLessonsJsonl as Yo,vonRohLektion as Uo}from"./brain-export.js";import{detectEditor as Wo}from"./editor.js";import{milestoneSent as Qe,markMilestoneSent as Xe}from"./funnel-milestones.js";import{kostprobeUebrig as Fo,kostprobeVerbrauchen as zo,kostprobeHinweis as qo,schrankeNachKostproben as Go}from"./kostprobe.js";import{netBalance as Ko}from"./ambient-recall.js";import{handleShareTool as et}from"./handlers/share.js";import{handleVizTool as Vo}from"./handlers/viz.js";import{commitArt as Zo,istRueckbau as Qo,zaehleLektionen as Xo}from"./commit-art.js";import{TOOLS as le}from"./tools.js";let tt=!1,ue=!1;function ot(){return Wo()}function en(e){if(!e)return null;const t=e.match(/\*\*💡\s+([^*]+)\*\*/),n=e.match(/^>\s+(.+)$/m);if(!t||!n)return null;const s=t[1].trim(),o=n[1].trim();return!s||!o?null:{topic:s,what:o}}function tn(e){try{const t=e.split(".");if(t.length!==3)return;const n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf-8"));if(!n.sub)return;let s=2166136261;for(let o=0;o<n.sub.length;o++)s^=n.sub.charCodeAt(o),s=s*16777619>>>0;return s.toString(16).padStart(8,"0")+n.sub.length.toString(16).padStart(4,"0")}catch{return}}function A(e,t,n){if(process.env.CACHLY_NO_TELEMETRY==="1")return;const s=x?tn(x):void 0;fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:e,version:M,editor:ot(),...x?{jwt:x}:{},...s?{user_fingerprint:s}:{},...n?{metrics:n}:{},...t}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}function on(e,t){return Ao({apiUrl:_,jwt:x,instanceId:e},t)}async function nn(e){if(!tt&&process.env.CACHLY_NO_TELEMETRY!=="1"){tt=!0;try{await fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:M,editor:ot(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const sn=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"]),rn={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."},nt=R("/billing","upgrade"),st=new Map;async function an(e){const t=st.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const s=((await P(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),o={tier:s,isFree:s==="free"||s===""};return st.set(e,{info:o,expiresAt:Date.now()+6e4}),o}catch{return{tier:"unknown",isFree:!1}}}async function cn(e,t){if(!sn.has(e)||!t)return null;const{isFree:n}=await an(t);if(!n)return null;const s=rn[e]??"A Premium intelligence feature.";if(Fo(e)){const o=zo(e);return{kostprobe:qo(e,o,nt)}}return{sperre:Go(e,s,nt)}}async function ln(e,t){try{await(await D(e)).hincrby(Tt(e),t,1)}catch{}}async function dn(e,t,n){if(It(t))try{const s=await D(e),o=Nt(n);await s.incrby(Et(e),o?Rt(n):0),await s.hincrby(Ee(e),"abrufe",1),o&&await s.hincrby(Ee(e),"treffer",1)}catch{}}async function pn(e){const t=await Yt();return t?(G=t,A("device_flow_started",{tool:e}),ae(t.verifyUrl,(n,s)=>{if(n){A("device_browser_opened",{stelle:"tool"});return}A("device_browser_failed",{reason:s??"unknown",stelle:"tool"}),process.stderr.write(`
25
+ \u2022 Technical detail: ${a}`)}return ee.set(e,o),W("verbindung: Valkey verbunden"),o}async function H(e,t={},n=!1){n||Ee(ve(x))!=="none"&&await $e(),St(x);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),o=await fetch(`${_}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`,...t.headers}});if(!o.ok){if(o.status===401&&!n&&(_e=0,await $e()))return H(e,t,!0);const i=(await o.json().catch(()=>({error:o.statusText}))).error??o.statusText;kt(o.status,i)}if(o.status!==204)return o.json()}import{handleBrainTool as mo}from"./handlers/brain.js";import{handleContextTool as go}from"./handlers/context.js";import{handleInstanceTool as fo}from"./handlers/instances.js";import{handleCacheTool as ho}from"./handlers/cache.js";import{handleTeamTool as yo}from"./handlers/team.js";import{handleRoadmapTool as bo}from"./handlers/roadmap.js";import{handleAdvancedTool as vo}from"./handlers/advanced.js";import{handleSyndicateTool as wo}from"./handlers/syndicate.js";import{handleFedbrainTool as Ae,_lastBrainFromGitCounts as ge}from"./handlers/fedbrain.js";import{extractFirstRecallProof as xo,renderFirstRecallProof as _o}from"./first-recall-proof.js";import{installClsPostCommitHook as Fe,CLS_HOOK_VERSION as ze}from"./cls-hook.js";import{installAmbientHooks as qe,AMBIENT_HOOK_VERSION as Ke}from"./ambient-hooks.js";import{hookHauptlauf as $o,auffrischenHauptlauf as Ao}from"./ambient-hook.js";import{rahmeAntwort as Co}from"./antwort-rahmen.js";import{appendLedgerEntry as So,readLedger as Ge,defaultLedgerPath as ko,reportLedgerEntry as To}from"./ambient-ledger.js";import{resolveApiKey as Ve,saveApiKey as re,saveInstanceId as Ze,readSavedApiKey as Io}from"./credentials.js";import{KEYCLOAK_BASIS as Qe,istTestSchluessel as Eo,waehleTestSchluessel as Ro,starteKeycloakAnmeldung as No,warteAufKeycloakAnmeldung as Lo,uebernimm as Bo,brainImKonto as jo,erfolgsText as Po,fehlerText as Ho,ersetzeSchluessel as Oo}from"./uebernahme.js";import{holeSofortTest as Do}from"./sofort-test.js";import{sichereZugang as Mo,echterWert as Ce}from"./zugang.js";import{zeitpunkt as W}from"./zeitmessung.js";import{warteAufLaufendeInstanz as Jo,gemeinsamerAufbau as Yo,PROVISION_TAKT_MS as Uo}from"./instanz-warten.js";import{merkeNeuesBrain as Xe}from"./leeres-brain.js";import{starteStartwissen as Wo,startwissenGestartet as Fo,beanspruchStartwissen as zo,holeStartwissenHinweis as qo,waehleProjektOrdner as Ko}from"./startwissen.js";import{pruefeNeueFassung as Go,holeNeueFassungHinweis as Vo}from"./neue-fassung.js";import{beiStdinEnde as Zo}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Qo,starteBrandWachhund as Xo}from"./brand-wachhund.js";import{sichtbareWerkzeuge as en,VERTEILER as et}from"./werkzeug-auswahl.js";import{buildLessonsMarkdown as tn,buildLessonsJsonl as on,vonRohLektion as nn}from"./brain-export.js";import{detectEditor as sn}from"./editor.js";import{milestoneSent as tt,markMilestoneSent as ot}from"./funnel-milestones.js";import{kostprobeUebrig as rn,kostprobeVerbrauchen as an,kostprobeHinweis as cn,schrankeNachKostproben as ln}from"./kostprobe.js";import{netBalance as dn}from"./ambient-recall.js";import{handleShareTool as nt}from"./handlers/share.js";import{handleVizTool as pn}from"./handlers/viz.js";import{commitArt as un,istRueckbau as mn,zaehleLektionen as gn}from"./commit-art.js";import{TOOLS as le}from"./tools.js";let st=!1,fe=!1;function rt(){return sn()}function fn(e){if(!e)return null;const t=e.match(/\*\*💡\s+([^*]+)\*\*/),n=e.match(/^>\s+(.+)$/m);if(!t||!n)return null;const s=t[1].trim(),o=n[1].trim();return!s||!o?null:{topic:s,what:o}}function hn(e){try{const t=e.split(".");if(t.length!==3)return;const n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf-8"));if(!n.sub)return;let s=2166136261;for(let o=0;o<n.sub.length;o++)s^=n.sub.charCodeAt(o),s=s*16777619>>>0;return s.toString(16).padStart(8,"0")+n.sub.length.toString(16).padStart(4,"0")}catch{return}}function C(e,t,n){if(process.env.CACHLY_NO_TELEMETRY==="1")return;const s=x?hn(x):void 0;fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:e,version:M,editor:rt(),...x?{jwt:x}:{},...s?{user_fingerprint:s}:{},...n?{metrics:n}:{},...t}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}function yn(e,t){return To({apiUrl:_,jwt:x,instanceId:e},t)}async function bn(e){if(!st&&process.env.CACHLY_NO_TELEMETRY!=="1"){st=!0;try{await fetch(`${_}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:M,editor:rt(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const vn=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"]),wn={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."},it=R("/billing","upgrade"),at=new Map;async function xn(e){const t=at.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const s=((await H(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),o={tier:s,isFree:s==="free"||s===""};return at.set(e,{info:o,expiresAt:Date.now()+6e4}),o}catch{return{tier:"unknown",isFree:!1}}}async function _n(e,t){if(!vn.has(e)||!t)return null;const{isFree:n}=await xn(t);if(!n)return null;const s=wn[e]??"A Premium intelligence feature.";if(rn(e)){const o=an(e);return{kostprobe:cn(e,o,it)}}return{sperre:ln(e,s,it)}}async function $n(e,t){try{await(await D(e)).hincrby(Rt(e),t,1)}catch{}}async function An(e,t,n){if(Nt(t))try{const s=await D(e),o=jt(n);await s.incrby(Lt(e),o?Bt(n):0),await s.hincrby(Re(e),"abrufe",1),o&&await s.hincrby(Re(e),"treffer",1)}catch{}}async function Cn(e){const t=await Ft();return t?(K=t,C("device_flow_started",{tool:e}),se(t.verifyUrl,(n,s)=>{if(n){C("device_browser_opened",{stelle:"tool"});return}C("device_browser_failed",{reason:s??"unknown",stelle:"tool"}),process.stderr.write(`
26
26
  cachly: could not open a browser (${s??"unknown"}).
27
27
  cachly: open this yourself to finish signing in:
28
28
  cachly: ${t.verifyUrl}
29
29
  cachly: code ${t.userCode}
30
30
 
31
- `)}),Wt(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(`
31
+ `)}),qt(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: ${R("/setup-ai","ambient-signin")}`,"","\u2728 Free tier includes: 1 Brain instance, persistent memory, semantic search."].join(`
33
- `)}async function un(e){if(!e)return!0;if(Lo(e))return!1;try{return await Bo(await D(e),"sitzungsstart")}catch{return!0}}async function U(e,t){if(!x){if(nn(e),G){const i=await Ue(G);return i==="done"?U(e,t):i==="expired"?(A("device_flow_failed",{reason:"timeout"}),G=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: **${G.verifyUrl}**`,`Code: **${G.userCode}**`,"","This completes automatically once you sign in \u2014 no need to come back here."].join(`
34
- `)}return To({schluessel:x,konfigurierteInstanz:B,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{W("sofort-test: Anfang");const i=await ko({apiUrl:_,version:M,speichern:()=>{}});return W(`sofort-test: ${i?"Brain angelegt":"kein Test"}`),i&&Ve(i.instanzId,ye()),i},ablagen:{setzeSchluessel:i=>{x=i},setEmbedJwt:ce,saveApiKey:i=>K(i),persistApiKeyToConfig:ve,merkeInstanz:i=>{B=i,ee=0},persistInstanceIdToConfig:we},meldeEreignis:A,werkzeug:()=>U(e,t),anmelden:()=>pn(e),neuesBrain:Je})}if(!t.instance_id){const i=await Ye();i&&(t={...t,instance_id:i})}const n=await cn(e,t.instance_id);let s="";if(n!==null){if("sperre"in n)return A("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;s=n.kostprobe,A("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&ln(t.instance_id,e),W(`werkzeug ${e}: Zugang und Tarif geklaert`);const o=await lo(e,t,D,P);if(W(`werkzeug ${e}: Brain-Werkzeug fertig`),o!==null){typeof t.instance_id=="string"&&t.instance_id&&dn(t.instance_id,e,String(o??"")),!ue&&x&&(ue=!0,Qe("first_call_success")||(Xe("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??B??""})));const i=t.instance_id??B??"",w=x?{api_key:x,instance_id:i}:{instance_id:i};if(e==="recall_best_solution")A("recall_best_solution",w);else if(e==="learn_from_attempts")A("learn_from_attempts",w);else if(e==="session_start"){A("session_start",w,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const f=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),N=f.includes("Welcome! Your AI Brain is live.");if(!N&&f.length>100)A("recall_best_solution",w);else if(N&&t.workspace_path&&await un(i))try{const j=await _e("brain_from_git",{instance_id:i,repo_path:t.workspace_path,limit:50},D,P);if(j!==null){A("brain_from_git",{...w,...pe??{}}),A("recall_best_solution",w);let $="";if((pe?.total??0)===0)try{const b=await et("brain_seed_starter",{instance_id:i},D,P);b&&(A("brain_seed_starter",{...w,auto:!0},{seeded_count:16,auto:!0}),$=`
33
+ `)}async function Sn(e){if(!e)return!0;if(Fo(e))return!1;try{return await zo(await D(e),"sitzungsstart")}catch{return!0}}async function U(e,t){if(!x){if(bn(e),K){const r=await We(K);return r==="done"?U(e,t):r==="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 Mo({schluessel:x,konfigurierteInstanz:B,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{W("sofort-test: Anfang");const r=await Do({apiUrl:_,version:M,speichern:()=>{}});return W(`sofort-test: ${r?"Brain angelegt":"kein Test"}`),r&&Xe(r.instanzId,xe()),r},ablagen:{setzeSchluessel:r=>{x=r},setEmbedJwt:ce,saveApiKey:r=>re(r),persistApiKeyToConfig:ue,merkeInstanz:r=>{B=r,X=0},persistInstanceIdToConfig:me},meldeEreignis:C,werkzeug:()=>U(e,t),anmelden:()=>Cn(e),neuesBrain:Ye})}if(!t.instance_id){const r=await Ue();r&&(t={...t,instance_id:r})}const n=await _n(e,t.instance_id);let s="";if(n!==null){if("sperre"in n)return C("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;s=n.kostprobe,C("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&$n(t.instance_id,e),W(`werkzeug ${e}: Zugang und Tarif geklaert`);const o=await mo(e,t,D,H);if(W(`werkzeug ${e}: Brain-Werkzeug fertig`),o!==null){typeof t.instance_id=="string"&&t.instance_id&&An(t.instance_id,e,String(o??"")),!fe&&x&&(fe=!0,tt("first_call_success")||(ot("first_call_success"),C("first_call_success",{tool:e,instance_id:t.instance_id??B??""})));const r=t.instance_id??B??"",b=x?{api_key:x,instance_id:r}:{instance_id:r};if(e==="recall_best_solution")C("recall_best_solution",b);else if(e==="learn_from_attempts")C("learn_from_attempts",b);else if(e==="session_start"){C("session_start",b,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const h=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),N=h.includes("Welcome! Your AI Brain is live.");if(!N&&h.length>100)C("recall_best_solution",b);else if(N&&t.workspace_path&&await Sn(r))try{const j=await Ae("brain_from_git",{instance_id:r,repo_path:t.workspace_path,limit:50},D,H);if(j!==null){C("brain_from_git",{...b,...ge??{}}),C("recall_best_solution",b);let $="";if((ge?.total??0)===0)try{const v=await nt("brain_seed_starter",{instance_id:r},D,H);v&&(C("brain_seed_starter",{...b,auto:!0},{seeded_count:16,auto:!0}),$=`
35
35
  ---
36
- `+String(b))}catch{}const k=String(j),T=pe?.total??0,H=T>0?`
37
- \u2705 **Brain bootstrapped from git \u2014 ${T} lesson${T===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(k||$||H)return String(o)+H+`
36
+ `+String(v))}catch{}const k=String(j),T=ge?.total??0,P=T>0?`
37
+ \u2705 **Brain bootstrapped from git \u2014 ${T} lesson${T===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(k||$||P)return String(o)+P+`
38
38
  ---
39
- `+k+$}}catch(j){return A("brain_from_git_failed",{...w,reason:j instanceof Error?j.message.slice(0,120):"unknown"}),String(o)+`
39
+ `+k+$}}catch(j){return C("brain_from_git_failed",{...b,reason:j instanceof Error?j.message.slice(0,120):"unknown"}),String(o)+`
40
40
 
41
41
  > \u26A0\uFE0F **Auto-bootstrap from git history failed** \u2014 your Brain is live but starts empty.
42
- > Run \`brain_from_git(instance_id="`+i+'", repo_path="'+String(t.workspace_path)+'")` manually to seed it.\n> Or try `brain_seed_starter` to load 16 universal engineering lessons instantly.'}}else if(e==="session_end")A("session_end",w);else if(e==="smart_recall"){const f=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),N=f.length>50&&!f.includes("No lessons found")&&!f.includes("no lessons")&&!f.includes("No matches found");if(A("smart_recall",w,{hit:N,topic:String(t.query??"").slice(0,80)}),N&&A("recall_best_solution",w),se&&typeof o=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${se.split(`
42
+ > Run \`brain_from_git(instance_id="`+r+'", 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",b);else if(e==="smart_recall"){const h=typeof o=="object"&&o!==null&&"content"in o?JSON.stringify(o):String(o??""),N=h.length>50&&!h.includes("No lessons found")&&!h.includes("no lessons")&&!h.includes("No matches found");if(C("smart_recall",b,{hit:N,topic:String(t.query??"").slice(0,80)}),N&&C("recall_best_solution",b),ne&&typeof o=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${ne.split(`
43
43
  `)[0]}
44
44
 
45
- ${o}`}return o}const c=await po(e,t,D,P);if(c!==null)return!ue&&x&&(ue=!0,Qe("first_call_success")||(Xe("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??B??""}))),c;const r=await uo(e,t,D,P);if(r!==null)return r;const a=await mo(e,t,D,P);if(a!==null)return a;const u=i=>s?i+s:i,d=await go(e,t,D,P);if(d!==null)return u(d);const l=await fo(e,t,D,P);if(l!==null)return l;const g=await ho(e,t,D,P);if(g!==null)return u(g);const y=await yo(e,t,D,P);if(y!==null){if(e==="brain_predict"){const i=t.instance_id??B??"";A("brain_predict",x?{api_key:x,instance_id:i}:{instance_id:i})}return u(y)}const v=await et(e,t,D,P);if(v!==null)return v;const h=await Vo(e,t,D,P);if(h!==null)return h;const p=await _e(e,t,D,P);if(p!==null){const i=t.instance_id??B??"",w=x?{api_key:x,instance_id:i}:{instance_id:i};if(e==="brain_from_git"){const f=pe;A("brain_from_git",{...w,...f??{}},f?{fixes:f.fixes,features:f.features,refactors:f.refactors,total:f.total}:void 0)}else e==="brain_predict_failures"&&A("brain_predict_failures",w);return p}switch(e){case"get_api_status":{let i="unknown";try{const S=await fetch(`${_}/health`,{signal:AbortSignal.timeout(8e3)});if(S.ok){const $=await S.json();i=`${$.status??"ok"} (db: ${$.db??"?"})`}else i=`HTTP ${S.status}`}catch(S){i=`unreachable: ${S.message}`}if(!x)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${i}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${R("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
46
- `);let w="\u274C invalid JWT format";try{const S=x.split(".");if(S.length===3){const $=JSON.parse(Buffer.from(S[1],"base64url").toString("utf-8")),k=$.sub??"(unknown)",T=$.iss??"(unknown)",H=T.includes("keycloak")?"Keycloak":"OIDC",b=$.exp?new Date($.exp*1e3):null,I=b?b<new Date:!1;w=["\u2705 JWT decoded",` Sub (user ID): ${k}`,` Provider: ${H}`,` Issuer: ${T}`,` Expires: ${b?b.toISOString():"never"} ${I?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
47
- `)}}catch{w="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let f="";try{const $=(await P("/api/v1/instances")).data??[];if($.length===0)f=`
45
+ ${o}`}return o}const c=await go(e,t,D,H);if(c!==null)return!fe&&x&&(fe=!0,tt("first_call_success")||(ot("first_call_success"),C("first_call_success",{tool:e,instance_id:t.instance_id??B??""}))),c;const i=await fo(e,t,D,H);if(i!==null)return i;const a=await ho(e,t,D,H);if(a!==null)return a;const m=r=>s?r+s:r,d=await yo(e,t,D,H);if(d!==null)return m(d);const l=await bo(e,t,D,H);if(l!==null)return l;const p=await vo(e,t,D,H);if(p!==null)return m(p);const y=await wo(e,t,D,H);if(y!==null){if(e==="brain_predict"){const r=t.instance_id??B??"";C("brain_predict",x?{api_key:x,instance_id:r}:{instance_id:r})}return m(y)}const w=await nt(e,t,D,H);if(w!==null)return w;const f=await pn(e,t,D,H);if(f!==null)return f;const u=await Ae(e,t,D,H);if(u!==null){const r=t.instance_id??B??"",b=x?{api_key:x,instance_id:r}:{instance_id:r};if(e==="brain_from_git"){const h=ge;C("brain_from_git",{...b,...h??{}},h?{fixes:h.fixes,features:h.features,refactors:h.refactors,total:h.total}:void 0)}else e==="brain_predict_failures"&&C("brain_predict_failures",b);return u}switch(e){case"get_api_status":{let r="unknown";try{const S=await fetch(`${_}/health`,{signal:AbortSignal.timeout(8e3)});if(S.ok){const $=await S.json();r=`${$.status??"ok"} (db: ${$.db??"?"})`}else r=`HTTP ${S.status}`}catch(S){r=`unreachable: ${S.message}`}if(!x)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${r}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${R("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
46
+ `);let b="\u274C invalid JWT format";try{const S=x.split(".");if(S.length===3){const $=JSON.parse(Buffer.from(S[1],"base64url").toString("utf-8")),k=$.sub??"(unknown)",T=$.iss??"(unknown)",P=T.includes("keycloak")?"Keycloak":"OIDC",v=$.exp?new Date($.exp*1e3):null,I=v?v<new Date:!1;b=["\u2705 JWT decoded",` Sub (user ID): ${k}`,` Provider: ${P}`,` Issuer: ${T}`,` Expires: ${v?v.toISOString():"never"} ${I?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
47
+ `)}}catch{b="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let h="";try{const $=(await H("/api/v1/instances")).data??[];if($.length===0)h=`
48
48
 
49
49
  \u{1F9E0} **Brain Instances:** none \u2014 create one at ${R("/instances","api-status")}`;else{const k=[`
50
50
 
51
- \u{1F9E0} **Brain Instances:**`];for(const T of $){const H=T.status==="running"?"\u{1F7E2}":T.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",b=T.id===B?" \u2190 active":"";if(k.push(` ${H} **${T.name}** (\`${T.id}\`) \xB7 ${T.status}${b}`),T.status==="running"&&T.host){const I=te.get(T.id);if(I)try{await I.ping(),k.push(" \u{1F493} Redis: connected")}catch{k.push(" \u26A0\uFE0F Redis: pooled but ping failed \u2014 will reconnect on next use")}else k.push(" \u{1F4A4} Redis: not connected yet (connects on first tool use)")}else T.status==="provisioning"?k.push(" \u23F3 Still provisioning \u2014 check back in ~30 s"):T.status!=="running"&&k.push(` \u274C Not reachable (status: ${T.status})`)}f=k.join(`
52
- `)}}catch(S){f=`
51
+ \u{1F9E0} **Brain Instances:**`];for(const T of $){const P=T.status==="running"?"\u{1F7E2}":T.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",v=T.id===B?" \u2190 active":"";if(k.push(` ${P} **${T.name}** (\`${T.id}\`) \xB7 ${T.status}${v}`),T.status==="running"&&T.host){const I=ee.get(T.id);if(I)try{await I.ping(),k.push(" \u{1F493} Redis: connected")}catch{k.push(" \u26A0\uFE0F Redis: pooled but ping failed \u2014 will reconnect on next use")}else k.push(" \u{1F4A4} Redis: not connected yet (connects on first tool use)")}else T.status==="provisioning"?k.push(" \u23F3 Still provisioning \u2014 check back in ~30 s"):T.status!=="running"&&k.push(` \u274C Not reachable (status: ${T.status})`)}h=k.join(`
52
+ `)}}catch(S){h=`
53
53
 
54
- \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${S.message}`}await xe();const N=fe(x),j=N.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":N.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${N.expiresInMs?` (${Math.round(N.expiresInMs/36e5)}h left)`:""}`:N.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${N.message.split(`
55
- `)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${i}`,` ${j}`,"","\u{1F511} **Auth:**",w,f].join(`
56
- `)}default:throw new rt(`Unknown tool: ${e}`)}}class rt extends Error{}const it=`This project has a Cachly AI Brain \u2014 persistent, cross-session memory of past fixes, decisions, and gotchas for THIS codebase. Use it proactively; it makes you faster and stops you repeating known mistakes.
54
+ \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${S.message}`}await $e();const N=ve(x),j=N.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":N.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${N.expiresInMs?` (${Math.round(N.expiresInMs/36e5)}h left)`:""}`:N.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${N.message.split(`
55
+ `)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${_}`,` \u{1F493} Health: ${r}`,` ${j}`,"","\u{1F511} **Auth:**",b,h].join(`
56
+ `)}default:throw new ct(`Unknown tool: ${e}`)}}class ct extends Error{}const lt=`This project has a Cachly AI Brain \u2014 persistent, cross-session memory of past fixes, decisions, and gotchas for THIS codebase. Use it proactively; it makes you faster and stops you repeating known mistakes.
57
57
 
58
58
  - BEFORE a non-trivial task: call smart_recall with a short description of what you're about to do. If it returns lessons, apply them before researching from scratch.
59
59
  - WHEN debugging an error: call causal_trace with the exact error first \u2014 a known fix may already exist.
60
60
  - AFTER a fix, deploy, or discovery: call learn_from_attempts so the knowledge persists.
61
61
  - BEFORE a risky op (deploy, migration, dependency bump): call brain_predict.
62
62
 
63
- The Brain instance id comes from the CACHLY_BRAIN_INSTANCE_ID environment variable.`,at={tools:{},resources:{},prompts:{}},ct=async()=>{const{katalog:e,unbekannteKernnamen:t}=Mo(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function lt(){return{resources:[]}}async function dt(){return{resourceTemplates:[]}}async function pt(){return{prompts:[]}}function mn(e){e.setRequestHandler(Oe,ct),e.setRequestHandler(Be,gt),e.setRequestHandler(Pe,lt),e.setRequestHandler(He,dt),e.setRequestHandler(je,pt)}function gn(){const e=new Le({name:"cachly-mcp",version:M},{capabilities:at,instructions:it});return mn(e),ut(e),e}function ut(e){const t=e.oninitialized;e.oninitialized=()=>{try{const n=e.getClientVersion();xt(n?.name,n?.version)}catch{}t?.()}}const V=new Le({name:"cachly-mcp",version:M},{capabilities:at,instructions:it});ut(V),V.setRequestHandler(Oe,ct),V.setRequestHandler(Pe,lt),V.setRequestHandler(He,dt),V.setRequestHandler(je,pt);let Ce=null,de=!1,Z=null,mt=0;async function fn(e){if(!de){if(Z){await Z;return}if(Z=(async()=>{de=!0,Ce=e;try{await U("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{Z=null}})(),await Z,process.env.CACHLY_AUTO_INDEX!=="false")try{const t=await D(e),n=await t.get(`cachly:index:last_indexed:${e}`),s=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>s)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),U("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code"}).catch(()=>{}))}catch{}}}async function Ae(){if(!(!de||!Ce)){de=!1;try{await U("session_end",{instance_id:Ce,summary:`Auto-ended after ${mt} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const gt=async e=>{let{name:t,arguments:n}=e.params;if(t===Ze){const o=n??{},c=typeof o.tool=="string"?o.tool:"";if(!c)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const r=le.find(a=>a.name===c);if(!r)return{content:[{type:"text",text:`Kein Werkzeug namens "${c}". Die Liste steht in der Beschreibung von ${Ze}.`}],isError:!0};if(o.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:r.name,description:r.description,inputSchema:r.inputSchema},null,2)}]};t=c,n=o.arguments??{}}const s=new Set(["session_start","session_start_summary","session_end","auto_learn_session"]);if(!s.has(t)&&!de&&!Z){const o=$e(n?.instance_id)||B||$e(process.env.CACHLY_BRAIN_INSTANCE_ID);o&&await fn(o).catch(()=>{})}else Z&&await Z.catch(()=>{});s.has(t)||mt++;try{Oo(),W(`werkzeug ${t}: Anfang`);const o=await U(t,n??{});return W(`werkzeug ${t}: Antwort fertig`),{content:[{type:"text",text:_o(t,o)+jo()}]}}catch(o){if(o instanceof rt)return{content:[{type:"text",text:o.message}],isError:!0};if(o instanceof X)throw o;const c=o.message??String(o);throw Re("cachly","tool_error",{tool:t,error:c}).catch(()=>{}),new X(ne.InternalError,c)}};V.setRequestHandler(Be,gt),process.on("SIGTERM",async()=>{await Ae().catch(()=>{});for(const[,e]of te)await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await Ae().catch(()=>{});for(const[,e]of te)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}
63
+ The Brain instance id comes from the CACHLY_BRAIN_INSTANCE_ID environment variable.`,dt={tools:{},resources:{},prompts:{}},pt=async()=>{const{katalog:e,unbekannteKernnamen:t}=en(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function ut(){return{resources:[]}}async function mt(){return{resourceTemplates:[]}}async function gt(){return{prompts:[]}}function kn(e){e.setRequestHandler(De,pt),e.setRequestHandler(je,yt),e.setRequestHandler(Oe,ut),e.setRequestHandler(He,mt),e.setRequestHandler(Pe,gt)}function Tn(){const e=new Be({name:"cachly-mcp",version:M},{capabilities:dt,instructions:lt});return kn(e),ft(e),e}function ft(e){const t=e.oninitialized;e.oninitialized=()=>{try{const n=e.getClientVersion();At(n?.name,n?.version)}catch{}t?.()}}const G=new Be({name:"cachly-mcp",version:M},{capabilities:dt,instructions:lt});ft(G),G.setRequestHandler(De,pt),G.setRequestHandler(Oe,ut),G.setRequestHandler(He,mt),G.setRequestHandler(Pe,gt);let Se=null,de=!1,V=null,ht=0;async function In(e){if(!de){if(V){await V;return}if(V=(async()=>{de=!0,Se=e;try{await U("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{V=null}})(),await V,process.env.CACHLY_AUTO_INDEX!=="false")try{const t=await D(e),n=await t.get(`cachly:index:last_indexed:${e}`),s=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>s)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),U("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code"}).catch(()=>{}))}catch{}}}async function ke(){if(!(!de||!Se)){de=!1;try{await U("session_end",{instance_id:Se,summary:`Auto-ended after ${ht} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const yt=async e=>{let{name:t,arguments:n}=e.params;if(t===et){const o=n??{},c=typeof o.tool=="string"?o.tool:"";if(!c)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const i=le.find(a=>a.name===c);if(!i)return{content:[{type:"text",text:`Kein Werkzeug namens "${c}". Die Liste steht in der Beschreibung von ${et}.`}],isError:!0};if(o.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:i.name,description:i.description,inputSchema:i.inputSchema},null,2)}]};t=c,n=o.arguments??{}}const s=new Set(["session_start","session_start_summary","session_end","auto_learn_session"]);if(!s.has(t)&&!de&&!V){const o=Ce(n?.instance_id)||B||Ce(process.env.CACHLY_BRAIN_INSTANCE_ID);o&&await In(o).catch(()=>{})}else V&&await V.catch(()=>{});s.has(t)||ht++;try{Qo(),W(`werkzeug ${t}: Anfang`);const o=await U(t,n??{});return W(`werkzeug ${t}: Antwort fertig`),{content:[{type:"text",text:Co(t,o)+qo()+Vo(t)}]}}catch(o){if(o instanceof ct)return{content:[{type:"text",text:o.message}],isError:!0};if(o instanceof Q)throw o;const c=o.message??String(o);throw Ne("cachly","tool_error",{tool:t,error:c}).catch(()=>{}),new Q(oe.InternalError,c)}};G.setRequestHandler(je,yt),process.on("SIGTERM",async()=>{await ke().catch(()=>{});for(const[,e]of ee)await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await ke().catch(()=>{});for(const[,e]of ee)await e.quit().catch(()=>{});process.exit(0)}),process.on("unhandledRejection",e=>{const t=e instanceof Error?e.message:String(e);process.stderr.write(`[cachly-mcp] unhandledRejection: ${t}
64
64
  `)}),process.on("uncaughtException",e=>{process.stderr.write(`[cachly-mcp] uncaughtException: ${e?.stack??String(e)}
65
- `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});const Se={claude:".mcp.json",cursor:".cursor/mcp.json",windsurf:".windsurf/mcp.json",copilot:".vscode/mcp.json",continue:".continue/config.json",cline:".vscode/mcp.json",zed:".zed/settings.json"},ke="<!-- cachly-brain-start -->",ft="<!-- cachly-brain-end -->",ht="https://api.cachly.dev";function re(e,t,n={}){const s={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(s.CACHLY_JWT=e),_&&_!==ht&&(s.CACHLY_API_URL=_),s}function hn(e,t,n){return n==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:re(e,t)}]}},null,2):n==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(e,t)},settings:{}}}},null,2):yt(n)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(e,t)}}},null,2)}function yt(e){return Se[e]===".vscode/mcp.json"}async function bt(e,t,n,s,o,c={}){const r={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(t,n)};if(!o.existsSync(e))return hn(t,n,s);let a={};try{a=JSON.parse(await o.readFile(e,"utf-8"))}catch{try{const{rename:g}=await import("node:fs/promises");await g(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
66
- `)}catch{}}if(s==="continue"){const g=a.experimental??{},y=g.modelContextProtocolServers??[];let v;for(const p of y){const i=p.env??{};if(i.CACHLY_JWT){v=i.CACHLY_JWT;break}}v&&K(v,c);const h=y.filter(p=>{const i=p.env??{};return!i.CACHLY_JWT&&!i.CACHLY_BRAIN_INSTANCE_ID});return h.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:r.env}),a.experimental={...g,modelContextProtocolServers:h},JSON.stringify(a,null,2)}if(s==="zed"){const g=a.context_servers??{},v=g.cachly?.command?.env?.CACHLY_JWT;return v&&K(v,c),g.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:r.env},settings:{}},a.context_servers=g,JSON.stringify(a,null,2)}if(yt(s)){const g=a.mcpServers??void 0,v=g?.cachly?.env?.CACHLY_JWT;v&&K(v,c),g&&"cachly"in g&&(delete g.cachly,Object.keys(g).length===0&&delete a.mcpServers);const h=a.servers??{},p=h.cachly,i=p?.env?.CACHLY_JWT;return i&&K(i,c),h.cachly=p?.envFile?{type:"stdio",...r,envFile:p.envFile}:{type:"stdio",...r},a.servers=h,JSON.stringify(a,null,2)}const u=a.mcpServers??{},l=u.cachly?.env?.CACHLY_JWT;return l&&K(l,c),u.cachly=r,a.mcpServers=u,JSON.stringify(a,null,2)}function vt(e){return`${ke}
65
+ `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});const he={claude:".mcp.json",cursor:".cursor/mcp.json",windsurf:".windsurf/mcp.json",copilot:".vscode/mcp.json",continue:".continue/config.json",cline:".vscode/mcp.json",zed:".zed/settings.json"},Te="<!-- cachly-brain-start -->",bt="<!-- cachly-brain-end -->",vt="https://api.cachly.dev";function ie(e,t,n={}){const s={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(s.CACHLY_JWT=e),_&&_!==vt&&(s.CACHLY_API_URL=_),s}function En(e,t,n){return n==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:ie(e,t)}]}},null,2):n==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ie(e,t)},settings:{}}}},null,2):wt(n)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ie(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ie(e,t)}}},null,2)}function wt(e){return he[e]===".vscode/mcp.json"}function pe(e,t){Eo(e)||re(e,t)}async function xt(e,t,n,s,o,c={}){const i={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ie(t,n)};if(!o.existsSync(e))return En(t,n,s);let a={};try{a=JSON.parse(await o.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
66
+ `)}catch{}}if(s==="continue"){const p=a.experimental??{},y=p.modelContextProtocolServers??[];let w;for(const u of y){const r=u.env??{};if(r.CACHLY_JWT){w=r.CACHLY_JWT;break}}w&&pe(w,c);const f=y.filter(u=>{const r=u.env??{};return!r.CACHLY_JWT&&!r.CACHLY_BRAIN_INSTANCE_ID});return f.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:i.env}),a.experimental={...p,modelContextProtocolServers:f},JSON.stringify(a,null,2)}if(s==="zed"){const p=a.context_servers??{},w=p.cachly?.command?.env?.CACHLY_JWT;return w&&pe(w,c),p.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:i.env},settings:{}},a.context_servers=p,JSON.stringify(a,null,2)}if(wt(s)){const p=a.mcpServers??void 0,w=p?.cachly?.env?.CACHLY_JWT;w&&pe(w,c),p&&"cachly"in p&&(delete p.cachly,Object.keys(p).length===0&&delete a.mcpServers);const f=a.servers??{},u=f.cachly,r=u?.env?.CACHLY_JWT;return r&&pe(r,c),f.cachly=u?.envFile?{type:"stdio",...i,envFile:u.envFile}:{type:"stdio",...i},a.servers=f,JSON.stringify(a,null,2)}const m=a.mcpServers??{},l=m.cachly?.env?.CACHLY_JWT;return l&&pe(l,c),m.cachly=i,a.mcpServers=m,JSON.stringify(a,null,2)}function _t(e){return`${Te}
67
67
  ## Cachly AI Brain \u2014 Always Active
68
68
 
69
69
  The Brain MCP server runs automatically. Instance: \`${e}\`
@@ -118,48 +118,48 @@ Report predicted failure risks to the user before proceeding.
118
118
 
119
119
  ### Half-finished code rule:
120
120
  Never commit code that does not compile. Run \`tsc --noEmit\` / \`go build ./...\` before every commit.
121
- ${ft}`}const yn=`---
121
+ ${bt}`}const Rn=`---
122
122
  description: Cachly AI Brain \u2014 persistent memory protocol (recall before tasks, learn after fixes)
123
123
  alwaysApply: true
124
124
  ---
125
125
 
126
- `;async function wt(e,t){const{writeFile:n,appendFile:s,readFile:o,mkdir:c}=await import("node:fs/promises"),{existsSync:r}=await import("node:fs"),{resolve:a,dirname:u}=await import("node:path"),d=[{path:a(e,"CLAUDE.md")},{path:a(e,"AGENTS.md")},{path:a(e,".github","copilot-instructions.md")},{path:a(e,".cursor","rules","cachly.mdc"),prefix:yn},{path:a(e,".windsurfrules")},{path:a(e,".clinerules")}],l=`
127
- `+vt(t)+`
128
- `,g={};for(const{path:y,prefix:v}of d){if(await c(u(y),{recursive:!0}),r(y)){const h=await o(y,"utf-8");if(h.includes(ke)){const p=h.replace(new RegExp(`${ke}[\\s\\S]*?${ft}`),vt(t));await n(y,p,"utf-8"),g[y]="updated";continue}await s(y,l,"utf-8"),g[y]="appended";continue}await n(y,(v??"")+l.trimStart(),"utf-8"),g[y]="written"}return g}if(process.argv[2]==="digest"){const e=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
126
+ `;async function $t(e,t){const{writeFile:n,appendFile:s,readFile:o,mkdir:c}=await import("node:fs/promises"),{existsSync:i}=await import("node:fs"),{resolve:a,dirname:m}=await import("node:path"),d=[{path:a(e,"CLAUDE.md")},{path:a(e,"AGENTS.md")},{path:a(e,".github","copilot-instructions.md")},{path:a(e,".cursor","rules","cachly.mdc"),prefix:Rn},{path:a(e,".windsurfrules")},{path:a(e,".clinerules")}],l=`
127
+ `+_t(t)+`
128
+ `,p={};for(const{path:y,prefix:w}of d){if(await c(m(y),{recursive:!0}),i(y)){const f=await o(y,"utf-8");if(f.includes(Te)){const u=f.replace(new RegExp(`${Te}[\\s\\S]*?${bt}`),_t(t));await n(y,u,"utf-8"),p[y]="updated";continue}await s(y,l,"utf-8"),p[y]="appended";continue}await n(y,(w??"")+l.trimStart(),"utf-8"),p[y]="written"}return p}if(process.argv[2]==="digest"){const e=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
129
129
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
130
130
  `),process.exit(1)),process.stdout.write(`
131
131
  \u{1F9E0} Fetching your weekly Brain digest...
132
132
 
133
- `);try{const n=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,c=s.total_recall_count??0,r=Math.round(s.iq_boost_pct??0),a=(s.top_lessons??[]).slice(0,5),u=s.team_authors??[],d=c*1200,l=(d*3e-6).toFixed(2),g=o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",y=new Date,v=new Date(y);v.setDate(y.getDate()-7);const h=f=>f.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${h(v)} \u2013 ${h(y)}\x1B[0m \u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total lessons : \x1B[33m${String(o).padEnd(8)}\x1B[0m Brain level : \x1B[32m${g.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(c).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(r).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${(Math.round(d/1e3)+"K").padEnd(8)}\x1B[0m Cost saved : \x1B[32m$${l.padEnd(20)}\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`)),a.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F525} Most recalled lessons this week:\x1B[0m \u2502");for(const f of a){const N=`${f.topic}: ${f.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${N.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 p=a[0],i=[`\u{1F9E0} My AI Brain weekly digest (${h(v)} \u2013 ${h(y)}):`,"",` \u{1F4DA} ${o} lessons learned`,` \u{1F501} ${c} recalls \xB7 ~${Math.round(d/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${g}`,p?` \u{1F525} Top lesson: "${p.topic}: ${p.what_worked.slice(0,60)}${p.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
134
- `),w="https://twitter.com/intent/tweet?text="+encodeURIComponent(i);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const f of i.split(`
135
- `))console.log(` ${f}`);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${w.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite\x1B[0m"),console.log(" \x1B[2m Cron: 0 9 * * 1 npx @cachly-dev/mcp-server@latest digest\x1B[0m"),console.log("")}catch(n){console.log(`
133
+ `);try{const n=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,c=s.total_recall_count??0,i=Math.round(s.iq_boost_pct??0),a=(s.top_lessons??[]).slice(0,5),m=s.team_authors??[],d=c*1200,l=(d*3e-6).toFixed(2),p=o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",y=new Date,w=new Date(y);w.setDate(y.getDate()-7);const f=h=>h.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${f(w)} \u2013 ${f(y)}\x1B[0m \u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total lessons : \x1B[33m${String(o).padEnd(8)}\x1B[0m Brain level : \x1B[32m${p.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(c).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(i).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${(Math.round(d/1e3)+"K").padEnd(8)}\x1B[0m Cost saved : \x1B[32m$${l.padEnd(20)}\x1B[0m\u2502`),m.length>0&&(console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1F465} Team contributors:\x1B[0m ${m.slice(0,5).join(", ").slice(0,42).padEnd(42)} \u2502`)),a.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F525} Most recalled lessons this week:\x1B[0m \u2502");for(const h of a){const N=`${h.topic}: ${h.what_worked}`.slice(0,57);console.log(`\u2502 \x1B[90m\u2022 ${N.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 u=a[0],r=[`\u{1F9E0} My AI Brain weekly digest (${f(w)} \u2013 ${f(y)}):`,"",` \u{1F4DA} ${o} lessons learned`,` \u{1F501} ${c} recalls \xB7 ~${Math.round(d/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${p}`,u?` \u{1F525} Top lesson: "${u.topic}: ${u.what_worked.slice(0,60)}${u.what_worked.length>60?"\u2026":""}"`:"","","Built with @cachly_dev \u2014 AI that actually remembers \u{1F680}","cachly.dev"].filter(Boolean).join(`
134
+ `),b="https://twitter.com/intent/tweet?text="+encodeURIComponent(r);console.log("\x1B[1m\u{1F4E3} Share your digest:\x1B[0m"),console.log(""),console.log("\x1B[90m"+"\u2500".repeat(63)+"\x1B[0m");for(const h of r.split(`
135
+ `))console.log(` ${h}`);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${b.slice(0,90)}...\x1B[0m`),console.log(""),console.log(" \x1B[2m\u{1F4A1} Invite your team: npx @cachly-dev/mcp-server@latest invite\x1B[0m"),console.log(" \x1B[2m Cron: 0 9 * * 1 npx @cachly-dev/mcp-server@latest digest\x1B[0m"),console.log("")}catch(n){console.log(`
136
136
  \u274C Could not fetch digest: ${n.message}
137
137
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="export"){const{writeFile:e,mkdir:t}=await import("node:fs/promises"),{resolve:n}=await import("node:path"),s=process.argv.slice(3),o=d=>{const l=s.indexOf(`--${d}`);return l!==-1?s[l+1]:void 0},c=o("format")??"both";c!=="md"&&c!=="jsonl"&&c!=="both"&&(console.log(`
138
138
  \u274C Unknown --format "${c}" \u2014 use md, jsonl, or both.
139
- `),process.exit(1));const r=n(o("out")??"."),a=x||Ke()||"",u=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!a||!u)&&(console.log(`
139
+ `),process.exit(1));const i=n(o("out")??"."),a=x||Ve()||"",m=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!a||!m)&&(console.log(`
140
140
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
141
141
  `),process.exit(1)),process.stdout.write(`
142
142
  \u{1F4E4} Exporting your Brain...
143
143
 
144
- `);try{let d=[],l="";const g=await fetch(`${_}/api/v1/instances/${u}/export`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(12e4)});if(g.ok){const v=await g.json();d=(v.lessons??[]).map(Uo).filter(h=>h!==null),v.complete===!1&&(l=v.note??"the server reported an incomplete read")}else if(g.status===404){const v=await fetch(`${_}/api/v1/instances/${u}/memory`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(8e3)});if(!v.ok)throw new Error(`memory HTTP ${v.status}`);d=((await v.json()).top_lessons??[]).map(p=>({topic:p.topic,outcome:p.outcome,severity:p.severity,tags:p.tags,whatWorked:p.what_worked,ts:p.ts,author:p.author,recallCount:p.recall_count})),l="this server has no /export endpoint yet, so this is the DASHBOARD SUMMARY: at most 50 lessons, each shortened to 120 characters. Update the server for a full export."}else throw new Error(`export HTTP ${g.status}`);d.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
145
- `),process.exit(0)),await t(r,{recursive:!0});const y=[];if(c==="md"||c==="both"){const v=n(r,"lessons.md");await e(v,Jo(d),"utf-8"),y.push(`${d.length} lesson${d.length===1?"":"s"} \u2192 ${v}`)}if(c==="jsonl"||c==="both"){const v=n(r,"lessons.jsonl");await e(v,Yo(d),"utf-8"),y.push(`${d.length} lesson${d.length===1?"":"s"} \u2192 ${v}`)}l?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${l}`),console.log("")):console.log("\u2705 Export complete:");for(const v of y)console.log(` ${v}`);console.log("")}catch(d){console.log(`
144
+ `);try{let d=[],l="";const p=await fetch(`${_}/api/v1/instances/${m}/export`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(12e4)});if(p.ok){const w=await p.json();d=(w.lessons??[]).map(nn).filter(f=>f!==null),w.complete===!1&&(l=w.note??"the server reported an incomplete read")}else if(p.status===404){const w=await fetch(`${_}/api/v1/instances/${m}/memory`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(8e3)});if(!w.ok)throw new Error(`memory HTTP ${w.status}`);d=((await w.json()).top_lessons??[]).map(u=>({topic:u.topic,outcome:u.outcome,severity:u.severity,tags:u.tags,whatWorked:u.what_worked,ts:u.ts,author:u.author,recallCount:u.recall_count})),l="this server has no /export endpoint yet, so this is the DASHBOARD SUMMARY: at most 50 lessons, each shortened to 120 characters. Update the server for a full export."}else throw new Error(`export HTTP ${p.status}`);d.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
145
+ `),process.exit(0)),await t(i,{recursive:!0});const y=[];if(c==="md"||c==="both"){const w=n(i,"lessons.md");await e(w,tn(d),"utf-8"),y.push(`${d.length} lesson${d.length===1?"":"s"} \u2192 ${w}`)}if(c==="jsonl"||c==="both"){const w=n(i,"lessons.jsonl");await e(w,on(d),"utf-8"),y.push(`${d.length} lesson${d.length===1?"":"s"} \u2192 ${w}`)}l?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${l}`),console.log("")):console.log("\u2705 Export complete:");for(const w of y)console.log(` ${w}`);console.log("")}catch(d){console.log(`
146
146
  \u274C Could not export your Brain: ${d.message}
147
147
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=process.env.CACHLY_JWT??"";e||(console.log(`
148
148
  \u26A0\uFE0F CACHLY_JWT must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
149
149
  `),process.exit(1));try{const t=await fetch(`${_}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json(),s=n.url??R(`/r/${n.code}`,"invite"),o=n.referral_count??0,c=`Hey, I've been using cachly to give my AI persistent memory across sessions \u2014 no more re-explaining my stack every morning.
150
150
 
151
- You get a free Brain: ${s}`,r=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
151
+ You get a free Brain: ${s}`,i=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
152
152
 
153
153
  Try it free: ${s}
154
154
 
155
155
  @cachlydev`);console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F9E0} Your cachly Brain invite link \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 ${s.padEnd(61)}\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),o>0&&(console.log(`\u2502 \x1B[32m\u2713 ${o} developer${o===1?"":"s"} joined via your link so far\x1B[0m`.padEnd(72)+"\u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524")),console.log("\u2502 \x1B[33mSlack / DM message:\x1B[0m \u2502"),console.log("\u2502 \u2502");for(const a of c.split(`
156
- `))console.log(`\u2502 \x1B[90m${a.slice(0,58).padEnd(58)}\x1B[0m \u2502`);console.log("\u2502 \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1D54F} Tweet:\x1B[0m https://twitter.com/intent/tweet?text=${r.slice(0,10)}... \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),console.log("\x1B[2m Each developer who signs up via your link earns you 1 month Pro.\x1B[0m"),console.log("")}catch(t){console.log(`
156
+ `))console.log(`\u2502 \x1B[90m${a.slice(0,58).padEnd(58)}\x1B[0m \u2502`);console.log("\u2502 \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[36m\u{1D54F} Tweet:\x1B[0m https://twitter.com/intent/tweet?text=${i.slice(0,10)}... \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),console.log("\x1B[2m Each developer who signs up via your link earns you 1 month Pro.\x1B[0m"),console.log("")}catch(t){console.log(`
157
157
  \u274C Could not fetch invite link: ${t.message}
158
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:c}=await import("node:path"),{homedir:r}=await import("node:os"),{createInterface:a}=await import("node:readline"),u=process.argv[3]??"";u||(console.log(`
158
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:c}=await import("node:path"),{homedir:i}=await import("node:os"),{createInterface:a}=await import("node:readline"),m=process.argv[3]??"";m||(console.log(`
159
159
  \u274C Usage: npx @cachly-dev/mcp-server@latest join <token>
160
160
  `),console.log(` Get a token from a teammate: npx @cachly-dev/mcp-server@latest invite
161
161
  `),process.exit(1)),console.log(`
162
- \u23F3 Looking up invite...`);let d;try{const $=await fetch(`${_}/api/invite/${u}`,{signal:AbortSignal.timeout(8e3)});$.status===404&&(console.log(`
162
+ \u23F3 Looking up invite...`);let d;try{const $=await fetch(`${_}/api/invite/${m}`,{signal:AbortSignal.timeout(8e3)});$.status===404&&(console.log(`
163
163
  \u274C Invite not found \u2014 the link may be invalid.
164
164
  `),process.exit(1)),$.status===410&&(console.log(`
165
165
  \u274C This invite link has expired (7-day limit).
@@ -167,17 +167,17 @@ Try it free: ${s}
167
167
  \u274C Could not fetch invite: HTTP ${$.status}
168
168
  `),process.exit(1)),d=await $.json()}catch($){console.log(`
169
169
  \u274C Network error: ${$.message}
170
- `),process.exit(1)}const{instance_id:l,instance_name:g,tier:y,label:v}=d,h=new Date(d.expires_at).toLocaleDateString();console.log(""),console.log(" \x1B[35m\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log(" \x1B[35m\u2551\x1B[0m \x1B[1m\u{1F9E0} Brain Invite\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log(" \x1B[35m\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Brain : \x1B[1m${g}\x1B[0m`),console.log(` Tier : ${y}`),v&&console.log(` Note : ${v}`),console.log(` Expires : ${h}`),console.log("");const p=a({input:process.stdin,output:process.stdout}),i=await new Promise($=>{p.question(" Join this Brain? [Y/n] ",k=>{p.close(),$(k.trim().toLowerCase()||"y")})});i!=="y"&&i!=="yes"&&(console.log(`
170
+ `),process.exit(1)}const{instance_id:l,instance_name:p,tier:y,label:w}=d,f=new Date(d.expires_at).toLocaleDateString();console.log(""),console.log(" \x1B[35m\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log(" \x1B[35m\u2551\x1B[0m \x1B[1m\u{1F9E0} Brain Invite\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log(" \x1B[35m\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Brain : \x1B[1m${p}\x1B[0m`),console.log(` Tier : ${y}`),w&&console.log(` Note : ${w}`),console.log(` Expires : ${f}`),console.log("");const u=a({input:process.stdin,output:process.stdout}),r=await new Promise($=>{u.question(" Join this Brain? [Y/n] ",k=>{u.close(),$(k.trim().toLowerCase()||"y")})});r!=="y"&&r!=="yes"&&(console.log(`
171
171
  Cancelled.
172
- `),process.exit(0));let w=x;if(!w){console.log(`
172
+ `),process.exit(0));let b=x;if(!b){console.log(`
173
173
  No API key found \u2014 starting sign-in (10 seconds)...
174
174
  `);try{const $=await fetch(`${_}/api/v1/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(1e4)});if($.ok){const k=await $.json();console.log(` \u{1F449} Open: \x1B[36m${k.verification_uri}\x1B[0m`),console.log(` Code: \x1B[1m${k.user_code}\x1B[0m
175
- `);const T=(k.interval??5)*1e3;for(let H=0;H<24;H++){await new Promise(b=>setTimeout(b,T));try{const b=await fetch(`${_}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:k.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(b.ok){const I=await b.json();if(I.access_token){w=I.access_token;break}}}catch{}}w||(console.log(`
175
+ `);const T=(k.interval??5)*1e3;for(let P=0;P<24;P++){await new Promise(v=>setTimeout(v,T));try{const v=await fetch(`${_}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:k.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(v.ok){const I=await v.json();if(I.access_token){b=I.access_token;break}}}catch{}}b||(console.log(`
176
176
  \u274C Sign-in timed out. Run the command again.
177
177
  `),process.exit(1)),console.log(` \u2705 Signed in!
178
178
  `)}}catch($){console.log(`
179
179
  \u26A0\uFE0F Could not start sign-in: ${$.message}`),console.log(` Set CACHLY_JWT manually from ${R("/setup-ai","join")}
180
- `),process.exit(1)}}const f=process.cwd(),N=r(),j=[{label:".mcp.json (Claude Code project)",path:o(f,".mcp.json")},{label:".cursor/mcp.json",path:o(f,".cursor","mcp.json")},{label:".windsurf/mcp.json",path:o(f,".windsurf","mcp.json")},{label:".vscode/mcp.json (Copilot/Cline)",path:o(f,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:o(N,".claude","mcp.json"),global:!0}];let S=0;for(const{label:$,path:k,global:T}of j){const H=c(k);if(!(!T&&!s(H)&&!s(k)))try{await n(H,{recursive:!0});let b={};if(s(k))try{b=JSON.parse(await t(k,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(k,k+".bak")}catch{}}const I=b.mcpServers??{},F=I.cachly??{},z=F.env??{};z.CACHLY_BRAIN_INSTANCE_ID=l,w&&!z.CACHLY_JWT&&(z.CACHLY_JWT=w),_!==ht&&(z.CACHLY_API_URL=_),I.cachly={...F,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:z},b.mcpServers=I,await e(k,JSON.stringify(b,null,2),"utf-8"),console.log(` \u2705 ${$}`),S++}catch(b){b.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${$}: ${b.message}`)}}console.log(""),S===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${g}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
180
+ `),process.exit(1)}}const h=process.cwd(),N=i(),j=[{label:".mcp.json (Claude Code project)",path:o(h,".mcp.json")},{label:".cursor/mcp.json",path:o(h,".cursor","mcp.json")},{label:".windsurf/mcp.json",path:o(h,".windsurf","mcp.json")},{label:".vscode/mcp.json (Copilot/Cline)",path:o(h,".vscode","mcp.json")},{label:"~/.claude/mcp.json (global)",path:o(N,".claude","mcp.json"),global:!0}];let S=0;for(const{label:$,path:k,global:T}of j){const P=c(k);if(!(!T&&!s(P)&&!s(k)))try{await n(P,{recursive:!0});let v={};if(s(k))try{v=JSON.parse(await t(k,"utf-8"))}catch{try{await(await import("node:fs/promises")).rename(k,k+".bak")}catch{}}const I=v.mcpServers??{},F=I.cachly??{},z=F.env??{};z.CACHLY_BRAIN_INSTANCE_ID=l,b&&!z.CACHLY_JWT&&(z.CACHLY_JWT=b),_!==vt&&(z.CACHLY_API_URL=_),I.cachly={...F,command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:z},v.mcpServers=I,await e(k,JSON.stringify(v,null,2),"utf-8"),console.log(` \u2705 ${$}`),S++}catch(v){v.code!=="ENOENT"&&console.log(` \u26A0\uFE0F ${$}: ${v.message}`)}}console.log(""),S===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${p}\x1B[0m`),console.log(` Restart your editor \u2014 your AI arrives pre-briefed from the team Brain.
181
181
  `),console.log(" \u{1F4DB} Add the badge to your README:"),console.log(` npx @cachly-dev/mcp-server@latest badge
182
182
  `)),process.exit(0)}if(process.argv[2]==="upgrade"){process.stdout.write(`
183
183
  \u23F3 Checking for updates...
@@ -185,20 +185,20 @@ Try it free: ${s}
185
185
  \u2705 Already on the latest version: \x1B[32mv${M}\x1B[0m
186
186
  `):(console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly update available\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Current : \x1B[31mv${M}\x1B[0m`),console.log(` Latest : \x1B[32mv${n}\x1B[0m`),console.log(""),console.log(" Update your editor configs to pick up the new version:"),console.log(""),console.log(" \x1B[32m npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(""),console.log(" \x1B[2m(npx always fetches the latest when @latest is specified)\x1B[0m"),console.log(""))}catch(e){console.log(`
187
187
  \u274C Could not check for updates: ${e.message}
188
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:n}=await import("node:path"),{loadExternalCorpus:s,runExternalBenchmark:o}=await import("./bench/external-corpus.js"),c=process.argv.includes("--json"),r=process.argv.slice(3).find(d=>!d.startsWith("--")),a=t(e(import.meta.url)),u=r?n(process.cwd(),r):n(a,"bench","external","sample-corpus.json");try{const d=await s(u),l=await o(d);c&&(console.log(JSON.stringify({corpus:d.name,lessons:l.corpusSize,queries:l.queryCount,cachly_p1:Math.round(l.cachly.precisionAt1*1e3)/10,flatfile_p1:Math.round(l.flatfile.precisionAt1*1e3)/10,cachly_mrr:Math.round(l.cachly.mrr*1e3)/10,flatfile_mrr:Math.round(l.flatfile.mrr*1e3)/10,p1_lift_vs_flatfile_pct:Math.round((l.cachly.precisionAt1-l.flatfile.precisionAt1)*1e3)/10,mrr_lift_vs_flatfile_pct:Math.round((l.cachly.mrr-l.flatfile.mrr)*1e3)/10},null,2)),process.exit(0));const g=((l.cachly.precisionAt1-l.flatfile.precisionAt1)*100).toFixed(1),y=((l.cachly.mrr-l.flatfile.mrr)*100).toFixed(1),v=((l.cachly.precisionAt1-l.baseline.precisionAt1)*100).toFixed(1),h=l.cachly.precisionAt1>=l.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",p=l.cachly.mrr>=l.flatfile.mrr?"\x1B[32m+":"\x1B[31m";console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly recall quality benchmark\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Corpus : ${d.name??u}`),console.log(` Dataset: ${l.corpusSize} lessons \xB7 ${l.queryCount} queries \xB7 10 engineering domains`),console.log(" (k8s, DB, auth, CI, frontend, API, payments, observability, Node.js, infra)"),console.log(""),console.log(" \x1B[1mPrecision@1\x1B[0m (finds the right lesson at rank #1):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.precisionAt1*100).toFixed(1)}%\x1B[0m (naive keyword overlap \u2014 no quality signal)`),console.log(` raw BM25 : \x1B[33m${(l.baseline.precisionAt1*100).toFixed(1)}%\x1B[0m (keyword ranking)`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.precisionAt1*100).toFixed(1)}%\x1B[0m (BM25 + quality reranking)`),console.log(""),console.log(" \x1B[1mMean Reciprocal Rank\x1B[0m (average rank of the right answer):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` raw BM25 : \x1B[33m${(l.baseline.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.mrr*100).toFixed(1)}%\x1B[0m`),console.log(""),console.log(" \x1B[1mLift vs flat-file memory\x1B[0m (what you get by switching from plain memory files):"),console.log(` Precision@1 : ${h}${g}%\x1B[0m`),console.log(` MRR : ${p}${y}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${v}%\x1B[0m Precision@1 (quality reranking on top of keyword search)`),console.log(""),console.log(" \x1B[2mFlat-file = lexical overlap over raw text files (how Anthropic/Claude Memory works).\x1B[0m"),console.log(" \x1B[2mAdversarial distractors included \u2014 failure lessons that share the exact query vocabulary.\x1B[0m"),console.log(" \x1B[2mcachly ignores them because they have low confidence / failed outcome.\x1B[0m"),console.log(""),console.log(" Share your results:"),console.log(` \x1B[36m"My Brain: Precision@1 ${(l.cachly.precisionAt1*100).toFixed(1)}% (${h}${g}% vs flat-file memory, ${l.queryCount} queries)"\x1B[0m`),console.log(""),console.log(" Run on a custom corpus:"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench my-incidents.json\x1B[0m"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench --json # machine-readable\x1B[0m"),console.log(""),console.log(" \x1B[1m\u2192 Give your AI this recall quality on your own work (free, 1\u20135 min):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(" \x1B[90m Signs in, configures every editor, bootstraps from your git history.\x1B[0m"),console.log(` \x1B[90m Or create your Brain at: \x1B[36m${R("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(d){console.error(`
188
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:n}=await import("node:path"),{loadExternalCorpus:s,runExternalBenchmark:o}=await import("./bench/external-corpus.js"),c=process.argv.includes("--json"),i=process.argv.slice(3).find(d=>!d.startsWith("--")),a=t(e(import.meta.url)),m=i?n(process.cwd(),i):n(a,"bench","external","sample-corpus.json");try{const d=await s(m),l=await o(d);c&&(console.log(JSON.stringify({corpus:d.name,lessons:l.corpusSize,queries:l.queryCount,cachly_p1:Math.round(l.cachly.precisionAt1*1e3)/10,flatfile_p1:Math.round(l.flatfile.precisionAt1*1e3)/10,cachly_mrr:Math.round(l.cachly.mrr*1e3)/10,flatfile_mrr:Math.round(l.flatfile.mrr*1e3)/10,p1_lift_vs_flatfile_pct:Math.round((l.cachly.precisionAt1-l.flatfile.precisionAt1)*1e3)/10,mrr_lift_vs_flatfile_pct:Math.round((l.cachly.mrr-l.flatfile.mrr)*1e3)/10},null,2)),process.exit(0));const p=((l.cachly.precisionAt1-l.flatfile.precisionAt1)*100).toFixed(1),y=((l.cachly.mrr-l.flatfile.mrr)*100).toFixed(1),w=((l.cachly.precisionAt1-l.baseline.precisionAt1)*100).toFixed(1),f=l.cachly.precisionAt1>=l.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",u=l.cachly.mrr>=l.flatfile.mrr?"\x1B[32m+":"\x1B[31m";console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly recall quality benchmark\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(` Corpus : ${d.name??m}`),console.log(` Dataset: ${l.corpusSize} lessons \xB7 ${l.queryCount} queries \xB7 10 engineering domains`),console.log(" (k8s, DB, auth, CI, frontend, API, payments, observability, Node.js, infra)"),console.log(""),console.log(" \x1B[1mPrecision@1\x1B[0m (finds the right lesson at rank #1):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.precisionAt1*100).toFixed(1)}%\x1B[0m (naive keyword overlap \u2014 no quality signal)`),console.log(` raw BM25 : \x1B[33m${(l.baseline.precisionAt1*100).toFixed(1)}%\x1B[0m (keyword ranking)`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.precisionAt1*100).toFixed(1)}%\x1B[0m (BM25 + quality reranking)`),console.log(""),console.log(" \x1B[1mMean Reciprocal Rank\x1B[0m (average rank of the right answer):"),console.log(` flat-file memory : \x1B[33m${(l.flatfile.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` raw BM25 : \x1B[33m${(l.baseline.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` cachly : \x1B[1m\x1B[32m${(l.cachly.mrr*100).toFixed(1)}%\x1B[0m`),console.log(""),console.log(" \x1B[1mLift vs flat-file memory\x1B[0m (what you get by switching from plain memory files):"),console.log(` Precision@1 : ${f}${p}%\x1B[0m`),console.log(` MRR : ${u}${y}%\x1B[0m`),console.log(` vs BM25 : \x1B[32m+${w}%\x1B[0m Precision@1 (quality reranking on top of keyword search)`),console.log(""),console.log(" \x1B[2mFlat-file = lexical overlap over raw text files (how Anthropic/Claude Memory works).\x1B[0m"),console.log(" \x1B[2mAdversarial distractors included \u2014 failure lessons that share the exact query vocabulary.\x1B[0m"),console.log(" \x1B[2mcachly ignores them because they have low confidence / failed outcome.\x1B[0m"),console.log(""),console.log(" Share your results:"),console.log(` \x1B[36m"My Brain: Precision@1 ${(l.cachly.precisionAt1*100).toFixed(1)}% (${f}${p}% vs flat-file memory, ${l.queryCount} queries)"\x1B[0m`),console.log(""),console.log(" Run on a custom corpus:"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench my-incidents.json\x1B[0m"),console.log(" \x1B[2m npx @cachly-dev/mcp-server@latest bench --json # machine-readable\x1B[0m"),console.log(""),console.log(" \x1B[1m\u2192 Give your AI this recall quality on your own work (free, 1\u20135 min):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(" \x1B[90m Signs in, configures every editor, bootstraps from your git history.\x1B[0m"),console.log(` \x1B[90m Or create your Brain at: \x1B[36m${R("/setup-ai","bench")}\x1B[0m`),console.log("")}catch(d){console.error(`
189
189
  \u274C bench failed: ${d.message}
190
190
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{execSync:e}=await import("node:child_process"),{existsSync:t,readFileSync:n}=await import("node:fs"),{resolve:s,basename:o}=await import("node:path"),c=process.cwd();console.log(`
191
191
  \x1B[35m\u{1F9E0} cachly Brain \u2014 Live Demo\x1B[0m`),console.log(`\x1B[90mNo account needed. Reading your git history...\x1B[0m
192
192
  `),t(s(c,".git"))||(console.log("\u26A0\uFE0F No git repository found here."),console.log(` Run this command inside a project directory with git history.
193
193
  `),console.log(` Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo
194
- `),process.exit(0));let r="";try{r=e("git config user.name",{cwd:c,encoding:"utf-8",stdio:"pipe"}).trim().split(" ")[0]??""}catch{}let a=o(c);try{const b=JSON.parse(n(s(c,"package.json"),"utf-8"));b.name&&(a=b.name.replace(/^@[^/]+\//,""))}catch{}let u="";try{u=e('git log HEAD --pretty=format:"%H|||%s|||%ad|||%an" --date=short --no-merges -n 200',{cwd:c,encoding:"utf-8",stdio:"pipe"})}catch{console.log(`\u26A0\uFE0F Could not read git log. Make sure you have commits.
195
- `),process.exit(0)}const d=u.trim().split(`
196
- `).filter(Boolean).map(b=>{const[I,F,z,oe]=b.split("|||");return{sha:(I??"").trim().slice(0,8),subject:(F??"").trim(),date:(z??"").trim(),author:(oe??"").trim()}});d.length===0&&(console.log(`\u26A0\uFE0F No commits found.
197
- `),process.exit(0));const l=new Map,g=[],y=[],v=[],h=new Set;let p=0;for(const b of d){const I=Zo(b.subject);l.set(I,(l.get(I)??0)+1),Qo(b.subject)&&p++,I==="fix"&&g.length<5&&g.push(b.subject.slice(0,72)),I==="feat"&&y.length<5&&y.push(b.subject.slice(0,72)),I==="security"&&v.length<3&&v.push(b.subject.slice(0,72)),b.author&&h.add(b.author)}const i=Xo(d.map(b=>b.subject)),w=`${d[d.length-1]?.date??"?"} \u2192 ${d[0]?.date??"?"}`,f=i>=501?"Oracle":i>=201?"Architect":i>=51?"Expert":i>=11?"Explorer":"Apprentice",j=`${r?`Hey ${r} \u2014 `:""}here's what your AI would know about ${a}`;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} ${j.slice(0,58).padEnd(58)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Commits analysed : \x1B[33m${String(d.length).padEnd(6)}\x1B[0m Date range: \x1B[90m${w.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(i).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(h.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${f.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(p).padEnd(21)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const S=[...l.entries()].filter(([b])=>b!=="chore").sort((b,I)=>I[1]-b[1]),$=(b,I)=>"\u2588".repeat(Math.round(b/I*20)).padEnd(20),k=Math.max(...S.map(([,b])=>b),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[b,I]of S){const F={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[b]??"\u2022";console.log(`\u2502 ${F} \x1B[36m${b.padEnd(10)}\x1B[0m \x1B[35m${$(I,k)}\x1B[0m \x1B[33m${String(I).padStart(3)}\x1B[0m \u2502`)}if(v.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 b of v)console.log(`\u2502 \x1B[90m\u2022 ${b.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(g.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F527} Bug fixes your AI would never repeat:\x1B[0m \u2502");for(const b of g.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${b.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(y.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 b of y.slice(0,3))console.log(`\u2502 \x1B[90m\u2022 ${b.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 T=new URLSearchParams({repo:a,commits:String(d.length),lessons:String(i),level:f,authors:String(h.size),reverts:String(p)}),H=R(`/preview?${T.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${H}\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=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
194
+ `),process.exit(0));let i="";try{i=e("git config user.name",{cwd:c,encoding:"utf-8",stdio:"pipe"}).trim().split(" ")[0]??""}catch{}let a=o(c);try{const v=JSON.parse(n(s(c,"package.json"),"utf-8"));v.name&&(a=v.name.replace(/^@[^/]+\//,""))}catch{}let m="";try{m=e('git log HEAD --pretty=format:"%H|||%s|||%ad|||%an" --date=short --no-merges -n 200',{cwd:c,encoding:"utf-8",stdio:"pipe"})}catch{console.log(`\u26A0\uFE0F Could not read git log. Make sure you have commits.
195
+ `),process.exit(0)}const d=m.trim().split(`
196
+ `).filter(Boolean).map(v=>{const[I,F,z,te]=v.split("|||");return{sha:(I??"").trim().slice(0,8),subject:(F??"").trim(),date:(z??"").trim(),author:(te??"").trim()}});d.length===0&&(console.log(`\u26A0\uFE0F No commits found.
197
+ `),process.exit(0));const l=new Map,p=[],y=[],w=[],f=new Set;let u=0;for(const v of d){const I=un(v.subject);l.set(I,(l.get(I)??0)+1),mn(v.subject)&&u++,I==="fix"&&p.length<5&&p.push(v.subject.slice(0,72)),I==="feat"&&y.length<5&&y.push(v.subject.slice(0,72)),I==="security"&&w.length<3&&w.push(v.subject.slice(0,72)),v.author&&f.add(v.author)}const r=gn(d.map(v=>v.subject)),b=`${d[d.length-1]?.date??"?"} \u2192 ${d[0]?.date??"?"}`,h=r>=501?"Oracle":r>=201?"Architect":r>=51?"Expert":r>=11?"Explorer":"Apprentice",j=`${i?`Hey ${i} \u2014 `:""}here's what your AI would know about ${a}`;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} ${j.slice(0,58).padEnd(58)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Commits analysed : \x1B[33m${String(d.length).padEnd(6)}\x1B[0m Date range: \x1B[90m${b.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(r).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(f.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${h.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(u).padEnd(21)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const S=[...l.entries()].filter(([v])=>v!=="chore").sort((v,I)=>I[1]-v[1]),$=(v,I)=>"\u2588".repeat(Math.round(v/I*20)).padEnd(20),k=Math.max(...S.map(([,v])=>v),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[v,I]of S){const F={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[v]??"\u2022";console.log(`\u2502 ${F} \x1B[36m${v.padEnd(10)}\x1B[0m \x1B[35m${$(I,k)}\x1B[0m \x1B[33m${String(I).padStart(3)}\x1B[0m \u2502`)}if(w.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 v of w)console.log(`\u2502 \x1B[90m\u2022 ${v.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[33m\u{1F527} Bug fixes your AI would never repeat:\x1B[0m \u2502");for(const v of p.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${v.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(y.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 v of y.slice(0,3))console.log(`\u2502 \x1B[90m\u2022 ${v.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 T=new URLSearchParams({repo:a,commits:String(d.length),lessons:String(r),level:h,authors:String(f.size),reverts:String(u)}),P=R(`/preview?${T.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${P}\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=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
198
198
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
199
199
  `),process.exit(1)),process.stdout.write(`
200
200
  \u{1F9E0} Fetching your Brain stats...
201
- `);try{const n=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,c=s.total_recall_count??0,r=Math.round(s.iq_boost_pct??0),a=c*1200,u=(a*3e-6).toFixed(2),d=o===0?"Intern \u{1F331}":o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}";console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F9E0} My AI Brain \xB7 powered by \x1B[35mcachly.dev\x1B[0m \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Lessons stored : \x1B[33m${String(o).padEnd(8)}\x1B[0m Brain level: \x1B[32m${d.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(c).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(r).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${((a/1e3).toFixed(0)+"K").padEnd(8)}\x1B[0m Cost saved: \x1B[32m$${u.padEnd(20)}\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=R("/","share"),g=`\u{1F9E0} My AI coding assistant now has persistent memory.
201
+ `);try{const n=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.json(),o=s.lesson_count??0,c=s.total_recall_count??0,i=Math.round(s.iq_boost_pct??0),a=c*1200,m=(a*3e-6).toFixed(2),d=o===0?"Intern \u{1F331}":o<10?"Junior Dev \u{1F527}":o<30?"Mid Dev \u26A1":o<60?"Senior Dev \u{1F9E0}":o<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}";console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F9E0} My AI Brain \xB7 powered by \x1B[35mcachly.dev\x1B[0m \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Lessons stored : \x1B[33m${String(o).padEnd(8)}\x1B[0m Brain level: \x1B[32m${d.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(c).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(i).padEnd(3)}%\x1B[0m \u2502`),console.log(`\u2502 Tokens saved : \x1B[32m${((a/1e3).toFixed(0)+"K").padEnd(8)}\x1B[0m Cost saved: \x1B[32m$${m.padEnd(20)}\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=R("/","share"),p=`\u{1F9E0} My AI coding assistant now has persistent memory.
202
202
 
203
203
  ${o} lessons stored \xB7 ${c} recalls \xB7 ${d}
204
204
 
@@ -206,7 +206,7 @@ Fix a bug once \u2192 AI remembers forever. Across Claude Code, Cursor, Windsurf
206
206
 
207
207
  ${l}
208
208
 
209
- #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(g.split(`
209
+ #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(p.split(`
210
210
  `).map(y=>` ${y}`).join(`
211
211
  `)),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(""),console.log(" \x1B[2mPro tip: add a screenshot of your Brain panel for 3x more engagement\x1B[0m"),console.log(" \x1B[2mAlso add a live badge to your README:\x1B[0m"),console.log(" \x1B[90m npx @cachly-dev/mcp-server@latest badge\x1B[0m"),console.log("")}catch(n){console.log(`
212
212
  \u274C Could not fetch stats: ${n.message}
@@ -214,7 +214,7 @@ ${l}
214
214
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
215
215
  `),process.exit(1));const n=process.argv.indexOf("--title"),s=n!==-1?process.argv[n+1]??"My Brain Snapshot":"My Brain Snapshot",o=process.argv.includes("--public");process.stdout.write(`
216
216
  \u{1F9E0} Publishing Brain snapshot...
217
- `);try{const c=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let r=0,a=0;if(c.ok){const y=await c.json();r=y.lesson_count??0,a=y.total_recall_count??0}const u=await fetch(`${_}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:s,visibility:o?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!u.ok)throw new Error(`HTTP ${u.status}`);const l=(await u.json()).share_id??"unavailable",g=R(`/brain/share/${l}`,"publish");console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F4E4} Brain Published \xB7 powered by \x1B[35mcachly.dev\x1B[0m \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Title : \x1B[33m${s.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(r).padEnd(10)}\x1B[0m Recalls: \x1B[36m${String(a).padEnd(26)}\x1B[0m\u2502`),console.log(`\u2502 Visibility: \x1B[${o?"32":"33"}m${(o?"public (discoverable)":"unlisted (link only)").padEnd(44)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[1mShare URL:\x1B[0m \x1B[36m${g.padEnd(51)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[2mAnyone can import with:\x1B[0m \u2502"),console.log(`\u2502 \x1B[90m brain_import(instance_id="...", share_id="${l.slice(0,17)}")\x1B[0m\u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),console.log(" \x1B[1m\u{1F4CB} Share this with your team:\x1B[0m"),console.log(` ${g}`),console.log(""),console.log(` \x1B[2mTo list all your shares:\x1B[0m brain_share_list(instance_id="${t.slice(0,24)}...")`),console.log(` \x1B[2mTo revoke this share:\x1B[0m brain_unshare(share_id="${l.slice(0,24)}...")`),console.log("")}catch(c){console.log(`
217
+ `);try{const c=await fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let i=0,a=0;if(c.ok){const y=await c.json();i=y.lesson_count??0,a=y.total_recall_count??0}const m=await fetch(`${_}/api/v1/brains/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({title:s,visibility:o?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!m.ok)throw new Error(`HTTP ${m.status}`);const l=(await m.json()).share_id??"unavailable",p=R(`/brain/share/${l}`,"publish");console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F4E4} Brain Published \xB7 powered by \x1B[35mcachly.dev\x1B[0m \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Title : \x1B[33m${s.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(i).padEnd(10)}\x1B[0m Recalls: \x1B[36m${String(a).padEnd(26)}\x1B[0m\u2502`),console.log(`\u2502 Visibility: \x1B[${o?"32":"33"}m${(o?"public (discoverable)":"unlisted (link only)").padEnd(44)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 \x1B[1mShare URL:\x1B[0m \x1B[36m${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="${l.slice(0,17)}")\x1B[0m\u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(""),console.log(" \x1B[1m\u{1F4CB} Share this with your team:\x1B[0m"),console.log(` ${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="${l.slice(0,24)}...")`),console.log("")}catch(c){console.log(`
218
218
  \u274C Could not publish Brain: ${c.message}
219
219
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="tool-specs"||process.argv[2]==="openapi"){const{renderToolSpecs:e}=await import("./toolspecs.js");let t="openapi";if(process.argv[2]!=="openapi"){const s=process.argv.find(o=>o.startsWith("--format="));if(s)t=s.slice(9);else{const o=process.argv.indexOf("--format");o!==-1&&(t=process.argv[o+1]??"openapi")}}const n=["openapi","openai","anthropic","langchain"];n.includes(t)||(process.stderr.write(`
220
220
  \u274C Unknown format "${t}". Use one of: ${n.join(", ")}
@@ -222,115 +222,133 @@ ${l}
222
222
  `),process.exit(1)),process.stdout.write(e(le,t,M)+`
223
223
  `,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=process.env.CACHLY_BRAIN_INSTANCE_ID??"";e||(console.log(`
224
224
  \u26A0\uFE0F CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
225
- `),process.exit(1));const t=`${_}/api/v1/badge/${e}`,n=R("/","badge"),s=`[![cachly Brain](${t})](${n})`,o=`<a href="${n}"><img src="${t}" alt="cachly Brain" /></a>`;console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly Brain Badge\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Paste into your README.md:"),console.log(""),console.log(` \x1B[32m${s}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${o}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Badge URL (live, updates every hour):"),console.log(` \x1B[90m${t}\x1B[0m`),console.log(""),console.log(" \x1B[2mThe badge shows your current lesson count \u2014 no auth required,"),console.log(" safe to embed in public repos. Updates hourly.\x1B[0m"),console.log(""),process.exit(0)}if(!process.argv[2]&&process.stdout.isTTY&&(console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly \u2014 Persistent AI Memory for Developers\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Stop re-teaching your AI every morning."),console.log(" cachly gives it a permanent brain \u2014 pre-briefed every session."),console.log(""),console.log(" \x1B[1mCommands:\x1B[0m"),console.log(" \x1B[1m\x1B[32m npx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2190 \x1B[1mOne command, fully ready\x1B[0m"),console.log(" \x1B[32m npx @cachly-dev/mcp-server@latest demo\x1B[0m \u2190 Try it first (no account)"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest setup\x1B[0m \u2190 Interactive setup (pick editors)"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest health\x1B[0m \u2190 Check everything works"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest doctor\x1B[0m \u2190 Diagnose a broken or missing install"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest digest\x1B[0m \u2190 Weekly Brain summary"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest share\x1B[0m \u2190 Share your Brain stats"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest badge\x1B[0m \u2190 README badge for your Brain"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest invite\x1B[0m \u2190 Invite a teammate"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest join <token>\x1B[0m \u2190 Accept a Brain invite"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest bench\x1B[0m \u2190 Recall quality vs flat-file memory"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest upgrade\x1B[0m \u2190 Check for updates"),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(0)),process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:n,readFile:s}=await import("node:fs/promises"),{resolve:o,dirname:c}=await import("node:path"),r=process.argv.slice(3),a=S=>{const $=r.indexOf(`--${S}`);return $!==-1?r[$+1]:void 0};let u=a("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,d=a("api-key")??process.env.CACHLY_JWT;const l=(a("editor")??"claude").toLowerCase(),g=o(a("project-dir")??"."),y=a("api-url");if(y&&(_=y.replace(/\/+$/,"")),!u||!d)try{const{existsSync:S}=await import("node:fs"),$=process.env.HOME??process.env.USERPROFILE??"",k=$?o($,".claude","mcp.json"):"";if(k&&S(k)){const H=JSON.parse(await s(k,"utf-8")).mcpServers?.cachly?.env??{};d??=H.CACHLY_JWT,u??=H.CACHLY_BRAIN_INSTANCE_ID,d&&u&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!u||!d)&&(console.error(`
225
+ `),process.exit(1));const t=`${_}/api/v1/badge/${e}`,n=R("/","badge"),s=`[![cachly Brain](${t})](${n})`,o=`<a href="${n}"><img src="${t}" alt="cachly Brain" /></a>`;console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly Brain Badge\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Paste into your README.md:"),console.log(""),console.log(` \x1B[32m${s}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${o}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Badge URL (live, updates every hour):"),console.log(` \x1B[90m${t}\x1B[0m`),console.log(""),console.log(" \x1B[2mThe badge shows your current lesson count \u2014 no auth required,"),console.log(" safe to embed in public repos. Updates hourly.\x1B[0m"),console.log(""),process.exit(0)}if(!process.argv[2]&&process.stdout.isTTY&&(console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly \u2014 Persistent AI Memory for Developers\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Stop re-teaching your AI every morning."),console.log(" cachly gives it a permanent brain \u2014 pre-briefed every session."),console.log(""),console.log(" \x1B[1mCommands:\x1B[0m"),console.log(" \x1B[1m\x1B[32m npx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2190 \x1B[1mOne command, fully ready\x1B[0m"),console.log(" \x1B[32m npx @cachly-dev/mcp-server@latest demo\x1B[0m \u2190 Try it first (no account)"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest setup\x1B[0m \u2190 Interactive setup (pick editors)"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest claim\x1B[0m \u2190 Keep a test Brain in your own account"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest health\x1B[0m \u2190 Check everything works"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest doctor\x1B[0m \u2190 Diagnose a broken or missing install"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest digest\x1B[0m \u2190 Weekly Brain summary"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest share\x1B[0m \u2190 Share your Brain stats"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest badge\x1B[0m \u2190 README badge for your Brain"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest invite\x1B[0m \u2190 Invite a teammate"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest join <token>\x1B[0m \u2190 Accept a Brain invite"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest bench\x1B[0m \u2190 Recall quality vs flat-file memory"),console.log(" \x1B[36m npx @cachly-dev/mcp-server@latest upgrade\x1B[0m \u2190 Check for updates"),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(0)),process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:n,readFile:s}=await import("node:fs/promises"),{resolve:o,dirname:c}=await import("node:path"),i=process.argv.slice(3),a=S=>{const $=i.indexOf(`--${S}`);return $!==-1?i[$+1]:void 0};let m=a("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,d=a("api-key")??process.env.CACHLY_JWT;const l=(a("editor")??"claude").toLowerCase(),p=o(a("project-dir")??"."),y=a("api-url");if(y&&(_=y.replace(/\/+$/,"")),!m||!d)try{const{existsSync:S}=await import("node:fs"),$=process.env.HOME??process.env.USERPROFILE??"",k=$?o($,".claude","mcp.json"):"";if(k&&S(k)){const P=JSON.parse(await s(k,"utf-8")).mcpServers?.cachly?.env??{};d??=P.CACHLY_JWT,m??=P.CACHLY_BRAIN_INSTANCE_ID,d&&m&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!m||!d)&&(console.error(`
226
226
  Usage: npx @cachly-dev/mcp-server@latest init --instance-id <uuid> --api-key <cky_live_...> [--editor claude|cursor|windsurf|copilot|continue] [--project-dir /path] [--api-url https://your-self-hosted-backend]
227
227
  `),console.error(`First time? Run the zero-config wizard (signs you in, auto-provisions): npx @cachly-dev/mcp-server@latest autopilot
228
228
  `),console.error(`Get your credentials from: ${R("/setup-ai","init")}
229
- `),process.exit(1));const v=Se[l]??".mcp.json",h=o(g,v);await n(c(h),{recursive:!0});const{existsSync:p}=await import("node:fs"),i=p(h),w=i?await s(h,"utf-8").catch(()=>""):"";K(d);const f=await bt(h,d,u,l,{readFile:s,existsSync:p});f!==w?(await t(h,f,"utf-8"),console.log(`
230
- \u2705 ${i?"Updated":"Written"}: ${v}`)):console.log(`
231
- \u2713 Already configured: ${v} (no change)`);const N=await wt(g,u);for(const[S,$]of Object.entries(N)){const k=$==="updated"?"\u2705 Updated":$==="appended"?"\u2705 Appended to":"\u2705 Written",T=S.split(/[\\/]/).pop()??S;console.log(`${k}: ${T}`)}try{const S=await We(g,u,x||void 0);S==="written"?console.log("\u2705 Written: .git/hooks/post-commit (CLS hook)"):S==="upgraded"?console.log(`\u2705 Upgraded: .git/hooks/post-commit (CLS hook \u2192 ${Fe})`):S==="appended"?console.log("\u2705 Appended: .git/hooks/post-commit (CLS hook)"):S==="unchanged"&&console.log("\u2713 CLS hook already current in .git/hooks/post-commit")}catch{}if(l==="claude")try{const S=await ze(g,u),$=S.scripts==="written"?"\u2705 Written":S.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${qe})`:"\u2713 Unchanged";console.log(`${$}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),S.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):S.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{}const j=((Date.now()-e)/1e3).toFixed(1);console.log(`
229
+ `),process.exit(1));const w=he[l]??".mcp.json",f=o(p,w);await n(c(f),{recursive:!0});const{existsSync:u}=await import("node:fs"),r=u(f),b=r?await s(f,"utf-8").catch(()=>""):"";re(d);const h=await xt(f,d,m,l,{readFile:s,existsSync:u});h!==b?(await t(f,h,"utf-8"),console.log(`
230
+ \u2705 ${r?"Updated":"Written"}: ${w}`)):console.log(`
231
+ \u2713 Already configured: ${w} (no change)`);const N=await $t(p,m);for(const[S,$]of Object.entries(N)){const k=$==="updated"?"\u2705 Updated":$==="appended"?"\u2705 Appended to":"\u2705 Written",T=S.split(/[\\/]/).pop()??S;console.log(`${k}: ${T}`)}try{const S=await Fe(p,m,x||void 0);S==="written"?console.log("\u2705 Written: .git/hooks/post-commit (CLS hook)"):S==="upgraded"?console.log(`\u2705 Upgraded: .git/hooks/post-commit (CLS hook \u2192 ${ze})`):S==="appended"?console.log("\u2705 Appended: .git/hooks/post-commit (CLS hook)"):S==="unchanged"&&console.log("\u2713 CLS hook already current in .git/hooks/post-commit")}catch{}if(l==="claude")try{const S=await qe(p,m),$=S.scripts==="written"?"\u2705 Written":S.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${Ke})`:"\u2713 Unchanged";console.log(`${$}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),S.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):S.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{}const j=((Date.now()-e)/1e3).toFixed(1);console.log(`
232
232
  \u{1F9E0} Cachly AI Brain configured for ${l==="claude"?"Claude Code":l}! (${j}s)`),console.log(" 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(`
233
233
  \u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
234
234
  `),process.exit(0)}if(process.argv[2]==="status"){const e=process.env.CACHLY_JWT??"",t=process.env.CACHLY_BRAIN_INSTANCE_ID??"";(!e||!t)&&(console.log(`
235
235
  \u26A0\uFE0F CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
236
- `),process.exit(1));try{const[n,s]=await Promise.all([fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${_}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)})]);if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const o=await n.json(),c=s.ok?await s.json():null,r=o.lesson_count??0,a=o.total_recall_count??0,u=Math.round(o.iq_boost_pct??0),d=o.team_authors??[],l=c?.referral_count??0,g=c?.url??"",y=r===0?"Intern \u{1F331}":r<10?"Junior Dev \u{1F527}":r<30?"Mid Dev \u26A1":r<60?"Senior Dev \u{1F9E0}":r<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",v=r>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 ${v} \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(r).padEnd(8)}\x1B[0m Level : \x1B[32m${y.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Recalls : \x1B[36m${String(a).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(u).padEnd(3)}%\x1B[0m \u2502`),d.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const h=d.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(d.length).padEnd(2)} developer${d.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-h.length))} \u2502`),console.log(`\u2502 ${h.slice(0,56).padEnd(56)} \u2502`)}if(g){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 h=`${g.slice(0,44)}${g.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Invite link\x1B[0m \xB7 ${l>0?`\x1B[32m${l} joined\x1B[0m`:"share to grow your team"}${" ".repeat(Math.max(0,35-String(l).length))} \u2502`),console.log(`\u2502 \x1B[2m${h.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(""),r===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(`
236
+ `),process.exit(1));try{const[n,s]=await Promise.all([fetch(`${_}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)}),fetch(`${_}/api/v1/referral/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)})]);if(!n.ok)throw new Error(`stats HTTP ${n.status}`);const o=await n.json(),c=s.ok?await s.json():null,i=o.lesson_count??0,a=o.total_recall_count??0,m=Math.round(o.iq_boost_pct??0),d=o.team_authors??[],l=c?.referral_count??0,p=c?.url??"",y=i===0?"Intern \u{1F331}":i<10?"Junior Dev \u{1F527}":i<30?"Mid Dev \u26A1":i<60?"Senior Dev \u{1F9E0}":i<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}",w=i>0?"\x1B[32m\u25CF\x1B[0m":"\x1B[33m\u25CF\x1B[0m";if(console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 ${w} \x1B[1mBrain status\x1B[0m \xB7 instance ${t.slice(0,8)}... \u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Lessons : \x1B[33m${String(i).padEnd(8)}\x1B[0m Level : \x1B[32m${y.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Recalls : \x1B[36m${String(a).padEnd(8)}\x1B[0m Quality score: \x1B[32m${String(m).padEnd(3)}%\x1B[0m \u2502`),d.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const f=d.slice(0,4).join(", ");console.log(`\u2502 \x1B[36m\u{1F465} Team Brain\x1B[0m \xB7 ${String(d.length).padEnd(2)} developer${d.length===1?" ":"s"} sharing lessons${" ".repeat(Math.max(0,19-f.length))} \u2502`),console.log(`\u2502 ${f.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 f=`${p.slice(0,44)}${p.length>44?"\u2026":""}`;console.log(`\u2502 \x1B[35m\u{1F517} Invite link\x1B[0m \xB7 ${l>0?`\x1B[32m${l} joined\x1B[0m`:"share to grow your team"}${" ".repeat(Math.max(0,35-String(l).length))} \u2502`),console.log(`\u2502 \x1B[2m${f.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(""),i===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(`
237
237
  \u274C Could not fetch status: ${n.message}
238
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="health"){const{existsSync:e}=await import("node:fs"),{readFile:t}=await import("node:fs/promises"),{resolve:n}=await import("node:path"),s=process.cwd();let o=0,c=0;const r=p=>{console.log(` \u2705 ${p}`),o++},a=p=>{console.log(` \u26A0\uFE0F ${p}`)},u=p=>{console.log(` \u274C ${p}`),c++};console.log(`
238
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="health"){const{existsSync:e}=await import("node:fs"),{readFile:t}=await import("node:fs/promises"),{resolve:n}=await import("node:path"),s=process.cwd();let o=0,c=0;const i=u=>{console.log(` \u2705 ${u}`),o++},a=u=>{console.log(` \u26A0\uFE0F ${u}`)},m=u=>{console.log(` \u274C ${u}`),c++};console.log(`
239
239
  \u{1F9E0} cachly health check
240
- `),console.log("\u{1F511} Auth token");const d=process.env.CACHLY_JWT??"";if(!d)u("CACHLY_JWT not set \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(d.startsWith("cky_"))r("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const p=d.split(".");if(p.length!==3)throw new Error("not a JWT");const i=JSON.parse(Buffer.from(p[1],"base64url").toString("utf-8")),w=i.exp?i.exp*1e3:null,f=w?Math.floor((w-Date.now())/6e4):null;w&&w<Date.now()?u(`JWT expired ${Math.abs(f)} minute(s) ago \u2014 get a new one: ${R("/setup-ai","health")}`):f!==null&&f<30?a(`JWT expires in ${f} minute(s) \u2014 refresh soon at ${R("/setup-ai","health")}`):r(`JWT valid${f!==null?` (expires in ${Math.floor(f/60)}h ${f%60}m)`:""}`)}catch{u("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
241
- \u{1F310} Brain API`);const l=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const p=await fetch(`${l}/health`,{signal:AbortSignal.timeout(5e3)});if(p.ok){const i=await p.json();r(`${l} reachable (status: ${i.status??"ok"})`)}else p.status===401||p.status===403?r(`${l} reachable (auth required \u2014 expected)`):u(`${l}/health returned HTTP ${p.status}`)}catch(p){u(`${l} unreachable \u2014 ${p.message}`)}console.log(`
242
- \u{1F9E0} Brain instance`);const g=process.env.CACHLY_BRAIN_INSTANCE_ID??"";if(!g)a("CACHLY_BRAIN_INSTANCE_ID not set \u2014 will auto-resolve on first tool call");else if(d)try{const p=await fetch(`${l}/api/v1/instances/${g}`,{headers:{Authorization:`Bearer ${d}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(p.ok){const i=await p.json();if(i.status==="running")if(r(`Instance "${i.name}" (${g.slice(0,8)}\u2026) is running`),console.log(`
243
- \u{1F50C} Redis connectivity`),i.host&&i.port)try{let w,f=i.tls_enabled!==!1;try{const S=await fetch(`${l}/api/v1/instances/${g}/connection`,{headers:{Authorization:`Bearer ${d}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(S.ok){const $=await S.json();w=$.password,f=$.tls_enabled!==!1}}catch{}const N=new De({host:i.host,port:i.port,password:w,...f?{tls:{}}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await N.connect();const j=await N.ping();N.disconnect(),j==="PONG"?r(`Redis PING \u2192 PONG (${i.host}:${i.port})`):a(`Redis responded but not PONG: ${j}`)}catch(w){u(`Redis unreachable \u2014 ${w.message}`)}else a("Instance has no host/port yet");else a(`Instance "${i.name}" status: ${i.status}`)}else u(`Instance ${g.slice(0,8)}\u2026 not found (HTTP ${p.status})`)}catch(p){u(`Could not check instance \u2014 ${p.message}`)}console.log(`
244
- \u{1F6E0} Editor configs (project dir)`);const y=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:".windsurf/mcp.json"},{editor:"Copilot / Cline",path:".vscode/mcp.json"},{editor:"Zed",path:".zed/settings.json"},{editor:"Continue.dev",path:".continue/config.json"}];let v=0;for(const{editor:p,path:i}of y){const w=n(s,i);if(e(w))try{const f=await t(w,"utf-8");f.includes("@cachly-dev/mcp-server")||f.includes("cachly")?(r(`${p}: ${i}`),v++):a(`${p}: ${i} exists but cachly not found inside`)}catch{a(`${p}: ${i} exists but could not read`)}}v===0&&u("No editor MCP configs found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot"),console.log(`
245
- \u{1FA9D} Git hook (ambient learning)`);const h=n(s,".git","hooks","post-commit");if(!e(n(s,".git")))a("Not in a git repository \u2014 skip");else if(e(h))try{(await t(h,"utf-8")).includes("cachly")?r(".git/hooks/post-commit (cachly CLS hook present)"):a(".git/hooks/post-commit exists but cachly hook not found \u2014 run setup to add it")}catch{a(".git/hooks/post-commit exists but could not read")}else a(".git/hooks/post-commit not found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");console.log(`
246
- \u{1F9EC} Embedding provider (semantic search)`);{const p=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],i=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase(),w=p.find(([f])=>process.env[f]);if(i&&i!=="cachly"){const f=p.find(([,N])=>N===i)?.[0];f&&process.env[f]?r(`BYOK: ${i} (key present in ${f})`):a(`CACHLY_EMBED_PROVIDER=${i} but its key env var is not set \u2014 semantic search will fail`)}else r(w?`BYOK: ${w[1]} auto-detected (${w[0]} present)`:"Server-side embeddings (cachly) \u2014 no key needed, uses your JWT")}console.log(`
240
+ `),console.log("\u{1F511} Auth token");const d=process.env.CACHLY_JWT??"";if(!d)m("CACHLY_JWT not set \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");else if(d.startsWith("cky_"))i("Long-lived API key set (cky_\u2026) \u2014 no client-side expiry");else try{const u=d.split(".");if(u.length!==3)throw new Error("not a JWT");const r=JSON.parse(Buffer.from(u[1],"base64url").toString("utf-8")),b=r.exp?r.exp*1e3:null,h=b?Math.floor((b-Date.now())/6e4):null;b&&b<Date.now()?m(`JWT expired ${Math.abs(h)} minute(s) ago \u2014 get a new one: ${R("/setup-ai","health")}`):h!==null&&h<30?a(`JWT expires in ${h} minute(s) \u2014 refresh soon at ${R("/setup-ai","health")}`):i(`JWT valid${h!==null?` (expires in ${Math.floor(h/60)}h ${h%60}m)`:""}`)}catch{m("CACHLY_JWT format invalid (expected a cky_ API key or a 3-part JWT)")}console.log(`
241
+ \u{1F310} Brain API`);const l=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const u=await fetch(`${l}/health`,{signal:AbortSignal.timeout(5e3)});if(u.ok){const r=await u.json();i(`${l} reachable (status: ${r.status??"ok"})`)}else u.status===401||u.status===403?i(`${l} reachable (auth required \u2014 expected)`):m(`${l}/health returned HTTP ${u.status}`)}catch(u){m(`${l} unreachable \u2014 ${u.message}`)}console.log(`
242
+ \u{1F9E0} Brain instance`);const p=process.env.CACHLY_BRAIN_INSTANCE_ID??"";if(!p)a("CACHLY_BRAIN_INSTANCE_ID not set \u2014 will auto-resolve on first tool call");else if(d)try{const u=await fetch(`${l}/api/v1/instances/${p}`,{headers:{Authorization:`Bearer ${d}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(u.ok){const r=await u.json();if(r.status==="running")if(i(`Instance "${r.name}" (${p.slice(0,8)}\u2026) is running`),console.log(`
243
+ \u{1F50C} Redis connectivity`),r.host&&r.port)try{let b,h=r.tls_enabled!==!1;try{const S=await fetch(`${l}/api/v1/instances/${p}/connection`,{headers:{Authorization:`Bearer ${d}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(S.ok){const $=await S.json();b=$.password,h=$.tls_enabled!==!1}}catch{}const N=new Me({host:r.host,port:r.port,password:b,...h?{tls:{}}:{},lazyConnect:!0,connectTimeout:5e3,retryStrategy:()=>null});await N.connect();const j=await N.ping();N.disconnect(),j==="PONG"?i(`Redis PING \u2192 PONG (${r.host}:${r.port})`):a(`Redis responded but not PONG: ${j}`)}catch(b){m(`Redis unreachable \u2014 ${b.message}`)}else a("Instance has no host/port yet");else a(`Instance "${r.name}" status: ${r.status}`)}else m(`Instance ${p.slice(0,8)}\u2026 not found (HTTP ${u.status})`)}catch(u){m(`Could not check instance \u2014 ${u.message}`)}console.log(`
244
+ \u{1F6E0} Editor configs (project dir)`);const y=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:".windsurf/mcp.json"},{editor:"Copilot / Cline",path:".vscode/mcp.json"},{editor:"Zed",path:".zed/settings.json"},{editor:"Continue.dev",path:".continue/config.json"}];let w=0;for(const{editor:u,path:r}of y){const b=n(s,r);if(e(b))try{const h=await t(b,"utf-8");h.includes("@cachly-dev/mcp-server")||h.includes("cachly")?(i(`${u}: ${r}`),w++):a(`${u}: ${r} exists but cachly not found inside`)}catch{a(`${u}: ${r} exists but could not read`)}}w===0&&m("No editor MCP configs found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot"),console.log(`
245
+ \u{1FA9D} Git hook (ambient learning)`);const f=n(s,".git","hooks","post-commit");if(!e(n(s,".git")))a("Not in a git repository \u2014 skip");else if(e(f))try{(await t(f,"utf-8")).includes("cachly")?i(".git/hooks/post-commit (cachly CLS hook present)"):a(".git/hooks/post-commit exists but cachly hook not found \u2014 run setup to add it")}catch{a(".git/hooks/post-commit exists but could not read")}else a(".git/hooks/post-commit not found \u2014 run: npx @cachly-dev/mcp-server@latest autopilot");console.log(`
246
+ \u{1F9EC} Embedding provider (semantic search)`);{const u=[["OPENAI_API_KEY","openai"],["GEMINI_API_KEY","gemini"],["MISTRAL_API_KEY","mistral"],["COHERE_API_KEY","cohere"],["OLLAMA_BASE_URL","ollama"]],r=(process.env.CACHLY_EMBED_PROVIDER??"").toLowerCase(),b=u.find(([h])=>process.env[h]);if(r&&r!=="cachly"){const h=u.find(([,N])=>N===r)?.[0];h&&process.env[h]?i(`BYOK: ${r} (key present in ${h})`):a(`CACHLY_EMBED_PROVIDER=${r} but its key env var is not set \u2014 semantic search will fail`)}else i(b?`BYOK: ${b[1]} auto-detected (${b[0]} present)`:"Server-side embeddings (cachly) \u2014 no key needed, uses your JWT")}console.log(`
247
247
  ${"\u2500".repeat(40)}`),c===0?console.log(`\u2705 All checks passed (${o} ok)
248
248
  `):(console.log(`\u274C ${c} check(s) failed, ${o} passed
249
249
  `),console.log(`\u{1F4A1} Fix issues with: npx @cachly-dev/mcp-server@latest autopilot
250
- `),process.exit(1)),process.exit(0)}const me=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||me){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:c}=await import("node:path"),{createInterface:r}=await import("node:readline"),a=Date.now(),u=me?"autopilot":"setup",d=process.argv.indexOf("--api-url");d!==-1&&process.argv[d+1]&&(_=process.argv[d+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${_}
251
- `)),A("setup_started");const l=process.stdin.isTTY===!0,g=me||process.argv.includes("--yes")||process.argv.includes("-y")||!l;me?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
250
+ `),process.exit(1)),process.exit(0)}if(process.argv[2]==="claim"){const{readFile:e,writeFile:t}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:s}=await import("node:path"),{homedir:o}=await import("node:os"),c=r=>{const b=process.argv.indexOf(`--${r}`);return b!==-1?process.argv[b+1]:void 0};_=(c("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const i=(c("auth-url")??Qe).replace(/\/+$/,"");console.log(`
251
+ \u{1F9E0} cachly \u2014 keep your test Brain in your own account
252
+ `),(_!=="https://api.cachly.dev"||i!==Qe)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${_}, sign-in ${i}
253
+ `);const a=Ro({argument:c("key"),credentials:Io()});a||(console.log("No test key (cky_trial_\u2026) was found in ~/.cachly/credentials.json."),console.log("If you already use your own cachly account, there is nothing to claim."),console.log(`Otherwise pass the key: npx @cachly-dev/mcp-server@latest claim --key cky_trial_\u2026
254
+ `),process.exit(1));const m=a.schluessel,d={argument:"--key",credentials:"~/.cachly/credentials.json"}[a.quelle];console.log(`Test key: ${m.slice(0,14)}\u2026 (from ${d})
255
+ `);let l="";try{console.log(`Step 1: Sign in to your cachly account
256
+ `);const r=await No(fetch,i);console.log(` Code: \x1B[1;33m${r.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${r.adresse}
257
+ `),se(r.adresse,(b,h)=>{b||console.log(`
258
+ \u2139\uFE0F No browser could be opened here (${h??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),l=await Lo(fetch,r,{basis:i,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
259
+ `)}catch(r){console.error(`
260
+
261
+ ${r.message}. Nothing was changed.
262
+ `),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 Bo(fetch,_,l,m,"mcp",`cachly-mcp/${M}`),console.log(` \x1B[32m\u2713\x1B[0m
263
+ `)}catch(r){console.error(`
264
+
265
+ ${Ho(r)}
266
+ `),process.exit(1)}x=p.apiKey,re(p.apiKey),Ze(p.instanceId,{apiKey:p.apiKey}),await ue(p.apiKey),await me(p.instanceId);const y=o(),w=new Set([...Object.values(he).map(r=>s(process.cwd(),r)),s(y,".claude.json"),s(y,".claude","mcp.json"),s(y,".cursor","mcp.json"),s(y,".codeium","windsurf","mcp_config.json")]);let f=0;for(const r of w)if(n(r))try{const b=Oo(await e(r,"utf-8"),m,p.apiKey);b.ersetzt&&(await t(r,b.text,"utf-8"),f++)}catch{}const u=await jo(fetch,_,p.apiKey,p.instanceId);console.log(Po(p,u)),console.log(`
267
+ New key stored in ~/.cachly/credentials.json${f?` and in ${f} 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.
268
+ `),process.exit(0)}const ye=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||ye){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:s}=await import("node:fs"),{resolve:o,dirname:c}=await import("node:path"),{createInterface:i}=await import("node:readline"),a=Date.now(),m=ye?"autopilot":"setup",d=process.argv.indexOf("--api-url");d!==-1&&process.argv[d+1]&&(_=process.argv[d+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${_}
269
+ `)),C("setup_started");const l=process.stdin.isTTY===!0,p=ye||process.argv.includes("--yes")||process.argv.includes("-y")||!l;ye?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
252
270
  `):!l&&!process.argv.includes("--yes")&&!process.argv.includes("-y")&&console.log(`\u2139\uFE0F Non-interactive terminal detected \u2014 running in automatic mode (no prompts).
253
- `);const y=r({input:process.stdin,output:process.stdout}),v=(m,C="")=>g?(console.log(`${m}${C}`),Promise.resolve(C)):new Promise(E=>y.question(m,J=>E(J.trim()||C)));console.log(`
271
+ `);const y=i({input:process.stdin,output:process.stdout}),w=(g,A="")=>p?(console.log(`${g}${A}`),Promise.resolve(A)):new Promise(E=>y.question(g,J=>E(J.trim()||A)));console.log(`
254
272
  \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
255
- `);let h=process.env.CACHLY_JWT??"";if(h)console.log(`\u2713 Using token from CACHLY_JWT env var
273
+ `);let f=process.env.CACHLY_JWT??"";if(f)console.log(`\u2713 Using token from CACHLY_JWT env var
256
274
  `);else{console.log(`Step 1: Sign in to cachly (free, no credit card)
257
- `),A("setup_auth_started");let m="",C="",E="",J=5e3,Y=!1,Q="cachly";try{const q=await fetch(`${_}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(q.ok){const L=await q.json();m=L.device_code,C=L.user_code;const O=L.verification_uri||R("/device",u);E=`${O}${O.includes("?")?"&":"?"}code=${encodeURIComponent(C)}`,J=(L.interval??5)*1e3,Y=!!m}}catch{}if(!Y)try{const L=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(L.ok){const O=await L.json();m=O.device_code,C=O.user_code,E=O.verification_uri_complete,J=(O.interval??5)*1e3,Y=!0,Q="keycloak"}}catch{}if(Y&&m){console.log(` Code: \x1B[1;33m${C}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${E}
258
- `),ae(E,(L,O)=>{if(L){A("device_browser_opened",{stelle:"setup"});return}A("device_browser_failed",{reason:O??"unknown",stelle:"setup"}),console.log(` \u2139\uFE0F No browser could be opened here (${O??"unknown"}) \u2014 please open the URL yourself.
259
- `)}),process.stdout.write(" Waiting for authorization");const q=Date.now()+600*1e3;for(;Date.now()<q;){await new Promise(L=>setTimeout(L,J)),process.stdout.write(".");try{let L=null;if(Q==="cachly")try{const O=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:m}),signal:AbortSignal.timeout(8e3)});O.status<500&&(L=await O.json())}catch{}else{const O="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{L=await(await fetch(`${O}/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=${m}`,signal:AbortSignal.timeout(8e3)})).json()}catch{}}if(L?.access_token){h=L.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
260
- `),A("setup_auth_completed"),A("device_flow_completed");break}L?.error==="slow_down"?J=Math.min(J+2e3,15e3):L?.error&&L.error!=="authorization_pending"&&(A("device_flow_failed",{reason:L.error}),console.error(`
275
+ `),C("setup_auth_started");let g="",A="",E="",J=5e3,Y=!1,Z="cachly";try{const q=await fetch(`${_}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(q.ok){const L=await q.json();g=L.device_code,A=L.user_code;const O=L.verification_uri||R("/device",m);E=`${O}${O.includes("?")?"&":"?"}code=${encodeURIComponent(A)}`,J=(L.interval??5)*1e3,Y=!!g}}catch{}if(!Y)try{const L=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(L.ok){const O=await L.json();g=O.device_code,A=O.user_code,E=O.verification_uri_complete,J=(O.interval??5)*1e3,Y=!0,Z="keycloak"}}catch{}if(Y&&g){console.log(` Code: \x1B[1;33m${A}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${E}
276
+ `),se(E,(L,O)=>{if(L){C("device_browser_opened",{stelle:"setup"});return}C("device_browser_failed",{reason:O??"unknown",stelle:"setup"}),console.log(` \u2139\uFE0F No browser could be opened here (${O??"unknown"}) \u2014 please open the URL yourself.
277
+ `)}),process.stdout.write(" Waiting for authorization");const q=Date.now()+600*1e3;for(;Date.now()<q;){await new Promise(L=>setTimeout(L,J)),process.stdout.write(".");try{let L=null;if(Z==="cachly")try{const O=await fetch(`${_}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:g}),signal:AbortSignal.timeout(8e3)});O.status<500&&(L=await O.json())}catch{}else{const O="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{L=await(await fetch(`${O}/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=${g}`,signal:AbortSignal.timeout(8e3)})).json()}catch{}}if(L?.access_token){f=L.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
278
+ `),C("setup_auth_completed"),C("device_flow_completed");break}L?.error==="slow_down"?J=Math.min(J+2e3,15e3):L?.error&&L.error!=="authorization_pending"&&(C("device_flow_failed",{reason:L.error}),console.error(`
261
279
  Auth error: ${L.error}. Aborting.
262
- `),y.close(),process.exit(1))}catch{}}h||(A("device_flow_failed",{reason:"timeout"}),console.error(`
280
+ `),y.close(),process.exit(1))}catch{}}f||(C("device_flow_failed",{reason:"timeout"}),console.error(`
263
281
  Timed out waiting for authorization. Aborting.
264
- `),y.close(),process.exit(1)),console.log("")}else{A("device_flow_failed",{reason:"device_flow_unavailable"});const q=R("/setup-ai",u);console.log(` \u26A0\uFE0F Could not start automatic sign-in. Opening browser for web sign-in...
282
+ `),y.close(),process.exit(1)),console.log("")}else{C("device_flow_failed",{reason:"device_flow_unavailable"});const q=R("/setup-ai",m);console.log(` \u26A0\uFE0F Could not start automatic sign-in. Opening browser for web sign-in...
265
283
  `),console.log(` URL: \x1B[36m${q}\x1B[0m`),console.log(" 1. Sign up / log in at the URL above"),console.log(" 2. Go to Settings \u2192 API Keys \u2192 Create new key"),console.log(` 3. Copy the key (starts with cky_live_...)
266
- `),ae(q),g?(A("device_flow_failed",{reason:"non_interactive_no_key"}),console.error(`
284
+ `),se(q),p?(C("device_flow_failed",{reason:"non_interactive_no_key"}),console.error(`
267
285
  \u26A0\uFE0F This terminal is non-interactive, so the key cannot be pasted here.`),console.error(` Get your key at the URL above, then set it and re-run setup:
268
286
  `),console.error(` \x1B[1mCACHLY_JWT=cky_live_xxx npx @cachly-dev/mcp-server@latest autopilot\x1B[0m
269
287
  `),console.error(` Or add it to your editor's MCP config under env.CACHLY_JWT.
270
- `),y.close(),process.exit(1)):(h=await v(" Paste API key (cky_live_...): "),h||(console.error(`
288
+ `),y.close(),process.exit(1)):(f=await w(" Paste API key (cky_live_...): "),f||(console.error(`
271
289
  API key is required. Aborting.
272
- `),y.close(),process.exit(1)),A("setup_auth_completed"),console.log(""))}}if(h.startsWith("eyJ")){process.stdout.write("\u23F3 Generating your API key...");try{const m=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({name:"cachly-mcp-setup",scope:"read_write"})});if(!m.ok)throw new Error(`HTTP ${m.status}`);const C=await m.json();if(!C.key)throw new Error("no key in response");h=C.key,console.log(` \u2713
290
+ `),y.close(),process.exit(1)),C("setup_auth_completed"),console.log(""))}}if(f.startsWith("eyJ")){process.stdout.write("\u23F3 Generating your API key...");try{const g=await fetch(`${_}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({name:"cachly-mcp-setup",scope:"read_write"})});if(!g.ok)throw new Error(`HTTP ${g.status}`);const A=await g.json();if(!A.key)throw new Error("no key in response");f=A.key,console.log(` \u2713
273
291
  `)}catch{console.log(` (skipped)
274
- `)}}process.stdout.write("\u23F3 Fetching your instances...");let p=[];try{const m=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${h}`}});if(!m.ok)throw new Error(`HTTP ${m.status}`);p=((await m.json()).data??[]).filter(E=>E.status==="running")}catch(m){const C=m.message;console.error(`
275
-
276
- Failed to fetch instances: ${C}`),C.includes("401")&&(console.error(`Token rejected. Get a valid token at ${R("/setup-ai",u)}
277
- `),ae(R("/setup-ai",u))),y.close(),process.exit(1)}if(console.log(` found ${p.length}
278
- `),p.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const m=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"}});if(!m.ok)throw new Error(`HTTP ${m.status}`);const C=await m.json();if(C.instance)p=[C.instance];else if(C.instance_id){const E=C.instance_id;console.log(` \u2713 created (${E.slice(0,8)}\u2026)
279
- `),process.stdout.write("\u23F3 Waiting for instance to start");for(let J=0;J<45;J++){await new Promise(Y=>setTimeout(Y,3e3)),process.stdout.write(".");try{const Y=await fetch(`${_}/api/v1/instances/${E}`,{headers:{Authorization:`Bearer ${h}`}});if(Y.ok){const Q=await Y.json();if(Q.status==="running"){p=[Q];break}}}catch{}}console.log("")}}catch(m){console.log(` failed: ${m.message}
280
- `)}p.length===0&&(console.error(`
281
- Could not create an instance automatically. Opening ${R("/instances",u)} \u2026
282
- `),ae(R("/instances",u)),y.close(),process.exit(1))}const i=p[0];p.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${i.name}`),console.log(` (Run with --instance-id <id> to use a different one)
283
- `)),console.log(`\u2713 Instance: ${i.name} (${i.id.slice(0,8)}\u2026)
284
- `),A("setup_instance_ready",{instance_id:i.id});const w=process.cwd(),f=[],{homedir:N}=await import("node:os"),j=N();f.push("claude"),s(o(w,".cursor"))&&f.push("cursor"),s(o(w,".windsurf"))&&f.push("windsurf"),s(o(w,".vscode"))&&f.push("copilot"),s(o(w,".continue"))&&f.push("continue");const S=process.platform==="darwin"?o(j,"Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev"):o(j,".vscode/extensions");(s(S)&&!f.includes("copilot")||s(S))&&f.push("cline");const $=process.platform==="darwin"?o(j,"Library/Application Support/Zed"):o(j,".config/zed");s($)&&f.push("zed");const k=m=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[m]??m,T=f;console.log(`Step 3: Configuring for: ${T.map(k).join(", ")}
285
- `);const{existsSync:H}=await import("node:fs"),b=[];let I=0;K(h);for(const m of T){const C=Se[m]??".mcp.json",E=o(w,C);try{await t(c(E),{recursive:!0});const J=H(E),Y=await bt(E,h,i.id,m,{readFile:n,existsSync:H});await e(E,Y,"utf-8"),console.log(`\u2705 ${J?"Updated":"Written"}: ${C}`),I++}catch(J){const Y=J.message;console.log(`\u26A0\uFE0F Could not write ${C}: ${Y}`),console.log(" Fix permissions or run with sudo, then re-run setup."),b.push({file:C,reason:Y})}}const F=o(j,".claude","mcp.json");try{await t(c(F),{recursive:!0});let m={};if(s(F))try{m=JSON.parse(await n(F,"utf-8"))}catch{}m.mcpServers??={},m.mcpServers.cachly={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:re(h,i.id,{includeApiKey:!0})},await e(F,JSON.stringify(m,null,2),"utf-8"),console.log("\u2705 Written: ~/.claude/mcp.json (global \u2014 works in every project)"),I++}catch(m){const C=m.message;console.log(`\u26A0\uFE0F Could not write ~/.claude/mcp.json: ${C}`),b.push({file:"~/.claude/mcp.json",reason:C})}const z=await wt(w,i.id);for(const[m,C]of Object.entries(z))console.log(`${C==="updated"?"\u2705 Updated":C==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${m}`);x=h;let oe=0;if(s(o(w,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const m=await U("brain_from_git",{instance_id:i.id,repo_path:w,limit:100}),C=m.match(/Ingested: \*\*(\d+)\*\*/);oe=C?parseInt(C[1],10):0,console.log(` \u2713 ${oe} lesson${oe===1?"":"s"} extracted from git history`);const E=bo(m);E&&(console.log(""),console.log(E))}catch(m){console.log(` (skipped: ${m.message.slice(0,80)})`)}}if(oe===0){process.stdout.write("\u{1F331} Seeding 16 universal engineering lessons (first recall works instantly)...");try{await U("brain_seed_starter",{instance_id:i.id}),console.log(" \u2713");try{const m=await U("smart_recall",{instance_id:i.id,query:"docker build slow"}),C=en(m);C&&(console.log(""),console.log(vo(C.topic,C.what)))}catch{}}catch(m){console.log(` (skipped: ${m.message.slice(0,60)})`)}}process.stdout.write(`
286
- \u23F3 Fetching your Brain health preview...`);try{const m=await fetch(`${_}/api/v1/instances/${i.id}/memory`,{headers:{Authorization:`Bearer ${h}`},signal:AbortSignal.timeout(6e3)});if(m.ok){const C=await m.json(),E=C.lesson_count??0,J=C.context_count??0,Y=Math.round(C.iq_boost_pct??0),Q=E===0?"Intern \u{1F331}":E<10?"Junior Dev \u{1F527}":E<30?"Mid Dev \u26A1":E<60?"Senior Dev \u{1F9E0}":E<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}";if(console.log(` \u2713
287
- `),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\u2510"),console.log("\u2502 \u{1F9E0} Brain Health Report \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\u2524"),console.log(`\u2502 Lessons stored : ${String(E).padEnd(6)} \u2502 Level: ${Q.padEnd(20)}\u2502`),console.log(`\u2502 Context entries : ${String(J).padEnd(6)} \u2502 Quality score: ${String(Y).padEnd(3)}% \u2502`),E===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\u2524"),console.log("\u2502 Your Brain is empty and ready to learn. \u2502"),console.log("\u2502 After your first coding session it will contain: \u2502"),console.log("\u2502 \u2022 Lessons from every bug you fixed \u2502"),console.log("\u2502 \u2022 Your project's indexed files \u2502"),console.log("\u2502 \u2022 A session summary for next time \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\u2518"),E>=5){process.stdout.write(`
288
- \u23F3 Running predictive risk scan...`);try{const L=(await U("brain_predict",{instance_id:i.id,context:"starting a new development session"})).split(`
292
+ `)}}process.stdout.write("\u23F3 Fetching your instances...");let u=[];try{const g=await fetch(`${_}/api/v1/instances`,{headers:{Authorization:`Bearer ${f}`}});if(!g.ok)throw new Error(`HTTP ${g.status}`);u=((await g.json()).data??[]).filter(E=>E.status==="running")}catch(g){const A=g.message;console.error(`
293
+
294
+ Failed to fetch instances: ${A}`),A.includes("401")&&(console.error(`Token rejected. Get a valid token at ${R("/setup-ai",m)}
295
+ `),se(R("/setup-ai",m))),y.close(),process.exit(1)}if(console.log(` found ${u.length}
296
+ `),u.length===0){process.stdout.write("\u23F3 Creating your free Brain instance...");try{const g=await fetch(`${_}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!g.ok)throw new Error(`HTTP ${g.status}`);const A=await g.json();if(A.instance)u=[A.instance];else if(A.instance_id){const E=A.instance_id;console.log(` \u2713 created (${E.slice(0,8)}\u2026)
297
+ `),process.stdout.write("\u23F3 Waiting for instance to start");for(let J=0;J<45;J++){await new Promise(Y=>setTimeout(Y,3e3)),process.stdout.write(".");try{const Y=await fetch(`${_}/api/v1/instances/${E}`,{headers:{Authorization:`Bearer ${f}`}});if(Y.ok){const Z=await Y.json();if(Z.status==="running"){u=[Z];break}}}catch{}}console.log("")}}catch(g){console.log(` failed: ${g.message}
298
+ `)}u.length===0&&(console.error(`
299
+ Could not create an instance automatically. Opening ${R("/instances",m)} \u2026
300
+ `),se(R("/instances",m)),y.close(),process.exit(1))}const r=u[0];u.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${r.name}`),console.log(` (Run with --instance-id <id> to use a different one)
301
+ `)),console.log(`\u2713 Instance: ${r.name} (${r.id.slice(0,8)}\u2026)
302
+ `),C("setup_instance_ready",{instance_id:r.id});const b=process.cwd(),h=[],{homedir:N}=await import("node:os"),j=N();h.push("claude"),s(o(b,".cursor"))&&h.push("cursor"),s(o(b,".windsurf"))&&h.push("windsurf"),s(o(b,".vscode"))&&h.push("copilot"),s(o(b,".continue"))&&h.push("continue");const S=process.platform==="darwin"?o(j,"Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev"):o(j,".vscode/extensions");(s(S)&&!h.includes("copilot")||s(S))&&h.push("cline");const $=process.platform==="darwin"?o(j,"Library/Application Support/Zed"):o(j,".config/zed");s($)&&h.push("zed");const k=g=>({claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",copilot:"GitHub Copilot",continue:"Continue.dev",cline:"Cline (VSCode)",zed:"Zed"})[g]??g,T=h;console.log(`Step 3: Configuring for: ${T.map(k).join(", ")}
303
+ `);const{existsSync:P}=await import("node:fs"),v=[];let I=0;re(f);for(const g of T){const A=he[g]??".mcp.json",E=o(b,A);try{await t(c(E),{recursive:!0});const J=P(E),Y=await xt(E,f,r.id,g,{readFile:n,existsSync:P});await e(E,Y,"utf-8"),console.log(`\u2705 ${J?"Updated":"Written"}: ${A}`),I++}catch(J){const Y=J.message;console.log(`\u26A0\uFE0F Could not write ${A}: ${Y}`),console.log(" Fix permissions or run with sudo, then re-run setup."),v.push({file:A,reason:Y})}}const F=o(j,".claude","mcp.json");try{await t(c(F),{recursive:!0});let g={};if(s(F))try{g=JSON.parse(await n(F,"utf-8"))}catch{}g.mcpServers??={},g.mcpServers.cachly={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ie(f,r.id,{includeApiKey:!0})},await e(F,JSON.stringify(g,null,2),"utf-8"),console.log("\u2705 Written: ~/.claude/mcp.json (global \u2014 works in every project)"),I++}catch(g){const A=g.message;console.log(`\u26A0\uFE0F Could not write ~/.claude/mcp.json: ${A}`),v.push({file:"~/.claude/mcp.json",reason:A})}const z=await $t(b,r.id);for(const[g,A]of Object.entries(z))console.log(`${A==="updated"?"\u2705 Updated":A==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${g}`);x=f;let te=0;if(s(o(b,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const g=await U("brain_from_git",{instance_id:r.id,repo_path:b,limit:100}),A=g.match(/Ingested: \*\*(\d+)\*\*/);te=A?parseInt(A[1],10):0,console.log(` \u2713 ${te} lesson${te===1?"":"s"} extracted from git history`);const E=xo(g);E&&(console.log(""),console.log(E))}catch(g){console.log(` (skipped: ${g.message.slice(0,80)})`)}}if(te===0){process.stdout.write("\u{1F331} Seeding 16 universal engineering lessons (first recall works instantly)...");try{await U("brain_seed_starter",{instance_id:r.id}),console.log(" \u2713");try{const g=await U("smart_recall",{instance_id:r.id,query:"docker build slow"}),A=fn(g);A&&(console.log(""),console.log(_o(A.topic,A.what)))}catch{}}catch(g){console.log(` (skipped: ${g.message.slice(0,60)})`)}}process.stdout.write(`
304
+ \u23F3 Fetching your Brain health preview...`);try{const g=await fetch(`${_}/api/v1/instances/${r.id}/memory`,{headers:{Authorization:`Bearer ${f}`},signal:AbortSignal.timeout(6e3)});if(g.ok){const A=await g.json(),E=A.lesson_count??0,J=A.context_count??0,Y=Math.round(A.iq_boost_pct??0),Z=E===0?"Intern \u{1F331}":E<10?"Junior Dev \u{1F527}":E<30?"Mid Dev \u26A1":E<60?"Senior Dev \u{1F9E0}":E<100?"Staff Eng \u{1F680}":"Principal Eng \u{1F3C6}";if(console.log(` \u2713
305
+ `),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\u2510"),console.log("\u2502 \u{1F9E0} Brain Health Report \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\u2524"),console.log(`\u2502 Lessons stored : ${String(E).padEnd(6)} \u2502 Level: ${Z.padEnd(20)}\u2502`),console.log(`\u2502 Context entries : ${String(J).padEnd(6)} \u2502 Quality score: ${String(Y).padEnd(3)}% \u2502`),E===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\u2524"),console.log("\u2502 Your Brain is empty and ready to learn. \u2502"),console.log("\u2502 After your first coding session it will contain: \u2502"),console.log("\u2502 \u2022 Lessons from every bug you fixed \u2502"),console.log("\u2502 \u2022 Your project's indexed files \u2502"),console.log("\u2502 \u2022 A session summary for next time \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\u2518"),E>=5){process.stdout.write(`
306
+ \u23F3 Running predictive risk scan...`);try{const L=(await U("brain_predict",{instance_id:r.id,context:"starting a new development session"})).split(`
289
307
  `).filter(O=>O.trim()).slice(0,6);if(L.length>0){console.log(` \u2713
290
308
  `),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\u2510"),console.log("\u2502 \u{1F52E} Brain Risk Preview (brain_predict) \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\u2524");for(const O of L)console.log(`\u2502 ${O.slice(0,51).padEnd(51)} \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\u2518")}else console.log(" (no risks found \u2014 clean slate!)")}catch{console.log(" (skipped)")}}}else console.log(" (skipped)")}catch{console.log(" (skipped)")}if(console.log(`
291
309
  \u{1F389} Your AI just got a permanent brain.`),console.log(` Restart your editor \u2014 from this session on, it arrives pre-briefed.
292
310
  `),console.log(` No more re-explaining your stack. No repeated mistakes.
293
- `),console.log(` Dashboard: ${R(`/instances/${i.id}`,u)}`),console.log(`
311
+ `),console.log(` Dashboard: ${R(`/instances/${r.id}`,m)}`),console.log(`
294
312
  \u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
295
- `),!g)try{if(console.log(`
296
- \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 v(" Set yourself as the first admin? (y/N): ","N")).toLowerCase()==="y"){const C=await v(' Your handle (e.g. "alice"): ');C.trim()&&await U("team_assign_role",{instance_id:i.id,handle:C.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${C.trim()} is now admin. Invite teammates:
297
- `),console.log(` team_assign_role(instance_id="${i.id}", handle="<teammate>", role="contributor", assigned_by="${C.trim()}")
313
+ `),!p)try{if(console.log(`
314
+ \u{1F451} Governance (optional \u2014 role model: admin \xB7 reviewer \xB7 contributor \xB7 viewer)`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),(await w(" Set yourself as the first admin? (y/N): ","N")).toLowerCase()==="y"){const A=await w(' Your handle (e.g. "alice"): ');A.trim()&&await U("team_assign_role",{instance_id:r.id,handle:A.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${A.trim()} is now admin. Invite teammates:
315
+ `),console.log(` team_assign_role(instance_id="${r.id}", handle="<teammate>", role="contributor", assigned_by="${A.trim()}")
298
316
  `))}else console.log(` Skipped \u2014 run team_assign_role at any time.
299
- `)}catch{}if(!g){const m=await v(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(m&&m.includes("@"))try{await fetch(`${_}/api/newsletter/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:m.trim().toLowerCase(),source:"mcp-setup"}),signal:AbortSignal.timeout(5e3)}),console.log(` \u2705 Subscribed \u2014 you'll only hear from us when it matters.
300
- `)}catch{}}try{const m=await We(process.cwd(),i.id,h||void 0);m==="written"?console.log(`
301
- \u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):m==="upgraded"?console.log(`
302
- \u2705 CLS git hook upgraded to ${Fe}.`):m==="appended"&&console.log(`
303
- \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(T.includes("claude"))try{const m=await ze(process.cwd(),i.id),C=m.scripts==="written"?"\u2705 Written":m.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${qe})`:"\u2713 Unchanged";console.log(`${C}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),m.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):m.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{}x=h;const Te=Math.round((Date.now()-a)/1e3);if(b.length>0&&A("setup_config_write_failed",{instance_id:i.id,failed:b.length,succeeded:I}),A("setup_completed",{instance_id:i.id,elapsed_s:Te,config_failures:b.length}),b.length>0&&I===0){console.log(`
317
+ `)}catch{}if(!p){const g=await w(" \u{1F4EC} Stay in the loop? Email for release notes [Enter to skip]: ");if(g&&g.includes("@"))try{await fetch(`${_}/api/newsletter/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:g.trim().toLowerCase(),source:"mcp-setup"}),signal:AbortSignal.timeout(5e3)}),console.log(` \u2705 Subscribed \u2014 you'll only hear from us when it matters.
318
+ `)}catch{}}try{const g=await Fe(process.cwd(),r.id,f||void 0);g==="written"?console.log(`
319
+ \u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):g==="upgraded"?console.log(`
320
+ \u2705 CLS git hook upgraded to ${ze}.`):g==="appended"&&console.log(`
321
+ \u2705 CLS git hook appended to existing post-commit.`)}catch{}if(T.includes("claude"))try{const g=await qe(process.cwd(),r.id),A=g.scripts==="written"?"\u2705 Written":g.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${Ke})`:"\u2713 Unchanged";console.log(`${A}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),g.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):g.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{}x=f;const Ie=Math.round((Date.now()-a)/1e3);if(v.length>0&&C("setup_config_write_failed",{instance_id:r.id,failed:v.length,succeeded:I}),C("setup_completed",{instance_id:r.id,elapsed_s:Ie,config_failures:v.length}),v.length>0&&I===0){console.log(`
304
322
  \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(`
305
- Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const m of b)console.log(` \u2022 ${m.file} \u2014 ${m.reason}`);console.log(`
306
- Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${h.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${i.id}`),console.log(` Docs: ${R("/docs/mcp",u)}
307
- `),y.close(),await new Promise(m=>setTimeout(m,300)),process.exit(1)}if(console.log(`
308
- \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557`),console.log("\u2551 \u{1F680} Brain is ready. \u2551"),console.log(`\u2551 \u23F1\uFE0F Setup completed in ${(Te+"s").padEnd(5)} \u2014 restart your editor \u2551`),console.log("\u2551 and your AI arrives pre-briefed every session. \u2551"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),b.length>0){console.log(`
309
- \u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const m of b)console.log(` \u2022 ${m.file} \u2014 ${m.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(""),y.close(),await new Promise(m=>setTimeout(m,300)),process.exit(0)}if(process.argv[2]==="index"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=a=>{const u=t.indexOf(`--${a}`);return u!==-1?t[u+1]:void 0},s=e(n("dir")??t.find(a=>!a.startsWith("--"))??"."),o=n("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,c=parseInt(n("max-files")??"500",10),r=n("namespace")??"cachly:sem:code";(!o||!x)&&(console.error(`
323
+ Your Brain instance exists, but no editor knows about it yet.`),console.log(" Failed writes:");for(const g of v)console.log(` \u2022 ${g.file} \u2014 ${g.reason}`);console.log(`
324
+ Fix the permissions above and re-run, or configure manually:`),console.log(` CACHLY_JWT=${f.slice(0,12)}\u2026 CACHLY_BRAIN_INSTANCE_ID=${r.id}`),console.log(` Docs: ${R("/docs/mcp",m)}
325
+ `),y.close(),await new Promise(g=>setTimeout(g,300)),process.exit(1)}if(console.log(`
326
+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557`),console.log("\u2551 \u{1F680} Brain is ready. \u2551"),console.log(`\u2551 \u23F1\uFE0F Setup completed in ${(Ie+"s").padEnd(5)} \u2014 restart your editor \u2551`),console.log("\u2551 and your AI arrives pre-briefed every session. \u2551"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),v.length>0){console.log(`
327
+ \u26A0\uFE0F Some editor configs could not be written (others succeeded):`);for(const g of v)console.log(` \u2022 ${g.file} \u2014 ${g.reason}`);console.log(" Fix the permissions above and re-run setup to configure them too.")}console.log(""),y.close(),await new Promise(g=>setTimeout(g,300)),process.exit(0)}if(process.argv[2]==="index"){const{resolve:e}=await import("node:path"),t=process.argv.slice(3),n=a=>{const m=t.indexOf(`--${a}`);return m!==-1?t[m+1]:void 0},s=e(n("dir")??t.find(a=>!a.startsWith("--"))??"."),o=n("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,c=parseInt(n("max-files")??"500",10),i=n("namespace")??"cachly:sem:code";(!o||!x)&&(console.error(`
310
328
  \u274C CACHLY_BRAIN_INSTANCE_ID and CACHLY_JWT must be set
311
329
  `),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
312
330
  `),process.exit(1)),console.log(`
313
331
  \u{1F4C2} Indexing: ${s}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max files: ${c}
314
- `);try{const a=await U("index_project",{instance_id:o,dir:s,max_files:c,ttl:604800,namespace:r});console.log(a),console.log(`
332
+ `);try{const a=await U("index_project",{instance_id:o,dir:s,max_files:c,ttl:604800,namespace:i});console.log(a),console.log(`
315
333
  \u2705 Indexing complete.
316
334
  `)}catch(a){console.error(`
317
335
  \u274C Indexing failed: ${a.message}
318
- `),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=r=>{const a=t.indexOf(`--${r}`);return a!==-1?t[a+1]:void 0},s=e(n("dir")??t.find(r=>!r.startsWith("--"))??"."),o=n("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,c=parseInt(n("max-commits")??"50",10);(!o||!x)&&(console.error(`
336
+ `),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=i=>{const a=t.indexOf(`--${i}`);return a!==-1?t[a+1]:void 0},s=e(n("dir")??t.find(i=>!i.startsWith("--"))??"."),o=n("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,c=parseInt(n("max-commits")??"50",10);(!o||!x)&&(console.error(`
319
337
  \u274C CACHLY_BRAIN_INSTANCE_ID and CACHLY_JWT must be set
320
338
  `),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 .
321
339
  `),process.exit(1)),console.log(`
322
340
  \u{1F9E0} Learning from git history: ${s}`),console.log(` Instance: ${o.slice(0,8)}\u2026 Max commits: ${c}
323
- `);try{const r=await U("brain_from_git",{instance_id:o,repo_path:s,limit:c});console.log(r),A("brain_from_git",{api_key:x,instance_id:o}),console.log(`
341
+ `);try{const i=await U("brain_from_git",{instance_id:o,repo_path:s,limit:c});console.log(i),C("brain_from_git",{api_key:x,instance_id:o}),console.log(`
324
342
  \u2705 Brain learned from your commits.
325
- `),await new Promise(a=>setTimeout(a,300))}catch(r){console.error(`
326
- \u274C learn-git failed: ${r.message}
327
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await wo(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await xo(),process.argv[2]==="ambient-credit"){try{const e=Math.round(Number(process.argv[3]));if(Number.isFinite(e)&&e>0){const t=Math.min(e,2e4),n=process.argv.slice(4).join(" ").slice(0,200)||void 0,s={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n};await $o(s),await on(process.env.CACHLY_BRAIN_INSTANCE_ID??B,s),console.log(`\u2705 ambient credit recorded: ${t} tokens${n?` (${n})`:""}`)}else console.error("Usage: npx @cachly-dev/mcp-server@latest ambient-credit <tokens-saved> [note]")}catch{}process.exit(0)}if(process.argv[2]==="ambient-stats"){const e=await Ge(),t=Ko(e),n=e.slice(-5);if(console.log(`
343
+ `),await new Promise(a=>setTimeout(a,300))}catch(i){console.error(`
344
+ \u274C learn-git failed: ${i.message}
345
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await $o(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await Ao(),process.argv[2]==="ambient-credit"){try{const e=Math.round(Number(process.argv[3]));if(Number.isFinite(e)&&e>0){const t=Math.min(e,2e4),n=process.argv.slice(4).join(" ").slice(0,200)||void 0,s={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n};await So(s),await yn(process.env.CACHLY_BRAIN_INSTANCE_ID??B,s),console.log(`\u2705 ambient credit recorded: ${t} tokens${n?` (${n})`:""}`)}else console.error("Usage: npx @cachly-dev/mcp-server@latest ambient-credit <tokens-saved> [note]")}catch{}process.exit(0)}if(process.argv[2]==="ambient-stats"){const e=await Ge(),t=dn(e),n=e.slice(-5);if(console.log(`
328
346
  \u{1F9E0} Ambient Recall \u2014 net-token ledger
329
347
  `),console.log(` Turns recorded: ${e.length}`),console.log(` Injected tokens: ${t.injected}`),console.log(` Prevented tokens: ${t.prevented} (agent-reported via ambient-credit)`),console.log(` NET: ${t.net>=0?"+":""}${t.net} tokens`),n.length>0){console.log(`
330
- Last entries:`);for(const s of n){const o=s.prevented>0?`+${s.prevented} prevented`:`-${s.injected} injected`;console.log(` \u2022 ${s.ts.slice(0,19)} ${s.event}: ${o}${s.note?` (${s.note})`:""}`)}}console.log(""),process.exit(0)}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:s,checkInstance:o,checkVectorCoverage:c,inspectAmbientHooks:r,checkHooks:a,checkLedger:u,renderDoctorReport:d,doctorExitCode:l}=await import("./doctor.js"),g=[e(),t(x),await n(_),await s(_,x),o(process.env.CACHLY_BRAIN_INSTANCE_ID??B),await c(_,x,process.env.CACHLY_BRAIN_INSTANCE_ID??B),a(r(process.cwd())),u(await Ge(),Co())];console.log(d(g)),process.exit(l(g))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!x)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??B;(!n||!t.source)&&process.exit(0),await U("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!x){const e=At();if(e)try{const t=await fetch(kt(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:St(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(x=n.access_token,ce(n.access_token),A("m2m_auth_completed",{grant:"client_credentials",client_id:e.clientId}),process.stderr.write(`\u{1F916} cachly: authenticated via client_credentials (M2M, headless).
348
+ Last entries:`);for(const s of n){const o=s.prevented>0?`+${s.prevented} prevented`:`-${s.injected} injected`;console.log(` \u2022 ${s.ts.slice(0,19)} ${s.event}: ${o}${s.note?` (${s.note})`:""}`)}}console.log(""),process.exit(0)}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:s,checkInstance:o,checkVectorCoverage:c,inspectAmbientHooks:i,checkHooks:a,checkLedger:m,renderDoctorReport:d,doctorExitCode:l}=await import("./doctor.js"),p=[e(),t(x),await n(_),await s(_,x),o(process.env.CACHLY_BRAIN_INSTANCE_ID??B),await c(_,x,process.env.CACHLY_BRAIN_INSTANCE_ID??B),a(i(process.cwd())),m(await Ge(),ko())];console.log(d(p)),process.exit(l(p))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!x)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??B;(!n||!t.source)&&process.exit(0),await U("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!x){const e=Tt();if(e)try{const t=await fetch(Et(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:It(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(x=n.access_token,ce(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).
331
349
  `))}else process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth failed (${t.status}). Check CACHLY_CLIENT_ID / CACHLY_CLIENT_SECRET.
332
- `),A("m2m_auth_failed",{status:t.status})}catch(t){process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth error: ${t.message}
333
- `),A("m2m_auth_failed",{reason:"network"})}}const bn=["demo","share","publish","health","autosetup","setup","autopilot","init","digest","invite","badge","join","upgrade","bench","tool-specs","openapi","ambient-credit","ambient-stats","doctor"];if(!x&&!bn.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&Bt){const s=`
350
+ `),C("m2m_auth_failed",{status:t.status})}catch(t){process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth error: ${t.message}
351
+ `),C("m2m_auth_failed",{reason:"network"})}}const Nn=["demo","share","publish","health","autosetup","setup","autopilot","init","digest","invite","badge","join","upgrade","bench","tool-specs","openapi","ambient-credit","ambient-stats","doctor"];if(!x&&!Nn.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&Ht){const s=`
334
352
  \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
335
353
  \u2551 \u{1F9E0} cachly AI Brain \u2014 Setup required \u2551
336
354
  \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
@@ -350,7 +368,7 @@ Could not create an instance automatically. Opening ${R("/instances",u)} \u2026
350
368
  \u{1F9E0} cachly: no API key yet \u2014 the first cachly tool call creates a test Brain on EU servers, no sign-up.
351
369
  (Own account: npx @cachly-dev/mcp-server@latest autopilot)
352
370
 
353
- `);else{const e=_t(x);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
371
+ `);else{const e=Ct(x);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
354
372
  \u26A0\uFE0F cachly: CACHLY_JWT expired ${Math.abs(t)} minute(s) ago.
355
373
  All tool calls will fail. Get a fresh token at ${R("/setup-ai","jwt-expiry")}
356
374
 
@@ -358,11 +376,7 @@ Could not create an instance automatically. Opening ${R("/instances",u)} \u2026
358
376
  \u26A0\uFE0F cachly: CACHLY_JWT expires in ${t} minute(s).
359
377
  Refresh it soon at ${R("/setup-ai","jwt-expiry")} to avoid interruptions.
360
378
 
361
- `)}}process.env.CACHLY_NO_UPDATE_CHECK||(async()=>{try{const e=await fetch("https://registry.npmjs.org/@cachly-dev/mcp-server/latest",{signal:AbortSignal.timeout(4e3)});if(e.ok){const n=(await e.json())?.version??"";n&&n!==M&&process.stderr.write(`
362
- \u26A1 cachly update available: ${M} \u2192 ${n}
363
- Run: npx @cachly-dev/mcp-server@latest autopilot
364
-
365
- `)}}catch{}})();const ge=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(ge){const{createServer:e}=await import("node:http");e((n,s)=>{const o=new URL(n.url??"/",`http://localhost:${ge}`);if(o.pathname==="/health"){s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({status:"ok",version:M,zeroResults:{total:ro,last10:so.slice(-10).map(c=>({query:c.query,ts:new Date(c.ts).toISOString()}))}}));return}if(o.pathname==="/mcp"||o.pathname==="/"){(async()=>{const c=gn(),r=new Ht({sessionIdGenerator:void 0});s.on("close",()=>{r.close().catch(()=>{}),c.close().catch(()=>{})});try{await c.connect(r),await r.handleRequest(n,s)}catch(a){process.stderr.write(`cachly-mcp HTTP: ${a.message}
366
- `),s.headersSent||(s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:a.message})))}})();return}s.writeHead(404),s.end("not found")}).listen(ge,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${ge}
367
- `)})}else{const e=new jt;W("start: Module geladen, stdio verbinden"),await V.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(Me=!0,Do(),Po(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 Session zu Ende, Server geht mit
368
- `),(async()=>{await Ae().catch(()=>{});for(const[,s]of te)await s.quit().catch(()=>{});process.exit(0)})()}))}Re("cachly","startup",{version:M,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{ft as CLAUDE_MD_MARKER_END,ke as CLAUDE_MD_MARKER_START,no as CROSS_LINGUAL_MAP,Se as EDITOR_FILES,Xt as STOPWORDS,to as arabicLightStem,vt as buildClaudeMdBlock,hn as buildMcpConfig,re as buildServerEnv,oo as expandCrossLingual,Qt as extractTimestamp,eo as katakanaToRomaji,Vt as levenshtein,bt as mergeMcpConfig,Zt as recencyBoost,io as reconnectOnce,Kt as splitMultiQuery,Wt as startBackgroundDevicePoll,Gt as tokenize,wt as writeInstructions};
379
+ `)}}process.env.PORT||Go({aktuelle:M});const be=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(be){const{createServer:e}=await import("node:http");e((n,s)=>{const o=new URL(n.url??"/",`http://localhost:${be}`);if(o.pathname==="/health"){s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({status:"ok",version:M,zeroResults:{total:co,last10:ao.slice(-10).map(c=>({query:c.query,ts:new Date(c.ts).toISOString()}))}}));return}if(o.pathname==="/mcp"||o.pathname==="/"){(async()=>{const c=Tn(),i=new Dt({sessionIdGenerator:void 0});s.on("close",()=>{i.close().catch(()=>{}),c.close().catch(()=>{})});try{await c.connect(i),await i.handleRequest(n,s)}catch(a){process.stderr.write(`cachly-mcp HTTP: ${a.message}
380
+ `),s.headersSent||(s.writeHead(500,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:a.message})))}})();return}s.writeHead(404),s.end("not found")}).listen(be,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${be}
381
+ `)})}else{const e=new Ot;W("start: Module geladen, stdio verbinden"),await G.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(Je=!0,Xo(),Zo(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 Session zu Ende, Server geht mit
382
+ `),(async()=>{await ke().catch(()=>{});for(const[,s]of ee)await s.quit().catch(()=>{});process.exit(0)})()}))}Ne("cachly","startup",{version:M,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{bt as CLAUDE_MD_MARKER_END,Te as CLAUDE_MD_MARKER_START,io as CROSS_LINGUAL_MAP,he as EDITOR_FILES,oo as STOPWORDS,so as arabicLightStem,_t as buildClaudeMdBlock,En as buildMcpConfig,ie as buildServerEnv,ro as expandCrossLingual,to as extractTimestamp,no as katakanaToRomaji,Xt as levenshtein,xt as mergeMcpConfig,eo as recencyBoost,lo as reconnectOnce,Qt as splitMultiQuery,qt as startBackgroundDevicePoll,Zt as tokenize,$t as writeInstructions};
@@ -0,0 +1,5 @@
1
+ import{mkdir as g,readFile as y,rename as w,writeFile as E}from"node:fs/promises";import{homedir as v}from"node:os";import{dirname as N,join as _}from"node:path";const b="https://registry.npmjs.org/@cachly-dev/mcp-server/latest",k=1440*60*1e3,S=2e3,x=new Set(["session_start","session_start_summary"]),A=/^v?(\d{1,9})\.(\d{1,9})\.(\d{1,9})(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/;function p(e){if(typeof e!="string"||e.length>64)return null;const t=A.exec(e.trim());return t?{kern:[Number(t[1]),Number(t[2]),Number(t[3])],vorab:t[4]?t[4].split("."):[]}:null}function m(e){return p(e)!==null}function z(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;for(let r=0;r<Math.max(e.length,t.length);r++){const s=e[r],n=t[r];if(s===void 0)return-1;if(n===void 0)return 1;const i=/^\d+$/.test(s),a=/^\d+$/.test(n);if(i&&a){if(Number(s)!==Number(n))return Number(s)<Number(n)?-1:1}else{if(i!==a)return i?-1:1;if(s!==n)return s<n?-1:1}}return 0}function d(e,t){const r=p(e),s=p(t);if(!r||!s)return!1;for(let n=0;n<3;n++)if(r.kern[n]!==s.kern[n])return r.kern[n]>s.kern[n];return z(r.vorab,s.vorab)>0}function C(e=process.env){const t=(e.CACHLY_UPDATE_CHECK??"").trim().toLowerCase();return t==="false"||t==="0"||t==="off"||t==="no"?!0:!!e.CACHLY_NO_UPDATE_CHECK}function $(e){return _(e,".cachly","update-check.json")}async function P(e){try{const t=JSON.parse(await y(e,"utf8"));if(!t||typeof t!="object")return null;const r=Date.parse(String(t.checkedAt));return!Number.isFinite(r)||!m(t.latest)?null:{zeit:r,latest:t.latest}}catch{return null}}async function T(e,t){try{await g(N(e),{recursive:!0});const r=`${e}.${process.pid}.tmp`;await E(r,JSON.stringify(t,null,2)+`
2
+ `,"utf8"),await w(r,e)}catch{}}async function j(e,t){let r;const s=new AbortController,n=new Promise((i,a)=>{r=setTimeout(()=>{s.abort(),a(new Error("timeout"))},t),r.unref?.()});try{const i=(async()=>{const a=await e(b,{signal:s.signal,headers:{accept:"application/json"}});if(!a.ok)throw new Error(`registry HTTP ${a.status}`);const o=(await a.json())?.version;if(!m(o))throw new Error("registry returned no version");return o.trim()})();return i.catch(()=>{}),await Promise.race([i,n])}finally{r&&clearTimeout(r)}}let f="",c="",h=!1;function F(e){return(e.HOME||e.USERPROFILE||"").trim()||v()||""}async function U(e){const t=e.env??process.env;if(f=e.aktuelle,c="",C(t))return{art:"aus"};const r=e.protokoll??(o=>{process.stderr.write(o)}),s=o=>{const l=d(o,e.aktuelle);if(l){c=o;try{r(`
3
+ \u26A1 cachly update available: ${e.aktuelle} \u2192 ${o}
4
+ `)}catch{}}return l},n=e.heim??F(t),i=n?$(n):"",a=(e.jetzt??Date.now)(),u=i?await P(i):null;if(u&&a-u.zeit>=0&&a-u.zeit<k)return{art:"zwischenspeicher",neueste:u.latest,neuer:s(u.latest)};try{const o=await j(e.holen??fetch,e.zeitgrenzeMs??S);return i&&await T(i,{checkedAt:new Date(a).toISOString(),latest:o}),{art:"abgefragt",neueste:o,neuer:s(o)}}catch(o){const l=u?s(u.latest):!1;return{art:"still",grund:o instanceof Error?o.message:String(o),neuer:l}}}function R(e,t,r=process.env){const n=r.CACHLY_QUELLE?.trim()==="claude-code-plugin"?"Plugin: /plugin \u2192 Marketplaces \u2192 cachly \u2192 Update, or turn on auto-update there; then restart Claude Code.":"npx users: restart your editor. If your config pins a version, run `npx @cachly-dev/mcp-server@latest upgrade` for the steps.";return["","","---",`\u2139\uFE0F **cachly:** version ${e} is available (you run ${t}). ${n} Mention this to the user once, in one sentence.`].join(`
5
+ `)}function Z(e,t=process.env){return h||!c||!x.has(e)||!d(c,f)?"":(h=!0,R(c,f,t))}function I(){f="",c="",h=!1}export{k as ABFRAGE_ABSTAND_MS,b as REGISTER_URL,x as SITZUNGSBEGINN_WERKZEUGE,S as ZEITGRENZE_MS,I as _neueFassungZuruecksetzen,R as hinweisSatz,Z as holeNeueFassungHinweis,m as istFassung,d as istNeuer,U as pruefeNeueFassung,C as pruefungAus,$ as standPfad};
@@ -0,0 +1,2 @@
1
+ const l="https://auth.cachly.dev/realms/cachly/protocol/openid-connect",d="cachly-cli",p="X-Trial-Key";function h(e){return typeof e=="string"&&/^cky_trial_[A-Za-z0-9]{8,}$/.test(e.trim())}function g(e){return h(e.argument)?{schluessel:e.argument.trim(),quelle:"argument"}:h(e.credentials)?{schluessel:e.credentials.trim(),quelle:"credentials"}:null}async function f(e,r=l,t=Date.now()){const a=await e(`${r}/auth/device`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:d,scope:"openid"}).toString(),signal:AbortSignal.timeout(1e4)});if(!a.ok)throw new Error(`sign-in could not start (HTTP ${a.status})`);const n=await a.json();if(!n.device_code||!n.user_code)throw new Error("sign-in could not start (no device code)");return{deviceCode:n.device_code,userCode:n.user_code,adresse:n.verification_uri_complete??n.verification_uri??`${r.replace(/\/protocol\/openid-connect$/,"")}/device`,intervallMs:Math.max(1,n.interval??5)*1e3,frist:t+Math.max(60,n.expires_in??600)*1e3}}async function w(e,r,t=l){let a;try{a=await e(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:d,grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:r.deviceCode}).toString(),signal:AbortSignal.timeout(1e4)})}catch{return{art:"warten"}}if(a.status>=500)return{art:"warten"};const n=await a.json().catch(()=>({}));return n.access_token?{art:"token",token:n.access_token}:n.error==="authorization_pending"?{art:"warten"}:n.error==="slow_down"?{art:"langsamer"}:{art:"fehler",grund:n.error??`HTTP ${a.status}`}}async function m(e,r,t={}){const a=t.schlafe??(s=>new Promise(c=>setTimeout(c,s))),n=t.jetzt??Date.now;let o=r.intervallMs;for(;n()<r.frist;){await a(o),t.puls?.();const s=await w(e,r,t.basis);if(s.art==="token")return s.token;if(s.art==="langsamer"&&(o=Math.min(o+5e3,3e4)),s.art==="fehler")throw new Error(`sign-in failed: ${s.grund}`)}throw new Error("sign-in timed out")}class u extends Error{status;reason;constructor(r,t,a){super(a),this.status=r,this.reason=t,this.name="UebernahmeFehler"}}async function y(e,r,t,a,n="mcp",o){if(t.startsWith("cky_"))throw new u(403,"sign_in_required","An API key is not a sign-in.");const s={"Content-Type":"application/json",Authorization:`Bearer ${t}`,[p]:a};o&&(s["User-Agent"]=o);const c=await e(`${r.replace(/\/+$/,"")}/auth/trial/claim`,{method:"POST",headers:s,body:JSON.stringify({client:n}),signal:AbortSignal.timeout(15e4)}),i=await c.json().catch(()=>({}));if(!c.ok||!i.api_key||!i.instance_id)throw new u(c.status,i.reason??"unknown",i.error??`HTTP ${c.status}`);return{apiKey:i.api_key,instanceId:i.instance_id,instances:i.instances??[i.instance_id],accountCreated:i.account_created===!0,revokedKeys:i.revoked_keys??0,brainRestarting:i.brain_restarting!==!1}}async function _(e,r,t,a){try{const n=await e(`${r.replace(/\/+$/,"")}/api/v1/instances/${encodeURIComponent(a)}`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return n.ok?(await n.json().catch(()=>({}))).id===a:!1}catch{return!1}}function k(e,r){const t=r?["Your test Brain is now part of your account. Lessons kept."]:["Your test Brain was moved to your account, but the new key could not reach it yet. Run `npx @cachly-dev/mcp-server@latest status` in a minute to check."];return t.push(`Brain: ${e.instanceId}${e.accountCreated?" (a new cachly account was created for your sign-in)":""}`),t.push(`The test key no longer works (${e.revokedKeys} key${e.revokedKeys===1?"":"s"} revoked). The new key is stored for you.`),e.brainRestarting&&t.push("The Brain restarts once with a new password \u2014 about 20 seconds."),t.join(`
2
+ `)}function v(e){if(!(e instanceof u))return`The Brain was not moved: ${e?.message??String(e)}. Nothing was changed.`;switch(e.reason){case"trial_key_invalid":return"This test key is unknown or was already claimed. Nothing was changed.";case"not_a_test_account":return"This key belongs to a regular account, not to a test Brain. There is nothing to claim.";case"sign_in_required":return"The sign-in was not accepted. Run the command again and finish the sign-in in the browser.";case"claim_unavailable":return"Moving the Brain is not possible right now. Nothing was changed. Please try again later.";default:return`${e.message}${/nothing/i.test(e.message)?"":" Nothing was changed."}`}}function T(e,r,t){return!r||!e.includes(r)?{text:e,ersetzt:!1}:{text:e.split(r).join(t),ersetzt:!0}}export{d as CLI_CLIENT,l as KEYCLOAK_BASIS,p as TEST_KEY_KOPF,u as UebernahmeFehler,_ as brainImKonto,k as erfolgsText,T as ersetzeSchluessel,v as fehlerText,w as frageAnmeldungAb,h as istTestSchluessel,f as starteKeycloakAnmeldung,y as uebernimm,g as waehleTestSchluessel,m as warteAufKeycloakAnmeldung};
@@ -1,6 +1,6 @@
1
- import{istPlatzhalter as a}from"./credentials.js";function o(e){if(typeof e!="string")return"";const t=e.trim();return t&&!a(t)?t:""}const c=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function i(e){return c.test(o(e))}function u(e){return["","","---",`\u2139\uFE0F **cachly:** no API key was found, so a test Brain was created on EU servers \u2014 no sign-up. Tell the user once: it keeps working without an account (${e.tarifEndetAm&&/^\d{4}-\d{2}-\d{2}/.test(e.tarifEndetAm)?`Dev tier until ${e.tarifEndetAm.slice(0,10)}`:"14 days of Dev tier"}, then the free tier, same key). To use their own cachly account instead, run \`npx @cachly-dev/mcp-server@latest autopilot\` \u2014 that account gets a new Brain; lessons from this test Brain do not move over yet.`].join(`
2
- `)}let r=null;function f(){r=null}async function d(e){if(e.schluessel)return e.werkzeug();if(i(e.konfigurierteInstanz)||i(e.aufrufInstanz))return e.anmelden();const t=r===null;t&&(r=e.holeSofortTest());const n=await r;if(!n)return e.anmelden();if(!t)return e.werkzeug();e.ablagen.setzeSchluessel(n.apiKey),e.ablagen.setEmbedJwt(n.apiKey),e.ablagen.saveApiKey(n.apiKey),e.ablagen.merkeInstanz(n.instanzId),await e.ablagen.persistApiKeyToConfig(n.apiKey),await e.ablagen.persistInstanceIdToConfig(n.instanzId),e.meldeEreignis("instant_trial_started",{tool:e.werkzeugName,instance_id:n.instanzId}),(e.protokoll??(s=>{process.stderr.write(s)}))(`
1
+ import{istPlatzhalter as o}from"./credentials.js";function c(e){if(typeof e!="string")return"";const t=e.trim();return t&&!o(t)?t:""}const u=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function s(e){return u.test(c(e))}const a="npx @cachly-dev/mcp-server@latest claim";function l(e){return["","","---",`\u2139\uFE0F **cachly:** no API key was found, so a test Brain was created on EU servers \u2014 no sign-up. Tell the user once: it keeps working without an account (${e.tarifEndetAm&&/^\d{4}-\d{2}-\d{2}/.test(e.tarifEndetAm)?`Dev tier until ${e.tarifEndetAm.slice(0,10)}`:"14 days of Dev tier"}, then the free tier, same key). To keep this Brain and its lessons in their own cachly account, they run \`${a}\` in a terminal and sign in \u2014 the Brain moves over and gets a new key.`].join(`
2
+ `)}let r=null;function d(){r=null}async function g(e){if(e.schluessel)return e.werkzeug();if(s(e.konfigurierteInstanz)||s(e.aufrufInstanz))return e.anmelden();const t=r===null;t&&(r=e.holeSofortTest());const n=await r;if(!n)return e.anmelden();if(!t)return e.werkzeug();e.ablagen.setzeSchluessel(n.apiKey),e.ablagen.setEmbedJwt(n.apiKey),e.ablagen.saveApiKey(n.apiKey),e.ablagen.merkeInstanz(n.instanzId),await e.ablagen.persistApiKeyToConfig(n.apiKey),await e.ablagen.persistInstanceIdToConfig(n.instanzId),e.meldeEreignis("instant_trial_started",{tool:e.werkzeugName,instance_id:n.instanzId}),(e.protokoll??(i=>{process.stderr.write(i)}))(`
3
3
  cachly: no API key found \u2014 created a test Brain on EU servers (instance ${n.instanzId}).
4
- cachly: the key is stored in ~/.cachly/credentials.json. Own account: npx @cachly-dev/mcp-server@latest autopilot
4
+ cachly: the key is stored in ~/.cachly/credentials.json. Keep this Brain in your own account: ${a}
5
5
 
6
- `);try{return await e.werkzeug()+u(n)}finally{try{e.neuesBrain?.(n.instanzId)}catch{}}}export{f as _zugangZuruecksetzen,o as echterWert,i as istInstanzKennung,d as sichereZugang,u as sofortTestHinweis};
6
+ `);try{return await e.werkzeug()+l(n)}finally{try{e.neuesBrain?.(n.instanzId)}catch{}}}export{a as CLAIM_BEFEHL,d as _zugangZuruecksetzen,c as echterWert,s as istInstanzKennung,g as sichereZugang,l as sofortTestHinweis};
package/glama.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://glama.ai/mcp/schemas/server.json",
3
- "version": "0.10.178",
3
+ "version": "0.10.179",
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.178",
3
+ "version": "0.10.179",
4
4
  "mcpName": "io.github.cachly-dev/mcp-server",
5
5
  "description": "Your AI forgets everything between sessions. cachly fixes that permanently: 124 MCP tools for Claude Code, Cursor, Copilot & Windsurf. Learns from every bug fix, commit and CI run. Arrives pre-briefed. Free tier forever, EU servers, GDPR.",
6
6
  "type": "module",
package/server.json CHANGED
@@ -6,13 +6,13 @@
6
6
  "url": "https://github.com/cachly-dev/cachly-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.10.178",
9
+ "version": "0.10.179",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "name": "@cachly-dev/mcp-server",
14
14
  "identifier": "@cachly-dev/mcp-server",
15
- "version": "0.10.178",
15
+ "version": "0.10.179",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  }