@cachly-dev/mcp-server 0.10.280 → 0.10.281

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