@cachly-dev/mcp-server 0.10.282 → 0.10.284
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/brain-weg.js +4 -0
- package/dist/src/handlers/brain.js +72 -72
- package/dist/src/handlers/team.js +30 -29
- package/dist/src/index.js +136 -136
- package/dist/src/raeume.js +1 -0
- package/dist/src/rolle.js +10 -9
- package/dist/src/schluessel-klassen.js +1 -1
- package/dist/src/speicher-zugang.js +1 -1
- package/glama.json +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/src/index.js
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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.
|
|
2
|
+
import{setzeClientKennung as ho}from"./herkunft.js";import{jwtExpiryMs as yo,checkJwt as bo,handleApiError as wo,diagnoseAuth as De,planAuthHeal as it,readClientCredentialsFromEnv as vo,buildClientCredentialsBody as xo,clientCredentialsTokenUrl as _o}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as $o}from"./werkzeug-nutzung.js";import{istLieferung as ko,lieferSchluessel as So,tokenDerAntwort as Ao,hatTreffer as Co,trefferSchluessel as rt}from"./geliefert.js";import{notify as at}from"./notifier.js";import{fileURLToPath as ct}from"node:url";import{createRequire as To}from"node:module";import{execFile as Ue}from"node:child_process";const Io=process.argv[1]!=null&&(process.argv[1]===ct(import.meta.url)||process.argv[1].endsWith("/dist/index.js")||process.argv[1].endsWith("/src/index.ts"));import{Server as lt}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Eo}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as Ro}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as dt,ErrorCode as ee,ListPromptsRequestSchema as ut,ListResourceTemplatesRequestSchema as pt,ListResourcesRequestSchema as mt,ListToolsRequestSchema as ft,McpError as q}from"@modelcontextprotocol/sdk/types.js";import{Redis as gt}from"ioredis";let v=process.env.CACHLY_API_URL??"https://api.cachly.dev",A=Ve()??"";ne(A);const Nr=process.env.CACHLY_EMBED_MODEL??"",M=(()=>{try{const e=To(import.meta.url);for(const t of["../../package.json","../package.json"])try{const o=e(t);if(o.name==="@cachly-dev/mcp-server"&&o.version)return o.version}catch{}}catch{}return"0.10.100"})(),jo=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let N=we(process.env.CACHLY_BRAIN_INSTANCE_ID);function _e(){return L()?he()?.schluessel??"":A}function No(){return L()?he()?.instanzId??"":N}function V(){return A||Ve()||""}function W(){return we(process.env.CACHLY_BRAIN_INSTANCE_ID)||de()||""}let Z=0,me=null,ht=!1;async function yt(){let e=[];try{X.getClientCapabilities()?.roots&&(e=(await X.listRoots(void 0,{timeout:3e3})).roots)}catch{}return li({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:ct})}function oe(){return ht?Ut(process.env):!1}function $e(e,t,o){!e||!oe()||ii({instanzId:e,vomHook:o,verbindung:H,ausGit:n=>Ke("brain_from_git",n,H,B),projektOrdner:t?async()=>t:yt,einbetten:n=>_t(n,{geduld:"lang"}),hatEinbettung:Yo,einbettenZweit:n=>_t(n,{geduld:"lang",modell:vn}),melde:n=>C("brain_from_git",{instance_id:e,total:n,auto:"startwissen"}),startvorrat:n=>Ze("brain_seed_starter",n,H,B),meldeStartvorrat:n=>C("brain_seed_starter",{instance_id:e,auto:!0},{seeded_count:n,auto:!0})})}function ke(){return oe()&&di()}const Po=7e3,Bo=12e3,Oo=18e4;let Se=null;function We(e){return Se||(Se=Lo(e).finally(()=>{Se=null})),Se}async function Lo(e){try{if(!A){const t=Date.now()+e;for(;!Ne()&&Vs({})&&Date.now()<t;)await new Promise(s=>setTimeout(s,Ks));const o=Ne();if(!o)return!1;A=o,ne(o);const n=de();n&&!N&&(N=n,Z=0),await fe(o),n&&await ge(n),C("instant_trial_started",{tool:"sessionstart-hook",...n?{instance_id:n}:{}})}if(oe()&&Dt()){const t=Gs();t&&(Pe(t.instanzId,oe(),ke()),$e(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!A}function Ho(){if(!Ut(process.env))return;const e=Date.now()+Oo,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}A&&!Dt()||We(0)},500);t.unref(),We(0)}async function Mo(){if(!A||L())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(),o=t.instance?.id??t.instance_id;if(o)return o}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:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}catch{fetch(`${v}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"auto_provision_failed",status:0,reason:"network_error",version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{})}return""}async function bt(){if(L())return No();if(N)return N;if(!A)return"";if(me)return me;const e=Date.now();if(Z>0&&e-Z<3e4)return"";Z=e,me=(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 n=(await t.json())?.data??[],s=n.find(d=>d.status==="running")??n.find(d=>d.status==="provisioning");if(s)return N=s.id,Z=0,N;const i=de(),a=await Mo();if(a)return Ot(A)&&i&&i!==a&&(Qe=Ht(i,{id:a,neu:!0},"datei")),N=a,Z=0,Pe(a,oe(),ke()),ge(a),$e(a),N}}catch{}return""})();try{return await me}finally{me=null}}let Je=0;const zo=6e4;let ce="";async function fe(e){try{const{writeFile:t,readFile:o}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:s}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const a=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(a.map(async d=>{if(n(d))try{const l=await o(d,"utf-8"),u=JSON.parse(l),r=u?.mcpServers?.cachly;r?.env&&(r.env.CACHLY_JWT=e,await t(d,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}async function ge(e){if(e){je(e,{apiKey:A});try{const{writeFile:t,readFile:o}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:s}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const a=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(a.map(async d=>{if(n(d))try{const l=JSON.parse(await o(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 Do(){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,ne(t.key),fe(t.key),C("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function Fe(){const e=De(A),t=it(e);if(t==="none")return ce="",!0;if(t==="refresh"){const o=Date.now();return o-Je>=zo&&(Je=o,await Do())?(ce="",!0):(ce=e.message,e.usable)}return ce=e.message,!1}function le(e,t){const o=(a,d)=>{try{t?.(a,d)}catch{}},n=a=>{a?o(!1,a.code??a.message):o(!0)},s=ls(e);if(!s){o(!1,"keine-http-adresse");return}const i=ds(s);try{process.platform==="win32"?Ue("cmd",["/c","start","",i],{windowsHide:!0},n):process.platform==="darwin"?Ue("open",[s],n):Ue("xdg-open",[s],n)}catch(a){o(!1,a instanceof Error?a.message:"unknown")}}let K=null;async function Uo(){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(),o=t.verification_uri||j("/device","ambient-signin"),n=`${o}${o.includes("?")?"&":"?"}code=${encodeURIComponent(t.user_code)}`;return{deviceCode:t.device_code,userCode:t.user_code,verifyUrl:n,pollInterval:(t.interval??5)*1e3,deadline:Date.now()+wt(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 o=await t.json();return{deviceCode:o.device_code,userCode:o.user_code,verifyUrl:o.verification_uri_complete,pollInterval:(o.interval??5)*1e3,deadline:Date.now()+wt(o.expires_in),polling:!1}}catch{return null}}function wt(e){const t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:600;return Math.min(t,3600)*1e3}function Wo(){const e=Os(v);return e?{deviceCode:e.deviceCode,userCode:e.userCode,verifyUrl:e.verifyUrl,pollInterval:e.pollInterval,deadline:e.deadline,polling:!1}:null}async function Jo(e){if(Date.now()>e.deadline)return Mt(e.deviceCode),"expired";const t=async()=>{const n=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 n.ok?n.json():null},o=async()=>(await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`client_id=cachly-cli&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=${e.deviceCode}`,signal:AbortSignal.timeout(8e3)})).json();try{let n=await t().catch(()=>null);if(n||(n=await o().catch(()=>null)),!n)return"pending";if(n.access_token){let s=n.access_token;try{const i=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(i.ok){const a=await i.json();a.key&&(s=a.key)}}catch{}return A=s,ne(s),K=null,Mt(e.deviceCode),C("device_flow_completed"),fe(s),se(s),Z=0,await bt(),N&&ge(N),"done"}return n.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function vt(e){if(e.polling)return"pending";e.polling=!0;try{return await Jo(e)}finally{e.polling=!1}}function xt(e,t=vt,o=s=>K===s,n=Fo){const s=async()=>{if(!o(e))return;let i="pending";try{i=await t(e)}catch{}if(i!=="done"){if(i==="expired"){o(e)&&(K=null);return}o(e)&&n(s,e.pollInterval)}};n(s,e.pollInterval)}function Fo(e,t){const o=setTimeout(e,t);typeof o.unref=="function"&&o.unref()}import{setEmbedJwt as ne,computeEmbedding as _t,hasEmbedProvider as Yo,EMBED_PROVIDER as $t,erzwingeEmbedAnbieterRemote as Ko}from"./embeddings.js";import{istMehrmandant as L,setzeMehrmandant as Go,mandantKontext as he,imMandant as qo,baueKontext as kt,poolSchluessel as Vo,leseBearer as Zo,leseInstanzKopf as Xo,BegrenzterSpeicher as Qo,baueZugangsAufloeser as en,ZugangAbgelehnt as St,bauePruefGrenze as tn,leseAufruferIp as on,imAufrufer as nn,installiereApiKoepfe as sn,ANLEITUNG_OHNE_KOPF as Ae,istRemoteErlaubt as rn,nurLokalText as an,bereinigeArgumente as cn}from"./remote-zugang.js";import{leseOAuthEinstellungen as ln,schutzMetadaten as dn,wwwAuthenticate as un,baueJwtPruefer as pn,TokenAbgelehnt as mn,tokenFehlerText as fn,KEIN_BRAIN_TEXT as gn,brauchtAnmeldung as hn,WERKZEUG_BRAUCHT_ANMELDUNG as yn,MAX_RUMPF_OHNE_ANMELDUNG as bn}from"./remote-oauth.js";import{serverInfo as At,beantworteLogo as wn}from"./remote-logo.js";import{ZWEIT_MODELL as vn}from"./rangfolge-stellschrauben.js";import{tokenize as xn,splitMultiQuery as _n,levenshtein as $n,recencyBoost as kn,extractTimestamp as Sn,STOPWORDS as An,katakanaToRomaji as Cn,arabicLightStem as Tn,expandCrossLingual as In,CROSS_LINGUAL_MAP as En}from"./search.js";const ye=new Map,Rn=200,jn=10*6e4,Ce=new Qo({max:Rn,ttlMs:jn,beiEntfernen:e=>{e.quit().catch(()=>e.disconnect())}});function Ye(){return[...ye.values(),...Ce.werte()]}function Nn(e){return e<=1?200:null}async function H(e){if(!e)throw new q(ee.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
|
|
3
3
|
|
|
4
4
|
This usually resolves in a few seconds \u2014 just call the tool again and it will connect automatically.
|
|
5
5
|
|
|
6
6
|
If it keeps happening:
|
|
7
7
|
\u2022 Run \`list_instances\` to check your instances, or
|
|
8
8
|
\u2022 Set CACHLY_BRAIN_INSTANCE_ID in your MCP config, or
|
|
9
|
-
\u2022 Reach us at support@cachly.dev.`);const t=
|
|
9
|
+
\u2022 Reach us at support@cachly.dev.`);const t=L()?he():void 0;if(L()&&!t)throw new q(ee.InvalidRequest,Ae);const o=t?Vo(t.schluessel,e):e,n=t?Ce.get(o):ye.get(e);return n||oi(Pn,o,()=>Bn(e,o,!!t))}const Pn=new Map;async function Bn(e,t=e,o=!1){Y("verbindung: Instanz abfragen");let n=await B(`/api/v1/instances/${e}`);if(Y(`verbindung: Instanz ${n.status}`),n=await ti(n,()=>B(`/api/v1/instances/${e}`),{fristMs:jo,melde:r=>Y(`verbindung: Instanz ${r.status}`)}),n.status!=="running"){o||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:n.status,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let r;throw n.status==="provisioning"?r=`\u23F3 Brain instance "${n.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.`:
|
|
11
|
+
First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:n.status==="failed"?r=`\u274C Brain instance "${n.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.`:
|
|
14
|
+
If this persists, contact support@cachly.dev.`:n.status==="suspended"?r=`\u23F8 Brain instance "${n.name}" is suspended (billing issue).
|
|
15
15
|
|
|
16
|
-
Update your payment method at: ${j("/billing","upgrade")}`:
|
|
16
|
+
Update your payment method at: ${j("/billing","upgrade")}`:n.status==="pending_payment"?r=`\u{1F4B3} Brain instance "${n.name}" is waiting for payment.
|
|
17
17
|
|
|
18
|
-
Complete your checkout at: ${j("/instances","upgrade")}`:
|
|
18
|
+
Complete your checkout at: ${j("/instances","upgrade")}`:r=`Brain instance "${n.name}" is not reachable (status: ${n.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 ee
|
|
21
|
+
\u2022 Run \`get_api_status\` for a full diagnostic.`,new q(ee.InvalidRequest,r)}if(!n.host||!n.port)throw new q(ee.InternalError,`Instance "${n.name}" is running but has no host/port \u2014 contact support@cachly.dev.`);const s=await Wi(()=>B(`/api/v1/instances/${e}/connection`),n.name);s&&Y("verbindung: Zugangsdaten da");const i=Ji(s);Li(e);const a=Yt({host:n.host,port:n.port,tls_enabled:n.tls_enabled},s),{roh:d,nutzbar:l}=Fi(gt,{host:a.host,port:a.port,commandTimeout:8e3,...a.tls?{tls:a.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:Nn,maxRetriesPerRequest:1,keepAlive:15e3},i,e),u=()=>{o?Ce.vergissWenn(t,l):ye.delete(e),d.disconnect()};d.on("error",u),d.on("end",u);try{await d.connect()}catch(r){d.disconnect();const m=r instanceof Error?r.message:String(r);throw o||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:n.host,port:n.port,error:m,version:M}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new q(ee.InternalError,`Could not reach Brain instance "${n.name}" (${n.host}:${n.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: ${m}`)}return
|
|
26
|
-
cachly: could not open a browser (${
|
|
25
|
+
\u2022 Technical detail: ${m}`)}return o?Ce.set(t,l):ye.set(e,l),Y(i.mitglied?"verbindung: Valkey verbunden (Mitglied)":"verbindung: Valkey verbunden"),l}async function B(e,t={},o=!1){!o&&!L()&&it(De(A))!=="none"&&await Fe();const n=_e();bo(n);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),i=await fetch(`${v}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...t.headers}});if(!i.ok){if(i.status===401&&!o&&!L()&&(Je=0,await Fe()))return B(e,t,!0);const a=await i.json().catch(()=>({error:i.statusText})),d=a.error??i.statusText;try{wo(i.status,d)}catch(l){throw Ui(l,i.status,a)}}if(i.status!==204)return i.json()}import{handleBrainTool as On}from"./handlers/brain.js";import{holeRegeln as Te,regelAbrufMitFetch as Ln,regelAnweisungsZeile as Hn,regelHinweisEinmal as Mn,regelStandImSpeicher as zn,REGEL_FRISCH_MS as Dn}from"./firmenregeln.js";import{handleContextTool as Un}from"./handlers/context.js";import{handleInstanceTool as Wn}from"./handlers/instances.js";import{handleCacheTool as Jn}from"./handlers/cache.js";import{handleTeamTool as Fn}from"./handlers/team.js";import{handleRoadmapTool as Yn}from"./handlers/roadmap.js";import{handleAdvancedTool as Kn}from"./handlers/advanced.js";import{handleSyndicateTool as Gn}from"./handlers/syndicate.js";import{handleFedbrainTool as Ke,_lastBrainFromGitCounts as Ie}from"./handlers/fedbrain.js";import{extractFirstRecallProof as qn,extractTopHit as Vn,fuersTerminal as Ct,renderFirstRecallProof as Zn}from"./first-recall-proof.js";import{aussetzerLeise as Xn}from"./aussetzer.js";import{gitHookOrdner as Qn,installClsPostCommitHook as Tt,CLS_HOOK_VERSION as It}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as es,CLAUDE_MD_MARKER_END as ts,EDITOR_FILES as Ee,ANWEISUNGS_DATEIEN as os,buildClaudeMdBlock as Et,setzeAnweisungsblock as ns,sollSchreiben as ss,globaleMcpDatei as Re,globalerEditorDa as Rt,diesesHeim as be,mcpZiel as jt}from"./projektdateien.js";import{klassiereArgument as is,leseFlag as Ge,flagsOhneWert as rs,pruefeInitEingaben as as}from"./cli-argumente.js";import{uninstallBefehl as cs}from"./uninstall.js";import{gitLesen as Nt}from"./git-ohne-shell.js";import{browserAdresse as ls,fuerCmd as ds}from"./browser-adresse.js";import{installAmbientHooks as qe,installCursorHooks as us,installCopilotHooks as ps,installCodexHooks as ms,installGeminiHooks as fs,AMBIENT_HOOK_VERSION as Pt,COPILOT_HOOKS_DATEI as gs,CODEX_HOOKS_DATEI as hs,GEMINI_SETTINGS_DATEI as ys}from"./ambient-hooks.js";import{hookHauptlauf as bs,auffrischenHauptlauf as ws,startwissenImportHauptlauf as vs}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as xs}from"./startwissen-hook.js";import{rahmeAntwort as _s}from"./antwort-rahmen.js";import{appendLedgerEntry as $s,readLedger as Bt,defaultLedgerPath as ks,reportLedgerEntry as Ss,teileNachInstanz as As}from"./ambient-ledger.js";import{installCodexMcp as Cs,installGeminiMcp as Ts}from"./editor-mcp-eintrag.js";import{resolveApiKey as Ve,saveApiKey as se,saveInstanceId as je,readSavedApiKey as Ne,readInstanceId as de}from"./credentials.js";import{istSofortTestSchluessel as Ot,ersetzeInstanceId as Is,istBekanntWeg as Es,merkeWeg as Rs,nimmHinweisEinmal as Lt,legeEinmalAn as js,ist404 as Ns,hinweisErsetzt as Ht,meldungRegistriert as Ps,meldungAnlegenFehlt as Bs}from"./brain-weg.js";import{ladeLaufendeAnmeldung as Os,merkeAnmeldung as Ls,vergissAnmeldung as Mt}from"./laufende-anmeldung.js";import{KEYCLOAK_BASIS as zt,istTestSchluessel as Hs,waehleTestSchluessel as Ms,starteKeycloakAnmeldung as zs,warteAufKeycloakAnmeldung as Ds,uebernimm as Us,brainImKonto as Ws,erfolgsText as Js,fehlerText as Fs,ersetzeSchluessel as Ys}from"./uebernahme.js";import{WARTE_TAKT_MS as Ks,auftragLiegt as Dt,nimmAuftrag as Gs,sichereKonto as qs,sperreLiegt as Vs,startwissenEingeschaltet as Ut}from"./konto-anlegen.js";import{sichereZugang as Zs,echterWert as we,istInstanzKennung as Xs}from"./zugang.js";import{zeitpunkt as Y}from"./zeitmessung.js";import{autoSitzungsSchritt as Qs,SITZUNGS_WERKZEUGE as ei}from"./auto-sitzung.js";import{warteAufLaufendeInstanz as ti,gemeinsamerAufbau as oi}from"./instanz-warten.js";import{merkeNeuesBrain as Pe,startetLautLetztemBlick as ni,setzeCommitQuelle as si}from"./leeres-brain.js";import{starteStartwissen as ii,startwissenGestartet as ri,beanspruchStartwissen as ai,holeStartwissenHinweis as ci,waehleProjektOrdner as li,startvorratErlaubt as di,projektCommits as ui}from"./startwissen.js";import{eigeneFassung as pi,pruefeNeueFassung as mi,holeNeueFassungHinweis as fi}from"./neue-fassung.js";import{beiStdinEnde as gi}from"./stdin-ende.js";import{merkeWerkzeugAufruf as hi,starteBrandWachhund as yi}from"./brand-wachhund.js";import{sichtbareWerkzeuge as bi,VERTEILER as Wt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as wi}from"./pflichtfelder.js";import{buildLessonsMarkdown as vi,buildLessonsJsonl as xi,vonRohLektion as _i}from"./brain-export.js";import{detectEditor as $i}from"./editor.js";import{milestoneSent as Jt,markMilestoneSent as Ft}from"./funnel-milestones.js";import{meldeKopf as ki,meldeRumpf as Si}from"./melde-weg.js";import{kostprobeUebrig as Ai,kostprobeVerbrauchen as Ci,kostprobeHinweis as Ti,kostprobePfadJeInstanz as Ii,schrankeNachKostproben as Ei}from"./kostprobe.js";import{netBalance as Ri}from"./ambient-recall.js";import{handleShareTool as Ze}from"./handlers/share.js";import{handleVizTool as ji}from"./handlers/viz.js";import{commitArt as Ni,istRueckbau as Pi,zaehleLektionen as Bi}from"./commit-art.js";import{TOOLS as ue}from"./tools.js";import{verbindungsWeg as Yt}from"./brains-tls.js";import{richteRolleEin as Oi,holeRolle as Li,istMitglied as Hi,imWerkzeugLauf as Mi,mitAbweisungsHinweis as zi,SchreibVerweigert as Di,markiereApiFehler as Ui}from"./rolle.js";import{holeVerbindungsAuskunft as Wi,anmeldungAus as Ji,baueSpeicherClient as Fi}from"./speicher-zugang.js";import{installiereClientKopf as Yi,clientKopfWert as Ki}from"./client-kopf.js";let Kt=!1,Gt=!1,Be=!1;function qt(){return $i()}function C(e,t,o){process.env.CACHLY_NO_TELEMETRY!=="1"&&(L()||fetch(`${v}/api/v1/telemetry/mcp`,{method:"POST",headers:ki(A),body:JSON.stringify(Si({event:e,version:M,editor:qt()},t,o)),signal:AbortSignal.timeout(3e3)}).catch(()=>{}))}function Gi(e,t){return Ss({apiUrl:v,jwt:A,instanceId:e},t)}async function qi(e){if(!(Kt||L())&&process.env.CACHLY_NO_TELEMETRY!=="1"){Kt=!0;try{await fetch(`${v}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:M,editor:qt(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const Vi=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"]),Zi={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."},Vt=j("/billing","upgrade"),Zt=new Map;async function Xi(e){const t=Zt.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const n=((await B(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),s={tier:n,isFree:n==="free"||n===""};return Zt.set(e,{info:s,expiresAt:Date.now()+6e4}),s}catch{return{tier:"unknown",isFree:!1}}}async function Qi(e,t){if(!Vi.has(e)||!t)return null;const{isFree:o}=await Xi(t);if(!o)return null;const n=Zi[e]??"A Premium intelligence feature.",s=L()?Ii(t):void 0;if(Ai(e,s)){const i=Ci(e,s);return{kostprobe:Ti(e,i,Vt)}}return{sperre:Ei(e,n,Vt)}}async function er(e,t){try{await(await H(e)).hincrby($o(e),t,1)}catch{}}async function tr(e,t,o){if(ko(t))try{const n=await H(e),s=Co(o);await n.incrby(So(e),s?Ao(o):0),await n.hincrby(rt(e),"abrufe",1),s&&await n.hincrby(rt(e),"treffer",1)}catch{}}async function or(e){const t=await Uo();return t?(K=t,Ls({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,(o,n)=>{if(o){C("device_browser_opened",{stelle:"tool"});return}C("device_browser_failed",{reason:n??"unknown",stelle:"tool"}),process.stderr.write(`
|
|
26
|
+
cachly: could not open a browser (${n??"unknown"}).
|
|
27
27
|
cachly: open this yourself to finish signing in:
|
|
28
28
|
cachly: ${t.verifyUrl}
|
|
29
29
|
cachly: code ${t.userCode}
|
|
30
30
|
|
|
31
|
-
`)}),
|
|
31
|
+
`)}),xt(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 ${ue.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
|
|
34
|
-
`)}return
|
|
33
|
+
`)}async function nr(e){if(!e)return!0;if(ri(e))return!1;try{return await ai(await H(e),"sitzungsstart")}catch{return!0}}const Xe=new Set;let Qe="",Oe="";async function sr(e){const t={args:e,hinweis:""};if(L()||!A)return t;const o=N;if(!o||!Xs(o)||(typeof e.instance_id=="string"&&e.instance_id?e.instance_id:o)!==o||Xe.has(o))return t;if(!Es(o)){try{return await B(`/api/v1/instances/${o}`),Xe.add(o),t}catch(a){if(!Ns(a))return t}Rs(o)}if(!Ot(A))throw new q(ee.InvalidRequest,Ps(o));const s=await js(()=>B("/api/v1/instances/auto",{method:"POST",body:"{}"}));if(!s.ok)throw new q(ee.InvalidRequest,Bs(o,s));const i=we(process.env.CACHLY_BRAIN_INSTANCE_ID)===o?"umgebung":de()===o?"datei":"prozess";return i==="datei"&&Is(o,s.id,{apiKey:A}),N=s.id,Z=0,Xe.add(s.id),s.neu&&(Pe(s.id,oe(),ke()),setImmediate(()=>$e(s.id))),{args:{...e,instance_id:s.id},hinweis:Lt()?Ht(o,s,i):""}}async function J(e,t){const o=await sr(t);o.hinweis&&(Oe=o.hinweis);try{return await rr(e,o.args)}finally{Qe&&Lt()&&(Oe=Qe)}}function ir(){const e=Oe;return Oe="",e}async function rr(e,t){if(L()&&!_e())return Ae;if(!_e()&&await We(Po))return J(e,t);if(!_e()){if(qi(e),!K){const c=Wo();c&&(K=c,C("device_flow_resumed",{tool:e}),xt(c))}if(K){const c=await vt(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 Zs({schluessel:A,konfigurierteInstanz:N,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{Y("sofort-test: Anfang");const c=await qs({apiUrl:v,version:M,fristMs:Bo}),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&&Pe(g.instanzId,oe(),ke()),g},ablagen:{setzeSchluessel:c=>{A=c},setEmbedJwt:ne,saveApiKey:c=>se(c),persistApiKeyToConfig:fe,merkeInstanz:c=>{N=c,Z=0},persistInstanceIdToConfig:ge},meldeEreignis:C,werkzeug:()=>J(e,t),anmelden:()=>or(e),neuesBrain:$e})}if(!t.instance_id){const c=await bt();c&&(t={...t,instance_id:c})}const o=await Qi(e,t.instance_id);let n="";if(o!==null){if("sperre"in o)return C("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),o.sperre;n=o.kostprobe,C("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&er(t.instance_id,e),Y(`werkzeug ${e}: Zugang und Tarif geklaert`);const s=await On(e,t,H,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??"")),!Be&&A&&(Be=!0,Jt("first_call_success")||(Ft("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(!ni(c)){if(!S&&p.length>100)C("recall_best_solution",g);else if(S&&t.workspace_path&&await nr(c))try{const k=await Ke("brain_from_git",{instance_id:c,repo_path:t.workspace_path,limit:50},H,B);if(k!==null){C("brain_from_git",{...g,...Ie??{}}),C("recall_best_solution",g);let R="";if((Ie?.total??0)===0)try{const z=await Ze("brain_seed_starter",{instance_id:c},H,B);z&&(C("brain_seed_starter",{...g,auto:!0},{seeded_count:16,auto:!0}),R=`
|
|
35
35
|
---
|
|
36
|
-
`+String(z))}catch{}const I=String(k),$=
|
|
36
|
+
`+String(z))}catch{}const I=String(k),$=Ie?.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+`
|
|
38
38
|
---
|
|
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)+`
|
|
@@ -42,18 +42,18 @@ cachly: code ${t.userCode}
|
|
|
42
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
|
|
45
|
+
${s}`}return s}const i=await Un(e,t,H,B);if(i!==null)return!Be&&A&&(Be=!0,Jt("first_call_success")||(Ft("first_call_success"),C("first_call_success",{tool:e,instance_id:t.instance_id??N??""}))),i;const a=await Wn(e,t,H,B);if(a!==null)return a;const d=await Jn(e,t,H,B);if(d!==null)return d;const l=c=>n?c+n:c,u=await Fn(e,t,H,B);if(u!==null)return l(u);const r=await Yn(e,t,H,B);if(r!==null)return r;const m=await Kn(e,t,H,B);if(m!==null)return l(m);const f=await Gn(e,t,H,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 Ze(e,t,H,B);if(y!==null)return y;const w=await ji(e,t,H,B);if(w!==null)return w;const h=await Ke(e,t,H,B);if(h!==null){const g={instance_id:t.instance_id??N??""};if(e==="brain_from_git"){const p=Ie;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=
|
|
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=ye.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
|
-
\u{1F9E0} **Brain Instances:** could not fetch \u2014 ${k.message}`}await
|
|
54
|
+
\u{1F9E0} **Brain Instances:** could not fetch \u2014 ${k.message}`}await Fe();const S=De(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
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
|
|
56
|
+
`)}default:throw new Xt(`Unknown tool: ${e}`)}}class Xt extends Error{}const et=`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,75 +63,75 @@ 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
|
|
66
|
+
session_start gives a briefing at the start of a session; it does not replace smart_recall for a concrete task.`;function Qt(e=N){if(L())return et;const t=Hn(e);return t?`${et}
|
|
67
67
|
|
|
68
|
-
${t}`:
|
|
68
|
+
${t}`:et}const tt=(e,t)=>B(e,t),ar=Date.now();async function cr(e){if(L()||!e)return"";try{let t=zn(e);return t?Date.now()-(t.geholtAm??0)>=Dn&&Te(e,tt):t=await Te(e,tt),Mn(e,t,{cwd:process.cwd(),prozessStart:ar})}catch{return""}}const eo={tools:{},resources:{},prompts:{}},to=async()=>{const{katalog:e,unbekannteKernnamen:t}=bi(ue);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function oo(){return{resources:[]}}async function no(){return{resourceTemplates:[]}}async function so(){return{prompts:[]}}function lr(e){e.setRequestHandler(ft,to),e.setRequestHandler(dt,co),e.setRequestHandler(mt,oo),e.setRequestHandler(pt,no),e.setRequestHandler(ut,so)}function dr(){const e=new lt(At(M),{capabilities:eo,instructions:Qt()});return lr(e),io(e),e}function io(e){const t=e.oninitialized;e.oninitialized=()=>{let o;try{o=e.getClientVersion(),ho(o?.name,o?.version)}catch{}Gt||(Gt=!0,C("mcp_verbunden",{client:String(o?.name??"unbekannt").slice(0,60),client_version:String(o?.version??"").slice(0,30)})),!L()&&N&&Te(N,tt),t?.()}}const X=new lt(At(M),{capabilities:eo,instructions:Qt()});io(X),X.setRequestHandler(ft,to),X.setRequestHandler(mt,oo),X.setRequestHandler(pt,no),X.setRequestHandler(ut,so);let Le=null,pe=!1,ie=null,ro=0;async function ur(e){if(!pe){if(ie){await ie;return}ie=(async()=>{pe=!0,Le=e;try{await J("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{ie=null}})(),await ie,ao(e)}}function pr(e){pe=!0,Le=e}function ao(e){process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await H(e);if(Hi(t))return;const o=await t.get(`cachly:index:last_indexed:${e}`),n=1440*60*1e3;(!o||Date.now()-parseInt(o,10)>n)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),await J("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code",hintergrund:!0}))})().catch(()=>{})}async function ot(){if(!(!pe||!Le)){pe=!1;try{await J("session_end",{instance_id:Le,summary:`Auto-ended after ${ro} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const co=async e=>{let{name:t,arguments:o}=e.params;if(t===Wt){const i=o??{},a=typeof i.tool=="string"?i.tool:"";if(!a)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const d=ue.find(l=>l.name===a);if(!d)return{content:[{type:"text",text:`Kein Werkzeug namens "${a}". Die Liste steht in der Beschreibung von ${Wt}.`}],isError:!0};if(i.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:d.name,description:d.description,inputSchema:d.inputSchema},null,2)}]};t=a,o=i.arguments??{}}if(L()){const i=he();if(!i)return{content:[{type:"text",text:Ae}],isError:!0};if(!i.instanzId)return{content:[{type:"text",text:gn}],isError:!0};if(!rn(t))return{content:[{type:"text",text:an(t)}],isError:!0};const a=cn(o??{},i.instanzId);if("fehler"in a)return{content:[{type:"text",text:a.fehler}],isError:!0};o=a.args}if(!["learn_from_attempts","smart_recall","recall_feedback"].includes(t)){const i=ue.find(d=>d.name===t),a=i?wi(t,i.inputSchema,o??{}):null;if(a)return{content:[{type:"text",text:a}],isError:!0}}const n=we(o?.instance_id)||N||we(process.env.CACHLY_BRAIN_INSTANCE_ID)||"",s=L()?"nichts":Qs(t,{gestartet:pe,startetGerade:ie!==null,instanz:n});s==="starten"?await ur(n).catch(()=>{}):s==="abwarten"?await ie?.catch(()=>{}):s==="als-gestartet-merken"&&pr(n),!L()&&!ei.has(t)&&ro++;try{hi(),Y(`werkzeug ${t}: Anfang`);const i=t==="session_start"?"":await cr(n),a=await Mi(()=>J(t,o??{})),d=zi(a.ergebnis,a.abgewiesen,a.rolle);return Y(`werkzeug ${t}: Antwort fertig`),s==="als-gestartet-merken"&&ao(n),{content:[{type:"text",text:_s(t,d)+ci()+fi(t)+ir()+(i?`
|
|
69
69
|
|
|
70
|
-
${
|
|
70
|
+
${i}`:"")}]}}catch(i){if(i instanceof Xt)return{content:[{type:"text",text:i.message}],isError:!0};if(i instanceof Di)return{content:[{type:"text",text:`\u{1F512} ${i.message}`}],isError:!0};if(i instanceof q)throw i;const a=i.message??String(i);throw at("cachly","tool_error",{tool:t,error:a}).catch(()=>{}),new q(ee.InternalError,a)}};X.setRequestHandler(dt,co),process.on("SIGTERM",async()=>{await ot().catch(()=>{});for(const e of Ye())await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await ot().catch(()=>{});for(const e of Ye())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
|
|
73
|
-
`)}catch{}}if(
|
|
72
|
+
`)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function mr(e,t){const o=Object.entries(t).map(([n,s])=>`${n}=${s}`);return e==="codex"?{befehl:`codex mcp add cachly ${o.map(n=>`--env ${n}`).join(" ")} -- npx -y @cachly-dev/mcp-server@latest`,wo:"~/.codex/config.toml"}:e==="gemini"?{befehl:`gemini mcp add -s project ${o.map(n=>`-e ${n}`).join(" ")} cachly npx -- -y @cachly-dev/mcp-server@latest`,wo:".gemini/settings.json"}:null}const lo="https://api.cachly.dev";function te(e,t,o={}){const n={CACHLY_BRAIN_INSTANCE_ID:t};return o.includeApiKey&&(n.CACHLY_JWT=e),v&&v!==lo&&(n.CACHLY_API_URL=v),n}function fr(e,t,o){return o==="continue"?JSON.stringify({experimental:{modelContextProtocolServers:[{transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:te(e,t)}]}},null,2):o==="zed"?JSON.stringify({context_servers:{cachly:{command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:te(e,t)},settings:{}}}},null,2):uo(o)?JSON.stringify({servers:{cachly:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:te(e,t)}}},null,2):JSON.stringify({mcpServers:{cachly:{command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:te(e,t)}}},null,2)}function uo(e){return Ee[e]===".vscode/mcp.json"}function ve(e,t){Hs(e)||se(e,t)}async function po(e,t,o,n,s,i={}){const a={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:te(t,o)};if(!s.existsSync(e))return fr(t,o,n);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(n==="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&&ve(y,i);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(n==="zed"){const m=d.context_servers??{},y=m.cachly?.command?.env?.CACHLY_JWT;return y&&ve(y,i),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(uo(n)){const m=d.mcpServers??void 0,y=m?.cachly?.env?.CACHLY_JWT;y&&ve(y,i),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&&ve(c,i),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??{},r=l.cachly?.env?.CACHLY_JWT;return r&&ve(r,i),l.cachly=a,d.mcpServers=l,JSON.stringify(d,null,2)}async function mo(e,t,o,n){const{existsSync:s}=await import("node:fs"),{resolve:i}=await import("node:path"),{homedir:a}=await import("node:os"),d=o??a(),l=os.filter(m=>ss(m,e,d,s,i,n)).map(m=>({path:i(e,...m.pfad),prefix:m.prefix})),u=Et(t),r={};for(const{path:m,prefix:f}of l)try{r[m]=await ns(m,u,f)}catch(y){r[m]=`failed:${y.message}`}return r}function fo(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=V(),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
|
|
78
|
+
`);try{const o=await fetch(`${v}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!o.ok)throw new Error(`stats HTTP ${o.status}`);const n=await o.json(),s=n.lesson_count??0,i=n.total_recall_count??0,a=Math.round(n.iq_boost_pct??0),d=(n.top_lessons??[]).slice(0,5),l=n.team_authors??[],u=i*1200,r=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${r.padEnd(18)}\x1B[0m\u2502`),console.log(`\u2502 Total recalls : \x1B[36m${String(i).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} ${i} recalls \xB7 ~${Math.round(u/1e3)}K tokens saved`,` \u{1F3AF} Brain Level: ${r}`,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
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(
|
|
81
|
-
\u274C Could not fetch digest: ${
|
|
82
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="export"){const{writeFile:e,mkdir:t}=await import("node:fs/promises"),{resolve:
|
|
83
|
-
\u274C Unknown --format "${
|
|
84
|
-
`),process.exit(1));const a=
|
|
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(o){console.log(`
|
|
81
|
+
\u274C Could not fetch digest: ${o.message}
|
|
82
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="export"){const{writeFile:e,mkdir:t}=await import("node:fs/promises"),{resolve:o}=await import("node:path"),n=process.argv.slice(3),s=u=>{const r=n.indexOf(`--${u}`);return r!==-1?n[r+1]:void 0},i=s("format")??"both";i!=="md"&&i!=="jsonl"&&i!=="both"&&(console.log(`
|
|
83
|
+
\u274C Unknown --format "${i}" \u2014 use md, jsonl, or both.
|
|
84
|
+
`),process.exit(1));const a=o(s("out")??"."),d=A||Ve()||"",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 u=[],
|
|
90
|
-
`),process.exit(0)),await t(a,{recursive:!0});const f=[];if(
|
|
89
|
+
`);try{let u=[],r="";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(_i).filter(w=>w!==null),y.complete===!1?r=y.note??"the server reported an incomplete read":typeof y.lesson_count=="number"&&u.length<y.lesson_count&&(r=`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})),r="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(i==="md"||i==="both"){const y=o(a,"lessons.md");await e(y,vi(u),"utf-8"),f.push(`${u.length} lesson${u.length===1?"":"s"} \u2192 ${y}`)}if(i==="jsonl"||i==="both"){const y=o(a,"lessons.jsonl");await e(y,xi(u),"utf-8"),f.push(`${u.length} lesson${u.length===1?"":"s"} \u2192 ${y}`)}r?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${r}`),console.log("")):console.log("\u2705 Export complete:");for(const y of f)console.log(` ${y}`);console.log("")}catch(u){console.log(`
|
|
91
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]:"",
|
|
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]:"",o=Ge(e,"source")??"",n=V();(!t||!o)&&(console.log(`
|
|
93
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)),
|
|
94
|
+
`),process.exit(1)),n||(console.log(`
|
|
95
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"),
|
|
96
|
+
`),process.exit(1));const{importiereDokumente:s}=await import("./import-docs.js"),i=await s({dir:t,source:o,apiUrl:v,apiKey:n,dryRun:e.includes("--dry-run"),confirmRemovals:e.includes("--confirm-removals")});process.exit(i.exitCode)}if(process.argv[2]==="invite"){const e=V(),t=(process.argv[3]??"").trim();(!t||t.startsWith("-"))&&(console.log(`
|
|
97
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
|
|
98
98
|
`),process.exit(1)),e||(console.log(`
|
|
99
99
|
\u26A0\uFE0F No cachly key found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
100
|
-
`),process.exit(1));const
|
|
100
|
+
`),process.exit(1));const o=W();o||(console.log(`
|
|
101
101
|
\u26A0\uFE0F No Brain selected. Set CACHLY_BRAIN_INSTANCE_ID or run:`),console.log(` npx @cachly-dev/mcp-server@latest setup
|
|
102
|
-
`),process.exit(1));try{const
|
|
102
|
+
`),process.exit(1));try{const n=await fetch(`${v}/api/v1/instances/${encodeURIComponent(o)}/share`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({email:t}),signal:AbortSignal.timeout(15e3)});if(n.status===400&&(console.log(`
|
|
103
103
|
\u274C "${t}" is not a valid email address.
|
|
104
|
-
`),process.exit(1)),
|
|
105
|
-
\u274C This Brain was not found in your account. Only the owner of a Brain can invite people.`),console.log(` Brain: ${
|
|
106
|
-
`),process.exit(1)),
|
|
104
|
+
`),process.exit(1)),n.status===404&&(console.log(`
|
|
105
|
+
\u274C This Brain was not found in your account. Only the owner of a Brain can invite people.`),console.log(` Brain: ${o}
|
|
106
|
+
`),process.exit(1)),n.status===409&&(console.log(`
|
|
107
107
|
\u2139\uFE0F ${t} already has access to this Brain. Nothing was sent.
|
|
108
|
-
`),process.exit(1)),!
|
|
109
|
-
\u274C Could not send the invitation: ${
|
|
110
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="refer"){const e=
|
|
108
|
+
`),process.exit(1)),!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.json(),i=s.invite_sent_to??t,a=s.instance?.name??o;console.log(""),console.log(` \u2705 Invitation sent to \x1B[1m${i}\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(n){console.log(`
|
|
109
|
+
\u274C Could not send the invitation: ${n.message}
|
|
110
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="refer"){const e=V();e||(console.log(`
|
|
111
111
|
\u26A0\uFE0F No cachly key found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
|
|
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
|
|
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 o=await t.json(),n=o.url??j(`/r/${o.code}`,"refer"),s=o.referral_count??0,i=`Hey, I've been using cachly to give my AI persistent memory across sessions \u2014 no more re-explaining my stack every morning.
|
|
113
113
|
|
|
114
|
-
You get a free Brain: ${
|
|
114
|
+
You get a free Brain: ${n}`,a=encodeURIComponent(`I gave my AI persistent memory. It remembers fixes, patterns, and context across every session \u2014 no more re-explaining.
|
|
115
115
|
|
|
116
|
-
Try it free: ${
|
|
116
|
+
Try it free: ${n}
|
|
117
117
|
|
|
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 ${
|
|
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 ${n.padEnd(61)}\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),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 i.split(`
|
|
119
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(`
|
|
120
120
|
\u274C Could not fetch referral link: ${t.message}
|
|
121
|
-
`),process.exit(1)}process.exit(0)}const
|
|
121
|
+
`),process.exit(1)}process.exit(0)}const gr={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:gs,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:hs,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:ys,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};if(process.argv[2]==="join"){const{writeFile:e,readFile:t,mkdir:o}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:s,dirname:i}=await import("node:path"),{homedir:a}=await import("node:os"),{createInterface:d}=await import("node:readline"),l=Ge(process.argv,"brain"),u=l===void 0&&process.argv[3]&&!process.argv[3].startsWith("-")?process.argv[3]:"";!u&&!l&&(console.log(`
|
|
122
122
|
\u274C Usage: npx @cachly-dev/mcp-server@latest join <token>`),console.log(` npx @cachly-dev/mcp-server@latest join --brain <instance-id>
|
|
123
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>
|
|
124
|
-
`),process.exit(1));let
|
|
124
|
+
`),process.exit(1));let r=A;if(!r){console.log(`
|
|
125
125
|
No API key found \u2014 starting sign-in (10 seconds)...
|
|
126
126
|
`);try{const p=await fetch(`${v}/api/v1/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(1e4)});if(p.ok){const S=await p.json();console.log(` \u{1F449} Open: \x1B[36m${S.verification_uri}\x1B[0m`),console.log(` Code: \x1B[1m${S.user_code}\x1B[0m
|
|
127
|
-
`);const x=(S.interval??5)*1e3;for(let k=0;k<24;k++){await new Promise(_=>setTimeout(_,x));try{const _=await fetch(`${v}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:S.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(_.ok){const R=await _.json();if(R.access_token){
|
|
127
|
+
`);const x=(S.interval??5)*1e3;for(let k=0;k<24;k++){await new Promise(_=>setTimeout(_,x));try{const _=await fetch(`${v}/api/v1/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:S.device_code,client_id:"cachly-mcp-cli"}),signal:AbortSignal.timeout(8e3)});if(_.ok){const R=await _.json();if(R.access_token){r=R.access_token;break}}}catch{}}r||(console.log(`
|
|
128
128
|
\u274C Sign-in timed out. Run the command again.
|
|
129
129
|
`),process.exit(1)),console.log(` \u2705 Signed in!
|
|
130
130
|
`)}}catch(p){console.log(`
|
|
131
131
|
\u26A0\uFE0F Could not start sign-in: ${p.message}`),console.log(` Set CACHLY_JWT manually from ${j("/setup-ai","join")}
|
|
132
|
-
`),process.exit(1)}}
|
|
132
|
+
`),process.exit(1)}}r||(console.log(`
|
|
133
133
|
\u274C Sign-in did not return a key. Run the command again.
|
|
134
|
-
`),process.exit(1));const m={Authorization:`Bearer ${
|
|
134
|
+
`),process.exit(1));const m={Authorization:`Bearer ${r}`};let f="",y="";if(l){console.log(`
|
|
135
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(`
|
|
136
136
|
\u274C Your key was not accepted. Sign in again: npx @cachly-dev/mcp-server@latest autopilot
|
|
137
137
|
`),process.exit(1)),(p.status===403||p.status===404)&&(console.log(`
|
|
@@ -154,118 +154,118 @@ Try it free: ${o}
|
|
|
154
154
|
Cancelled.
|
|
155
155
|
`),process.exit(1)),k=x[I-1]}f=k.id,y=k.name??k.id,console.log(`
|
|
156
156
|
\u2705 Invitation accepted. Brain: \x1B[1m${y}\x1B[0m
|
|
157
|
-
`)}
|
|
157
|
+
`)}r!==A&&se(r);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:Re("windsurf",be())},{label:"cline_mcp_settings.json (Cline)",path:Re("cline",be())},{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=i(S);if(!(!x&&!n(k)&&!n(S)))try{await o(k,{recursive:!0});let _={};if(n(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,r&&x&&!$.CACHLY_JWT&&($.CACHLY_JWT=r),v!==lo&&($.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 qe(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{}n(s(w,".cursor"))&&await re("cursor",w,f," "),n(s(w,".vscode"))&&await re("copilot",w,f," ");try{const p=await Te(f,Ln(v,r));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.
|
|
158
158
|
`),console.log(" \u{1F4DB} Add the badge to your README:"),console.log(` npx @cachly-dev/mcp-server@latest badge
|
|
159
159
|
`)),process.exit(0)}if(process.argv[2]==="upgrade"){process.stdout.write(`
|
|
160
160
|
\u23F3 Checking for updates...
|
|
161
|
-
`);try{const e=await fetch("https://registry.npmjs.org/@cachly-dev/mcp-server/latest",{signal:AbortSignal.timeout(8e3)});if(!e.ok)throw new Error(`registry HTTP ${e.status}`);const
|
|
162
|
-
\u2705 Already on the latest version: \x1B[32mv${
|
|
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${
|
|
161
|
+
`);try{const e=await fetch("https://registry.npmjs.org/@cachly-dev/mcp-server/latest",{signal:AbortSignal.timeout(8e3)});if(!e.ok)throw new Error(`registry HTTP ${e.status}`);const o=(await e.json()).version;if(!o||!/^\d+\.\d+\.\d+/.test(o))throw new Error("npm registry returned unexpected response");o===M?console.log(`
|
|
162
|
+
\u2705 Already on the latest version: \x1B[32mv${M}\x1B[0m
|
|
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${M}\x1B[0m`),console.log(` Latest : \x1B[32mv${o}\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(`
|
|
164
164
|
\u274C Could not check for updates: ${e.message}
|
|
165
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:
|
|
165
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="bench"){const{fileURLToPath:e}=await import("node:url"),{dirname:t,resolve:o}=await import("node:path"),{loadExternalCorpus:n,runExternalBenchmark:s}=await import("./bench/external-corpus.js"),i=process.argv.includes("--json"),a=process.argv.slice(3).find(u=>!u.startsWith("--")),d=t(e(import.meta.url)),l=a?o(process.cwd(),a):o(d,"bench","external","sample-corpus.json");try{const u=await n(l),r=await s(u);i&&(console.log(JSON.stringify({corpus:u.name,lessons:r.corpusSize,queries:r.queryCount,cachly_p1:Math.round(r.cachly.precisionAt1*1e3)/10,flatfile_p1:Math.round(r.flatfile.precisionAt1*1e3)/10,cachly_mrr:Math.round(r.cachly.mrr*1e3)/10,flatfile_mrr:Math.round(r.flatfile.mrr*1e3)/10,p1_lift_vs_flatfile_pct:Math.round((r.cachly.precisionAt1-r.flatfile.precisionAt1)*1e3)/10,mrr_lift_vs_flatfile_pct:Math.round((r.cachly.mrr-r.flatfile.mrr)*1e3)/10},null,2)),process.exit(0));const m=((r.cachly.precisionAt1-r.flatfile.precisionAt1)*100).toFixed(1),f=((r.cachly.mrr-r.flatfile.mrr)*100).toFixed(1),y=((r.cachly.precisionAt1-r.baseline.precisionAt1)*100).toFixed(1),w=r.cachly.precisionAt1>=r.flatfile.precisionAt1?"\x1B[32m+":"\x1B[31m",h=r.cachly.mrr>=r.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: ${r.corpusSize} lessons \xB7 ${r.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${(r.flatfile.precisionAt1*100).toFixed(1)}%\x1B[0m (naive keyword overlap \u2014 no quality signal)`),console.log(` raw BM25 : \x1B[33m${(r.baseline.precisionAt1*100).toFixed(1)}%\x1B[0m (keyword ranking)`),console.log(` cachly : \x1B[1m\x1B[32m${(r.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${(r.flatfile.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` raw BM25 : \x1B[33m${(r.baseline.mrr*100).toFixed(1)}%\x1B[0m`),console.log(` cachly : \x1B[1m\x1B[32m${(r.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 ${(r.cachly.precisionAt1*100).toFixed(1)}% (${w}${m}% vs flat-file memory, ${r.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
166
|
\u274C bench failed: ${u.message}
|
|
167
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{existsSync:e,readFileSync:t}=await import("node:fs"),{resolve:
|
|
167
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="demo"){const{existsSync:e,readFileSync:t}=await import("node:fs"),{resolve:o,basename:n}=await import("node:path"),s=process.cwd();console.log(`
|
|
168
168
|
\x1B[35m\u{1F9E0} cachly Brain \u2014 Live Demo\x1B[0m`),console.log(`\x1B[90mNo account needed. Reading your git history...\x1B[0m
|
|
169
|
-
`),e(
|
|
169
|
+
`),e(o(s,".git"))||(console.log("\u26A0\uFE0F No git repository found here."),console.log(` Run this command inside a project directory with git history.
|
|
170
170
|
`),console.log(` Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo
|
|
171
|
-
`),process.exit(0));let
|
|
171
|
+
`),process.exit(0));let i="";try{i=Nt(s,["config","user.name"]).trim().split(" ")[0]??""}catch{}let a=n(s);try{const $=JSON.parse(t(o(s,"package.json"),"utf-8"));$.name&&(a=$.name.replace(/^@[^/]+\//,""))}catch{}let d="";try{d=Nt(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
172
|
`),process.exit(0)}const l=d.trim().split(`
|
|
173
|
-
`).filter(Boolean).map($=>{const[E,z,
|
|
174
|
-
`),process.exit(0));const u=new Map,
|
|
173
|
+
`).filter(Boolean).map($=>{const[E,z,ze,ae]=$.split("|||");return{sha:(E??"").trim().slice(0,8),subject:(z??"").trim(),date:(ze??"").trim(),author:(ae??"").trim()}});l.length===0&&(console.log(`\u26A0\uFE0F No commits found.
|
|
174
|
+
`),process.exit(0));const u=new Map,r=[],m=[],f=[],y=new Set;let w=0;for(const $ of l){const E=Ni($.subject);u.set(E,(u.get(E)??0)+1),Pi($.subject)&&w++,E==="fix"&&r.length<5&&r.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=Bi(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=`${i?`Hey ${i} \u2014 `:""}here's what your AI would know about ${a}`;process.stdout.write("\x1B[2K\r"),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log(`\u2502 \x1B[1m\u{1F9E0} ${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(r.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F527} Bug fixes your AI would never repeat:\x1B[0m \u2502");for(const $ of r.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=V(),t=W();(!e||!t)&&(console.log(`
|
|
175
175
|
\u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
|
|
176
176
|
`),process.exit(1)),process.stdout.write(`
|
|
177
177
|
\u{1F9E0} Fetching your Brain stats...
|
|
178
|
-
`);try{const
|
|
178
|
+
`);try{const o=await fetch(`${v}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});if(!o.ok)throw new Error(`HTTP ${o.status}`);const n=await o.json(),s=n.lesson_count??0,i=n.total_recall_count??0,a=Math.round(n.iq_boost_pct??0),d=i*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(i).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"),r=`\u{1F9E0} My AI coding assistant now has persistent memory.
|
|
179
179
|
|
|
180
|
-
${s} lessons stored \xB7 ${
|
|
180
|
+
${s} lessons stored \xB7 ${i} recalls \xB7 ${l}
|
|
181
181
|
|
|
182
182
|
Fix a bug once \u2192 AI remembers forever. Across Claude Code, Cursor, Windsurf, Copilot.
|
|
183
183
|
|
|
184
184
|
${u}
|
|
185
185
|
|
|
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(
|
|
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(r.split(`
|
|
187
187
|
`).map(m=>` ${m}`).join(`
|
|
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(
|
|
189
|
-
\u274C Could not fetch stats: ${
|
|
190
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="publish"){const e=
|
|
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(o){console.log(`
|
|
189
|
+
\u274C Could not fetch stats: ${o.message}
|
|
190
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="publish"){const e=V(),t=W();(!e||!t)&&(console.log(`
|
|
191
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
|
|
192
|
-
`),process.exit(1));const
|
|
192
|
+
`),process.exit(1));const o=process.argv.indexOf("--title"),n=o!==-1?process.argv[o+1]??"My Brain Snapshot":"My Brain Snapshot",s=process.argv.includes("--public");process.stdout.write(`
|
|
193
193
|
\u{1F9E0} Publishing Brain snapshot...
|
|
194
|
-
`);try{const
|
|
195
|
-
\u274C Could not publish Brain: ${
|
|
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
|
|
197
|
-
\u274C Unknown format "${t}". Use one of: ${
|
|
194
|
+
`);try{const i=await fetch(`${v}/api/v1/instances/${t}/memory`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(8e3)});let a=0,d=0;if(i.ok){const f=await i.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:n,visibility:s?"public":"unlisted",instance_id:t}),signal:AbortSignal.timeout(15e3)});if(!l.ok)throw new Error(`HTTP ${l.status}`);const r=(await l.json()).share_id??"unavailable",m=j(`/brain/share/${r}`,"publish");console.log(""),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 \u{1F4E4} Brain Published \xB7 powered by \x1B[35mcachly.dev\x1B[0m \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Title : \x1B[33m${n.slice(0,44).padEnd(44)}\x1B[0m\u2502`),console.log(`\u2502 Lessons : \x1B[32m${String(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="${r.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="${r.slice(0,24)}...")`),console.log("")}catch(i){console.log(`
|
|
195
|
+
\u274C Could not publish Brain: ${i.message}
|
|
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 n=process.argv.find(s=>s.startsWith("--format="));if(n)t=n.slice(9);else{const s=process.argv.indexOf("--format");s!==-1&&(t=process.argv[s+1]??"openapi")}}const o=["openapi","openai","anthropic","langchain"];o.includes(t)||(process.stderr.write(`
|
|
197
|
+
\u274C Unknown format "${t}". Use one of: ${o.join(", ")}
|
|
198
198
|
|
|
199
|
-
`),process.exit(1)),process.stdout.write(e(
|
|
199
|
+
`),process.exit(1)),process.stdout.write(e(ue,t,M)+`
|
|
200
200
|
`,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=W();e||(console.log(`
|
|
201
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)
|
|
202
|
-
`),process.exit(1));const t=`${v}/api/v1/badge/${e}`,
|
|
203
|
-
`,()=>process.exit(0)),await new Promise(()=>{})),
|
|
204
|
-
Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||
|
|
202
|
+
`),process.exit(1));const t=`${v}/api/v1/badge/${e}`,o=j("/","badge"),n=`[](${o})`,s=`<a href="${o}"><img src="${t}" alt="cachly Brain" /></a>`;console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly Brain Badge\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Paste into your README.md:"),console.log(""),console.log(` \x1B[32m${n}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${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 xe=is(process.argv[2],process.stdin.isTTY===!0&&process.stdout.isTTY===!0);if(xe==="version"&&(process.stdout.write(`${M}
|
|
203
|
+
`,()=>process.exit(0)),await new Promise(()=>{})),xe==="unbekannt"&&console.error(`
|
|
204
|
+
Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||xe==="hilfe"||xe==="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,o)=>console.log(` \x1B[36m ${t.padEnd(22)}\x1B[0m ${o}`);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 ${ue.length} MCP tools\x1B[0m`),console.log(""),process.exit(xe==="unbekannt"?1:0)}function hr(e,t,o){if(!t)return;const{datei:n,name:s,wie:i}=gr[e];if(t.hooks==="skipped"){console.log(`\u26A0\uFE0F ${o}${n} ${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}${o}${d}: ${n} (Ambient Recall for ${s} \u2014 ${i})`)}async function nt(e,t,o,n){const s=e==="codex"?"Codex":"Gemini CLI",i=await(e==="codex"?Cs:Ts)(t,o).catch(()=>null);if(!i||i.status==="skipped"){const l=mr(e,o);console.log(`\u26A0\uFE0F ${n}${i?`${i.datei} ${i.grund??"could not be read"} \u2014 left untouched.`:`${s} MCP entry could not be written.`} Register cachly yourself:`),l&&console.log(` ${n}${l.befehl}`);return}const a=i.status==="unchanged"?"\u2713 ":"\u2705 ",d=i.status==="written"?"Written":i.status==="updated"?"Updated":"Already configured";console.log(`${a}${n}${d}: ${i.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,o,n){const s={cursor:us,copilot:ps,codex:ms,gemini:fs}[e];hr(e,await s(t,o).catch(()=>null),n)}if(process.argv[2]==="init"){const e=Date.now(),{writeFile:t,mkdir:o,readFile:n}=await import("node:fs/promises"),{resolve:s,dirname:i,relative:a}=await import("node:path"),d=process.argv.slice(3),l=x=>Ge(d,x),u=rs(d,["instance-id","api-key","editor","project-dir","api-url"]);u.length>0&&(console.error(`
|
|
205
205
|
Missing value for ${u.map(x=>`--${x}`).join(", ")}. Nothing was written.
|
|
206
|
-
`),process.exit(1));let
|
|
206
|
+
`),process.exit(1));let r=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(/\/+$/,"")),!r||!m){const x=Ne(),k=de();x&&k&&(m??=x,r??=k,m===x&&r===k&&console.log("\u2713 Reusing credentials from ~/.cachly/credentials.json (saved by a prior setup)"))}if(!r||!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 n(_,"utf-8")).mcpServers?.cachly?.env??{};m??=I.CACHLY_JWT,r??=I.CACHLY_BRAIN_INSTANCE_ID,m&&r&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!r||!m)&&(console.error(`
|
|
207
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]
|
|
208
208
|
`),console.error(`First time? Run the zero-config wizard (signs you in, auto-provisions): npx @cachly-dev/mcp-server@latest autopilot
|
|
209
209
|
`),console.error(`Get your credentials from: ${j("/setup-ai","init")}
|
|
210
|
-
`),process.exit(1));const h=
|
|
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/${
|
|
210
|
+
`),process.exit(1));const h=as({instanceId:r,apiKey:m,editor:f},[...Object.keys(Ee),"codex","gemini"]);if(h.length>0){console.error(`
|
|
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/${r}/memory`,{headers:{Authorization:`Bearer ${m}`},signal:AbortSignal.timeout(8e3)});(x.status===401||x.status===403||x.status===404)&&(console.error(`
|
|
212
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")}
|
|
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=()=>{
|
|
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=()=>{se(m),de()||je(r,{apiKey:m})};if(f==="codex"||f==="gemini")c(),console.log(""),await nt(f,y,te(m,r),"");else{const x=jt(f,y),k=x.anzeige,_=x.pfad;await o(i(_),{recursive:!0});const{existsSync:R}=await import("node:fs"),I=R(_),$=I?await n(_,"utf-8").catch(()=>""):"";c();const E=await po(_,m,r,x.format,{readFile:n,existsSync:R});E!==$?(await t(_,E,"utf-8"),console.log(`
|
|
214
214
|
\u2705 ${I?"Updated":"Written"}: ${k}`)):console.log(`
|
|
215
|
-
\u2713 Already configured: ${k} (no change)`)}const g=d.includes("--all-editors"),p=await
|
|
215
|
+
\u2713 Already configured: ${k} (no change)`)}const g=d.includes("--all-editors"),p=await mo(y,r,void 0,g?void 0:f);for(const[x,k]of Object.entries(p))console.log(fo(x.split(/[\\/]/).pop()??x,k));try{const x=await Tt(y,r),k=a(y,s(Qn(y),"post-commit")).replace(/\\/g,"/");x==="written"?console.log(`\u2705 Written: ${k} (CLS hook)`):x==="upgraded"?console.log(`\u2705 Upgraded: ${k} (CLS hook \u2192 ${It})`):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 qe(y,r);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 ${Pt})`:"\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,r,"");const S=((Date.now()-e)/1e3).toFixed(1);console.log(`
|
|
216
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(`
|
|
217
217
|
\u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
|
|
218
|
-
`),process.exit(0)}if(process.argv[2]==="status"){const e=
|
|
218
|
+
`),process.exit(0)}if(process.argv[2]==="status"){const e=V(),t=W();(!e||!t)&&(console.log(`
|
|
219
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
|
|
220
|
-
`),process.exit(1));try{const[n
|
|
221
|
-
\u274C Could not fetch status: ${
|
|
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:
|
|
220
|
+
`),process.exit(1));try{const[o,n]=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(!o.ok)throw new Error(`stats HTTP ${o.status}`);const s=await o.json(),i=n.ok?await n.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??[],r=i?.referral_count??0,m=i?.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 ${r>0?`\x1B[32m${r} joined\x1B[0m`:"share to invite new users"}${" ".repeat(Math.max(0,35-String(r).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(o){console.log(`
|
|
221
|
+
\u274C Could not fetch status: ${o.message}
|
|
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:o}=await import("node:path"),n=process.cwd();let s=0,i=0;const a=h=>{console.log(` \u2705 ${h}`),s++},d=h=>{console.log(` \u26A0\uFE0F ${h}`)},l=h=>{console.log(` \u274C ${h}`),i++};console.log(`
|
|
223
223
|
\u{1F9E0} cachly health check
|
|
224
|
-
`),console.log("\u{1F511} Auth token");const u=
|
|
225
|
-
\u{1F310} Brain API`);const
|
|
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(`${
|
|
227
|
-
\u{1F50C} Redis connectivity`),c.host&&c.port)try{let g,p;try{const _=await fetch(`${
|
|
228
|
-
\u{1F6E0} Editor configs (project dir)`);const f=[{editor:"Claude Code",path:".mcp.json"},{editor:"Cursor",path:".cursor/mcp.json"},{editor:"Windsurf",path:
|
|
229
|
-
\u{1FA9D} Git hook (ambient learning)`);const w=n
|
|
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{
|
|
231
|
-
${"\u2500".repeat(40)}`),
|
|
232
|
-
`):(console.log(`\u274C ${
|
|
224
|
+
`),console.log("\u{1F511} Auth token");const u=V();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 r=process.env.CACHLY_API_URL??"https://api.cachly.dev";try{const h=await fetch(`${r}/health`,{signal:AbortSignal.timeout(5e3)});if(h.ok){const c=await h.json();a(`${r} reachable (status: ${c.status??"ok"})`)}else h.status===401||h.status===403?a(`${r} reachable (auth required \u2014 expected)`):l(`${r}/health returned HTTP ${h.status}`)}catch(h){l(`${r} 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(`${r}/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(`${r}/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=Yt({host:c.host,port:c.port,tls_enabled:c.tls_enabled},p),x=new gt({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:Re("windsurf",be())},{editor:"Cline",path:Re("cline",be())},{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=o(n,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=o(n,".git","hooks","post-commit");if(!e(o(n,".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{$t==="ollama"?a("Local Ollama (OLLAMA_BASE_URL) \u2014 text stays on your machine"):$t==="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(`
|
|
231
|
+
${"\u2500".repeat(40)}`),i===0?console.log(`\u2705 All checks passed (${s} ok)
|
|
232
|
+
`):(console.log(`\u274C ${i} check(s) failed, ${s} passed
|
|
233
233
|
`),console.log(`\u{1F4A1} Fix issues with: npx @cachly-dev/mcp-server@latest autopilot
|
|
234
|
-
`),process.exit(1)),process.exit(0)}if(process.argv[2]==="claim"){const{readFile:e,writeFile:t}=await import("node:fs/promises"),{existsSync:
|
|
234
|
+
`),process.exit(1)),process.exit(0)}if(process.argv[2]==="claim"){const{readFile:e,writeFile:t}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:n}=await import("node:path"),{homedir:s}=await import("node:os"),i=c=>{const g=process.argv.indexOf(`--${c}`);return g!==-1?process.argv[g+1]:void 0};v=(i("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const a=(i("auth-url")??zt).replace(/\/+$/,"");console.log(`
|
|
235
235
|
\u{1F9E0} cachly \u2014 keep your test Brain in your own account
|
|
236
|
-
`),(v!=="https://api.cachly.dev"||a!==
|
|
237
|
-
`);const d=
|
|
236
|
+
`),(v!=="https://api.cachly.dev"||a!==zt)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${v}, sign-in ${a}
|
|
237
|
+
`);const d=Ms({argument:i("key"),credentials:Ne()});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
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})
|
|
239
|
-
`);let
|
|
240
|
-
`);const c=await
|
|
239
|
+
`);let r="";try{console.log(`Step 1: Sign in to your cachly account
|
|
240
|
+
`);const c=await zs(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
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"),
|
|
242
|
+
\u2139\uFE0F No browser could be opened here (${p??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),r=await Ds(fetch,c,{basis:a,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
|
|
243
243
|
`)}catch(c){console.error(`
|
|
244
244
|
|
|
245
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
|
|
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 Us(fetch,v,r,l,"mcp",`cachly-mcp/${M}`),console.log(` \x1B[32m\u2713\x1B[0m
|
|
247
247
|
`)}catch(c){console.error(`
|
|
248
248
|
|
|
249
|
-
${
|
|
250
|
-
`),process.exit(1)}A=m.apiKey,
|
|
249
|
+
${Fs(c)}
|
|
250
|
+
`),process.exit(1)}A=m.apiKey,se(m.apiKey),je(m.instanceId,{apiKey:m.apiKey}),await fe(m.apiKey),await ge(m.instanceId);const f=s(),y=new Set([...Object.values(Ee).map(c=>n(process.cwd(),c)),n(f,".claude.json"),n(f,".claude","mcp.json"),n(f,".cursor","mcp.json"),n(f,".codeium","windsurf","mcp_config.json")]);let w=0;for(const c of y)if(o(c))try{const g=Ys(await e(c,"utf-8"),l,m.apiKey);g.ersetzt&&(await t(c,g.text,"utf-8"),w++)}catch{}const h=await Ws(fetch,v,m.apiKey,m.instanceId);console.log(Js(m,h)),console.log(`
|
|
251
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.
|
|
252
|
-
`),process.exit(0)}const
|
|
253
|
-
`)),C("setup_started");const
|
|
254
|
-
`):!
|
|
252
|
+
`),process.exit(0)}const He=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||He){const{writeFile:e,mkdir:t,readFile:o}=await import("node:fs/promises"),{existsSync:n}=await import("node:fs"),{resolve:s,dirname:i}=await import("node:path"),{createInterface:a}=await import("node:readline"),d=Date.now(),l=He?"autopilot":"setup";Xn();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}
|
|
253
|
+
`)),C("setup_started");const r=process.stdin.isTTY===!0,m=He||process.argv.includes("--yes")||process.argv.includes("-y")||!r;He?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
|
|
254
|
+
`):!r&&!process.argv.includes("--yes")&&!process.argv.includes("-y")&&console.log(`\u2139\uFE0F Non-interactive terminal detected \u2014 running in automatic mode (no prompts).
|
|
255
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(`
|
|
256
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
|
|
257
257
|
`);let w=process.env.CACHLY_JWT??"";if(w)console.log(`\u2713 Using token from CACHLY_JWT env var
|
|
258
258
|
`);else{console.log(`Step 1: Sign in to cachly (free, no credit card)
|
|
259
|
-
`),C("setup_auth_started");let b="",T="",P="",D=5e3,F=!1,G="cachly";try{const
|
|
259
|
+
`),C("setup_auth_started");let b="",T="",P="",D=5e3,F=!1,G="cachly";try{const Q=await fetch(`${v}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(Q.ok){const O=await Q.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}
|
|
260
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.
|
|
261
|
-
`)}),process.stdout.write(" Waiting for authorization");const
|
|
261
|
+
`)}),process.stdout.write(" Waiting for authorization");const Q=Date.now()+600*1e3;for(;Date.now()<Q;){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
|
|
262
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(`
|
|
263
263
|
Auth error: ${O.error}. Aborting.
|
|
264
264
|
`),f.close(),process.exit(1))}catch{}}w||(C("device_flow_failed",{reason:"timeout"}),console.error(`
|
|
265
265
|
Timed out waiting for authorization. Aborting.
|
|
266
|
-
`),f.close(),process.exit(1)),console.log("")}else{C("device_flow_failed",{reason:"device_flow_unavailable"});const
|
|
267
|
-
`),console.log(` URL: \x1B[36m${
|
|
268
|
-
`),le(
|
|
266
|
+
`),f.close(),process.exit(1)),console.log("")}else{C("device_flow_failed",{reason:"device_flow_unavailable"});const Q=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${Q}\x1B[0m`),console.log(" 1. Sign up / log in at the URL above"),console.log(" 2. Go to Settings \u2192 API Keys \u2192 Create new key"),console.log(` 3. Copy the key (starts with cky_live_...)
|
|
268
|
+
`),le(Q),m?(C("device_flow_failed",{reason:"non_interactive_no_key"}),console.error(`
|
|
269
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:
|
|
270
270
|
`),console.error(` \x1B[1mCACHLY_JWT=cky_live_xxx npx @cachly-dev/mcp-server@latest autopilot\x1B[0m
|
|
271
271
|
`),console.error(` Or add it to your editor's MCP config under env.CACHLY_JWT.
|
|
@@ -283,53 +283,53 @@ Failed to fetch instances: ${T}`),T.includes("401")&&(console.error(`Token rejec
|
|
|
283
283
|
Could not create an instance automatically. Opening ${j("/instances",l)} \u2026
|
|
284
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
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"),
|
|
287
|
-
`);const{existsSync:$}=await import("node:fs"),E=[];let z=0;
|
|
288
|
-
`)[0].slice(0,160)})`);else{const T=b.match(/Ingested: \*\*(\d+)\*\*/);
|
|
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"),n(s(g,".cursor"))&&p.push("cursor");const k=be();(n(s(g,".windsurf"))||Rt("windsurf",k,n))&&p.push("windsurf"),n(s(g,".vscode"))&&p.push("copilot"),n(s(g,".continue"))&&p.push("continue"),Rt("cline",k,n)&&p.push("cline");const _=process.platform==="darwin"?s(x,"Library/Application Support/Zed"):s(x,".config/zed");n(_)&&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;se(w),je(c.id,{apiKey:w});for(const b of I){const T=jt(b,g),P=T.anzeige,D=T.pfad;try{await t(i(D),{recursive:!0});const F=$(D),G=await po(D,w,c.id,T.format,{readFile:o,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 ze=await mo(g,c.id);for(const[b,T]of Object.entries(ze)){const{relative:P}=await import("node:path");console.log(fo(P(g,b)||b,T))}A=w;let ae=0;if(n(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: ${Ct(b.replace(/^❌\s*/,"")).split(`
|
|
288
|
+
`)[0].slice(0,160)})`);else{const T=b.match(/Ingested: \*\*(\d+)\*\*/);ae=T?parseInt(T[1],10):0,console.log(` \u2713 ${ae} lesson${ae===1?"":"s"} extracted from git history`);const P=qn(b);P&&(console.log(""),console.log(Ct(P)))}}catch(b){console.log(` (skipped: ${b.message.slice(0,80)})`)}}if(ae===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=Vn(b);T&&(console.log(""),console.log(Zn(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?`
|
|
289
289
|
\u{1F9E0} Your Brain is empty. It learns from your fixes and commits from now on.`:`
|
|
290
290
|
\u{1F9E0} Your Brain now holds ${P} lesson${P===1?"":"s"}.`)}}catch{}if(!m)try{if(console.log(`
|
|
291
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
292
|
`),console.log(` team_assign_role(instance_id="${c.id}", handle="<teammate>", role="contributor", assigned_by="${T.trim()}")
|
|
293
293
|
`))}else console.log(` Skipped \u2014 run team_assign_role at any time.
|
|
294
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.
|
|
295
|
-
`)}catch{}}try{const b=await
|
|
295
|
+
`)}catch{}}try{const b=await Tt(process.cwd(),c.id);b==="written"?console.log(`
|
|
296
296
|
\u2705 CLS git hook installed \u2014 your brain will learn from every commit.`):b==="upgraded"?console.log(`
|
|
297
|
-
\u2705 CLS git hook upgraded to ${
|
|
298
|
-
\u2705 CLS git hook appended to existing post-commit.`)}catch{}if(I.includes("claude"))try{const b=await
|
|
297
|
+
\u2705 CLS git hook upgraded to ${It}.`):b==="appended"&&console.log(`
|
|
298
|
+
\u2705 CLS git hook appended to existing post-commit.`)}catch{}if(I.includes("claude"))try{const b=await qe(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 ${Pt})`:"\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(),c.id," "),I.includes("copilot")&&await re("copilot",process.cwd(),c.id," "),(n(s(x,".codex"))||n(s(g,".codex")))&&(await re("codex",process.cwd(),c.id," "),await nt("codex",process.cwd(),te("",c.id)," ")),(n(s(x,".gemini"))||n(s(g,".gemini")))&&(await re("gemini",process.cwd(),c.id," "),await nt("gemini",process.cwd(),te("",c.id)," ")),A=w;const st=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:st,config_failures:E.length}),E.length>0&&z===0){console.log(`
|
|
299
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(`
|
|
300
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(`
|
|
301
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)}
|
|
302
302
|
`),f.close(),await new Promise(b=>setTimeout(b,300)),process.exit(1)}if(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 ${(
|
|
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 ${(st+"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(`
|
|
304
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(`
|
|
305
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.
|
|
306
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),
|
|
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),o=d=>{const l=t.indexOf(`--${d}`);return l!==-1?t[l+1]:void 0},n=e(o("dir")??t.find(d=>!d.startsWith("--"))??"."),s=o("instance-id")||W(),i=parseInt(o("max-files")??"500",10),a=o("namespace")??"cachly:sem:code";(!s||!A)&&(console.error(`
|
|
308
308
|
\u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
|
|
309
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
|
|
310
310
|
`),process.exit(1)),console.log(`
|
|
311
|
-
\u{1F4C2} Indexing: ${
|
|
312
|
-
`);try{const d=await J("index_project",{instance_id:s,dir:
|
|
311
|
+
\u{1F4C2} Indexing: ${n}`),console.log(` Instance: ${s.slice(0,8)}\u2026 Max files: ${i}
|
|
312
|
+
`);try{const d=await J("index_project",{instance_id:s,dir:n,max_files:i,ttl:604800,namespace:a});console.log(d),console.log(`
|
|
313
313
|
\u2705 Indexing complete.
|
|
314
314
|
`)}catch(d){console.error(`
|
|
315
315
|
\u274C Indexing failed: ${d.message}
|
|
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),
|
|
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),o=a=>{const d=t.indexOf(`--${a}`);return d!==-1?t[d+1]:void 0},n=e(o("dir")??t.find(a=>!a.startsWith("--"))??"."),s=o("instance-id")||W(),i=parseInt(o("max-commits")??"50",10);(!s||!A)&&(console.error(`
|
|
317
317
|
\u274C No Brain instance or key found (flag, environment or ~/.cachly/credentials.json)
|
|
318
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 .
|
|
319
319
|
`),process.exit(1)),console.log(`
|
|
320
|
-
\u{1F9E0} Learning from git history: ${
|
|
321
|
-
`);try{const a=await J("brain_from_git",{instance_id:s,repo_path:
|
|
320
|
+
\u{1F9E0} Learning from git history: ${n}`),console.log(` Instance: ${s.slice(0,8)}\u2026 Max commits: ${i}
|
|
321
|
+
`);try{const a=await J("brain_from_git",{instance_id:s,repo_path:n,limit:i});console.log(a),C("brain_from_git",{instance_id:s}),console.log(`
|
|
322
322
|
\u2705 Brain learned from your commits.
|
|
323
323
|
`),await new Promise(d=>setTimeout(d,300))}catch(a){console.error(`
|
|
324
324
|
\u274C learn-git failed: ${a.message}
|
|
325
|
-
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await
|
|
325
|
+
`),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await bs(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await ws(),process.argv[2]===xs&&await vs(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),o=process.argv.slice(4).join(" ").slice(0,200)||void 0,n={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:o,instanz:W()||void 0};await $s(n),await Gi(process.env.CACHLY_BRAIN_INSTANCE_ID??N,n),console.log(`\u2705 ambient credit recorded: ${t} tokens${o?` (${o})`:""}`)}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=As(await Bt(),e||void 0),o=t.eigene,n=Ri(o),s=o.slice(-5);if(console.log(`
|
|
326
326
|
\u{1F9E0} Ambient Recall \u2014 net-token ledger
|
|
327
|
-
`),console.log(` Instance: ${e?`${e.slice(0,8)}\u2026`:"(none set \u2014 showing every entry on this computer)"}`),console.log(` Turns recorded: ${
|
|
328
|
-
Last entries:`);for(const
|
|
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:
|
|
327
|
+
`),console.log(` Instance: ${e?`${e.slice(0,8)}\u2026`:"(none set \u2014 showing every entry on this computer)"}`),console.log(` Turns recorded: ${o.length}`),console.log(` Injected tokens: ${n.injected}`),console.log(` Prevented tokens: ${n.prevented} (agent-reported via ambient-credit)`),console.log(` NET: ${n.net>=0?"+":""}${n.net} tokens`),s.length>0){console.log(`
|
|
328
|
+
Last entries:`);for(const i of s){const a=i.prevented>0?`+${i.prevented} prevented`:`-${i.injected} injected`;console.log(` \u2022 ${i.ts.slice(0,19)} ${i.event}: ${a}${i.note?` (${i.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:o}=await import("node:path"),{createInterface:n}=await import("node:readline/promises"),s=process.argv.slice(3),a={projekt:o((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:V(),instanz:W(),apiUrl:v,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:d=>console.log(d),frage:async d=>{const l=n({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 cs(s,a))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:o,checkAuthAccepted:n,checkInstance:s,checkVectorCoverage:i,inspectAmbientHooks:a,checkHooks:d,checkLedger:l,renderDoctorReport:u,doctorExitCode:r}=await import("./doctor.js"),m=[e(),t(A),await o(v),await n(v,A),s(W()||N),await i(v,A,W()||N),d(a(process.cwd())),l(await Bt(),ks())];console.log(u(m)),process.exit(r(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 o=t.instance_id??N;(!o||!t.source)&&process.exit(0),await J("cls_ingest",{instance_id:o,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!A){const e=vo();if(e)try{const t=await fetch(_o(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:xo(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const o=await t.json();o.access_token&&(A=o.access_token,ne(o.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).
|
|
330
330
|
`))}else process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth failed (${t.status}). Check CACHLY_CLIENT_ID / CACHLY_CLIENT_SECRET.
|
|
331
331
|
`),C("m2m_auth_failed",{status:t.status})}catch(t){process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth error: ${t.message}
|
|
332
|
-
`),C("m2m_auth_failed",{reason:"network"})}}const
|
|
332
|
+
`),C("m2m_auth_failed",{reason:"network"})}}const yr=["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&&!yr.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&Io){const n=`
|
|
333
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
|
|
334
334
|
\u2551 \u{1F9E0} cachly AI Brain \u2014 Setup required \u2551
|
|
335
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,11 +345,11 @@ Could not create an instance automatically. Opening ${j("/instances",l)} \u2026
|
|
|
345
345
|
\u2551 Free tier \u2014 no credit card required. \u2551
|
|
346
346
|
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
|
|
347
347
|
|
|
348
|
-
`;process.stdout.write(
|
|
348
|
+
`;process.stdout.write(n),process.exit(0)}else process.stderr.write(`
|
|
349
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).
|
|
350
350
|
(Own account: npx @cachly-dev/mcp-server@latest autopilot)
|
|
351
351
|
|
|
352
|
-
`);else{const e=
|
|
352
|
+
`);else{const e=yo(A);if(e!==null){const t=Math.floor((e-Date.now())/6e4);t<=0?process.stderr.write(`
|
|
353
353
|
\u26A0\uFE0F cachly: CACHLY_JWT expired ${Math.abs(t)} minute(s) ago.
|
|
354
354
|
All tool calls will fail. Get a fresh token at ${j("/setup-ai","jwt-expiry")}
|
|
355
355
|
|
|
@@ -357,9 +357,9 @@ Could not create an instance automatically. Opening ${j("/instances",l)} \u2026
|
|
|
357
357
|
\u26A0\uFE0F cachly: CACHLY_JWT expires in ${t} minute(s).
|
|
358
358
|
Refresh it soon at ${j("/setup-ai","jwt-expiry")} to avoid interruptions.
|
|
359
359
|
|
|
360
|
-
`)}}process.env.PORT||
|
|
361
|
-
`);const t=
|
|
362
|
-
`);const{createServer:s}=await import("node:http"),
|
|
363
|
-
`),u.headersSent||(u.writeHead(500,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:x.message})))}};await(c?
|
|
364
|
-
`)})}else{
|
|
365
|
-
`),(async()=>{await
|
|
360
|
+
`)}}process.env.PORT||mi({aktuelle:pi(M)});const Me=process.env.PORT?parseInt(process.env.PORT,10):void 0;function go(){Oi({abruf:B,bereich:()=>L()?he()?.schluesselHash??"-":""}),Yi(()=>v,Ki(M))}if(Me){Go(!0),A="",N="",ne(""),Ko(),go();const e=sn(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=en(async(l,u)=>{const r=await fetch(`${v}${l}`,{headers:{Authorization:`Bearer ${u}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)}),m=r.ok?await r.json().catch(()=>null):null,f=Number(r.headers.get("retry-after"));return{status:r.status,body:m,retryAfterS:Number.isFinite(f)&&f>0?f:void 0}},{grenze:tn()}),o=ln(),n=pn(o);process.stderr.write(`cachly-mcp HTTP: OAuth ${o.resource} -> ${o.aussteller}, Unterschrift ${o.jwksUrl?"hier geprueft":"nur in der API geprueft (MCP_OAUTH_JWKS_URL=aus)"}
|
|
362
|
+
`);const{createServer:s}=await import("node:http"),i=(l,u,r,m,f)=>{l.headersSent||(l.writeHead(u,{"Content-Type":"application/json",...u===429&&m?{"Retry-After":String(m)}:{},...u===401?{"WWW-Authenticate":un(o,"invalid_token",f)}:{}}),l.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:r},id:null})))},a=async(l,u)=>{const r=[];let m=0;for await(const f of l){const y=f;if(m+=y.length,m>u)return;r.push(y)}return Buffer.concat(r).toString("utf8")};s((l,u)=>{const r=new URL(l.url??"/",`http://localhost:${Me}`);if(r.pathname==="/health"){u.writeHead(200,{"Content-Type":"application/json"}),u.end(JSON.stringify({status:"ok",version:M,mode:"http-remote"}));return}if(!wn(l,u,r.pathname)){if(o.metadatenPfade.includes(r.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(dn(o)));return}if(r.pathname==="/mcp"||r.pathname==="/"){const m=on(l.headers["x-real-ip"],l.socket.remoteAddress);nn(m,async()=>{const f=Zo(l.headersDistinct?.authorization??l.headers.authorization,{aussteller:o.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"?fn("aussteller"):"Das ist kein cachly-API-Schluessel (er beginnt mit cky_). Neuen holen: "+j("/setup-ai","setup");return i(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,bn);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(hn(y))return i(u,401,Ae,void 0,yn)}const w=Xo(l.headers["x-cachly-instance"]);if(w.art==="abgelehnt")return i(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=kt(f.schluessel,p)}catch(p){return p instanceof St?i(u,p.httpStatus,p.message,p.retryAfterS):i(u,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}if(f.art==="jwt")try{const p=await n.pruefe(f.token),S=await t.loese(f.token,h,m,{anmeldung:!0,bisMs:p.bisMs});c=kt(f.token,S,p.sub)}catch(p){return p instanceof mn?p.grund==="jwks-fehlt"?i(u,502,p.message):i(u,401,p.message):p instanceof St?i(u,p.httpStatus,p.message,p.retryAfterS):i(u,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}const g=async()=>{const p=dr(),S=new Ro({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?qo(c,g):g())});return}u.writeHead(404),u.end("not found")}}).listen(Me,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${Me}
|
|
364
|
+
`)})}else{go();const e=new Eo;Y("start: Module geladen, stdio verbinden"),await X.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(ht=!0,si(()=>ui(yt)),Ho(),yi(),gi(process.stdin,o=>{process.stderr.write(`[cachly-mcp] ${o} \u2014 session over, server exits too
|
|
365
|
+
`),(async()=>{await ot().catch(()=>{});for(const n of Ye())await n.quit().catch(()=>{});process.exit(0)})()}))}at("cachly","startup",{version:M,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{ts as CLAUDE_MD_MARKER_END,es as CLAUDE_MD_MARKER_START,En as CROSS_LINGUAL_MAP,Ee as EDITOR_FILES,An as STOPWORDS,fo as anweisungsZeile,Tn as arabicLightStem,Et as buildClaudeMdBlock,fr as buildMcpConfig,te as buildServerEnv,In as expandCrossLingual,Sn as extractTimestamp,wt as fristMs,Cn as katakanaToRomaji,$n as levenshtein,mr as mcpAddBefehl,Qt as mcpAnweisungen,po as mergeMcpConfig,kn as recencyBoost,Nn as reconnectOnce,_n as splitMultiQuery,xt as startBackgroundDevicePoll,xn as tokenize,mo as writeInstructions};
|