anyray-connect 0.11.412 → 0.11.413

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 +3 -3
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  var Are=Object.defineProperty;var U=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var gm=(e,t)=>{for(var n in t)Are(e,n,{get:t[n],enumerable:!0})};var vre,il,fB,Cre,Sre,St,yo,Ot,gE,_re,ru,jo,bt,dt=U(()=>{"use strict";vre="http://localhost:8787",il="anyray-placeholder",fB=/^ark_[A-Za-z0-9_-]{20,512}$/,Cre="ark_svc_",Sre=/^ark_svc_[A-Za-z0-9_-]{20,512}$/,St=e=>{let t=e?.trim();return!!(t&&fB.test(t))},yo=e=>{let t=e?.trim();if(t){if(Sre.test(t))return"service";if(!t.startsWith(Cre))return fB.test(t)?"personal":void 0}},Ot=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},gE=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,_re=new Set(["localhost","127.0.0.1","[::1]","::1","0.0.0.0"]),ru=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!_re.has(n)}catch{return!1}},jo=e=>{let t=Ot(e||process.env.ANYRAY_GATEWAY_URL||vre),n;try{n=new URL(t)}catch{throw new Error(`invalid gateway URL: "${t}" (expected e.g. http://localhost:8787)`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`invalid gateway URL: "${t}" \u2014 must start with http:// or https://`);return t},bt=(e={})=>{let t=jo(e.origin),n=e.placeholderKey?.trim()||il,r=e.clientKey?.trim()||process.env.ANYRAY_CLIENT_KEY?.trim()||void 0,o={user:e.user?.trim()||void 0,team:e.team?.trim()||void 0,intent:gE(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:gE(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:gE(e.session,"ANYRAY_METADATA_SESSION")},a=e.subscription?"subscription":e.placeholder?"placeholder":e.seat?"auto":"placeholder";return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:n,clientKey:r,keyKind:yo(r),authMode:a,byoUpstream:e.byoUpstream,seat:a==="auto"?e.seat:void 0,metadata:o}}});var pB,mB,Fw,Uw=U(()=>{"use strict";pB="/connect/optimize-output",mB=e=>({matcher:"*",hooks:[{type:"http",url:`${e}${pB}`,timeout:2,headers:{"x-anyray-api-key":"$ANYRAY_CLIENT_KEY",Authorization:"Bearer $ANTHROPIC_AUTH_TOKEN"},allowedEnvVars:["ANYRAY_CLIENT_KEY","ANTHROPIC_AUTH_TOKEN"]}]}),Fw=e=>{if(!e||typeof e!="object")return!1;let t=e;if(t.type!=="http"||typeof t.url!="string")return!1;try{let n=new URL(t.url);return["http:","https:"].includes(n.protocol)&&n.pathname===pB&&!n.search&&!n.hash}catch{return!1}}});var wE,Hw,Gw=U(()=>{"use strict";wE=(e,t)=>{let n="",r="",o=t;for(;o<e.length&&e[o]!==" ";){let a=e[o];if(a==='"'){for(o+=1;;){if(o>=e.length)return;let s=o===t+1&&e[o+1]==="\\";if(e[o]==="\\"&&!s&&(e[o+1]==='"'||e[o+1]==="\\"))n+=e[o+1],o+=2;else{if(e[o]==='"')break;n+=e[o],o+=1}}o+=1}else{if(/\s/.test(a))return;n+=a,r+=a,o+=1}}return o===t?void 0:{value:n,end:o,unquoted:r}},Hw=e=>{if(e==="")return[];let t=[],n=0;for(;;){let r=wE(e,n);if(!r)return;if(t.push(r.value),r.end===e.length)return t;n=r.end+1}}});import{randomUUID as Ere}from"node:crypto";import{lstat as bE,open as Ire,readFile as kE,rename as Ww,rm as xre,writeFile as Rre}from"node:fs/promises";import{platform as hB}from"node:os";var yB,Ore,Bi,cl,Tre,ze,_n=U(()=>{"use strict";yB=e=>e?.code==="ENOENT",Ore=new Set(["EBUSY","EXDEV","ETXTBSY"]),Bi=async(e,t=hB())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},cl=class extends Error{recoveryCopy;code="ANYRAY_PUBLISH_CONFLICT";constructor(t){super("destination changed before publication"),this.recoveryCopy=t,this.name="PublishConflictError"}},Tre=async(e,t,n={})=>{let r=await kE(e),o;try{o=await kE(t)}catch(s){if(!yB(s))throw s;await Rre(t,r);return}let a=async s=>{let i=await Ire(t,"r+");try{await i.write(s,0,s.length,0),await i.truncate(s.length),await Bi(i)}finally{await i.close()}};try{if(await a(r),await n.corruptAfterWrite?.(t),!(await kE(t)).equals(r))throw Object.assign(new Error("in-place publication did not persist"),{code:"EIO"})}catch(s){throw await a(o).catch(()=>{}),s}},ze=async(e,t,n=hB(),r={})=>{let o=r.rename??Ww;if(n!=="win32"){try{await o(e,t)}catch(i){if(!Ore.has(i?.code??""))throw i;await Tre(e,t,r)}return}let a=`${t}.anyray-old-${process.pid}-${Ere()}`,s=!1;try{let i=await bE(t);if(!i.isFile()&&!i.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await Ww(t,a),s=!0}catch(i){if(!yB(i))throw i}if(s&&r.verifyDisplaced){let i=!1;try{i=await r.verifyDisplaced(a)}catch{i=!1}if(!i){let c=!1;try{await bE(t),c=!0}catch{c=!1}if(c)throw new cl(a);try{await o(a,t)}catch(l){let d=l?.code==="EEXIST";if(!d)try{await bE(t),d=!0}catch{d=!1}throw d?new cl(a):new Error(`destination changed before publication and could not be restored; recovery copy remains at ${a}`,{cause:l})}throw new cl}}try{await Ww(e,t)}catch(i){if(s)try{await Ww(a,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${a}`)}throw i}s&&await xre(a,{force:!0})}});var go,ll=U(()=>{"use strict";go=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}});var Pre,wm,AE=U(()=>{"use strict";Pre=new Set(["EPERM","EACCES"]),wm=(e,t=process.platform)=>t==="win32"&&e!==void 0&&Pre.has(e)});import{writeFile as Kw,readFile as km,chmod as bB,stat as _E,mkdir as kB,rename as AB,rm as dl,unlink as vE}from"node:fs/promises";import{AsyncLocalStorage as Lre}from"node:async_hooks";import{randomUUID as vB}from"node:crypto";import{homedir as Vw}from"node:os";import{join as Sa}from"node:path";var te,Zw,EE,bm,Nre,CB,SB,gB,Dre,Mre,Ne,Yw,$n,Am,$re,IE,J,Ko,Wn,En,Bre,Fre,_B,Ure,Hre,jw,EB,Gre,Wre,wo,pt,xE,wn,jre,CE,Kre,Tt,kt,vm,SE,wB,Cm,Xw,Jw,IB,Sm,_a,zw,ue=U(()=>{"use strict";_n();ll();AE();te=()=>Sa(Vw(),".anyray"),Zw=async()=>{let e=te();try{if((await _E(e)).isDirectory())return Sa(e,"connect.json")}catch{}return e},EE=()=>Sa(te(),"dev-key.pem"),bm=()=>Sa(Vw(),".anyray-connect-profile.migrating"),Nre=()=>Sa(Vw(),".anyray-connect-layout.lock"),CB=async e=>{let t=await pt(Nre(),{busyMessage:"the Anyray state directory is busy; retry the command"});try{return await e()}finally{await t()}},SB=e=>_E(e).then(t=>t.isDirectory(),()=>!1),gB=async(e,t)=>{if(t.code==="ENOENT")return!0;if(await SB(e))return!1;throw t},Dre=async(e,t)=>{let n;try{n=await km(e)}catch(o){return gB(e,o)}let r=`${bm()}.${process.pid}.${vB()}.tmp`;try{await(t.writeFile??Kw)(r,n,{mode:384}),await AB(r,bm())}catch(o){throw await vE(r).catch(()=>{}),o}await t.beforeUnlink?.();try{await vE(e)}catch(o){return gB(e,o)}return!0},Mre=async e=>{let t=te();if(await e.afterInspect?.(),!!await Dre(t,e)){await kB(t,{recursive:!0,mode:448});try{await AB(bm(),Sa(t,"connect.json"))}catch(n){if(n.code==="ENOENT")return;throw n}}},Ne=async(e={})=>{await SB(te())||await CB(()=>Mre(e))},Yw=async e=>{await Ne();let t=EE();await Kw(t,e,{mode:384}),await bB(t,384)},$n=async()=>{try{let e=await km(EE(),"utf-8");return e.trim()?e:void 0}catch{return}},Am=async()=>{await dl(EE(),{force:!0}).catch(()=>{})},$re=(e,t,n)=>e==="ENOENT"||e==="EISDIR"||n&&wm(e,t),IE=async(e={})=>{let t=e.readFile??(r=>km(r,"utf-8")),n=e.platform??process.platform;for(let r=0;;r++){let o=await Zw();await e.afterResolve?.();try{return await t(o)}catch(a){let s=a.code;if(!$re(s,n,o===te()))throw a;let i=await t(bm()).catch(c=>{if(c.code!=="ENOENT")throw c});if(i!==void 0)return i;if(r>0)throw a}}},J=async()=>{try{let e=await IE(),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}},Ko=class extends Error{reason;constructor(t){super(`the connect profile could not be ${t==="read"?"read":"parsed"}`),this.reason=t,this.name="ProfileUnreadableError"}},Wn=async(e={})=>{let t;try{t=await IE(e)}catch(r){return r?.code==="ENOENT"?{state:"absent"}:{state:"unreadable",reason:"read"}}let n;try{n=JSON.parse(t)}catch{return{state:"unreadable",reason:"parse"}}return n===null||typeof n!="object"||Array.isArray(n)?{state:"unreadable",reason:"parse"}:{state:"present",profile:n}},En=async()=>{let e=await Wn();if(e.state==="absent")return{};if(e.state==="unreadable")throw new Ko(e.reason);return e.profile},Bre=0,Fre=3e4,_B=5e3,Ure=25,Hre=()=>Sa(Vw(),".anyray-connect-profile.lock"),jw=new Lre,EB=async e=>{let t=await km(Sa(e,"owner.json"),"utf-8").catch(()=>{}),n=await _E(e,{bigint:!0});return{dev:n.dev,ino:n.ino,mtimeNs:n.mtimeNs,owner:t}},Gre=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.mtimeNs===t.mtimeNs&&e.owner===t.owner,Wre=async(e,t)=>{let n=await EB(e);if(n.owner!==void 0)try{let o=JSON.parse(n.owner);if(typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0)return go(o.pid)?void 0:n}catch{}let r=Number(n.mtimeNs/1000000n);return Date.now()-r>t?n:void 0},wo=class extends Error{constructor(t){super(t),this.name="LockBusyError"}},pt=async(e,t={},n={})=>{let r=t.waitMs??_B,o=t.staleMs??Fre,a=Sa(e,"owner.json"),s=Date.now()+r,i=n.mkdir??kB,c=n.platform??process.platform,l;for(;;){let d=vB();try{await i(e,{mode:448});let f=`${a}.anyray-tmp-${process.pid}-${d}`;try{await Kw(f,`${JSON.stringify({pid:process.pid,nonce:d})}
3
3
  `,{flag:"wx",mode:384}),await ze(f,a)}catch(p){throw await dl(f,{force:!0}).catch(()=>{}),await dl(e,{recursive:!0,force:!0}).catch(()=>{}),p}return async()=>{try{JSON.parse(await km(a,"utf-8")).nonce===d&&await dl(e,{recursive:!0,force:!0})}catch{}}}catch(f){let p=f.code;if(wm(p,c))l=f;else{if(p!=="EEXIST")throw f;l=void 0}}let u=await Wre(e,o).catch(()=>{});if(u){await n.beforeReclaim?.();let f=await EB(e).catch(()=>{});if(f&&Gre(u,f)&&await dl(e,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))continue}if(Date.now()>=s)throw l||new wo(t.busyMessage??`${e} is busy; retry the command`);await new Promise(f=>setTimeout(f,Ure))}},xE=(e=_B)=>pt(Hre(),{waitMs:e,busyMessage:"connect profile is busy; retry the command"}),wn=async(e,t={})=>{if(jw.getStore()===!0)return e();let n=await xE(t.waitMs);try{return await jw.run(!0,e)}finally{await n()}},jre=(e,t)=>{if(e===void 0)return t;if(t===void 0)return e;let n=Date.parse(e),r=Date.parse(t);return Number.isFinite(r)?Number.isFinite(n)?r>n?t:e:t:e},CE=async(e,t={})=>{let n=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));await CB(async()=>{await Kre(n,t),await dl(bm(),{force:!0}).catch(()=>{})})},Kre=async(e,t)=>{let n=await Zw(),r=await IE().then(s=>JSON.parse(s).retrievalTransportSwitchAt).catch(()=>{}),o=jre(typeof r=="string"?r:void 0,e.retrievalTransportSwitchAt);o!==void 0&&(e.retrievalTransportSwitchAt=o);let a=`${n}.${process.pid}.${Bre++}.tmp`;try{await(t.writeFile??Kw)(a,`${JSON.stringify(e,null,2)}
4
4
  `,{mode:384}),await bB(a,384),await ze(a,n)}catch(s){throw await vE(a).catch(()=>{}),s}},Tt=async(e,t={})=>{if(jw.getStore()===!0){await CE(e,t);return}let n=await xE();try{await CE(e,t)}finally{await n()}},kt=async e=>{let t=async()=>{let r=await En(),{next:o,result:a}=e(r);return o&&await CE(o),a};if(jw.getStore()===!0)return t();let n=await xE();try{return await t()}finally{await n()}},vm=e=>kt(t=>({next:{...t,...e},result:void 0})),SE=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],wB="ssoLink",Cm=async()=>{let e=await J();return SE.some(t=>e[t]!==void 0)?!0:await $n()!==void 0},Xw=async()=>{await dl(Sa(te(),"device-token.json"),{force:!0}).catch(()=>{})},Jw=async()=>{let e=await En(),t=SE.some(a=>e[a]!==void 0),n=e[wB]!==void 0,r=e.byoUpstream!==void 0,o=await $n()!==void 0;if(t||n||r||e.managedEnrollmentDisabled!==!0){let a={...e};for(let s of SE)delete a[s];delete a[wB],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,await Tt(a)}if(await Am(),await $n())throw new Error(`could not remove the dev key from ${te()}`);return t||n||r||o},IB=()=>kt(e=>e.managedEnrollmentDisabled===!0?{next:{...e,managedEnrollmentDisabled:void 0},result:void 0}:{result:void 0}),Sm=(e,t)=>e==="reverted"||e==="queued"||t&&(e==="manual"||e==="not-found"),_a=async(e,t,n=!1,r)=>{await kt(o=>{let a=new Set(o.managedTools??[]),s=new Set(a),i=new Set(o.revertedTools??[]),c=new Set(o.blockedTools??[]),l=Array.isArray(o.selectedTools)?o.selectedTools:void 0,d=o.toolSelection,u=n?void 0:r?.personChooses===!0&&!t?!0:o.toolOptIn,f=o.offboardedAt;for(let x of e){let _=x.status==="configured"||x.status==="queued"||x.status==="manual"&&x.landed===!0;!t&&_&&(a.add(x.id),i.delete(x.id),c.delete(x.id),f=void 0),!t&&x.refused===!0&&c.add(x.id),t&&Sm(x.status,s.has(x.id))&&(a.delete(x.id),i.add(x.id),c.delete(x.id))}if(n&&(a.clear(),c.clear()),r&&!t){let x=new Set(r.knownToolIds);for(let _ of r.declinedToolIds??[])x.has(_)&&!a.has(_)&&i.add(_)}if(r){let x=r.namedToolIds??[];if(n)l=[];else if(t&&l){let _=new Set(l);for(let v of x)_.delete(v);l=[..._].sort()}else if(!t&&x.length>0){let _=new Set(r.knownToolIds),v=new Set((l??[]).filter(S=>_.has(S)));for(let S of x)_.has(S)&&v.add(S);l=[...v].sort()}t||(d=x.length>0?"explicit":"all")}let p=[...a].sort(),m=[...o.managedTools??[]].sort(),y=[...i].sort(),g=[...o.revertedTools??[]].sort(),w=[...c].sort(),h=[...o.blockedTools??[]].sort(),b=(x,_)=>x.length===_.length&&x.every((v,S)=>v===_[S]),k=l===void 0?o.selectedTools===void 0:o.selectedTools!==void 0&&b(l,o.selectedTools);if(b(p,m)&&o.revertedTools!=null&&b(y,g)&&b(w,h)&&k&&d===o.toolSelection&&u===o.toolOptIn&&f===o.offboardedAt)return{result:void 0};let{offboardedAt:R,toolOptIn:I,...A}=o;return{next:{...A,...f!==void 0?{offboardedAt:f}:{},...u?{toolOptIn:u}:{},managedTools:p,revertedTools:y,blockedTools:w,selectedTools:l,toolSelection:d},result:void 0}})},zw=async(e=new Date().toISOString())=>{await vm({offboardedAt:e})}});import{execFile as Vre}from"node:child_process";import{readFile as Zre,readdir as Yre}from"node:fs/promises";import{platform as Qw}from"node:os";import{promisify as Xre}from"node:util";import{posix as OE,win32 as TE}from"node:path";var xB,en,RB,Jre,zre,OB,qre,ou,TB,Qre,PB,Rs,_m,eoe,Em,toe,LE,PE,LB,NB,noe,roe,ooe,aoe,RE,NE,qw,Ea,Vo=U(()=>{"use strict";xB=Xre(Vre),en=(e=Qw())=>{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"}},RB=(e,t)=>{let n=en(t);return t==="win32"?TE.join(TE.dirname(n),e):OE.join(OE.dirname(n),e)},Jre=(e=Qw())=>RB("managed-settings.d",e),zre=(e=Qw())=>RB("managed-mcp.json",e),OB=["wslInheritsWindowsSettings","managedSourcesBehavior"],qre=["disableAllHooks","allowManagedHooksOnly","allowManagedMcpServersOnly"],ou="allowedMcpServers",TB=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh","otelHeadersHelper","proxyAuthHelper","forceLoginOrgUUID","forceLoginMethod","forceLoginGatewayUrl","gatewayInternalNetworks","parentSettingsBehavior","modelPicker","policyHelper","permissions.defaultMode"],Qre="/Library/Managed Preferences/com.anthropic.claudecode.plist",PB="SOFTWARE\\Policies\\ClaudeCode",Rs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_m=e=>{if(!(e===void 0||!e.trim()))try{let t=JSON.parse(e);return Rs(t)?t:void 0}catch{return}},eoe=e=>Object.entries(e).some(([t,n])=>!OB.includes(t)&&n!==null),Em=e=>{let[t,n]=e.split(".");return t==="env"&&n?`env.${n}`:t},toe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),LE=(e,t)=>{for(let n of t)e.some(r=>toe(r,n))||e.push(n)},PE=(e,t,n,r,o)=>{for(let[a,s]of Object.entries(t)){if(s===null)continue;let i=n?`${n}.${a}`:a,c=e[a];Array.isArray(c)&&Array.isArray(s)?(LE(c,s),r[Em(i)]=o):Rs(c)&&Rs(s)?(PE(c,s,i,r,o),n||(r[a]=o)):(e[a]=structuredClone(s),r[Em(i)]=o,Rs(s)&&PE(e[a],s,i,r,o))}},LB=(e,t,n)=>{let r=structuredClone(e);if(n||!Rs(r))return r;for(let o of Object.keys(r)){let a=`${t}.${o}`;TB.includes(a)?delete r[o]:r[o]=LB(r[o],a,n)}return r},NB=(e,t,n,r,o,a)=>{for(let[s,i]of Object.entries(n)){if(!r&&OB.includes(s)||i===null)continue;let c=r?`${r}.${s}`:s;if(!a&&TB.includes(c))continue;let l=t.origin[Em(c)]??t.origin[Em(s)]??t.info.label;if(!(s in e)){e[s]=LB(i,c,a),o[Em(c)]=l;continue}let d=e[s];!r&&qre.includes(s)?i===!0&&d!==!0&&(e[s]=!0,o[s]=l):Array.isArray(d)&&Array.isArray(i)&&!(!r&&s===ou)?LE(d,i):Rs(d)&&Rs(i)&&NB(d,t,i,c,o,a)}},noe=async e=>Zre(e,"utf8").catch(()=>{}),roe=async e=>Yre(e).catch(()=>{}),ooe=async()=>{try{let{stdout:e}=await xB("plutil",["-convert","json","-o","-","--",Qre],{timeout:3e3});return _m(e)}catch{return}},aoe=async e=>{try{let{stdout:t}=await xB("reg",["query",`${e}\\${PB}`,"/v","Settings"],{timeout:3e3,windowsHide:!0});for(let n of t.split(`
5
- `)){let r=n.trim();if(r.startsWith("Settings"))for(let o of["REG_EXPAND_SZ","REG_SZ"]){let a=r.indexOf(`${o} `);if(a>0)return r.slice(a+o.length).trim()}}return}catch{return}},RE=(e,t,n)=>({info:{kind:e,label:t,policy:eoe(n)},doc:n,origin:{}}),NE=async(e={})=>{let t=e.platform??Qw(),n=e.readText??noe,r=e.listDir??roe,o=en(t),a=Jre(t),s=A=>t==="win32"?TE.join(a,A):OE.join(a,A),i=[];if(t==="darwin"){let A=await(e.readPlist??ooe)().catch(()=>{});A&&i.push(RE("plist","macOS managed preferences (com.anthropic.claudecode)",A))}let c=async A=>{if(t!=="win32")return;let x=_m(await(e.readRegistry??aoe)(A).catch(()=>{}));return x?RE(A==="HKLM"?"hklm":"hkcu",`Windows registry (${A}\\${PB})`,x):void 0},l=await c("HKLM");l&&i.push(l);let d=[],u=_m(await n(o).catch(()=>{}));u&&d.push({label:`managed settings (${o})`,doc:u});let f=(await r(a).catch(()=>{})??[]).filter(A=>A.endsWith(".json")&&!A.startsWith(".")).sort();for(let A of f){let x=_m(await n(s(A)).catch(()=>{}));x&&d.push({label:`managed settings (${s(A)})`,doc:x})}let p=[];if(d.length){let A={},x={};for(let{label:_,doc:v}of d)PE(A,v,"",x,_);p.push({...RE("file",d[0]?.label??o,A),origin:x})}let m=await c("HKCU"),y=[...i,...p],w=y.find(A=>A.info.policy||"managedSourcesBehavior"in A.doc)?.doc.managedSourcesBehavior==="merge",h=y.find(A=>A.info.policy)??(m?.info.policy?m:void 0),b={},k={},C=(A,x)=>A.origin[x]??A.info.label;if(w){let A=y.filter(x=>x.info.policy);for(let[x,_]of A.entries())NB(b,_,_.doc,"",k,x===0)}else if(h){for(let[A,x]of Object.entries(h.doc))x!==null&&(b[A]=structuredClone(x),k[A]=C(h,A));if(y.includes(h)){let A={};for(let v of y)if(Rs(v.doc.env))for(let[S,O]of Object.entries(v.doc.env))S in A||O===null||(A[S]=O,k[`env.${S}`]=C(v,`env.${S}`));Object.keys(A).length&&(b.env=A);let x=y.find(v=>v.doc.allowManagedMcpServersOnly===!0);if(x){b.allowManagedMcpServersOnly=!0,k.allowManagedMcpServersOnly=C(x,"allowManagedMcpServersOnly");let v=y.find(S=>Array.isArray(S.doc[ou]));v&&(b[ou]=structuredClone(v.doc[ou]),k[ou]=C(v,ou))}let _=[];for(let v of y)Array.isArray(v.doc.deniedMcpServers)&&LE(_,v.doc.deniedMcpServers);_.length&&(b.deniedMcpServers=_,k.deniedMcpServers??=C(y[0],"deniedMcpServers"))}}let R=await n(zre(t)).catch(()=>{}),I=_m(R);return{settings:b,originOf:A=>k[A]??(A.startsWith("env.")?k.env:void 0),sources:[...y,...m?[m]:[]].map(A=>A.info),mcpFile:R===void 0?{present:!1}:{present:!0,...I&&Rs(I.mcpServers)?{servers:Object.keys(I.mcpServers)}:I?{servers:[]}:{}}}},qw=(e,t=`managed settings (${en()})`)=>({settings:e,originOf:()=>t,sources:[],mcpFile:{present:!1}}),Ea=async e=>{try{return e.managedView?await e.managedView():e.readManaged?qw(await e.readManaged()):await NE()}catch{return qw({})}}});import{readFileSync as soe}from"node:fs";import{isAbsolute as ioe,win32 as coe}from"node:path";var Im,loe,doe,tb,eb,uoe,foe,poe,moe,hoe,DB,xm=U(()=>{"use strict";Gw();Vo();Im="__anyray-sso-gate",loe="__anyray-hook",doe="--managed-source",tb=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(ioe(e)||coe.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),eb=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),uoe=/^(?:[A-Za-z]:\/|\/\/[^/])/,foe=/^[A-Za-z0-9_./:=-]*$/,poe=e=>{let t=wE(e,0);if(!t||!foe.test(t.unquoted))return;let n=e.slice(t.end);if(!(n!==""&&!n.startsWith(" ")))return{binary:t.value,args:n.split(" ").filter(r=>r!=="")}},moe=e=>{let t=poe(e);if(!t||!tb(t.binary))return;let[n,r]=t.args;if(n===Im||n===loe&&r===doe)return uoe.test(t.binary)?t.binary.replace(/\//g,"\\"):t.binary},hoe=e=>{if(!eb(e)||!eb(e.hooks))return;let t=new Set;for(let n of Object.values(e.hooks))if(Array.isArray(n)){for(let r of n)if(!(!eb(r)||!Array.isArray(r.hooks)))for(let o of r.hooks){if(!eb(o)||typeof o.command!="string")continue;let a=moe(o.command);a!==void 0&&t.add(a)}}return t.size===1?[...t][0]:void 0},DB=(e=en())=>{try{let t=soe(e,"utf8");return t.length>1024*1024?void 0:hoe(JSON.parse(t))}catch{return}}});var _r,In,bo,au,ko=U(()=>{"use strict";_r=(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,In=(e=process.env)=>_r(e)!==null,bo=e=>e==="codespaces"||e==="devcontainer",au=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}}});var Ke,lr=U(()=>{"use strict";Ke="0.11.412"});import{access as yoe,chmod as goe,mkdir as DE,open as FE,readFile as WB,rm as Zo,stat as MB,utimes as woe}from"node:fs/promises";import{createHash as UE,randomUUID as jB}from"node:crypto";import{readFileSync as KB,statSync as $B}from"node:fs";import{dirname as HE,join as boe}from"node:path";import{isDeepStrictEqual as su}from"node:util";var Fi,VB,BB,koe,G,ae,Ao,FB,ZB,vo,Om,ye,YB,UB,Aoe,voe,XB,Coe,Rm,ME,$E,HB,Soe,BE,iu,JB,zB,qB,nb,GB,rb,Co,We,Ze=U(()=>{"use strict";ll();_n();Fi=e=>`${e}.anyray-bak`,VB=async e=>{let t;try{t=await FE(HE(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},BB=async(e,t)=>{let n,r;try{n=await FE(e,"wx",384),await n.writeFile(t,"utf-8"),await Bi(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Zo(e,{force:!0}).catch(()=>{}),r;await VB(e)},koe=async e=>{let t;try{t=await FE(e,"r"),await Bi(t)}finally{await t?.close().catch(()=>{})}await VB(e)},G=async e=>{try{return await yoe(e),!0}catch{return!1}},ae=async e=>{if(!await G(e))return{};let t=await WB(e,"utf-8");if(!t.trim())return{};let n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n},Ao=class extends Error{constructor(){super("repair deferred: configuration changed before publication")}},FB=e=>`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}:${e.ctimeNs}`,ZB=e=>{try{let t=FB($B(e,{bigint:!0})),n=KB(e),r=FB($B(e,{bigint:!0}));if(t!==r)throw new Ao;return{raw:n.toString("utf8"),fingerprint:`${r}:${UE("sha256").update(n).digest("hex")}`}}catch(t){if(t.code==="ENOENT")return{raw:"",fingerprint:"missing"};throw t}},vo=e=>{let{raw:t,fingerprint:n}=ZB(e),r=t.trim()?JSON.parse(t):{};if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("configuration is not a JSON object");return{value:r,fingerprint:n}},Om=async(e,t,n={})=>{for(let r=0;r<3;r++)try{let o=vo(e);if(n.requireExisting&&o.fingerprint==="missing")return"unchanged";let a=JSON.stringify(o.value);return t(o.value),JSON.stringify(o.value)===a?"unchanged":(await ye(e,o.value,{backup:n.backup,expectedFingerprint:o.fingerprint}),"written")}catch(o){if(!(o instanceof Ao))throw o}return"repair deferred"},ye=async(e,t,n={})=>{await DE(HE(e),{recursive:!0,mode:448});let r=Fi(e);if(n.backup!==!1&&!await G(r)){let a=await G(e),s=a?await WB(e,"utf-8"):`{}
5
+ `)){let r=n.trim();if(r.startsWith("Settings"))for(let o of["REG_EXPAND_SZ","REG_SZ"]){let a=r.indexOf(`${o} `);if(a>0)return r.slice(a+o.length).trim()}}return}catch{return}},RE=(e,t,n)=>({info:{kind:e,label:t,policy:eoe(n)},doc:n,origin:{}}),NE=async(e={})=>{let t=e.platform??Qw(),n=e.readText??noe,r=e.listDir??roe,o=en(t),a=Jre(t),s=A=>t==="win32"?TE.join(a,A):OE.join(a,A),i=[];if(t==="darwin"){let A=await(e.readPlist??ooe)().catch(()=>{});A&&i.push(RE("plist","macOS managed preferences (com.anthropic.claudecode)",A))}let c=async A=>{if(t!=="win32")return;let x=_m(await(e.readRegistry??aoe)(A).catch(()=>{}));return x?RE(A==="HKLM"?"hklm":"hkcu",`Windows registry (${A}\\${PB})`,x):void 0},l=await c("HKLM");l&&i.push(l);let d=[],u=_m(await n(o).catch(()=>{}));u&&d.push({label:`managed settings (${o})`,doc:u});let f=(await r(a).catch(()=>{})??[]).filter(A=>A.endsWith(".json")&&!A.startsWith(".")).sort();for(let A of f){let x=_m(await n(s(A)).catch(()=>{}));x&&d.push({label:`managed settings (${s(A)})`,doc:x})}let p=[];if(d.length){let A={},x={};for(let{label:_,doc:v}of d)PE(A,v,"",x,_);p.push({...RE("file",d[0]?.label??o,A),origin:x})}let m=await c("HKCU"),y=[...i,...p],w=y.find(A=>A.info.policy||"managedSourcesBehavior"in A.doc)?.doc.managedSourcesBehavior==="merge",h=y.find(A=>A.info.policy)??(m?.info.policy?m:void 0),b={},k={},C=(A,x)=>A.origin[x]??A.info.label;if(w){let A=y.filter(x=>x.info.policy);for(let[x,_]of A.entries())NB(b,_,_.doc,"",k,x===0)}else if(h){for(let[A,x]of Object.entries(h.doc))x!==null&&(b[A]=structuredClone(x),k[A]=C(h,A));if(y.includes(h)){let A={};for(let v of y)if(Rs(v.doc.env))for(let[S,O]of Object.entries(v.doc.env))S in A||O===null||(A[S]=O,k[`env.${S}`]=C(v,`env.${S}`));Object.keys(A).length&&(b.env=A);let x=y.find(v=>v.doc.allowManagedMcpServersOnly===!0);if(x){b.allowManagedMcpServersOnly=!0,k.allowManagedMcpServersOnly=C(x,"allowManagedMcpServersOnly");let v=y.find(S=>Array.isArray(S.doc[ou]));v&&(b[ou]=structuredClone(v.doc[ou]),k[ou]=C(v,ou))}let _=[];for(let v of y)Array.isArray(v.doc.deniedMcpServers)&&LE(_,v.doc.deniedMcpServers);_.length&&(b.deniedMcpServers=_,k.deniedMcpServers??=C(y[0],"deniedMcpServers"))}}let R=await n(zre(t)).catch(()=>{}),I=_m(R);return{settings:b,originOf:A=>k[A]??(A.startsWith("env.")?k.env:void 0),sources:[...y,...m?[m]:[]].map(A=>A.info),mcpFile:R===void 0?{present:!1}:{present:!0,...I&&Rs(I.mcpServers)?{servers:Object.keys(I.mcpServers)}:I?{servers:[]}:{}}}},qw=(e,t=`managed settings (${en()})`)=>({settings:e,originOf:()=>t,sources:[],mcpFile:{present:!1}}),Ea=async e=>{try{return e.managedView?await e.managedView():e.readManaged?qw(await e.readManaged()):await NE()}catch{return qw({})}}});import{readFileSync as soe}from"node:fs";import{isAbsolute as ioe,win32 as coe}from"node:path";var Im,loe,doe,tb,eb,uoe,foe,poe,moe,hoe,DB,xm=U(()=>{"use strict";Gw();Vo();Im="__anyray-sso-gate",loe="__anyray-hook",doe="--managed-source",tb=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(ioe(e)||coe.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),eb=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),uoe=/^(?:[A-Za-z]:\/|\/\/[^/])/,foe=/^[A-Za-z0-9_./:=-]*$/,poe=e=>{let t=wE(e,0);if(!t||!foe.test(t.unquoted))return;let n=e.slice(t.end);if(!(n!==""&&!n.startsWith(" ")))return{binary:t.value,args:n.split(" ").filter(r=>r!=="")}},moe=e=>{let t=poe(e);if(!t||!tb(t.binary))return;let[n,r]=t.args;if(n===Im||n===loe&&r===doe)return uoe.test(t.binary)?t.binary.replace(/\//g,"\\"):t.binary},hoe=e=>{if(!eb(e)||!eb(e.hooks))return;let t=new Set;for(let n of Object.values(e.hooks))if(Array.isArray(n)){for(let r of n)if(!(!eb(r)||!Array.isArray(r.hooks)))for(let o of r.hooks){if(!eb(o)||typeof o.command!="string")continue;let a=moe(o.command);a!==void 0&&t.add(a)}}return t.size===1?[...t][0]:void 0},DB=(e=en())=>{try{let t=soe(e,"utf8");return t.length>1024*1024?void 0:hoe(JSON.parse(t))}catch{return}}});var _r,In,bo,au,ko=U(()=>{"use strict";_r=(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,In=(e=process.env)=>_r(e)!==null,bo=e=>e==="codespaces"||e==="devcontainer",au=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}}});var Ke,lr=U(()=>{"use strict";Ke="0.11.413"});import{access as yoe,chmod as goe,mkdir as DE,open as FE,readFile as WB,rm as Zo,stat as MB,utimes as woe}from"node:fs/promises";import{createHash as UE,randomUUID as jB}from"node:crypto";import{readFileSync as KB,statSync as $B}from"node:fs";import{dirname as HE,join as boe}from"node:path";import{isDeepStrictEqual as su}from"node:util";var Fi,VB,BB,koe,G,ae,Ao,FB,ZB,vo,Om,ye,YB,UB,Aoe,voe,XB,Coe,Rm,ME,$E,HB,Soe,BE,iu,JB,zB,qB,nb,GB,rb,Co,We,Ze=U(()=>{"use strict";ll();_n();Fi=e=>`${e}.anyray-bak`,VB=async e=>{let t;try{t=await FE(HE(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},BB=async(e,t)=>{let n,r;try{n=await FE(e,"wx",384),await n.writeFile(t,"utf-8"),await Bi(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Zo(e,{force:!0}).catch(()=>{}),r;await VB(e)},koe=async e=>{let t;try{t=await FE(e,"r"),await Bi(t)}finally{await t?.close().catch(()=>{})}await VB(e)},G=async e=>{try{return await yoe(e),!0}catch{return!1}},ae=async e=>{if(!await G(e))return{};let t=await WB(e,"utf-8");if(!t.trim())return{};let n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n},Ao=class extends Error{constructor(){super("repair deferred: configuration changed before publication")}},FB=e=>`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}:${e.ctimeNs}`,ZB=e=>{try{let t=FB($B(e,{bigint:!0})),n=KB(e),r=FB($B(e,{bigint:!0}));if(t!==r)throw new Ao;return{raw:n.toString("utf8"),fingerprint:`${r}:${UE("sha256").update(n).digest("hex")}`}}catch(t){if(t.code==="ENOENT")return{raw:"",fingerprint:"missing"};throw t}},vo=e=>{let{raw:t,fingerprint:n}=ZB(e),r=t.trim()?JSON.parse(t):{};if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("configuration is not a JSON object");return{value:r,fingerprint:n}},Om=async(e,t,n={})=>{for(let r=0;r<3;r++)try{let o=vo(e);if(n.requireExisting&&o.fingerprint==="missing")return"unchanged";let a=JSON.stringify(o.value);return t(o.value),JSON.stringify(o.value)===a?"unchanged":(await ye(e,o.value,{backup:n.backup,expectedFingerprint:o.fingerprint}),"written")}catch(o){if(!(o instanceof Ao))throw o}return"repair deferred"},ye=async(e,t,n={})=>{await DE(HE(e),{recursive:!0,mode:448});let r=Fi(e);if(n.backup!==!1&&!await G(r)){let a=await G(e),s=a?await WB(e,"utf-8"):`{}
6
6
  `;if(a||n.tombstoneAbsent!==!1)try{await BB(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${jB()}`;try{if(await BB(o,`${JSON.stringify(t,null,2)}
7
7
  `),n.expectedFingerprint!==void 0){if(ZB(e).fingerprint!==n.expectedFingerprint)throw new Ao;let a=n.expectedFingerprint.slice(n.expectedFingerprint.lastIndexOf(":")+1);try{await ze(o,e,n.runtimePlatform,{verifyDisplaced:async s=>UE("sha256").update(KB(s)).digest("hex")===a})}catch(s){throw s instanceof cl?new Ao:s}return}await ze(o,e,n.runtimePlatform),await goe(e,384),await koe(e)}finally{await Zo(o,{force:!0}).catch(()=>{})}},YB=1,UB=3e4,Aoe=5e3,voe=/^[a-f0-9]{64}$/,XB=e=>`${e}.pending`,Coe=e=>`${e}.lock`,Rm=e=>{if(e===void 0)return"null";if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(n=>Rm(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Rm(t[n])}`).join(",")}}`},ME=(e,t)=>({exists:e,sha256:UE("sha256").update(Rm(t)).digest("hex")}),$E=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),HB=e=>$E(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&voe.test(e.sha256),Soe=e=>$E(e)&&e.transactionVersion===YB&&HB(e.before)&&HB(e.after)&&$E(e.journal),BE=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,iu=async(e,t)=>{try{return await ae(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},JB=async e=>{let t=Coe(e),n=boe(t,"owner.json");await DE(HE(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=jB();try{await DE(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await iu(n,"ownership journal");if(typeof c.pid!="number"||!Number.isSafeInteger(c.pid)||c.pid<=0)throw new Error("lock owner is missing or invalid");let l=Date.now()-(await MB(n)).mtimeMs;i=!go(c.pid)||l>UB}catch{try{i=Date.now()-(await MB(t)).mtimeMs>UB}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Zo(t,{recursive:!0,force:!0});continue}try{await ye(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Zo(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await iu(n,"ownership journal")).nonce!==o)return;let i=new Date;await woe(n,i,i)}catch{}})()},Aoe);return a.unref(),async()=>{clearInterval(a);try{(await iu(n,"ownership journal")).nonce===o&&await Zo(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},zB=async e=>{let t=await G(e),n={};if(t)try{n=await ae(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:ME(t,n)}},qB=async(e,t)=>{let n=XB(t);if(!await G(n))return;let r=await iu(n,"prepared ownership transaction");if(!Soe(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await zB(e),a=await G(t),s=await G(Fi(e)),i=BE(o.fingerprint,r.before),c=BE(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await ye(t,r.journal,{backup:!1}),await Zo(n,{force:!0});return}if(i){await Zo(n,{force:!0}),a||await We(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},nb=async(e,t,n)=>{let r=await JB(t);try{return await qB(e,t),await n()}finally{await r()}},GB=async(e,t,n,r)=>{if(!await G(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await iu(e,"ownership journal");if(!(n&&su(a,t))){if(!su(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await ye(e,t,{backup:!1}):await Zo(e,{force:!0})}},rb=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await JB(a);try{await qB(n,a);let l=await zB(n),d=ME(i,r),u=await G(a),f=u?await iu(a,"ownership journal"):void 0,p=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!BE(l.fingerprint,d)){if(su(l.value,o)&&f&&su(f,p))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&su(l.value,o)&&f&&su(f,p))return;let m=await G(Fi(n));if(f?.fileExisted===!0&&!m)throw new Error("ownership backup is missing; configuration was left unchanged");if(m&&!f)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let y=XB(a),g={transactionVersion:YB,before:l.fingerprint,after:ME(!0,o),journal:p};await ye(y,g,{backup:!1});try{await ye(n,o,f?{backup:!1}:{tombstoneAbsent:!1}),await(t.writeJournal??ye)(a,p,{backup:!1}),await Zo(y,{force:!0})}catch(w){try{await GB(n,l.value,l.exists,o)}catch(h){throw new AggregateError([w,h],"ownership journal publication failed and config rollback was incomplete")}try{await GB(a,f??{},u,p),await Zo(y,{force:!0}),!m&&!f&&await We(n)}catch(h){throw new AggregateError([w,h],"ownership journal publication failed after config rollback")}throw w}}finally{await c()}},Co=async e=>{try{return await ae(Fi(e))}catch{return{}}},We=async e=>{await Zo(Fi(e),{force:!0}).catch(()=>{})}});var st,cu=U(()=>{"use strict";st=(e,t,n=0)=>{let r=e.indexOf(t,n);for(;r>=0;){let o=e.lastIndexOf(`
8
8
  `,r-1)+1,a=e.indexOf(`
@@ -689,7 +689,7 @@ Examples:
689
689
  `),0}if(s!==aO(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await Oye(i,s);for(let d of l){let u=await xK(d.path,d.content,s),f=d.label[0].toUpperCase()+d.label.slice(1);r.write(u==="unchanged"?`${f} already current at ${d.path}.
690
690
  `:`${u==="installed"?"Installed":"Updated"} ${d.label} at ${d.path}.
691
691
  `)}return 0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
692
- `),1}}});import{execFile as Pye}from"node:child_process";import{readFile as Lye}from"node:fs/promises";import{platform as Nye}from"node:os";import{promisify as Dye}from"node:util";var Mye,OK,TK,Qh,$ye,Bye,PK,lO,NA=U(()=>{"use strict";vf();dt();At();to();Vl();cc();Mye=Dye(Pye),OK=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),TK=(e,t)=>{if(e.inferenceCredentialHelper!==Qa)return!1;try{let n=new URL(t.anthropicBaseUrl);if(typeof e.bootstrapUrl=="string"){let r=new URL(e.bootstrapUrl);return e.bootstrapEnabled!==!1&&e.bootstrapEnabled!=="false"&&r.origin===n.origin&&r.pathname==="/connect/claude-desktop/bootstrap"&&(r.searchParams.get("os")??"macos")==="macos"&&!r.username&&!r.password}return e.inferenceProvider==="gateway"&&e.inferenceCredentialKind==="helper-script"&&qu(e.inferenceGatewayAuthScheme)&&typeof e.inferenceGatewayBaseUrl=="string"&&new URL(e.inferenceGatewayBaseUrl).href===n.href}catch{return!1}},Qh=async(e,t={})=>{if((t.platform??Nye)()!=="darwin")return!1;let n=await wr(An(t),t);if(!n||n.unreadable)return!1;let r=await(t.readManagedPolicy??af)(n.path);return r!==void 0&&TK(r,{anthropicBaseUrl:e})},$ye=async()=>{let{stdout:e}=await Mye(Qa,[],{timeout:3e4,maxBuffer:65536});return e},Bye=async(e,t)=>{try{let n=await(t.runFleetCredentialHelper??$ye)(),r=JSON.parse(n);return OK(r)&&U0(r.token)&&OK(r.headers)&&r.headers["x-anyray-auth-mode"]==="passthrough"&&r.headers["x-anyray-provider"]==="anthropic"&&typeof r.headers["x-anyray-api-key"]=="string"&&St(r.headers["x-anyray-api-key"])&&r.headers["x-anyray-api-key"]===e.clientKey}catch{return!1}},PK=async(e,t,n,r)=>{if(!(!t.explicit||!t.reportsToUser||n.unreadable||!Te(e,"anthropic")))return lO(e,n,r,t.dryRun)},lO=async(e,t,n,r)=>{let o=(a,s)=>({status:"manual",failureClass:a,messages:[s]});try{let a=await(n.readManagedPolicy??af)(t.path);if(!a||!TK(a,e))return;let s=await(n.readFleetCredentialHelper??(()=>Lye(Qa,"utf8")))();if(!SK(s))return o("credential_helper_foreign","The managed Claude Desktop credential helper is not the packaged Anyray helper. Repair the Anyray Connect package, then retry.");if(r)return await(n.claudeCodeInstalled??Zu)()?{status:"held",messages:["Would authorize your Claude subscription and verify the installed MDM credential helper. The managed policy stays installed."]}:o("claude_missing","Claude subscription authorization needs Claude Code. Install it, then retry.");let i=await(n.ensureSeatToken??Xa)();return i.status==="missing-claude"?o("claude_missing","Claude subscription authorization needs Claude Code. Install it, then retry."):i.status==="mint-failed"||i.status==="no-token-output"?o("seat_token_mint_failed","Claude subscription authorization did not complete. Re-run anyray-connect --subscription --tools claude-desktop and finish the browser approval."):await Bye(e,n)?{status:"held",messages:["Your Claude subscription is authorized. In Claude, click Check again. If it still asks, quit and reopen Claude."]}:(i.status==="minted"&&await(n.removeSeatToken??ac)().catch(()=>{}),o("credential_helper_failed","The installed MDM credential helper did not produce Claude subscription passthrough credentials. Repair the Anyray Connect package or its stored billing mode, then retry."))}catch{return o("credential_helper_failed","Could not prepare the managed Claude subscription credential. Check the Anyray Connect package and retry.")}}});var Ht,Lo=U(()=>{"use strict";ue();ta();dt();Ht=async(e=J,t=Ba)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:bt({origin:n.gateway,clientKey:n.clientKey,subscription:n.authMode==="subscription",placeholder:n.authMode==="placeholder",byoUpstream:n.byoUpstream,seat:r,user:n.name,team:n.team})}}});import{homedir as Fye}from"node:os";import{join as Uye}from"node:path";import{rm as Hye}from"node:fs/promises";import{z as dO}from"zod";var ey,LK,ua,ni,uO,it,NK,fO,yc,es,No=U(()=>{"use strict";Ze();un();ey=["gateway","gateway_hooks","gateway_hooks_mcp"],LK=dO.object({level:dO.enum(ey),source:dO.enum(["agent","user","team","org","default"])}).strict(),ua={level:"gateway_hooks_mcp",source:"default"},ni=async(e,t,n={})=>{if(t?.trim())try{let r=await Zn(e,t.trim(),void 0,n);if(typeof r!="object"||r===null||Array.isArray(r))return;if(!Object.hasOwn(r,"integrationLevel"))return ua;let o=LK.safeParse(r.integrationLevel);return o.success?o.data:void 0}catch{return}},uO=()=>Uye(Fye(),".anyray-integration-level.json"),it=async()=>{try{let e=LK.safeParse(await ae(uO()));return e.success?e.data:void 0}catch{return}},NK=async e=>ye(uO(),e,{backup:!1}),fO=async()=>Hye(uO(),{force:!0}),yc=e=>e!=="gateway",es=e=>e==="gateway_hooks_mcp"});var Qn,Gye,DK,gc,MK,$K,ts=U(()=>{"use strict";At();Qn=(e,t)=>e?.tiers?.[t]==="locked"?"locked":"recommended",Gye=e=>e==="subscription"?"subscription":"placeholder",DK=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?Gye(t.lane):void 0,a=o!=null&&o!==e.authMode;return{routingUpdated:n,teamUpdated:r,laneUpdated:a,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{},...a?{authMode:o}:{}}},gc=(e,t,n,r)=>{let o=new Set(t.enabled??[]),a=e.managedTools??[],s=a.filter(u=>o.has(u)||n);if(t.defaulted===!0&&(e.toolSelection!=="all"||e.toolOptIn===!0))return{candidateIds:s,freshIds:[]};let i=new Set(e.revertedTools??[]),c=e.revertedTools!=null,l=new Set(r.filter(Xo).map(u=>u.id)),d=[];for(let u of o)a.includes(u)||Qn(t,u)!=="locked"&&(l.has(u)||!c||i.has(u)||e.toolOptIn===!0)||d.push(u);return{candidateIds:s,freshIds:d}},MK=(e,t,n)=>{let r=[],o=[],a=[],s=new Set(e.revertedTools??[]),i=new Set(e.managedTools??[]);if(t===void 0||t.defaulted===!0){for(let l of n)s.has(l.id)&&!i.has(l.id)?a.push({id:l.id,reason:"opted_out"}):Xo(l)?a.push({id:l.id,reason:"consent"}):r.push(l.id);return{applyIds:r,revertIds:o,skipped:a}}let c=new Set(t.enabled??[]);for(let l of n){let{id:d}=l;if(!c.has(d)){i.has(d)?o.push(d):a.push({id:d,reason:"not_enabled"});continue}if(i.has(d)){r.push(d);continue}let u=Qn(t,d);if(s.has(d)&&u!=="locked"){a.push({id:d,reason:"opted_out"});continue}if(Xo(l)){u==="locked"?r.push(d):a.push({id:d,reason:"consent"});continue}r.push(d)}return{applyIds:r,revertIds:o,skipped:a}},$K=(e,t,n)=>{let r=new Set(e.managedTools??[]),o=new Set(t?.enabled??[]);return n.map(a=>a.id).filter(a=>r.has(a)||o.has(a)&&Qn(t,a)==="locked")}});import{z as pO}from"zod";var Wye,mO,jye,BK,hO=U(()=>{"use strict";un();Wye=5e3,mO=pO.object({url:pO.string().url().refine(e=>/^https:\/\//i.test(e))}).optional().catch(void 0),jye=pO.object({personalUpstream:mO}),BK=async(e,t,n={})=>{if(t?.trim())try{let r=await Zn(e,t.trim(),void 0,{...n,timeoutMs:n.timeoutMs??Wye}),o=jye.safeParse(r);return o.success?o.data.personalUpstream?.url:void 0}catch{return}}});import{mkdir as Kye,readFile as kO,rm as AO,rmdir as Vye,writeFile as Zye}from"node:fs/promises";import{join as ri}from"node:path";import{homedir as Yye}from"node:os";import{createHash as Xye,randomUUID as Jye}from"node:crypto";import{z as De}from"zod";var zye,qye,ns,vO,KK,gO,Qye,ege,tge,Cf,CO,yO,MA,rs,FK,$A,BA,FA,nge,VK,rge,ZK,oge,age,sge,ige,cge,SO,Sf,lge,UK,dge,uge,wO,ty,HK,fge,YK,GK,pge,WK,bO,UA,mge,hge,DA,yge,gge,wge,bge,kge,Age,vge,_f,XK,jK,ed,Cge,JK,HA,Sge,zK,qK,Ef,QK,GA,ro=U(()=>{"use strict";_n();Pt();No();Ze();dt();xa();ck();un();ts();ue();hO();Lo();os();zye=1e4,qye=1,ns="anyray",vO=async(e,t)=>{let n=e.skills.some(r=>r.id===ns);return kt(r=>r.gateway!==t.gateway||r.clientKey!==t.clientKey?{result:!1}:!n&&e.skillsIncomplete?{result:!0}:(n?r.builtinSkillRequired===!0:r.builtinSkillRequired!==!0)?{result:!0}:{next:{...r,builtinSkillRequired:n},result:!0}).then(r=>r?"completed":"incomplete",()=>"incomplete")},KK=De.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),gO=/^[a-z0-9][a-z0-9-]{0,31}$/,Qye=De.object({id:KK,name:De.string().min(1),version:De.string().min(1),body:De.string(),variants:De.record(De.string().regex(gO),De.string()).optional().catch(void 0),plugin:De.boolean().optional()}),ege=De.object({url:De.string().url(),plugins:De.array(KK)}),tge=De.object({version:De.literal(qye).optional(),skills:De.array(Qye),skillsIncomplete:De.boolean().optional(),marketplace:ege.optional(),mcp:De.object({org:De.object({url:De.string().url()})}).optional(),retrievalMcp:De.object({url:De.string().url()}).optional().catch(void 0),personalUpstream:mO,updatedAt:De.string().min(1).optional(),routing:De.object({origin:De.string().min(1)}).optional(),team:De.string().min(1).optional(),lane:De.enum(["subscription","org"]).optional().catch(void 0),tools:De.object({enabled:De.array(De.string().min(1)),defaulted:De.literal(!0).optional().catch(void 0),tiers:De.record(De.string().min(1),De.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional(),updates:De.object({mode:De.enum(["auto","directed","off"]).catch("directed")}).optional(),hooks:De.object({digest:De.enum(["on","off"]).catch("off"),readTrim:De.enum(["on","off"]).optional().catch("off"),readTrimRequiresRetrieve:De.enum(["on","off"]).optional().catch("on"),lifecycle:De.enum(["on","off"]).optional().catch("off"),prompt:De.enum(["on","off"]).optional().catch("off"),logRead:De.enum(["on","off"]).optional().catch("off"),fleetReadBack:De.enum(["on","off"]).optional().catch("off"),digestEconomics:De.enum(["on","off"]).optional().catch("off"),rangedArrival:De.enum(["on","off"]).optional().catch("off")}).optional(),capabilities:De.array(De.string()).optional().catch(void 0),clientAssets:ox.optional().catch(void 0)}),Cf=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},CO=e=>e instanceof Cf&&e.kind==="auth",yO=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",MA=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",rs=async(e,t,n={})=>{let r=n.timeoutMs??zye,o=`${e}/connect/policy`,a;try{a=await Zn(e,t,void 0,{policySnapshot:n.policySnapshot,timeoutMs:r})}catch(s){if(s instanceof Ls&&s.details.status!==void 0)throw new Cf(s.kind==="auth"?"auth":"unavailable",`team policy fetch failed: the gateway responded ${s.details.status} at ${o}`);if(s instanceof Ls&&s.kind==="unavailable"){let i=s.details.timeoutMs!==void 0?` no response within ${s.details.timeoutMs}ms.`:s.details.networkSuffix??"";throw new Cf("unavailable",`could not reach the gateway at ${o}.${i}`)}throw new Cf("malformed","team policy fetch failed: the gateway returned a malformed response")}return tge.parse(a)},FK=64,$A=e=>{let t=e.tools;if(!t||t.defaulted===!0)return;let n=t.enabled.filter(o=>gO.test(o)).slice(0,FK).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>gO.test(o)).slice(0,FK).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},BA=async()=>{await kt(e=>({next:{...e,policyReceivedAt:new Date().toISOString()},result:void 0}))},FA=async(e,t,n=rs,r)=>{let o=await n(e,t,{policySnapshot:r}),a=$A(o);return await kt(s=>{let{fleetToolPolicy:i,...c}=s;return{next:{...c,...a?{fleetToolPolicy:a}:{}},result:void 0}}),o},nge=e=>({mode:e.updates?.mode??"auto"}),VK=(e,t)=>e.hooks?{digest:e.hooks.digest,...e.hooks.readTrim==="on"?{readTrim:"on"}:{},...e.hooks.readTrimRequiresRetrieve==="on"?{readTrimRequiresRetrieve:"on"}:{},...e.hooks.lifecycle==="on"?{lifecycle:"on"}:{},...e.hooks.logRead==="on"?{logRead:"on"}:{},...e.hooks.fleetReadBack==="on"?{fleetReadBack:"on"}:{},...e.hooks.digestEconomics==="on"?{digestEconomics:"on"}:{},...e.hooks.rangedArrival==="on"?{rangedArrival:"on"}:{}}:t,rge=e=>kt(t=>{let n=VK(e,t.fleetHookPolicy);if(JSON.stringify(n??null)===JSON.stringify(t.fleetHookPolicy??null))return{result:void 0};let{fleetHookPolicy:r,...o}=t;return{next:{...o,...n?{fleetHookPolicy:n}:{}},result:void 0}}),ZK=2,oge=(e,t)=>{let{retrievalMcpUrl:n,retrievalMcpMisses:r,...o}=e;if(t)return e.retrievalMcpUrl===t&&e.retrievalMcpMisses===void 0?e:{...o,retrievalMcpUrl:t};if(e.retrievalMcpUrl===void 0)return e.retrievalMcpMisses===void 0?e:o;let a=(e.retrievalMcpMisses??0)+1;return a>=ZK?o:{...e,retrievalMcpMisses:a}},age=(e,t)=>{let{personalUpstreamUrl:n,personalUpstreamMisses:r,...o}=e;if(t)return e.personalUpstreamUrl===t&&e.personalUpstreamMisses===void 0?e:{...o,personalUpstreamUrl:t};if(e.personalUpstreamUrl===void 0)return e.personalUpstreamMisses===void 0?e:o;let a=(e.personalUpstreamMisses??0)+1;return a>=ZK?o:{...e,personalUpstreamMisses:a}},sge=e=>kt(t=>{let n=age(t,e.personalUpstream?.url);return n===t?{result:void 0}:{next:n,result:void 0}}),ige=e=>kt(t=>{let n=oge(t,e.retrievalMcp?.url);return n===t?{result:void 0}:{next:n,result:void 0}}),cge=async(e={})=>{let t=await(e.loadProfile??J)(),n=e.adapters??ge,r=t.managedTools??await QK(n,t.gateway),o=[],a=[];for(let s of n){if(!s.syncRetrievalMcp||!r.includes(s.id))continue;let i=await s.syncRetrievalMcp().catch(()=>null);if(!i||i.completion==="incomplete"){a.push(s.id);continue}i.changed&&o.push(s.id)}return{changed:o,failed:a}},SO=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?Qn(n,t)==="locked":!1},Sf=async(e,t={})=>{let n=t.loadProfile??En,r=t.saveProfile??Tt,o=t.targetFromProfile??Ht,a=t.adapters??ge,s=t.repairTools??Do,i=t.recordManaged??_a,c=t.recordClientAssets??ix,l=await n(),d={...l},u=DK(l,{routingOrigin:e.routing?.origin?jo(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:f,teamUpdated:p,laneUpdated:m}=u;(f||p||m)&&(d={...await n()},u.gateway!=null&&(d.gateway=u.gateway),u.team!=null&&(d.team=u.team),u.authMode!=null&&(d.authMode=u.authMode),await r(d));let y=gc(d,{enabled:e.tools?.enabled,tiers:e.tools?.tiers,defaulted:e.tools?.defaulted},f||p||m,a),{candidateIds:g,freshIds:w}=y,h=0,b=0,k=0;if(g.length>0||w.length>0){let S=await o(async()=>d);if(S){await c(S.target.origin,e.clientAssets).catch(()=>{});let O;if(f||p||m){let $=new Set(g);O=[];for(let B of a)if($.has(B.id))try{(await B.detect()).installed&&O.push(B)}catch{}}else{O=await If(g,S.target.origin,a);let $=new Set(e.capabilities??[]),B=new Set(O.map(D=>D.id));for(let D of await fa(g,a))if(!(B.has(D.id)||!D.gatewayFeatureDrift))try{if(D.automaticRepairAllowed&&!await D.automaticRepairAllowed())continue;await D.gatewayFeatureDrift($,t.policySnapshot)&&O.push(D)}catch{}}let F=new Set(w),L=[];for(let $ of a)if(F.has($.id))try{(await $.detect()).installed&&L.push($)}catch{}if(h=O.length+L.length,h>0){let $=await s([...O,...L],S.target,t.policySnapshot);b=$.filter(Ql).length;let B=$.filter(D=>F.has(D.id));if(k=B.filter(Ql).length,B.length>0)try{await i(B,!1)}catch{}}}}let C=$A(e),R=nge(e),I=await n(),A=VK(e,I.fleetHookPolicy),x=JSON.stringify(C??null)!==JSON.stringify(I.fleetToolPolicy??null),_=JSON.stringify(R??null)!==JSON.stringify(I.fleetUpdatePolicy??null),v=JSON.stringify(A??null)!==JSON.stringify(I.fleetHookPolicy??null);if(x||_||v){let{fleetToolPolicy:S,fleetUpdatePolicy:O,fleetHookPolicy:F,...L}=I;await r({...L,...C?{fleetToolPolicy:C}:{},...R?{fleetUpdatePolicy:R}:{},...A?{fleetHookPolicy:A}:{}})}return{routingUpdated:f,teamUpdated:p,laneUpdated:m,toolsRequested:h,toolsApplied:b,toolsEnrolled:k,profileUpdated:f||p||m,updatesMode:R?.mode??"auto",updatesUpdated:_}},lge="generic",UK="claude-code",dge=e=>e.readers?.length===1?e.readers[0]:lge,uge=(e,t)=>{let n=dge(t);return e.variants&&Object.hasOwn(e.variants,n)?e.variants[n]:e.body},wO=(e,t)=>hge({...e,body:uge(e,t)}),ty=(e,t=ge,n=new Set)=>{let r=e.managedTools,o=i=>i.id===UK,a=HK(t.find(o)??ge.find(o)),s=new Map;for(let i of t){if(r&&!r.includes(i.id))continue;let c=HK(i),l=!n.has(i.id);for(let d of c){if(!d)continue;let u=s.get(d),f=a.includes(d)?UK:i.id,p=u?.readers??[];s.set(d,{dir:d,includePluginSkills:(u?.includePluginSkills??!1)||l,readers:p.includes(f)?p:[...p,f]})}}return[...s.values()]},HK=e=>{let t=e?.skillsDir?.();return typeof t=="string"?[t]:t??[]},fge=e=>e.map(t=>typeof t=="string"?{dir:t,includePluginSkills:!0}:t),YK=async(e,t)=>{await AO(ri(e,t,"SKILL.md"),{force:!0}),await Vye(ri(e,t)).catch(()=>{})},GK=async(e,t)=>{try{return await kO(ri(e,t,"SKILL.md"),"utf-8")}catch(n){if(n?.code==="ENOENT")return null;throw n}},pge=async(e,t,n)=>{let r=ri(e,`.SKILL.md.anyray-tmp-${process.pid}-${Jye()}`);try{await Zye(r,n,{encoding:"utf-8",flag:"wx"}),await ze(r,t)}finally{await AO(r,{force:!0}).catch(()=>{})}},WK=(e,t,n)=>t!==void 0&&UA(e)===t||n!==void 0&&e===n,bO=()=>ri(Yye(),".anyray-claude-skill.json"),UA=e=>Xye("sha256").update(e).digest("hex"),mge=async e=>{try{let t=await ae(bO());if(t.dir!==e||typeof t.digest!="string")return;let n=await kO(ri(e,"anyray","SKILL.md"),"utf8");if(UA(n)!==t.digest)return;await YK(e,"anyray"),await AO(bO(),{force:!0})}catch{}},hge=e=>{let t=e.body.replace(/\r\n?/g,`
692
+ `),1}}});import{execFile as Pye}from"node:child_process";import{readFile as Lye}from"node:fs/promises";import{platform as Nye}from"node:os";import{promisify as Dye}from"node:util";var Mye,OK,TK,Qh,$ye,Bye,PK,lO,NA=U(()=>{"use strict";vf();dt();At();to();Vl();cc();Mye=Dye(Pye),OK=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),TK=(e,t)=>{if(e.inferenceCredentialHelper!==Qa)return!1;try{let n=new URL(t.anthropicBaseUrl);if(typeof e.bootstrapUrl=="string"){let r=new URL(e.bootstrapUrl);return e.bootstrapEnabled!==!1&&e.bootstrapEnabled!=="false"&&r.origin===n.origin&&r.pathname==="/connect/claude-desktop/bootstrap"&&(r.searchParams.get("os")??"macos")==="macos"&&!r.username&&!r.password}return e.inferenceProvider==="gateway"&&e.inferenceCredentialKind==="helper-script"&&qu(e.inferenceGatewayAuthScheme)&&typeof e.inferenceGatewayBaseUrl=="string"&&new URL(e.inferenceGatewayBaseUrl).href===n.href}catch{return!1}},Qh=async(e,t={})=>{if((t.platform??Nye)()!=="darwin")return!1;let n=await wr(An(t),t);if(!n||n.unreadable)return!1;let r=await(t.readManagedPolicy??af)(n.path);return r!==void 0&&TK(r,{anthropicBaseUrl:e})},$ye=async()=>{let{stdout:e}=await Mye(Qa,[],{timeout:3e4,maxBuffer:65536});return e},Bye=async(e,t)=>{try{let n=await(t.runFleetCredentialHelper??$ye)(),r=JSON.parse(n);return OK(r)&&U0(r.token)&&OK(r.headers)&&r.headers["x-anyray-auth-mode"]==="passthrough"&&r.headers["x-anyray-provider"]==="anthropic"&&typeof r.headers["x-anyray-api-key"]=="string"&&St(r.headers["x-anyray-api-key"])&&r.headers["x-anyray-api-key"]===e.clientKey}catch{return!1}},PK=async(e,t,n,r)=>{if(!(!t.explicit||!t.reportsToUser||n.unreadable||!Te(e,"anthropic")))return lO(e,n,r,t.dryRun)},lO=async(e,t,n,r)=>{let o=(a,s)=>({status:"manual",failureClass:a,messages:[s]});try{let a=await(n.readManagedPolicy??af)(t.path);if(!a||!TK(a,e))return;let s=await(n.readFleetCredentialHelper??(()=>Lye(Qa,"utf8")))();if(!SK(s))return o("credential_helper_foreign","The managed Claude Desktop credential helper is not the packaged Anyray helper. Repair the Anyray Connect package, then retry.");if(r)return await(n.claudeCodeInstalled??Zu)()?{status:"held",messages:["Would authorize your Claude subscription and verify the installed MDM credential helper. The managed policy stays installed."]}:o("claude_missing","Claude subscription authorization needs Claude Code. Install it, then retry.");let i=await(n.ensureSeatToken??Xa)();return i.status==="missing-claude"?o("claude_missing","Claude subscription authorization needs Claude Code. Install it, then retry."):i.status==="mint-failed"||i.status==="no-token-output"?o("seat_token_mint_failed","Claude subscription authorization did not complete. Re-run anyray-connect --subscription --tools claude-desktop and finish the browser approval."):await Bye(e,n)?{status:"held",messages:["Your Claude subscription is authorized. In Claude, click Check again. If it still asks, quit and reopen Claude."]}:(i.status==="minted"&&await(n.removeSeatToken??ac)().catch(()=>{}),o("credential_helper_failed","The installed MDM credential helper did not produce Claude subscription passthrough credentials. Repair the Anyray Connect package or its stored billing mode, then retry."))}catch{return o("credential_helper_failed","Could not prepare the managed Claude subscription credential. Check the Anyray Connect package and retry.")}}});var Ht,Lo=U(()=>{"use strict";ue();ta();dt();Ht=async(e=J,t=Ba)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:bt({origin:n.gateway,clientKey:n.clientKey,subscription:n.authMode==="subscription",placeholder:n.authMode==="placeholder",byoUpstream:n.byoUpstream,seat:r,user:n.name,team:n.team})}}});import{homedir as Fye}from"node:os";import{join as Uye}from"node:path";import{rm as Hye}from"node:fs/promises";import{z as dO}from"zod";var ey,LK,ua,ni,uO,it,NK,fO,yc,es,No=U(()=>{"use strict";Ze();un();ey=["gateway","gateway_hooks","gateway_hooks_mcp"],LK=dO.object({level:dO.enum(ey),source:dO.enum(["agent","user","team","org","default"])}).strict(),ua={level:"gateway_hooks_mcp",source:"default"},ni=async(e,t,n={})=>{if(t?.trim())try{let r=await Zn(e,t.trim(),void 0,n);if(typeof r!="object"||r===null||Array.isArray(r))return;if(!Object.hasOwn(r,"integrationLevel"))return ua;let o=LK.safeParse(r.integrationLevel);return o.success?o.data:void 0}catch{return}},uO=()=>Uye(Fye(),".anyray-integration-level.json"),it=async()=>{try{let e=LK.safeParse(await ae(uO()));return e.success?e.data:void 0}catch{return}},NK=async e=>ye(uO(),e,{backup:!1}),fO=async()=>Hye(uO(),{force:!0}),yc=e=>e!=="gateway",es=e=>e==="gateway_hooks_mcp"});var Qn,Gye,DK,gc,MK,$K,ts=U(()=>{"use strict";At();Qn=(e,t)=>e?.tiers?.[t]==="locked"?"locked":"recommended",Gye=e=>e==="subscription"?"subscription":"placeholder",DK=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?Gye(t.lane):void 0,a=o!=null&&o!==e.authMode;return{routingUpdated:n,teamUpdated:r,laneUpdated:a,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{},...a?{authMode:o}:{}}},gc=(e,t,n,r)=>{let o=new Set(t.enabled??[]),a=e.managedTools??[],s=a.filter(u=>o.has(u)||n);if(t.defaulted===!0&&(e.toolSelection!=="all"||e.toolOptIn===!0))return{candidateIds:s,freshIds:[]};let i=new Set(e.revertedTools??[]),c=e.revertedTools!=null,l=new Set(r.filter(Xo).map(u=>u.id)),d=[];for(let u of o)a.includes(u)||Qn(t,u)!=="locked"&&(l.has(u)||!c||i.has(u)||e.toolOptIn===!0)||d.push(u);return{candidateIds:s,freshIds:d}},MK=(e,t,n)=>{let r=[],o=[],a=[],s=new Set(e.revertedTools??[]),i=new Set(e.managedTools??[]);if(t===void 0||t.defaulted===!0){for(let l of n)s.has(l.id)&&!i.has(l.id)?a.push({id:l.id,reason:"opted_out"}):Xo(l)?a.push({id:l.id,reason:"consent"}):r.push(l.id);return{applyIds:r,revertIds:o,skipped:a}}let c=new Set(t.enabled??[]);for(let l of n){let{id:d}=l;if(!c.has(d)){i.has(d)?o.push(d):a.push({id:d,reason:"not_enabled"});continue}if(i.has(d)){r.push(d);continue}let u=Qn(t,d);if(s.has(d)&&u!=="locked"){a.push({id:d,reason:"opted_out"});continue}if(Xo(l)){u==="locked"?r.push(d):a.push({id:d,reason:"consent"});continue}r.push(d)}return{applyIds:r,revertIds:o,skipped:a}},$K=(e,t,n)=>{let r=new Set(e.managedTools??[]),o=new Set(t?.enabled??[]);return n.map(a=>a.id).filter(a=>r.has(a)||o.has(a)&&Qn(t,a)==="locked")}});import{z as pO}from"zod";var Wye,mO,jye,BK,hO=U(()=>{"use strict";un();Wye=5e3,mO=pO.object({url:pO.string().url().refine(e=>/^https:\/\//i.test(e))}).optional().catch(void 0),jye=pO.object({personalUpstream:mO}),BK=async(e,t,n={})=>{if(t?.trim())try{let r=await Zn(e,t.trim(),void 0,{...n,timeoutMs:n.timeoutMs??Wye}),o=jye.safeParse(r);return o.success?o.data.personalUpstream?.url:void 0}catch{return}}});import{mkdir as Kye,readFile as kO,rm as AO,rmdir as Vye,writeFile as Zye}from"node:fs/promises";import{join as ri}from"node:path";import{homedir as Yye}from"node:os";import{createHash as Xye,randomUUID as Jye}from"node:crypto";import{z as De}from"zod";var zye,qye,ns,vO,KK,gO,Qye,ege,tge,Cf,CO,yO,MA,rs,FK,$A,BA,FA,nge,VK,rge,ZK,oge,age,sge,ige,cge,SO,Sf,lge,UK,dge,uge,wO,ty,HK,fge,YK,GK,pge,WK,bO,UA,mge,hge,DA,yge,gge,wge,bge,kge,Age,vge,_f,XK,jK,ed,Cge,JK,HA,Sge,zK,qK,Ef,QK,GA,ro=U(()=>{"use strict";_n();Pt();No();Ze();dt();xa();ck();un();ts();ue();hO();Lo();os();zye=1e4,qye=1,ns="anyray",vO=async(e,t)=>{let n=e.skills.some(r=>r.id===ns);return kt(r=>r.gateway!==t.gateway||r.clientKey!==t.clientKey?{result:!1}:!n&&e.skillsIncomplete?{result:!0}:(n?r.builtinSkillRequired===!0:r.builtinSkillRequired!==!0)?{result:!0}:{next:{...r,builtinSkillRequired:n},result:!0}).then(r=>r?"completed":"incomplete",()=>"incomplete")},KK=De.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),gO=/^[a-z0-9][a-z0-9-]{0,31}$/,Qye=De.object({id:KK,name:De.string().min(1),version:De.string().min(1),body:De.string(),variants:De.record(De.string().regex(gO),De.string()).optional().catch(void 0),plugin:De.boolean().optional()}),ege=De.object({url:De.string().url(),plugins:De.array(KK)}),tge=De.object({version:De.literal(qye).optional(),skills:De.array(Qye),skillsIncomplete:De.boolean().optional(),marketplace:ege.optional(),mcp:De.object({org:De.object({url:De.string().url()})}).optional(),retrievalMcp:De.object({url:De.string().url()}).optional().catch(void 0),personalUpstream:mO,updatedAt:De.string().min(1).optional(),routing:De.object({origin:De.string().min(1)}).optional(),team:De.string().min(1).optional(),lane:De.enum(["subscription","org"]).optional().catch(void 0),tools:De.object({enabled:De.array(De.string().min(1)),defaulted:De.literal(!0).optional().catch(void 0),tiers:De.record(De.string().min(1),De.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional(),updates:De.object({mode:De.enum(["auto","directed","off"]).catch("directed")}).optional(),hooks:De.object({digest:De.enum(["on","off"]).catch("off"),readTrim:De.enum(["on","off"]).optional().catch("off"),readTrimRequiresRetrieve:De.enum(["on","off"]).optional().catch("on"),lifecycle:De.enum(["on","off"]).optional().catch("off"),prompt:De.enum(["on","off"]).optional().catch("off"),logRead:De.enum(["on","off"]).optional().catch("off"),fleetReadBack:De.enum(["on","off"]).optional().catch("off"),digestEconomics:De.enum(["on","off"]).optional().catch("off"),rangedArrival:De.enum(["on","off"]).optional().catch("off")}).optional(),capabilities:De.array(De.string()).optional().catch(void 0),clientAssets:ox.optional().catch(void 0)}),Cf=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},CO=e=>e instanceof Cf&&e.kind==="auth",yO=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",MA=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",rs=async(e,t,n={})=>{let r=n.timeoutMs??zye,o=`${e}/connect/policy`,a;try{a=await Zn(e,t,void 0,{policySnapshot:n.policySnapshot,timeoutMs:r})}catch(s){if(s instanceof Ls&&s.details.status!==void 0)throw new Cf(s.kind==="auth"?"auth":"unavailable",`team policy fetch failed: the gateway responded ${s.details.status} at ${o}`);if(s instanceof Ls&&s.kind==="unavailable"){let i=s.details.timeoutMs!==void 0?` no response within ${s.details.timeoutMs}ms.`:s.details.networkSuffix??"";throw new Cf("unavailable",`could not reach the gateway at ${o}.${i}`)}throw new Cf("malformed","team policy fetch failed: the gateway returned a malformed response")}return tge.parse(a)},FK=64,$A=e=>{let t=e.tools;if(!t||t.defaulted===!0)return;let n=t.enabled.filter(o=>gO.test(o)).slice(0,FK).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>gO.test(o)).slice(0,FK).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},BA=async()=>{await kt(e=>({next:{...e,policyReceivedAt:new Date().toISOString()},result:void 0}))},FA=async(e,t,n=rs,r)=>{let o=await n(e,t,{policySnapshot:r}),a=$A(o);return await kt(s=>{let{fleetToolPolicy:i,...c}=s;return{next:{...c,...a?{fleetToolPolicy:a}:{}},result:void 0}}),o},nge=e=>({mode:e.updates?.mode??"auto"}),VK=(e,t)=>e.hooks?{digest:e.hooks.digest,...e.hooks.readTrim==="on"?{readTrim:"on"}:{},...e.hooks.readTrimRequiresRetrieve==="on"?{readTrimRequiresRetrieve:"on"}:{},...e.hooks.lifecycle==="on"?{lifecycle:"on"}:{},...e.hooks.logRead==="off"?{logRead:"off"}:{},...e.hooks.fleetReadBack==="on"?{fleetReadBack:"on"}:{},...e.hooks.digestEconomics==="on"?{digestEconomics:"on"}:{},...e.hooks.rangedArrival==="on"?{rangedArrival:"on"}:{}}:t,rge=e=>kt(t=>{let n=VK(e,t.fleetHookPolicy);if(JSON.stringify(n??null)===JSON.stringify(t.fleetHookPolicy??null))return{result:void 0};let{fleetHookPolicy:r,...o}=t;return{next:{...o,...n?{fleetHookPolicy:n}:{}},result:void 0}}),ZK=2,oge=(e,t)=>{let{retrievalMcpUrl:n,retrievalMcpMisses:r,...o}=e;if(t)return e.retrievalMcpUrl===t&&e.retrievalMcpMisses===void 0?e:{...o,retrievalMcpUrl:t};if(e.retrievalMcpUrl===void 0)return e.retrievalMcpMisses===void 0?e:o;let a=(e.retrievalMcpMisses??0)+1;return a>=ZK?o:{...e,retrievalMcpMisses:a}},age=(e,t)=>{let{personalUpstreamUrl:n,personalUpstreamMisses:r,...o}=e;if(t)return e.personalUpstreamUrl===t&&e.personalUpstreamMisses===void 0?e:{...o,personalUpstreamUrl:t};if(e.personalUpstreamUrl===void 0)return e.personalUpstreamMisses===void 0?e:o;let a=(e.personalUpstreamMisses??0)+1;return a>=ZK?o:{...e,personalUpstreamMisses:a}},sge=e=>kt(t=>{let n=age(t,e.personalUpstream?.url);return n===t?{result:void 0}:{next:n,result:void 0}}),ige=e=>kt(t=>{let n=oge(t,e.retrievalMcp?.url);return n===t?{result:void 0}:{next:n,result:void 0}}),cge=async(e={})=>{let t=await(e.loadProfile??J)(),n=e.adapters??ge,r=t.managedTools??await QK(n,t.gateway),o=[],a=[];for(let s of n){if(!s.syncRetrievalMcp||!r.includes(s.id))continue;let i=await s.syncRetrievalMcp().catch(()=>null);if(!i||i.completion==="incomplete"){a.push(s.id);continue}i.changed&&o.push(s.id)}return{changed:o,failed:a}},SO=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?Qn(n,t)==="locked":!1},Sf=async(e,t={})=>{let n=t.loadProfile??En,r=t.saveProfile??Tt,o=t.targetFromProfile??Ht,a=t.adapters??ge,s=t.repairTools??Do,i=t.recordManaged??_a,c=t.recordClientAssets??ix,l=await n(),d={...l},u=DK(l,{routingOrigin:e.routing?.origin?jo(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:f,teamUpdated:p,laneUpdated:m}=u;(f||p||m)&&(d={...await n()},u.gateway!=null&&(d.gateway=u.gateway),u.team!=null&&(d.team=u.team),u.authMode!=null&&(d.authMode=u.authMode),await r(d));let y=gc(d,{enabled:e.tools?.enabled,tiers:e.tools?.tiers,defaulted:e.tools?.defaulted},f||p||m,a),{candidateIds:g,freshIds:w}=y,h=0,b=0,k=0;if(g.length>0||w.length>0){let S=await o(async()=>d);if(S){await c(S.target.origin,e.clientAssets).catch(()=>{});let O;if(f||p||m){let $=new Set(g);O=[];for(let B of a)if($.has(B.id))try{(await B.detect()).installed&&O.push(B)}catch{}}else{O=await If(g,S.target.origin,a);let $=new Set(e.capabilities??[]),B=new Set(O.map(D=>D.id));for(let D of await fa(g,a))if(!(B.has(D.id)||!D.gatewayFeatureDrift))try{if(D.automaticRepairAllowed&&!await D.automaticRepairAllowed())continue;await D.gatewayFeatureDrift($,t.policySnapshot)&&O.push(D)}catch{}}let F=new Set(w),L=[];for(let $ of a)if(F.has($.id))try{(await $.detect()).installed&&L.push($)}catch{}if(h=O.length+L.length,h>0){let $=await s([...O,...L],S.target,t.policySnapshot);b=$.filter(Ql).length;let B=$.filter(D=>F.has(D.id));if(k=B.filter(Ql).length,B.length>0)try{await i(B,!1)}catch{}}}}let C=$A(e),R=nge(e),I=await n(),A=VK(e,I.fleetHookPolicy),x=JSON.stringify(C??null)!==JSON.stringify(I.fleetToolPolicy??null),_=JSON.stringify(R??null)!==JSON.stringify(I.fleetUpdatePolicy??null),v=JSON.stringify(A??null)!==JSON.stringify(I.fleetHookPolicy??null);if(x||_||v){let{fleetToolPolicy:S,fleetUpdatePolicy:O,fleetHookPolicy:F,...L}=I;await r({...L,...C?{fleetToolPolicy:C}:{},...R?{fleetUpdatePolicy:R}:{},...A?{fleetHookPolicy:A}:{}})}return{routingUpdated:f,teamUpdated:p,laneUpdated:m,toolsRequested:h,toolsApplied:b,toolsEnrolled:k,profileUpdated:f||p||m,updatesMode:R?.mode??"auto",updatesUpdated:_}},lge="generic",UK="claude-code",dge=e=>e.readers?.length===1?e.readers[0]:lge,uge=(e,t)=>{let n=dge(t);return e.variants&&Object.hasOwn(e.variants,n)?e.variants[n]:e.body},wO=(e,t)=>hge({...e,body:uge(e,t)}),ty=(e,t=ge,n=new Set)=>{let r=e.managedTools,o=i=>i.id===UK,a=HK(t.find(o)??ge.find(o)),s=new Map;for(let i of t){if(r&&!r.includes(i.id))continue;let c=HK(i),l=!n.has(i.id);for(let d of c){if(!d)continue;let u=s.get(d),f=a.includes(d)?UK:i.id,p=u?.readers??[];s.set(d,{dir:d,includePluginSkills:(u?.includePluginSkills??!1)||l,readers:p.includes(f)?p:[...p,f]})}}return[...s.values()]},HK=e=>{let t=e?.skillsDir?.();return typeof t=="string"?[t]:t??[]},fge=e=>e.map(t=>typeof t=="string"?{dir:t,includePluginSkills:!0}:t),YK=async(e,t)=>{await AO(ri(e,t,"SKILL.md"),{force:!0}),await Vye(ri(e,t)).catch(()=>{})},GK=async(e,t)=>{try{return await kO(ri(e,t,"SKILL.md"),"utf-8")}catch(n){if(n?.code==="ENOENT")return null;throw n}},pge=async(e,t,n)=>{let r=ri(e,`.SKILL.md.anyray-tmp-${process.pid}-${Jye()}`);try{await Zye(r,n,{encoding:"utf-8",flag:"wx"}),await ze(r,t)}finally{await AO(r,{force:!0}).catch(()=>{})}},WK=(e,t,n)=>t!==void 0&&UA(e)===t||n!==void 0&&e===n,bO=()=>ri(Yye(),".anyray-claude-skill.json"),UA=e=>Xye("sha256").update(e).digest("hex"),mge=async e=>{try{let t=await ae(bO());if(t.dir!==e||typeof t.digest!="string")return;let n=await kO(ri(e,"anyray","SKILL.md"),"utf8");if(UA(n)!==t.digest)return;await YK(e,"anyray"),await AO(bO(),{force:!0})}catch{}},hge=e=>{let t=e.body.replace(/\r\n?/g,`
693
693
  `),n=t.startsWith(`---
694
694
  `)?t.indexOf(`
695
695
  ---`,4):-1,r=n+4,o=n>=0&&(r>=t.length||t[r]===`
@@ -750,7 +750,7 @@ ${t.stderr??""}`}},FJ=async e=>{try{return(await P_e(e)).isDirectory()?"present"
750
750
  `).join("");return{body:T,bodyBytes:Buffer.byteLength(T),sourceBytes:N}},g=[],w=[],h=0,b,k=0;for(let[_,v]of u.entries()){let S;try{S=y(_,v)}catch(B){if(!i||!(B instanceof Hr)||!OEe(B.code))throw B;w.push({entry:_+1,code:B.code,failure:B});continue}let{body:O,bodyBytes:F,sourceBytes:L}=S;if(k+=L,k>wL){i||mn("batch_too_large",_+1),b="batch_too_large";break}let $=JSON.stringify({path:d[_].path,start_line:d[_].offset,bytes:F})+`
751
751
  `+O+`
752
752
  `;if(i&&p(g.length+1).length+h+$.length>o){b="result_bound";break}g.push({entry:_+1,text:$}),h+=$.length}if(!b&&!w.length){let _=p(g.length)+g.map(({text:v})=>v).join("");return _.length>o&&mn("result_bound"),_}let C=b,R=d.map(({path:_})=>_),I=!0,A=TEe(w,R),x=()=>LEe(g.map(({entry:_})=>_),d.length,w,R,C,I,o);for(;g.length&&p(g.length).length+h+x().length>o;){if(I&&A){I=!1;continue}h-=g.pop().text.length,C="result_bound"}if(!g.length)throw w[0]?.failure??new Hr("result_bound");return p(g.length)+g.map(({text:_})=>_).join("")+x()}finally{f.close()}}catch(a){throw a instanceof Hr?a:new Hr("file_unavailable")}}});import{z as lo}from"zod";var $Ee,Sz,BC,_p,Sd,_d=U(()=>{"use strict";$C();$Ee=lo.object({searchBatch:lo.boolean().default(!1),searchContext:lo.boolean().default(!1),searchContextHints:lo.boolean().default(!0),readBatch:lo.boolean().default(!0),readBatchAlwaysLoad:lo.boolean().default(!0),readBatchInstructions:lo.boolean().default(!0),readBatchRanges:lo.boolean().default(!0),readBatchNudge:lo.boolean().default(!0),readBatchCodexNudge:lo.boolean().default(!0),readBatchMainHint:lo.boolean().default(!0),webFetchRefusalNote:lo.boolean().default(!0),teeFooterIdRoute:lo.boolean().default(!0)}),Sz={searchContext:!1,searchContextHints:!1,searchBatch:!1,readBatch:!1,readBatchAlwaysLoad:!1,readBatchInstructions:!1,readBatchRanges:!1,readBatchNudge:!1,readBatchCodexNudge:!1,readBatchMainHint:!1,webFetchRefusalNote:!1,teeFooterIdRoute:!1},BC=e=>{try{let t=$Ee.safeParse(e??{});return t.success?{policies:t.data,invalid:!1}:{policies:Sz,invalid:!0}}catch{return{policies:Sz,invalid:!0}}},_p=e=>BC(e).policies,Sd=async(e,t=Wc)=>{let{policies:n,invalid:r}=BC(e),o=n.teeFooterIdRoute?"id_route":"legacy",a=n.readBatchAlwaysLoad,s=n.readBatchInstructions,i=n.readBatchNudge,c=n.readBatchCodexNudge,l=n.readBatchMainHint,d=n.webFetchRefusalNote,u=n.searchContextHints,f=r?"invalid_policy":n.searchBatch?"enabled":"off",p={readBatchAlwaysLoad:a,readBatchInstructions:s,readBatchNudge:i,readBatchCodexNudge:c,readBatchMainHint:l,webFetchRefusalNote:d,searchContextHints:u,searchBatch:f,teeFooterWording:o};if(r)return{...p,readBatch:"invalid_policy",searchContext:"invalid_policy"};if(!n.readBatch&&!n.searchContext)return{...p,readBatch:"off",searchContext:"off"};let m=await t().catch(()=>"native_binding_unavailable"),y=m===!0||m==="supported"?"enabled":m===!1?"unsupported_platform":m;return{...p,searchContext:n.searchContext?y:"off",readBatch:n.readBatch?y==="enabled"&&n.readBatchRanges?"enabled_ranged":y:"off"}}});import{homedir as BEe}from"node:os";import{join as FEe}from"node:path";import{rm as UEe}from"node:fs/promises";var FC,_z,kL,AL,Ez,ng,Iz,tg,UC,vL,xz=U(()=>{"use strict";Ze();FC=["WebSearch","DesignSync"],_z=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kL=e=>{let t=e.permissions;if(_z(t))return Array.isArray(t.deny)?t.deny:void 0},AL=e=>{if(e.permissions!==void 0&&!_z(e.permissions))return!1;let t=e.permissions??{};return t.deny===void 0||Array.isArray(t.deny)},Ez=(e,t,n=FC)=>{let r=kL(e)??[],o=n.filter(i=>t.includes(i)&&r.includes(i));if(!AL(e))return o;let a=n.filter(i=>!r.includes(i));if(a.length===0)return o;let s=e.permissions??{};return s.deny=[...r,...a],e.permissions=s,n.filter(i=>o.includes(i)||a.includes(i))},ng=(e,t)=>{let n=kL(e);if(!n||t.length===0)return!1;let r=n.filter(a=>!(typeof a=="string"&&t.includes(a)));if(r.length===n.length)return!1;let o=e.permissions;return r.length>0?o.deny=r:(delete o.deny,Object.keys(o).length===0&&delete e.permissions),!0},Iz=(e,t=FC)=>{let n=kL(e)??[];return t.every(r=>n.includes(r))},tg=()=>FEe(BEe(),".anyray","claude-code-denied-tools.json"),UC=async()=>{try{let e=await ae(tg());return Array.isArray(e.rules)?e.rules.filter(t=>typeof t=="string"):[]}catch{return[]}},vL=async e=>{if(e.length===0){await UEe(tg(),{force:!0});return}await ye(tg(),{rules:[...e]},{backup:!1})}});import{z as CL}from"zod";var HEe,GEe,WEe,jEe,Rz,Oz,KEe,Ed,VEe,Tz,ZEe,SL,Pz,Lz,Nz=U(()=>{"use strict";un();HEe=5e3,GEe=1e3,WEe=1e8,jEe=CL.object({modelContext:CL.object({contextTokens:CL.number().int().min(GEe).max(WEe)}).optional()}),Rz=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},Oz=async(e,t,n,r={})=>{if(!(!t||!n))try{let o=await Zn(e,t,n,{...r,timeoutMs:r.timeoutMs??HEe}),a=jEe.safeParse(o);return a.success?a.data.modelContext?.contextTokens:void 0}catch{return}},KEe=1e6,Ed="[1m]",VEe=new Set(["default","best","fable","opus","sonnet","haiku","opusplan"]),Tz=e=>{let t=e.trim().toLowerCase(),n=t.endsWith(Ed)?t.slice(0,-Ed.length):t;return VEe.has(n)},ZEe=e=>{let t=e.trim().toLowerCase();return Tz(e)||t.startsWith("claude-")||t.split(/[/.]/).some(n=>n.startsWith("claude-"))},SL=e=>!ZEe(e),Pz=(e,t)=>!e||t===void 0?{}:SL(e)?{envTokens:t}:Tz(e)?{}:t<KEe?{}:e.toLowerCase().endsWith(Ed)?{}:{model:`${e}${Ed}`},Lz=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(Ed))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(Ed))return e.slice(0,-Ed.length)}});var vi,HC,YEe,Dz,Mz,_L,EL,$z,GC=U(()=>{"use strict";Vo();vi=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"},{name:"CLAUDE_CODE_USE_FOUNDRY",cloud:"Microsoft Foundry"}],HC=e=>typeof e=="string"&&e.trim()!=="",YEe=(e,t)=>typeof e[t]=="string"&&!HC(e[t]),Dz=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},Mz=async(e={})=>{let t=e.env??process.env,n=Dz(e.userSettings??{}),r=await Ea(e),o=Dz(r.settings),a=[];for(let{name:s,cloud:i}of vi)HC(o[s])?a.push({name:s,cloud:i,kind:"managed",source:r.originOf(`env.${s}`)??`managed settings (${en()})`,repairable:!1}):HC(n[s])?a.push({name:s,cloud:i,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!YEe(n,s)&&HC(t[s])&&a.push({name:s,cloud:i,kind:"shell",source:"shell environment",repairable:!0});return a},_L=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`,EL=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.",$z=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 Nt,XEe,IL,WC,rg,xL,JEe,Fz,RL,Uz,Bz,ka,OL,Hz,og,jC=U(()=>{"use strict";Nt="anyray-retrieval",XEe="/mcp",IL="x-anyray-api-key",WC=["anyray_retrieve","anyray_recall"],rg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xL=e=>{if(typeof e=="string")try{return new URL(e)}catch{return}},JEe=e=>xL(e)?.origin,Fz=e=>e!==void 0&&(e.protocol==="https:"||e.protocol==="http:")&&e.pathname.replace(/\/+$/,"")===XEe&&e.search===""&&e.hash==="",RL=e=>{let t=JEe(e.gateway);if(!t||!e.clientKey||!e.retrievalMcpUrl)return;let n=xL(e.retrievalMcpUrl);return Fz(n)&&n.origin===t&&n.username===""&&n.password===""?{url:n.href,clientKey:e.clientKey}:void 0},Uz=e=>({type:"http",url:e.url,headers:{[IL]:e.clientKey},alwaysLoad:!0}),Bz=(e,t)=>{let n=Object.keys(e).sort();return n.length===t.length&&t.every((r,o)=>r===n[o])},ka=e=>rg(e)&&Bz(e,["alwaysLoad","headers","type","url"])&&e.type==="http"&&e.alwaysLoad===!0&&Fz(xL(e.url))&&rg(e.headers)&&Bz(e.headers,[IL])&&typeof e.headers[IL]=="string",OL=(e,t)=>JSON.stringify(e)===JSON.stringify(Uz(t)),Hz=(e,t)=>{if("mcpServers"in e&&!rg(e.mcpServers))return"conflict";let n=rg(e.mcpServers)?{...e.mcpServers}:{},r=n[Nt];return r!==void 0&&!ka(r)?"conflict":(n[Nt]=Uz(t),e.mcpServers=n,"installed")},og=e=>{let t=e.mcpServers;return!rg(t)||!ka(t[Nt])?!1:(delete t[Nt],Object.keys(t).length===0&&delete e.mcpServers,!0)}});var zEe,PL,Ep,ag,LL,NL,TL,KC,Gz,Id,sg,Wz=U(()=>{"use strict";jC();zEe="anyray",PL=["anyray_retrieve","anyray_recall","anyray_read_batch","anyray_history"],Ep=PL.map(e=>`mcp__${zEe}__${e}`),ag=WC.map(e=>`mcp__${Nt}__${e}`),LL=[...Ep,...ag],NL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),TL=e=>{let t=e.permissions;if(NL(t))return Array.isArray(t.allow)?t.allow:void 0},KC=e=>{if(e.permissions!==void 0&&!NL(e.permissions))return!1;let t=e.permissions??{};return t.allow===void 0||Array.isArray(t.allow)},Gz=(e,t=Ep)=>{if(e.permissions!==void 0&&!NL(e.permissions))return!1;let n=e.permissions??{};if(n.allow!==void 0&&!Array.isArray(n.allow))return!1;let r=n.allow??[],o=t.filter(a=>!r.includes(a));return o.length===0?!1:(n.allow=[...r,...o],e.permissions=n,!0)},Id=(e,t={},n=Ep)=>{let r=TL(e);if(!r)return!1;let o=TL(t)??[],a=new Set(n.filter(c=>!o.includes(c))),s=r.filter(c=>!(typeof c=="string"&&a.has(c)));if(s.length===r.length)return!1;let i=e.permissions;return s.length>0?i.allow=s:(delete i.allow,Object.keys(i).length===0&&delete e.permissions),!0},sg=(e,t=Ep)=>{let n=TL(e)??[],r=t.filter(o=>n.includes(o)).length;return r===t.length?"approved":r===0?"none":"partial"}});var qEe,QEe,jz,Kz,eIe,tIe,Vz,Zz,nIe,rIe,oIe,Yz,aIe,Xz,VC,ZC,Jz,zz,qz,DL=U(()=>{"use strict";Vo();Yi();GC();wl();Et();qEe=vi.map(e=>e.name),QEe=[...Ib.filter(e=>!qEe.includes(e)),"ENABLE_TOOL_SEARCH"],jz=e=>typeof e=="string"&&e.trim()!=="",Kz=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},eIe=(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)},tIe="x-anyray-metadata",Vz=e=>{let t=new Map;for(let n of e.split(`
753
- `)){let r=n.indexOf(":");r>0&&t.set(n.slice(0,r).trim().toLowerCase(),n.slice(r+1).trim())}return t},Zz=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}},nIe=(e,t)=>{let n=Zz(e),r=Zz(t);return!n||!r?e!==t:Object.entries(n).some(([o,a])=>o in r&&JSON.stringify(r[o])!==JSON.stringify(a))},rIe=(e,t)=>{let n=Vz(e);for(let[r,o]of Vz(t)){let a=n.get(r);if(r===tIe){if(a!==void 0&&nIe(a,o))return!0}else if(a!==o)return!0}return!1},oIe=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Yz=async()=>(await Ea({})).settings,aIe=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=>Cd(r,On))},Xz=async(e={})=>{let t=await Ea(e),n=t.settings;return n.disableAllHooks===!0?{state:"disabled",source:t.originOf("disableAllHooks")}:n.allowManagedHooksOnly===!0&&!aIe(n)?{state:"restricted_dropping_ours",source:t.originOf("allowManagedHooksOnly")}:{state:"fine"}},VC=e=>{let t=e.source??`managed settings (${en()})`;return e.state==="disabled"?`disableAllHooks is true in ${t} \u2014 Claude Code skips every hook and the status line, including Anyray's savings hook`:e.state==="restricted_dropping_ours"?`allowManagedHooksOnly is true in ${t}, but the managed hooks do 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"},ZC=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.",Jz=async(e={})=>{let t=Kz(e.userSettings??{}),n=await Ea(e),r=Kz(n.settings),o=[];for(let a of QEe){if(!jz(r[a])||!jz(t[a]))continue;let s=a==="ANTHROPIC_BASE_URL";if(a==="ANTHROPIC_CUSTOM_HEADERS"){if(!rIe(String(r[a]),String(t[a])))continue}else if(eIe(r[a],t[a],s))continue;if(a==="ENABLE_TOOL_SEARCH"&&r[a]===wu&&Io(t[a]))continue;let i=s?oIe(r[a]):void 0;o.push({name:a,source:n.originOf(`env.${a}`)??`managed settings (${en()})`,routing:s,...i?{managedOrigin:i}:{}})}return o},zz=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`,qz=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."});var Hn,Qz,ML,$L,e3=U(()=>{"use strict";Hn="ANTHROPIC_API_KEY",Qz=e=>typeof e=="string"&&e.trim()!=="",ML=e=>{let t=e.userSettings?.env,n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};if(Qz(n[Hn]))return{source:"~/.claude/settings.json env block"};if(!(typeof n[Hn]=="string")&&Qz((e.env??process.env)[Hn]))return{source:"shell environment"}},$L=e=>`${Hn} is set (${e.source}) and Claude Code ranks it above the apiKeyHelper, so that key would be sent instead of the gateway key`});var sIe,BL,iIe,t3,cIe,n3,lIe,dIe,uIe,fIe,r3,o3=U(()=>{"use strict";sIe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),BL=e=>Array.isArray(e)?e.filter(sIe):void 0,iIe=(e,t)=>{let n=0,r=0,o=-1,a=0;for(;r<t.length;)if(n<e.length&&e[n]==="*")o=n,n+=1,a=r;else if(n<e.length&&e[n]===t[r])n+=1,r+=1;else if(o>=0)n=o+1,a+=1,r=a;else return!1;for(;n<e.length&&e[n]==="*";)n+=1;return n===e.length},t3=(e,t)=>{let n=e.indexOf("://"),r=n<0?-1:e.indexOf("/",n+3),o=(r<0?e:e.slice(0,r)).toLowerCase(),a=r<0?t?"/*":"":e.slice(r);return o+a},cIe=(e,t)=>Array.isArray(e)&&t!==void 0&&e.length===t.length&&e.every((n,r)=>n===t[r]),n3=(e,t)=>e.serverName===t.name||typeof e.serverUrl=="string"&&t.url!==void 0&&iIe(t3(e.serverUrl,!0),t3(t.url,!1))||cIe(e.serverCommand,t.command),lIe=(e,t)=>{let n=t.type==="http"?"serverUrl":"serverCommand",r=e.filter(o=>n in o);return r.length>0?r.some(o=>n3(o,t)):e.some(o=>o.serverName===t.name)},dIe=(e,t,n)=>{let r=e.settings,o=(l,d)=>e.originOf(l)??d,a=e.mcpFile.servers?.includes(n.name)===!0;if(e.mcpFile.present&&e.mcpFile.servers&&!a)return{source:"managed-mcp.json",reason:"managed-mcp.json takes exclusive control of MCP servers and does not list it"};if(BL(r.deniedMcpServers)?.some(l=>n3(l,n)))return{source:o("deniedMcpServers","managed settings"),reason:"deniedMcpServers names it"};if(a)return;let i=BL(r.allowedMcpServers),c=r.allowManagedMcpServersOnly===!0?void 0:BL(t.allowedMcpServers);if(!(i===void 0&&c===void 0)&&!lIe([...i??[],...c??[]],n))return{source:o("allowedMcpServers","managed settings"),reason:"allowedMcpServers does not admit it"}},uIe=e=>typeof e=="string"?e.trim()!=="":Array.isArray(e)&&e.length>0,fIe=["forceLoginMethod","forceLoginOrgUUID","forceLoginGatewayUrl"],r3=(e,t)=>{let n=[],r=t.servers.map(s=>dIe(e,t.userSettings,s)),o=r[0];if(t.servers.length>0&&o&&r.every(s=>s!==void 0)){let s=t.servers[0]?.name??"anyray";n.push({effect:"blocks_mcp",problem:`Managed policy blocks the Anyray retrieval MCP server \`${s}\` (${o.source}): ${o.reason}, so anyray_retrieve is unavailable until the policy changes`,fix:o.reason.startsWith("managed-mcp")?`Fix: ask your admin to add \`${s}\` to managed-mcp.json, then restart Claude Code.`:`Fix: ask your admin to ${o.reason.startsWith("denied")?"drop":"add"} a \`{ "serverName": "${s}" }\` entry ${o.reason.startsWith("denied")?"from deniedMcpServers":"to allowedMcpServers"}, then restart Claude Code.`})}let a=fIe.filter(s=>uIe(e.settings[s]));return t.keyLane&&a.length>0&&n.push({effect:"blocks_auth",problem:`Managed policy sets ${a.join(" and ")} (${e.originOf(a[0])??"managed settings"}): Claude Code blocks an ANTHROPIC_AUTH_TOKEN or apiKeyHelper credential at startup, so the gateway key is refused`,fix:"Fix: ask your admin to drop the login restriction for this seat, or to sign it in through the managed method. Connect never overrides machine policy."}),n}});import{z as a3}from"zod";var FL,jc,ig=U(()=>{"use strict";FL=a3.object({greenCollapse:a3.boolean().default(!1)}),jc=e=>{let t=FL.safeParse(e??{});return t.success?t.data:{greenCollapse:!1}}});var pIe,xd,cg,YC,s3,lg=U(()=>{"use strict";ue();ig();No();pIe={digest:!1,readTrim:!1,lifecycle:!1,logRead:!1,digestEconomics:!1,rangedArrival:!1},xd=e=>{let t=e.fleetHookPolicy,n=jc(e.hookPolicies);return{digest:t?.digest!=="off",readTrim:t?.readTrim==="on",lifecycle:t?.lifecycle==="on"||n.greenCollapse,logRead:t?.logRead==="on",digestEconomics:t?.digestEconomics==="on",rangedArrival:t?.rangedArrival==="on"}},cg=e=>{let t=xd(e);return!t.digest&&!t.readTrim&&!t.logRead?"off_by_policy":"enabled"},YC=e=>{switch(e.state){case"present":return xd(e.profile);case"absent":return xd({});case"unreadable":return pIe}},s3=async(e,t)=>{let n=t??(await it())?.level;return n==="gateway_hooks_mcp"||n===void 0?e:{...e,digest:!1,readTrim:!1,logRead:!1,digestEconomics:!1,rangedArrival:!1}}});import{mkdir as l3,readdir as mIe,readFile as hIe,rm as xp,stat as d3,open as yIe}from"node:fs/promises";import{createHash as gIe,randomUUID as wIe}from"node:crypto";import{homedir as JC}from"node:os";import{join as fg}from"node:path";import{z as Ip}from"zod";var UL,HL,bIe,XC,GL,dg,WL,i3,ug,kIe,AIe,u3,vIe,c3,zC,jL,f3,p3,m3,Rd,h3,y3,pg=U(()=>{"use strict";Ze();AE();No();UL=1440*60*1e3,HL=Ip.object({level:Ip.enum(["gateway","gateway_hooks","gateway_hooks_mcp"]),expiresAt:Ip.number().int().positive()}).strict(),bIe=Ip.object({level:Ip.enum(["gateway","gateway_hooks","gateway_hooks_mcp"]),source:Ip.enum(["agent","user","team","org","default"])}).strict(),XC=()=>fg(JC(),".anyray-claude-sessions"),GL=()=>fg(JC(),".anyray-integration-pending.json"),dg=()=>fg(JC(),".anyray-integration-lock"),WL=e=>typeof e=="string"&&/^[\w.:-]{1,256}$/.test(e),i3={gateway:0,gateway_hooks:1,gateway_hooks_mcp:2},ug=e=>fg(XC(),`${gIe("sha256").update(e).digest("hex")}.json`),kIe=10*6e4,AIe=6e4,u3=async()=>{try{let e=JSON.parse(await hIe(dg(),"utf8")),{pid:t,token:n}=e;return Number.isInteger(t)&&t>0&&typeof n=="string"?{pid:t,token:n}:void 0}catch{return}},vIe=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},c3=async e=>{(await u3())?.token===e&&await xp(dg(),{force:!0})},zC=async e=>{await l3(JC(),{recursive:!0});let t=wIe(),n;for(let r=0;r<1200;r++){let o;try{o=await yIe(dg(),"wx",384)}catch(s){let i=s.code;if(wm(i)){n=s,await new Promise(u=>setTimeout(u,50));continue}if(n=void 0,i!=="EEXIST")throw s;let c=await d3(dg()).then(u=>Date.now()-u.mtimeMs,()=>0),l=await u3();(l?!vIe(l.pid)||c>kIe:c>AIe)&&await c3(l?.token).catch(()=>{}),await new Promise(u=>setTimeout(u,50));continue}let a=!1;try{return await o.writeFile(JSON.stringify({pid:process.pid,token:t})),a=!0,await e()}finally{await o.close(),a?await c3(t):await xp(dg(),{force:!0})}}throw n||new Error("integration session lock unavailable")},jL=async(e=Date.now())=>{let t=await mIe(XC()).catch(r=>{if(r.code==="ENOENT")return[];throw r}),n=0;for(let r of t){if(!r.endsWith(".json"))continue;let o=fg(XC(),r);try{let a=HL.safeParse(await ae(o));if(a.success&&a.data.expiresAt<=e){await xp(o,{force:!0});continue}if(!a.success&&await d3(o).then(i=>e-i.mtimeMs)>UL){await xp(o,{force:!0});continue}n++}catch{n++}}return n},f3=async(e,t=Date.now())=>{WL(e)&&await zC(async()=>{await l3(XC(),{recursive:!0});let n=HL.safeParse(await ae(ug(e)).catch(()=>({}))),r=(await it())?.level,o=(await Rd())?.level,a=n.success?n.data.level:r&&o&&i3[o]<i3[r]?o:r;a&&await ye(ug(e),{level:a,expiresAt:t+UL},{backup:!1})})},p3=async(e,t=Date.now())=>{if(WL(e))try{let n=HL.safeParse(await ae(ug(e)));return!n.success||n.data.expiresAt<=t?void 0:(await ye(ug(e),{...n.data,expiresAt:t+UL},{backup:!1}).catch(()=>{}),n.data.level)}catch{return}},m3=async e=>{WL(e)&&await zC(async()=>xp(ug(e),{force:!0}))},Rd=async()=>{try{let e=bIe.safeParse(await ae(GL()));return e.success?e.data:void 0}catch{return}},h3=async e=>ye(GL(),e,{backup:!1}),y3=async()=>xp(GL(),{force:!0})});import{X509Certificate as VL}from"node:crypto";import{request as CIe}from"node:http";import{isIP as A3}from"node:net";import{connect as SIe,getCACertificates as _Ie,rootCertificates as EIe}from"node:tls";import{z as Ci}from"zod";var v3,qC,IIe,g3,w3,b3,KL,xIe,RIe,OIe,TIe,PIe,LIe,k3,NIe,ZL,DIe,Od,Rp=U(()=>{"use strict";kl();v3=Ci.discriminatedUnion("state",[Ci.object({state:Ci.enum(["public","not_tls","unreachable","not_checked"])}).strict(),Ci.object({state:Ci.literal("os_store"),rootSubject:Ci.string()}).strict(),Ci.object({state:Ci.enum(["untrusted","invalid_cert"]),code:Ci.string().min(1)}).strict()]),qC=e=>{if(!e)return{state:"not_checked"};switch(e.state){case"os_store":return{state:"os_store",rootSubject:e.rootSubject};case"untrusted":case"invalid_cert":return{state:e.state,code:e.code};default:return{state:e.state}}},IIe=3e3,g3=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID"]),w3=e=>Zm({code:e}).kind==="tls-unknown-issuer",b3=(e,t)=>{try{return e?e():_Ie(t)}catch{return t==="bundled"?EIe:[]}},KL=e=>e.replace(/[A-Z]+/g,t=>t.toLowerCase()),xIe=(e,t)=>{let n=(t.no_proxy??"").trim()||(t.NO_PROXY??"").trim();if(!n)return!1;let r=KL(e),o=A3(r)!==0;for(let a of n.split(/[\s,]+/)){if(a==="*")return!0;let s=KL(a).replace(/^\./,"");if(s&&(r===s||!o&&r.endsWith(`.${s}`)))return!0}return!1},RIe=e=>{if(!e.username&&!e.password)return;let t=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;return`Basic ${Buffer.from(t,"utf8").toString("base64")}`},OIe=(e,t)=>{let n=(t.https_proxy??"").trim()||(t.HTTPS_PROXY??"").trim();if(!(!n||xIe(e,t)))try{let r=new URL(n);if(r.protocol!=="http:")return"unusable";let o=RIe(r);return{host:r.hostname.replace(/^\[|\]$/g,""),port:Number(r.port)||80,...o?{credential:o}:{}}}catch{return"unusable"}},TIe=(e,t)=>new Promise(n=>{let r=!1,o=`${KL(e.host)}:${e.port}`,a=CIe({host:e.proxy.host,port:e.proxy.port,method:"CONNECT",path:o,agent:!1,headers:{host:o,...e.proxy.credential?{"proxy-authorization":e.proxy.credential}:{}}}),s=c=>{r||(r=!0,clearTimeout(i),c||a.destroy(),n(c))},i=setTimeout(()=>s(void 0),Math.max(0,t-Date.now()));a.once("connect",(c,l,d)=>{if(!((c.statusCode??0)>=200&&(c.statusCode??0)<300)||d.length>0){l.destroy(),s(void 0);return}s(l)}),a.once("response",()=>s(void 0)),a.once("error",()=>s(void 0)),a.once("close",()=>s(void 0)),a.end()}),PIe=e=>{let t=[],n=new Set;for(let r=e;r?.raw&&!n.has(r.fingerprint256);r=r.issuerCertificate)n.add(r.fingerprint256),t.push(new VL(r.raw));return t},LIe=e=>{if(typeof e=="string"&&e)return e;let t=e?.code;return typeof t=="string"&&t?t:"CERT_UNTRUSTED"},k3=async(e,t,n)=>{let r;return e.proxy&&(r=await TIe({...e,proxy:e.proxy},n),!r)?{outcome:"no_answer"}:new Promise(o=>{let a=!1,s,i=SIe({host:e.host,...r?{socket:r}:{port:e.port},ca:[...t],rejectUnauthorized:!0,...A3(e.host)?{}:{servername:e.host}}),c=l=>{a||(a=!0,s&&clearTimeout(s),i.destroy(),r?.destroy(),o(l))};s=setTimeout(()=>c({outcome:"no_answer"}),Math.max(0,n-Date.now())),i.once("secureConnect",()=>c(i.authorized?{outcome:"verified",chain:PIe(i.getPeerCertificate(!0))}:{outcome:"rejected",code:LIe(i.authorizationError)})),i.on("error",l=>c(typeof l.code=="string"&&l.code?{outcome:"rejected",code:l.code}:{outcome:"no_answer"})),i.once("close",()=>c({outcome:"no_answer"}))})},NIe=e=>e.subject.split(`
753
+ `)){let r=n.indexOf(":");r>0&&t.set(n.slice(0,r).trim().toLowerCase(),n.slice(r+1).trim())}return t},Zz=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}},nIe=(e,t)=>{let n=Zz(e),r=Zz(t);return!n||!r?e!==t:Object.entries(n).some(([o,a])=>o in r&&JSON.stringify(r[o])!==JSON.stringify(a))},rIe=(e,t)=>{let n=Vz(e);for(let[r,o]of Vz(t)){let a=n.get(r);if(r===tIe){if(a!==void 0&&nIe(a,o))return!0}else if(a!==o)return!0}return!1},oIe=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Yz=async()=>(await Ea({})).settings,aIe=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=>Cd(r,On))},Xz=async(e={})=>{let t=await Ea(e),n=t.settings;return n.disableAllHooks===!0?{state:"disabled",source:t.originOf("disableAllHooks")}:n.allowManagedHooksOnly===!0&&!aIe(n)?{state:"restricted_dropping_ours",source:t.originOf("allowManagedHooksOnly")}:{state:"fine"}},VC=e=>{let t=e.source??`managed settings (${en()})`;return e.state==="disabled"?`disableAllHooks is true in ${t} \u2014 Claude Code skips every hook and the status line, including Anyray's savings hook`:e.state==="restricted_dropping_ours"?`allowManagedHooksOnly is true in ${t}, but the managed hooks do 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"},ZC=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.",Jz=async(e={})=>{let t=Kz(e.userSettings??{}),n=await Ea(e),r=Kz(n.settings),o=[];for(let a of QEe){if(!jz(r[a])||!jz(t[a]))continue;let s=a==="ANTHROPIC_BASE_URL";if(a==="ANTHROPIC_CUSTOM_HEADERS"){if(!rIe(String(r[a]),String(t[a])))continue}else if(eIe(r[a],t[a],s))continue;if(a==="ENABLE_TOOL_SEARCH"&&r[a]===wu&&Io(t[a]))continue;let i=s?oIe(r[a]):void 0;o.push({name:a,source:n.originOf(`env.${a}`)??`managed settings (${en()})`,routing:s,...i?{managedOrigin:i}:{}})}return o},zz=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`,qz=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."});var Hn,Qz,ML,$L,e3=U(()=>{"use strict";Hn="ANTHROPIC_API_KEY",Qz=e=>typeof e=="string"&&e.trim()!=="",ML=e=>{let t=e.userSettings?.env,n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};if(Qz(n[Hn]))return{source:"~/.claude/settings.json env block"};if(!(typeof n[Hn]=="string")&&Qz((e.env??process.env)[Hn]))return{source:"shell environment"}},$L=e=>`${Hn} is set (${e.source}) and Claude Code ranks it above the apiKeyHelper, so that key would be sent instead of the gateway key`});var sIe,BL,iIe,t3,cIe,n3,lIe,dIe,uIe,fIe,r3,o3=U(()=>{"use strict";sIe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),BL=e=>Array.isArray(e)?e.filter(sIe):void 0,iIe=(e,t)=>{let n=0,r=0,o=-1,a=0;for(;r<t.length;)if(n<e.length&&e[n]==="*")o=n,n+=1,a=r;else if(n<e.length&&e[n]===t[r])n+=1,r+=1;else if(o>=0)n=o+1,a+=1,r=a;else return!1;for(;n<e.length&&e[n]==="*";)n+=1;return n===e.length},t3=(e,t)=>{let n=e.indexOf("://"),r=n<0?-1:e.indexOf("/",n+3),o=(r<0?e:e.slice(0,r)).toLowerCase(),a=r<0?t?"/*":"":e.slice(r);return o+a},cIe=(e,t)=>Array.isArray(e)&&t!==void 0&&e.length===t.length&&e.every((n,r)=>n===t[r]),n3=(e,t)=>e.serverName===t.name||typeof e.serverUrl=="string"&&t.url!==void 0&&iIe(t3(e.serverUrl,!0),t3(t.url,!1))||cIe(e.serverCommand,t.command),lIe=(e,t)=>{let n=t.type==="http"?"serverUrl":"serverCommand",r=e.filter(o=>n in o);return r.length>0?r.some(o=>n3(o,t)):e.some(o=>o.serverName===t.name)},dIe=(e,t,n)=>{let r=e.settings,o=(l,d)=>e.originOf(l)??d,a=e.mcpFile.servers?.includes(n.name)===!0;if(e.mcpFile.present&&e.mcpFile.servers&&!a)return{source:"managed-mcp.json",reason:"managed-mcp.json takes exclusive control of MCP servers and does not list it"};if(BL(r.deniedMcpServers)?.some(l=>n3(l,n)))return{source:o("deniedMcpServers","managed settings"),reason:"deniedMcpServers names it"};if(a)return;let i=BL(r.allowedMcpServers),c=r.allowManagedMcpServersOnly===!0?void 0:BL(t.allowedMcpServers);if(!(i===void 0&&c===void 0)&&!lIe([...i??[],...c??[]],n))return{source:o("allowedMcpServers","managed settings"),reason:"allowedMcpServers does not admit it"}},uIe=e=>typeof e=="string"?e.trim()!=="":Array.isArray(e)&&e.length>0,fIe=["forceLoginMethod","forceLoginOrgUUID","forceLoginGatewayUrl"],r3=(e,t)=>{let n=[],r=t.servers.map(s=>dIe(e,t.userSettings,s)),o=r[0];if(t.servers.length>0&&o&&r.every(s=>s!==void 0)){let s=t.servers[0]?.name??"anyray";n.push({effect:"blocks_mcp",problem:`Managed policy blocks the Anyray retrieval MCP server \`${s}\` (${o.source}): ${o.reason}, so anyray_retrieve is unavailable until the policy changes`,fix:o.reason.startsWith("managed-mcp")?`Fix: ask your admin to add \`${s}\` to managed-mcp.json, then restart Claude Code.`:`Fix: ask your admin to ${o.reason.startsWith("denied")?"drop":"add"} a \`{ "serverName": "${s}" }\` entry ${o.reason.startsWith("denied")?"from deniedMcpServers":"to allowedMcpServers"}, then restart Claude Code.`})}let a=fIe.filter(s=>uIe(e.settings[s]));return t.keyLane&&a.length>0&&n.push({effect:"blocks_auth",problem:`Managed policy sets ${a.join(" and ")} (${e.originOf(a[0])??"managed settings"}): Claude Code blocks an ANTHROPIC_AUTH_TOKEN or apiKeyHelper credential at startup, so the gateway key is refused`,fix:"Fix: ask your admin to drop the login restriction for this seat, or to sign it in through the managed method. Connect never overrides machine policy."}),n}});import{z as a3}from"zod";var FL,jc,ig=U(()=>{"use strict";FL=a3.object({greenCollapse:a3.boolean().default(!1)}),jc=e=>{let t=FL.safeParse(e??{});return t.success?t.data:{greenCollapse:!1}}});var pIe,xd,cg,YC,s3,lg=U(()=>{"use strict";ue();ig();No();pIe={digest:!1,readTrim:!1,lifecycle:!1,logRead:!1,digestEconomics:!1,rangedArrival:!1},xd=e=>{let t=e.fleetHookPolicy,n=jc(e.hookPolicies);return{digest:t?.digest!=="off",readTrim:t?.readTrim==="on",lifecycle:t?.lifecycle==="on"||n.greenCollapse,logRead:t?.logRead!=="off",digestEconomics:t?.digestEconomics==="on",rangedArrival:t?.rangedArrival==="on"}},cg=e=>{let t=xd(e);return!t.digest&&!t.readTrim&&!t.logRead?"off_by_policy":"enabled"},YC=e=>{switch(e.state){case"present":return xd(e.profile);case"absent":return xd({});case"unreadable":return pIe}},s3=async(e,t)=>{let n=t??(await it())?.level;return n==="gateway_hooks_mcp"||n===void 0?e:{...e,digest:!1,readTrim:!1,logRead:!1,digestEconomics:!1,rangedArrival:!1}}});import{mkdir as l3,readdir as mIe,readFile as hIe,rm as xp,stat as d3,open as yIe}from"node:fs/promises";import{createHash as gIe,randomUUID as wIe}from"node:crypto";import{homedir as JC}from"node:os";import{join as fg}from"node:path";import{z as Ip}from"zod";var UL,HL,bIe,XC,GL,dg,WL,i3,ug,kIe,AIe,u3,vIe,c3,zC,jL,f3,p3,m3,Rd,h3,y3,pg=U(()=>{"use strict";Ze();AE();No();UL=1440*60*1e3,HL=Ip.object({level:Ip.enum(["gateway","gateway_hooks","gateway_hooks_mcp"]),expiresAt:Ip.number().int().positive()}).strict(),bIe=Ip.object({level:Ip.enum(["gateway","gateway_hooks","gateway_hooks_mcp"]),source:Ip.enum(["agent","user","team","org","default"])}).strict(),XC=()=>fg(JC(),".anyray-claude-sessions"),GL=()=>fg(JC(),".anyray-integration-pending.json"),dg=()=>fg(JC(),".anyray-integration-lock"),WL=e=>typeof e=="string"&&/^[\w.:-]{1,256}$/.test(e),i3={gateway:0,gateway_hooks:1,gateway_hooks_mcp:2},ug=e=>fg(XC(),`${gIe("sha256").update(e).digest("hex")}.json`),kIe=10*6e4,AIe=6e4,u3=async()=>{try{let e=JSON.parse(await hIe(dg(),"utf8")),{pid:t,token:n}=e;return Number.isInteger(t)&&t>0&&typeof n=="string"?{pid:t,token:n}:void 0}catch{return}},vIe=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},c3=async e=>{(await u3())?.token===e&&await xp(dg(),{force:!0})},zC=async e=>{await l3(JC(),{recursive:!0});let t=wIe(),n;for(let r=0;r<1200;r++){let o;try{o=await yIe(dg(),"wx",384)}catch(s){let i=s.code;if(wm(i)){n=s,await new Promise(u=>setTimeout(u,50));continue}if(n=void 0,i!=="EEXIST")throw s;let c=await d3(dg()).then(u=>Date.now()-u.mtimeMs,()=>0),l=await u3();(l?!vIe(l.pid)||c>kIe:c>AIe)&&await c3(l?.token).catch(()=>{}),await new Promise(u=>setTimeout(u,50));continue}let a=!1;try{return await o.writeFile(JSON.stringify({pid:process.pid,token:t})),a=!0,await e()}finally{await o.close(),a?await c3(t):await xp(dg(),{force:!0})}}throw n||new Error("integration session lock unavailable")},jL=async(e=Date.now())=>{let t=await mIe(XC()).catch(r=>{if(r.code==="ENOENT")return[];throw r}),n=0;for(let r of t){if(!r.endsWith(".json"))continue;let o=fg(XC(),r);try{let a=HL.safeParse(await ae(o));if(a.success&&a.data.expiresAt<=e){await xp(o,{force:!0});continue}if(!a.success&&await d3(o).then(i=>e-i.mtimeMs)>UL){await xp(o,{force:!0});continue}n++}catch{n++}}return n},f3=async(e,t=Date.now())=>{WL(e)&&await zC(async()=>{await l3(XC(),{recursive:!0});let n=HL.safeParse(await ae(ug(e)).catch(()=>({}))),r=(await it())?.level,o=(await Rd())?.level,a=n.success?n.data.level:r&&o&&i3[o]<i3[r]?o:r;a&&await ye(ug(e),{level:a,expiresAt:t+UL},{backup:!1})})},p3=async(e,t=Date.now())=>{if(WL(e))try{let n=HL.safeParse(await ae(ug(e)));return!n.success||n.data.expiresAt<=t?void 0:(await ye(ug(e),{...n.data,expiresAt:t+UL},{backup:!1}).catch(()=>{}),n.data.level)}catch{return}},m3=async e=>{WL(e)&&await zC(async()=>xp(ug(e),{force:!0}))},Rd=async()=>{try{let e=bIe.safeParse(await ae(GL()));return e.success?e.data:void 0}catch{return}},h3=async e=>ye(GL(),e,{backup:!1}),y3=async()=>xp(GL(),{force:!0})});import{X509Certificate as VL}from"node:crypto";import{request as CIe}from"node:http";import{isIP as A3}from"node:net";import{connect as SIe,getCACertificates as _Ie,rootCertificates as EIe}from"node:tls";import{z as Ci}from"zod";var v3,qC,IIe,g3,w3,b3,KL,xIe,RIe,OIe,TIe,PIe,LIe,k3,NIe,ZL,DIe,Od,Rp=U(()=>{"use strict";kl();v3=Ci.discriminatedUnion("state",[Ci.object({state:Ci.enum(["public","not_tls","unreachable","not_checked"])}).strict(),Ci.object({state:Ci.literal("os_store"),rootSubject:Ci.string()}).strict(),Ci.object({state:Ci.enum(["untrusted","invalid_cert"]),code:Ci.string().min(1)}).strict()]),qC=e=>{if(!e)return{state:"not_checked"};switch(e.state){case"os_store":return{state:"os_store",rootSubject:e.rootSubject};case"untrusted":case"invalid_cert":return{state:e.state,code:e.code};default:return{state:e.state}}},IIe=3e3,g3=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID"]),w3=e=>Zm({code:e}).kind==="tls-unknown-issuer",b3=(e,t)=>{try{return e?e():_Ie(t)}catch{return t==="bundled"?EIe:[]}},KL=e=>e.replace(/[A-Z]+/g,t=>t.toLowerCase()),xIe=(e,t)=>{let n=(t.no_proxy??"").trim()||(t.NO_PROXY??"").trim();if(!n)return!1;let r=KL(e),o=A3(r)!==0;for(let a of n.split(/[\s,]+/)){if(a==="*")return!0;let s=KL(a).replace(/^\./,"");if(s&&(r===s||!o&&r.endsWith(`.${s}`)))return!0}return!1},RIe=e=>{if(!e.username&&!e.password)return;let t=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;return`Basic ${Buffer.from(t,"utf8").toString("base64")}`},OIe=(e,t)=>{let n=(t.https_proxy??"").trim()||(t.HTTPS_PROXY??"").trim();if(!(!n||xIe(e,t)))try{let r=new URL(n);if(r.protocol!=="http:")return"unusable";let o=RIe(r);return{host:r.hostname.replace(/^\[|\]$/g,""),port:Number(r.port)||80,...o?{credential:o}:{}}}catch{return"unusable"}},TIe=(e,t)=>new Promise(n=>{let r=!1,o=`${KL(e.host)}:${e.port}`,a=CIe({host:e.proxy.host,port:e.proxy.port,method:"CONNECT",path:o,agent:!1,headers:{host:o,...e.proxy.credential?{"proxy-authorization":e.proxy.credential}:{}}}),s=c=>{r||(r=!0,clearTimeout(i),c||a.destroy(),n(c))},i=setTimeout(()=>s(void 0),Math.max(0,t-Date.now()));a.once("connect",(c,l,d)=>{if(!((c.statusCode??0)>=200&&(c.statusCode??0)<300)||d.length>0){l.destroy(),s(void 0);return}s(l)}),a.once("response",()=>s(void 0)),a.once("error",()=>s(void 0)),a.once("close",()=>s(void 0)),a.end()}),PIe=e=>{let t=[],n=new Set;for(let r=e;r?.raw&&!n.has(r.fingerprint256);r=r.issuerCertificate)n.add(r.fingerprint256),t.push(new VL(r.raw));return t},LIe=e=>{if(typeof e=="string"&&e)return e;let t=e?.code;return typeof t=="string"&&t?t:"CERT_UNTRUSTED"},k3=async(e,t,n)=>{let r;return e.proxy&&(r=await TIe({...e,proxy:e.proxy},n),!r)?{outcome:"no_answer"}:new Promise(o=>{let a=!1,s,i=SIe({host:e.host,...r?{socket:r}:{port:e.port},ca:[...t],rejectUnauthorized:!0,...A3(e.host)?{}:{servername:e.host}}),c=l=>{a||(a=!0,s&&clearTimeout(s),i.destroy(),r?.destroy(),o(l))};s=setTimeout(()=>c({outcome:"no_answer"}),Math.max(0,n-Date.now())),i.once("secureConnect",()=>c(i.authorized?{outcome:"verified",chain:PIe(i.getPeerCertificate(!0))}:{outcome:"rejected",code:LIe(i.authorizationError)})),i.on("error",l=>c(typeof l.code=="string"&&l.code?{outcome:"rejected",code:l.code}:{outcome:"no_answer"})),i.once("close",()=>c({outcome:"no_answer"}))})},NIe=e=>e.subject.split(`
754
754
  `).find(t=>t.startsWith("CN="))?.slice(3)??e.subject,ZL=e=>{let t=new Set,n=[];for(let r of e){let o;try{o=new VL(r)}catch{continue}t.has(o.fingerprint256)||(t.add(o.fingerprint256),n.push(o.toString()))}return n},DIe=(e,t)=>{let n=e[e.length-1];if(!n)return{pems:[],root:void 0};let r=[],o;for(let a of t){let s;try{s=new VL(a)}catch{continue}(s.fingerprint256===n.fingerprint256||n.checkIssued(s)&&n.verify(s.publicKey))&&(r.push(a),o??=s)}return{pems:ZL(r),root:o}},Od=async(e,t={})=>{let n;try{n=new URL(e)}catch{return{state:"unreachable"}}if(n.protocol==="http:")return{state:"not_tls"};if(n.protocol!=="https:")return{state:"unreachable"};let r=n.hostname.replace(/^\[|\]$/g,""),o=Number(n.port)||443,a=OIe(r,process.env);if(a==="unusable")return{state:"unreachable"};let s={host:r,port:o,...a?{proxy:a}:{}},i=Date.now()+(t.timeoutMs??IIe),c=b3(t.bundledRoots,"bundled"),l=b3(t.systemRoots,"system");try{let d=await k3(s,c,i);if(d.outcome==="verified")return{state:"public"};if(d.outcome==="no_answer")return{state:"unreachable"};if(g3.has(d.code))return{state:"invalid_cert",code:d.code};if(!w3(d.code))return{state:"unreachable"};let u=await k3(s,[...c,...l],i);if(u.outcome==="no_answer")return{state:"unreachable"};if(u.outcome==="rejected")return g3.has(u.code)?{state:"invalid_cert",code:u.code}:w3(u.code)?{state:"untrusted",code:u.code}:{state:"unreachable"};let{pems:f,root:p}=DIe(u.chain,l);return p?{state:"os_store",rootSubject:NIe(p),rootPems:f}:{state:"untrusted",code:d.code}}catch{return{state:"unreachable"}}}});import{execFile as MIe}from"node:child_process";import{access as $Ie,constants as BIe,open as FIe}from"node:fs/promises";import{delimiter as UIe,dirname as HIe,isAbsolute as S3,join as GIe}from"node:path";import{promisify as WIe}from"node:util";var jIe,C3,KIe,VIe,ZIe,YIe,XIe,JIe,zIe,qIe,QIe,exe,mg,QC,eS=U(()=>{"use strict";to();jIe=WIe(MIe),C3=512,KIe=[Buffer.from([127,69,76,70]),Buffer.from([207,250,237,254]),Buffer.from([206,250,237,254]),Buffer.from([202,254,186,190]),Buffer.from([77,90])],VIe=async e=>{try{let t=await FIe(e,"r");try{let n=Buffer.alloc(C3),{bytesRead:r}=await t.read(n,0,C3,0);return n.subarray(0,r)}finally{await t.close()}}catch{return}},ZIe=e=>KIe.some(t=>e.length>=t.length&&e.subarray(0,t.length).equals(t)),YIe=/(^|[\\/])node(\.exe)?$/i,XIe=e=>{let t=e.toString("utf8").split(`
755
755
  `)[0]??"";if(!t.startsWith("#!"))return{kind:"unnamed"};let n=t.slice(2).trim().split(/\s+/).find(r=>YIe.test(r));return n===void 0||!/[\\/]/.test(n)?{kind:"unnamed"}:S3(n)?{kind:"absolute",path:n}:{kind:"relative"}},JIe=process.platform==="win32"?["node.exe"]:["node"],zIe=async e=>{try{return await $Ie(e,BIe.X_OK),!0}catch{return!1}},qIe=async(e,t)=>{let n=[HIe(e),...(t.PATH??t.Path??"").split(UIe)].filter(r=>r!==""&&S3(r));for(let r of n)for(let o of JIe){let a=GIe(r,o);if(await zIe(a))return a}},QIe=async e=>{try{let{stdout:t}=await jIe(e,["--version"],{timeout:5e3,windowsHide:!0});return/^v?(\d+\.\d+\.\d+)/.exec(t.trim())?.[1]}catch{return}},exe=async(e,t)=>{let n=XIe(t);if(n.kind==="relative")return;let r=n.kind==="absolute"?n.path:await qIe(e,process.env);return r===void 0?void 0:QIe(r)},mg=async(e={})=>{let t=await(e.resolveBinary??Vu)();if(t===void 0)return{kind:"not_found"};let n=await VIe(t);return n===void 0?{kind:"not_found"}:ZIe(n)?{kind:"native"}:{kind:"node",nodeVersion:await(e.nodeVersion??(o=>exe(o,n)))(t)??null}},QC=e=>{if(e.kind==="native")return"not_needed";if(e.kind==="not_found")return"unknown";let t=/^v?(\d+)\.(\d+)\.\d+/.exec(e.nodeVersion??"");if(!t)return"unknown";let n=Number(t[1]),r=Number(t[2]);return n<22||n===22&&r<15||n===23&&r<10?"needed":"not_needed"}});import{randomUUID as txe}from"node:crypto";import{access as nxe,mkdir as rxe,open as oxe,rm as YL,writeFile as axe}from"node:fs/promises";import{dirname as sxe,join as _3}from"node:path";var Mn,Gr,Op,XL,tS,JL,E3,I3,zL,x3,R3,qL,QL=U(()=>{"use strict";_n();Rp();ue();eS();Mn="NODE_EXTRA_CA_CERTS",Gr=()=>_3(te(),"ca","gateway-roots.pem"),Op=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t[Mn]:void 0},XL=(e,t)=>{if(typeof t=="string")return"managed";if(typeof e=="string"&&e!==Gr())return"user"},tS=(e=process.env)=>{let t=(e[Mn]??"").trim();return t!==""&&t!==Gr()?t:void 0},JL=()=>_3(te(),"claude-code-ca-shell-export.json"),E3=async()=>{try{return await nxe(JL()),!0}catch{return!1}},I3=async()=>{await Ne(),await axe(JL(),`${JSON.stringify({recordedAt:new Date().toISOString()})}
756
756
  `,{mode:384})},zL=async()=>{await YL(JL(),{force:!0})},x3=async e=>{if(e.uid===0)return{action:"leave",reason:"root"};let t=XL(e.userValue,e.managedValue);if(t)return{action:"keep_theirs",owner:t};if(e.shellValue!==void 0)return{action:"yield_to_shell"};if(!e.interactive&&e.shellExportRecorded)return{action:"leave",reason:"shell_export_recorded"};let n=await e.probe();if(n.state==="unreachable"||n.state==="invalid_cert")return{action:"leave",reason:"no_verdict"};if(n.state!=="os_store")return{action:"remove"};let r=await e.runtime(),o=QC(r);return o==="unknown"?{action:"leave",reason:"unknown_runtime"}:o==="not_needed"||n.rootPems.length===0?{action:"remove"}:{action:"write",rootPems:n.rootPems,rootSubject:n.rootSubject,nodeVersion:r.kind==="node"?r.nodeVersion:null}},R3=async e=>{let t=Gr();await Ne(),await rxe(sxe(t),{recursive:!0});let n=`${t}.${process.pid}-${txe()}.tmp`;try{let r=await oxe(n,"wx",420);try{await r.writeFile(ZL(e).map(o=>`${o.trim()}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anyray-connect",
3
- "version": "0.11.412",
3
+ "version": "0.11.413",
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": {