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