@cachly-dev/mcp-server 0.10.259 → 0.10.260

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import{setzeClientKennung as Qt}from"./herkunft.js";import{jwtExpiryMs as eo,checkJwt as to,handleApiError as oo,diagnoseAuth as Ne,planAuthHeal as Ze,readClientCredentialsFromEnv as no,buildClientCredentialsBody as so,clientCredentialsTokenUrl as io}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as ro}from"./werkzeug-nutzung.js";import{istLieferung as ao,lieferSchluessel as co,tokenDerAntwort as lo,hatTreffer as uo,trefferSchluessel as Xe}from"./geliefert.js";import{notify as Qe}from"./notifier.js";import{fileURLToPath as et}from"node:url";import{createRequire as po}from"node:module";import{execFile as Oe}from"node:child_process";const mo=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 go}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ho}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ot,ErrorCode as te,ListPromptsRequestSchema as nt,ListResourceTemplatesRequestSchema as st,ListResourcesRequestSchema as it,ListToolsRequestSchema as rt,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",S=Fe()??"";oe(S);const Ai=process.env.CACHLY_EMBED_MODEL??"",H=(()=>{try{const e=po(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"})(),fo=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let P=Ie(process.env.CACHLY_BRAIN_INSTANCE_ID);function we(){return W()?xe()?.schluessel??"":S}function yo(){return W()?xe()?.instanzId??"":P}function X(){return S||Fe()||""}function U(){return Ie(process.env.CACHLY_BRAIN_INSTANCE_ID)||Te()||""}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 ws({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:et})}function re(){return ct?Ct(process.env):!1}function Le(e,t,n){!e||!re()||hs({instanzId:e,vomHook:n,verbindung:L,ausGit:o=>Je("brain_from_git",o,L,O),projektOrdner:t?async()=>t:lt,einbetten:o=>pt(o,{geduld:"lang"}),hatEinbettung:Eo,einbettenZweit:o=>pt(o,{geduld:"lang",modell:Jo}),melde:o=>A("brain_from_git",{instance_id:e,total:o,auto:"startwissen"}),startvorrat:o=>Ke("brain_seed_starter",o,L,O),meldeStartvorrat:o=>A("brain_seed_starter",{instance_id:e,auto:!0},{seeded_count:o,auto:!0})})}function He(){return re()&&vs()}const bo=7e3,wo=12e3,vo=18e4;let ve=null;function Me(e){return ve||(ve=xo(e).finally(()=>{ve=null})),ve}async function xo(e){try{if(!S){const t=Date.now()+e;for(;!Ce()&&as({})&&Date.now()<t;)await new Promise(s=>setTimeout(s,ss));const n=Ce();if(!n)return!1;S=n,oe(n);const o=Te();o&&!P&&(P=o,Q=0),await pe(n),o&&await me(o),A("instant_trial_started",{tool:"sessionstart-hook",...o?{instance_id:o}:{}})}if(re()&&At()){const t=is();t&&(Ye(t.instanzId,re(),He()),Le(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!S}function _o(){if(!Ct(process.env))return;const e=Date.now()+vo,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}S&&!At()||Me(0)},500);t.unref(),Me(0)}async function $o(){if(!S||W())return"";try{const e=await fetch(`${x}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"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 ${S}`},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 yo();if(P)return P;if(!S)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 ${S}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const o=(await t.json())?.data??[],s=o.find(r=>r.status==="running")??o.find(r=>r.status==="provisioning");if(s)return P=s.id,Q=0,P;const i=await $o();if(i)return P=i,Q=0,Ye(i,re(),He()),me(i),Le(i),P}}catch{}return""})();try{return await ue}finally{ue=null}}let ze=0;const ko=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"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const r=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(o(a))try{const u=await n(a,"utf-8"),p=JSON.parse(u),c=p?.mcpServers?.cachly;c?.env&&(c.env.CACHLY_JWT=e,await t(a,JSON.stringify(p,null,2),"utf-8"))}catch{}}))}catch{}}async function me(e){if(e){Ae(e,{apiKey:S});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const r=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(o(a))try{const u=JSON.parse(await n(a,"utf-8")),p=u?.mcpServers?.cachly;p?.env&&(p.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(a,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}}async function So(){try{const e=await fetch(`${x}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`},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?(S=t.key,oe(t.key),pe(t.key),A("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function De(){const e=Ne(S),t=Ze(e);if(t==="none")return ae="",!0;if(t==="refresh"){const n=Date.now();return n-ze>=ko&&(ze=n,await So())?(ae="",!0):(ae=e.message,e.usable)}return ae=e.message,!1}function ce(e,t){const n=(r,a)=>{try{t?.(r,a)}catch{}},o=r=>{r?n(!1,r.code??r.message):n(!0)},s=In(e);if(!s){n(!1,"keine-http-adresse");return}const i=En(s);try{process.platform==="win32"?Oe("cmd",["/c","start","",i],{windowsHide:!0},o):process.platform==="darwin"?Oe("open",[s],o):Oe("xdg-open",[s],o)}catch(r){n(!1,r instanceof Error?r.message:"unknown")}}let G=null;async function Ao(){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()+600*1e3,polling:!1}}}catch{}try{const t=await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/auth/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id=cachly-cli&scope=openid",signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;const n=await t.json();return{deviceCode:n.device_code,userCode:n.user_code,verifyUrl:n.verification_uri_complete,pollInterval:(n.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}catch{return null}}async function Co(e){if(Date.now()>e.deadline)return"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 i=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(i.ok){const r=await i.json();r.key&&(s=r.key)}}catch{}return S=s,oe(s),G=null,A("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 ut(e){if(e.polling)return"pending";e.polling=!0;try{return await Co(e)}finally{e.polling=!1}}function To(e,t=ut,n=s=>G===s,o=Io){const s=async()=>{if(!n(e))return;let i="pending";try{i=await t(e)}catch{}if(i!=="done"){if(i==="expired"){n(e)&&(G=null);return}n(e)&&o(s,e.pollInterval)}};o(s,e.pollInterval)}function Io(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as oe,computeEmbedding as pt,hasEmbedProvider as Eo,EMBED_PROVIDER as mt,erzwingeEmbedAnbieterRemote as Ro}from"./embeddings.js";import{istMehrmandant as W,setzeMehrmandant as jo,mandantKontext as xe,imMandant as Bo,baueKontext as Po,poolSchluessel as No,leseBearer as Oo,leseInstanzKopf as Lo,BegrenzterSpeicher as Ho,baueZugangsAufloeser as Mo,ZugangAbgelehnt as zo,ANLEITUNG_OHNE_KOPF as Ue,istRemoteErlaubt as Do,nurLokalText as Uo,bereinigeArgumente as Wo}from"./remote-zugang.js";import{ZWEIT_MODELL as Jo}from"./rangfolge-stellschrauben.js";import{tokenize as Fo,splitMultiQuery as Yo,levenshtein as Ko,recencyBoost as Go,extractTimestamp as qo,STOPWORDS as Vo,katakanaToRomaji as Zo,arabicLightStem as Xo,expandCrossLingual as Qo,CROSS_LINGUAL_MAP as en}from"./search.js";const ge=new Map,tn=200,on=10*6e4,_e=new Ho({max:tn,ttlMs:on,beiEntfernen:e=>{e.quit().catch(()=>e.disconnect())}});function We(){return[...ge.values(),..._e.werte()]}function nn(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 Qt}from"./herkunft.js";import{jwtExpiryMs as eo,checkJwt as to,handleApiError as oo,diagnoseAuth as Pe,planAuthHeal as Ze,readClientCredentialsFromEnv as no,buildClientCredentialsBody as so,clientCredentialsTokenUrl as io}from"./auth.js";import{cachlyUrl as j}from"./cachly-url.js";import{nutzungsSchluessel as ro}from"./werkzeug-nutzung.js";import{istLieferung as ao,lieferSchluessel as co,tokenDerAntwort as lo,hatTreffer as uo,trefferSchluessel as Xe}from"./geliefert.js";import{notify as Qe}from"./notifier.js";import{fileURLToPath as et}from"node:url";import{createRequire as po}from"node:module";import{execFile as Oe}from"node:child_process";const mo=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 go}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ho}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ot,ErrorCode as te,ListPromptsRequestSchema as nt,ListResourceTemplatesRequestSchema as st,ListResourcesRequestSchema as it,ListToolsRequestSchema as rt,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",S=Fe()??"";oe(S);const Ti=process.env.CACHLY_EMBED_MODEL??"",H=(()=>{try{const e=po(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"})(),fo=Number(process.env.CACHLY_PROVISION_TIMEOUT_MS??9e4);let N=Ie(process.env.CACHLY_BRAIN_INSTANCE_ID);function we(){return W()?xe()?.schluessel??"":S}function yo(){return W()?xe()?.instanzId??"":N}function X(){return S||Fe()||""}function U(){return Ie(process.env.CACHLY_BRAIN_INSTANCE_ID)||Te()||""}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 xs({wurzeln:e,env:process.env,cwd:process.cwd(),dateiPfad:et})}function re(){return ct?Ct(process.env):!1}function Le(e,t,n){!e||!re()||ys({instanzId:e,vomHook:n,verbindung:L,ausGit:o=>Je("brain_from_git",o,L,O),projektOrdner:t?async()=>t:lt,einbetten:o=>pt(o,{geduld:"lang"}),hatEinbettung:Eo,einbettenZweit:o=>pt(o,{geduld:"lang",modell:Yo}),melde:o=>A("brain_from_git",{instance_id:e,total:o,auto:"startwissen"}),startvorrat:o=>Ke("brain_seed_starter",o,L,O),meldeStartvorrat:o=>A("brain_seed_starter",{instance_id:e,auto:!0},{seeded_count:o,auto:!0})})}function He(){return re()&&_s()}const bo=7e3,wo=12e3,vo=18e4;let ve=null;function Me(e){return ve||(ve=xo(e).finally(()=>{ve=null})),ve}async function xo(e){try{if(!S){const t=Date.now()+e;for(;!Ce()&&ls({})&&Date.now()<t;)await new Promise(s=>setTimeout(s,rs));const n=Ce();if(!n)return!1;S=n,oe(n);const o=Te();o&&!N&&(N=o,Q=0),await pe(n),o&&await me(o),A("instant_trial_started",{tool:"sessionstart-hook",...o?{instance_id:o}:{}})}if(re()&&At()){const t=as();t&&(Ye(t.instanzId,re(),He()),Le(t.instanzId,t.projekt||void 0,t.vomHook))}}catch{}return!!S}function _o(){if(!Ct(process.env))return;const e=Date.now()+vo,t=setInterval(()=>{if(Date.now()>e){clearInterval(t);return}S&&!At()||Me(0)},500);t.unref(),Me(0)}async function $o(){if(!S||W())return"";try{const e=await fetch(`${x}/api/v1/instances/auto`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"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 ${S}`},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 yo();if(N)return N;if(!S)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 ${S}`,Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(t.ok){const o=(await t.json())?.data??[],s=o.find(r=>r.status==="running")??o.find(r=>r.status==="provisioning");if(s)return N=s.id,Q=0,N;const i=await $o();if(i)return N=i,Q=0,Ye(i,re(),He()),me(i),Le(i),N}}catch{}return""})();try{return await ue}finally{ue=null}}let ze=0;const ko=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"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const r=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(o(a))try{const u=await n(a,"utf-8"),p=JSON.parse(u),c=p?.mcpServers?.cachly;c?.env&&(c.env.CACHLY_JWT=e,await t(a,JSON.stringify(p,null,2),"utf-8"))}catch{}}))}catch{}}async function me(e){if(e){Ae(e,{apiKey:S});try{const{writeFile:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s}=await import("node:path"),i=process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??"";if(!i)return;const r=[s(i,".claude","mcp.json"),s(i,".cursor","mcp.json"),s(i,".codeium","windsurf","mcp_config.json")];await Promise.allSettled(r.map(async a=>{if(o(a))try{const u=JSON.parse(await n(a,"utf-8")),p=u?.mcpServers?.cachly;p?.env&&(p.env.CACHLY_BRAIN_INSTANCE_ID=e,await t(a,JSON.stringify(u,null,2),"utf-8"))}catch{}}))}catch{}}}async function So(){try{const e=await fetch(`${x}/api/v1/api-keys`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`},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?(S=t.key,oe(t.key),pe(t.key),A("auth_self_healed",{reason:"near_expiry_refresh"}),!0):!1}catch{return!1}}async function De(){const e=Pe(S),t=Ze(e);if(t==="none")return ae="",!0;if(t==="refresh"){const n=Date.now();return n-ze>=ko&&(ze=n,await So())?(ae="",!0):(ae=e.message,e.usable)}return ae=e.message,!1}function ce(e,t){const n=(r,a)=>{try{t?.(r,a)}catch{}},o=r=>{r?n(!1,r.code??r.message):n(!0)},s=Rn(e);if(!s){n(!1,"keine-http-adresse");return}const i=jn(s);try{process.platform==="win32"?Oe("cmd",["/c","start","",i],{windowsHide:!0},o):process.platform==="darwin"?Oe("open",[s],o):Oe("xdg-open",[s],o)}catch(r){n(!1,r instanceof Error?r.message:"unknown")}}let G=null;async function Ao(){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()+600*1e3,polling:!1}}}catch{}try{const t=await fetch("https://auth.cachly.dev/realms/cachly/protocol/openid-connect/auth/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id=cachly-cli&scope=openid",signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;const n=await t.json();return{deviceCode:n.device_code,userCode:n.user_code,verifyUrl:n.verification_uri_complete,pollInterval:(n.interval??5)*1e3,deadline:Date.now()+600*1e3,polling:!1}}catch{return null}}async function Co(e){if(Date.now()>e.deadline)return"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 i=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(i.ok){const r=await i.json();r.key&&(s=r.key)}}catch{}return S=s,oe(s),G=null,A("device_flow_completed"),pe(s),ne(s),Q=0,await dt(),N&&me(N),"done"}return o.error==="slow_down"&&(e.pollInterval=Math.min(e.pollInterval+2e3,15e3)),"pending"}catch{return"pending"}}async function ut(e){if(e.polling)return"pending";e.polling=!0;try{return await Co(e)}finally{e.polling=!1}}function To(e,t=ut,n=s=>G===s,o=Io){const s=async()=>{if(!n(e))return;let i="pending";try{i=await t(e)}catch{}if(i!=="done"){if(i==="expired"){n(e)&&(G=null);return}n(e)&&o(s,e.pollInterval)}};o(s,e.pollInterval)}function Io(e,t){const n=setTimeout(e,t);typeof n.unref=="function"&&n.unref()}import{setEmbedJwt as oe,computeEmbedding as pt,hasEmbedProvider as Eo,EMBED_PROVIDER as mt,erzwingeEmbedAnbieterRemote as Ro}from"./embeddings.js";import{istMehrmandant as W,setzeMehrmandant as jo,mandantKontext as xe,imMandant as Bo,baueKontext as No,poolSchluessel as Po,leseBearer as Oo,leseInstanzKopf as Lo,BegrenzterSpeicher as Ho,baueZugangsAufloeser as Mo,ZugangAbgelehnt as zo,bauePruefGrenze as Do,leseAufruferIp as Uo,ANLEITUNG_OHNE_KOPF as Ue,istRemoteErlaubt as Wo,nurLokalText as Jo,bereinigeArgumente as Fo}from"./remote-zugang.js";import{ZWEIT_MODELL as Yo}from"./rangfolge-stellschrauben.js";import{tokenize as Ko,splitMultiQuery as Go,levenshtein as qo,recencyBoost as Vo,extractTimestamp as Zo,STOPWORDS as Xo,katakanaToRomaji as Qo,arabicLightStem as en,expandCrossLingual as tn,CROSS_LINGUAL_MAP as on}from"./search.js";const ge=new Map,nn=200,sn=10*6e4,_e=new Ho({max:nn,ttlMs:sn,beiEntfernen:e=>{e.quit().catch(()=>e.disconnect())}});function We(){return[...ge.values(),..._e.werte()]}function rn(e){return e<=1?200:null}async function L(e){if(!e)throw new Z(te.InvalidRequest,`\u23F3 Your Brain instance is still being set up.
3
3
 
4
4
  This usually resolves in a few seconds \u2014 just call the tool again and it will connect automatically.
5
5
 
6
6
  If it keeps happening:
7
7
  \u2022 Run \`list_instances\` to check your instances, or
8
8
  \u2022 Set CACHLY_BRAIN_INSTANCE_ID in your MCP config, or
9
- \u2022 Reach us at support@cachly.dev.`);const t=W()?xe():void 0;if(W()&&!t)throw new Z(te.InvalidRequest,Ue);const n=t?No(t.schluessel,e):e,o=t?_e.get(n):ge.get(e);return o||ps(sn,n,()=>rn(e,n,!!t))}const sn=new Map;async function rn(e,t=e,n=!1){Y("verbindung: Instanz abfragen");let o=await O(`/api/v1/instances/${e}`);if(Y(`verbindung: Instanz ${o.status}`),o=await us(o,()=>O(`/api/v1/instances/${e}`),{fristMs:fo,melde:p=>Y(`verbindung: Instanz ${p.status}`)}),o.status!=="running"){n||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:o.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let p;throw o.status==="provisioning"?p=`\u23F3 Brain instance "${o.name}" is still starting up.
9
+ \u2022 Reach us at support@cachly.dev.`);const t=W()?xe():void 0;if(W()&&!t)throw new Z(te.InvalidRequest,Ue);const n=t?Po(t.schluessel,e):e,o=t?_e.get(n):ge.get(e);return o||gs(an,n,()=>cn(e,n,!!t))}const an=new Map;async function cn(e,t=e,n=!1){Y("verbindung: Instanz abfragen");let o=await O(`/api/v1/instances/${e}`);if(Y(`verbindung: Instanz ${o.status}`),o=await ms(o,()=>O(`/api/v1/instances/${e}`),{fristMs:fo,melde:p=>Y(`verbindung: Instanz ${p.status}`)}),o.status!=="running"){n||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify({event:"instance_not_reachable",instance_id:e,status:o.status,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{});let p;throw o.status==="provisioning"?p=`\u23F3 Brain instance "${o.name}" is still starting up.
10
10
 
11
11
  First-time provisioning typically takes 1\u20133 minutes. Please retry in a moment \u2014 the instance will be ready soon.`:o.status==="failed"?p=`\u274C Brain instance "${o.name}" failed to start.
12
12
 
@@ -18,11 +18,11 @@ Update your payment method at: ${j("/billing","upgrade")}`:o.status==="pending_p
18
18
  Complete your checkout at: ${j("/instances","upgrade")}`:p=`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,p)}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,i;try{const p=await O(`/api/v1/instances/${e}/connection`);s=p.password??void 0,i=p,Y("verbindung: Zugangsdaten da")}catch(p){const c=p instanceof Error?p.message:String(p);if(c.includes("401")||c.includes("403")||c.includes("Unauthorized"))throw new Z(te.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const r=Rt({host:o.host,port:o.port,tls_enabled:o.tls_enabled},i),a=new at({host:r.host,port:r.port,password:s||void 0,commandTimeout:8e3,...r.tls?{tls:r.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:nn,maxRetriesPerRequest:1,keepAlive:15e3}),u=()=>{n?_e.vergissWenn(t,a):ge.delete(e),a.disconnect()};a.on("error",u),a.on("end",u);try{await a.connect()}catch(p){a.disconnect();const c=p instanceof Error?p.message:String(p);throw n||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:o.host,port:o.port,error:c,version:H}),signal:AbortSignal.timeout(3e3)}).catch(()=>{}),new Z(te.InternalError,`Could not reach Brain instance "${o.name}" (${o.host}:${o.port}).
21
+ \u2022 Run \`get_api_status\` for a full diagnostic.`,new Z(te.InvalidRequest,p)}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,i;try{const p=await O(`/api/v1/instances/${e}/connection`);s=p.password??void 0,i=p,Y("verbindung: Zugangsdaten da")}catch(p){const c=p instanceof Error?p.message:String(p);if(c.includes("401")||c.includes("403")||c.includes("Unauthorized"))throw new Z(te.InvalidRequest,"API key rejected \u2014 run `cachly setup` to refresh your credentials.")}const r=Rt({host:o.host,port:o.port,tls_enabled:o.tls_enabled},i),a=new at({host:r.host,port:r.port,password:s||void 0,commandTimeout:8e3,...r.tls?{tls:r.tls}:{},lazyConnect:!0,enableReadyCheck:!0,connectTimeout:8e3,retryStrategy:rn,maxRetriesPerRequest:1,keepAlive:15e3}),u=()=>{n?_e.vergissWenn(t,a):ge.delete(e),a.disconnect()};a.on("error",u),a.on("end",u);try{await a.connect()}catch(p){a.disconnect();const c=p instanceof Error?p.message:String(p);throw n||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify({event:"redis_connect_failed",instance_id:e,host:o.host,port:o.port,error:c,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: ${c}`)}return n?_e.set(t,a):ge.set(e,a),Y("verbindung: Valkey verbunden"),a}async function O(e,t={},n=!1){!n&&!W()&&Ze(Ne(S))!=="none"&&await De();const o=we();to(o);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),i=await fetch(`${x}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,...t.headers}});if(!i.ok){if(i.status===401&&!n&&!W()&&(ze=0,await De()))return O(e,t,!0);const a=(await i.json().catch(()=>({error:i.statusText}))).error??i.statusText;oo(i.status,a)}if(i.status!==204)return i.json()}import{handleBrainTool as an}from"./handlers/brain.js";import{handleContextTool as cn}from"./handlers/context.js";import{handleInstanceTool as ln}from"./handlers/instances.js";import{handleCacheTool as dn}from"./handlers/cache.js";import{handleTeamTool as un}from"./handlers/team.js";import{handleRoadmapTool as pn}from"./handlers/roadmap.js";import{handleAdvancedTool as mn}from"./handlers/advanced.js";import{handleSyndicateTool as gn}from"./handlers/syndicate.js";import{handleFedbrainTool as Je,_lastBrainFromGitCounts as $e}from"./handlers/fedbrain.js";import{extractFirstRecallProof as hn,extractTopHit as fn,fuersTerminal as gt,renderFirstRecallProof as yn}from"./first-recall-proof.js";import{aussetzerLeise as bn}from"./aussetzer.js";import{gitHookOrdner as wn,installClsPostCommitHook as ht,CLS_HOOK_VERSION as ft}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as vn,CLAUDE_MD_MARKER_END as xn,EDITOR_FILES as ke,ANWEISUNGS_DATEIEN as _n,buildClaudeMdBlock as yt,setzeAnweisungsblock as $n,sollSchreiben as kn,globaleMcpDatei as Se,globalerEditorDa as bt,diesesHeim as he,mcpZiel as wt}from"./projektdateien.js";import{klassiereArgument as Sn,leseFlag as vt,flagsOhneWert as An,pruefeInitEingaben as Cn}from"./cli-argumente.js";import{uninstallBefehl as Tn}from"./uninstall.js";import{gitLesen as xt}from"./git-ohne-shell.js";import{browserAdresse as In,fuerCmd as En}from"./browser-adresse.js";import{installAmbientHooks as _t,installCursorHooks as Rn,installCopilotHooks as jn,installCodexHooks as Bn,installGeminiHooks as Pn,AMBIENT_HOOK_VERSION as $t,COPILOT_HOOKS_DATEI as Nn,CODEX_HOOKS_DATEI as On,GEMINI_SETTINGS_DATEI as Ln}from"./ambient-hooks.js";import{hookHauptlauf as Hn,auffrischenHauptlauf as Mn,startwissenImportHauptlauf as zn}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as Dn}from"./startwissen-hook.js";import{rahmeAntwort as Un}from"./antwort-rahmen.js";import{appendLedgerEntry as Wn,readLedger as kt,defaultLedgerPath as Jn,reportLedgerEntry as Fn,teileNachInstanz as Yn}from"./ambient-ledger.js";import{installCodexMcp as Kn,installGeminiMcp as Gn}from"./editor-mcp-eintrag.js";import{resolveApiKey as Fe,saveApiKey as ne,saveInstanceId as Ae,readSavedApiKey as Ce,readInstanceId as Te}from"./credentials.js";import{KEYCLOAK_BASIS as St,istTestSchluessel as qn,waehleTestSchluessel as Vn,starteKeycloakAnmeldung as Zn,warteAufKeycloakAnmeldung as Xn,uebernimm as Qn,brainImKonto as es,erfolgsText as ts,fehlerText as os,ersetzeSchluessel as ns}from"./uebernahme.js";import{WARTE_TAKT_MS as ss,auftragLiegt as At,nimmAuftrag as is,sichereKonto as rs,sperreLiegt as as,startwissenEingeschaltet as Ct}from"./konto-anlegen.js";import{sichereZugang as cs,echterWert as Ie}from"./zugang.js";import{zeitpunkt as Y}from"./zeitmessung.js";import{autoSitzungsSchritt as ls,SITZUNGS_WERKZEUGE as ds}from"./auto-sitzung.js";import{warteAufLaufendeInstanz as us,gemeinsamerAufbau as ps}from"./instanz-warten.js";import{merkeNeuesBrain as Ye,startetLautLetztemBlick as ms,setzeCommitQuelle as gs}from"./leeres-brain.js";import{starteStartwissen as hs,startwissenGestartet as fs,beanspruchStartwissen as ys,holeStartwissenHinweis as bs,waehleProjektOrdner as ws,startvorratErlaubt as vs,projektCommits as xs}from"./startwissen.js";import{eigeneFassung as _s,pruefeNeueFassung as $s,holeNeueFassungHinweis as ks}from"./neue-fassung.js";import{beiStdinEnde as Ss}from"./stdin-ende.js";import{merkeWerkzeugAufruf as As,starteBrandWachhund as Cs}from"./brand-wachhund.js";import{sichtbareWerkzeuge as Ts,VERTEILER as Tt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as Is}from"./pflichtfelder.js";import{buildLessonsMarkdown as Es,buildLessonsJsonl as Rs,vonRohLektion as js}from"./brain-export.js";import{detectEditor as Bs}from"./editor.js";import{milestoneSent as It,markMilestoneSent as Et}from"./funnel-milestones.js";import{meldeKopf as Ps,meldeRumpf as Ns}from"./melde-weg.js";import{kostprobeUebrig as Os,kostprobeVerbrauchen as Ls,kostprobeHinweis as Hs,kostprobePfadJeInstanz as Ms,schrankeNachKostproben as zs}from"./kostprobe.js";import{netBalance as Ds}from"./ambient-recall.js";import{handleShareTool as Ke}from"./handlers/share.js";import{handleVizTool as Us}from"./handlers/viz.js";import{commitArt as Ws,istRueckbau as Js,zaehleLektionen as Fs}from"./commit-art.js";import{TOOLS as le}from"./tools.js";import{verbindungsWeg as Rt}from"./brains-tls.js";let jt=!1,Bt=!1,Ee=!1;function Pt(){return Bs()}function A(e,t,n){process.env.CACHLY_NO_TELEMETRY!=="1"&&(W()||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:Ps(S),body:JSON.stringify(Ns({event:e,version:H,editor:Pt()},t,n)),signal:AbortSignal.timeout(3e3)}).catch(()=>{}))}function Ys(e,t){return Fn({apiUrl:x,jwt:S,instanceId:e},t)}async function Ks(e){if(!(jt||W())&&process.env.CACHLY_NO_TELEMETRY!=="1"){jt=!0;try{await fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:H,editor:Pt(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const Gs=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"]),qs={causal_trace:"Causal root-cause tracing \u2014 follow the failure chain to the real cause, not just the symptom.",brain_predict:"Predictive risk \u2014 your Brain warns you what will break *before* you run it.",brain_plan:"Generative planning \u2014 turn a goal into an ordered, risk-aware plan from your own history.",brain_predict_failures:"Failure prediction \u2014 catch CI/build breakage before it happens.",team_learn:"Team Brain \u2014 one shared memory across your whole team.",team_confirm:"Team Brain \u2014 peer + senior review that raises lesson trust.",team_recall:"Team Brain \u2014 recall everything your teammates have already solved.",team_synthesize:"Team Brain \u2014 synthesize collective knowledge across authors.",team_crystallize:"Team Brain \u2014 compress your team's wisdom into a shareable crystal.",global_learn:"Team Brain \u2014 contribute to your organization's shared memory.",global_recall:"Team Brain \u2014 recall across your entire organization."},Nt=j("/billing","upgrade"),Ot=new Map;async function Vs(e){const t=Ot.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const o=((await O(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),s={tier:o,isFree:o==="free"||o===""};return Ot.set(e,{info:s,expiresAt:Date.now()+6e4}),s}catch{return{tier:"unknown",isFree:!1}}}async function Zs(e,t){if(!Gs.has(e)||!t)return null;const{isFree:n}=await Vs(t);if(!n)return null;const o=qs[e]??"A Premium intelligence feature.",s=W()?Ms(t):void 0;if(Os(e,s)){const i=Ls(e,s);return{kostprobe:Hs(e,i,Nt)}}return{sperre:zs(e,o,Nt)}}async function Xs(e,t){try{await(await L(e)).hincrby(ro(e),t,1)}catch{}}async function Qs(e,t,n){if(ao(t))try{const o=await L(e),s=uo(n);await o.incrby(co(e),s?lo(n):0),await o.hincrby(Xe(e),"abrufe",1),s&&await o.hincrby(Xe(e),"treffer",1)}catch{}}async function ei(e){const t=await Ao();return t?(G=t,A("device_flow_started",{tool:e}),ce(t.verifyUrl,(n,o)=>{if(n){A("device_browser_opened",{stelle:"tool"});return}A("device_browser_failed",{reason:o??"unknown",stelle:"tool"}),process.stderr.write(`
25
+ \u2022 Technical detail: ${c}`)}return n?_e.set(t,a):ge.set(e,a),Y("verbindung: Valkey verbunden"),a}async function O(e,t={},n=!1){!n&&!W()&&Ze(Pe(S))!=="none"&&await De();const o=we();to(o);const s=Number(process.env.CACHLY_API_TIMEOUT_MS??15e3),i=await fetch(`${x}${e}`,{...t,signal:AbortSignal.timeout(s),headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,...t.headers}});if(!i.ok){if(i.status===401&&!n&&!W()&&(ze=0,await De()))return O(e,t,!0);const a=(await i.json().catch(()=>({error:i.statusText}))).error??i.statusText;oo(i.status,a)}if(i.status!==204)return i.json()}import{handleBrainTool as ln}from"./handlers/brain.js";import{handleContextTool as dn}from"./handlers/context.js";import{handleInstanceTool as un}from"./handlers/instances.js";import{handleCacheTool as pn}from"./handlers/cache.js";import{handleTeamTool as mn}from"./handlers/team.js";import{handleRoadmapTool as gn}from"./handlers/roadmap.js";import{handleAdvancedTool as hn}from"./handlers/advanced.js";import{handleSyndicateTool as fn}from"./handlers/syndicate.js";import{handleFedbrainTool as Je,_lastBrainFromGitCounts as $e}from"./handlers/fedbrain.js";import{extractFirstRecallProof as yn,extractTopHit as bn,fuersTerminal as gt,renderFirstRecallProof as wn}from"./first-recall-proof.js";import{aussetzerLeise as vn}from"./aussetzer.js";import{gitHookOrdner as xn,installClsPostCommitHook as ht,CLS_HOOK_VERSION as ft}from"./cls-hook.js";import{CLAUDE_MD_MARKER_START as _n,CLAUDE_MD_MARKER_END as $n,EDITOR_FILES as ke,ANWEISUNGS_DATEIEN as kn,buildClaudeMdBlock as yt,setzeAnweisungsblock as Sn,sollSchreiben as An,globaleMcpDatei as Se,globalerEditorDa as bt,diesesHeim as he,mcpZiel as wt}from"./projektdateien.js";import{klassiereArgument as Cn,leseFlag as vt,flagsOhneWert as Tn,pruefeInitEingaben as In}from"./cli-argumente.js";import{uninstallBefehl as En}from"./uninstall.js";import{gitLesen as xt}from"./git-ohne-shell.js";import{browserAdresse as Rn,fuerCmd as jn}from"./browser-adresse.js";import{installAmbientHooks as _t,installCursorHooks as Bn,installCopilotHooks as Nn,installCodexHooks as Pn,installGeminiHooks as On,AMBIENT_HOOK_VERSION as $t,COPILOT_HOOKS_DATEI as Ln,CODEX_HOOKS_DATEI as Hn,GEMINI_SETTINGS_DATEI as Mn}from"./ambient-hooks.js";import{hookHauptlauf as zn,auffrischenHauptlauf as Dn,startwissenImportHauptlauf as Un}from"./ambient-hook.js";import{STARTWISSEN_IMPORT as Wn}from"./startwissen-hook.js";import{rahmeAntwort as Jn}from"./antwort-rahmen.js";import{appendLedgerEntry as Fn,readLedger as kt,defaultLedgerPath as Yn,reportLedgerEntry as Kn,teileNachInstanz as Gn}from"./ambient-ledger.js";import{installCodexMcp as qn,installGeminiMcp as Vn}from"./editor-mcp-eintrag.js";import{resolveApiKey as Fe,saveApiKey as ne,saveInstanceId as Ae,readSavedApiKey as Ce,readInstanceId as Te}from"./credentials.js";import{KEYCLOAK_BASIS as St,istTestSchluessel as Zn,waehleTestSchluessel as Xn,starteKeycloakAnmeldung as Qn,warteAufKeycloakAnmeldung as es,uebernimm as ts,brainImKonto as os,erfolgsText as ns,fehlerText as ss,ersetzeSchluessel as is}from"./uebernahme.js";import{WARTE_TAKT_MS as rs,auftragLiegt as At,nimmAuftrag as as,sichereKonto as cs,sperreLiegt as ls,startwissenEingeschaltet as Ct}from"./konto-anlegen.js";import{sichereZugang as ds,echterWert as Ie}from"./zugang.js";import{zeitpunkt as Y}from"./zeitmessung.js";import{autoSitzungsSchritt as us,SITZUNGS_WERKZEUGE as ps}from"./auto-sitzung.js";import{warteAufLaufendeInstanz as ms,gemeinsamerAufbau as gs}from"./instanz-warten.js";import{merkeNeuesBrain as Ye,startetLautLetztemBlick as hs,setzeCommitQuelle as fs}from"./leeres-brain.js";import{starteStartwissen as ys,startwissenGestartet as bs,beanspruchStartwissen as ws,holeStartwissenHinweis as vs,waehleProjektOrdner as xs,startvorratErlaubt as _s,projektCommits as $s}from"./startwissen.js";import{eigeneFassung as ks,pruefeNeueFassung as Ss,holeNeueFassungHinweis as As}from"./neue-fassung.js";import{beiStdinEnde as Cs}from"./stdin-ende.js";import{merkeWerkzeugAufruf as Ts,starteBrandWachhund as Is}from"./brand-wachhund.js";import{sichtbareWerkzeuge as Es,VERTEILER as Tt}from"./werkzeug-auswahl.js";import{fehlendePflichtfelder as Rs}from"./pflichtfelder.js";import{buildLessonsMarkdown as js,buildLessonsJsonl as Bs,vonRohLektion as Ns}from"./brain-export.js";import{detectEditor as Ps}from"./editor.js";import{milestoneSent as It,markMilestoneSent as Et}from"./funnel-milestones.js";import{meldeKopf as Os,meldeRumpf as Ls}from"./melde-weg.js";import{kostprobeUebrig as Hs,kostprobeVerbrauchen as Ms,kostprobeHinweis as zs,kostprobePfadJeInstanz as Ds,schrankeNachKostproben as Us}from"./kostprobe.js";import{netBalance as Ws}from"./ambient-recall.js";import{handleShareTool as Ke}from"./handlers/share.js";import{handleVizTool as Js}from"./handlers/viz.js";import{commitArt as Fs,istRueckbau as Ys,zaehleLektionen as Ks}from"./commit-art.js";import{TOOLS as le}from"./tools.js";import{verbindungsWeg as Rt}from"./brains-tls.js";let jt=!1,Bt=!1,Ee=!1;function Nt(){return Ps()}function A(e,t,n){process.env.CACHLY_NO_TELEMETRY!=="1"&&(W()||fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:Os(S),body:JSON.stringify(Ls({event:e,version:H,editor:Nt()},t,n)),signal:AbortSignal.timeout(3e3)}).catch(()=>{}))}function Gs(e,t){return Kn({apiUrl:x,jwt:S,instanceId:e},t)}async function qs(e){if(!(jt||W())&&process.env.CACHLY_NO_TELEMETRY!=="1"){jt=!0;try{await fetch(`${x}/api/v1/telemetry/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"first_call_no_jwt",version:H,editor:Nt(),tool:e}),signal:AbortSignal.timeout(3e3)})}catch{}}}const Vs=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"]),Zs={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."},Pt=j("/billing","upgrade"),Ot=new Map;async function Xs(e){const t=Ot.get(e);if(t&&t.expiresAt>Date.now())return t.info;try{const o=((await O(`/api/v1/instances/${e}`))?.tier??"free").toLowerCase(),s={tier:o,isFree:o==="free"||o===""};return Ot.set(e,{info:s,expiresAt:Date.now()+6e4}),s}catch{return{tier:"unknown",isFree:!1}}}async function Qs(e,t){if(!Vs.has(e)||!t)return null;const{isFree:n}=await Xs(t);if(!n)return null;const o=Zs[e]??"A Premium intelligence feature.",s=W()?Ds(t):void 0;if(Hs(e,s)){const i=Ms(e,s);return{kostprobe:zs(e,i,Pt)}}return{sperre:Us(e,o,Pt)}}async function ei(e,t){try{await(await L(e)).hincrby(ro(e),t,1)}catch{}}async function ti(e,t,n){if(ao(t))try{const o=await L(e),s=uo(n);await o.incrby(co(e),s?lo(n):0),await o.hincrby(Xe(e),"abrufe",1),s&&await o.hincrby(Xe(e),"treffer",1)}catch{}}async function oi(e){const t=await Ao();return t?(G=t,A("device_flow_started",{tool:e}),ce(t.verifyUrl,(n,o)=>{if(n){A("device_browser_opened",{stelle:"tool"});return}A("device_browser_failed",{reason:o??"unknown",stelle:"tool"}),process.stderr.write(`
26
26
  cachly: could not open a browser (${o??"unknown"}).
27
27
  cachly: open this yourself to finish signing in:
28
28
  cachly: ${t.verifyUrl}
@@ -30,8 +30,8 @@ cachly: code ${t.userCode}
30
30
 
31
31
  `)}),To(t),["\u{1F9E0} **cachly AI Brain \u2014 the user must sign in once.**","","**Show the following link and code to the user verbatim \u2014 they cannot","continue without them.**","",`\u{1F449} **${t.verifyUrl}**`,"",`Code: **${t.userCode}**`,"","A browser may have opened automatically with the code pre-filled. If it","did not, the link above is the whole step.","","Once signed in, the Brain activates on its own \u2014 no further action, no","restart. The next request arrives brain-powered.","",`\u2728 ${le.length} MCP tools \xB7 GDPR \xB7 EU servers \xB7 free tier, no credit card`].join(`
32
32
  `)):["\u{1F9E0} **cachly AI Brain \u2014 Setup required**","","Run the setup wizard once in your terminal:"," ```"," npx @cachly-dev/mcp-server@latest autopilot"," ```","",`Or get your API key at: ${j("/setup-ai","ambient-signin")}`,"","\u2728 Free tier includes: 1 Brain instance, persistent memory, semantic search."].join(`
33
- `)}async function ti(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(W()&&!we())return Ue;if(!we()&&await Me(bo))return J(e,t);if(!we()){if(Ks(e),G){const l=await ut(G);return l==="done"?J(e,t):l==="expired"?(A("device_flow_failed",{reason:"timeout"}),G=null,"\u231B **Authentication timed out.** Please call any tool again to restart the sign-in flow."):["\u23F3 **Signing you in\u2026**","",`Finish in your browser: **${G.verifyUrl}**`,`Code: **${G.userCode}**`,"","This completes automatically once you sign in \u2014 no need to come back here."].join(`
34
- `)}return cs({schluessel:S,konfigurierteInstanz:P,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{Y("sofort-test: Anfang");const l=await rs({apiUrl:x,version:H,fristMs:wo}),m=l.art==="angelegt"?l.test:l.art==="vorhanden"&&l.instanzId?{apiKey:l.apiKey,instanzId:l.instanzId}:null;return Y(`sofort-test: ${m?"Brain angelegt":"kein Test"}`),m&&Ye(m.instanzId,re(),He()),m},ablagen:{setzeSchluessel:l=>{S=l},setEmbedJwt:oe,saveApiKey:l=>ne(l),persistApiKeyToConfig:pe,merkeInstanz:l=>{P=l,Q=0},persistInstanceIdToConfig:me},meldeEreignis:A,werkzeug:()=>J(e,t),anmelden:()=>ei(e),neuesBrain:Le})}if(!t.instance_id){const l=await dt();l&&(t={...t,instance_id:l})}const n=await Zs(e,t.instance_id);let o="";if(n!==null){if("sperre"in n)return A("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;o=n.kostprobe,A("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&Xs(t.instance_id,e),Y(`werkzeug ${e}: Zugang und Tarif geklaert`);const s=await an(e,t,L,O);if(Y(`werkzeug ${e}: Brain-Werkzeug fertig`),s!==null){typeof t.instance_id=="string"&&t.instance_id&&Qs(t.instance_id,e,String(s??"")),!Ee&&S&&(Ee=!0,It("first_call_success")||(Et("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??P??""})));const l=t.instance_id??P??"",m={instance_id:l};if(e==="recall_best_solution")A("recall_best_solution",m);else if(e==="learn_from_attempts")A("learn_from_attempts",m);else if(e==="session_start"){A("session_start",m,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const h=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),C=h.includes("Welcome! Your AI Brain is live.");if(!ms(l)){if(!C&&h.length>100)A("recall_best_solution",m);else if(C&&t.workspace_path&&await ti(l))try{const k=await Je("brain_from_git",{instance_id:l,repo_path:t.workspace_path,limit:50},L,O);if(k!==null){A("brain_from_git",{...m,...$e??{}}),A("recall_best_solution",m);let R="";if(($e?.total??0)===0)try{const M=await Ke("brain_seed_starter",{instance_id:l},L,O);M&&(A("brain_seed_starter",{...m,auto:!0},{seeded_count:16,auto:!0}),R=`
33
+ `)}async function ni(e){if(!e)return!0;if(bs(e))return!1;try{return await ws(await L(e),"sitzungsstart")}catch{return!0}}async function J(e,t){if(W()&&!we())return Ue;if(!we()&&await Me(bo))return J(e,t);if(!we()){if(qs(e),G){const l=await ut(G);return l==="done"?J(e,t):l==="expired"?(A("device_flow_failed",{reason:"timeout"}),G=null,"\u231B **Authentication timed out.** Please call any tool again to restart the sign-in flow."):["\u23F3 **Signing you in\u2026**","",`Finish in your browser: **${G.verifyUrl}**`,`Code: **${G.userCode}**`,"","This completes automatically once you sign in \u2014 no need to come back here."].join(`
34
+ `)}return ds({schluessel:S,konfigurierteInstanz:N,aufrufInstanz:t.instance_id,werkzeugName:e,holeSofortTest:async()=>{Y("sofort-test: Anfang");const l=await cs({apiUrl:x,version:H,fristMs:wo}),m=l.art==="angelegt"?l.test:l.art==="vorhanden"&&l.instanzId?{apiKey:l.apiKey,instanzId:l.instanzId}:null;return Y(`sofort-test: ${m?"Brain angelegt":"kein Test"}`),m&&Ye(m.instanzId,re(),He()),m},ablagen:{setzeSchluessel:l=>{S=l},setEmbedJwt:oe,saveApiKey:l=>ne(l),persistApiKeyToConfig:pe,merkeInstanz:l=>{N=l,Q=0},persistInstanceIdToConfig:me},meldeEreignis:A,werkzeug:()=>J(e,t),anmelden:()=>oi(e),neuesBrain:Le})}if(!t.instance_id){const l=await dt();l&&(t={...t,instance_id:l})}const n=await Qs(e,t.instance_id);let o="";if(n!==null){if("sperre"in n)return A("premium_gate_hit",{tool:e,instance_id:t.instance_id??""}),n.sperre;o=n.kostprobe,A("premium_taste_used",{tool:e,instance_id:t.instance_id??""})}typeof t.instance_id=="string"&&t.instance_id&&ei(t.instance_id,e),Y(`werkzeug ${e}: Zugang und Tarif geklaert`);const s=await ln(e,t,L,O);if(Y(`werkzeug ${e}: Brain-Werkzeug fertig`),s!==null){typeof t.instance_id=="string"&&t.instance_id&&ti(t.instance_id,e,String(s??"")),!Ee&&S&&(Ee=!0,It("first_call_success")||(Et("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""})));const l=t.instance_id??N??"",m={instance_id:l};if(e==="recall_best_solution")A("recall_best_solution",m);else if(e==="learn_from_attempts")A("learn_from_attempts",m);else if(e==="session_start"){A("session_start",m,{born_at:void 0,recalls_total:void 0,starter_seeded:!1});const h=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),C=h.includes("Welcome! Your AI Brain is live.");if(!hs(l)){if(!C&&h.length>100)A("recall_best_solution",m);else if(C&&t.workspace_path&&await ni(l))try{const k=await Je("brain_from_git",{instance_id:l,repo_path:t.workspace_path,limit:50},L,O);if(k!==null){A("brain_from_git",{...m,...$e??{}}),A("recall_best_solution",m);let R="";if(($e?.total??0)===0)try{const M=await Ke("brain_seed_starter",{instance_id:l},L,O);M&&(A("brain_seed_starter",{...m,auto:!0},{seeded_count:16,auto:!0}),R=`
35
35
  ---
36
36
  `+String(M))}catch{}const I=String(k),$=$e?.total??0,E=$>0?`
37
37
  \u2705 **Brain bootstrapped from git \u2014 ${$} lesson${$===1?"":"s"} loaded.** Your AI already knows your history.`:"";if(I||R||E)return String(s)+E+`
@@ -42,16 +42,16 @@ cachly: code ${t.userCode}
42
42
  > Run \`brain_from_git(instance_id="`+l+'", repo_path="'+String(t.workspace_path)+'")` manually to seed it.\n> Or try `brain_seed_starter` to load 16 universal engineering lessons instantly.'}}}else if(e==="session_end")A("session_end",m);else if(e==="smart_recall"){const h=typeof s=="object"&&s!==null&&"content"in s?JSON.stringify(s):String(s??""),C=h.length>50&&!h.includes("No lessons found")&&!h.includes("no lessons")&&!h.includes("No matches found");if(A("smart_recall",m,{hit:C,topic:String(t.query??"").slice(0,80)}),C&&A("recall_best_solution",m),ae&&typeof s=="string")return`> \u26A0\uFE0F **Brain auth degraded** \u2014 ${ae.split(`
43
43
  `)[0]}
44
44
 
45
- ${s}`}return s}const i=await cn(e,t,L,O);if(i!==null)return!Ee&&S&&(Ee=!0,It("first_call_success")||(Et("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??P??""}))),i;const r=await ln(e,t,L,O);if(r!==null)return r;const a=await dn(e,t,L,O);if(a!==null)return a;const u=l=>o?l+o:l,p=await un(e,t,L,O);if(p!==null)return u(p);const c=await pn(e,t,L,O);if(c!==null)return c;const d=await mn(e,t,L,O);if(d!==null)return u(d);const f=await gn(e,t,L,O);if(f!==null){if(e==="brain_predict"){const m={instance_id:t.instance_id??P??""};A("brain_predict",m)}return u(f)}const y=await Ke(e,t,L,O);if(y!==null)return y;const w=await Us(e,t,L,O);if(w!==null)return w;const g=await Je(e,t,L,O);if(g!==null){const m={instance_id:t.instance_id??P??""};if(e==="brain_from_git"){const h=$e;A("brain_from_git",{...m,...h??{}},h?{fixes:h.fixes,features:h.features,refactors:h.refactors,total:h.total}:void 0)}else e==="brain_predict_failures"&&A("brain_predict_failures",m);return g}switch(e){case"get_api_status":{let l="unknown";try{const k=await fetch(`${x}/health`,{signal:AbortSignal.timeout(8e3)});if(k.ok){const _=await k.json();l=`${_.status??"ok"} (db: ${_.db??"?"})`}else l=`HTTP ${k.status}`}catch(k){l=`unreachable: ${k.message}`}if(!S)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${x}`,` \u{1F493} Health: ${l}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${j("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
45
+ ${s}`}return s}const i=await dn(e,t,L,O);if(i!==null)return!Ee&&S&&(Ee=!0,It("first_call_success")||(Et("first_call_success"),A("first_call_success",{tool:e,instance_id:t.instance_id??N??""}))),i;const r=await un(e,t,L,O);if(r!==null)return r;const a=await pn(e,t,L,O);if(a!==null)return a;const u=l=>o?l+o:l,p=await mn(e,t,L,O);if(p!==null)return u(p);const c=await gn(e,t,L,O);if(c!==null)return c;const d=await hn(e,t,L,O);if(d!==null)return u(d);const f=await fn(e,t,L,O);if(f!==null){if(e==="brain_predict"){const m={instance_id:t.instance_id??N??""};A("brain_predict",m)}return u(f)}const y=await Ke(e,t,L,O);if(y!==null)return y;const w=await Js(e,t,L,O);if(w!==null)return w;const g=await Je(e,t,L,O);if(g!==null){const m={instance_id:t.instance_id??N??""};if(e==="brain_from_git"){const h=$e;A("brain_from_git",{...m,...h??{}},h?{fixes:h.fixes,features:h.features,refactors:h.refactors,total:h.total}:void 0)}else e==="brain_predict_failures"&&A("brain_predict_failures",m);return g}switch(e){case"get_api_status":{let l="unknown";try{const k=await fetch(`${x}/health`,{signal:AbortSignal.timeout(8e3)});if(k.ok){const _=await k.json();l=`${_.status??"ok"} (db: ${_.db??"?"})`}else l=`HTTP ${k.status}`}catch(k){l=`unreachable: ${k.message}`}if(!S)return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${x}`,` \u{1F493} Health: ${l}`," \u{1F511} Auth: \u274C CACHLY_JWT not set","",`\u{1F4A1} Get your API token at ${j("/instances","api-status")} \u2192 Settings \u2192 API Token`].join(`
46
46
  `);let m="\u274C invalid JWT format";try{const k=S.split(".");if(k.length===3){const _=JSON.parse(Buffer.from(k[1],"base64url").toString("utf-8")),R=_.sub??"(unknown)",I=_.iss??"(unknown)",$=I.includes("keycloak")?"Keycloak":"OIDC",E=_.exp?new Date(_.exp*1e3):null,M=E?E<new Date:!1;m=["\u2705 JWT decoded",` Sub (user ID): ${R}`,` Provider: ${$}`,` Issuer: ${I}`,` Expires: ${E?E.toISOString():"never"} ${M?"\u26A0\uFE0F EXPIRED \u2013 get a new token!":"\u2705"}`].join(`
47
47
  `)}}catch{m="\u274C JWT decode failed \u2013 check CACHLY_JWT format"}let h="";try{const _=(await O("/api/v1/instances")).data??[];if(_.length===0)h=`
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===P?" \u2190 active":"";if(R.push(` ${$} **${I.name}** (\`${I.id}\`) \xB7 ${I.status}${E}`),I.status==="running"&&I.host){const M=ge.get(I.id);if(M)try{await M.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})`)}h=R.join(`
51
+ \u{1F9E0} **Brain Instances:**`];for(const I of _){const $=I.status==="running"?"\u{1F7E2}":I.status==="provisioning"?"\u{1F7E1}":"\u{1F534}",E=I.id===N?" \u2190 active":"";if(R.push(` ${$} **${I.name}** (\`${I.id}\`) \xB7 ${I.status}${E}`),I.status==="running"&&I.host){const M=ge.get(I.id);if(M)try{await M.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})`)}h=R.join(`
52
52
  `)}}catch(k){h=`
53
53
 
54
- \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${k.message}`}await De();const C=Ne(S),v=C.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":C.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${C.expiresInMs?` (${Math.round(C.expiresInMs/36e5)}h left)`:""}`:C.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${C.message.split(`
54
+ \u{1F9E0} **Brain Instances:** could not fetch \u2014 ${k.message}`}await De();const C=Pe(S),v=C.state==="long_lived"?"\u{1F6E1}\uFE0F Self-healing: \u2705 long-lived API key (won't expire silently)":C.state==="healthy"?`\u{1F6E1}\uFE0F Self-healing: \u2705 token valid${C.expiresInMs?` (${Math.round(C.expiresInMs/36e5)}h left)`:""}`:C.state==="near_expiry"?"\u{1F6E1}\uFE0F Self-healing: \u267B\uFE0F token near expiry \u2014 auto-refresh attempted":`\u{1F6E1}\uFE0F Self-healing: \u26A0\uFE0F ${C.message.split(`
55
55
  `)[0]}`;return["\u{1F4E1} **cachly API Status**","",` \u{1F310} API: ${x}`,` \u{1F493} Health: ${l}`,` ${v}`,"","\u{1F511} **Auth:**",m,h].join(`
56
56
  `)}default:throw new Lt(`Unknown tool: ${e}`)}}class Lt extends Error{}const Ht=`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
 
@@ -63,10 +63,10 @@ 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.`,Mt={tools:{},resources:{},prompts:{}},zt=async()=>{const{katalog:e,unbekannteKernnamen:t}=Ts(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function Dt(){return{resources:[]}}async function Ut(){return{resourceTemplates:[]}}async function Wt(){return{prompts:[]}}function oi(e){e.setRequestHandler(rt,zt),e.setRequestHandler(ot,Kt),e.setRequestHandler(it,Dt),e.setRequestHandler(st,Ut),e.setRequestHandler(nt,Wt)}function ni(){const e=new tt({name:"cachly-mcp",version:H},{capabilities:Mt,instructions:Ht});return oi(e),Jt(e),e}function Jt(e){const t=e.oninitialized;e.oninitialized=()=>{let n;try{n=e.getClientVersion(),Qt(n?.name,n?.version)}catch{}Bt||(Bt=!0,A("mcp_verbunden",{client:String(n?.name??"unbekannt").slice(0,60),client_version:String(n?.version??"").slice(0,30)})),t?.()}}const q=new tt({name:"cachly-mcp",version:H},{capabilities:Mt,instructions:Ht});Jt(q),q.setRequestHandler(rt,zt),q.setRequestHandler(it,Dt),q.setRequestHandler(st,Ut),q.setRequestHandler(nt,Wt);let Re=null,de=!1,se=null,Ft=0;async function si(e){if(!de){if(se){await se;return}se=(async()=>{de=!0,Re=e;try{await J("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{se=null}})(),await se,Yt(e)}}function ii(e){de=!0,Re=e}function Yt(e){process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await L(e),n=await t.get(`cachly:index:last_indexed:${e}`),o=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>o)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),await J("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code",hintergrund:!0}))})().catch(()=>{})}async function Ge(){if(!(!de||!Re)){de=!1;try{await J("session_end",{instance_id:Re,summary:`Auto-ended after ${Ft} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Kt=async e=>{let{name:t,arguments:n}=e.params;if(t===Tt){const i=n??{},r=typeof i.tool=="string"?i.tool:"";if(!r)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const a=le.find(u=>u.name===r);if(!a)return{content:[{type:"text",text:`Kein Werkzeug namens "${r}". Die Liste steht in der Beschreibung von ${Tt}.`}],isError:!0};if(i.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:a.name,description:a.description,inputSchema:a.inputSchema},null,2)}]};t=r,n=i.arguments??{}}if(W()){const i=xe();if(!i)return{content:[{type:"text",text:Ue}],isError:!0};if(!Do(t))return{content:[{type:"text",text:Uo(t)}],isError:!0};const r=Wo(n??{},i.instanzId);if("fehler"in r)return{content:[{type:"text",text:r.fehler}],isError:!0};n=r.args}if(!["learn_from_attempts","smart_recall","recall_feedback"].includes(t)){const i=le.find(a=>a.name===t),r=i?Is(t,i.inputSchema,n??{}):null;if(r)return{content:[{type:"text",text:r}],isError:!0}}const o=Ie(n?.instance_id)||P||Ie(process.env.CACHLY_BRAIN_INSTANCE_ID)||"",s=W()?"nichts":ls(t,{gestartet:de,startetGerade:se!==null,instanz:o});s==="starten"?await si(o).catch(()=>{}):s==="abwarten"?await se?.catch(()=>{}):s==="als-gestartet-merken"&&ii(o),!W()&&!ds.has(t)&&Ft++;try{As(),Y(`werkzeug ${t}: Anfang`);const i=await J(t,n??{});return Y(`werkzeug ${t}: Antwort fertig`),s==="als-gestartet-merken"&&Yt(o),{content:[{type:"text",text:Un(t,i)+bs()+ks(t)}]}}catch(i){if(i instanceof Lt)return{content:[{type:"text",text:i.message}],isError:!0};if(i instanceof Z)throw i;const r=i.message??String(i);throw Qe("cachly","tool_error",{tool:t,error:r}).catch(()=>{}),new Z(te.InternalError,r)}};q.setRequestHandler(ot,Kt),process.on("SIGTERM",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("unhandledRejection",e=>{const t=e instanceof Error?e.message:String(e);process.stderr.write(`[cachly-mcp] unhandledRejection: ${t}
66
+ session_start gives a briefing at the start of a session; it does not replace smart_recall for a concrete task.`,Mt={tools:{},resources:{},prompts:{}},zt=async()=>{const{katalog:e,unbekannteKernnamen:t}=Es(le);return t.length>0&&console.error(`cachly: ${t.length} Kernwerkzeug(e) gibt es gar nicht: ${t.join(", ")}`),{tools:e}};async function Dt(){return{resources:[]}}async function Ut(){return{resourceTemplates:[]}}async function Wt(){return{prompts:[]}}function si(e){e.setRequestHandler(rt,zt),e.setRequestHandler(ot,Kt),e.setRequestHandler(it,Dt),e.setRequestHandler(st,Ut),e.setRequestHandler(nt,Wt)}function ii(){const e=new tt({name:"cachly-mcp",version:H},{capabilities:Mt,instructions:Ht});return si(e),Jt(e),e}function Jt(e){const t=e.oninitialized;e.oninitialized=()=>{let n;try{n=e.getClientVersion(),Qt(n?.name,n?.version)}catch{}Bt||(Bt=!0,A("mcp_verbunden",{client:String(n?.name??"unbekannt").slice(0,60),client_version:String(n?.version??"").slice(0,30)})),t?.()}}const q=new tt({name:"cachly-mcp",version:H},{capabilities:Mt,instructions:Ht});Jt(q),q.setRequestHandler(rt,zt),q.setRequestHandler(it,Dt),q.setRequestHandler(st,Ut),q.setRequestHandler(nt,Wt);let Re=null,de=!1,se=null,Ft=0;async function ri(e){if(!de){if(se){await se;return}se=(async()=>{de=!0,Re=e;try{await J("session_start",{instance_id:e,focus:"auto (MCP session)",workspace_path:process.cwd()})}catch{}finally{se=null}})(),await se,Yt(e)}}function ai(e){de=!0,Re=e}function Yt(e){process.env.CACHLY_AUTO_INDEX!=="false"&&(async()=>{const t=await L(e),n=await t.get(`cachly:index:last_indexed:${e}`),o=1440*60*1e3;(!n||Date.now()-parseInt(n,10)>o)&&(await t.set(`cachly:index:last_indexed:${e}`,String(Date.now()),"EX",9e4),await J("index_project",{instance_id:e,dir:process.cwd(),max_files:150,ttl:86400*7,namespace:"cachly:sem:code",hintergrund:!0}))})().catch(()=>{})}async function Ge(){if(!(!de||!Re)){de=!1;try{await J("session_end",{instance_id:Re,summary:`Auto-ended after ${Ft} tool call(s). Session was started automatically.`,files_changed:[],lessons_learned:0})}catch{}}}const Kt=async e=>{let{name:t,arguments:n}=e.params;if(t===Tt){const i=n??{},r=typeof i.tool=="string"?i.tool:"";if(!r)return{content:[{type:"text",text:'cachly_tool braucht das Feld "tool" \u2014 den Namen des Werkzeugs.'}],isError:!0};const a=le.find(u=>u.name===r);if(!a)return{content:[{type:"text",text:`Kein Werkzeug namens "${r}". Die Liste steht in der Beschreibung von ${Tt}.`}],isError:!0};if(i.describe===!0)return{content:[{type:"text",text:JSON.stringify({name:a.name,description:a.description,inputSchema:a.inputSchema},null,2)}]};t=r,n=i.arguments??{}}if(W()){const i=xe();if(!i)return{content:[{type:"text",text:Ue}],isError:!0};if(!Wo(t))return{content:[{type:"text",text:Jo(t)}],isError:!0};const r=Fo(n??{},i.instanzId);if("fehler"in r)return{content:[{type:"text",text:r.fehler}],isError:!0};n=r.args}if(!["learn_from_attempts","smart_recall","recall_feedback"].includes(t)){const i=le.find(a=>a.name===t),r=i?Rs(t,i.inputSchema,n??{}):null;if(r)return{content:[{type:"text",text:r}],isError:!0}}const o=Ie(n?.instance_id)||N||Ie(process.env.CACHLY_BRAIN_INSTANCE_ID)||"",s=W()?"nichts":us(t,{gestartet:de,startetGerade:se!==null,instanz:o});s==="starten"?await ri(o).catch(()=>{}):s==="abwarten"?await se?.catch(()=>{}):s==="als-gestartet-merken"&&ai(o),!W()&&!ps.has(t)&&Ft++;try{Ts(),Y(`werkzeug ${t}: Anfang`);const i=await J(t,n??{});return Y(`werkzeug ${t}: Antwort fertig`),s==="als-gestartet-merken"&&Yt(o),{content:[{type:"text",text:Jn(t,i)+vs()+As(t)}]}}catch(i){if(i instanceof Lt)return{content:[{type:"text",text:i.message}],isError:!0};if(i instanceof Z)throw i;const r=i.message??String(i);throw Qe("cachly","tool_error",{tool:t,error:r}).catch(()=>{}),new Z(te.InternalError,r)}};q.setRequestHandler(ot,Kt),process.on("SIGTERM",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("SIGINT",async()=>{await Ge().catch(()=>{});for(const e of We())await e.quit().catch(()=>{});process.exit(0)}),process.on("unhandledRejection",e=>{const t=e instanceof Error?e.message:String(e);process.stderr.write(`[cachly-mcp] unhandledRejection: ${t}
67
67
  `)}),process.on("uncaughtException",e=>{process.stderr.write(`[cachly-mcp] uncaughtException: ${e?.stack??String(e)}
68
- `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function ri(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 Gt="https://api.cachly.dev";function ee(e,t,n={}){const o={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(o.CACHLY_JWT=e),x&&x!==Gt&&(o.CACHLY_API_URL=x),o}function ai(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):qt(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 qt(e){return ke[e]===".vscode/mcp.json"}function fe(e,t){qn(e)||ne(e,t)}async function Vt(e,t,n,o,s,i={}){const r={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(t,n)};if(!s.existsSync(e))return ai(t,n,o);let a={};try{a=JSON.parse(await s.readFile(e,"utf-8"))}catch{try{const{rename:d}=await import("node:fs/promises");await d(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
69
- `)}catch{}}if(o==="continue"){const d=a.experimental??{},f=d.modelContextProtocolServers??[];let y;for(const g of f){const l=g.env??{};if(l.CACHLY_JWT){y=l.CACHLY_JWT;break}}y&&fe(y,i);const w=f.filter(g=>{const l=g.env??{};return!l.CACHLY_JWT&&!l.CACHLY_BRAIN_INSTANCE_ID});return w.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:r.env}),a.experimental={...d,modelContextProtocolServers:w},JSON.stringify(a,null,2)}if(o==="zed"){const d=a.context_servers??{},y=d.cachly?.command?.env?.CACHLY_JWT;return y&&fe(y,i),d.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:r.env},settings:{}},a.context_servers=d,JSON.stringify(a,null,2)}if(qt(o)){const d=a.mcpServers??void 0,y=d?.cachly?.env?.CACHLY_JWT;y&&fe(y,i),d&&"cachly"in d&&(delete d.cachly,Object.keys(d).length===0&&delete a.mcpServers);const w=a.servers??{},g=w.cachly,l=g?.env?.CACHLY_JWT;return l&&fe(l,i),w.cachly=g?.envFile?{type:"stdio",...r,envFile:g.envFile}:{type:"stdio",...r},a.servers=w,JSON.stringify(a,null,2)}const u=a.mcpServers??{},c=u.cachly?.env?.CACHLY_JWT;return c&&fe(c,i),u.cachly=r,a.mcpServers=u,JSON.stringify(a,null,2)}async function Zt(e,t,n,o){const{existsSync:s}=await import("node:fs"),{resolve:i}=await import("node:path"),{homedir:r}=await import("node:os"),a=n??r(),u=_n.filter(d=>kn(d,e,a,s,i,o)).map(d=>({path:i(e,...d.pfad),prefix:d.prefix})),p=yt(t),c={};for(const{path:d,prefix:f}of u)try{c[d]=await $n(d,p,f)}catch(y){c[d]=`failed:${y.message}`}return c}function Xt(e,t){return t.startsWith("failed:")?`\u26A0\uFE0F Could not write ${e}: ${t.slice(7)} (the rest of the setup continues)`:t==="unchanged"?`\u2713 Unchanged: ${e}`:`${t==="updated"?"\u2705 Updated":t==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${e}`}if(process.argv[2]==="digest"){const e=X(),t=U();(!e||!t)&&(console.log(`
68
+ `)}),process.stdout.on("error",()=>{}),process.stdin.on("error",()=>{});function ci(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 Gt="https://api.cachly.dev";function ee(e,t,n={}){const o={CACHLY_BRAIN_INSTANCE_ID:t};return n.includeApiKey&&(o.CACHLY_JWT=e),x&&x!==Gt&&(o.CACHLY_API_URL=x),o}function li(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):qt(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 qt(e){return ke[e]===".vscode/mcp.json"}function fe(e,t){Zn(e)||ne(e,t)}async function Vt(e,t,n,o,s,i={}){const r={command:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:ee(t,n)};if(!s.existsSync(e))return li(t,n,o);let a={};try{a=JSON.parse(await s.readFile(e,"utf-8"))}catch{try{const{rename:d}=await import("node:fs/promises");await d(e,e+".bak"),process.stderr.write(`\u26A0\uFE0F ${e} was not valid JSON \u2014 backed up to ${e}.bak
69
+ `)}catch{}}if(o==="continue"){const d=a.experimental??{},f=d.modelContextProtocolServers??[];let y;for(const g of f){const l=g.env??{};if(l.CACHLY_JWT){y=l.CACHLY_JWT;break}}y&&fe(y,i);const w=f.filter(g=>{const l=g.env??{};return!l.CACHLY_JWT&&!l.CACHLY_BRAIN_INSTANCE_ID});return w.push({transport:{type:"stdio",command:"npx",args:["-y","@cachly-dev/mcp-server@latest"]},env:r.env}),a.experimental={...d,modelContextProtocolServers:w},JSON.stringify(a,null,2)}if(o==="zed"){const d=a.context_servers??{},y=d.cachly?.command?.env?.CACHLY_JWT;return y&&fe(y,i),d.cachly={command:{path:"npx",args:["-y","@cachly-dev/mcp-server@latest"],env:r.env},settings:{}},a.context_servers=d,JSON.stringify(a,null,2)}if(qt(o)){const d=a.mcpServers??void 0,y=d?.cachly?.env?.CACHLY_JWT;y&&fe(y,i),d&&"cachly"in d&&(delete d.cachly,Object.keys(d).length===0&&delete a.mcpServers);const w=a.servers??{},g=w.cachly,l=g?.env?.CACHLY_JWT;return l&&fe(l,i),w.cachly=g?.envFile?{type:"stdio",...r,envFile:g.envFile}:{type:"stdio",...r},a.servers=w,JSON.stringify(a,null,2)}const u=a.mcpServers??{},c=u.cachly?.env?.CACHLY_JWT;return c&&fe(c,i),u.cachly=r,a.mcpServers=u,JSON.stringify(a,null,2)}async function Zt(e,t,n,o){const{existsSync:s}=await import("node:fs"),{resolve:i}=await import("node:path"),{homedir:r}=await import("node:os"),a=n??r(),u=kn.filter(d=>An(d,e,a,s,i,o)).map(d=>({path:i(e,...d.pfad),prefix:d.prefix})),p=yt(t),c={};for(const{path:d,prefix:f}of u)try{c[d]=await Sn(d,p,f)}catch(y){c[d]=`failed:${y.message}`}return c}function Xt(e,t){return t.startsWith("failed:")?`\u26A0\uFE0F Could not write ${e}: ${t.slice(7)} (the rest of the setup continues)`:t==="unchanged"?`\u2713 Unchanged: ${e}`:`${t==="updated"?"\u2705 Updated":t==="appended"?"\u2705 Appended to":"\u2705 Written"}: ${e}`}if(process.argv[2]==="digest"){const e=X(),t=U();(!e||!t)&&(console.log(`
70
70
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot
71
71
  `),process.exit(1)),process.stdout.write(`
72
72
  \u{1F9E0} Fetching your weekly Brain digest...
@@ -82,8 +82,8 @@ session_start gives a briefing at the start of a session; it does not replace sm
82
82
  `),process.exit(1)),process.stdout.write(`
83
83
  \u{1F4E4} Exporting your Brain...
84
84
 
85
- `);try{let p=[],c="";const d=await fetch(`${x}/api/v1/instances/${u}/export`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(12e4)});if(d.ok){const y=await d.json();p=(y.lessons??[]).map(js).filter(w=>w!==null),y.complete===!1?c=y.note??"the server reported an incomplete read":typeof y.lesson_count=="number"&&p.length<y.lesson_count&&(c=`the server counts ${y.lesson_count} lessons, but only ${p.length} could be read as lessons`)}else if(d.status===404){const y=await fetch(`${x}/api/v1/instances/${u}/memory`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(8e3)});if(!y.ok)throw new Error(`memory HTTP ${y.status}`);p=((await y.json()).top_lessons??[]).map(g=>({topic:g.topic,outcome:g.outcome,severity:g.severity,tags:g.tags,whatWorked:g.what_worked,ts:g.ts,author:g.author,recallCount:g.recall_count})),c="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 ${d.status}`);p.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
86
- `),process.exit(0)),await t(r,{recursive:!0});const f=[];if(i==="md"||i==="both"){const y=n(r,"lessons.md");await e(y,Es(p),"utf-8"),f.push(`${p.length} lesson${p.length===1?"":"s"} \u2192 ${y}`)}if(i==="jsonl"||i==="both"){const y=n(r,"lessons.jsonl");await e(y,Rs(p),"utf-8"),f.push(`${p.length} lesson${p.length===1?"":"s"} \u2192 ${y}`)}c?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${c}`),console.log("")):console.log("\u2705 Export complete:");for(const y of f)console.log(` ${y}`);console.log("")}catch(p){console.log(`
85
+ `);try{let p=[],c="";const d=await fetch(`${x}/api/v1/instances/${u}/export`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(12e4)});if(d.ok){const y=await d.json();p=(y.lessons??[]).map(Ns).filter(w=>w!==null),y.complete===!1?c=y.note??"the server reported an incomplete read":typeof y.lesson_count=="number"&&p.length<y.lesson_count&&(c=`the server counts ${y.lesson_count} lessons, but only ${p.length} could be read as lessons`)}else if(d.status===404){const y=await fetch(`${x}/api/v1/instances/${u}/memory`,{headers:{Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(8e3)});if(!y.ok)throw new Error(`memory HTTP ${y.status}`);p=((await y.json()).top_lessons??[]).map(g=>({topic:g.topic,outcome:g.outcome,severity:g.severity,tags:g.tags,whatWorked:g.what_worked,ts:g.ts,author:g.author,recallCount:g.recall_count})),c="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 ${d.status}`);p.length===0&&(console.log(` No lessons in this Brain yet \u2014 nothing to export.
86
+ `),process.exit(0)),await t(r,{recursive:!0});const f=[];if(i==="md"||i==="both"){const y=n(r,"lessons.md");await e(y,js(p),"utf-8"),f.push(`${p.length} lesson${p.length===1?"":"s"} \u2192 ${y}`)}if(i==="jsonl"||i==="both"){const y=n(r,"lessons.jsonl");await e(y,Bs(p),"utf-8"),f.push(`${p.length} lesson${p.length===1?"":"s"} \u2192 ${y}`)}c?(console.log("\u26A0\uFE0F Export INCOMPLETE \u2014 this is not your whole Brain:"),console.log(` ${c}`),console.log("")):console.log("\u2705 Export complete:");for(const y of f)console.log(` ${y}`);console.log("")}catch(p){console.log(`
87
87
  \u274C Could not export your Brain: ${p.message}
88
88
  `),process.exit(1)}process.exit(0)}if(process.argv[2]==="invite"){const e=X(),t=(process.argv[3]??"").trim();(!t||t.startsWith("-"))&&(console.log(`
89
89
  Usage: npx @cachly-dev/mcp-server@latest invite <email>`),console.log(" Example: npx @cachly-dev/mcp-server@latest invite teammate@example.com"),console.log(` Your referral link: npx @cachly-dev/mcp-server@latest refer
@@ -162,8 +162,8 @@ Try it free: ${o}
162
162
  `),console.log(` Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo
163
163
  `),process.exit(0));let i="";try{i=xt(s,["config","user.name"]).trim().split(" ")[0]??""}catch{}let r=o(s);try{const $=JSON.parse(t(n(s,"package.json"),"utf-8"));$.name&&(r=$.name.replace(/^@[^/]+\//,""))}catch{}let a="";try{a=xt(s,["log","HEAD","--pretty=format:%H|||%s|||%ad|||%an","--date=short","--no-merges","-n","200"],{timeoutMs:3e4})}catch{console.log(`\u26A0\uFE0F Could not read git log. Make sure you have commits.
164
164
  `),process.exit(0)}const u=a.trim().split(`
165
- `).filter(Boolean).map($=>{const[E,M,Pe,ie]=$.split("|||");return{sha:(E??"").trim().slice(0,8),subject:(M??"").trim(),date:(Pe??"").trim(),author:(ie??"").trim()}});u.length===0&&(console.log(`\u26A0\uFE0F No commits found.
166
- `),process.exit(0));const p=new Map,c=[],d=[],f=[],y=new Set;let w=0;for(const $ of u){const E=Ws($.subject);p.set(E,(p.get(E)??0)+1),Js($.subject)&&w++,E==="fix"&&c.length<5&&c.push($.subject.slice(0,72)),E==="feat"&&d.length<5&&d.push($.subject.slice(0,72)),E==="security"&&f.length<3&&f.push($.subject.slice(0,72)),$.author&&y.add($.author)}const g=Fs(u.map($=>$.subject)),l=`${u[u.length-1]?.date??"?"} \u2192 ${u[0]?.date??"?"}`,m=g>=501?"Oracle":g>=201?"Architect":g>=51?"Expert":g>=11?"Explorer":"Apprentice",C=`${i?`Hey ${i} \u2014 `:""}here's what your AI would know about ${r}`;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} ${C.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${l.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(g).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(y.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${m.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(w).padEnd(21)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const v=[...p.entries()].filter(([$])=>$!=="chore").sort(($,E)=>E[1]-$[1]),k=($,E)=>"\u2588".repeat(Math.round($/E*20)).padEnd(20),_=Math.max(...v.map(([,$])=>$),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[$,E]of v){const M={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[$]??"\u2022";console.log(`\u2502 ${M} \x1B[36m${$.padEnd(10)}\x1B[0m \x1B[35m${k(E,_)}\x1B[0m \x1B[33m${String(E).padStart(3)}\x1B[0m \u2502`)}if(f.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[31m\u{1F512} Security fixes your AI would know:\x1B[0m \u2502");for(const $ of f)console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(c.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F527} Bug fixes your AI would never repeat:\x1B[0m \u2502");for(const $ of c.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(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[32m\u2728 Features & decisions it would recall:\x1B[0m \u2502");for(const $ of d.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:r,commits:String(u.length),lessons:String(g),level:m,authors:String(y.size),reverts:String(w)}),I=j(`/preview?${R.toString()}`,"demo");console.log(" \x1B[1mMake this permanent (free, 1\u20135 minutes):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(""),console.log(` \x1B[90m\u{1F517} Shareable preview:\x1B[0m \x1B[36m${I}\x1B[0m`),console.log(""),console.log(" Works with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 Copilot \xB7 Cline \xB7 Zed"),console.log(" GDPR \xB7 German servers \xB7 free tier, no credit card"),console.log(""),process.exit(0)}if(process.argv[2]==="share"){const e=X(),t=U();(!e||!t)&&(console.log(`
165
+ `).filter(Boolean).map($=>{const[E,M,Ne,ie]=$.split("|||");return{sha:(E??"").trim().slice(0,8),subject:(M??"").trim(),date:(Ne??"").trim(),author:(ie??"").trim()}});u.length===0&&(console.log(`\u26A0\uFE0F No commits found.
166
+ `),process.exit(0));const p=new Map,c=[],d=[],f=[],y=new Set;let w=0;for(const $ of u){const E=Fs($.subject);p.set(E,(p.get(E)??0)+1),Ys($.subject)&&w++,E==="fix"&&c.length<5&&c.push($.subject.slice(0,72)),E==="feat"&&d.length<5&&d.push($.subject.slice(0,72)),E==="security"&&f.length<3&&f.push($.subject.slice(0,72)),$.author&&y.add($.author)}const g=Ks(u.map($=>$.subject)),l=`${u[u.length-1]?.date??"?"} \u2192 ${u[0]?.date??"?"}`,m=g>=501?"Oracle":g>=201?"Architect":g>=51?"Expert":g>=11?"Explorer":"Apprentice",C=`${i?`Hey ${i} \u2014 `:""}here's what your AI would know about ${r}`;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} ${C.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${l.slice(0,23).padEnd(23)}\x1B[0m \u2502`),console.log(`\u2502 Lessons extracted: \x1B[32m${String(g).padEnd(6)}\x1B[0m Contributors: \x1B[36m${String(y.size).padEnd(20)}\x1B[0m\u2502`),console.log(`\u2502 Brain Level : \x1B[35m${m.padEnd(10)}\x1B[0m Reverts: \x1B[33m${String(w).padEnd(21)}\x1B[0m\u2502`),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const v=[...p.entries()].filter(([$])=>$!=="chore").sort(($,E)=>E[1]-$[1]),k=($,E)=>"\u2588".repeat(Math.round($/E*20)).padEnd(20),_=Math.max(...v.map(([,$])=>$),1);console.log("\u2502 \x1B[90mCategory breakdown:\x1B[0m \u2502");for(const[$,E]of v){const M={fix:"\u{1F527}",feat:"\u2728",perf:"\u26A1",security:"\u{1F512}",deploy:"\u{1F680}",refactor:"\u{1F504}"}[$]??"\u2022";console.log(`\u2502 ${M} \x1B[36m${$.padEnd(10)}\x1B[0m \x1B[35m${k(E,_)}\x1B[0m \x1B[33m${String(E).padStart(3)}\x1B[0m \u2502`)}if(f.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[31m\u{1F512} Security fixes your AI would know:\x1B[0m \u2502");for(const $ of f)console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(c.length>0){console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log("\u2502 \x1B[33m\u{1F527} Bug fixes your AI would never repeat:\x1B[0m \u2502");for(const $ of c.slice(0,4))console.log(`\u2502 \x1B[90m\u2022 ${$.slice(0,58).padEnd(58)}\x1B[0m \u2502`)}if(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[32m\u2728 Features & decisions it would recall:\x1B[0m \u2502");for(const $ of d.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:r,commits:String(u.length),lessons:String(g),level:m,authors:String(y.size),reverts:String(w)}),I=j(`/preview?${R.toString()}`,"demo");console.log(" \x1B[1mMake this permanent (free, 1\u20135 minutes):\x1B[0m"),console.log(" \x1B[32m$ npx @cachly-dev/mcp-server@latest autopilot\x1B[0m"),console.log(""),console.log(` \x1B[90m\u{1F517} Shareable preview:\x1B[0m \x1B[36m${I}\x1B[0m`),console.log(""),console.log(" Works with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 Copilot \xB7 Cline \xB7 Zed"),console.log(" GDPR \xB7 German servers \xB7 free tier, no credit card"),console.log(""),process.exit(0)}if(process.argv[2]==="share"){const e=X(),t=U();(!e||!t)&&(console.log(`
167
167
  \u26A0\uFE0F No cachly key or Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
168
168
  `),process.exit(1)),process.stdout.write(`
169
169
  \u{1F9E0} Fetching your Brain stats...
@@ -191,20 +191,20 @@ ${p}
191
191
  `),process.exit(1)),process.stdout.write(e(le,t,H)+`
192
192
  `,()=>process.exit(0))}if(process.argv[2]==="badge"){const e=U();e||(console.log(`
193
193
  \u26A0\uFE0F No Brain instance found (environment or ~/.cachly/credentials.json).`),console.log(` Run: npx @cachly-dev/mcp-server@latest autopilot (takes 1\u20135 minutes)
194
- `),process.exit(1));const t=`${x}/api/v1/badge/${e}`,n=j("/","badge"),o=`[![cachly Brain](${t})](${n})`,s=`<a href="${n}"><img src="${t}" alt="cachly Brain" /></a>`;console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly Brain Badge\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Paste into your README.md:"),console.log(""),console.log(` \x1B[32m${o}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${s}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Badge URL (live, updates every hour):"),console.log(` \x1B[90m${t}\x1B[0m`),console.log(""),console.log(" \x1B[2mThe badge shows your current lesson count \u2014 no auth required,"),console.log(" safe to embed in public repos. Updates hourly.\x1B[0m"),console.log(""),process.exit(0)}const ye=Sn(process.argv[2],process.stdin.isTTY===!0&&process.stdout.isTTY===!0);if(ye==="version"&&(process.stdout.write(`${H}
194
+ `),process.exit(1));const t=`${x}/api/v1/badge/${e}`,n=j("/","badge"),o=`[![cachly Brain](${t})](${n})`,s=`<a href="${n}"><img src="${t}" alt="cachly Brain" /></a>`;console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly Brain Badge\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Paste into your README.md:"),console.log(""),console.log(` \x1B[32m${o}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Or paste into HTML:"),console.log(""),console.log(` \x1B[36m${s}\x1B[0m`),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Badge URL (live, updates every hour):"),console.log(` \x1B[90m${t}\x1B[0m`),console.log(""),console.log(" \x1B[2mThe badge shows your current lesson count \u2014 no auth required,"),console.log(" safe to embed in public repos. Updates hourly.\x1B[0m"),console.log(""),process.exit(0)}const ye=Cn(process.argv[2],process.stdin.isTTY===!0&&process.stdout.isTTY===!0);if(ye==="version"&&(process.stdout.write(`${H}
195
195
  `,()=>process.exit(0)),await new Promise(()=>{})),ye==="unbekannt"&&console.error(`
196
- Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||ye==="hilfe"||ye==="unbekannt"){console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly \u2014 Persistent AI Memory for Developers\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Stop re-teaching your AI every morning."),console.log(" cachly gives it a permanent brain \u2014 pre-briefed every session."),console.log("");const e=(t,n)=>console.log(` \x1B[36m ${t.padEnd(22)}\x1B[0m ${n}`);console.log(" \x1B[1mStart:\x1B[0m \x1B[1m\x1B[32mnpx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2190 \x1B[1mOne command, fully ready\x1B[0m"),console.log(" Every command below runs as: npx @cachly-dev/mcp-server@latest <command>"),console.log(""),console.log(" \x1B[1mEvery day:\x1B[0m"),e("status","Lessons, recalls and team at a glance"),e("ambient-stats","Tokens injected vs saved \u2014 the honest net, even when negative"),e("doctor","Diagnose a broken or missing install"),e("health","Check key, API, editor configs and git hook"),e("digest","What your Brain learned this week"),console.log(" \x1B[1mSet up:\x1B[0m"),e("demo","Try it first (no account)"),e("setup","Interactive setup (pick editors)"),e("init","Write the config for one editor (flags)"),e("claim","Keep a test Brain in your own account"),e("upgrade","Check for updates"),e("uninstall","Take cachly out of this project (--dry-run first)"),console.log(" \x1B[1mYour data:\x1B[0m"),e("export","Write your lessons to disk (md / jsonl)"),e("index [dir]","Index a project into the Brain (CI)"),e("learn-git [repo]","Learn lessons from recent commits (CI)"),console.log(" \x1B[1mTeam & sharing:\x1B[0m"),e("invite <email>","Share your Brain with a teammate (sends an email)"),e("join <token>","Accept an invitation to a shared Brain"),e("join --brain <id>","Connect a Brain you already have access to"),e("refer","Your referral link for new users"),e("share","Share your Brain stats"),e("publish","Publish an importable Brain snapshot"),e("badge","README badge for your Brain"),console.log(" \x1B[1mMore:\x1B[0m"),e("bench","Recall quality vs flat-file memory"),e("tool-specs | openapi","Tool definitions for other agent frameworks"),console.log(""),console.log(" \x1B[90mWorks with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 GitHub Copilot \xB7 Cline \xB7 Zed\x1B[0m"),console.log(` \x1B[90mGDPR \xB7 German servers \xB7 ${le.length} MCP tools\x1B[0m`),console.log(""),process.exit(ye==="unbekannt"?1:0)}const ci={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:Nn,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:On,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:Ln,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function li(e,t,n){if(!t)return;const{datei:o,name:s,wie:i}=ci[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 r=t.hooks==="unchanged"?"\u2713 ":"\u2705 ",a=t.hooks==="written"?"Written":t.hooks==="merged"?"Merged":"Already wired";console.log(`${r}${n}${a}: ${o} (Ambient Recall for ${s} \u2014 ${i})`)}async function qe(e,t,n,o){const s=e==="codex"?"Codex":"Gemini CLI",i=await(e==="codex"?Kn:Gn)(t,n).catch(()=>null);if(!i||i.status==="skipped"){const u=ri(e,n);console.log(`\u26A0\uFE0F ${o}${i?`${i.datei} ${i.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 r=i.status==="unchanged"?"\u2713 ":"\u2705 ",a=i.status==="written"?"Written":i.status==="updated"?"Updated":"Already configured";console.log(`${r}${o}${a}: ${i.datei} (MCP server cachly for ${s} \u2014 it asks once to trust this folder; until then the server stays off)`)}async function be(e,t,n,o){const s={cursor:Rn,copilot:jn,codex:Bn,gemini:Pn}[e];li(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:i,relative:r}=await import("node:path"),a=process.argv.slice(3),u=v=>vt(a,v),p=An(a,["instance-id","api-key","editor","project-dir","api-url"]);p.length>0&&(console.error(`
196
+ Unknown command: ${process.argv[2]}`),!process.argv[2]&&process.stdout.isTTY||ye==="hilfe"||ye==="unbekannt"){console.log(""),console.log("\x1B[35m \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\x1B[0m"),console.log("\x1B[35m \u2551\x1B[0m \x1B[1m\u{1F9E0} cachly \u2014 Persistent AI Memory for Developers\x1B[0m \x1B[35m\u2551\x1B[0m"),console.log("\x1B[35m \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m"),console.log(""),console.log(" Stop re-teaching your AI every morning."),console.log(" cachly gives it a permanent brain \u2014 pre-briefed every session."),console.log("");const e=(t,n)=>console.log(` \x1B[36m ${t.padEnd(22)}\x1B[0m ${n}`);console.log(" \x1B[1mStart:\x1B[0m \x1B[1m\x1B[32mnpx @cachly-dev/mcp-server@latest autopilot\x1B[0m \u2190 \x1B[1mOne command, fully ready\x1B[0m"),console.log(" Every command below runs as: npx @cachly-dev/mcp-server@latest <command>"),console.log(""),console.log(" \x1B[1mEvery day:\x1B[0m"),e("status","Lessons, recalls and team at a glance"),e("ambient-stats","Tokens injected vs saved \u2014 the honest net, even when negative"),e("doctor","Diagnose a broken or missing install"),e("health","Check key, API, editor configs and git hook"),e("digest","What your Brain learned this week"),console.log(" \x1B[1mSet up:\x1B[0m"),e("demo","Try it first (no account)"),e("setup","Interactive setup (pick editors)"),e("init","Write the config for one editor (flags)"),e("claim","Keep a test Brain in your own account"),e("upgrade","Check for updates"),e("uninstall","Take cachly out of this project (--dry-run first)"),console.log(" \x1B[1mYour data:\x1B[0m"),e("export","Write your lessons to disk (md / jsonl)"),e("index [dir]","Index a project into the Brain (CI)"),e("learn-git [repo]","Learn lessons from recent commits (CI)"),console.log(" \x1B[1mTeam & sharing:\x1B[0m"),e("invite <email>","Share your Brain with a teammate (sends an email)"),e("join <token>","Accept an invitation to a shared Brain"),e("join --brain <id>","Connect a Brain you already have access to"),e("refer","Your referral link for new users"),e("share","Share your Brain stats"),e("publish","Publish an importable Brain snapshot"),e("badge","README badge for your Brain"),console.log(" \x1B[1mMore:\x1B[0m"),e("bench","Recall quality vs flat-file memory"),e("tool-specs | openapi","Tool definitions for other agent frameworks"),console.log(""),console.log(" \x1B[90mWorks with: Claude Code \xB7 Cursor \xB7 Windsurf \xB7 GitHub Copilot \xB7 Cline \xB7 Zed\x1B[0m"),console.log(` \x1B[90mGDPR \xB7 German servers \xB7 ${le.length} MCP tools\x1B[0m`),console.log(""),process.exit(ye==="unbekannt"?1:0)}const di={cursor:{datei:".cursor/hooks.json",name:"Cursor",wie:"session briefing, per-prompt recall after the first tool call"},copilot:{datei:Ln,name:"VS Code / Copilot",wie:"session briefing, per-prompt recall"},codex:{datei:Hn,name:"Codex",wie:"session briefing, per-prompt recall; trust it once in /hooks"},gemini:{datei:Mn,name:"Gemini CLI",wie:"session briefing, per-prompt recall"}};function ui(e,t,n){if(!t)return;const{datei:o,name:s,wie:i}=di[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 r=t.hooks==="unchanged"?"\u2713 ":"\u2705 ",a=t.hooks==="written"?"Written":t.hooks==="merged"?"Merged":"Already wired";console.log(`${r}${n}${a}: ${o} (Ambient Recall for ${s} \u2014 ${i})`)}async function qe(e,t,n,o){const s=e==="codex"?"Codex":"Gemini CLI",i=await(e==="codex"?qn:Vn)(t,n).catch(()=>null);if(!i||i.status==="skipped"){const u=ci(e,n);console.log(`\u26A0\uFE0F ${o}${i?`${i.datei} ${i.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 r=i.status==="unchanged"?"\u2713 ":"\u2705 ",a=i.status==="written"?"Written":i.status==="updated"?"Updated":"Already configured";console.log(`${r}${o}${a}: ${i.datei} (MCP server cachly for ${s} \u2014 it asks once to trust this folder; until then the server stays off)`)}async function be(e,t,n,o){const s={cursor:Bn,copilot:Nn,codex:Pn,gemini:On}[e];ui(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:i,relative:r}=await import("node:path"),a=process.argv.slice(3),u=v=>vt(a,v),p=Tn(a,["instance-id","api-key","editor","project-dir","api-url"]);p.length>0&&(console.error(`
197
197
  Missing value for ${p.map(v=>`--${v}`).join(", ")}. Nothing was written.
198
198
  `),process.exit(1));let c=u("instance-id")??process.env.CACHLY_BRAIN_INSTANCE_ID,d=u("api-key")??process.env.CACHLY_JWT;const f=(u("editor")??"claude").toLowerCase(),y=s(u("project-dir")??"."),w=u("api-url");if(w&&(x=w.replace(/\/+$/,"")),!c||!d){const v=Ce(),k=Te();v&&k&&(d??=v,c??=k,d===v&&c===k&&console.log("\u2713 Reusing credentials from ~/.cachly/credentials.json (saved by a prior setup)"))}if(!c||!d)try{const{existsSync:v}=await import("node:fs"),k=process.env.HOME??process.env.USERPROFILE??"",_=k?s(k,".claude","mcp.json"):"";if(_&&v(_)){const I=JSON.parse(await o(_,"utf-8")).mcpServers?.cachly?.env??{};d??=I.CACHLY_JWT,c??=I.CACHLY_BRAIN_INSTANCE_ID,d&&c&&console.log("\u2713 Reusing credentials from ~/.claude/mcp.json (saved by a prior setup)")}}catch{}(!c||!d)&&(console.error(`
199
199
  Usage: npx @cachly-dev/mcp-server@latest init --instance-id <uuid> --api-key <cky_live_...> [--editor claude|cursor|windsurf|copilot|continue|cline|zed|codex|gemini] [--all-editors] [--project-dir /path] [--api-url https://your-self-hosted-backend]
200
200
  `),console.error(`First time? Run the zero-config wizard (signs you in, auto-provisions): npx @cachly-dev/mcp-server@latest autopilot
201
201
  `),console.error(`Get your credentials from: ${j("/setup-ai","init")}
202
- `),process.exit(1));const g=Cn({instanceId:c,apiKey:d,editor:f},[...Object.keys(ke),"codex","gemini"]);if(g.length>0){console.error(`
202
+ `),process.exit(1));const g=In({instanceId:c,apiKey:d,editor:f},[...Object.keys(ke),"codex","gemini"]);if(g.length>0){console.error(`
203
203
  Nothing was written:`);for(const v of g)console.error(` - ${v}`);console.error(""),process.exit(1)}try{const v=await fetch(`${x}/api/v1/instances/${c}/memory`,{headers:{Authorization:`Bearer ${d}`},signal:AbortSignal.timeout(8e3)});(v.status===401||v.status===403||v.status===404)&&(console.error(`
204
204
  The server does not accept this key and instance (HTTP ${v.status}). Nothing was written.`),console.error(`Get your credentials from: ${j("/setup-ai","init")}
205
205
  `),process.exit(1))}catch{console.log("\u26A0\uFE0F Could not reach the server to check the key \u2014 writing the config anyway.")}const l=()=>{ne(d),Te()||Ae(c,{apiKey:d})};if(f==="codex"||f==="gemini")l(),console.log(""),await qe(f,y,ee(d,c),"");else{const v=wt(f,y),k=v.anzeige,_=v.pfad;await n(i(_),{recursive:!0});const{existsSync:R}=await import("node:fs"),I=R(_),$=I?await o(_,"utf-8").catch(()=>""):"";l();const E=await Vt(_,d,c,v.format,{readFile:o,existsSync:R});E!==$?(await t(_,E,"utf-8"),console.log(`
206
206
  \u2705 ${I?"Updated":"Written"}: ${k}`)):console.log(`
207
- \u2713 Already configured: ${k} (no change)`)}const m=a.includes("--all-editors"),h=await Zt(y,c,void 0,m?void 0:f);for(const[v,k]of Object.entries(h))console.log(Xt(v.split(/[\\/]/).pop()??v,k));try{const v=await ht(y,c),k=r(y,s(wn(y),"post-commit")).replace(/\\/g,"/");v==="written"?console.log(`\u2705 Written: ${k} (CLS hook)`):v==="upgraded"?console.log(`\u2705 Upgraded: ${k} (CLS hook \u2192 ${ft})`):v==="appended"?console.log(`\u2705 Appended: ${k} (CLS hook)`):v==="unchanged"&&console.log(`\u2713 CLS hook already current in ${k}`)}catch{}if(f==="claude")try{const v=await _t(y,c);if(v.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${v.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const k=v.scripts==="written"?"\u2705 Written":v.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${$t})`:"\u2713 Unchanged";console.log(`${k}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),v.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):v.settings==="merged"?console.log("\u2705 Merged: .claude/settings.json (Ambient Recall hooks wired)"):console.log("\u2713 Ambient Recall hooks already wired in .claude/settings.json")}}catch{}(f==="cursor"||f==="copilot"||f==="codex"||f==="gemini")&&await be(f,y,c,"");const C=((Date.now()-e)/1e3).toFixed(1);console.log(`
207
+ \u2713 Already configured: ${k} (no change)`)}const m=a.includes("--all-editors"),h=await Zt(y,c,void 0,m?void 0:f);for(const[v,k]of Object.entries(h))console.log(Xt(v.split(/[\\/]/).pop()??v,k));try{const v=await ht(y,c),k=r(y,s(xn(y),"post-commit")).replace(/\\/g,"/");v==="written"?console.log(`\u2705 Written: ${k} (CLS hook)`):v==="upgraded"?console.log(`\u2705 Upgraded: ${k} (CLS hook \u2192 ${ft})`):v==="appended"?console.log(`\u2705 Appended: ${k} (CLS hook)`):v==="unchanged"&&console.log(`\u2713 CLS hook already current in ${k}`)}catch{}if(f==="claude")try{const v=await _t(y,c);if(v.settings==="skipped")console.log(`\u26A0\uFE0F .claude/settings.json ${v.grund??"is not valid JSON"} \u2014 left untouched, Ambient Recall hooks not wired`);else{const k=v.scripts==="written"?"\u2705 Written":v.scripts==="upgraded"?`\u2705 Upgraded (\u2192 ${$t})`:"\u2713 Unchanged";console.log(`${k}: .claude/hooks/ (Ambient Recall \u2014 session briefing, per-prompt recall, file briefing, auto-learn)`),v.settings==="written"?console.log("\u2705 Written: .claude/settings.json (Ambient Recall hooks wired)"):v.settings==="merged"?console.log("\u2705 Merged: .claude/settings.json (Ambient Recall hooks wired)"):console.log("\u2713 Ambient Recall hooks already wired in .claude/settings.json")}}catch{}(f==="cursor"||f==="copilot"||f==="codex"||f==="gemini")&&await be(f,y,c,"");const C=((Date.now()-e)/1e3).toFixed(1);console.log(`
208
208
  \u{1F9E0} Cachly AI Brain configured for ${f==="claude"?"Claude Code":f}! (${C}s)`),console.log(f==="codex"||f==="gemini"?` Start ${f} in this folder and trust it when asked \u2014 the \`cachly\` MCP tools will appear.`:" Restart your editor \u2014 the `cachly` MCP tools will appear."),console.log(" Re-run `init` anytime \u2014 it's idempotent (only writes what changed)."),console.log(`
209
209
  \u{1F4DB} Add a live badge to your README:`),console.log(` npx @cachly-dev/mcp-server@latest badge
210
210
  `),process.exit(0)}if(process.argv[2]==="status"){const e=X(),t=U();(!e||!t)&&(console.log(`
@@ -226,33 +226,33 @@ ${"\u2500".repeat(40)}`),i===0?console.log(`\u2705 All checks passed (${s} ok)
226
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"),i=l=>{const m=process.argv.indexOf(`--${l}`);return m!==-1?process.argv[m+1]:void 0};x=(i("api-url")??"https://api.cachly.dev").replace(/\/+$/,"");const r=(i("auth-url")??St).replace(/\/+$/,"");console.log(`
227
227
  \u{1F9E0} cachly \u2014 keep your test Brain in your own account
228
228
  `),(x!=="https://api.cachly.dev"||r!==St)&&console.log(`\u26A0\uFE0F Not the cachly servers: API ${x}, sign-in ${r}
229
- `);const a=Vn({argument:i("key"),credentials:Ce()});a||(console.log("No test key (cky_trial_\u2026) was found in ~/.cachly/credentials.json."),console.log("If you already use your own cachly account, there is nothing to claim."),console.log(`Otherwise pass the key: npx @cachly-dev/mcp-server@latest claim --key cky_trial_\u2026
229
+ `);const a=Xn({argument:i("key"),credentials:Ce()});a||(console.log("No test key (cky_trial_\u2026) was found in ~/.cachly/credentials.json."),console.log("If you already use your own cachly account, there is nothing to claim."),console.log(`Otherwise pass the key: npx @cachly-dev/mcp-server@latest claim --key cky_trial_\u2026
230
230
  `),process.exit(1));const u=a.schluessel,p={argument:"--key",credentials:"~/.cachly/credentials.json"}[a.quelle];console.log(`Test key: ${u.slice(0,14)}\u2026 (from ${p})
231
231
  `);let c="";try{console.log(`Step 1: Sign in to your cachly account
232
- `);const l=await Zn(fetch,r);console.log(` Code: \x1B[1;33m${l.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${l.adresse}
232
+ `);const l=await Qn(fetch,r);console.log(` Code: \x1B[1;33m${l.userCode}\x1B[0m`),console.log(" Open this URL and confirm the code:"),console.log(`${l.adresse}
233
233
  `),ce(l.adresse,(m,h)=>{m||console.log(`
234
- \u2139\uFE0F No browser could be opened here (${h??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),c=await Xn(fetch,l,{basis:r,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
234
+ \u2139\uFE0F No browser could be opened here (${h??"unknown"}) \u2014 please open the URL yourself.`)}),process.stdout.write(" Waiting for sign-in"),c=await es(fetch,l,{basis:r,puls:()=>process.stdout.write(".")}),console.log(` \x1B[32m\u2713\x1B[0m
235
235
  `)}catch(l){console.error(`
236
236
 
237
237
  ${l.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 d;try{d=await Qn(fetch,x,c,u,"mcp",`cachly-mcp/${H}`),console.log(` \x1B[32m\u2713\x1B[0m
238
+ `),process.exit(1)}process.stdout.write("Step 2: Moving the test Brain into your account (it restarts once, up to a minute)\u2026");let d;try{d=await ts(fetch,x,c,u,"mcp",`cachly-mcp/${H}`),console.log(` \x1B[32m\u2713\x1B[0m
239
239
  `)}catch(l){console.error(`
240
240
 
241
- ${os(l)}
242
- `),process.exit(1)}S=d.apiKey,ne(d.apiKey),Ae(d.instanceId,{apiKey:d.apiKey}),await pe(d.apiKey),await me(d.instanceId);const f=s(),y=new Set([...Object.values(ke).map(l=>o(process.cwd(),l)),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 l of y)if(n(l))try{const m=ns(await e(l,"utf-8"),u,d.apiKey);m.ersetzt&&(await t(l,m.text,"utf-8"),w++)}catch{}const g=await es(fetch,x,d.apiKey,d.instanceId);console.log(ts(d,g)),console.log(`
241
+ ${ss(l)}
242
+ `),process.exit(1)}S=d.apiKey,ne(d.apiKey),Ae(d.instanceId,{apiKey:d.apiKey}),await pe(d.apiKey),await me(d.instanceId);const f=s(),y=new Set([...Object.values(ke).map(l=>o(process.cwd(),l)),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 l of y)if(n(l))try{const m=is(await e(l,"utf-8"),u,d.apiKey);m.ersetzt&&(await t(l,m.text,"utf-8"),w++)}catch{}const g=await os(fetch,x,d.apiKey,d.instanceId);console.log(ns(d,g)),console.log(`
243
243
  New key stored in ~/.cachly/credentials.json${w?` and in ${w} editor config file(s) that held the test key`:""}.`),console.log(`Restart your editor (or reload its MCP servers) so it uses the new key.
244
- `),process.exit(0)}const je=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||je){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s,dirname:i}=await import("node:path"),{createInterface:r}=await import("node:readline"),a=Date.now(),u=je?"autopilot":"setup";bn();const p=process.argv.indexOf("--api-url");p!==-1&&process.argv[p+1]&&(x=process.argv[p+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${x}
244
+ `),process.exit(0)}const je=process.argv[2]==="autopilot";if(process.argv[2]==="autosetup"||process.argv[2]==="setup"||je){const{writeFile:e,mkdir:t,readFile:n}=await import("node:fs/promises"),{existsSync:o}=await import("node:fs"),{resolve:s,dirname:i}=await import("node:path"),{createInterface:r}=await import("node:readline"),a=Date.now(),u=je?"autopilot":"setup";vn();const p=process.argv.indexOf("--api-url");p!==-1&&process.argv[p+1]&&(x=process.argv[p+1].replace(/\/+$/,""),console.log(`\u2139\uFE0F Using self-hosted backend: ${x}
245
245
  `)),A("setup_started");const c=process.stdin.isTTY===!0,d=je||process.argv.includes("--yes")||process.argv.includes("-y")||!c;je?console.log(`\u{1F916} Autopilot \u2014 one-command setup (auth \u2192 instance \u2192 configs \u2192 Brain), zero prompts.
246
246
  `):!c&&!process.argv.includes("--yes")&&!process.argv.includes("-y")&&console.log(`\u2139\uFE0F Non-interactive terminal detected \u2014 running in automatic mode (no prompts).
247
247
  `);const f=r({input:process.stdin,output:process.stdout}),y=(b,T="")=>d?(console.log(`${b}${T}`),Promise.resolve(T)):new Promise(B=>f.question(b,z=>B(z.trim()||T)));console.log(`
248
248
  \u{1F9E0} cachly AI Brain \u2014 Setup`),console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
249
249
  `);let w=process.env.CACHLY_JWT??"";if(w)console.log(`\u2713 Using token from CACHLY_JWT env var
250
250
  `);else{console.log(`Step 1: Sign in to cachly (free, no credit card)
251
- `),A("setup_auth_started");let b="",T="",B="",z=5e3,F=!1,K="cachly";try{const V=await fetch(`${x}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(V.ok){const N=await V.json();b=N.device_code,T=N.user_code;const D=N.verification_uri||j("/device",u);B=`${D}${D.includes("?")?"&":"?"}code=${encodeURIComponent(T)}`,z=(N.interval??5)*1e3,F=!!b}}catch{}if(!F)try{const N=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(N.ok){const D=await N.json();b=D.device_code,T=D.user_code,B=D.verification_uri_complete,z=(D.interval??5)*1e3,F=!0,K="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(`${B}
252
- `),ce(B,(N,D)=>{if(N){A("device_browser_opened",{stelle:"setup"});return}A("device_browser_failed",{reason:D??"unknown",stelle:"setup"}),console.log(` \u2139\uFE0F No browser could be opened here (${D??"unknown"}) \u2014 please open the URL yourself.
253
- `)}),process.stdout.write(" Waiting for authorization");const V=Date.now()+600*1e3;for(;Date.now()<V;){await new Promise(N=>setTimeout(N,z)),process.stdout.write(".");try{let N=null;if(K==="cachly")try{const D=await fetch(`${x}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:b}),signal:AbortSignal.timeout(8e3)});D.status<500&&(N=await D.json())}catch{}else{const D="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{N=await(await fetch(`${D}/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(N?.access_token){w=N.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
254
- `),A("setup_auth_completed"),A("device_flow_completed");break}N?.error==="slow_down"?z=Math.min(z+2e3,15e3):N?.error&&N.error!=="authorization_pending"&&(A("device_flow_failed",{reason:N.error}),console.error(`
255
- Auth error: ${N.error}. Aborting.
251
+ `),A("setup_auth_started");let b="",T="",B="",z=5e3,F=!1,K="cachly";try{const V=await fetch(`${x}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),signal:AbortSignal.timeout(8e3)});if(V.ok){const P=await V.json();b=P.device_code,T=P.user_code;const D=P.verification_uri||j("/device",u);B=`${D}${D.includes("?")?"&":"?"}code=${encodeURIComponent(T)}`,z=(P.interval??5)*1e3,F=!!b}}catch{}if(!F)try{const P=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(P.ok){const D=await P.json();b=D.device_code,T=D.user_code,B=D.verification_uri_complete,z=(D.interval??5)*1e3,F=!0,K="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(`${B}
252
+ `),ce(B,(P,D)=>{if(P){A("device_browser_opened",{stelle:"setup"});return}A("device_browser_failed",{reason:D??"unknown",stelle:"setup"}),console.log(` \u2139\uFE0F No browser could be opened here (${D??"unknown"}) \u2014 please open the URL yourself.
253
+ `)}),process.stdout.write(" Waiting for authorization");const V=Date.now()+600*1e3;for(;Date.now()<V;){await new Promise(P=>setTimeout(P,z)),process.stdout.write(".");try{let P=null;if(K==="cachly")try{const D=await fetch(`${x}/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:b}),signal:AbortSignal.timeout(8e3)});D.status<500&&(P=await D.json())}catch{}else{const D="https://auth.cachly.dev/realms/cachly/protocol/openid-connect";try{P=await(await fetch(`${D}/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(P?.access_token){w=P.access_token,console.log(` \x1B[32m\u2713 Authorized!\x1B[0m
254
+ `),A("setup_auth_completed"),A("device_flow_completed");break}P?.error==="slow_down"?z=Math.min(z+2e3,15e3):P?.error&&P.error!=="authorization_pending"&&(A("device_flow_failed",{reason:P.error}),console.error(`
255
+ Auth error: ${P.error}. Aborting.
256
256
  `),f.close(),process.exit(1))}catch{}}w||(A("device_flow_failed",{reason:"timeout"}),console.error(`
257
257
  Timed out waiting for authorization. Aborting.
258
258
  `),f.close(),process.exit(1)),console.log("")}else{A("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...
@@ -276,8 +276,8 @@ Could not create an instance automatically. Opening ${j("/instances",u)} \u2026
276
276
  `),ce(j("/instances",u)),f.close(),process.exit(1))}const l=g[0];g.length>1&&(console.log(`\u2139\uFE0F Multiple instances found \u2014 using most recent: ${l.name}`),console.log(` (Run with --instance-id <id> to use a different one)
277
277
  `)),console.log(`\u2713 Instance: ${l.name} (${l.id.slice(0,8)}\u2026)
278
278
  `),A("setup_instance_ready",{instance_id:l.id});const m=process.cwd(),h=[],{homedir:C}=await import("node:os"),v=C();h.push("claude"),o(s(m,".cursor"))&&h.push("cursor");const k=he();(o(s(m,".windsurf"))||bt("windsurf",k,o))&&h.push("windsurf"),o(s(m,".vscode"))&&h.push("copilot"),o(s(m,".continue"))&&h.push("continue"),bt("cline",k,o)&&h.push("cline");const _=process.platform==="darwin"?s(v,"Library/Application Support/Zed"):s(v,".config/zed");o(_)&&h.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=h;console.log(`\u{1F527} Configuring for: ${I.map(R).join(", ")}
279
- `);const{existsSync:$}=await import("node:fs"),E=[];let M=0;ne(w),Ae(l.id,{apiKey:w});for(const b of I){const T=wt(b,m),B=T.anzeige,z=T.pfad;try{await t(i(z),{recursive:!0});const F=$(z),K=await Vt(z,w,l.id,T.format,{readFile:n,existsSync:$});await e(z,K,"utf-8"),console.log(`\u2705 ${F?"Updated":"Written"}: ${B}`),M++}catch(F){const K=F.message;console.log(`\u26A0\uFE0F Could not write ${B}: ${K}`),console.log(" Fix permissions or run with sudo, then re-run setup."),E.push({file:B,reason:K})}}const Pe=await Zt(m,l.id);for(const[b,T]of Object.entries(Pe)){const{relative:B}=await import("node:path");console.log(Xt(B(m,b)||b,T))}S=w;let ie=0;if(o(s(m,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const b=await J("brain_from_git",{instance_id:l.id,repo_path:m,limit:100});if(b.startsWith("\u274C"))console.log(` (skipped: ${gt(b.replace(/^❌\s*/,"")).split(`
280
- `)[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 B=hn(b);B&&(console.log(""),console.log(gt(B)))}}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:l.id}),console.log(" \u2713");try{const b=await J("smart_recall",{instance_id:l.id,query:"docker build slow"}),T=fn(b);T&&(console.log(""),console.log(yn(T.topic,T.what)))}catch{}}catch(b){console.log(` (skipped: ${b.message.slice(0,60)})`)}}try{const b=await fetch(`${x}/api/v1/instances/${l.id}/memory`,{headers:{Authorization:`Bearer ${w}`},signal:AbortSignal.timeout(6e3)});if(b.ok){const B=(await b.json()).lesson_count??0;console.log(B===0?`
279
+ `);const{existsSync:$}=await import("node:fs"),E=[];let M=0;ne(w),Ae(l.id,{apiKey:w});for(const b of I){const T=wt(b,m),B=T.anzeige,z=T.pfad;try{await t(i(z),{recursive:!0});const F=$(z),K=await Vt(z,w,l.id,T.format,{readFile:n,existsSync:$});await e(z,K,"utf-8"),console.log(`\u2705 ${F?"Updated":"Written"}: ${B}`),M++}catch(F){const K=F.message;console.log(`\u26A0\uFE0F Could not write ${B}: ${K}`),console.log(" Fix permissions or run with sudo, then re-run setup."),E.push({file:B,reason:K})}}const Ne=await Zt(m,l.id);for(const[b,T]of Object.entries(Ne)){const{relative:B}=await import("node:path");console.log(Xt(B(m,b)||b,T))}S=w;let ie=0;if(o(s(m,".git"))){process.stdout.write("\u23F3 Bootstrapping Brain from git history (~10s)...");try{const b=await J("brain_from_git",{instance_id:l.id,repo_path:m,limit:100});if(b.startsWith("\u274C"))console.log(` (skipped: ${gt(b.replace(/^❌\s*/,"")).split(`
280
+ `)[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 B=yn(b);B&&(console.log(""),console.log(gt(B)))}}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:l.id}),console.log(" \u2713");try{const b=await J("smart_recall",{instance_id:l.id,query:"docker build slow"}),T=bn(b);T&&(console.log(""),console.log(wn(T.topic,T.what)))}catch{}}catch(b){console.log(` (skipped: ${b.message.slice(0,60)})`)}}try{const b=await fetch(`${x}/api/v1/instances/${l.id}/memory`,{headers:{Authorization:`Bearer ${w}`},signal:AbortSignal.timeout(6e3)});if(b.ok){const B=(await b.json()).lesson_count??0;console.log(B===0?`
281
281
  \u{1F9E0} Your Brain is empty. It learns from your fixes and commits from now on.`:`
282
282
  \u{1F9E0} Your Brain now holds ${B} lesson${B===1?"":"s"}.`)}}catch{}if(!d)try{if(console.log(`
283
283
  \u{1F451} Governance (optional \u2014 role model: admin \xB7 reviewer \xB7 contributor \xB7 viewer)`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),(await y(" Set yourself as the first admin? (y/N): ","N")).toLowerCase()==="y"){const T=await y(' Your handle (e.g. "alice"): ');T.trim()&&await J("team_assign_role",{instance_id:l.id,handle:T.trim(),role:"admin"}).catch(()=>"")&&(console.log(` \u2705 ${T.trim()} is now admin. Invite teammates:
@@ -314,14 +314,14 @@ Could not create an instance automatically. Opening ${j("/instances",u)} \u2026
314
314
  \u2705 Brain learned from your commits.
315
315
  `),await new Promise(a=>setTimeout(a,300))}catch(r){console.error(`
316
316
  \u274C learn-git failed: ${r.message}
317
- `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await Hn(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await Mn(),process.argv[2]===Dn&&await zn(process.argv[3]??""),process.argv[2]==="ambient-credit"){try{const e=Math.round(Number(process.argv[3]));if(Number.isFinite(e)&&e>0){const t=Math.min(e,2e4),n=process.argv.slice(4).join(" ").slice(0,200)||void 0,o={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n,instanz:U()||void 0};await Wn(o),await Ys(process.env.CACHLY_BRAIN_INSTANCE_ID??P,o),console.log(`\u2705 ambient credit recorded: ${t} tokens${n?` (${n})`:""}`)}else console.error("Usage: npx @cachly-dev/mcp-server@latest ambient-credit <tokens-saved> [note]")}catch{}process.exit(0)}if(process.argv[2]==="ambient-stats"){const e=U(),t=Yn(await kt(),e||void 0),n=t.eigene,o=Ds(n),s=n.slice(-5);if(console.log(`
317
+ `),process.exit(1)}process.exit(0)}if(process.argv[2]==="ambient-recall"&&await zn(process.argv.slice(3),process.argv[1]),process.argv[2]==="ambient-auffrischen"&&await Dn(),process.argv[2]===Wn&&await Un(process.argv[3]??""),process.argv[2]==="ambient-credit"){try{const e=Math.round(Number(process.argv[3]));if(Number.isFinite(e)&&e>0){const t=Math.min(e,2e4),n=process.argv.slice(4).join(" ").slice(0,200)||void 0,o={ts:new Date().toISOString(),event:"credit",injected:0,prevented:t,note:n,instanz:U()||void 0};await Fn(o),await Gs(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=U(),t=Gn(await kt(),e||void 0),n=t.eigene,o=Ws(n),s=n.slice(-5);if(console.log(`
318
318
  \u{1F9E0} Ambient Recall \u2014 net-token ledger
319
319
  `),console.log(` Instance: ${e?`${e.slice(0,8)}\u2026`:"(none set \u2014 showing every entry on this computer)"}`),console.log(` Turns recorded: ${n.length}`),console.log(` Injected tokens: ${o.injected}`),console.log(` Prevented tokens: ${o.prevented} (agent-reported via ambient-credit)`),console.log(` NET: ${o.net>=0?"+":""}${o.net} tokens`),s.length>0){console.log(`
320
320
  Last entries:`);for(const i of s){const r=i.prevented>0?`+${i.prevented} prevented`:`-${i.injected} injected`;console.log(` \u2022 ${i.ts.slice(0,19)} ${i.event}: ${r}${i.note?` (${i.note})`:""}`)}}(t.ohneInstanz>0||t.andereInstanzen>0)&&(console.log(`
321
- Not counted above:`),t.ohneInstanz>0&&console.log(` \u2022 ${t.ohneInstanz} older entries without an instance (before 0.10.207)`),t.andereInstanzen>0&&console.log(` \u2022 entries of ${t.andereInstanzen} other instance${t.andereInstanzen===1?"":"s"} on this computer`)),console.log(""),process.exit(0)}if(process.argv[2]==="uninstall"){const{homedir:e,tmpdir:t}=await import("node:os"),{resolve:n}=await import("node:path"),{createInterface:o}=await import("node:readline/promises"),s=process.argv.slice(3),r={projekt:n((a=>{const u=s.indexOf(`--${a}`);return u!==-1?s[u+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:X(),instanz:U(),apiUrl:x,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:a=>console.log(a),frage:async a=>{const u=o({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await u.question(a)).trim())}finally{u.close()}}};process.exit(await Tn(s,r))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:o,checkInstance:s,checkVectorCoverage:i,inspectAmbientHooks:r,checkHooks:a,checkLedger:u,renderDoctorReport:p,doctorExitCode:c}=await import("./doctor.js"),d=[e(),t(S),await n(x),await o(x,S),s(U()||P),await i(x,S,U()||P),a(r(process.cwd())),u(await kt(),Jn())];console.log(p(d)),process.exit(c(d))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!S)&&process.exit(0);let t;try{t=JSON.parse(e)}catch{process.exit(0)}const n=t.instance_id??P;(!n||!t.source)&&process.exit(0),await J("cls_ingest",{instance_id:n,source:t.source,payload:t.payload??{}})}catch{}process.exit(0)}if(!S){const e=no();if(e)try{const t=await fetch(io(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:so(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(S=n.access_token,oe(n.access_token),A("m2m_auth_completed",{grant:"client_credentials",client_id:e.clientId}),process.stderr.write(`\u{1F916} cachly: authenticated via client_credentials (M2M, headless).
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),r={projekt:n((a=>{const u=s.indexOf(`--${a}`);return u!==-1?s[u+1]:void 0})("project-dir")??"."),heim:process.env.HOME??process.env.USERPROFILE??process.env.APPDATA??e(),tmp:t(),schluessel:X(),instanz:U(),apiUrl:x,istTty:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,ausgabe:a=>console.log(a),frage:async a=>{const u=o({input:process.stdin,output:process.stdout});try{return/^(y|yes|j|ja)$/i.test((await u.question(a)).trim())}finally{u.close()}}};process.exit(await En(s,r))}if(process.argv[2]==="doctor"){const{checkNodeVersion:e,checkCredential:t,checkApiReachable:n,checkAuthAccepted:o,checkInstance:s,checkVectorCoverage:i,inspectAmbientHooks:r,checkHooks:a,checkLedger:u,renderDoctorReport:p,doctorExitCode:c}=await import("./doctor.js"),d=[e(),t(S),await n(x),await o(x,S),s(U()||N),await i(x,S,U()||N),a(r(process.cwd())),u(await kt(),Yn())];console.log(p(d)),process.exit(c(d))}if(process.argv[2]==="cls-ingest"){try{const e=process.argv[3];(!e||!S)&&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(!S){const e=no();if(e)try{const t=await fetch(io(e),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:so(e),signal:AbortSignal.timeout(8e3)});if(t.ok){const n=await t.json();n.access_token&&(S=n.access_token,oe(n.access_token),A("m2m_auth_completed",{grant:"client_credentials",client_id:e.clientId}),process.stderr.write(`\u{1F916} cachly: authenticated via client_credentials (M2M, headless).
322
322
  `))}else process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth failed (${t.status}). Check CACHLY_CLIENT_ID / CACHLY_CLIENT_SECRET.
323
323
  `),A("m2m_auth_failed",{status:t.status})}catch(t){process.stderr.write(`\u26A0\uFE0F cachly: client_credentials auth error: ${t.message}
324
- `),A("m2m_auth_failed",{reason:"network"})}}const di=["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(!S&&!di.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&mo){const o=`
324
+ `),A("m2m_auth_failed",{reason:"network"})}}const pi=["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(!S&&!pi.includes(process.argv[2]??""))if(!process.argv[2]&&process.stdout.isTTY===!0&&mo){const o=`
325
325
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
326
326
  \u2551 \u{1F9E0} cachly AI Brain \u2014 Setup required \u2551
327
327
  \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
@@ -349,7 +349,7 @@ Could not create an instance automatically. Opening ${j("/instances",u)} \u2026
349
349
  \u26A0\uFE0F cachly: CACHLY_JWT expires in ${t} minute(s).
350
350
  Refresh it soon at ${j("/setup-ai","jwt-expiry")} to avoid interruptions.
351
351
 
352
- `)}}process.env.PORT||$s({aktuelle:_s(H)});const Be=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(Be){jo(!0),S="",P="",oe(""),Ro();const e=Mo(async(s,i)=>{const r=await fetch(`${x}${s}`,{headers:{Authorization:`Bearer ${i}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)}),a=r.ok?await r.json().catch(()=>null):null;return{status:r.status,body:a}}),{createServer:t}=await import("node:http"),n=(s,i,r)=>{s.headersSent||(s.writeHead(i,{"Content-Type":"application/json",...i===401?{"WWW-Authenticate":'Bearer realm="cachly"'}:{}}),s.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:r},id:null})))};t((s,i)=>{const r=new URL(s.url??"/",`http://localhost:${Be}`);if(r.pathname==="/health"){i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"ok",version:H,mode:"http-remote"}));return}if(r.pathname==="/mcp"||r.pathname==="/"){(async()=>{const a=Oo(s.headersDistinct?.authorization??s.headers.authorization);if(a.art==="abgelehnt"){const d=a.grund==="zu-lang"?"Der Authorization-Kopf ist zu lang.":a.grund==="mehrfach"?"Der Authorization-Kopf darf nur einmal vorkommen.":a.grund==="kein-bearer"?'Nur "Authorization: Bearer cky_..." wird akzeptiert.':"Das ist kein cachly-API-Schluessel (er beginnt mit cky_). Neuen holen: "+j("/setup-ai","setup");return n(i,401,d)}const u=Lo(s.headers["x-cachly-instance"]);if(u.art==="abgelehnt")return n(i,400,"X-Cachly-Instance muss eine Instanz-ID (UUID) sein.");let p;if(a.art==="ok")try{const d=await e.loese(a.schluessel,u.art==="ok"?u.instanzId:void 0);p=Po(a.schluessel,d)}catch(d){return d instanceof zo?n(i,d.httpStatus,d.message):n(i,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}const c=async()=>{const d=ni(),f=new ho({sessionIdGenerator:void 0});i.on("close",()=>{f.close().catch(()=>{}),d.close().catch(()=>{})});try{await d.connect(f),await f.handleRequest(s,i)}catch(y){process.stderr.write(`cachly-mcp HTTP: ${y.message}
352
+ `)}}process.env.PORT||Ss({aktuelle:ks(H)});const Be=process.env.PORT?parseInt(process.env.PORT,10):void 0;if(Be){jo(!0),S="",N="",oe(""),Ro();const e=Mo(async(s,i)=>{const r=await fetch(`${x}${s}`,{headers:{Authorization:`Bearer ${i}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)}),a=r.ok?await r.json().catch(()=>null):null,u=Number(r.headers.get("retry-after"));return{status:r.status,body:a,retryAfterS:Number.isFinite(u)&&u>0?u:void 0}},{grenze:Do()}),{createServer:t}=await import("node:http"),n=(s,i,r,a)=>{s.headersSent||(s.writeHead(i,{"Content-Type":"application/json",...i===429&&a?{"Retry-After":String(a)}:{},...i===401?{"WWW-Authenticate":'Bearer realm="cachly"'}:{}}),s.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:r},id:null})))};t((s,i)=>{const r=new URL(s.url??"/",`http://localhost:${Be}`);if(r.pathname==="/health"){i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"ok",version:H,mode:"http-remote"}));return}if(r.pathname==="/mcp"||r.pathname==="/"){(async()=>{const a=Oo(s.headersDistinct?.authorization??s.headers.authorization);if(a.art==="abgelehnt"){const d=a.grund==="zu-lang"?"Der Authorization-Kopf ist zu lang.":a.grund==="mehrfach"?"Der Authorization-Kopf darf nur einmal vorkommen.":a.grund==="kein-bearer"?'Nur "Authorization: Bearer cky_..." wird akzeptiert.':"Das ist kein cachly-API-Schluessel (er beginnt mit cky_). Neuen holen: "+j("/setup-ai","setup");return n(i,401,d)}const u=Lo(s.headers["x-cachly-instance"]);if(u.art==="abgelehnt")return n(i,400,"X-Cachly-Instance muss eine Instanz-ID (UUID) sein.");let p;if(a.art==="ok")try{const d=await e.loese(a.schluessel,u.art==="ok"?u.instanzId:void 0,Uo(s.headers["x-real-ip"],s.socket.remoteAddress));p=No(a.schluessel,d)}catch(d){return d instanceof zo?n(i,d.httpStatus,d.message,d.retryAfterS):n(i,502,"Die cachly-API ist gerade nicht erreichbar. Bitte gleich noch einmal versuchen.")}const c=async()=>{const d=ii(),f=new ho({sessionIdGenerator:void 0});i.on("close",()=>{f.close().catch(()=>{}),d.close().catch(()=>{})});try{await d.connect(f),await f.handleRequest(s,i)}catch(y){process.stderr.write(`cachly-mcp HTTP: ${y.message}
353
353
  `),i.headersSent||(i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:y.message})))}};await(p?Bo(p,c):c())})();return}i.writeHead(404),i.end("not found")}).listen(Be,()=>{process.stderr.write(`cachly-mcp HTTP server listening on :${Be}
354
- `)})}else{const e=new go;Y("start: Module geladen, stdio verbinden"),await q.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(ct=!0,gs(()=>xs(lt)),_o(),Cs(),Ss(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 session over, server exits too
355
- `),(async()=>{await Ge().catch(()=>{});for(const o of We())await o.quit().catch(()=>{});process.exit(0)})()}))}Qe("cachly","startup",{version:H,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{xn as CLAUDE_MD_MARKER_END,vn as CLAUDE_MD_MARKER_START,en as CROSS_LINGUAL_MAP,ke as EDITOR_FILES,Vo as STOPWORDS,Xt as anweisungsZeile,Xo as arabicLightStem,yt as buildClaudeMdBlock,ai as buildMcpConfig,ee as buildServerEnv,Qo as expandCrossLingual,qo as extractTimestamp,Zo as katakanaToRomaji,Ko as levenshtein,ri as mcpAddBefehl,Vt as mergeMcpConfig,Go as recencyBoost,nn as reconnectOnce,Yo as splitMultiQuery,To as startBackgroundDevicePoll,Fo as tokenize,Zt as writeInstructions};
354
+ `)})}else{const e=new go;Y("start: Module geladen, stdio verbinden"),await q.connect(e),typeof process.argv[2]=="string"&&!process.argv[2].startsWith("-")||(ct=!0,fs(()=>$s(lt)),_o(),Is(),Cs(process.stdin,n=>{process.stderr.write(`[cachly-mcp] ${n} \u2014 session over, server exits too
355
+ `),(async()=>{await Ge().catch(()=>{});for(const o of We())await o.quit().catch(()=>{});process.exit(0)})()}))}Qe("cachly","startup",{version:H,mode:process.env.MCP_HTTP_PORT?"http":"stdio"}).catch(()=>{});export{$n as CLAUDE_MD_MARKER_END,_n as CLAUDE_MD_MARKER_START,on as CROSS_LINGUAL_MAP,ke as EDITOR_FILES,Xo as STOPWORDS,Xt as anweisungsZeile,en as arabicLightStem,yt as buildClaudeMdBlock,li as buildMcpConfig,ee as buildServerEnv,tn as expandCrossLingual,Zo as extractTimestamp,Qo as katakanaToRomaji,qo as levenshtein,ci as mcpAddBefehl,Vt as mergeMcpConfig,Vo as recencyBoost,rn as reconnectOnce,Go as splitMultiQuery,To as startBackgroundDevicePoll,Ko as tokenize,Zt as writeInstructions};
@@ -1,2 +1,2 @@
1
- import{AsyncLocalStorage as x}from"node:async_hooks";import{createHash as S}from"node:crypto";import{KERNWERKZEUGE as v}from"./werkzeug-auswahl.js";const m=new x;let w=!1;function C(t){w=t}function N(){return w}function $(){return m.getStore()}function R(t,e){return m.run(t,e)}function p(t){return S("sha256").update(t).digest("hex")}function j(t,e){return{schluessel:t,schluesselHash:p(t),instanzId:e}}function k(t,e){return`${p(t)}:${e}`}const A=256,_=/^cky_[A-Za-z0-9_-]{8,200}$/,b=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Z(t){if(t===void 0)return{art:"fehlt"};if(Array.isArray(t)){if(t.length>1)return{art:"abgelehnt",grund:"mehrfach"};if(t=t[0],t===void 0)return{art:"fehlt"}}if(t.trim()==="")return{art:"fehlt"};if(t.length>A)return{art:"abgelehnt",grund:"zu-lang"};const e=/^Bearer[ \t]+(\S+)$/i.exec(t.trim());return e?_.test(e[1])?{art:"ok",schluessel:e[1]}:{art:"abgelehnt",grund:"form"}:{art:"abgelehnt",grund:"kein-bearer"}}function G(t){if(t===void 0)return{art:"fehlt"};if(Array.isArray(t))return{art:"abgelehnt"};const e=t.trim();return e===""?{art:"fehlt"}:e.length>36||!b.test(e)?{art:"abgelehnt"}:{art:"ok",instanzId:e.toLowerCase()}}class y{opt;eintraege=new Map;jetzt;constructor(e){this.opt=e,this.jetzt=e.jetzt??Date.now}get groesse(){return this.eintraege.size}has(e){return this.get(e)!==void 0}get(e){const n=this.eintraege.get(e);if(n){if(n.bis<=this.jetzt()){this.eintraege.delete(e),this.opt.beiEntfernen?.(n.wert,"abgelaufen");return}return this.eintraege.delete(e),this.eintraege.set(e,n),n.wert}}set(e,n,i=this.opt.ttlMs){const a=this.eintraege.get(e);for(a&&a.wert!==n&&this.opt.beiEntfernen?.(a.wert,"geloescht"),this.eintraege.delete(e),this.eintraege.set(e,{wert:n,bis:this.jetzt()+i});this.eintraege.size>this.opt.max;){const h=this.eintraege.keys().next().value;if(h===void 0)break;const f=this.eintraege.get(h);this.eintraege.delete(h),f&&this.opt.beiEntfernen?.(f.wert,"verdraengt")}}vergiss(e){this.eintraege.delete(e)}vergissWenn(e,n){this.eintraege.get(e)?.wert===n&&this.eintraege.delete(e)}werte(){return[...this.eintraege.values()].map(e=>e.wert)}leeren(){for(const e of this.eintraege.values())this.opt.beiEntfernen?.(e.wert,"geloescht");this.eintraege.clear()}}class o extends Error{httpStatus;constructor(e,n){super(n),this.httpStatus=e,this.name="ZugangAbgelehnt"}}const z=10*6e4,E=200,D=6e4,I=1e3;function T(t,e){const n=e?.jetzt,i=new y({max:E,ttlMs:z,jetzt:n}),a=new y({max:I,ttlMs:D,jetzt:n}),h=new Map;async function f(d,l){if(l){const r=await t(`/api/v1/instances/${l}`,d);if(r.status===200)return l;throw r.status===401?new o(401,"Der Schluessel wurde abgelehnt (ungueltig, abgelaufen oder widerrufen)."):r.status===403||r.status===404?new o(403,"Dieser Schluessel gilt nicht fuer die angegebene Instanz (Kopf X-Cachly-Instance)."):new o(502,`Die cachly-API antwortete mit ${r.status}; bitte spaeter erneut versuchen.`)}const s=await t("/api/v1/instances",d);if(s.status===401)throw new o(401,"Der Schluessel wurde abgelehnt (ungueltig, abgelaufen oder widerrufen).");if(s.status===403)throw new o(400,'Dieser Schluessel ist an ein einzelnes Brain gebunden und darf keine Instanzliste lesen. Setze den Kopf "X-Cachly-Instance: <Instanz-ID>" (die ID steht im Dashboard unter cachly.dev/instances).');if(s.status!==200)throw new o(502,`Die cachly-API antwortete mit ${s.status}; bitte spaeter erneut versuchen.`);const g=s.body?.data,c=(Array.isArray(g)?g:[]).map(r=>typeof r?.id=="string"?r.id.toLowerCase():"").filter(r=>b.test(r));if(c.length===1)return c[0];throw c.length===0?new o(400,"Zu diesem Schluessel gehoert noch kein Brain. Lege eines an: https://cachly.dev/setup-ai"):new o(400,`Zu diesem Schluessel gehoeren ${c.length} Brains. Waehle eines mit dem Kopf "X-Cachly-Instance: <Instanz-ID>" (Dashboard: cachly.dev/instances).`)}return{async loese(d,l){const s=`${p(d)}|${l??"*"}`,g=i.get(s);if(g)return g;const c=a.get(s);if(c)throw c;let r=h.get(s);return r||(r=f(d,l).then(u=>(i.set(s,u),u)).catch(u=>{throw u instanceof o&&u.httpStatus!==502&&a.set(s,u),u}).finally(()=>{h.delete(s)}),h.set(s,r)),r},leeren(){i.leeren(),a.leeren(),h.clear()}}}const P=["Dieser Remote-MCP-Server braucht deinen cachly-Schluessel, damit er DEIN Brain oeffnet.","The remote MCP server needs your cachly API key to open YOUR Brain.","","1. Schluessel holen / get a key: https://cachly.dev/setup-ai","2. Kopf setzen / set the header, zum Beispiel / for example:",' claude mcp add --transport http cachly https://mcp.cachly.dev/mcp --header "Authorization: Bearer <key>"',' (Cursor / VS Code: "url" und "headers" in der mcp.json, siehe https://cachly.dev/docs)','3. Mehrere Brains im Konto? Zusaetzlich / more than one Brain? Add: --header "X-Cachly-Instance: <instance-id>"',"","Lieber lokal, ohne Kopf: npx @cachly-dev/mcp-server@latest autopilot"].join(`
2
- `),M=new Set(["autopilot","brain_from_git","index_project"]);function X(t){return v.includes(t)&&!M.has(t)}const L=["workspace_path","repo_path","dir","project_dir"];function H(t){return`Das Werkzeug "${t}" ist ueber den Remote-Server (mcp.cachly.dev) nicht verfuegbar: es liest Dateien auf deinem Rechner oder gehoert nicht zu den Kernwerkzeugen. Lokal geht es: npx @cachly-dev/mcp-server@latest autopilot. / "${t}" is not available on the remote server; run the local server for it.`}function O(t,e){const n=t.instance_id;if(typeof n=="string"&&n.trim()!==""&&n.trim().toLowerCase()!==e)return{fehler:"Die Instanz in instance_id ist nicht die, die dieser Schluessel freigibt. Lass instance_id weg: dieser Server nimmt immer das Brain des Schluessels (oder des Kopfs X-Cachly-Instance)."};const i={...t};for(const a of L)delete i[a];return i.instance_id=e,{args:i}}export{I as ABLEHNUNG_MAX,D as ABLEHNUNG_TTL_MS,P as ANLEITUNG_OHNE_KOPF,y as BegrenzterSpeicher,A as MAX_AUTH_KOPF,M as NUR_LOKAL_WERKZEUGE,L as PFAD_ARGUMENTE,E as ZUGANG_MAX,z as ZUGANG_TTL_MS,o as ZugangAbgelehnt,j as baueKontext,T as baueZugangsAufloeser,O as bereinigeArgumente,p as hashDesSchluessels,R as imMandant,N as istMehrmandant,X as istRemoteErlaubt,Z as leseBearer,G as leseInstanzKopf,$ as mandantKontext,H as nurLokalText,k as poolSchluessel,C as setzeMehrmandant};
1
+ import{AsyncLocalStorage as S}from"node:async_hooks";import{createHash as _}from"node:crypto";import{isIP as z}from"node:net";import{KERNWERKZEUGE as v}from"./werkzeug-auswahl.js";const y=new S;let x=!1;function Z(t){x=t}function G(){return x}function T(){return y.getStore()}function F(t,e){return y.run(t,e)}function w(t){return _("sha256").update(t).digest("hex")}function X(t,e){return{schluessel:t,schluesselHash:w(t),instanzId:e}}function H(t,e){return`${w(t)}:${e}`}const E=256,M=/^cky_[A-Za-z0-9_-]{8,200}$/,A=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function O(t){if(t===void 0)return{art:"fehlt"};if(Array.isArray(t)){if(t.length>1)return{art:"abgelehnt",grund:"mehrfach"};if(t=t[0],t===void 0)return{art:"fehlt"}}if(t.trim()==="")return{art:"fehlt"};if(t.length>E)return{art:"abgelehnt",grund:"zu-lang"};const e=/^Bearer[ \t]+(\S+)$/i.exec(t.trim());return e?M.test(e[1])?{art:"ok",schluessel:e[1]}:{art:"abgelehnt",grund:"form"}:{art:"abgelehnt",grund:"kein-bearer"}}function W(t){if(t===void 0)return{art:"fehlt"};if(Array.isArray(t))return{art:"abgelehnt"};const e=t.trim();return e===""?{art:"fehlt"}:e.length>36||!A.test(e)?{art:"abgelehnt"}:{art:"ok",instanzId:e.toLowerCase()}}class b{opt;eintraege=new Map;jetzt;constructor(e){this.opt=e,this.jetzt=e.jetzt??Date.now}get groesse(){return this.eintraege.size}has(e){return this.get(e)!==void 0}get(e){const r=this.eintraege.get(e);if(r){if(r.bis<=this.jetzt()){this.eintraege.delete(e),this.opt.beiEntfernen?.(r.wert,"abgelaufen");return}return this.eintraege.delete(e),this.eintraege.set(e,r),r.wert}}set(e,r,n=this.opt.ttlMs){const a=this.eintraege.get(e);for(a&&a.wert!==r&&this.opt.beiEntfernen?.(a.wert,"geloescht"),this.eintraege.delete(e),this.eintraege.set(e,{wert:r,bis:this.jetzt()+n});this.eintraege.size>this.opt.max;){const s=this.eintraege.keys().next().value;if(s===void 0)break;const h=this.eintraege.get(s);this.eintraege.delete(s),h&&this.opt.beiEntfernen?.(h.wert,"verdraengt")}}vergiss(e){this.eintraege.delete(e)}vergissWenn(e,r){this.eintraege.get(e)?.wert===r&&this.eintraege.delete(e)}werte(){return[...this.eintraege.values()].map(e=>e.wert)}leeren(){for(const e of this.eintraege.values())this.opt.beiEntfernen?.(e.wert,"geloescht");this.eintraege.clear()}}class u extends Error{httpStatus;retryAfterS;constructor(e,r,n){super(r),this.httpStatus=e,this.retryAfterS=n,this.name="ZugangAbgelehnt"}}const I=10*6e4,D=200,L=6e4,U=1e3,B=20,N=6e4,R=1e4;function V(t){const e=t?.max??B,r=t?.fensterMs??N,n=t?.jetzt??Date.now,a=new b({max:t?.maxIps??R,ttlMs:r,jetzt:n});return{zaehle(s){const h=n();let l=a.get(s);return(!l||l.ende<=h)&&(l={n:0,ende:h+r},a.set(s,l)),l.n>=e?{erlaubt:!1,retryAfterS:Math.max(1,Math.ceil((l.ende-h)/1e3))}:(l.n+=1,{erlaubt:!0})}}}function J(t,e){const r=a=>{const s=a?.trim();return s&&z(s)?s.toLowerCase():void 0};return(typeof t=="string"?r(t):void 0)??r(e)??"unbekannt"}function Y(t,e){const r=e?.jetzt,n=new b({max:D,ttlMs:I,jetzt:r}),a=new b({max:U,ttlMs:L,jetzt:r}),s=new Map,h=f=>{const d=f.retryAfterS&&f.retryAfterS>0?Math.min(Math.ceil(f.retryAfterS),3600):60;return new u(429,`Die cachly-API begrenzt gerade die Anfragen. Bitte in ${d} s erneut versuchen.`,d)};async function l(f,d){if(d){const i=await t(`/api/v1/instances/${d}`,f);if(i.status===429)throw h(i);if(i.status===200)return d;throw i.status===401?new u(401,"Der Schluessel wurde abgelehnt (ungueltig, abgelaufen oder widerrufen)."):i.status===403||i.status===404?new u(403,"Dieser Schluessel gilt nicht fuer die angegebene Instanz (Kopf X-Cachly-Instance)."):new u(502,`Die cachly-API antwortete mit ${i.status}; bitte spaeter erneut versuchen.`)}const g=await t("/api/v1/instances",f);if(g.status===429)throw h(g);if(g.status===401)throw new u(401,"Der Schluessel wurde abgelehnt (ungueltig, abgelaufen oder widerrufen).");if(g.status===403)throw new u(400,'Dieser Schluessel ist an ein einzelnes Brain gebunden und darf keine Instanzliste lesen. Setze den Kopf "X-Cachly-Instance: <Instanz-ID>" (die ID steht im Dashboard unter cachly.dev/instances).');if(g.status!==200)throw new u(502,`Die cachly-API antwortete mit ${g.status}; bitte spaeter erneut versuchen.`);const c=g.body?.data,p=(Array.isArray(c)?c:[]).map(i=>typeof i?.id=="string"?i.id.toLowerCase():"").filter(i=>A.test(i));if(p.length===1)return p[0];throw p.length===0?new u(400,"Zu diesem Schluessel gehoert noch kein Brain. Lege eines an: https://cachly.dev/setup-ai"):new u(400,`Zu diesem Schluessel gehoeren ${p.length} Brains. Waehle eines mit dem Kopf "X-Cachly-Instance: <Instanz-ID>" (Dashboard: cachly.dev/instances).`)}return{async loese(f,d,g){const c=`${w(f)}|${d??"*"}`,p=n.get(c);if(p)return p;const i=a.get(c);if(i)throw i;let m=s.get(c);if(!m){if(e?.grenze){const o=e.grenze.zaehle(g||"unbekannt");if(!o.erlaubt)throw new u(429,`Zu viele Schluesselpruefungen von dieser Adresse. Bitte in ${o.retryAfterS} s erneut versuchen.`,o.retryAfterS)}m=l(f,d).then(o=>(n.set(c,o),o)).catch(o=>{throw o instanceof u&&o.httpStatus!==502&&o.httpStatus!==429&&a.set(c,o),o}).finally(()=>{s.delete(c)}),s.set(c,m)}return m},leeren(){n.leeren(),a.leeren(),s.clear()}}}const q=["Dieser Remote-MCP-Server braucht deinen cachly-Schluessel, damit er DEIN Brain oeffnet.","The remote MCP server needs your cachly API key to open YOUR Brain.","","1. Schluessel holen / get a key: https://cachly.dev/setup-ai","2. Kopf setzen / set the header, zum Beispiel / for example:",' claude mcp add --transport http cachly https://mcp.cachly.dev/mcp --header "Authorization: Bearer <key>"',' (Cursor / VS Code: "url" und "headers" in der mcp.json, siehe https://cachly.dev/docs)','3. Mehrere Brains im Konto? Zusaetzlich / more than one Brain? Add: --header "X-Cachly-Instance: <instance-id>"',"","Lieber lokal, ohne Kopf: npx @cachly-dev/mcp-server@latest autopilot"].join(`
2
+ `),k=new Set(["autopilot","brain_from_git","index_project"]);function Q(t){return v.includes(t)&&!k.has(t)}const P=["workspace_path","repo_path","dir","project_dir"];function ee(t){return`Das Werkzeug "${t}" ist ueber den Remote-Server (mcp.cachly.dev) nicht verfuegbar: es liest Dateien auf deinem Rechner oder gehoert nicht zu den Kernwerkzeugen. Lokal geht es: npx @cachly-dev/mcp-server@latest autopilot. / "${t}" is not available on the remote server; run the local server for it.`}function te(t,e){const r=t.instance_id;if(typeof r=="string"&&r.trim()!==""&&r.trim().toLowerCase()!==e)return{fehler:"Die Instanz in instance_id ist nicht die, die dieser Schluessel freigibt. Lass instance_id weg: dieser Server nimmt immer das Brain des Schluessels (oder des Kopfs X-Cachly-Instance)."};const n={...t};for(const a of P)delete n[a];return n.instance_id=e,{args:n}}export{U as ABLEHNUNG_MAX,L as ABLEHNUNG_TTL_MS,q as ANLEITUNG_OHNE_KOPF,b as BegrenzterSpeicher,E as MAX_AUTH_KOPF,k as NUR_LOKAL_WERKZEUGE,P as PFAD_ARGUMENTE,N as PRUEF_FENSTER_MS,B as PRUEF_GRENZE_JE_MINUTE,R as PRUEF_IP_MAX,D as ZUGANG_MAX,I as ZUGANG_TTL_MS,u as ZugangAbgelehnt,X as baueKontext,V as bauePruefGrenze,Y as baueZugangsAufloeser,te as bereinigeArgumente,w as hashDesSchluessels,F as imMandant,G as istMehrmandant,Q as istRemoteErlaubt,J as leseAufruferIp,O as leseBearer,W as leseInstanzKopf,T as mandantKontext,ee as nurLokalText,H as poolSchluessel,Z as setzeMehrmandant};
package/glama.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://glama.ai/mcp/schemas/server.json",
3
- "version": "0.10.259",
3
+ "version": "0.10.260",
4
4
  "maintainers": [
5
5
  "HeinrichNebula"
6
6
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cachly-dev/mcp-server",
3
- "version": "0.10.259",
3
+ "version": "0.10.260",
4
4
  "mcpName": "io.github.cachly-dev/mcp-server",
5
5
  "description": "Memory for coding agents: your AI stores every fix and finds it again when the problem returns. MCP server for Claude Code, Cursor, Copilot, Windsurf, Codex and Gemini CLI, hosted in the EU.",
6
6
  "type": "module",
package/server.json CHANGED
@@ -17,12 +17,12 @@
17
17
  "url": "https://github.com/cachly-dev/cachly-mcp",
18
18
  "source": "github"
19
19
  },
20
- "version": "0.10.259",
20
+ "version": "0.10.260",
21
21
  "packages": [
22
22
  {
23
23
  "registryType": "npm",
24
24
  "identifier": "@cachly-dev/mcp-server",
25
- "version": "0.10.259",
25
+ "version": "0.10.260",
26
26
  "runtimeHint": "npx",
27
27
  "transport": {
28
28
  "type": "stdio"