anyray-connect 0.11.157 → 0.11.158

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var UR="http://localhost:8787",as="anyray-placeholder",xe=e=>{let t=e?.trim();re
5
5
  `,{mode:384})}catch(a){throw await Hr(e,{recursive:!0,force:!0}).catch(()=>{}),a}return async()=>{try{JSON.parse(await cs(t,"utf-8")).nonce===r&&await Hr(e,{recursive:!0,force:!0})}catch{}}}catch(a){if(a.code!=="EEXIST")throw a}if(!(await pO(e).catch(()=>!1)&&await Hr(e,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=n)throw new Error("connect profile is busy; retry the command");await new Promise(a=>setTimeout(a,lO))}}},Gg=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Bo(),r=`${n}.${process.pid}.${sO++}.tmp`;await wc(r,`${JSON.stringify(t,null,2)}
6
6
  `,{mode:384}),await Uu(r,384);try{await he(r,n)}catch(o){throw await Hr(r,{force:!0}).catch(()=>{}),o}},oe=async e=>{let t=await Hg();try{await Gg(e)}finally{await t()}},Kg=async e=>{let t=await Hg();try{let n=await D(),{next:r,result:o}=e(n);return r&&await Gg(r),o}finally{await t()}},Fu=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],Fg="ssoLink",Gu=async()=>{let e=await D();return Fu.some(t=>e[t]!==void 0)?!0:await We()!==void 0},kc=async()=>{let e=await D(),t=Fu.some(a=>e[a]!==void 0),n=e[Fg]!==void 0,r=e.byoUpstream!==void 0,o=await We()!==void 0;if(!t&&!n&&!r&&!o)return!1;if(t||n||r){let a={...e};for(let s of Fu)delete a[s];delete a[Fg],delete a.byoUpstream,delete a.anyrayFleetManaged,await oe(a)}if(await ls(),await We())throw new Error(`could not remove the dev key from ${ee()}`);return!0},Vg=["fallback-bundle.enc","fallback-key","fallback-usage-queue.jsonl"],Cc=async()=>{let e=ee();for(let t of Vg)await Hr(Pn(e,t),{force:!0}).catch(()=>{})},Ku=async()=>{let e=ee(),t=[];for(let n of Vg){let r=Pn(e,n);try{await rO(r),t.push(r)}catch{}}return t},rr=async(e,t,n=!1)=>{let r=await D(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let h of e){let m=h.status==="configured"||h.status==="queued";!t&&m&&(o.add(h.id),a.delete(h.id),s=void 0),t&&(h.status==="reverted"||h.status==="queued")&&(o.delete(h.id),a.add(h.id))}n&&o.clear();let i=[...o].sort(),c=[...r.managedTools??[]].sort(),l=[...a].sort(),d=[...r.revertedTools??[]].sort();if(i.length===c.length&&i.every((h,m)=>h===c[m])&&r.revertedTools!=null&&l.length===d.length&&l.every((h,m)=>h===d[m])&&s===r.offboardedAt)return;let{offboardedAt:f,...p}=r;await oe({...p,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},Ac=async(e=new Date().toISOString())=>{await oe({...await D(),offboardedAt:e})};var Uo=e=>CO(e).replace(/\\/g,"/").toLowerCase(),ju=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",us=e=>`${e}.source`,Xg=e=>/(^|\/)_npx(\/|$)/.test(Uo(e)),Zu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Uo(e)),Ju=e=>{let t=Uo(e),n=[kO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Uo);return Xg(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},yt=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),ps=e=>/[\\/](node|node\.exe)$/i.test(e),or=(e=yt())=>ps(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,Yg=e=>{try{let t=Zg(e);return t.isFile()?t.size:void 0}catch{return}},Xu=e=>{let t=Ke(e);if(Fo(t)==="versions")return t;let n=Ke(t);return Fo(n)==="versions"?n:void 0},Sc=(e,t)=>t!==void 0&&(Ke(e)===t||Ke(Ke(e))===t),AO=e=>{let t=Xu(e);if(!t)return;let n=Re(Ke(t),"bin",ju());try{let r=ds(n);return r===ds(e)||Sc(r,ds(t))?n:void 0}catch{return}},Wo=(e=ee(),t=process.platform)=>{let n=Re(e,"bin",ju(t));try{let r=ds(n),o=ds(Re(e,"versions"));if(Sc(r,o))return n;if(t==="win32"){let a=hO(us(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=Yg(Re(o,a,ju(t)))??Yg(Re(o,a));if(s!==void 0&&s===Zg(n).size)return n}}catch{return}},Gr=(e=yt())=>{let t=or(e),n=Zu(t)||qu(t)?Wo():void 0;return AO(e.execPath)??n??t},zg=(e=yt())=>Gr(e)!==or(e),pn=(e,t=yt())=>{let n=Gr(t);return ps(t.execPath)&&t.scriptPath!==void 0&&n===or(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},qg=(e=yt())=>{let t=Gr(e);return!ps(e.execPath)&&!Ju(t)?Ke(t):Re(ee(),"bin")},vc=async e=>{try{return await mO(e),!0}catch{return!1}},vO=async e=>{let t=await gO(e),n=Ke(t),r=Ke(n),o=Re(r,"package.json"),a=await Yu(o,"utf8"),s=JSON.parse(a);if(typeof s.version!="string"||!/^[0-9A-Za-z][0-9A-Za-z.-]*$/.test(s.version))throw new Error("published package has no safe version");if(!await vc(Re(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},SO=async(e,t)=>{let n=t;for(;;){let r=Re(n,"node_modules",e);if(await vc(Re(r,"package.json")))return r;let o=Ke(n);if(o===n)return;n=o}},EO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Yu(Re(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await SO(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Jg(i,Re(t,s),{recursive:!0}),r.push(i)}}},IO=async(e=yt())=>{let t=Wo();if(t)return{command:t,args:[],entryPath:t};if(!ps(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await vO(e.scriptPath);await Ct();let r=Re(ee(),"bin",`connect-runtime-${n.version}`),o=Re(r,"dist","index.js");if(!await vc(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Vu(a,{recursive:!0,force:!0}),await jg(a,{recursive:!0,mode:448});try{await Jg(n.dist,Re(a,"dist"),{recursive:!0}),await bO(Re(a,"package.json"),await Yu(n.packageJson),{mode:384}),await EO(n.root,Re(a,"node_modules")),await jg(Ke(r),{recursive:!0,mode:448});try{await wO(a,r)}catch(s){if(!await vc(o))throw s}}finally{await Vu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},zu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,xO=e=>{let t=Fo(Ke(Ke(e)));return zu.test(t)?t:void 0},qu=(e,t=ee())=>{let n=Ke(Ke(e));return Uo(Ke(n))===Uo(Re(t,"bin"))&&zu.test(Fo(n))&&Fo(Ke(e))==="dist"&&Fo(e)==="index.js"},Ec=async(e=yt())=>{let t=Re(ee(),"bin"),n=xO(or(e)),r=[];for(let o of await yO(t).catch(()=>[])){if(!zu.test(o)||o===n)continue;let a=Re(t,o);await Vu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},Qg=async(e,t=yt())=>{let n=or(t);if(!ps(t.execPath)||!Xg(n)||Wo())return;let r=await IO(t),o=fO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Qu=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,fs=(e,t)=>[e,...t].map(Qu).join(" "),Tn=(e,t={})=>({...t.matcher!==void 0?{matcher:t.matcher}:{},hooks:[{type:"command",command:e,...t.timeout!==void 0?{timeout:t.timeout}:{},...t.async!==void 0?{async:t.async}:{}}]}),ar=(e,t)=>{if(e===null||typeof e!="object")return!1;let n=e.hooks;return Array.isArray(n)&&n.some(r=>r!==null&&typeof r=="object"&&typeof r.command=="string"&&r.command.includes(t))},Ic=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!ar(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},Ho=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!ar(s,n));return a.length===o.length?!1:(a.length?r[t]=a:delete r[t],Object.keys(r).length===0&&delete e.hooks,!0)},ep=e=>{let t=e.hooks;if(!t)return!1;let n=!1;for(let[r,o]of Object.entries(t)){if(!Array.isArray(o))continue;let a=o.filter(s=>!ar(s,"__anyray-"));a.length!==o.length&&(n=!0,a.length?t[r]=a:delete t[r])}return n&&Object.keys(t).length===0&&delete e.hooks,n};var Xe="__anyray-hook",ew="__anyray-codex-hook",sr="__anyray-prompt-hook",tw="__anyray-shell-pretool",tp="__anyray-shell-run",nw="__anyray-read-pretool",ir="__anyray-refresh",hs=(e,t=[])=>{let{command:n,args:r}=pn([e,...t]);return{command:n,args:r}},Lt=(e,t=[])=>{let n=hs(e,t);return[n.command,...n.args].map(Qu).join(" ")},xc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Lt(t,n),rw=()=>Lt("print-key"),Oe=()=>Gr(),Ve=Ju,le=()=>!Ve(Oe()),Kr=async()=>{if(!le())return!1;try{return await RO(Oe()),!0}catch{return!1}},cr="__anyray-mcp-server",je=e=>hs(cr,[e]),OO=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),Rc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=je(t);return n.command===r.command&&OO(n.args,r.args)},qt=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(typeof n.command!="string"||!Array.isArray(n.args)||!n.args.every(o=>typeof o=="string"))return!1;let r=n.args;return(r.length===2||r.length===3)&&r.at(-2)===cr&&r.at(-1)===t};var X=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,de=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Vr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],ow=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Oc=[...Vr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],_O=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
7
7
  `)},fn=(e,t={})=>{let n=e.byoUpstream,r=!n&&X(e,"anthropic"),o=de({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1&&!((r||n)&&e.viaLocalProxy),s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=_O(o,r,a?e.clientKey:void 0,n?.url);return{env:{ANTHROPIC_BASE_URL:e.anthropicBaseUrl,...c?{ANTHROPIC_CUSTOM_HEADERS:c}:{},...n&&s?{ANTHROPIC_AUTH_TOKEN:n.key}:{},...r||n||!s?{}:{ANTHROPIC_AUTH_TOKEN:e.clientKey??e.placeholderKey},...n?{}:{ENABLE_TOOL_SEARCH:"true"},...n?{}:{_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL:"1"},...i!==void 0?{CLAUDE_CODE_MAX_CONTEXT_TOKENS:String(i)}:{}},subscription:r,byoUpstream:!!n,meta:o,headers:c}};import{z as np}from"zod";var PO=5e3,TO=1e3,LO=1e8,DO=np.object({modelContext:np.object({contextTokens:np.number().int().min(TO).max(LO)}).optional()}),aw=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},sw=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??PO,a=new AbortController,s=setTimeout(()=>a.abort(),o);try{let i=`${e}/connect/policy?model=${encodeURIComponent(n)}`,c=await fetch(i,{method:"GET",headers:{"x-anyray-api-key":t},signal:a.signal});if(!c.ok)return;let l=DO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var NO=1e6,ms="[1m]",$O=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},iw=(e,t)=>!e||t===void 0?{}:$O(e)?{envTokens:t}:t<NO?{}:e.toLowerCase().endsWith(ms)?{}:{model:`${e}${ms}`},cw=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(ms))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(ms))return e.slice(0,-ms.length)};import{platform as MO}from"node:os";var Dt=(e=MO())=>{switch(e){case"darwin":return"/Library/Application Support/ClaudeCode/managed-settings.json";case"win32":return"C:\\Program Files\\ClaudeCode\\managed-settings.json";default:return"/etc/claude-code/managed-settings.json"}};var Ln=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],_c=e=>typeof e=="string"&&e.trim()!=="",BO=(e,t)=>typeof e[t]=="string"&&!_c(e[t]),lw=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},FO=()=>F(Dt()).catch(()=>({})),dw=async(e={})=>{let t=e.env??process.env,n=lw(e.userSettings??{}),r=lw(await(e.readManaged??FO)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of Ln)_c(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Dt()})`,repairable:!1}):_c(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!BO(n,a)&&_c(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},rp=e=>`${e.name} is set (${e.source}) \u2014 Claude Code sends requests straight to ${e.cloud} and ignores the gateway routing written here, so none of its traffic reaches Anyray until that setting is removed`,op=e=>"Fix: remove the setting where it is set"+(e.some(t=>t.kind==="managed")?" (the managed settings file is IT-owned \u2014 ask your admin)":"")+", then restart Claude Code. The gateway can serve Bedrock/Vertex itself once its provider is configured \u2014 see the Bedrock page in the Anyray docs.",uw=e=>`Disabled direct ${e.cloud} mode: ${e.name} was set (${e.source}), which would bypass the gateway route entirely \u2014 pinned it empty in settings.json (the env block outranks shell exports, and '' is Claude Code's documented unset). Delete the original setting to drop the pin.`;var UO=Ln.map(e=>e.name),WO=Oc.filter(e=>!UO.includes(e)),pw=e=>typeof e=="string"&&e.trim()!=="",fw=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},HO=(e,t,n)=>{if(typeof e!="string"||typeof t!="string")return!1;let r=o=>n?o.trim().replace(/\/+$/,""):o.trim();return r(e)===r(t)},GO=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},ap=()=>F(Dt()).catch(()=>({})),hw=ap,KO=e=>{let t=e.hooks;if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t.PostToolUse;return Array.isArray(n)&&n.some(r=>ar(r,Xe))},mw=async(e={})=>{let t=await(e.readManaged??hw)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!KO(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},Pc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Dt()}) \u2014 Claude Code skips every hook and the status line, including Anyray's savings hook`:e.state==="restricted_dropping_ours"?`allowManagedHooksOnly is true in managed settings (${Dt()}), but that file does not carry the Anyray PostToolUse hook \u2014 Claude Code silently drops the user-scope hook Connect installed`:"Claude Code managed hook policy allows the Anyray hook lane",Tc=e=>e.state==="disabled"?"Fix: ask the MDM owner to drop `disableAllHooks`, then restart Claude Code. Connect never overrides machine policy.":e.state==="restricted_dropping_ours"?"Fix: ask the MDM owner to drop `allowManagedHooksOnly`, or add the Anyray hooks to the managed file. `anyray-connect managed --print --sso <link> --bin <path>` emits the credential-free block; then restart Claude Code.":"No action required.",yw=async(e={})=>{let t=fw(e.userSettings??{}),n=fw(await(e.readManaged??hw)().catch(()=>({}))),r=[];for(let o of WO){if(!pw(n[o])||!pw(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(HO(n[o],t[o],a))continue;let s=a?GO(n[o]):void 0;r.push({name:o,source:`managed settings (${Dt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},gw=e=>e.routing?`${e.name} is set to a different value (${e.source}), which outranks the routing written in settings.json \u2014 Claude Code sends its traffic to ${e.managedOrigin??"that endpoint"} instead, so none of it reaches Anyray until the managed value changes`:`${e.name} is set to a different value (${e.source}), which outranks the value written in settings.json \u2014 Claude Code uses the managed one, so the behavior this key controls is not the one connect configured`,ww=e=>"Fix: the managed settings file is IT-owned \u2014 ask your admin to "+(e.some(t=>t.routing)?"point it at the Anyray gateway (`anyray-connect managed --print` emits the block to deploy) or drop the key so per-user setup governs":"drop the key so per-user setup governs")+", then restart Claude Code.";import{homedir as VO}from"node:os";import{join as jO}from"node:path";import{readFile as YO}from"node:fs/promises";var ot=e=>!!e.keyRefreshEnabled;var ZO=400,bw=async()=>{try{let e=jO(VO(),".claude","settings.json"),n=JSON.parse(await YO(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
8
- `)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},kw=async()=>{try{let e=await D();return e.gateway?{origin:new URL(e.gateway).origin,metadata:de({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},at=async(e="auto")=>e==="profile"?kw():e==="claude"?bw():await bw()??await kw(),Lc=async(e={})=>{let t=e.readTarget??at,n=e.loadProfile??D,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return ot(r)&&r.fallbackPort&&a.add(`http://${mt}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},Qt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},Dc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),ZO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Qt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var Dn=()=>$c(Nc(),".claude","settings.json"),ys=()=>$c(Nc(),".claude.json"),JO=Oc,lr="anyray",XO=()=>({type:"stdio",...je("claude"),alwaysLoad:!0}),jr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zO=e=>{if("mcpServers"in e&&!jr(e.mcpServers))return"conflict";let t=jr(e.mcpServers)?{...e.mcpServers}:{},n=t[lr];return n!==void 0&&!qt(n,"claude")?"conflict":(t[lr]=XO(),e.mcpServers=t,"installed")},Cw=e=>{let t=e.mcpServers;return!t||!(lr in t)||!qt(t[lr],"claude")?!1:(delete t[lr],Object.keys(t).length===0&&delete e.mcpServers,!0)},qO=e=>{Ic(e,"PostToolUse",Xe,Tn(Lt(Xe),{matcher:"*"})),Ic(e,"UserPromptSubmit",sr,Tn(Lt(sr)))},QO=e=>{Ic(e,"SessionStart",ir,Tn(Lt(ir),{async:!0}))},Sw=e=>Ho(e,"SessionStart",ir),Aw=e=>{let t=Ho(e,"PostToolUse",Xe),n=Ho(e,"UserPromptSubmit",sr),r=Sw(e);return t||n||r},e_="print-key",t_=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Yr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===e_&&t_(t)},n_=async(e,t)=>{let n=(await Wr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of JO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},r_=e=>typeof e.apiKeyHelper=="string"&&!Yr(e),Ew=async e=>{let t=await ap(),n=async()=>t,[r,o,a]=await Promise.all([dw({userSettings:e,readManaged:n}),yw({userSettings:e,readManaged:n}).catch(()=>[]),mw({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},vw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await Ew(e),o=op(t),a=ww(n);return{routingOverrides:[...t.map(i=>({problem:rp(i),fix:i.repairable?"Fix: run `anyray-connect doctor --repair` (or re-run `anyray-connect`) \u2014 apply disables this switch by pinning it empty in settings.json.":o,repairable:i.repairable})),...n.map(i=>({problem:gw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},dr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=$c(Nc(),".claude"),t=await R(e);return{installed:t,detail:t?Dn():"no ~/.claude directory"}},async apply(e,t){let n=Dn(),r=await F(n),o=aw(r),a=await sw(e.origin,e.clientKey,o),s=iw(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=fn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await Ew(r),h=f.filter(x=>!x.repairable),m=f.filter(x=>x.repairable),w=[...h.map(x=>`WARNING: ${rp(x)}.`),...h.length?[op(h)]:[],...p.state==="fine"?[]:[`WARNING: ${Pc(p)}.`,Tc(p)],...m.map(x=>uw(x)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let y=r.env??{};r.env={...y,...i};let g=r.env;for(let{name:x}of Ln)m.some(P=>P.name===x)?g[x]="":g[x]===""&&(process.env[x]??"").trim()===""&&delete g[x];if(u||delete g.ANTHROPIC_CUSTOM_HEADERS,c&&(y.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete g.ANTHROPIC_AUTH_TOKEN),l)for(let x of ow)delete g[x];let b=!!e.clientKey,A=le(),v=r_(r);!c&&!l&&b&&A&&!v?(r.apiKeyHelper=rw(),g.ANTHROPIC_AUTH_TOKEN="",w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Yr(r)&&delete r.apiKeyHelper,v&&!c&&!l&&b&&A&&w.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&A?(QO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Sw(r),le()?(qO(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(Aw(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await J(n,r);let I=[n],C=ys();try{let x=await F(C),P=!1;le()?zO(x)==="conflict"?w.push(`MCP name conflict in ${C}: mcpServers.${lr} is not owned by Anyray Connect, so it was left untouched.`):(P=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):P=Cw(x),P&&(await J(C,x),I.push(C))}catch(x){w.push(`Could not register the Anyray MCP server in ${C} (${x instanceof Error?x.message:String(x)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:I}},skillsDir(){return $c(Nc(),".claude","skills")},async watchPaths(){return[Dn(),ys()]},async pointsAt(e){let t=Dn();if(!await R(t))return!1;try{let o=(await F(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await F(Dn()).catch(()=>({}));return vw(e)},async routingOverrides(){let e=await F(Dn()).catch(()=>({}));return(await vw(e)).routingOverrides},async mcpStatus(){let e=ys();if(!await R(e))return{registered:!1,command:null};try{let r=(await F(e)).mcpServers?.[lr];return!r||!qt(r,"claude")?{registered:!1,command:null}:{registered:!0,command:typeof r.command=="string"?r.command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=Dn();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!jr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>ar(c,Xe))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>ar(c,Xe)&&jr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>jr(l)&&xc(l.command,Xe))))}}catch{e="unreadable"}let r,o=!0,a=ys();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!jr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[lr];r=i===void 0?"missing":qt(i,"claude")?"owned":"foreign",r==="owned"&&(o=Rc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Kr()?"owned":"missing",beacon_target:await Lc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await F(Dn()),t=jr(e.env)?e.env:{},n=typeof t.ANTHROPIC_CUSTOM_HEADERS=="string"?t.ANTHROPIC_CUSTOM_HEADERS:"";if(/^x-anyray-custom-host:/m.test(n))return["byo"];if(/^x-anyray-auth-mode:\s*passthrough$/m.test(n))return["subscription"];if(typeof t.ANTHROPIC_AUTH_TOKEN=="string"||typeof e.apiKeyHelper=="string")return["api_key"]}catch{}return["unknown"]},async revert(e){let t=Dn();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await F(t),r=n.env,o=Aw(n),a=Yr(n);a&&delete n.apiKeyHelper;let s=r?await n_(t,r):[],i=cw(typeof n.model=="string"?n.model:void 0,(await Wr(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await J(t,n,{backup:!1});let c=[`removed Anyray keys from ${t}`];i!==void 0&&c.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&c.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&c.push("Removed the Anyray apiKeyHelper."),s.length&&c.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let l=ys();try{let d=await F(l);Cw(d)&&(await J(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await se(t),{status:"reverted",messages:c,changedFiles:[t]}}};var ke="0.11.157";var hn=e=>{let{command:t,args:n}=pn([e]);return{command:t,args:n}},ur=()=>Gr();import{homedir as Iw,userInfo as o_}from"node:os";var gs=()=>{try{return Iw()!==o_().homedir}catch{return!1}},Go=e=>[`Skipped ${e} \u2014 HOME (${Iw()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var gt=(e=process.env)=>e.CODESPACES==="true"||e.CODESPACE_NAME?"codespaces":e.REMOTE_CONTAINERS==="true"||e.REMOTE_CONTAINERS_IPC||e.DEVCONTAINER?"devcontainer":e.SSH_CONNECTION||e.SSH_TTY?"ssh":null,Zr=(e=process.env)=>gt(e)!==null,At=e=>e==="codespaces"||e==="devcontainer",pr=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var lp="__anyray-fallback-proxy",ks="ai.anyray.connect.fallback",fr="anyray-fallback",Pw=ks,Ae=8785,Cs=60,dp="x-anyray-local",up=()=>hn(lp),xw=ur,Bc=async(e=Ae)=>{let t=n=>new Promise(r=>{let o=i_();o.once("error",()=>r(!1)),o.listen(n,"127.0.0.1",()=>o.close(()=>r(!0)))});for(let n=e;n<e+20;n++)if(await t(n))return n;return e},Ce=async(e,t=1500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}/__anyray/health`,{signal:n.signal});return o.ok?await o.json():null}catch{return null}finally{clearTimeout(r)}},Yo=()=>jo(bs(),"Library","LaunchAgents",`${Pw}.plist`),As=()=>jo(bs(),".anyray","logs"),ws=()=>jo(As(),"connect-daemon.log"),Tw=async(e,t=1048576)=>{await Ow(e).then(r=>r.size,()=>0)>t&&await s_(e).catch(()=>{})},Zo=()=>jo(bs(),".config","systemd","user",`${fr}.service`),sp=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vs=(e=up())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${sp(o)}</string>`).join(`
8
+ `)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},kw=async()=>{try{let e=await D();return e.gateway?{origin:new URL(e.gateway).origin,metadata:de({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},at=async(e="auto")=>e==="profile"?kw():e==="claude"?bw():await bw()??await kw(),Lc=async(e={})=>{let t=e.readTarget??at,n=e.loadProfile??D,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return ot(r)&&r.fallbackPort&&a.add(`http://${mt}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},Qt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},Dc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),ZO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Qt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var Dn=()=>$c(Nc(),".claude","settings.json"),ys=()=>$c(Nc(),".claude.json"),JO=Oc,lr="anyray",XO=()=>({type:"stdio",...je("claude"),alwaysLoad:!0}),jr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zO=e=>{if("mcpServers"in e&&!jr(e.mcpServers))return"conflict";let t=jr(e.mcpServers)?{...e.mcpServers}:{},n=t[lr];return n!==void 0&&!qt(n,"claude")?"conflict":(t[lr]=XO(),e.mcpServers=t,"installed")},Cw=e=>{let t=e.mcpServers;return!t||!(lr in t)||!qt(t[lr],"claude")?!1:(delete t[lr],Object.keys(t).length===0&&delete e.mcpServers,!0)},qO=e=>{Ic(e,"PostToolUse",Xe,Tn(Lt(Xe),{matcher:"*"})),Ic(e,"UserPromptSubmit",sr,Tn(Lt(sr)))},QO=e=>{Ic(e,"SessionStart",ir,Tn(Lt(ir),{async:!0}))},Sw=e=>Ho(e,"SessionStart",ir),Aw=e=>{let t=Ho(e,"PostToolUse",Xe),n=Ho(e,"UserPromptSubmit",sr),r=Sw(e);return t||n||r},e_="print-key",t_=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Yr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===e_&&t_(t)},n_=async(e,t)=>{let n=(await Wr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of JO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},r_=e=>typeof e.apiKeyHelper=="string"&&!Yr(e),Ew=async e=>{let t=await ap(),n=async()=>t,[r,o,a]=await Promise.all([dw({userSettings:e,readManaged:n}),yw({userSettings:e,readManaged:n}).catch(()=>[]),mw({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},vw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await Ew(e),o=op(t),a=ww(n);return{routingOverrides:[...t.map(i=>({problem:rp(i),fix:i.repairable?"Fix: run `anyray-connect doctor --repair` (or re-run `anyray-connect`) \u2014 apply disables this switch by pinning it empty in settings.json.":o,repairable:i.repairable})),...n.map(i=>({problem:gw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},dr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=$c(Nc(),".claude"),t=await R(e);return{installed:t,detail:t?Dn():"no ~/.claude directory"}},async apply(e,t){let n=Dn(),r=await F(n),o=aw(r),a=await sw(e.origin,e.clientKey,o),s=iw(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=fn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await Ew(r),h=f.filter(x=>!x.repairable),m=f.filter(x=>x.repairable),w=[...h.map(x=>`WARNING: ${rp(x)}.`),...h.length?[op(h)]:[],...p.state==="fine"?[]:[`WARNING: ${Pc(p)}.`,Tc(p)],...m.map(x=>uw(x)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let y=r.env??{};r.env={...y,...i};let g=r.env;for(let{name:x}of Ln)m.some(P=>P.name===x)?g[x]="":g[x]===""&&(process.env[x]??"").trim()===""&&delete g[x];if(u||delete g.ANTHROPIC_CUSTOM_HEADERS,c&&(y.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete g.ANTHROPIC_AUTH_TOKEN),l)for(let x of ow)delete g[x];let b=!!e.clientKey,A=le(),v=r_(r);!c&&!l&&b&&A&&!v?(r.apiKeyHelper=rw(),g.ANTHROPIC_AUTH_TOKEN="",w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Yr(r)&&delete r.apiKeyHelper,v&&!c&&!l&&b&&A&&w.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&A?(QO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Sw(r),le()?(qO(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(Aw(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await J(n,r);let I=[n],C=ys();try{let x=await F(C),P=!1;le()?zO(x)==="conflict"?w.push(`MCP name conflict in ${C}: mcpServers.${lr} is not owned by Anyray Connect, so it was left untouched.`):(P=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):P=Cw(x),P&&(await J(C,x),I.push(C))}catch(x){w.push(`Could not register the Anyray MCP server in ${C} (${x instanceof Error?x.message:String(x)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:I}},skillsDir(){return $c(Nc(),".claude","skills")},async watchPaths(){return[Dn(),ys()]},async pointsAt(e){let t=Dn();if(!await R(t))return!1;try{let o=(await F(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await F(Dn()).catch(()=>({}));return vw(e)},async routingOverrides(){let e=await F(Dn()).catch(()=>({}));return(await vw(e)).routingOverrides},async mcpStatus(){let e=ys();if(!await R(e))return{registered:!1,command:null};try{let r=(await F(e)).mcpServers?.[lr];return!r||!qt(r,"claude")?{registered:!1,command:null}:{registered:!0,command:typeof r.command=="string"?r.command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=Dn();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!jr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>ar(c,Xe))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>ar(c,Xe)&&jr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>jr(l)&&xc(l.command,Xe))))}}catch{e="unreadable"}let r,o=!0,a=ys();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!jr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[lr];r=i===void 0?"missing":qt(i,"claude")?"owned":"foreign",r==="owned"&&(o=Rc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Kr()?"owned":"missing",beacon_target:await Lc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await F(Dn()),t=jr(e.env)?e.env:{},n=typeof t.ANTHROPIC_CUSTOM_HEADERS=="string"?t.ANTHROPIC_CUSTOM_HEADERS:"";if(/^x-anyray-custom-host:/m.test(n))return["byo"];if(/^x-anyray-auth-mode:\s*passthrough$/m.test(n))return["subscription"];if(typeof t.ANTHROPIC_AUTH_TOKEN=="string"||typeof e.apiKeyHelper=="string")return["api_key"]}catch{}return["unknown"]},async revert(e){let t=Dn();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await F(t),r=n.env,o=Aw(n),a=Yr(n);a&&delete n.apiKeyHelper;let s=r?await n_(t,r):[],i=cw(typeof n.model=="string"?n.model:void 0,(await Wr(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await J(t,n,{backup:!1});let c=[`removed Anyray keys from ${t}`];i!==void 0&&c.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&c.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&c.push("Removed the Anyray apiKeyHelper."),s.length&&c.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let l=ys();try{let d=await F(l);Cw(d)&&(await J(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await se(t),{status:"reverted",messages:c,changedFiles:[t]}}};var ke="0.11.158";var hn=e=>{let{command:t,args:n}=pn([e]);return{command:t,args:n}},ur=()=>Gr();import{homedir as Iw,userInfo as o_}from"node:os";var gs=()=>{try{return Iw()!==o_().homedir}catch{return!1}},Go=e=>[`Skipped ${e} \u2014 HOME (${Iw()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var gt=(e=process.env)=>e.CODESPACES==="true"||e.CODESPACE_NAME?"codespaces":e.REMOTE_CONTAINERS==="true"||e.REMOTE_CONTAINERS_IPC||e.DEVCONTAINER?"devcontainer":e.SSH_CONNECTION||e.SSH_TTY?"ssh":null,Zr=(e=process.env)=>gt(e)!==null,At=e=>e==="codespaces"||e==="devcontainer",pr=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var lp="__anyray-fallback-proxy",ks="ai.anyray.connect.fallback",fr="anyray-fallback",Pw=ks,Ae=8785,Cs=60,dp="x-anyray-local",up=()=>hn(lp),xw=ur,Bc=async(e=Ae)=>{let t=n=>new Promise(r=>{let o=i_();o.once("error",()=>r(!1)),o.listen(n,"127.0.0.1",()=>o.close(()=>r(!0)))});for(let n=e;n<e+20;n++)if(await t(n))return n;return e},Ce=async(e,t=1500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}/__anyray/health`,{signal:n.signal});return o.ok?await o.json():null}catch{return null}finally{clearTimeout(r)}},Yo=()=>jo(bs(),"Library","LaunchAgents",`${Pw}.plist`),As=()=>jo(bs(),".anyray","logs"),ws=()=>jo(As(),"connect-daemon.log"),Tw=async(e,t=1048576)=>{await Ow(e).then(r=>r.size,()=>0)>t&&await s_(e).catch(()=>{})},Zo=()=>jo(bs(),".config","systemd","user",`${fr}.service`),sp=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vs=(e=up())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${sp(o)}</string>`).join(`
9
9
  `);return`<?xml version="1.0" encoding="UTF-8"?>
10
10
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
11
11
  <plist version="1.0">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anyray-connect",
3
- "version": "0.11.157",
3
+ "version": "0.11.158",
4
4
  "description": "Anyray connect \u2014 points local coding tools (Claude Code, Cursor, Windsurf, SDKs) at the Anyray gateway through supported configuration and enrolled personal authentication.",
5
5
  "type": "module",
6
6
  "bin": {