anyray-connect 0.11.147 → 0.11.148

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 +227 -227
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- var kR="http://localhost:8787",Qa="anyray-placeholder",xe=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Ze=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},Cu=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,CR=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),ig=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!CR.has(n)}catch{return!1}},dn=e=>{let t=Ze(e||process.env.ANYRAY_GATEWAY_URL||kR),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},ft="127.0.0.1",In=(e,t)=>{let n=`http://${ft}:${t}`;return{...e,anthropicBaseUrl:n,openaiBaseUrl:`${n}/v1`,viaLocalProxy:!0}},ge=(e={})=>{let t=dn(e.origin),n=e.placeholderKey?.trim()||Qa,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:Cu(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:Cu(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:Cu(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,authMode:a,byoUpstream:e.byoUpstream,seat:a==="auto"?e.seat:void 0,metadata:o}};import{homedir as fs,platform as Ho}from"node:os";import{join as Ko}from"node:path";import{mkdir as zu,readFile as uw,rename as UO,stat as pw,truncate as BO,writeFile as fw,rm as Wo}from"node:fs/promises";import{spawnSync as hn}from"node:child_process";import{createServer as WO}from"node:net";import{homedir as Ic}from"node:os";import{join as xc}from"node:path";import{access as IR,chmod as xR,mkdir as Au,open as xu,readFile as hg,rm as Xt,stat as lg,utimes as RR}from"node:fs/promises";import{createHash as OR,randomUUID as mg}from"node:crypto";import{dirname as Ru,join as _R}from"node:path";import{isDeepStrictEqual as Lo}from"node:util";import{randomUUID as AR}from"node:crypto";import{lstat as vR,rename as sc,rm as SR}from"node:fs/promises";import{platform as cg}from"node:os";var ER=e=>e?.code==="ENOENT",es=async(e,t=cg())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},he=async(e,t,n=cg())=>{if(n!=="win32"){await sc(e,t);return}let r=`${t}.anyray-old-${process.pid}-${AR()}`,o=!1;try{let a=await vR(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await sc(t,r),o=!0}catch(a){if(!ER(a))throw a}try{await sc(e,t)}catch(a){if(o)try{await sc(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await SR(r,{force:!0})};var ts=e=>`${e}.anyray-bak`,yg=async e=>{let t;try{t=await xu(Ru(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},dg=async(e,t)=>{let n,r;try{n=await xu(e,"wx",384),await n.writeFile(t,"utf-8"),await es(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Xt(e,{force:!0}).catch(()=>{}),r;await yg(e)},TR=async e=>{let t;try{t=await xu(e,"r"),await es(t)}finally{await t?.close().catch(()=>{})}await yg(e)},R=async e=>{try{return await IR(e),!0}catch{return!1}},U=async e=>{if(!await R(e))return{};let t=await hg(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},J=async(e,t,n={})=>{await Au(Ru(e),{recursive:!0,mode:448});let r=ts(e);if(n.backup!==!1&&await R(e)&&!await R(r))try{await dg(r,await hg(e,"utf-8"))}catch(a){if(a.code!=="EEXIST")throw a}let o=`${e}.anyray-tmp-${process.pid}-${mg()}`;try{await dg(o,`${JSON.stringify(t,null,2)}
3
- `),await he(o,e),await xR(e,384),await TR(e)}finally{await Xt(o,{force:!0}).catch(()=>{})}},gg=1,ug=3e4,PR=5e3,LR=/^[a-f0-9]{64}$/,wg=e=>`${e}.pending`,DR=e=>`${e}.lock`,vu=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=>vu(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${vu(t[n])}`).join(",")}}`},Su=(e,t)=>({exists:e,sha256:OR("sha256").update(vu(t)).digest("hex")}),Eu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),pg=e=>Eu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&LR.test(e.sha256),NR=e=>Eu(e)&&e.transactionVersion===gg&&pg(e.before)&&pg(e.after)&&Eu(e.journal),Iu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,Do=async(e,t)=>{try{return await U(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},$R=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},bg=async e=>{let t=DR(e),n=_R(t,"owner.json");await Au(Ru(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=mg();try{await Au(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await Do(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 lg(n)).mtimeMs;i=!$R(c.pid)||l>ug}catch{try{i=Date.now()-(await lg(t)).mtimeMs>ug}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Xt(t,{recursive:!0,force:!0});continue}try{await J(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Xt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await Do(n,"ownership journal")).nonce!==o)return;let i=new Date;await RR(n,i,i)}catch{}})()},PR);return a.unref(),async()=>{clearInterval(a);try{(await Do(n,"ownership journal")).nonce===o&&await Xt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},kg=async e=>{let t=await R(e),n={};if(t)try{n=await U(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:Su(t,n)}},Cg=async(e,t)=>{let n=wg(t);if(!await R(n))return;let r=await Do(n,"prepared ownership transaction");if(!NR(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await kg(e),a=await R(t),s=await R(ts(e)),i=Iu(o.fingerprint,r.before),c=Iu(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await J(t,r.journal,{backup:!1}),await Xt(n,{force:!0});return}if(i){await Xt(n,{force:!0}),a||await ae(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},ic=async(e,t,n)=>{let r=await bg(t);try{return await Cg(e,t),await n()}finally{await r()}},fg=async(e,t,n,r)=>{if(!await R(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await Do(e,"ownership journal");if(!(n&&Lo(a,t))){if(!Lo(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await J(e,t,{backup:!1}):await Xt(e,{force:!0})}},cc=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await bg(a);try{await Cg(n,a);let l=await kg(n),d=Su(i,r),u=await R(a),f=u?await Do(a,"ownership journal"):void 0,p=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!Iu(l.fingerprint,d)){if(Lo(l.value,o)&&f&&Lo(f,p))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&Lo(l.value,o)&&f&&Lo(f,p))return;let h=await R(ts(n));if(f?.fileExisted===!0&&!h)throw new Error("ownership backup is missing; configuration was left unchanged");if(h&&!f)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let m=wg(a),w={transactionVersion:gg,before:l.fingerprint,after:Su(!0,o),journal:p};await J(m,w,{backup:!1});try{await J(n,o,f?{backup:!1}:{}),await(t.writeJournal??J)(a,p,{backup:!1}),await Xt(m,{force:!0})}catch(g){try{await fg(n,l.value,l.exists,o)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed and config rollback was incomplete")}try{await fg(a,f??{},u,p),await Xt(m,{force:!0}),!h&&!f&&await ae(n)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed after config rollback")}throw g}}finally{await c()}},Fr=async e=>{try{return await U(ts(e))}catch{return{}}},ae=async e=>{await Xt(ts(e),{force:!0}).catch(()=>{})};import{access as cO}from"node:fs/promises";import{spawnSync as YR}from"node:child_process";import{readFileSync as ZR,realpathSync as os,statSync as Tg}from"node:fs";import{access as JR,cp as Pg,mkdir as Og,readdir as XR,readFile as Mu,realpath as zR,rename as qR,rm as Nu,writeFile as QR}from"node:fs/promises";import{tmpdir as eO}from"node:os";import{basename as $o,dirname as Ge,join as Re,resolve as tO}from"node:path";import{writeFile as lc,readFile as ns,chmod as _u,stat as Tu,mkdir as vg,rm as Ur,access as MR}from"node:fs/promises";import{randomUUID as FR}from"node:crypto";import{homedir as Sg}from"node:os";import{join as xn}from"node:path";var Q=()=>xn(Sg(),".anyray"),No=async()=>{let e=Q();try{if((await Tu(e)).isDirectory())return xn(e,"connect.json")}catch{}return e},Pu=()=>xn(Q(),"dev-key.pem"),kt=async()=>{let e=Q(),t;try{if(!(await Tu(e)).isDirectory())t=await ns(e,"utf-8").catch(()=>{}),await Ur(e,{force:!0});else return}catch{}if(await vg(e,{recursive:!0,mode:448}),t!==void 0){let n=xn(e,"connect.json");await lc(n,t,{mode:384}),await _u(n,384)}},dc=async e=>{await kt();let t=Pu();await lc(t,e,{mode:384}),await _u(t,384)},We=async()=>{try{let e=await ns(Pu(),"utf-8");return e.trim()?e:void 0}catch{return}},rs=async()=>{await Ur(Pu(),{force:!0}).catch(()=>{})},UR=e=>{let{fallbackEnabled:t,fallbackGatewayTimeoutMs:n,fallbackBreaker:r,...o}=e,a=o;return t===!0&&(a.keyRefreshEnabled=!0),a},L=async()=>{try{let e=await ns(await No(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:UR(t)}catch{return{}}},BR=0,WR=3e4,HR=5e3,KR=25,GR=()=>xn(Sg(),".anyray-connect-profile.lock"),jR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},VR=async e=>{try{let t=JSON.parse(await ns(xn(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!jR(t.pid)}catch{}return Date.now()-(await Tu(e)).mtimeMs>WR},Eg=async()=>{let e=GR(),t=xn(e,"owner.json"),n=Date.now()+HR;for(;;){let r=FR();try{await vg(e,{mode:448});try{await lc(t,`${JSON.stringify({pid:process.pid,nonce:r})}
4
- `,{mode:384})}catch(a){throw await Ur(e,{recursive:!0,force:!0}).catch(()=>{}),a}return async()=>{try{JSON.parse(await ns(t,"utf-8")).nonce===r&&await Ur(e,{recursive:!0,force:!0})}catch{}}}catch(a){if(a.code!=="EEXIST")throw a}if(!(await VR(e).catch(()=>!1)&&await Ur(e,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=n)throw new Error("connect profile is busy; retry the command");await new Promise(a=>setTimeout(a,KR))}}},Ig=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await No(),r=`${n}.${process.pid}.${BR++}.tmp`;await lc(r,`${JSON.stringify(t,null,2)}
5
- `,{mode:384}),await _u(r,384);try{await he(r,n)}catch(o){throw await Ur(r,{force:!0}).catch(()=>{}),o}},re=async e=>{let t=await Eg();try{await Ig(e)}finally{await t()}},xg=async e=>{let t=await Eg();try{let n=await L(),{next:r,result:o}=e(n);return r&&await Ig(r),o}finally{await t()}},Ou=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],Ag="ssoLink",Lu=async()=>{let e=await L();return Ou.some(t=>e[t]!==void 0)?!0:await We()!==void 0},uc=async()=>{let e=await L(),t=Ou.some(a=>e[a]!==void 0),n=e[Ag]!==void 0,r=e.byoUpstream!==void 0,o=await We()!==void 0;if(!t&&!n&&!r&&!o)return!1;if(t||n||r){let a={...e};for(let s of Ou)delete a[s];delete a[Ag],delete a.byoUpstream,delete a.anyrayFleetManaged,await re(a)}if(await rs(),await We())throw new Error(`could not remove the dev key from ${Q()}`);return!0},Rg=["fallback-bundle.enc","fallback-key","fallback-usage-queue.jsonl"],pc=async()=>{let e=Q();for(let t of Rg)await Ur(xn(e,t),{force:!0}).catch(()=>{})},Du=async()=>{let e=Q(),t=[];for(let n of Rg){let r=xn(e,n);try{await MR(r),t.push(r)}catch{}}return t},Qn=async(e,t,n=!1)=>{let r=await L(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let h of e){let m=h.status==="configured"||h.status==="queued";!t&&m&&(o.add(h.id),a.delete(h.id),s=void 0),t&&(h.status==="reverted"||h.status==="queued")&&(o.delete(h.id),a.add(h.id))}n&&o.clear();let i=[...o].sort(),c=[...r.managedTools??[]].sort(),l=[...a].sort(),d=[...r.revertedTools??[]].sort();if(i.length===c.length&&i.every((h,m)=>h===c[m])&&r.revertedTools!=null&&l.length===d.length&&l.every((h,m)=>h===d[m])&&s===r.offboardedAt)return;let{offboardedAt:f,...p}=r;await re({...p,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},fc=async(e=new Date().toISOString())=>{await re({...await L(),offboardedAt:e})};var Mo=e=>tO(e).replace(/\\/g,"/").toLowerCase(),$u=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",as=e=>`${e}.source`,Lg=e=>/(^|\/)_npx(\/|$)/.test(Mo(e)),Fu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Mo(e)),Uu=e=>{let t=Mo(e),n=[eO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Mo);return Lg(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},ht=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),ss=e=>/[\\/](node|node\.exe)$/i.test(e),er=(e=ht())=>ss(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,_g=e=>{try{let t=Tg(e);return t.isFile()?t.size:void 0}catch{return}},Bu=e=>{let t=Ge(e);if($o(t)==="versions")return t;let n=Ge(t);return $o(n)==="versions"?n:void 0},mc=(e,t)=>t!==void 0&&(Ge(e)===t||Ge(Ge(e))===t),nO=e=>{let t=Bu(e);if(!t)return;let n=Re(Ge(t),"bin",$u());try{let r=os(n);return r===os(e)||mc(r,os(t))?n:void 0}catch{return}},Fo=(e=Q(),t=process.platform)=>{let n=Re(e,"bin",$u(t));try{let r=os(n),o=os(Re(e,"versions"));if(mc(r,o))return n;if(t==="win32"){let a=ZR(as(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=_g(Re(o,a,$u(t)))??_g(Re(o,a));if(s!==void 0&&s===Tg(n).size)return n}}catch{return}},Br=(e=ht())=>{let t=er(e),n=Fu(t)||Hu(t)?Fo():void 0;return nO(e.execPath)??n??t},Dg=(e=ht())=>Br(e)!==er(e),un=(e,t=ht())=>{let n=Br(t);return ss(t.execPath)&&t.scriptPath!==void 0&&n===er(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},Ng=(e=ht())=>{let t=Br(e);return!ss(e.execPath)&&!Uu(t)?Ge(t):Re(Q(),"bin")},hc=async e=>{try{return await JR(e),!0}catch{return!1}},rO=async e=>{let t=await zR(e),n=Ge(t),r=Ge(n),o=Re(r,"package.json"),a=await Mu(o,"utf8"),s=JSON.parse(a);if(typeof s.version!="string"||!/^[0-9A-Za-z][0-9A-Za-z.-]*$/.test(s.version))throw new Error("published package has no safe version");if(!await hc(Re(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},oO=async(e,t)=>{let n=t;for(;;){let r=Re(n,"node_modules",e);if(await hc(Re(r,"package.json")))return r;let o=Ge(n);if(o===n)return;n=o}},aO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Mu(Re(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await oO(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Pg(i,Re(t,s),{recursive:!0}),r.push(i)}}},sO=async(e=ht())=>{let t=Fo();if(t)return{command:t,args:[],entryPath:t};if(!ss(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await rO(e.scriptPath);await kt();let r=Re(Q(),"bin",`connect-runtime-${n.version}`),o=Re(r,"dist","index.js");if(!await hc(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Nu(a,{recursive:!0,force:!0}),await Og(a,{recursive:!0,mode:448});try{await Pg(n.dist,Re(a,"dist"),{recursive:!0}),await QR(Re(a,"package.json"),await Mu(n.packageJson),{mode:384}),await aO(n.root,Re(a,"node_modules")),await Og(Ge(r),{recursive:!0,mode:448});try{await qR(a,r)}catch(s){if(!await hc(o))throw s}}finally{await Nu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Wu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,iO=e=>{let t=$o(Ge(Ge(e)));return Wu.test(t)?t:void 0},Hu=(e,t=Q())=>{let n=Ge(Ge(e));return Mo(Ge(n))===Mo(Re(t,"bin"))&&Wu.test($o(n))&&$o(Ge(e))==="dist"&&$o(e)==="index.js"},yc=async(e=ht())=>{let t=Re(Q(),"bin"),n=iO(er(e)),r=[];for(let o of await XR(t).catch(()=>[])){if(!Wu.test(o)||o===n)continue;let a=Re(t,o);await Nu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},$g=async(e,t=ht())=>{let n=er(t);if(!ss(t.execPath)||!Lg(n)||Fo())return;let r=await sO(t),o=YR(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Ku=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,is=(e,t)=>[e,...t].map(Ku).join(" "),Rn=(e,t={})=>({...t.matcher!==void 0?{matcher:t.matcher}:{},hooks:[{type:"command",command:e,...t.timeout!==void 0?{timeout:t.timeout}:{},...t.async!==void 0?{async:t.async}:{}}]}),tr=(e,t)=>{if(e===null||typeof e!="object")return!1;let n=e.hooks;return Array.isArray(n)&&n.some(r=>r!==null&&typeof r=="object"&&typeof r.command=="string"&&r.command.includes(t))},gc=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!tr(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},Uo=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!tr(s,n));return a.length===o.length?!1:(a.length?r[t]=a:delete r[t],Object.keys(r).length===0&&delete e.hooks,!0)},Gu=e=>{let t=e.hooks;if(!t)return!1;let n=!1;for(let[r,o]of Object.entries(t)){if(!Array.isArray(o))continue;let a=o.filter(s=>!tr(s,"__anyray-"));a.length!==o.length&&(n=!0,a.length?t[r]=a:delete t[r])}return n&&Object.keys(t).length===0&&delete e.hooks,n};var Je="__anyray-hook",Mg="__anyray-codex-hook",nr="__anyray-prompt-hook",Fg="__anyray-shell-pretool",ju="__anyray-shell-run",Ug="__anyray-read-pretool",rr="__anyray-refresh",cs=(e,t=[])=>{let{command:n,args:r}=un([e,...t]);return{command:n,args:r}},Lt=(e,t=[])=>{let n=cs(e,t);return[n.command,...n.args].map(Ku).join(" ")},wc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Lt(t,n),Bg=()=>Lt("print-key"),Oe=()=>Br(),je=Uu,le=()=>!je(Oe()),Wr=async()=>{if(!le())return!1;try{return await cO(Oe()),!0}catch{return!1}},or="__anyray-mcp-server",Ve=e=>cs(or,[e]),lO=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),bc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ve(t);return n.command===r.command&&lO(n.args,r.args)},zt=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(typeof n.command!="string"||!Array.isArray(n.args)||!n.args.every(o=>typeof o=="string"))return!1;let r=n.args;return(r.length===2||r.length===3)&&r.at(-2)===or&&r.at(-1)===t};var X=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,de=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Hr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Wg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],kc=[...Hr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],dO=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
6
- `)},pn=(e,t={})=>{let n=e.byoUpstream,r=!n&&X(e,"anthropic"),o=de({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1&&!((r||n)&&e.viaLocalProxy),s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=dO(o,r,a?e.clientKey:void 0,n?.url);return{env:{ANTHROPIC_BASE_URL:e.anthropicBaseUrl,...c?{ANTHROPIC_CUSTOM_HEADERS:c}:{},...n&&s?{ANTHROPIC_AUTH_TOKEN:n.key}:{},...r||n||!s?{}:{ANTHROPIC_AUTH_TOKEN:e.clientKey??e.placeholderKey},...n?{}:{ENABLE_TOOL_SEARCH:"true"},...n?{}:{_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL:"1"},...i!==void 0?{CLAUDE_CODE_MAX_CONTEXT_TOKENS:String(i)}:{}},subscription:r,byoUpstream:!!n,meta:o,headers:c}};import{z as Vu}from"zod";var uO=5e3,pO=1e3,fO=1e8,hO=Vu.object({modelContext:Vu.object({contextTokens:Vu.number().int().min(pO).max(fO)}).optional()}),Hg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},Kg=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??uO,a=new AbortController,s=setTimeout(()=>a.abort(),o);try{let i=`${e}/connect/policy?model=${encodeURIComponent(n)}`,c=await fetch(i,{method:"GET",headers:{"x-anyray-api-key":t},signal:a.signal});if(!c.ok)return;let l=hO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var mO=1e6,ls="[1m]",yO=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Gg=(e,t)=>!e||t===void 0?{}:yO(e)?{envTokens:t}:t<mO?{}:e.toLowerCase().endsWith(ls)?{}:{model:`${e}${ls}`},jg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(ls))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(ls))return e.slice(0,-ls.length)};import{platform as gO}from"node:os";var Dt=(e=gO())=>{switch(e){case"darwin":return"/Library/Application Support/ClaudeCode/managed-settings.json";case"win32":return"C:\\Program Files\\ClaudeCode\\managed-settings.json";default:return"/etc/claude-code/managed-settings.json"}};var On=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],Cc=e=>typeof e=="string"&&e.trim()!=="",wO=(e,t)=>typeof e[t]=="string"&&!Cc(e[t]),Vg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},bO=()=>U(Dt()).catch(()=>({})),Yg=async(e={})=>{let t=e.env??process.env,n=Vg(e.userSettings??{}),r=Vg(await(e.readManaged??bO)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of On)Cc(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Dt()})`,repairable:!1}):Cc(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!wO(n,a)&&Cc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Yu=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`,Zu=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.",Zg=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 kO=On.map(e=>e.name),CO=kc.filter(e=>!kO.includes(e)),Jg=e=>typeof e=="string"&&e.trim()!=="",Xg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},AO=(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)},vO=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Ju=()=>U(Dt()).catch(()=>({})),zg=Ju,SO=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=>tr(r,Je))},qg=async(e={})=>{let t=await(e.readManaged??zg)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!SO(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},Ac=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Dt()}) \u2014 Claude Code skips every hook and the status line, including Anyray's savings hook`:e.state==="restricted_dropping_ours"?`allowManagedHooksOnly is true in managed settings (${Dt()}), but that file does not carry the Anyray PostToolUse hook \u2014 Claude Code silently drops the user-scope hook Connect installed`:"Claude Code managed hook policy allows the Anyray hook lane",vc=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.",Qg=async(e={})=>{let t=Xg(e.userSettings??{}),n=Xg(await(e.readManaged??zg)().catch(()=>({}))),r=[];for(let o of CO){if(!Jg(n[o])||!Jg(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(AO(n[o],t[o],a))continue;let s=a?vO(n[o]):void 0;r.push({name:o,source:`managed settings (${Dt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},ew=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`,tw=e=>"Fix: the managed settings file is IT-owned \u2014 ask your admin to "+(e.some(t=>t.routing)?"point it at the Anyray gateway (`anyray-connect managed --print` emits the block to deploy) or drop the key so per-user setup governs":"drop the key so per-user setup governs")+", then restart Claude Code.";import{homedir as EO}from"node:os";import{join as IO}from"node:path";import{readFile as xO}from"node:fs/promises";var nt=e=>!!e.keyRefreshEnabled;var RO=400,nw=async()=>{try{let e=IO(EO(),".claude","settings.json"),n=JSON.parse(await xO(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
7
- `)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},rw=async()=>{try{let e=await L();return e.gateway?{origin:new URL(e.gateway).origin,metadata:de({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},rt=async(e="auto")=>e==="profile"?rw():e==="claude"?nw():await nw()??await rw(),Sc=async(e={})=>{let t=e.readTarget??rt,n=e.loadProfile??L,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return nt(r)&&r.fallbackPort&&a.add(`http://${ft}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},qt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},Ec=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),RO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:qt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var _n=()=>xc(Ic(),".claude","settings.json"),ds=()=>xc(Ic(),".claude.json"),OO=kc,ar="anyray",_O=()=>({type:"stdio",...Ve("claude"),alwaysLoad:!0}),Kr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),TO=e=>{if("mcpServers"in e&&!Kr(e.mcpServers))return"conflict";let t=Kr(e.mcpServers)?{...e.mcpServers}:{},n=t[ar];return n!==void 0&&!zt(n,"claude")?"conflict":(t[ar]=_O(),e.mcpServers=t,"installed")},ow=e=>{let t=e.mcpServers;return!t||!(ar in t)||!zt(t[ar],"claude")?!1:(delete t[ar],Object.keys(t).length===0&&delete e.mcpServers,!0)},PO=e=>{gc(e,"PostToolUse",Je,Rn(Lt(Je),{matcher:"*"})),gc(e,"UserPromptSubmit",nr,Rn(Lt(nr)))},LO=e=>{gc(e,"SessionStart",rr,Rn(Lt(rr),{async:!0}))},iw=e=>Uo(e,"SessionStart",rr),aw=e=>{let t=Uo(e,"PostToolUse",Je),n=Uo(e,"UserPromptSubmit",nr),r=iw(e);return t||n||r},DO="print-key",NO=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Gr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===DO&&NO(t)},$O=async(e,t)=>{let n=(await Fr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of OO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},MO=e=>typeof e.apiKeyHelper=="string"&&!Gr(e),cw=async e=>{let t=await Ju(),n=async()=>t,[r,o,a]=await Promise.all([Yg({userSettings:e,readManaged:n}),Qg({userSettings:e,readManaged:n}).catch(()=>[]),qg({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},sw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await cw(e),o=Zu(t),a=tw(n);return{routingOverrides:[...t.map(i=>({problem:Yu(i),fix:i.repairable?"Fix: run `anyray-connect doctor --repair` (or re-run `anyray-connect`) \u2014 apply disables this switch by pinning it empty in settings.json.":o,repairable:i.repairable})),...n.map(i=>({problem:ew(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},sr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=xc(Ic(),".claude"),t=await R(e);return{installed:t,detail:t?_n():"no ~/.claude directory"}},async apply(e,t){let n=_n(),r=await U(n),o=Hg(r),a=await Kg(e.origin,e.clientKey,o),s=Gg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=pn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await cw(r),h=f.filter(x=>!x.repairable),m=f.filter(x=>x.repairable),w=[...h.map(x=>`WARNING: ${Yu(x)}.`),...h.length?[Zu(h)]:[],...p.state==="fine"?[]:[`WARNING: ${Ac(p)}.`,vc(p)],...m.map(x=>Zg(x)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let g=r.env??{};r.env={...g,...i};let y=r.env;for(let{name:x}of On)m.some(T=>T.name===x)?y[x]="":y[x]===""&&(process.env[x]??"").trim()===""&&delete y[x];if(u||delete y.ANTHROPIC_CUSTOM_HEADERS,c&&(g.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete y.ANTHROPIC_AUTH_TOKEN),l)for(let x of Wg)delete y[x];let b=!!e.clientKey,A=le(),v=MO(r);!c&&!l&&b&&A&&!v?(r.apiKeyHelper=Bg(),y.ANTHROPIC_AUTH_TOKEN="",w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Gr(r)&&delete r.apiKeyHelper,v&&!c&&!l&&b&&A&&w.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&A?(LO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):iw(r),le()?(PO(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(aw(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await J(n,r);let I=[n],C=ds();try{let x=await U(C),T=!1;le()?TO(x)==="conflict"?w.push(`MCP name conflict in ${C}: mcpServers.${ar} is not owned by Anyray Connect, so it was left untouched.`):(T=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):T=ow(x),T&&(await J(C,x),I.push(C))}catch(x){w.push(`Could not register the Anyray MCP server in ${C} (${x instanceof Error?x.message:String(x)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:I}},skillsDir(){return xc(Ic(),".claude","skills")},async watchPaths(){return[_n(),ds()]},async pointsAt(e){let t=_n();if(!await R(t))return!1;try{let o=(await U(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await U(_n()).catch(()=>({}));return sw(e)},async routingOverrides(){let e=await U(_n()).catch(()=>({}));return(await sw(e)).routingOverrides},async mcpStatus(){let e=ds();if(!await R(e))return{registered:!1,command:null};try{let r=(await U(e)).mcpServers?.[ar];return!r||!zt(r,"claude")?{registered:!1,command:null}:{registered:!0,command:typeof r.command=="string"?r.command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=_n();if(!await R(n))e="missing";else try{let s=await U(n);if(s.hooks===void 0)e="missing";else if(!Kr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>tr(c,Je))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>tr(c,Je)&&Kr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Kr(l)&&wc(l.command,Je))))}}catch{e="unreadable"}let r,o=!0,a=ds();if(!await R(a))r="missing";else try{let s=await U(a);if(s.mcpServers===void 0)r="missing";else if(!Kr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[ar];r=i===void 0?"missing":zt(i,"claude")?"owned":"foreign",r==="owned"&&(o=bc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Wr()?"owned":"missing",beacon_target:await Sc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await U(_n()),t=Kr(e.env)?e.env:{},n=typeof t.ANTHROPIC_CUSTOM_HEADERS=="string"?t.ANTHROPIC_CUSTOM_HEADERS:"";if(/^x-anyray-custom-host:/m.test(n))return["byo"];if(/^x-anyray-auth-mode:\s*passthrough$/m.test(n))return["subscription"];if(typeof t.ANTHROPIC_AUTH_TOKEN=="string"||typeof e.apiKeyHelper=="string")return["api_key"]}catch{}return["unknown"]},async revert(e){let t=_n();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await U(t),r=n.env,o=aw(n),a=Gr(n);a&&delete n.apiKeyHelper;let s=r?await $O(t,r):[],i=jg(typeof n.model=="string"?n.model:void 0,(await Fr(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await J(t,n,{backup:!1});let c=[`removed Anyray keys from ${t}`];i!==void 0&&c.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&c.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&c.push("Removed the Anyray apiKeyHelper."),s.length&&c.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let l=ds();try{let d=await U(l);ow(d)&&(await J(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await ae(t),{status:"reverted",messages:c,changedFiles:[t]}}};var we="0.11.147";var fn=e=>{let{command:t,args:n}=un([e]);return{command:t,args:n}},ir=()=>Br();import{homedir as lw,userInfo as FO}from"node:os";var us=()=>{try{return lw()!==FO().homedir}catch{return!1}},Bo=e=>[`Skipped ${e} \u2014 HOME (${lw()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var mt=(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,jr=(e=process.env)=>mt(e)!==null,Ct=e=>e==="codespaces"||e==="devcontainer",cr=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var Qu="__anyray-fallback-proxy",hs="ai.anyray.connect.fallback",lr="anyray-fallback",hw=hs,ke=8785,ms=60,ep="x-anyray-local",tp=()=>fn(Qu),dw=ir,Oc=async(e=ke)=>{let t=n=>new Promise(r=>{let o=WO();o.once("error",()=>r(!1)),o.listen(n,"127.0.0.1",()=>o.close(()=>r(!0)))});for(let n=e;n<e+20;n++)if(await t(n))return n;return e},be=async(e,t=1500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}/__anyray/health`,{signal:n.signal});return o.ok?await o.json():null}catch{return null}finally{clearTimeout(r)}},Go=()=>Ko(fs(),"Library","LaunchAgents",`${hw}.plist`),ys=()=>Ko(fs(),".anyray","logs"),ps=()=>Ko(ys(),"connect-daemon.log"),mw=async(e,t=1048576)=>{await pw(e).then(r=>r.size,()=>0)>t&&await BO(e).catch(()=>{})},jo=()=>Ko(fs(),".config","systemd","user",`${lr}.service`),Xu=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),gs=(e=tp())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${Xu(o)}</string>`).join(`
2
+ var EO="http://localhost:8787",ts="anyray-placeholder",xe=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Xe=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},vu=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,xO=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),lg=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!xO.has(n)}catch{return!1}},dn=e=>{let t=Xe(e||process.env.ANYRAY_GATEWAY_URL||EO),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},ht="127.0.0.1",On=(e,t)=>{let n=`http://${ht}:${t}`;return{...e,anthropicBaseUrl:n,openaiBaseUrl:`${n}/v1`,viaLocalProxy:!0}},ge=(e={})=>{let t=dn(e.origin),n=e.placeholderKey?.trim()||ts,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:vu(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:vu(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:vu(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,authMode:a,byoUpstream:e.byoUpstream,seat:a==="auto"?e.seat:void 0,metadata:o}};import{homedir as ms,platform as Ho}from"node:os";import{join as Ko}from"node:path";import{mkdir as Qu,readFile as fw,rename as GR,stat as hw,truncate as jR,writeFile as mw,rm as Wo}from"node:fs/promises";import{spawnSync as hn}from"node:child_process";import{createServer as VR}from"node:net";import{homedir as Oc}from"node:os";import{join as Rc}from"node:path";import{access as PO,chmod as TO,mkdir as Su,open as Ru,readFile as yg,rm as Jt,stat as ug,utimes as LO}from"node:fs/promises";import{createHash as DO,randomUUID as gg}from"node:crypto";import{dirname as _u,join as NO}from"node:path";import{isDeepStrictEqual as Lo}from"node:util";import{randomUUID as IO}from"node:crypto";import{lstat as OO,rename as cc,rm as RO}from"node:fs/promises";import{platform as dg}from"node:os";var _O=e=>e?.code==="ENOENT",ns=async(e,t=dg())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},he=async(e,t,n=dg())=>{if(n!=="win32"){await cc(e,t);return}let r=`${t}.anyray-old-${process.pid}-${IO()}`,o=!1;try{let a=await OO(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await cc(t,r),o=!0}catch(a){if(!_O(a))throw a}try{await cc(e,t)}catch(a){if(o)try{await cc(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await RO(r,{force:!0})};var rs=e=>`${e}.anyray-bak`,wg=async e=>{let t;try{t=await Ru(_u(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},pg=async(e,t)=>{let n,r;try{n=await Ru(e,"wx",384),await n.writeFile(t,"utf-8"),await ns(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Jt(e,{force:!0}).catch(()=>{}),r;await wg(e)},$O=async e=>{let t;try{t=await Ru(e,"r"),await ns(t)}finally{await t?.close().catch(()=>{})}await wg(e)},O=async e=>{try{return await PO(e),!0}catch{return!1}},U=async e=>{if(!await O(e))return{};let t=await yg(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},X=async(e,t,n={})=>{await Su(_u(e),{recursive:!0,mode:448});let r=rs(e);if(n.backup!==!1&&await O(e)&&!await O(r))try{await pg(r,await yg(e,"utf-8"))}catch(a){if(a.code!=="EEXIST")throw a}let o=`${e}.anyray-tmp-${process.pid}-${gg()}`;try{await pg(o,`${JSON.stringify(t,null,2)}
3
+ `),await he(o,e),await TO(e,384),await $O(e)}finally{await Jt(o,{force:!0}).catch(()=>{})}},bg=1,fg=3e4,MO=5e3,FO=/^[a-f0-9]{64}$/,kg=e=>`${e}.pending`,UO=e=>`${e}.lock`,Eu=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=>Eu(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Eu(t[n])}`).join(",")}}`},xu=(e,t)=>({exists:e,sha256:DO("sha256").update(Eu(t)).digest("hex")}),Iu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),hg=e=>Iu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&FO.test(e.sha256),BO=e=>Iu(e)&&e.transactionVersion===bg&&hg(e.before)&&hg(e.after)&&Iu(e.journal),Ou=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,Do=async(e,t)=>{try{return await U(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},WO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Cg=async e=>{let t=UO(e),n=NO(t,"owner.json");await Su(_u(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=gg();try{await Su(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await Do(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 ug(n)).mtimeMs;i=!WO(c.pid)||l>fg}catch{try{i=Date.now()-(await ug(t)).mtimeMs>fg}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Jt(t,{recursive:!0,force:!0});continue}try{await X(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Jt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await Do(n,"ownership journal")).nonce!==o)return;let i=new Date;await LO(n,i,i)}catch{}})()},MO);return a.unref(),async()=>{clearInterval(a);try{(await Do(n,"ownership journal")).nonce===o&&await Jt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},Ag=async e=>{let t=await O(e),n={};if(t)try{n=await U(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:xu(t,n)}},vg=async(e,t)=>{let n=kg(t);if(!await O(n))return;let r=await Do(n,"prepared ownership transaction");if(!BO(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await Ag(e),a=await O(t),s=await O(rs(e)),i=Ou(o.fingerprint,r.before),c=Ou(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await X(t,r.journal,{backup:!1}),await Jt(n,{force:!0});return}if(i){await Jt(n,{force:!0}),a||await se(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},lc=async(e,t,n)=>{let r=await Cg(t);try{return await vg(e,t),await n()}finally{await r()}},mg=async(e,t,n,r)=>{if(!await O(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await Do(e,"ownership journal");if(!(n&&Lo(a,t))){if(!Lo(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await X(e,t,{backup:!1}):await Jt(e,{force:!0})}},dc=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await Cg(a);try{await vg(n,a);let l=await Ag(n),d=xu(i,r),u=await O(a),f=u?await Do(a,"ownership journal"):void 0,p=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!Ou(l.fingerprint,d)){if(Lo(l.value,o)&&f&&Lo(f,p))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&Lo(l.value,o)&&f&&Lo(f,p))return;let h=await O(rs(n));if(f?.fileExisted===!0&&!h)throw new Error("ownership backup is missing; configuration was left unchanged");if(h&&!f)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let m=kg(a),w={transactionVersion:bg,before:l.fingerprint,after:xu(!0,o),journal:p};await X(m,w,{backup:!1});try{await X(n,o,f?{backup:!1}:{}),await(t.writeJournal??X)(a,p,{backup:!1}),await Jt(m,{force:!0})}catch(g){try{await mg(n,l.value,l.exists,o)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed and config rollback was incomplete")}try{await mg(a,f??{},u,p),await Jt(m,{force:!0}),!h&&!f&&await se(n)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed after config rollback")}throw g}}finally{await c()}},Mr=async e=>{try{return await U(rs(e))}catch{return{}}},se=async e=>{await Jt(rs(e),{force:!0}).catch(()=>{})};import{access as fR}from"node:fs/promises";import{spawnSync as zO}from"node:child_process";import{readFileSync as QO,realpathSync as ss,statSync as Lg}from"node:fs";import{access as eR,cp as Dg,mkdir as Pg,readdir as tR,readFile as Uu,realpath as nR,rename as rR,rm as Mu,writeFile as oR}from"node:fs/promises";import{tmpdir as aR}from"node:os";import{basename as $o,dirname as Ge,join as Ie,resolve as sR}from"node:path";import{writeFile as uc,readFile as os,chmod as Tu,stat as Lu,mkdir as Eg,rm as Fr,access as HO}from"node:fs/promises";import{randomUUID as KO}from"node:crypto";import{homedir as xg}from"node:os";import{join as Rn}from"node:path";var Q=()=>Rn(xg(),".anyray"),No=async()=>{let e=Q();try{if((await Lu(e)).isDirectory())return Rn(e,"connect.json")}catch{}return e},Du=()=>Rn(Q(),"dev-key.pem"),kt=async()=>{let e=Q(),t;try{if(!(await Lu(e)).isDirectory())t=await os(e,"utf-8").catch(()=>{}),await Fr(e,{force:!0});else return}catch{}if(await Eg(e,{recursive:!0,mode:448}),t!==void 0){let n=Rn(e,"connect.json");await uc(n,t,{mode:384}),await Tu(n,384)}},pc=async e=>{await kt();let t=Du();await uc(t,e,{mode:384}),await Tu(t,384)},We=async()=>{try{let e=await os(Du(),"utf-8");return e.trim()?e:void 0}catch{return}},as=async()=>{await Fr(Du(),{force:!0}).catch(()=>{})},GO=e=>{let{fallbackEnabled:t,fallbackGatewayTimeoutMs:n,fallbackBreaker:r,...o}=e,a=o;return t===!0&&(a.keyRefreshEnabled=!0),a},D=async()=>{try{let e=await os(await No(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:GO(t)}catch{return{}}},jO=0,VO=3e4,YO=5e3,ZO=25,XO=()=>Rn(xg(),".anyray-connect-profile.lock"),JO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},qO=async e=>{try{let t=JSON.parse(await os(Rn(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!JO(t.pid)}catch{}return Date.now()-(await Lu(e)).mtimeMs>VO},Ig=async()=>{let e=XO(),t=Rn(e,"owner.json"),n=Date.now()+YO;for(;;){let r=KO();try{await Eg(e,{mode:448});try{await uc(t,`${JSON.stringify({pid:process.pid,nonce:r})}
4
+ `,{mode:384})}catch(a){throw await Fr(e,{recursive:!0,force:!0}).catch(()=>{}),a}return async()=>{try{JSON.parse(await os(t,"utf-8")).nonce===r&&await Fr(e,{recursive:!0,force:!0})}catch{}}}catch(a){if(a.code!=="EEXIST")throw a}if(!(await qO(e).catch(()=>!1)&&await Fr(e,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=n)throw new Error("connect profile is busy; retry the command");await new Promise(a=>setTimeout(a,ZO))}}},Og=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await No(),r=`${n}.${process.pid}.${jO++}.tmp`;await uc(r,`${JSON.stringify(t,null,2)}
5
+ `,{mode:384}),await Tu(r,384);try{await he(r,n)}catch(o){throw await Fr(r,{force:!0}).catch(()=>{}),o}},re=async e=>{let t=await Ig();try{await Og(e)}finally{await t()}},Rg=async e=>{let t=await Ig();try{let n=await D(),{next:r,result:o}=e(n);return r&&await Og(r),o}finally{await t()}},Pu=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],Sg="ssoLink",Nu=async()=>{let e=await D();return Pu.some(t=>e[t]!==void 0)?!0:await We()!==void 0},fc=async()=>{let e=await D(),t=Pu.some(a=>e[a]!==void 0),n=e[Sg]!==void 0,r=e.byoUpstream!==void 0,o=await We()!==void 0;if(!t&&!n&&!r&&!o)return!1;if(t||n||r){let a={...e};for(let s of Pu)delete a[s];delete a[Sg],delete a.byoUpstream,delete a.anyrayFleetManaged,await re(a)}if(await as(),await We())throw new Error(`could not remove the dev key from ${Q()}`);return!0},_g=["fallback-bundle.enc","fallback-key","fallback-usage-queue.jsonl"],hc=async()=>{let e=Q();for(let t of _g)await Fr(Rn(e,t),{force:!0}).catch(()=>{})},$u=async()=>{let e=Q(),t=[];for(let n of _g){let r=Rn(e,n);try{await HO(r),t.push(r)}catch{}}return t},tr=async(e,t,n=!1)=>{let r=await D(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let h of e){let m=h.status==="configured"||h.status==="queued";!t&&m&&(o.add(h.id),a.delete(h.id),s=void 0),t&&(h.status==="reverted"||h.status==="queued")&&(o.delete(h.id),a.add(h.id))}n&&o.clear();let i=[...o].sort(),c=[...r.managedTools??[]].sort(),l=[...a].sort(),d=[...r.revertedTools??[]].sort();if(i.length===c.length&&i.every((h,m)=>h===c[m])&&r.revertedTools!=null&&l.length===d.length&&l.every((h,m)=>h===d[m])&&s===r.offboardedAt)return;let{offboardedAt:f,...p}=r;await re({...p,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},mc=async(e=new Date().toISOString())=>{await re({...await D(),offboardedAt:e})};var Mo=e=>sR(e).replace(/\\/g,"/").toLowerCase(),Fu=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",is=e=>`${e}.source`,Ng=e=>/(^|\/)_npx(\/|$)/.test(Mo(e)),Bu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Mo(e)),Wu=e=>{let t=Mo(e),n=[aR(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Mo);return Ng(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},mt=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),cs=e=>/[\\/](node|node\.exe)$/i.test(e),nr=(e=mt())=>cs(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,Tg=e=>{try{let t=Lg(e);return t.isFile()?t.size:void 0}catch{return}},Hu=e=>{let t=Ge(e);if($o(t)==="versions")return t;let n=Ge(t);return $o(n)==="versions"?n:void 0},gc=(e,t)=>t!==void 0&&(Ge(e)===t||Ge(Ge(e))===t),iR=e=>{let t=Hu(e);if(!t)return;let n=Ie(Ge(t),"bin",Fu());try{let r=ss(n);return r===ss(e)||gc(r,ss(t))?n:void 0}catch{return}},Fo=(e=Q(),t=process.platform)=>{let n=Ie(e,"bin",Fu(t));try{let r=ss(n),o=ss(Ie(e,"versions"));if(gc(r,o))return n;if(t==="win32"){let a=QO(is(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=Tg(Ie(o,a,Fu(t)))??Tg(Ie(o,a));if(s!==void 0&&s===Lg(n).size)return n}}catch{return}},Ur=(e=mt())=>{let t=nr(e),n=Bu(t)||Gu(t)?Fo():void 0;return iR(e.execPath)??n??t},$g=(e=mt())=>Ur(e)!==nr(e),un=(e,t=mt())=>{let n=Ur(t);return cs(t.execPath)&&t.scriptPath!==void 0&&n===nr(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},Mg=(e=mt())=>{let t=Ur(e);return!cs(e.execPath)&&!Wu(t)?Ge(t):Ie(Q(),"bin")},yc=async e=>{try{return await eR(e),!0}catch{return!1}},cR=async e=>{let t=await nR(e),n=Ge(t),r=Ge(n),o=Ie(r,"package.json"),a=await Uu(o,"utf8"),s=JSON.parse(a);if(typeof s.version!="string"||!/^[0-9A-Za-z][0-9A-Za-z.-]*$/.test(s.version))throw new Error("published package has no safe version");if(!await yc(Ie(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},lR=async(e,t)=>{let n=t;for(;;){let r=Ie(n,"node_modules",e);if(await yc(Ie(r,"package.json")))return r;let o=Ge(n);if(o===n)return;n=o}},dR=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Uu(Ie(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await lR(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Dg(i,Ie(t,s),{recursive:!0}),r.push(i)}}},uR=async(e=mt())=>{let t=Fo();if(t)return{command:t,args:[],entryPath:t};if(!cs(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await cR(e.scriptPath);await kt();let r=Ie(Q(),"bin",`connect-runtime-${n.version}`),o=Ie(r,"dist","index.js");if(!await yc(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Mu(a,{recursive:!0,force:!0}),await Pg(a,{recursive:!0,mode:448});try{await Dg(n.dist,Ie(a,"dist"),{recursive:!0}),await oR(Ie(a,"package.json"),await Uu(n.packageJson),{mode:384}),await dR(n.root,Ie(a,"node_modules")),await Pg(Ge(r),{recursive:!0,mode:448});try{await rR(a,r)}catch(s){if(!await yc(o))throw s}}finally{await Mu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Ku=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,pR=e=>{let t=$o(Ge(Ge(e)));return Ku.test(t)?t:void 0},Gu=(e,t=Q())=>{let n=Ge(Ge(e));return Mo(Ge(n))===Mo(Ie(t,"bin"))&&Ku.test($o(n))&&$o(Ge(e))==="dist"&&$o(e)==="index.js"},wc=async(e=mt())=>{let t=Ie(Q(),"bin"),n=pR(nr(e)),r=[];for(let o of await tR(t).catch(()=>[])){if(!Ku.test(o)||o===n)continue;let a=Ie(t,o);await Mu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},Fg=async(e,t=mt())=>{let n=nr(t);if(!cs(t.execPath)||!Ng(n)||Fo())return;let r=await uR(t),o=zO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var ju=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,ls=(e,t)=>[e,...t].map(ju).join(" "),_n=(e,t={})=>({...t.matcher!==void 0?{matcher:t.matcher}:{},hooks:[{type:"command",command:e,...t.timeout!==void 0?{timeout:t.timeout}:{},...t.async!==void 0?{async:t.async}:{}}]}),rr=(e,t)=>{if(e===null||typeof e!="object")return!1;let n=e.hooks;return Array.isArray(n)&&n.some(r=>r!==null&&typeof r=="object"&&typeof r.command=="string"&&r.command.includes(t))},bc=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!rr(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},Uo=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!rr(s,n));return a.length===o.length?!1:(a.length?r[t]=a:delete r[t],Object.keys(r).length===0&&delete e.hooks,!0)},Vu=e=>{let t=e.hooks;if(!t)return!1;let n=!1;for(let[r,o]of Object.entries(t)){if(!Array.isArray(o))continue;let a=o.filter(s=>!rr(s,"__anyray-"));a.length!==o.length&&(n=!0,a.length?t[r]=a:delete t[r])}return n&&Object.keys(t).length===0&&delete e.hooks,n};var Je="__anyray-hook",Ug="__anyray-codex-hook",or="__anyray-prompt-hook",Bg="__anyray-shell-pretool",Yu="__anyray-shell-run",Wg="__anyray-read-pretool",ar="__anyray-refresh",ds=(e,t=[])=>{let{command:n,args:r}=un([e,...t]);return{command:n,args:r}},Tt=(e,t=[])=>{let n=ds(e,t);return[n.command,...n.args].map(ju).join(" ")},kc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Tt(t,n),Hg=()=>Tt("print-key"),Oe=()=>Ur(),je=Wu,le=()=>!je(Oe()),Br=async()=>{if(!le())return!1;try{return await fR(Oe()),!0}catch{return!1}},sr="__anyray-mcp-server",Ve=e=>ds(sr,[e]),hR=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),Cc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ve(t);return n.command===r.command&&hR(n.args,r.args)},qt=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(typeof n.command!="string"||!Array.isArray(n.args)||!n.args.every(o=>typeof o=="string"))return!1;let r=n.args;return(r.length===2||r.length===3)&&r.at(-2)===sr&&r.at(-1)===t};var J=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,de=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Wr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Kg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Ac=[...Wr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],mR=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
6
+ `)},pn=(e,t={})=>{let n=e.byoUpstream,r=!n&&J(e,"anthropic"),o=de({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1&&!((r||n)&&e.viaLocalProxy),s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=mR(o,r,a?e.clientKey:void 0,n?.url);return{env:{ANTHROPIC_BASE_URL:e.anthropicBaseUrl,...c?{ANTHROPIC_CUSTOM_HEADERS:c}:{},...n&&s?{ANTHROPIC_AUTH_TOKEN:n.key}:{},...r||n||!s?{}:{ANTHROPIC_AUTH_TOKEN:e.clientKey??e.placeholderKey},...n?{}:{ENABLE_TOOL_SEARCH:"true"},...n?{}:{_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL:"1"},...i!==void 0?{CLAUDE_CODE_MAX_CONTEXT_TOKENS:String(i)}:{}},subscription:r,byoUpstream:!!n,meta:o,headers:c}};import{z as Zu}from"zod";var yR=5e3,gR=1e3,wR=1e8,bR=Zu.object({modelContext:Zu.object({contextTokens:Zu.number().int().min(gR).max(wR)}).optional()}),Gg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},jg=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??yR,a=new AbortController,s=setTimeout(()=>a.abort(),o);try{let i=`${e}/connect/policy?model=${encodeURIComponent(n)}`,c=await fetch(i,{method:"GET",headers:{"x-anyray-api-key":t},signal:a.signal});if(!c.ok)return;let l=bR.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var kR=1e6,us="[1m]",CR=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Vg=(e,t)=>!e||t===void 0?{}:CR(e)?{envTokens:t}:t<kR?{}:e.toLowerCase().endsWith(us)?{}:{model:`${e}${us}`},Yg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(us))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(us))return e.slice(0,-us.length)};import{platform as AR}from"node:os";var Lt=(e=AR())=>{switch(e){case"darwin":return"/Library/Application Support/ClaudeCode/managed-settings.json";case"win32":return"C:\\Program Files\\ClaudeCode\\managed-settings.json";default:return"/etc/claude-code/managed-settings.json"}};var Pn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],vc=e=>typeof e=="string"&&e.trim()!=="",vR=(e,t)=>typeof e[t]=="string"&&!vc(e[t]),Zg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},SR=()=>U(Lt()).catch(()=>({})),Xg=async(e={})=>{let t=e.env??process.env,n=Zg(e.userSettings??{}),r=Zg(await(e.readManaged??SR)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of Pn)vc(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Lt()})`,repairable:!1}):vc(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!vR(n,a)&&vc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Xu=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`,Ju=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.",Jg=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 ER=Pn.map(e=>e.name),xR=Ac.filter(e=>!ER.includes(e)),qg=e=>typeof e=="string"&&e.trim()!=="",zg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},IR=(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)},OR=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},qu=()=>U(Lt()).catch(()=>({})),Qg=qu,RR=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=>rr(r,Je))},ew=async(e={})=>{let t=await(e.readManaged??Qg)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!RR(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},Sc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Lt()}) \u2014 Claude Code skips every hook and the status line, including Anyray's savings hook`:e.state==="restricted_dropping_ours"?`allowManagedHooksOnly is true in managed settings (${Lt()}), but that file does not carry the Anyray PostToolUse hook \u2014 Claude Code silently drops the user-scope hook Connect installed`:"Claude Code managed hook policy allows the Anyray hook lane",Ec=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.",tw=async(e={})=>{let t=zg(e.userSettings??{}),n=zg(await(e.readManaged??Qg)().catch(()=>({}))),r=[];for(let o of xR){if(!qg(n[o])||!qg(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(IR(n[o],t[o],a))continue;let s=a?OR(n[o]):void 0;r.push({name:o,source:`managed settings (${Lt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},nw=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`,rw=e=>"Fix: the managed settings file is IT-owned \u2014 ask your admin to "+(e.some(t=>t.routing)?"point it at the Anyray gateway (`anyray-connect managed --print` emits the block to deploy) or drop the key so per-user setup governs":"drop the key so per-user setup governs")+", then restart Claude Code.";import{homedir as _R}from"node:os";import{join as PR}from"node:path";import{readFile as TR}from"node:fs/promises";var rt=e=>!!e.keyRefreshEnabled;var LR=400,ow=async()=>{try{let e=PR(_R(),".claude","settings.json"),n=JSON.parse(await TR(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
7
+ `)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},aw=async()=>{try{let e=await D();return e.gateway?{origin:new URL(e.gateway).origin,metadata:de({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},ot=async(e="auto")=>e==="profile"?aw():e==="claude"?ow():await ow()??await aw(),xc=async(e={})=>{let t=e.readTarget??ot,n=e.loadProfile??D,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return rt(r)&&r.fallbackPort&&a.add(`http://${ht}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},zt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},Ic=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),LR);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:zt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var Tn=()=>Rc(Oc(),".claude","settings.json"),ps=()=>Rc(Oc(),".claude.json"),DR=Ac,ir="anyray",NR=()=>({type:"stdio",...Ve("claude"),alwaysLoad:!0}),Hr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$R=e=>{if("mcpServers"in e&&!Hr(e.mcpServers))return"conflict";let t=Hr(e.mcpServers)?{...e.mcpServers}:{},n=t[ir];return n!==void 0&&!qt(n,"claude")?"conflict":(t[ir]=NR(),e.mcpServers=t,"installed")},sw=e=>{let t=e.mcpServers;return!t||!(ir in t)||!qt(t[ir],"claude")?!1:(delete t[ir],Object.keys(t).length===0&&delete e.mcpServers,!0)},MR=e=>{bc(e,"PostToolUse",Je,_n(Tt(Je),{matcher:"*"})),bc(e,"UserPromptSubmit",or,_n(Tt(or)))},FR=e=>{bc(e,"SessionStart",ar,_n(Tt(ar),{async:!0}))},lw=e=>Uo(e,"SessionStart",ar),iw=e=>{let t=Uo(e,"PostToolUse",Je),n=Uo(e,"UserPromptSubmit",or),r=lw(e);return t||n||r},UR="print-key",BR=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Kr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===UR&&BR(t)},WR=async(e,t)=>{let n=(await Mr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of DR){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},HR=e=>typeof e.apiKeyHelper=="string"&&!Kr(e),dw=async e=>{let t=await qu(),n=async()=>t,[r,o,a]=await Promise.all([Xg({userSettings:e,readManaged:n}),tw({userSettings:e,readManaged:n}).catch(()=>[]),ew({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},cw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await dw(e),o=Ju(t),a=rw(n);return{routingOverrides:[...t.map(i=>({problem:Xu(i),fix:i.repairable?"Fix: run `anyray-connect doctor --repair` (or re-run `anyray-connect`) \u2014 apply disables this switch by pinning it empty in settings.json.":o,repairable:i.repairable})),...n.map(i=>({problem:nw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},cr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=Rc(Oc(),".claude"),t=await O(e);return{installed:t,detail:t?Tn():"no ~/.claude directory"}},async apply(e,t){let n=Tn(),r=await U(n),o=Gg(r),a=await jg(e.origin,e.clientKey,o),s=Vg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=pn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await dw(r),h=f.filter(I=>!I.repairable),m=f.filter(I=>I.repairable),w=[...h.map(I=>`WARNING: ${Xu(I)}.`),...h.length?[Ju(h)]:[],...p.state==="fine"?[]:[`WARNING: ${Sc(p)}.`,Ec(p)],...m.map(I=>Jg(I)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let g=r.env??{};r.env={...g,...i};let y=r.env;for(let{name:I}of Pn)m.some(P=>P.name===I)?y[I]="":y[I]===""&&(process.env[I]??"").trim()===""&&delete y[I];if(u||delete y.ANTHROPIC_CUSTOM_HEADERS,c&&(g.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete y.ANTHROPIC_AUTH_TOKEN),l)for(let I of Kg)delete y[I];let b=!!e.clientKey,A=le(),v=HR(r);!c&&!l&&b&&A&&!v?(r.apiKeyHelper=Hg(),y.ANTHROPIC_AUTH_TOKEN="",w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Kr(r)&&delete r.apiKeyHelper,v&&!c&&!l&&b&&A&&w.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&A?(FR(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):lw(r),le()?(MR(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(iw(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await X(n,r);let x=[n],C=ps();try{let I=await U(C),P=!1;le()?$R(I)==="conflict"?w.push(`MCP name conflict in ${C}: mcpServers.${ir} is not owned by Anyray Connect, so it was left untouched.`):(P=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):P=sw(I),P&&(await X(C,I),x.push(C))}catch(I){w.push(`Could not register the Anyray MCP server in ${C} (${I instanceof Error?I.message:String(I)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:x}},skillsDir(){return Rc(Oc(),".claude","skills")},async watchPaths(){return[Tn(),ps()]},async pointsAt(e){let t=Tn();if(!await O(t))return!1;try{let o=(await U(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await U(Tn()).catch(()=>({}));return cw(e)},async routingOverrides(){let e=await U(Tn()).catch(()=>({}));return(await cw(e)).routingOverrides},async mcpStatus(){let e=ps();if(!await O(e))return{registered:!1,command:null};try{let r=(await U(e)).mcpServers?.[ir];return!r||!qt(r,"claude")?{registered:!1,command:null}:{registered:!0,command:typeof r.command=="string"?r.command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=Tn();if(!await O(n))e="missing";else try{let s=await U(n);if(s.hooks===void 0)e="missing";else if(!Hr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>rr(c,Je))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>rr(c,Je)&&Hr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Hr(l)&&kc(l.command,Je))))}}catch{e="unreadable"}let r,o=!0,a=ps();if(!await O(a))r="missing";else try{let s=await U(a);if(s.mcpServers===void 0)r="missing";else if(!Hr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[ir];r=i===void 0?"missing":qt(i,"claude")?"owned":"foreign",r==="owned"&&(o=Cc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Br()?"owned":"missing",beacon_target:await xc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await U(Tn()),t=Hr(e.env)?e.env:{},n=typeof t.ANTHROPIC_CUSTOM_HEADERS=="string"?t.ANTHROPIC_CUSTOM_HEADERS:"";if(/^x-anyray-custom-host:/m.test(n))return["byo"];if(/^x-anyray-auth-mode:\s*passthrough$/m.test(n))return["subscription"];if(typeof t.ANTHROPIC_AUTH_TOKEN=="string"||typeof e.apiKeyHelper=="string")return["api_key"]}catch{}return["unknown"]},async revert(e){let t=Tn();if(!await O(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await U(t),r=n.env,o=iw(n),a=Kr(n);a&&delete n.apiKeyHelper;let s=r?await WR(t,r):[],i=Yg(typeof n.model=="string"?n.model:void 0,(await Mr(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await X(t,n,{backup:!1});let c=[`removed Anyray keys from ${t}`];i!==void 0&&c.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&c.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&c.push("Removed the Anyray apiKeyHelper."),s.length&&c.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let l=ps();try{let d=await U(l);sw(d)&&(await X(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await se(t),{status:"reverted",messages:c,changedFiles:[t]}}};var we="0.11.148";var fn=e=>{let{command:t,args:n}=un([e]);return{command:t,args:n}},lr=()=>Ur();import{homedir as uw,userInfo as KR}from"node:os";var fs=()=>{try{return uw()!==KR().homedir}catch{return!1}},Bo=e=>[`Skipped ${e} \u2014 HOME (${uw()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var yt=(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,Gr=(e=process.env)=>yt(e)!==null,Ct=e=>e==="codespaces"||e==="devcontainer",dr=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var tp="__anyray-fallback-proxy",ys="ai.anyray.connect.fallback",ur="anyray-fallback",yw=ys,ke=8785,gs=60,np="x-anyray-local",rp=()=>fn(tp),pw=lr,Pc=async(e=ke)=>{let t=n=>new Promise(r=>{let o=VR();o.once("error",()=>r(!1)),o.listen(n,"127.0.0.1",()=>o.close(()=>r(!0)))});for(let n=e;n<e+20;n++)if(await t(n))return n;return e},be=async(e,t=1500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}/__anyray/health`,{signal:n.signal});return o.ok?await o.json():null}catch{return null}finally{clearTimeout(r)}},Go=()=>Ko(ms(),"Library","LaunchAgents",`${yw}.plist`),ws=()=>Ko(ms(),".anyray","logs"),hs=()=>Ko(ws(),"connect-daemon.log"),gw=async(e,t=1048576)=>{await hw(e).then(r=>r.size,()=>0)>t&&await jR(e).catch(()=>{})},jo=()=>Ko(ms(),".config","systemd","user",`${ur}.service`),zu=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),bs=(e=rp())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${zu(o)}</string>`).join(`
8
8
  `);return`<?xml version="1.0" encoding="UTF-8"?>
9
9
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
10
10
  <plist version="1.0">
11
11
  <dict>
12
- <key>Label</key><string>${hw}</string>
12
+ <key>Label</key><string>${yw}</string>
13
13
  <key>ProgramArguments</key>
14
14
  <array>
15
15
  ${r}
@@ -17,12 +17,12 @@ ${r}
17
17
  <key>RunAtLoad</key><true/>
18
18
  <key>KeepAlive</key><true/>
19
19
  <key>ProcessType</key><string>Background</string>
20
- <key>ExitTimeOut</key><integer>${ms}</integer>
21
- <key>StandardOutPath</key><string>${Xu(ps())}</string>
22
- <key>StandardErrorPath</key><string>${Xu(ps())}</string>
20
+ <key>ExitTimeOut</key><integer>${gs}</integer>
21
+ <key>StandardOutPath</key><string>${zu(hs())}</string>
22
+ <key>StandardErrorPath</key><string>${zu(hs())}</string>
23
23
  </dict>
24
24
  </plist>
25
- `},ws=(e=tp())=>{let{command:t,args:n}=e;return`[Unit]
25
+ `},ks=(e=rp())=>{let{command:t,args:n}=e;return`[Unit]
26
26
  Description=Anyray connect local key-refresh proxy
27
27
  After=network-online.target
28
28
 
@@ -30,93 +30,93 @@ After=network-online.target
30
30
  ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
31
31
  Restart=always
32
32
  RestartSec=2
33
- TimeoutStopSec=${ms}
33
+ TimeoutStopSec=${gs}
34
34
 
35
35
  [Install]
36
36
  WantedBy=default.target
37
- `},Rc=()=>{let{command:e,args:t}=tp();return["Auto-start is not wired for this OS. Run the key-refresh proxy yourself:",` ${[e,...t].map(r=>/\s/.test(r)?JSON.stringify(r):r).join(" ")}`,"(keep it running in the background \u2014 your tools route through it)."]},yw=async()=>{let e=Ho();if(e!=="darwin"&&e!=="linux")return!1;let t=e==="darwin"?Go():jo();try{return await pw(t),!0}catch{return!1}},gw=async()=>{let e=Ho();if(e!=="darwin"&&e!=="linux")return!0;let t=e==="darwin"?Go():jo(),n=e==="darwin"?gs():ws();return await uw(t,"utf-8").catch(()=>null)===n},qu=async e=>{await zu(Ko(fs(),"Library","LaunchAgents"),{recursive:!0}),await zu(ys(),{recursive:!0,mode:448}),await fw(e,gs())},ww=async()=>{let e=Ho();return e==="darwin"?(await qu(Go()),!0):e==="linux"?(await zu(Ko(fs(),".config","systemd","user"),{recursive:!0}),await fw(jo(),ws()),!0):!1},bw=async()=>ww().catch(()=>!1),HO=async(e,t)=>{let n=Ho();if(n!=="darwin"&&n!=="linux")return!1;let r=n==="darwin"?Go():jo(),o=n==="darwin"?gs():ws();if(await uw(r,"utf-8").catch(()=>null)!==o)return!1;let s=await be(e);return s?.version!==we?!1:typeof s.remoteOrigin=="string"&&Ze(s.remoteOrigin)===Ze(t)},Nt=async e=>{if(je(dw()))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 anyray-connect is running from a temporary path (${dw()}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(us())return{ok:!1,messages:Bo("key-refresh auto-start")};{let n=mt();if(Ct(n))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 ${cr(n)} has no per-user service manager to supervise the daemon.`]}}if(await HO(e.port,e.remoteOrigin))return{ok:!0,messages:["Key-refresh service already current \u2014 left running."]};let t=Ho();try{if(t==="darwin"){let n=Go(),r=String(process.getuid?.()??""),o=`${n}.new-${process.pid}`;await Wo(o,{force:!0}).catch(()=>{}),await qu(o),hn("launchctl",["bootout",`gui/${r}`,n]),await Wo(n,{force:!0}).catch(()=>{});try{await UO(o,n)}catch{await qu(n),await Wo(o,{force:!0}).catch(()=>{})}return hn("launchctl",["bootstrap",`gui/${r}`,n]).status===0||hn("launchctl",["load","-w",n]).status===0?{ok:!0,messages:[`Installed launchd agent ${n}.`]}:{ok:!1,messages:[`Wrote ${n} but launchd would not load the agent.`,...Rc()]}}if(t==="linux"){let n=jo();return await ww(),hn("systemctl",["--user","daemon-reload"]),hn("systemctl",["--user","enable",`${lr}.service`]),hn("systemctl",["--user","restart",`${lr}.service`]).status!==0?{ok:!1,messages:[`Wrote ${n} but \`systemctl --user restart\` failed.`,...Rc()]}:{ok:!0,messages:[`Installed systemd user unit ${n}.`]}}return{ok:!1,messages:Rc()}}catch(n){return{ok:!1,messages:[`Could not install the key-refresh service: ${n instanceof Error?n.message:String(n)}`,...Rc()]}}},np=async(e=ke,t={})=>{if(await be(e)===null)return!1;let n=t.drain==="idle"?"?drain=idle":"";try{let r=new AbortController,o=setTimeout(()=>r.abort(),1500);try{await fetch(`http://127.0.0.1:${e}/__anyray/shutdown${n}`,{method:"POST",headers:{[ep]:"1"},signal:r.signal})}finally{clearTimeout(o)}}catch{}for(let r=0;r<10&&await be(e,300)!==null;r++)await new Promise(o=>setTimeout(o,100));return!0},Qt=async(e=ke)=>{let t=Ho();await Wo(ps(),{force:!0}).catch(()=>{});let n=[],r=us();try{if(r)n.push(...Bo("key-refresh service teardown"));else if(t==="darwin"){let o=Go(),a=String(process.getuid?.()??"");hn("launchctl",["bootout",`gui/${a}`,o]),hn("launchctl",["unload",o]),await Wo(o,{force:!0}),n.push("Removed the launchd key-refresh agent.")}else t==="linux"&&(hn("systemctl",["--user","disable","--now",`${lr}.service`]),await Wo(jo(),{force:!0}),hn("systemctl",["--user","daemon-reload"]),n.push("Removed the systemd key-refresh unit."))}catch{}try{await np(e)&&n.push("Stopped the running key-refresh proxy daemon.")}catch{}return{ok:!0,messages:n}};import{stat as cJ}from"node:fs/promises";import{readFileSync as KO,rmSync as GO,writeFileSync as jO,mkdirSync as VO}from"node:fs";import{join as YO}from"node:path";var rp=()=>YO(Q(),"draining"),kw=e=>{try{VO(Q(),{recursive:!0}),jO(rp(),`${Math.floor(e)}
38
- `,"utf-8")}catch{}},op=()=>{try{GO(rp(),{force:!0})}catch{}},ZO=16*6e4,ap=(e=Date.now())=>{let t;try{t=KO(rp(),"utf-8")}catch{return!1}let n=t.trim();if(!/^\d+$/.test(n))return!1;let r=Number(n);return Number.isSafeInteger(r)&&r>e&&r<=e+ZO};import{homedir as lp,platform as dp}from"node:os";import{join as Vo}from"node:path";import{mkdir as sp,readFile as JO,rename as XO,writeFile as _c,rm as Vr}from"node:fs/promises";import{spawnSync as zO}from"node:child_process";var cp=()=>Vo(ys(),"connect-refresh.log"),Pc=1800,Cs="ai.anyray.connect.refresh",Yr="anyray-refresh",Lc="\\AnyrayConnectKeyRefresh",Dc=Cs,As=Yr,ks=Lc,qO=String(Pc/60),up=(e,t)=>{let n=zO(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},pp=()=>Vo(lp(),"Library","LaunchAgents",`${Dc}.plist`),fp=()=>Vo(lp(),".config","systemd","user"),Cw=()=>Vo(fp(),`${As}.service`),Tc=()=>Vo(fp(),`${As}.timer`),ip=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Nc=()=>fn(rr),QO=(e=Nc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${ip(o)}</string>`).join(`
37
+ `},_c=()=>{let{command:e,args:t}=rp();return["Auto-start is not wired for this OS. Run the key-refresh proxy yourself:",` ${[e,...t].map(r=>/\s/.test(r)?JSON.stringify(r):r).join(" ")}`,"(keep it running in the background \u2014 your tools route through it)."]},ww=async()=>{let e=Ho();if(e!=="darwin"&&e!=="linux")return!1;let t=e==="darwin"?Go():jo();try{return await hw(t),!0}catch{return!1}},bw=async()=>{let e=Ho();if(e!=="darwin"&&e!=="linux")return!0;let t=e==="darwin"?Go():jo(),n=e==="darwin"?bs():ks();return await fw(t,"utf-8").catch(()=>null)===n},ep=async e=>{await Qu(Ko(ms(),"Library","LaunchAgents"),{recursive:!0}),await Qu(ws(),{recursive:!0,mode:448}),await mw(e,bs())},kw=async()=>{let e=Ho();return e==="darwin"?(await ep(Go()),!0):e==="linux"?(await Qu(Ko(ms(),".config","systemd","user"),{recursive:!0}),await mw(jo(),ks()),!0):!1},Cw=async()=>kw().catch(()=>!1),YR=async(e,t)=>{let n=Ho();if(n!=="darwin"&&n!=="linux")return!1;let r=n==="darwin"?Go():jo(),o=n==="darwin"?bs():ks();if(await fw(r,"utf-8").catch(()=>null)!==o)return!1;let s=await be(e);return s?.version!==we?!1:typeof s.remoteOrigin=="string"&&Xe(s.remoteOrigin)===Xe(t)},Dt=async e=>{if(je(pw()))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 anyray-connect is running from a temporary path (${pw()}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(fs())return{ok:!1,messages:Bo("key-refresh auto-start")};{let n=yt();if(Ct(n))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 ${dr(n)} has no per-user service manager to supervise the daemon.`]}}if(await YR(e.port,e.remoteOrigin))return{ok:!0,messages:["Key-refresh service already current \u2014 left running."]};let t=Ho();try{if(t==="darwin"){let n=Go(),r=String(process.getuid?.()??""),o=`${n}.new-${process.pid}`;await Wo(o,{force:!0}).catch(()=>{}),await ep(o),hn("launchctl",["bootout",`gui/${r}`,n]),await Wo(n,{force:!0}).catch(()=>{});try{await GR(o,n)}catch{await ep(n),await Wo(o,{force:!0}).catch(()=>{})}return hn("launchctl",["bootstrap",`gui/${r}`,n]).status===0||hn("launchctl",["load","-w",n]).status===0?{ok:!0,messages:[`Installed launchd agent ${n}.`]}:{ok:!1,messages:[`Wrote ${n} but launchd would not load the agent.`,..._c()]}}if(t==="linux"){let n=jo();return await kw(),hn("systemctl",["--user","daemon-reload"]),hn("systemctl",["--user","enable",`${ur}.service`]),hn("systemctl",["--user","restart",`${ur}.service`]).status!==0?{ok:!1,messages:[`Wrote ${n} but \`systemctl --user restart\` failed.`,..._c()]}:{ok:!0,messages:[`Installed systemd user unit ${n}.`]}}return{ok:!1,messages:_c()}}catch(n){return{ok:!1,messages:[`Could not install the key-refresh service: ${n instanceof Error?n.message:String(n)}`,..._c()]}}},op=async(e=ke,t={})=>{if(await be(e)===null)return!1;let n=t.drain==="idle"?"?drain=idle":"";try{let r=new AbortController,o=setTimeout(()=>r.abort(),1500);try{await fetch(`http://127.0.0.1:${e}/__anyray/shutdown${n}`,{method:"POST",headers:{[np]:"1"},signal:r.signal})}finally{clearTimeout(o)}}catch{}for(let r=0;r<10&&await be(e,300)!==null;r++)await new Promise(o=>setTimeout(o,100));return!0},Qt=async(e=ke)=>{let t=Ho();await Wo(hs(),{force:!0}).catch(()=>{});let n=[],r=fs();try{if(r)n.push(...Bo("key-refresh service teardown"));else if(t==="darwin"){let o=Go(),a=String(process.getuid?.()??"");hn("launchctl",["bootout",`gui/${a}`,o]),hn("launchctl",["unload",o]),await Wo(o,{force:!0}),n.push("Removed the launchd key-refresh agent.")}else t==="linux"&&(hn("systemctl",["--user","disable","--now",`${ur}.service`]),await Wo(jo(),{force:!0}),hn("systemctl",["--user","daemon-reload"]),n.push("Removed the systemd key-refresh unit."))}catch{}try{await op(e)&&n.push("Stopped the running key-refresh proxy daemon.")}catch{}return{ok:!0,messages:n}};import{stat as E5}from"node:fs/promises";import{readFileSync as ZR,rmSync as XR,writeFileSync as JR,mkdirSync as qR}from"node:fs";import{join as zR}from"node:path";var ap=()=>zR(Q(),"draining"),Aw=e=>{try{qR(Q(),{recursive:!0}),JR(ap(),`${Math.floor(e)}
38
+ `,"utf-8")}catch{}},sp=()=>{try{XR(ap(),{force:!0})}catch{}},QR=16*6e4,ip=(e=Date.now())=>{let t;try{t=ZR(ap(),"utf-8")}catch{return!1}let n=t.trim();if(!/^\d+$/.test(n))return!1;let r=Number(n);return Number.isSafeInteger(r)&&r>e&&r<=e+QR};import{homedir as up,platform as pp}from"node:os";import{join as Vo}from"node:path";import{mkdir as cp,readFile as e_,rename as t_,writeFile as Tc,rm as jr}from"node:fs/promises";import{spawnSync as n_}from"node:child_process";var dp=()=>Vo(ws(),"connect-refresh.log"),Dc=1800,vs="ai.anyray.connect.refresh",Vr="anyray-refresh",Nc="\\AnyrayConnectKeyRefresh",$c=vs,Ss=Vr,As=Nc,r_=String(Dc/60),fp=(e,t)=>{let n=n_(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},hp=()=>Vo(up(),"Library","LaunchAgents",`${$c}.plist`),mp=()=>Vo(up(),".config","systemd","user"),vw=()=>Vo(mp(),`${Ss}.service`),Lc=()=>Vo(mp(),`${Ss}.timer`),lp=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Mc=()=>fn(ar),o_=(e=Mc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${lp(o)}</string>`).join(`
39
39
  `);return`<?xml version="1.0" encoding="UTF-8"?>
40
40
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
41
41
  <plist version="1.0">
42
42
  <dict>
43
- <key>Label</key><string>${Dc}</string>
43
+ <key>Label</key><string>${$c}</string>
44
44
  <key>ProgramArguments</key>
45
45
  <array>
46
46
  ${r}
47
47
  </array>
48
- <key>StartInterval</key><integer>${Pc}</integer>
48
+ <key>StartInterval</key><integer>${Dc}</integer>
49
49
  <key>RunAtLoad</key><true/>
50
50
  <key>ProcessType</key><string>Background</string>
51
51
  <key>LowPriorityIO</key><true/>
52
- <key>StandardOutPath</key><string>${ip(cp())}</string>
53
- <key>StandardErrorPath</key><string>${ip(cp())}</string>
52
+ <key>StandardOutPath</key><string>${lp(dp())}</string>
53
+ <key>StandardErrorPath</key><string>${lp(dp())}</string>
54
54
  </dict>
55
55
  </plist>
56
- `},e_=(e=Nc())=>{let{command:t,args:n}=e;return`[Unit]
56
+ `},a_=(e=Mc())=>{let{command:t,args:n}=e;return`[Unit]
57
57
  Description=Anyray connect gateway key refresh
58
58
  After=network-online.target
59
59
 
60
60
  [Service]
61
61
  Type=oneshot
62
62
  ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
63
- `},t_=()=>`[Unit]
64
- Description=Anyray connect gateway key refresh (every ${Pc/60}m)
63
+ `},s_=()=>`[Unit]
64
+ Description=Anyray connect gateway key refresh (every ${Dc/60}m)
65
65
 
66
66
  [Timer]
67
67
  OnBootSec=5min
68
- OnUnitActiveSec=${Pc/60}min
68
+ OnUnitActiveSec=${Dc/60}min
69
69
  Persistent=true
70
70
 
71
71
  [Install]
72
72
  WantedBy=timers.target
73
- `,n_=(e=Nc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),bs=e=>["Auto-refresh scheduling is not wired for this OS. To keep your gateway","key from expiring mid-session, run this on a ~30-min schedule yourself","(e.g. cron / Task Scheduler), or just re-run connect when a tool 401s:",` ${[e.command,...e.args].map(n=>/\s/.test(n)?JSON.stringify(n):n).join(" ")}`],Aw=e=>!e.run&&us(),r_=async(e,t)=>await JO(pp(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Dc]).ok,dr=async(e={})=>{let t=e.os??dp(),n=e.invocation??Nc(),r=e.run??up,o=e.binaryPath??ir();if(je(o))return{ok:!1,messages:[`Skipped auto-refresh scheduling \u2014 anyray-connect is running from a temporary path (${o}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(Aw(e))return{ok:!1,messages:Bo("auto-refresh scheduling")};let a=mt(e.env??(e.run?{}:process.env));if(Ct(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${cr(a)} has no per-user service manager.`,"Claude Code re-mints its key on demand via the apiKeyHelper; other tools refresh whenever `anyray-connect` runs (add it to your postStartCommand or shell profile)."]};try{if(t==="darwin"){let s=pp(),i=QO(n);if(await r_(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await sp(ys(),{recursive:!0,mode:448}),await sp(Vo(lp(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await Vr(l,{force:!0}).catch(()=>{}),await _c(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await Vr(s,{force:!0}).catch(()=>{});try{await XO(l,s)}catch{await _c(s,i),await Vr(l,{force:!0}).catch(()=>{})}return r("launchctl",["bootstrap",`gui/${c}`,s]).ok||r("launchctl",["load","-w",s]).ok?{ok:!0,messages:[`Scheduled auto-refresh via launchd (${s}).`]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...bs(n)]}}if(t==="linux")return await sp(fp(),{recursive:!0}),await _c(Cw(),e_(n)),await _c(Tc(),t_()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${As}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${Tc()}).`]}:{ok:!1,messages:[`Wrote ${Tc()} but \`systemctl --user enable --now\` failed.`,...bs(n)]};if(t==="win32"){let s=n_(n);return r("schtasks",["/Create","/TN",ks,"/TR",s,"/SC","MINUTE","/MO",qO,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",ks]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${ks}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...bs(n)]}}return{ok:!1,messages:bs(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...bs(n)]}}},ur=async(e={})=>{await Vr(cp(),{force:!0}).catch(()=>{});let t=e.os??dp(),n=e.run??up,r=[];if(Aw(e))return{ok:!0,messages:Bo("scheduler teardown")};try{if(t==="darwin"){let o=pp(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Vr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${As}.timer`]),await Vr(Tc(),{force:!0}),await Vr(Cw(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",ks,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Yo=async(e=dp(),t=up)=>e==="win32"?t("schtasks",["/Query","/TN",ks]).ok:e==="darwin"?t("launchctl",["list",Dc]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${As}.timer`]).ok:!1;import nH from"node:http";import{spawn as pB}from"node:child_process";import{createHash as fB}from"node:crypto";import{homedir as hB}from"node:os";import{join as NS}from"node:path";import{readFile as mB,writeFile as $S,chmod as yB,stat as gB,unlink as ES}from"node:fs/promises";import{homedir as Uc,platform as Nw}from"node:os";import{join as at}from"node:path";import{execFile as p_}from"node:child_process";import{readFile as f_,readdir as h_}from"node:fs/promises";import{homedir as o_,platform as a_}from"node:os";import{join as $c}from"node:path";var ot=e=>{let t=o_();switch(a_()){case"darwin":return $c(t,"Library","Application Support",e);case"win32":return $c(process.env.APPDATA??$c(t,"AppData","Roaming"),e);default:return $c(t,".config",e)}};import{readFile as Ew}from"node:fs/promises";import{homedir as Zr,platform as Zo}from"node:os";import{join as Tn,posix as s_,win32 as i_}from"node:path";var vs=["Code","Code - Insiders","VSCodium"],hp="1.121.0",vw=1,c_=121,Iw="1.102.0",Sw=1,l_=102,d_={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Mc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},mp=e=>{let t=Mc(e);return t?t.major!==vw?t.major>vw:t.minor>=c_:!1},xw=e=>{let t=Mc(e);return t?t.major!==Sw?t.major>Sw:t.minor>=l_:!1},u_=async e=>{if(Zo()!=="darwin")return;let t=Tn("/Applications",`${d_[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await Ew(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Rw=(e,t=Zo(),n=Zr(),r=process.env)=>{switch(t){case"darwin":return Tn(n,"Library","Application Support",e);case"win32":return Tn(r.APPDATA??Tn(n,"AppData","Roaming"),e);default:return Tn(n,".config",e)}},yp=(e,t)=>e?t==="win32"?i_.join:s_.join:Tn,Jo=(e,t=!1,n=Zo(),r=Zr(),o=process.env)=>t?yp(t,n)(r,Ss[e],"data","User"):Tn(Rw(e,n,r,o),"User"),Ow=async(e,t=!1,n=Zo(),r=Zr(),o=process.env)=>{try{let a=yp(t,n)(Jo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Ew(a,"utf8"))?.userDataProfiles;if(!Array.isArray(i))return[];let c=i.map(l=>l).filter(l=>typeof l.name=="string"&&l.name.trim().length>0&&l.name.length<=128&&!/[\u0000-\u001f\u007f]/.test(l.name)&&typeof l.location=="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(l.location)&&l.location!=="."&&l.location!=="..").map(({name:l,location:d})=>({name:l,location:d}));return c.filter((l,d)=>c.findIndex(u=>u.location===l.location)===d)}catch{return[]}},_w=async(e,t=Zo(),n=Zr(),r=process.env)=>{let a=(await Ow(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},Tw=async(e,t=!1,n=Zo(),r=Zr(),o=process.env)=>{let a=yp(t,n),s=Jo(e,t,n,r,o),i=await Ow(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Fc=async()=>{for(let e of vs)if(await R(Rw(e)))return e},Ss={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Pw=(e,t=Zr())=>Tn(t,Ss[e],"extensions"),gp=async(e=Zr())=>{for(let t of vs)if(await R(Tn(e,Ss[t])))return t},Lw=async e=>{let t=e??await Fc();if(!t)return{status:"unknown"};let n=await u_(t);return n?{variant:t,version:n,status:mp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var m_=3e3,y_="Claude Code-credentials",g_=["copilot-cli","CopilotCLI"],$w=e=>new Promise(t=>{try{p_("security",["find-generic-password","-s",e],{timeout:m_},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),w_=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=at(Uc(),".claude");return!!(await R(at(e,".oauth_token"))||await R(at(e,".credentials.json"))||Nw()==="darwin"&&await $w(y_))},b_=async()=>{let e=at(process.env.CODEX_HOME?.trim()||at(Uc(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await f_(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},Dw=async e=>{try{return(await h_(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},wp=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of vs){let n=at(ot(t),"User","globalStorage");if(await R(at(n,"github.copilot-chat"))||await R(at(n,"github.copilot")))return!0}let e=at(Uc(),".config","github-copilot");if(await R(at(e,"apps.json"))||await R(at(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await Dw(at(Uc(),t,"extensions")))return!0;for(let t of vs){if(await Dw(Pw(t)))return!0;let n=at(Jo(t,!0),"globalStorage");if(await R(at(n,"github.copilot-chat"))||await R(at(n,"github.copilot")))return!0}if(Nw()==="darwin"){for(let t of g_)if(await $w(t))return!0}return!1},$t=async()=>{let[e,t,n]=await Promise.all([w_(),b_(),wp()]);return{anthropic:e,openai:t,copilot:n}};var _e=async(e=L,t=$t,n)=>{let r=await e();if(!r.gateway||!r.clientKey)return;let o=await t().catch(()=>{}),a=ge({origin:r.gateway,clientKey:r.clientKey,subscription:r.authMode==="subscription",placeholder:r.authMode==="placeholder",byoUpstream:r.byoUpstream,seat:o,user:r.name,team:r.team});if(!nt(r))return{target:a,toolOrigin:a.origin};if(!(!Number.isInteger(r.fallbackPort)||r.fallbackPort<1||r.fallbackPort>65535))return n&&await n(r.fallbackPort)===null?{target:a,toolOrigin:a.origin}:{target:In(a,r.fallbackPort),toolOrigin:`http://${ft}:${r.fallbackPort}`}};import{homedir as x_}from"node:os";import{join as Yc}from"node:path";import{chmod as R_,readFile as Es,rm as Hw,copyFile as O_}from"node:fs/promises";var Jr="# >>> anyray connect >>>",Hc="# <<< anyray connect <<<",bp="# restore: ",Mw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Kc=e=>{let t=new RegExp(`\\n*${Mw(Jr)}[\\s\\S]*?${Mw(Hc)}\\n?`,"g");return e.replace(t,"")},kp=e=>{let t="",n=!1,r="";for(let o=0;o<e.length;o++){let a=e[o];if(n){if(a==="\\"&&r==='"'){o++;continue}a===r&&(n=!1);continue}if(a==='"'||a==="'"){n=!0,r=a;continue}if(a==="#")break;t+=a}return t},Bc=(e,t)=>e.split(t).length-1,Fw=e=>Bc(e,"[")-Bc(e,"]"),k_=e=>e.replace(/^['"]|['"]$/g,""),Wc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Bc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+Fw(kp(a))),t.push({kind:"other"});continue}let s=a.trim();if(s===""||s.startsWith("#")){t.push({kind:"other"});continue}if(s.startsWith("[")){t.push({kind:"table"});continue}let i=a.indexOf("="),c=i>=0?k_(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=kp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Bc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+Fw(l)))}return t},Cp=e=>e.findIndex(t=>t.kind==="table"),Ap=e=>e.includes(Jr),Uw=(e,t)=>{let n=`[${t}]`;return e.split(`
74
- `).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},vp=(e,t)=>Uw(Kc(e),t),Sp=e=>{let t=e.indexOf(Jr);if(t<0)return;let n=e.indexOf(Hc,t+Jr.length);if(!(n<0))return e.slice(t,n)},Bw=(e,t)=>{let n=e.indexOf(Jr);if(n<0)return!1;let r=e.indexOf(Hc,n+Jr.length);return r<0?!1:Uw(e.slice(n,r),t)},Ep=(e,t)=>{let r=Kc(e).split(`
75
- `),o=Wc(r),a=Cp(o),s=a<0?r.length:a;for(let i=0;i<s;i++){let c=o[i];if(c.kind!=="key"||c.key!==t)continue;let l=r[i].indexOf("="),d=kp(r[i].slice(l+1)).trim();if(!/^\d[\d_]*$/.test(d))return;let u=Number(d.replaceAll("_",""));return Number.isSafeInteger(u)&&u>0?u:void 0}},Gc=(e,t,n)=>{let r=Ww(e),a=Kc(e).split(`
76
- `),s=Wc(a),i=Cp(s),c=new Set(n),l=i===-1?a.length:i,d=[],u=new Map(r);for(let b=0;b<a.length;b++){let A=s[b];if(b<l&&A.kind==="key"&&c.has(A.key)){u.has(A.key)||u.set(A.key,a[b].trim());continue}d.push(a[b])}let f=Wc(d),p=Cp(f),h=(p===-1?d:d.slice(0,p)).join(`
73
+ `,i_=(e=Mc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),Cs=e=>["Auto-refresh scheduling is not wired for this OS. To keep your gateway","key from expiring mid-session, run this on a ~30-min schedule yourself","(e.g. cron / Task Scheduler), or just re-run connect when a tool 401s:",` ${[e.command,...e.args].map(n=>/\s/.test(n)?JSON.stringify(n):n).join(" ")}`],Sw=e=>!e.run&&fs(),c_=async(e,t)=>await e_(hp(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",$c]).ok,pr=async(e={})=>{let t=e.os??pp(),n=e.invocation??Mc(),r=e.run??fp,o=e.binaryPath??lr();if(je(o))return{ok:!1,messages:[`Skipped auto-refresh scheduling \u2014 anyray-connect is running from a temporary path (${o}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(Sw(e))return{ok:!1,messages:Bo("auto-refresh scheduling")};let a=yt(e.env??(e.run?{}:process.env));if(Ct(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${dr(a)} has no per-user service manager.`,"Claude Code re-mints its key on demand via the apiKeyHelper; other tools refresh whenever `anyray-connect` runs (add it to your postStartCommand or shell profile)."]};try{if(t==="darwin"){let s=hp(),i=o_(n);if(await c_(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await cp(ws(),{recursive:!0,mode:448}),await cp(Vo(up(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await jr(l,{force:!0}).catch(()=>{}),await Tc(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await jr(s,{force:!0}).catch(()=>{});try{await t_(l,s)}catch{await Tc(s,i),await jr(l,{force:!0}).catch(()=>{})}return r("launchctl",["bootstrap",`gui/${c}`,s]).ok||r("launchctl",["load","-w",s]).ok?{ok:!0,messages:[`Scheduled auto-refresh via launchd (${s}).`]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...Cs(n)]}}if(t==="linux")return await cp(mp(),{recursive:!0}),await Tc(vw(),a_(n)),await Tc(Lc(),s_()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${Ss}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${Lc()}).`]}:{ok:!1,messages:[`Wrote ${Lc()} but \`systemctl --user enable --now\` failed.`,...Cs(n)]};if(t==="win32"){let s=i_(n);return r("schtasks",["/Create","/TN",As,"/TR",s,"/SC","MINUTE","/MO",r_,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",As]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${As}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...Cs(n)]}}return{ok:!1,messages:Cs(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...Cs(n)]}}},fr=async(e={})=>{await jr(dp(),{force:!0}).catch(()=>{});let t=e.os??pp(),n=e.run??fp,r=[];if(Sw(e))return{ok:!0,messages:Bo("scheduler teardown")};try{if(t==="darwin"){let o=hp(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await jr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${Ss}.timer`]),await jr(Lc(),{force:!0}),await jr(vw(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",As,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Yo=async(e=pp(),t=fp)=>e==="win32"?t("schtasks",["/Query","/TN",As]).ok:e==="darwin"?t("launchctl",["list",$c]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${Ss}.timer`]).ok:!1;import iW from"node:http";import{spawn as gB}from"node:child_process";import{createHash as wB}from"node:crypto";import{homedir as bB}from"node:os";import{join as $S}from"node:path";import{readFile as kB,writeFile as MS,chmod as CB,stat as AB,unlink as xS}from"node:fs/promises";import{homedir as Bc,platform as Mw}from"node:os";import{join as at}from"node:path";import{execFile as g_}from"node:child_process";import{readFile as w_,readdir as b_}from"node:fs/promises";import{homedir as l_,platform as d_}from"node:os";import{join as Fc}from"node:path";var Ye=e=>{let t=l_();switch(d_()){case"darwin":return Fc(t,"Library","Application Support",e);case"win32":return Fc(process.env.APPDATA??Fc(t,"AppData","Roaming"),e);default:return Fc(t,".config",e)}};import{readFile as Iw}from"node:fs/promises";import{homedir as Yr,platform as Zo}from"node:os";import{join as Ln,posix as u_,win32 as p_}from"node:path";var Es=["Code","Code - Insiders","VSCodium"],yp="1.121.0",Ew=1,f_=121,Ow="1.102.0",xw=1,h_=102,m_={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Uc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},gp=e=>{let t=Uc(e);return t?t.major!==Ew?t.major>Ew:t.minor>=f_:!1},Rw=e=>{let t=Uc(e);return t?t.major!==xw?t.major>xw:t.minor>=h_:!1},y_=async e=>{if(Zo()!=="darwin")return;let t=Ln("/Applications",`${m_[e]}.app`,"Contents","Resources","app","package.json");if(await O(t))try{let n=JSON.parse(await Iw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},_w=(e,t=Zo(),n=Yr(),r=process.env)=>{switch(t){case"darwin":return Ln(n,"Library","Application Support",e);case"win32":return Ln(r.APPDATA??Ln(n,"AppData","Roaming"),e);default:return Ln(n,".config",e)}},wp=(e,t)=>e?t==="win32"?p_.join:u_.join:Ln,Xo=(e,t=!1,n=Zo(),r=Yr(),o=process.env)=>t?wp(t,n)(r,xs[e],"data","User"):Ln(_w(e,n,r,o),"User"),Pw=async(e,t=!1,n=Zo(),r=Yr(),o=process.env)=>{try{let a=wp(t,n)(Xo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Iw(a,"utf8"))?.userDataProfiles;if(!Array.isArray(i))return[];let c=i.map(l=>l).filter(l=>typeof l.name=="string"&&l.name.trim().length>0&&l.name.length<=128&&!/[\u0000-\u001f\u007f]/.test(l.name)&&typeof l.location=="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(l.location)&&l.location!=="."&&l.location!=="..").map(({name:l,location:d})=>({name:l,location:d}));return c.filter((l,d)=>c.findIndex(u=>u.location===l.location)===d)}catch{return[]}},Tw=async(e,t=Zo(),n=Yr(),r=process.env)=>{let a=(await Pw(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},Lw=async(e,t=!1,n=Zo(),r=Yr(),o=process.env)=>{let a=wp(t,n),s=Xo(e,t,n,r,o),i=await Pw(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Jo=async()=>{for(let e of Es)if(await O(_w(e)))return e},xs={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Dw=(e,t=Yr())=>Ln(t,xs[e],"extensions"),bp=async(e=Yr())=>{for(let t of Es)if(await O(Ln(e,xs[t])))return t},Nw=async e=>{let t=e??await Jo();if(!t)return{status:"unknown"};let n=await y_(t);return n?{variant:t,version:n,status:gp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var k_=3e3,C_="Claude Code-credentials",A_=["copilot-cli","CopilotCLI"],Fw=e=>new Promise(t=>{try{g_("security",["find-generic-password","-s",e],{timeout:k_},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),v_=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=at(Bc(),".claude");return!!(await O(at(e,".oauth_token"))||await O(at(e,".credentials.json"))||Mw()==="darwin"&&await Fw(C_))},S_=async()=>{let e=at(process.env.CODEX_HOME?.trim()||at(Bc(),".codex"),"auth.json");if(!await O(e))return!1;try{let t=JSON.parse(await w_(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},$w=async e=>{try{return(await b_(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},kp=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of Es){let n=at(Ye(t),"User","globalStorage");if(await O(at(n,"github.copilot-chat"))||await O(at(n,"github.copilot")))return!0}let e=at(Bc(),".config","github-copilot");if(await O(at(e,"apps.json"))||await O(at(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await $w(at(Bc(),t,"extensions")))return!0;for(let t of Es){if(await $w(Dw(t)))return!0;let n=at(Xo(t,!0),"globalStorage");if(await O(at(n,"github.copilot-chat"))||await O(at(n,"github.copilot")))return!0}if(Mw()==="darwin"){for(let t of A_)if(await Fw(t))return!0}return!1},Nt=async()=>{let[e,t,n]=await Promise.all([v_(),S_(),kp()]);return{anthropic:e,openai:t,copilot:n}};var Re=async(e=D,t=Nt,n)=>{let r=await e();if(!r.gateway||!r.clientKey)return;let o=await t().catch(()=>{}),a=ge({origin:r.gateway,clientKey:r.clientKey,subscription:r.authMode==="subscription",placeholder:r.authMode==="placeholder",byoUpstream:r.byoUpstream,seat:o,user:r.name,team:r.team});if(!rt(r))return{target:a,toolOrigin:a.origin};if(!(!Number.isInteger(r.fallbackPort)||r.fallbackPort<1||r.fallbackPort>65535))return n&&await n(r.fallbackPort)===null?{target:a,toolOrigin:a.origin}:{target:On(a,r.fallbackPort),toolOrigin:`http://${ht}:${r.fallbackPort}`}};import{homedir as T_}from"node:os";import{join as Zc}from"node:path";import{chmod as L_,readFile as Is,rm as Gw,copyFile as D_}from"node:fs/promises";var Zr="# >>> anyray connect >>>",Kc="# <<< anyray connect <<<",Cp="# restore: ",Uw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Gc=e=>{let t=new RegExp(`\\n*${Uw(Zr)}[\\s\\S]*?${Uw(Kc)}\\n?`,"g");return e.replace(t,"")},Ap=e=>{let t="",n=!1,r="";for(let o=0;o<e.length;o++){let a=e[o];if(n){if(a==="\\"&&r==='"'){o++;continue}a===r&&(n=!1);continue}if(a==='"'||a==="'"){n=!0,r=a;continue}if(a==="#")break;t+=a}return t},Wc=(e,t)=>e.split(t).length-1,Bw=e=>Wc(e,"[")-Wc(e,"]"),E_=e=>e.replace(/^['"]|['"]$/g,""),Hc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Wc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+Bw(Ap(a))),t.push({kind:"other"});continue}let s=a.trim();if(s===""||s.startsWith("#")){t.push({kind:"other"});continue}if(s.startsWith("[")){t.push({kind:"table"});continue}let i=a.indexOf("="),c=i>=0?E_(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=Ap(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Wc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+Bw(l)))}return t},vp=e=>e.findIndex(t=>t.kind==="table"),Sp=e=>e.includes(Zr),Ww=(e,t)=>{let n=`[${t}]`;return e.split(`
74
+ `).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},Ep=(e,t)=>Ww(Gc(e),t),xp=e=>{let t=e.indexOf(Zr);if(t<0)return;let n=e.indexOf(Kc,t+Zr.length);if(!(n<0))return e.slice(t,n)},Hw=(e,t)=>{let n=e.indexOf(Zr);if(n<0)return!1;let r=e.indexOf(Kc,n+Zr.length);return r<0?!1:Ww(e.slice(n,r),t)},Ip=(e,t)=>{let r=Gc(e).split(`
75
+ `),o=Hc(r),a=vp(o),s=a<0?r.length:a;for(let i=0;i<s;i++){let c=o[i];if(c.kind!=="key"||c.key!==t)continue;let l=r[i].indexOf("="),d=Ap(r[i].slice(l+1)).trim();if(!/^\d[\d_]*$/.test(d))return;let u=Number(d.replaceAll("_",""));return Number.isSafeInteger(u)&&u>0?u:void 0}},jc=(e,t,n)=>{let r=Kw(e),a=Gc(e).split(`
76
+ `),s=Hc(a),i=vp(s),c=new Set(n),l=i===-1?a.length:i,d=[],u=new Map(r);for(let b=0;b<a.length;b++){let A=s[b];if(b<l&&A.kind==="key"&&c.has(A.key)){u.has(A.key)||u.set(A.key,a[b].trim());continue}d.push(a[b])}let f=Hc(d),p=vp(f),h=(p===-1?d:d.slice(0,p)).join(`
77
77
  `),m=p===-1?"":d.slice(p).join(`
78
- `),w=[...u.entries()].sort(([b],[A])=>b.localeCompare(A)).map(([,b])=>`${bp}${b}`),g=[Jr,...w,...t,Hc].join(`
78
+ `),w=[...u.entries()].sort(([b],[A])=>b.localeCompare(A)).map(([,b])=>`${Cp}${b}`),g=[Zr,...w,...t,Kc].join(`
79
79
  `);return[h.replace(/\s*$/,""),g,m.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
80
80
 
81
81
  `).replace(/\s*$/,"")+`
82
- `},Ww=e=>{let t=new Map,n=Sp(e);if(n===void 0)return t;for(let r of n.split(`
83
- `)){let o=r.trim();if(!o.startsWith(bp))continue;let a=o.slice(bp.length).trim(),[s]=Wc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},jc=e=>{if(!Ap(e))return null;let t=[...Ww(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Kc(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
82
+ `},Kw=e=>{let t=new Map,n=xp(e);if(n===void 0)return t;for(let r of n.split(`
83
+ `)){let o=r.trim();if(!o.startsWith(Cp))continue;let a=o.slice(Cp.length).trim(),[s]=Hc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Vc=e=>{if(!Sp(e))return null;let t=[...Kw(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Gc(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
84
84
  `),n].filter(a=>a.length>0).join(`
85
85
 
86
86
  `);return o.length>0?o+`
87
- `:""};import{randomUUID as C_}from"node:crypto";import{chmod as A_,mkdir as v_,rm as S_,writeFile as E_}from"node:fs/promises";import{dirname as I_}from"node:path";var pe=async(e,t)=>{await v_(I_(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${C_()}`;try{await E_(n,t,{flag:"wx",mode:384}),await he(n,e),await A_(e,384)}finally{await S_(n,{force:!0}).catch(()=>{})}};var __="codex",T_="Codex app / CLI / IDE",P_="https://chatgpt.com/backend-api/codex",L_="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",D_="x-anyray-client-context-window",N_="x-anyray-client-auto-compact-limit",Zc=()=>process.env.CODEX_HOME?.trim()||Yc(x_(),".codex"),Xr=()=>Yc(Zc(),"config.toml"),Vc=()=>`${Xr()}.anyray-bak`,Ip=()=>Yc(Zc(),"hooks.json"),Pn=()=>Yc(Zc(),"anyray.config.toml"),Kw=e=>Uo(e,"PostToolUse",Mg),Gw=(e,t=!1)=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||__,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||T_}),st=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,xp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,Is=(e,t={})=>{let n=Gw(e,t.ignoreEnv),r=X(e,"openai"),o=t.auth==="command"&&!r,a=r?"openai":t.ignoreEnv?void 0:process.env.ANYRAY_CODEX_PROVIDER?.trim(),s=t.ignoreEnv?void 0:xp(),i=e.clientKey&&!e.viaLocalProxy,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${st(P_)}`,`"x-anyray-forward-headers" = ${st(L_)}`,...i?[`"x-anyray-api-key" = ${st(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${st(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${st(n)}`),a&&c.push(`"x-anyray-provider" = ${st(a)}`),t.modelContextWindow&&c.push(`"${D_}" = ${st(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${N_}" = ${st(String(t.modelAutoCompactTokenLimit))}`),["# Anyray always-on routing \u2014 plain `codex` routes through the gateway.","# Managed by anyray-connect (this block is owned by the tool).",'model_provider = "anyray"',...s?[`model = ${st(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${st(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${st(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>st(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${st(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(st).join(", ")}]`]:[]]},$_=()=>xp()?["model_provider","model"]:["model_provider"],jw={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=Zc(),t=await R(e);return{installed:t,detail:t?Xr():`no ${e} directory`}},async apply(e,t){let n=Xr(),r=Ip(),o=Gw(e),a=X(e,"openai"),s=xp(),i=le(),c={},l=await R(r);try{l&&(c=await U(r))}catch(A){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${A instanceof Error?A.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run Connect so the retired Anyray PostToolUse entry can be removed safely.`]}}let d=Kw(c),u=await R(n),f=u?await Es(n,"utf-8"):"";if(vp(f,"model_providers.anyray"))return{status:"manual",messages:[`Refused to replace the existing model provider in ${n}: model_providers.anyray is not owned by Anyray Connect. Rename that provider or route it manually; the file was left unchanged.`]};let p=vp(f,"mcp_servers.anyray"),h=Ep(f,"model_context_window"),m=Ep(f,"model_auto_compact_token_limit"),w=[`${n} \u2190 always-on default route (model_provider = anyray)`,`Base URL: ${e.openaiBaseUrl}/responses (wire_api = responses)`,"Plain `codex` now routes through the gateway \u2014 no --profile needed.","Codex app, CLI, and IDE extension share this config.toml route.",a?"Subscription mode: Codex keeps your ChatGPT sign-in; its OAuth token passes through the gateway to the ChatGPT backend (never stored). Requires being signed in with ChatGPT, not an API key.":`Auth: ${e.clientKey?"personal gateway key (written to the config, not shown here)":"placeholder token (gateway swaps in the server-held key)"}`,s?`Model: ${s} (pinned via ANYRAY_CODEX_MODEL)`:"Model: inherits your existing default. If the desktop or IDE model picker ignores custom providers, re-run with ANYRAY_CODEX_MODEL pinned.",m?`Context budget: follows model_auto_compact_token_limit=${m}.`:h?`Context budget: follows model_context_window=${h}.`:"Context budget: follows the request model; unknown models use the safe fallback.",`Attribution: ${o??"(none \u2014 pass --user)"}`,"Codex cloud/web tasks run on OpenAI infrastructure and cannot route through a local gateway."];if(t.dryRun)return w.push(d?`Would remove the retired Anyray Codex PostToolUse hook from ${r}.`:"Codex source-side tool-output trimming remains unavailable: its only replacement signal rejects the already-completed tool promise and is unsafe for side-effecting tools."),{status:"configured",messages:w};let g=[];d?(await J(r,c,{backup:!1}),await ae(r),g.push(r),w.push(`Removed the retired Anyray Codex PostToolUse hook from ${r}; Codex does not expose a safe pre-transcript replacement seam for side-effecting tools.`)):w.push("Codex source-side tool-output trimming is not installed because its blocking PostToolUse result can turn a completed side effect into an apparent failure."),u&&!await R(Vc())&&(await O_(n,Vc()),await R_(Vc(),384),w.push(`Backed up your original config to ${Vc()}.`));let y=i&&!p?Ve("profile"):void 0;w.push(p?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:y?"Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.":`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable retrieval.`);let b=Gc(f,Is(e,{mcpServer:y,modelContextWindow:h,modelAutoCompactTokenLimit:m}),$_());return await pe(n,b),g.push(n),await R(Pn())&&(await Hw(Pn(),{force:!0}),g.push(Pn()),w.push(`Removed the old opt-in profile ${Pn()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:g}},async pointsAt(e){let t=Xr();if(!await R(t))return!1;try{let n=await Es(t,"utf-8"),r=`base_url = ${st(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){let e=Xr();if(!await R(e))return{registered:!1,command:null};try{let t=await Es(e,"utf-8");if(!Bw(t,"mcp_servers.anyray"))return{registered:!1,command:null};let n=t.match(/\[mcp_servers\.anyray\]\r?\ncommand = ("(?:[^"\\]|\\.)*")/),r=null;if(n)try{r=JSON.parse(n[1])}catch{r=null}return{registered:!0,command:r}}catch{return{registered:!1,command:null}}},async inferenceAuthLanes(){try{let e=await Es(Xr(),"utf-8"),t=Sp(e);if(!t||!t.includes("[model_providers.anyray]"))return["unknown"];if(/^requires_openai_auth = true$/m.test(t)||t.includes('"x-anyray-auth-mode" = "passthrough"'))return["subscription"];if(t.includes('"Authorization" = "Bearer ')||t.includes("[model_providers.anyray.auth]"))return["api_key"]}catch{}return["unknown"]},async revert(e){let t=Xr(),n=await R(t),r=await R(Pn()),o=await R(Ip());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=Ip(),c;try{c=await U(i)}catch(l){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${i} (${l instanceof Error?l.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run --revert.`]}}Kw(c)&&(e.dryRun||(await J(i,c,{backup:!1}),await ae(i)),s.push(i),a.push(e.dryRun?`would remove the retired Anyray Codex PostToolUse hook from ${i}`:`removed the retired Anyray Codex PostToolUse hook from ${i}`))}if(n){let i=jc(await Es(t,"utf-8"));i!==null&&(e.dryRun||await pe(t,i),s.push(t),a.push(e.dryRun?`would remove the Anyray default route from ${t}`:`removed the Anyray default route from ${t}`))}return r&&(e.dryRun||await Hw(Pn(),{force:!0}),s.push(Pn()),a.push(e.dryRun?`would remove the old opt-in profile ${Pn()}`:`removed the old opt-in profile ${Pn()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await ae(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as H_}from"node:os";import{join as K_}from"node:path";import{readFile as Jw,rm as Op}from"node:fs/promises";import{readFile as M_,writeFile as Vw,access as F_}from"node:fs/promises";import{homedir as U_}from"node:os";import{join as Rp}from"node:path";var B_="# >>> anyray connect >>>",W_="# <<< anyray connect <<<",xs=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:B_,end:W_},At=()=>{let e=U_(),t=process.env.SHELL||"";return t.includes("zsh")?Rp(e,".zshrc"):t.includes("bash")?Rp(e,".bashrc"):Rp(e,".profile")},Jc=async e=>{try{return await F_(e),await M_(e,"utf-8")}catch{return""}},Yw=(e,t)=>{let{begin:n,end:r}=xs(t),o=e.indexOf(n);if(o===-1)return e;let a=e.indexOf(r,o+n.length);if(a===-1)return e;let s=o;for(;s>0&&e[s-1]===`
87
+ `:""};import{randomUUID as x_}from"node:crypto";import{chmod as I_,mkdir as O_,rm as R_,writeFile as __}from"node:fs/promises";import{dirname as P_}from"node:path";var pe=async(e,t)=>{await O_(P_(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${x_()}`;try{await __(n,t,{flag:"wx",mode:384}),await he(n,e),await I_(e,384)}finally{await R_(n,{force:!0}).catch(()=>{})}};var N_="codex",$_="Codex app / CLI / IDE",M_="https://chatgpt.com/backend-api/codex",F_="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",U_="x-anyray-client-context-window",B_="x-anyray-client-auto-compact-limit",Xc=()=>process.env.CODEX_HOME?.trim()||Zc(T_(),".codex"),Xr=()=>Zc(Xc(),"config.toml"),Yc=()=>`${Xr()}.anyray-bak`,Op=()=>Zc(Xc(),"hooks.json"),Dn=()=>Zc(Xc(),"anyray.config.toml"),jw=e=>Uo(e,"PostToolUse",Ug),Vw=(e,t=!1)=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||N_,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||$_}),st=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Rp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,Os=(e,t={})=>{let n=Vw(e,t.ignoreEnv),r=J(e,"openai"),o=t.auth==="command"&&!r,a=r?"openai":t.ignoreEnv?void 0:process.env.ANYRAY_CODEX_PROVIDER?.trim(),s=t.ignoreEnv?void 0:Rp(),i=e.clientKey&&!e.viaLocalProxy,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${st(M_)}`,`"x-anyray-forward-headers" = ${st(F_)}`,...i?[`"x-anyray-api-key" = ${st(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${st(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${st(n)}`),a&&c.push(`"x-anyray-provider" = ${st(a)}`),t.modelContextWindow&&c.push(`"${U_}" = ${st(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${B_}" = ${st(String(t.modelAutoCompactTokenLimit))}`),["# Anyray always-on routing \u2014 plain `codex` routes through the gateway.","# Managed by anyray-connect (this block is owned by the tool).",'model_provider = "anyray"',...s?[`model = ${st(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${st(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${st(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>st(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${st(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(st).join(", ")}]`]:[]]},W_=()=>Rp()?["model_provider","model"]:["model_provider"],Yw={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=Xc(),t=await O(e);return{installed:t,detail:t?Xr():`no ${e} directory`}},async apply(e,t){let n=Xr(),r=Op(),o=Vw(e),a=J(e,"openai"),s=Rp(),i=le(),c={},l=await O(r);try{l&&(c=await U(r))}catch(A){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${A instanceof Error?A.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run Connect so the retired Anyray PostToolUse entry can be removed safely.`]}}let d=jw(c),u=await O(n),f=u?await Is(n,"utf-8"):"";if(Ep(f,"model_providers.anyray"))return{status:"manual",messages:[`Refused to replace the existing model provider in ${n}: model_providers.anyray is not owned by Anyray Connect. Rename that provider or route it manually; the file was left unchanged.`]};let p=Ep(f,"mcp_servers.anyray"),h=Ip(f,"model_context_window"),m=Ip(f,"model_auto_compact_token_limit"),w=[`${n} \u2190 always-on default route (model_provider = anyray)`,`Base URL: ${e.openaiBaseUrl}/responses (wire_api = responses)`,"Plain `codex` now routes through the gateway \u2014 no --profile needed.","Codex app, CLI, and IDE extension share this config.toml route.",a?"Subscription mode: Codex keeps your ChatGPT sign-in; its OAuth token passes through the gateway to the ChatGPT backend (never stored). Requires being signed in with ChatGPT, not an API key.":`Auth: ${e.clientKey?"personal gateway key (written to the config, not shown here)":"placeholder token (gateway swaps in the server-held key)"}`,s?`Model: ${s} (pinned via ANYRAY_CODEX_MODEL)`:"Model: inherits your existing default. If the desktop or IDE model picker ignores custom providers, re-run with ANYRAY_CODEX_MODEL pinned.",m?`Context budget: follows model_auto_compact_token_limit=${m}.`:h?`Context budget: follows model_context_window=${h}.`:"Context budget: follows the request model; unknown models use the safe fallback.",`Attribution: ${o??"(none \u2014 pass --user)"}`,"Codex cloud/web tasks run on OpenAI infrastructure and cannot route through a local gateway."];if(t.dryRun)return w.push(d?`Would remove the retired Anyray Codex PostToolUse hook from ${r}.`:"Codex source-side tool-output trimming remains unavailable: its only replacement signal rejects the already-completed tool promise and is unsafe for side-effecting tools."),{status:"configured",messages:w};let g=[];d?(await X(r,c,{backup:!1}),await se(r),g.push(r),w.push(`Removed the retired Anyray Codex PostToolUse hook from ${r}; Codex does not expose a safe pre-transcript replacement seam for side-effecting tools.`)):w.push("Codex source-side tool-output trimming is not installed because its blocking PostToolUse result can turn a completed side effect into an apparent failure."),u&&!await O(Yc())&&(await D_(n,Yc()),await L_(Yc(),384),w.push(`Backed up your original config to ${Yc()}.`));let y=i&&!p?Ve("profile"):void 0;w.push(p?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:y?"Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.":`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable retrieval.`);let b=jc(f,Os(e,{mcpServer:y,modelContextWindow:h,modelAutoCompactTokenLimit:m}),W_());return await pe(n,b),g.push(n),await O(Dn())&&(await Gw(Dn(),{force:!0}),g.push(Dn()),w.push(`Removed the old opt-in profile ${Dn()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:g}},async pointsAt(e){let t=Xr();if(!await O(t))return!1;try{let n=await Is(t,"utf-8"),r=`base_url = ${st(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){let e=Xr();if(!await O(e))return{registered:!1,command:null};try{let t=await Is(e,"utf-8");if(!Hw(t,"mcp_servers.anyray"))return{registered:!1,command:null};let n=t.match(/\[mcp_servers\.anyray\]\r?\ncommand = ("(?:[^"\\]|\\.)*")/),r=null;if(n)try{r=JSON.parse(n[1])}catch{r=null}return{registered:!0,command:r}}catch{return{registered:!1,command:null}}},async inferenceAuthLanes(){try{let e=await Is(Xr(),"utf-8"),t=xp(e);if(!t||!t.includes("[model_providers.anyray]"))return["unknown"];if(/^requires_openai_auth = true$/m.test(t)||t.includes('"x-anyray-auth-mode" = "passthrough"'))return["subscription"];if(t.includes('"Authorization" = "Bearer ')||t.includes("[model_providers.anyray.auth]"))return["api_key"]}catch{}return["unknown"]},async revert(e){let t=Xr(),n=await O(t),r=await O(Dn()),o=await O(Op());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=Op(),c;try{c=await U(i)}catch(l){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${i} (${l instanceof Error?l.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run --revert.`]}}jw(c)&&(e.dryRun||(await X(i,c,{backup:!1}),await se(i)),s.push(i),a.push(e.dryRun?`would remove the retired Anyray Codex PostToolUse hook from ${i}`:`removed the retired Anyray Codex PostToolUse hook from ${i}`))}if(n){let i=Vc(await Is(t,"utf-8"));i!==null&&(e.dryRun||await pe(t,i),s.push(t),a.push(e.dryRun?`would remove the Anyray default route from ${t}`:`removed the Anyray default route from ${t}`))}return r&&(e.dryRun||await Gw(Dn(),{force:!0}),s.push(Dn()),a.push(e.dryRun?`would remove the old opt-in profile ${Dn()}`:`removed the old opt-in profile ${Dn()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await se(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as Y_}from"node:os";import{join as Z_}from"node:path";import{readFile as qw,rm as Pp}from"node:fs/promises";import{readFile as H_,writeFile as Zw,access as K_}from"node:fs/promises";import{homedir as G_}from"node:os";import{join as _p}from"node:path";var j_="# >>> anyray connect >>>",V_="# <<< anyray connect <<<",Rs=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:j_,end:V_},At=()=>{let e=G_(),t=process.env.SHELL||"";return t.includes("zsh")?_p(e,".zshrc"):t.includes("bash")?_p(e,".bashrc"):_p(e,".profile")},Jc=async e=>{try{return await K_(e),await H_(e,"utf-8")}catch{return""}},Xw=(e,t)=>{let{begin:n,end:r}=Rs(t),o=e.indexOf(n);if(o===-1)return e;let a=e.indexOf(r,o+n.length);if(a===-1)return e;let s=o;for(;s>0&&e[s-1]===`
88
88
  `;)s-=1;let i=a+r.length;return e[i]===`
89
- `&&(i+=1),e.slice(0,s)+e.slice(i)},Xc=async(e,t,n)=>{let r=await Jc(e),{begin:o,end:a}=xs(n),s=Yw(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
89
+ `&&(i+=1),e.slice(0,s)+e.slice(i)},qc=async(e,t,n)=>{let r=await Jc(e),{begin:o,end:a}=Rs(n),s=Xw(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
90
90
  `),c=s?`${s}
91
91
 
92
92
  ${i}
93
93
  `:`${i}
94
- `;return await Vw(e,c),e},zc=async(e,t)=>{let n=await Jc(e),{begin:r,end:o}=xs(t),a=n.indexOf(r);if(a===-1)return;let s=a+r.length,i=n.indexOf(o,s);if(i!==-1)return n.slice(s,i).split(`
95
- `).filter(c=>c.trim().length>0)},Zw=async(e,t)=>(await Jc(e)).includes(xs(t).begin),Rs=async(e,t)=>{let n=await Jc(e);return n.includes(xs(t).begin)?(await Vw(e,Yw(n,t).replace(/\s*$/,"")+`
96
- `),!0):!1};var Mt=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var ve=e=>`'${e.replace(/'/g,"'\\''")}'`,G_=e=>{let t=ve(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},Xw=(e,t,n,r)=>{let a=e.viaLocalProxy===!0?e.placeholderKey:t;return[`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${ve(a)}`],`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${ve(a)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]]},j_=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],V_=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],_p=()=>K_(H_(),".anyray","shell-env.sh"),qw="# Managed by anyray-connect. Do not source this file anywhere else.",zw=e=>e.split(/\r?\n/,1)[0]===qw,Tp=e=>V_.some(t=>e.startsWith(`export ${t}=`)),Qw=(e,t=process.env)=>Pp([e],t),Pp=(e,t=process.env)=>e.some(r=>t.ANTHROPIC_BASE_URL===r.anthropicBaseUrl||t.OPENAI_BASE_URL===r.openaiBaseUrl)?j_.filter(r=>(t[r]??"")!==""):[],eb={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=At();return{installed:!0,detail:await R(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await zc(At());return e?e.some(n=>Tp(n)||n.includes(_p()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=At(),r=X(e,"openai"),o=X(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=Xw(e,s,r,o),c=i.filter(Tp),l=i.filter(b=>!Tp(b)),d=_p(),u=Ng(),f=[G_(u),...l,...c.length>0?[`[ -r ${ve(d)} ] && . ${ve(d)}`]:[]],p=e.clientKey?Xw(e,Mt(e.clientKey),r,o):i,h=r&&o?"either family":r?"OpenAI":"Anthropic",m=[`${n} \u2190 managed Anyray block`,` ${u} added to PATH (so \`anyray-connect\` runs from a new shell)`,...p.map(b=>` ${b}`),...c.length>0?[`${d} \u2190 owner-only credentials (mode 0600)`]:[],`Run \`source ${n}\` or open a new terminal to apply.`,...a?[`No auth token exported for ${h} \u2014 your seat-based tool keeps`,"its own sign-in (a placeholder here would override it). Raw SDK/script","calls on a seat need your own key."]:["Note: standard SDK env vars carry no per-user header, so attribution","for these falls back to the gateway default."]],w=await R(d),g=w?await Jw(d,"utf8"):void 0,y=g===void 0||zw(g);if(c.length>0&&!y)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(y||m.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:m};try{c.length>0?await pe(d,[qw,...c,""].join(`
97
- `)):w&&y&&await Op(d,{force:!0}),await Xc(n,f)}catch(b){try{g!==void 0&&y?await pe(d,g):y&&await Op(d,{force:!0})}catch{throw new Error("shell environment update failed and credential rollback could not be completed")}throw b}return{status:"configured",messages:m,changedFiles:[n,...c.length>0||w&&y?[d]:[]]}},async revert(e){let t=At(),n=_p(),r=await R(n),o=r?zw(await Jw(n,"utf8")):!1;if(e.dryRun)return{status:"reverted",messages:[`would remove the Anyray block from ${t}`,...o?[`would remove owner-only credentials from ${n}`]:r?[`would preserve user-managed ${n}`]:[]]};let a=await Rs(t);o&&await Op(n,{force:!0});let s=[...a?[t]:[],...o?[n]:[]];return{status:s.length>0?"reverted":"not-found",messages:[a?`removed the Anyray block from ${t}`:`no Anyray block found in ${t}`,...o?[`removed owner-only credentials from ${n}`]:r?[`preserved user-managed ${n}`]:[]],changedFiles:s.length>0?s:void 0}}};import{spawnSync as xT}from"node:child_process";import{closeSync as RT,copyFileSync as OT,existsSync as Se,mkdirSync as _T,openSync as TT,readFileSync as Pb,readSync as PT,renameSync as LT,rmSync as mn,writeFileSync as Yp}from"node:fs";import{homedir as Lb,platform as DT}from"node:os";import{dirname as Db,join as Qo,resolve as NT}from"node:path";import{isIP as Bp}from"node:net";import{execFileSync as el}from"node:child_process";import{mkdtempSync as Y_,rmSync as Z_,writeFileSync as J_}from"node:fs";import{createRequire as X_}from"node:module";import{tmpdir as z_}from"node:os";import{join as tb}from"node:path";var Os=class extends Error{},_s=e=>e instanceof Os?`: ${e.message}`:"",nb=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new Os("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new Os(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},rb=()=>{try{return el("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Dp=64*1024*1024,q_=Dp*2+64,Qc=e=>`'${e.replace(/'/g,"''")}'`,Q_=(e,t)=>el("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:q_,stdio:["ignore","pipe","pipe"]}),eT=(e,t)=>el("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Dp,stdio:["pipe","pipe","pipe"]}),ob=(e,t,n=Q_)=>{let r=Qc(t),o=`SELECT 'present:' || COALESCE(hex(CAST(value AS BLOB)), '') FROM ItemTable WHERE key=${r} UNION ALL SELECT 'absent:' WHERE NOT EXISTS (SELECT 1 FROM ItemTable WHERE key=${r});`,a=n(e,o),s=a.endsWith(`\r
94
+ `;return await Zw(e,c),e},zc=async(e,t)=>{let n=await Jc(e),{begin:r,end:o}=Rs(t),a=n.indexOf(r);if(a===-1)return;let s=a+r.length,i=n.indexOf(o,s);if(i!==-1)return n.slice(s,i).split(`
95
+ `).filter(c=>c.trim().length>0)},Jw=async(e,t)=>(await Jc(e)).includes(Rs(t).begin),_s=async(e,t)=>{let n=await Jc(e);return n.includes(Rs(t).begin)?(await Zw(e,Xw(n,t).replace(/\s*$/,"")+`
96
+ `),!0):!1};var $t=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var ve=e=>`'${e.replace(/'/g,"'\\''")}'`,X_=e=>{let t=ve(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},zw=(e,t,n,r)=>{let a=e.viaLocalProxy===!0?e.placeholderKey:t;return[`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${ve(a)}`],`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${ve(a)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]]},J_=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],q_=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],Tp=()=>Z_(Y_(),".anyray","shell-env.sh"),eb="# Managed by anyray-connect. Do not source this file anywhere else.",Qw=e=>e.split(/\r?\n/,1)[0]===eb,Lp=e=>q_.some(t=>e.startsWith(`export ${t}=`)),tb=(e,t=process.env)=>Dp([e],t),Dp=(e,t=process.env)=>e.some(r=>t.ANTHROPIC_BASE_URL===r.anthropicBaseUrl||t.OPENAI_BASE_URL===r.openaiBaseUrl)?J_.filter(r=>(t[r]??"")!==""):[],nb={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=At();return{installed:!0,detail:await O(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await zc(At());return e?e.some(n=>Lp(n)||n.includes(Tp()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=At(),r=J(e,"openai"),o=J(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=zw(e,s,r,o),c=i.filter(Lp),l=i.filter(b=>!Lp(b)),d=Tp(),u=Mg(),f=[X_(u),...l,...c.length>0?[`[ -r ${ve(d)} ] && . ${ve(d)}`]:[]],p=e.clientKey?zw(e,$t(e.clientKey),r,o):i,h=r&&o?"either family":r?"OpenAI":"Anthropic",m=[`${n} \u2190 managed Anyray block`,` ${u} added to PATH (so \`anyray-connect\` runs from a new shell)`,...p.map(b=>` ${b}`),...c.length>0?[`${d} \u2190 owner-only credentials (mode 0600)`]:[],`Run \`source ${n}\` or open a new terminal to apply.`,...a?[`No auth token exported for ${h} \u2014 your seat-based tool keeps`,"its own sign-in (a placeholder here would override it). Raw SDK/script","calls on a seat need your own key."]:["Note: standard SDK env vars carry no per-user header, so attribution","for these falls back to the gateway default."]],w=await O(d),g=w?await qw(d,"utf8"):void 0,y=g===void 0||Qw(g);if(c.length>0&&!y)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(y||m.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:m};try{c.length>0?await pe(d,[eb,...c,""].join(`
97
+ `)):w&&y&&await Pp(d,{force:!0}),await qc(n,f)}catch(b){try{g!==void 0&&y?await pe(d,g):y&&await Pp(d,{force:!0})}catch{throw new Error("shell environment update failed and credential rollback could not be completed")}throw b}return{status:"configured",messages:m,changedFiles:[n,...c.length>0||w&&y?[d]:[]]}},async revert(e){let t=At(),n=Tp(),r=await O(n),o=r?Qw(await qw(n,"utf8")):!1;if(e.dryRun)return{status:"reverted",messages:[`would remove the Anyray block from ${t}`,...o?[`would remove owner-only credentials from ${n}`]:r?[`would preserve user-managed ${n}`]:[]]};let a=await _s(t);o&&await Pp(n,{force:!0});let s=[...a?[t]:[],...o?[n]:[]];return{status:s.length>0?"reverted":"not-found",messages:[a?`removed the Anyray block from ${t}`:`no Anyray block found in ${t}`,...o?[`removed owner-only credentials from ${n}`]:r?[`preserved user-managed ${n}`]:[]],changedFiles:s.length>0?s:void 0}}};import{spawnSync as TP}from"node:child_process";import{closeSync as LP,copyFileSync as DP,existsSync as Se,mkdirSync as NP,openSync as $P,readFileSync as Db,readSync as MP,renameSync as FP,rmSync as mn,writeFileSync as Xp}from"node:fs";import{homedir as Nb,platform as UP}from"node:os";import{dirname as $b,join as ea,resolve as BP}from"node:path";import{isIP as Hp}from"node:net";import{execFileSync as tl}from"node:child_process";import{mkdtempSync as z_,rmSync as Q_,writeFileSync as eP}from"node:fs";import{createRequire as tP}from"node:module";import{tmpdir as nP}from"node:os";import{join as rb}from"node:path";var Ps=class extends Error{},Ts=e=>e instanceof Ps?`: ${e.message}`:"",ob=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new Ps("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new Ps(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},ab=()=>{try{return tl("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},$p=64*1024*1024,rP=$p*2+64,el=e=>`'${e.replace(/'/g,"''")}'`,oP=(e,t)=>tl("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:rP,stdio:["ignore","pipe","pipe"]}),aP=(e,t)=>tl("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:$p,stdio:["pipe","pipe","pipe"]}),sb=(e,t,n=oP)=>{let r=el(t),o=`SELECT 'present:' || COALESCE(hex(CAST(value AS BLOB)), '') FROM ItemTable WHERE key=${r} UNION ALL SELECT 'absent:' WHERE NOT EXISTS (SELECT 1 FROM ItemTable WHERE key=${r});`,a=n(e,o),s=a.endsWith(`\r
98
98
  `)?a.slice(0,-2):a.endsWith(`
99
- `)?a.slice(0,-1):a;if(s==="absent:")return;if(!s.startsWith("present:"))throw new Error("state DB returned an unexpected item encoding");let i=s.slice(8);if(i.length%2!==0||!/^[0-9a-f]*$/i.test(i))throw new Error("state DB returned an unexpected item encoding");return Buffer.from(i,"hex").toString("utf-8")},ab=(e,t=eT)=>{let r=t(e,`.bail on
99
+ `)?a.slice(0,-1):a;if(s==="absent:")return;if(!s.startsWith("present:"))throw new Error("state DB returned an unexpected item encoding");let i=s.slice(8);if(i.length%2!==0||!/^[0-9a-f]*$/i.test(i))throw new Error("state DB returned an unexpected item encoding");return Buffer.from(i,"hex").toString("utf-8")},ib=(e,t=aP)=>{let r=t(e,`.bail on
100
100
  .timeout 5000
101
101
  PRAGMA wal_checkpoint(TRUNCATE);
102
- `).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");nb(o?.slice(1).map(Number))},tT=(e,t)=>{let n=Y_(tb(z_(),"anyray-cursor-"));try{let o=[".bail on",".timeout 5000","BEGIN IMMEDIATE;",...t.map((a,s)=>{if(a.value===void 0)return`DELETE FROM ItemTable WHERE key=${Qc(a.key)};`;let i=tb(n,`value-${s}`);return J_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${Qc(a.key)}, CAST(readfile(${Qc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
103
- `);el("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Dp,stdio:["pipe","ignore","pipe"]})}finally{try{Z_(n,{recursive:!0,force:!0})}catch{}}},nT={kind:"sqlite3-cli",readItem:(e,t)=>ob(e,t),checkpointWal:e=>ab(e),mutateRows:tT},rT=()=>{try{let t=X_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Lp=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},oT=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),aT=e=>({kind:"node-sqlite",readItem:(t,n)=>Lp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:oT(o.value)}),checkpointWal:t=>Lp(e,t,n=>{let r=n.prepare("PRAGMA wal_checkpoint(TRUNCATE);").get(),o=[r?.busy,r?.log,r?.checkpointed].map(a=>typeof a=="bigint"?Number(a):a);nb(o)}),mutateRows:(t,n)=>Lp(e,t,r=>{r.exec("BEGIN IMMEDIATE;");try{for(let o of n)o.value===void 0?r.prepare("DELETE FROM ItemTable WHERE key = ?").run(o.key):r.prepare("INSERT INTO ItemTable(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(o.key,o.value);r.exec("COMMIT;")}catch(o){try{r.exec("ROLLBACK;")}catch{}throw o}})}),qc,Ts=()=>{if(qc!==void 0)return qc;let e=rT();return qc=e?aT(e):rb()?nT:null,qc};import{spawn as sT}from"node:child_process";import{randomUUID as sb}from"node:crypto";import{constants as ib}from"node:fs";import{chmod as iT,copyFile as cb,mkdir as cT,readdir as lT,readFile as dT,rename as uT,rm as Ps,writeFile as pT}from"node:fs/promises";import{join as Np}from"node:path";var $p=/^[a-z0-9][a-z0-9-]{0,31}$/,fT=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,lb=/^[a-z0-9][a-z0-9-]{0,31}$/,hT=/^[0-9TZ:.+-]{1,40}$/,Mp=()=>Np(Q(),"pending"),nl=e=>{if(!$p.test(e)||fT.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Np(Mp(),`${e}.json`)},db=()=>Np(Q(),"cursor-pending.json"),mT=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),yT=(e,t)=>{if(!mT(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!$p.test(n)||typeof e.op!="string"||!lb.test(e.op)||typeof e.requestedAt!="string"||!hT.test(e.requestedAt)||Number.isNaN(Date.parse(e.requestedAt))))return{version:1,adapter:n,op:e.op,requestedAt:e.requestedAt,watcherPid:typeof e.watcherPid=="number"&&Number.isSafeInteger(e.watcherPid)&&e.watcherPid>0?e.watcherPid:void 0,...typeof e.generation=="string"&&e.generation?{generation:e.generation}:{}}},Fp=async(e,t)=>{try{return yT(JSON.parse(await dT(e,"utf-8")),t)}catch{return}},ub=async()=>{let e=db(),t=await Fp(e,"cursor");if(!t)return;let n=!1;try{await pb(),await cb(e,nl("cursor"),ib.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await Ps(e,{force:!0})}catch{}return t},rl=async e=>{let t=await Fp(nl(e),e);return t||(e==="cursor"?ub():void 0)},pr=async()=>{let e;try{e=await lT(Mp())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!$p.test(r))continue;let o=await rl(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await ub();n&&t.push(n)}return t},pb=async()=>{await kt();let e=Mp();await cT(e,{recursive:!0,mode:448});try{await iT(e,448)}catch{}},tl=async e=>{await pb();let t=nl(e.adapter),n=`${t}.${process.pid}.tmp`;await pT(n,`${JSON.stringify(e)}
104
- `,{mode:384}),await he(n,t)},gT=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,fr=async(e,t)=>await Up(e,t)==="claimed",Up=async(e,t)=>{let n=nl(e);if(t){let o=`${n}.${process.pid}.${sb()}.claimed`;try{await uT(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Fp(o,e);if(a&&gT(a,t))return await Ps(o,{force:!0}),"claimed";let s=!1;try{await cb(o,n,ib.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await Ps(o,{force:!0})}return"superseded"}let r=!1;try{await Ps(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await Ps(db(),{force:!0})}catch{}return r?"claimed":"absent"},hr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},wT=e=>{let{command:t,args:n}=fn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},bT=e=>{let{exe:t,args:n}=wT(e),r=sT(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},fb=bT;var hb=async()=>{let e=[],t;try{t=await pr()}catch{return e}for(let n of t)if(!hr(n.watcherPid))try{let r=fb(n.adapter);if(!r)continue;await tl({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},Ls=async(e,t)=>{if(!lb.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await rl(e),r=new Date().toISOString(),o=sb();if(n&&hr(n.watcherPid))return await tl({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await tl({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=fb(e)}catch{a=void 0}return a&&await tl({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as kT,spawnSync as yb}from"node:child_process";import{existsSync as ol}from"node:fs";import{homedir as CT,platform as mr}from"node:os";import{join as gb,win32 as mb}from"node:path";var wb=(e,t={})=>{let n=t.env??process.env,r=t.exists??ol,o=(t.home??CT)(),a={localAppData:n.LOCALAPPDATA??mb.join(o,"AppData","Local"),programFiles:n.ProgramFiles,programFilesX86:n["ProgramFiles(x86)"]};for(let s of e.win32Install??[]){let i=a[s.root];if(!i)continue;let c=mb.join(i,s.path);if(r(c))return c}},zr=/^[A-Za-z0-9 ._-]{1,64}$/,AT=/^[A-Za-z0-9.-]{1,128}$/,al=e=>e.darwinBundleId&&AT.test(e.darwinBundleId)?e.darwinBundleId:void 0,bb=(e,t=mr())=>t==="darwin"?al(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",kb=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",Cb=(e,t=mr(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return wb(e,r)!==void 0;let o=e.linuxProcess;return!o||!zr.test(o)?!1:n.split(":").filter(Boolean).some(a=>ol(gb(a,o)))},Ab=(e,t=mr())=>{if(t==="darwin"&&al(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&zr.test(n))},vb=1e4,Ds=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=gb(t,"System32",e);return ol(n)?n:e},vT=e=>{let t=`/usr/bin/${e}`;return ol(t)?t:e},ST=(e,t)=>{try{let n=yb(e,t,{encoding:"utf-8",timeout:vb,windowsHide:!0,...mr()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:mr()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},ET=e=>new Promise(t=>setTimeout(t,e)),Sb=(e,t={})=>{let n=t.runtimePlatform??mr(),r=t.run??ST;if(n==="darwin"){let a=al(e);if(a&&r("/usr/bin/osascript",["-e",`if application id "${a}" is running then tell application id "${a}" to quit`]))return!0;let s=e.darwinAppName;return!s||!zr.test(s)?!1:r("/usr/bin/osascript",["-e",`if application "${s}" is running then tell application "${s}" to quit`])}if(n==="win32"){let a=e.win32Image;return!a||!zr.test(a)?!1:r(Ds("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!zr.test(o)?!1:r(vT("pkill"),["-TERM","-o","-x",o])},Eb=async(e,t=2e4,n={})=>{let r=n.sleep??ET,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},IT=(e,t,n={})=>{let r=mr();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=yb(e,t,{stdio:"ignore",timeout:vb,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=kT(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},Ib=(e,t={})=>{let n=t.runtimePlatform??mr(),r=t.launch??IT;if(n==="darwin"){let a=al(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!zr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=wb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!zr.test(o)?!1:r(o,[])};var $T={darwinAppName:"Cursor",darwinBundleId:"com.todesktop.230313mzl4w4u92",win32Image:"Cursor.exe",linuxProcess:"cursor",win32Install:[{root:"localAppData",path:"Programs\\cursor\\Cursor.exe"},{root:"programFiles",path:"cursor\\Cursor.exe"},{root:"programFilesX86",path:"cursor\\Cursor.exe"}]},MT=e=>e==="apply"||e==="native"||e==="revert",Nb=()=>ot("Cursor"),qr=()=>Qo(Nb(),"User","globalStorage","state.vscdb"),$s=()=>`${qr()}.anyray-bak.json`,qo=()=>`${qr()}.anyray-bak`,Xe="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",ct="cursorAuth/openAIKey";var Hp="/seat/cursor",Zp="Prefer the anyray_search and anyray_read tools over the built-in codebase search and file read. anyray_search returns relevance-filtered matches; anyray_read returns the pertinent slice of a file plus a retrieve handle you can pass to anyray_retrieve to recover any elided detail. Use them when finding or reading code.",Ns=Qo(".cursor","rules","anyray.mdc"),$b="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",FT=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",$b,"",Zp,""].join(`
105
- `),UT=e=>{let t=NT(e);for(;;){if(Se(Qo(t,".git")))return t;let n=Db(t);if(n===t)return null;t=n}},BT=e=>e.authMode!=="placeholder",en=()=>Qo(Lb(),".cursor","hooks.json"),tn=()=>Qo(Lb(),".cursor","mcp.json"),Ft="anyray",Mb="--anyray-owner=cursor-v1",WT="postToolUse",HT="beforeSubmitPrompt",xb="preToolUse",KT="^MCP:",GT="UserPromptSubmit",jT="Shell",VT="^(Read|Grep)$",dl="--anyray-owner=cursor-hook-v1",Qr=[{event:WT,flag:Je,trailingArgs:["cursor"],matcher:KT},{event:HT,flag:nr,trailingArgs:[],matcher:GT},{event:xb,flag:Fg,trailingArgs:[],matcher:jT},{event:xb,flag:Ug,trailingArgs:[],matcher:VT}];var Rb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},YT=(e,t,n)=>xT(e,t,n),Ob=YT,ZT,JT=()=>{let e=ZT??DT();if(e==="win32"){let t=Ob(Ds("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],Rb);return t.error||t.signal||t.status!==0?!0:/(?:^|\r?\n)"Cursor\.exe",/iu.test(t.stdout??"")}for(let t of e==="linux"?["cursor","Cursor"]:["Cursor"]){let n=Ob("pgrep",["-x",t],Rb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},XT=JT,cl=()=>XT();var zT=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Xe)??null,openAIKey:e.readItem(n,ct)??null,lastWritten:r};Yp(t,`${JSON.stringify(o,null,2)}
106
- `,{encoding:"utf-8",flag:"wx",mode:384})},Fb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Yp(n,`${JSON.stringify(t,null,2)}
107
- `,{encoding:"utf-8",flag:"wx",mode:384});try{LT(n,e)}catch(r){throw mn(n,{force:!0}),r}},qT=(e,t)=>{let n=Xo(e);Fb(e,{...n,lastWritten:t})},oe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_b=e=>oe(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Xo=e=>{let t=Pb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(oe(n)&&(Object.keys(n).length===2||Object.keys(n).length===3)&&Object.prototype.hasOwnProperty.call(n,"applicationUser")&&Object.prototype.hasOwnProperty.call(n,"openAIKey")&&(typeof n.applicationUser=="string"||n.applicationUser===null)&&(typeof n.openAIKey=="string"||n.openAIKey===null)&&(n.lastWritten===void 0||oe(n.lastWritten)&&Object.keys(n.lastWritten).length===2&&typeof n.lastWritten.applicationUser=="string"&&typeof n.lastWritten.openAIKey=="string"))return{applicationUser:n.applicationUser,openAIKey:n.openAIKey,...n.lastWritten?{lastWritten:{applicationUser:n.lastWritten.applicationUser,openAIKey:n.lastWritten.openAIKey}}:{}};if(!oe(n)||n.version!==1||!oe(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Xe],o=n.rows[ct];if(!_b(r)||!_b(o))throw new Error("Cursor value backup is missing an exact managed row");return{applicationUser:r.exists?r.value:null,openAIKey:o.exists?o.value:null}},Tb=e=>{let t=Buffer.alloc(16),n=TT(e,"r");try{return PT(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{RT(n)}},QT=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return oe(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Ub=e=>{let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".lan")||t.endsWith(".internal")||t.endsWith(".home")||!t.includes(".")&&Bp(t)===0||t==="0.0.0.0")return!0;if(Bp(t)===4){let[n,r,o]=t.split(".").map(Number);return n===10||n===0||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===192&&r===0&&(o===0||o===2)||n===198&&(r===18||r===19)||n===198&&r===51&&o===100||n===203&&r===0&&o===113||n>=224}if(Bp(t)===6){let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return Ub(`${r>>>8}.${r&255}.${o>>>8}.${o&255}`)}return t==="::"||t==="::1"||t.startsWith("fc")||t.startsWith("fd")?!0:/^fe[89a-f]/.test(t)}return!1},Kp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Ub(t.hostname)}catch{return!1}},eP=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},tP=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Ze(e.origin)}/v1${Hp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Hp}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),zo=(e,t=!1)=>[...t?[`Cursor's server-side BYOK lane bypasses the local key-refresh proxy and points directly at ${e.openaiBaseUrl}.`]:[],"Route capability: only custom-model requests Cursor actually sends to its OpenAI BYOK endpoint. Cursor's Agent wire behavior varies by release; native Team models, Tab, indexing, and other first-party traffic stay on Cursor-hosted services.","Billing: this lane bills as an Anyray subscription seat \u2014 each distinct attributed developer with usage in a month is one seat. Attribution rides your per-user ark_ key (Cursor sends no metadata header), so enroll each developer with their own key."],Bb=()=>{let e=qr();if(!Se(e))return"clear";let t=Ts();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Xe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return oe(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},nP=(e,t)=>{if(!Kp(e))return{routed:!1,problem:"gateway-not-public-https"};let n=qr();if(!Se(n))return{routed:!1,problem:"state-db-missing"};let r=Ts();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Xe),a=r.readItem(n,ct)}catch{return{routed:!1,problem:"state-db-unreadable"}}if(o===void 0)return{routed:!1,problem:"settings-missing"};let s;try{s=JSON.parse(o)}catch{return{routed:!1,problem:"settings-malformed"}}if(!oe(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ze(e)}/v1${Hp}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!xe(a)||!xe(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},rP=(e,t=[])=>({command:Lt(e,[...t,dl])}),Jp=(e,t,n)=>{if(!oe(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Lt(t,[...n,dl])||r===Lt(t,n)||r.endsWith(` ${dl}`)&&r.includes(` ${t} `)},oP=(e,t)=>oe(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Wb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Jp(a,t,n)){r=!0;continue}if(!oe(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!oP(c,t));if(s.length===a.hooks.length){o.push(a);continue}r=!0;let i=Object.keys(a).every(c=>c==="matcher"||c==="hooks");s.length===0&&i||o.push({...a,hooks:s})}return{entries:o,changed:r}},Xp=(e,t)=>{let n=e[t];if(n===void 0)return[];if(!Array.isArray(n))throw new Error(`Cursor hook event ${t} is not an array`);return n},Hb=(e,t,n,r,o)=>oe(e.hooks)&&Xp(e.hooks,t).some(a=>oe(a)&&a.matcher===o&&Jp(a,n,r)),aP=(e,t,n,r,o)=>oe(e.hooks)&&Xp(e.hooks,t).some(a=>oe(a)&&a.matcher===o&&Jp(a,n,r)&&wc(a.command,n,[...r,dl])),Kb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!oe(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=oe(e.hooks)?{...e.hooks}:{},{entries:s}=Wb(Xp(a,t),n,r);return s.push({...rP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},sP=(e,t,n,r=[])=>{if(!oe(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Wb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},iP=async()=>{let e=en();if(!le()){let t=await jb();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await U(e);for(let n of Qr)t=Kb(t,n.event,n.flag,n.trailingArgs,n.matcher);return await J(e,t),{changedFiles:[e],messages:[`Installed Cursor global hooks in ${e} (postToolUse trims oversized MCP tool outputs; preToolUse trims recognized Shell command output and redirects bulky built-in Read/Grep to Anyray's context tools; beforeSubmitPrompt beacons oversized pasted-data prompts). Cursor hook cache/tee persistence is disabled; gateway request logs and savings/spend rows remain metadata-only, while trace decision content follows the deployment's ANYRAY_CONTENT_MODE.`],complete:!0}}catch{return{changedFiles:[],messages:[`Could not install Cursor hooks in ${e}. Chat can still route through Anyray, but hook-based trimming/beacons are unavailable until this is fixed.`],complete:!1}}},ll=()=>{let e=Ve("profile");return{command:e.command,args:[...e.args,Mb]}},Gp=e=>oe(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===ll().command&&e.args.length===ll().args.length&&e.args.every((t,n)=>t===ll().args[n]),cP=e=>{if(!oe(e)||Object.keys(e).some(o=>o!=="command"&&o!=="args")||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(o=>typeof o=="string")||je(e.command))return!1;let t=e.args;if(t.at(-2)!==or||t.at(-1)!=="profile")return!1;let n=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(n))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(n)||t.length!==3)return!1;let r=t[0].replaceAll("\\","/");return!je(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},ul=e=>oe(e)&&Array.isArray(e.args)&&e.args.at(-1)===Mb||cP(e),lP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,dP=async()=>{if(!le())return Gb();let e=tn();try{let t=await U(e);if(t.mcpServers!==void 0&&!oe(t.mcpServers))throw new Error("mcpServers is not an object");let n=oe(t.mcpServers)?{...t.mcpServers}:{},r=n[Ft];return r!==void 0&&!ul(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Ft} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Ft]=ll(),await J(e,{...t,mcpServers:n}),{changedFiles:[e],messages:[`Registered the Anyray retrieval MCP server (anyray_retrieve) in ${e} for explicit recovery of stashed context.`],complete:!0})}catch{return{changedFiles:[],messages:[`Could not register the Anyray MCP server in ${e}; retrieval via anyray_retrieve is unavailable until this is fixed.`],complete:!1}}},Gb=async()=>{let e=tn();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await U(e);if(!oe(t.mcpServers)||!(Ft in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!ul(t.mcpServers[Ft]))return{changedFiles:[],messages:[`Preserved the foreign ${Ft} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Ft];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await J(e,r,{backup:!1}),{changedFiles:[e],messages:["Removed the Anyray retrieval MCP server (anyray_retrieve)."],complete:!0}}catch{return{changedFiles:[],messages:[`Could not remove the Anyray MCP server from ${e}; the registration was left in place.`],complete:!1}}},jb=async()=>{let e=en();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await U(e),n=t;for(let r of Qr)n=sP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await J(e,n,{backup:!1}),{changedFiles:[e],messages:["Removed Cursor global Anyray hooks."],complete:!0})}catch{return{changedFiles:[],messages:[`Could not remove Cursor hooks from ${e}; the hooks were left in place.`],complete:!1}}},uP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=UT(e);if(!n)return t;let r=Qo(n,Ns),o=FT();try{if(Se(r)){let a=Pb(r,"utf8");if(a===o)return t;if(!a.includes($b))return{...t,messages:[`Left ${Ns} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Zp}"`]}}return _T(Db(r),{recursive:!0}),Yp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Ns} so Cursor agents in this repo default to Anyray's tools (that is what produces gateway traces \u2014 Cursor's built-in search and read never reach Anyray). Commit it to share with the team.`],complete:!0}}catch{return{...t,messages:[`Could not write ${Ns} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Vb=async()=>{let e=await iP(),t=await dP(),n=await uP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},jp=async()=>{let e=await jb(),t=await Gb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Yb=async()=>{if(!le()){let e=await jp();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${Oe()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await U(en());for(let r of Qr)e=Kb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await U(tn());if(t.mcpServers!==void 0&&!oe(t.mcpServers))throw new Error("mcpServers is not an object");let n=oe(t.mcpServers)?t.mcpServers[Ft]:void 0;return n!==void 0&&!ul(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${tn()} already contains a foreign ${Ft} MCP registration. Rename or remove that entry explicitly, then re-run Connect.`],complete:!1}:{changedFiles:[],messages:[],complete:!0}}catch{return{changedFiles:[],messages:[`Cursor routing was not changed because its hook or MCP configuration could not be validated safely. Repair ${en()} and ${tn()}, then re-run Connect.`],complete:!1}}},pP=async()=>{if(!le())return!1;try{let e=await U(en());if(!oe(e.hooks)||!Qr.every(r=>Hb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await U(tn()),n=oe(t.mcpServers)?t.mcpServers[Ft]:void 0;return Gp(n)}catch{return!1}},Zb=["openAIBaseUrl","useOpenAIKey"],Ms=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!oe(t))throw new Error("Cursor application-user settings are not an object");return t},fP=(e,t,n)=>{let r=Ms(e),o=Ms(t??void 0),a=n===void 0?void 0:Ms(n),s={...r},i=[];for(let c of Zb){let l=Object.prototype.hasOwnProperty.call(r,c),d=a!==void 0&&Object.prototype.hasOwnProperty.call(a,c);if(a===void 0||l!==d||l&&!Object.is(r[c],a[c])){i.push(c);continue}Object.prototype.hasOwnProperty.call(o,c)?s[c]=o[c]:delete s[c]}return{mutation:Object.keys(s).length===0?{key:Xe}:{key:Xe,value:JSON.stringify(s)},conflicts:i}},Wp=(e,t)=>{let n=Ms(e),r=Ms(t??void 0),o={...n};for(let a of Zb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Xe}:{key:Xe,value:JSON.stringify(o)}},sl=e=>typeof e=="string"&&e.startsWith("ark_"),il=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);oe(o)&&(n=o)}catch{}let r=sl(t)||n!==null&&(sl(n.useOpenAIKey)||sl(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,sl(o.openAIKey)&&delete o.openAIKey,{applicationUser:Object.keys(o).length===0?null:JSON.stringify(o),openAIKey:null}}if(Object.prototype.hasOwnProperty.call(n,"useOpenAIKey")&&typeof n.useOpenAIKey!="boolean"){let o={...n};return delete o.useOpenAIKey,{applicationUser:Object.keys(o).length===0?null:JSON.stringify(o),openAIKey:t}}return{applicationUser:e,openAIKey:t}},it=(e,t)=>{if(!e.clientKey)return[...t?[t]:[],"Enrollment required: Cursor needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; do not save a placeholder Custom Endpoint.",...zo(e)];let n=de(e.metadata);return[...t?[t]:[],"Configure Cursor by hand: Cursor \u2192 Settings \u2192 Models \u2192 OpenAI API Key:",` \u2022 Override OpenAI Base URL: ${e.openaiBaseUrl}`," \u2022 API key: run `anyray-connect print-key` and paste the returned personal gateway key (the key is not shown here).",n?` \u2022 Cursor has no custom-header field, so attribution rides your per-user key, not ${n}.`:" \u2022 (No attribution metadata resolved; set --user, or use --enroll for a per-user key.)","This is Cursor's OpenAI-BYOK lane: usage counts toward your Anyray subscription seat, but the upstream still needs a provider API key. It does not consume the native Cursor Team entitlement; exact custom-model Agent compatibility varies by Cursor release.",...zo(e)]},Vp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!le())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await Ls("cursor",e)}catch{return n}return{status:"queued",messages:[`Cursor is running \u2014 ${o} queued. It completes automatically the next time Cursor fully quits; relaunch Cursor afterwards to pick it up.`,a.alreadyWatching?"A queue watcher was already waiting; it will run the latest queued operation.":a.watcherPid?"A background watcher is now waiting for Cursor to quit.":"The queue was saved, but a background watcher could not be started; the next Connect run will service it.",...r]}},hP=async(e,t)=>{if(!xe(e.clientKey))return{status:"manual",messages:["Cursor native subscription mode was not changed: a valid personal ark_ gateway key is required for Anyray hooks and MCP retrieval."]};if(!t.dryRun&&!t.preservePendingOp)try{await fr("cursor")}catch{return{status:"manual",messages:["Cursor native subscription mode was not changed because Connect could not cancel Cursor's stale queued operation. Repair the owner-only ~/.anyray cursor queue and re-run."]}}let n=await Yb();if(!n.complete)return{status:"manual",messages:n.messages};let r=Se($s())||Se(qo());if(r&&cl())return Vp("native",t,{status:"manual",messages:["Cursor is running \u2014 fully quit it and re-run so Connect can restore the journaled BYOK override before enabling native subscription mode."]},["No native Claude/Opus request will be redirected: the queued operation restores Cursor\u2019s prior settings, then installs only Anyray hooks/MCP."]);if(!r){let c=Bb();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Se(qo())?qo():$s()}, then install Anyray's local hooks and retrieval MCP server.`:`Would leave Cursor's native Team sign-in and model route unchanged, install global hooks in ${en()}, and register the Anyray retrieval MCP server in ${tn()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Fs.revert({dryRun:!1,preservePendingOp:!0}),o.status!=="reverted"))return{...o,messages:[...o.messages,"Cursor native subscription mode was not reported active because the prior BYOK route could not be restored safely."]};let a=await Vb(),s=[];if(!t.preservePendingOp)try{await fr("cursor")}catch{s.push("Could not clear Cursor's stale queue marker.")}return{status:a.complete&&s.length===0?"configured":"manual",changedFiles:[...new Set([...o?.changedFiles??[],...a.changedFiles])],messages:[...o?.messages??[],"Kept Cursor's native Team sign-in and Claude/Opus model route; no Anyray OpenAI override or model credential was written.",...a.messages,...s,"Claude/Opus inference remains Cursor-hosted and will not produce gateway inference traces. Anyray records content-free hook savings only when a supported oversized Shell/MCP result is actually reduced.",`Make it seamless org-wide: paste this into Cursor's dashboard Team Rules and mark it Required, so every member's agent uses Anyray's tools without being asked -- "${Zp}" (connect already writes ${Ns} when run inside a repo, which covers that repo once committed; see docs/integrations/cursor.md).`,"Restart Cursor so its MCP registration is loaded; hooks.json itself is watched and reloads automatically."]}},Fs={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>cl(),quitTarget:$T,needsTarget:e=>e!=="revert",async complete(e,t,n){return MT(e)?e!=="revert"&&t?Fs.apply(t,n):Fs.revert(n):{status:"manual",messages:[`Cursor could not service a queued "${e}" operation it does not recognise; the queue entry was dropped.`]}}},async detect(){let e=Nb(),t=Se(e);return{installed:t,detail:t?qr():"Cursor user dir not found"}},async watchPaths(){return[en(),tn()]},async mcpStatus(){let e=tn();if(!await R(e))return{registered:!1,command:null};try{let t=await U(e),n=oe(t.mcpServers)?t.mcpServers[Ft]:void 0;return Gp(n)?{registered:!0,command:lP(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=en();if(!await R(n))e="missing";else try{let s=await U(n);if(s.hooks===void 0)e="missing";else if(!oe(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Qr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Qr.every(c=>Hb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Qr.every(c=>aP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=tn();if(!await R(a))r="missing";else try{let s=await U(a);if(s.mcpServers===void 0)r="missing";else if(!oe(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Ft];r=i===void 0?"missing":ul(i)?"owned":"foreign",r==="owned"&&(o=Gp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Wr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await L();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(BT(e))return hP(e,t);let n=tP(e),r=eP(e.openaiBaseUrl),o=qr(),a=$s(),s=qo();if(!xe(e.clientKey))return{status:"manual",messages:it(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let i={changedFiles:[],messages:[],complete:!0},c=y=>{let b=y.status==="configured"&&!i.complete;return{...y,status:b?"manual":y.status,changedFiles:[...y.changedFiles??[],...i.changedFiles],messages:[...y.messages,...i.messages,...b?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Kp(n.openaiBaseUrl))return c({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach loopback/LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect. No proxy, DNS, certificate, or interception workaround is installed.",...zo(n)]});let l=await Yb();if(!l.complete)return{status:"manual",messages:l.messages};let d=Ts();if(!d)return c({status:"manual",messages:it(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Se(o))return c({status:"manual",messages:it(n,`No Cursor state DB at ${o} (open Cursor once first).`)});let u=null,f;if(Se(s)){if(Se(a))return c({status:"manual",messages:it(n,`Both a legacy Cursor Anyray backup (${s}) and a current value backup (${a}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{Tb(s)?u="sqlite":(Xo(s),u="value")}catch{u=null}if(!u)return c({status:"manual",messages:it(n,`Legacy Cursor Anyray backup at ${s} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(Se(a))try{p=Xo(a)}catch{return c({status:"manual",messages:it(n,`Existing Cursor backup at ${a} is invalid \u2014 refusing to write or replace recovery data.`)})}if(cl())return c(await Vp("apply",t,{status:"manual",messages:it(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...zo(n,r),...u?[`The legacy Anyray backup at ${s} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...u?[`Would migrate the legacy Anyray backup at ${s}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${o}, ${Se(a)?`retain the original value backup at ${a}`:`create a mode-0600 value backup at ${a}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${en()}, and register the Anyray retrieval MCP server in ${tn()}.`,...zo(n,r)]};if(u){try{d.checkpointWal(o)}catch(b){return c({status:"manual",messages:it(n,`Couldn't checkpoint Cursor's state DB at ${o} while migrating the legacy Anyray backup at ${s}${_s(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=il(d.readItem(s,Xe)??null,d.readItem(s,ct)??null);else{let b=Xo(s);y=il(b.applicationUser,b.openAIKey)}}catch{return c({status:"manual",messages:it(n,`Couldn't read the legacy Anyray backup at ${s} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{d.mutateRows(o,[Wp(d.readItem(o,Xe),y.applicationUser),y.openAIKey===null?{key:ct}:{key:ct,value:y.openAIKey}])}catch{return c({status:"manual",messages:it(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${s} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{mn(s,{force:!0}),mn(`${s}-wal`,{force:!0}),mn(`${s}-shm`,{force:!0}),f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held and removed it.`}catch{f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{d.checkpointWal(o)}catch(y){return c({status:"manual",messages:it(n,`Couldn't checkpoint Cursor's state DB at ${o}${_s(y)} \u2014 refusing to write; set it by hand:`)})}let h;try{h=d.readItem(o,Xe)}catch{return c({status:"manual",messages:it(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=QT(h,n);if(!m)return c({status:"manual",messages:it(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let w={applicationUser:m.value,openAIKey:e.clientKey};if(Se(a))try{qT(a,w)}catch{return c({status:"manual",messages:it(n,`Couldn't update three-way ownership in the protected Cursor backup at ${a} \u2014 refusing to write; set it by hand:`)})}else try{zT(d,a,o,w)}catch{return c({status:"manual",messages:it(n,`Couldn't create the protected Cursor value backup at ${a} \u2014 refusing to write; set it by hand:`)})}try{d.mutateRows(o,[{key:Xe,value:m.value},{key:ct,value:e.clientKey}])}catch{let y=!0;if(p)try{Fb(a,p)}catch{y=!1}return c({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${a}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${a} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}i=await Vb();let g=[];if(!t.preservePendingOp)try{await fr("cursor")}catch{g.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return c({status:"configured",changedFiles:[o],messages:[...f?[f]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${a}).`,"Stored the API key in Cursor's credential row (not shown here).",...g,...zo(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await L().catch(()=>{}),n=e;if(!Kp(n)){let o=t&&nt(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&Ze(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Se($s())||Se(qo())||Bb()!=="clear"?!1:pP():nP(n,r).routed},async revert(e){let t=qr(),n=$s(),r=qo(),o=Se(n),a=Se(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${en()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${en()} and unregister its owned retrieval MCP server.`]};if((o||a)&&cl()){if(e.fullRevert){let h=await jp(),m=!0;try{await fr("cursor")}catch{m=!1}return{status:"manual",changedFiles:h.changedFiles,messages:[...h.messages,...m?[]:["Could not clear Cursor's stale queue marker."],`Cursor is running, so its saved settings in ${a?r:n} were left in place and nothing was queued. Quit Cursor and re-run --revert to restore them.`]}}return Vp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Ts(),i=!1,c=!1,l,d=[];if(a)try{if(Tb(r))if(Se(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let h=il(s.readItem(r,Xe)??null,s.readItem(r,ct)??null);s.mutateRows(t,[Wp(s.readItem(t,Xe),h.applicationUser),h.openAIKey===null?{key:ct}:{key:ct,value:h.openAIKey}]),c=!0}else i=!0,OT(r,t),mn(`${t}-wal`,{force:!0}),mn(`${t}-shm`,{force:!0});else{let h=Xo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let m=il(h.applicationUser,h.openAIKey);s.mutateRows(t,[Wp(s.readItem(t,Xe),m.applicationUser),m.openAIKey===null?{key:ct}:{key:ct,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${_s(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Xo(n)}catch{return{status:"manual",messages:[`Couldn't read a supported Cursor value backup from ${n}; the backup was retained.`]}}if(l){if(!l.lastWritten)return{status:"manual",messages:[`The Cursor backup at ${n} predates three-way ownership, so Connect cannot prove which current values are still its own. The backup was retained and no hook or MCP cleanup was attempted.`]};if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let h=fP(s.readItem(t,Xe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,ct);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:ct}:{key:ct,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${_s(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{mn(r,{force:!0}),mn(`${r}-wal`,{force:!0}),mn(`${r}-shm`,{force:!0}),mn(n,{force:!0})}catch{f=!1,u.push("Cursor values were restored, but a recovery sidecar could not be removed; retain it until a later revert can finish cleanup.")}if(!e.preservePendingOp)try{await fr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await jp();return f=f&&p.complete,{status:f?"reverted":"manual",changedFiles:[...o||a?[t]:[],...p.changedFiles],messages:[i?"Restored Cursor's state DB from the legacy Anyray backup.":c?"Restored Cursor's managed settings fields and credential from the legacy Anyray backup while preserving current unrelated settings and rows.":l?"Restored Cursor's managed settings fields and credential from the Anyray backup while preserving current unrelated settings.":"No Cursor row backup was present; only owned hook and MCP integrations were considered for cleanup.",...u,...d.length>0?[`Preserved Cursor values changed after Connect configured them: ${[...new Set(d)].join(", ")}.`]:[],...p.messages,"Restart Cursor."]}}};import{chmod as zP,mkdir as qP,readFile as bk,rm as QP,writeFile as eL}from"node:fs/promises";import{randomUUID as tL}from"node:crypto";import{dirname as nL,join as kk}from"node:path";var mP=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
108
- `;)r+=1;r-=1;continue}if(o==="/"&&e[r+1]==="*"){let a=e.indexOf("*/",r+2);r=a===-1?e.length:a+1,t+=" ";continue}t+=o}return t},yP=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o===","){let a=r+1;for(;a<e.length&&/\s/.test(e[a]);)a+=1;if(e[a]==="}"||e[a]==="]")continue}t+=o}return t},yr=e=>JSON.parse(yP(mP(e)));import{spawnSync as gP}from"node:child_process";import{platform as wP}from"node:os";var Jb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},bP=(e,t,n)=>gP(e,t,n),Xb=bP,kP,CP=()=>{let e=kP??wP();if(e==="win32"){let n=Xb(Ds("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],Jb);return n.error||n.signal||n.status!==0?!0:/(?:^|\r?\n)"Code\.exe",/iu.test(n.stdout??"")}let t=e==="linux"?[["-f","Visual Studio Code"],["-x","code"]]:[["-f","Visual Studio Code"]];for(let[n,r]of t){let o=Xb("pgrep",[n,r],Jb);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},AP=CP,Us=()=>AP();var pl={darwinAppName:"Visual Studio Code",darwinBundleId:"com.microsoft.VSCode",win32Image:"Code.exe",linuxProcess:"code",win32Install:[{root:"localAppData",path:"Programs\\Microsoft VS Code\\Code.exe"},{root:"programFiles",path:"Microsoft VS Code\\Code.exe"},{root:"programFilesX86",path:"Microsoft VS Code\\Code.exe"}]};import{execFile as vP}from"node:child_process";import{readdirSync as SP,statSync as EP}from"node:fs";import{createHash as tk,randomBytes as IP,randomUUID as nk}from"node:crypto";import{chmod as xP,lstat as ef,mkdir as tf,readdir as rk,readFile as gn,rm as ok,unlink as hl,writeFile as nf}from"node:fs/promises";import{homedir as ea,platform as rf}from"node:os";import{dirname as zp,join as vt,posix as qb,win32 as RP}from"node:path";import{promisify as OP}from"node:util";var yn="0.1.23";var gr="31112ab5ee55ece527cade12d2845cf6016ca0d94eb733727e7045af98442ea1",fl="7c92a5f547d092df7439ab98d83cafb4d6c6982ce39cbe7d8d3e5538a5fc5fa0",zb="UEsDBBQAAAgIAEepDF07WYI0CAMAALQJAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeoqXlXgp3tYGg2IlQKVAg18cCI3K0mpoiCQ5XlvLrg93Vl5W0jewgt13OzHucDz4yf7teWrHCyORdT3azKynQaW/IlT1ZpXnnd/m2uLzIJ6AfocQxOJojJ/GwC7nOruqg9dI67slFSuFGKdYLXAJnS9LRs5+nTPulMrhC6wNGteJ1p/VR11fd7jb8xrwAoGOQqXQtTnF5cZGPMYGBBPXPRT406BKljRiBKysosSfRdf6aSjE0PQluE2HTWbH2BuUhq6usm13/JsWkmlniBcadqxSqxX1HHCxsPsISi35jEnMfxcNUDLzBXB3b2wBkHSkk8q5O94YDaOzJEJExrlAWfWMEroMlTUlsIUtI+AQbsfQGLQsft4bOU4QQ0IiBD2R9ElzNDvBb77SIvioXuz39CsHzHyz8fE6awAq7rUin8Rch+hUZjKI/GWa5Otpvm8A9lFw8j+FcNauNfQAJSx8JuegP34xBL8ihGCFER67M1ZG98X8P1mLc3NkaoSm0ztWzxdqtcZ3EuutpF7pf2DRNHO+H5IG4AjtNlSGf1Tlnt64kV3cWbIU9+Xc36143U67ORlondPV0vMOAzqDThLwHfg1gfbZ+CNCf5Mwe6MnHx2bG3lT0AtCR12DpM5rduXldrg5mFk0/UB3iGew34M5OG3WVkAft0W3BUqzwBYBTjCvSyNmI3CNnU19FfQCtRYlvlCopLapZI0WtGnz4pJbe+YjBZyWl8wpzwvkeEyeICc1P5qX0oZr9XM5pFYKP6SxSRcxVPYWv4G3E6CzWXyKCWZ6M1Av42yrfWVj5iGYM8dH4J/ftsT0PeeBdQpeySSRNrtxD3kVEqYrL59vO1YmW5iPS6BgL3KmIGg0Htx+nt1lap1ztzFstztXx9ZoPHSewFg63xPHKPcQS0/8dZNmknatTrPxYaFufPjOm7b6bb3G/CfjfMrF7skgxgbToyUOeoX3TZP+wd1L0jYnIXOvU8358D9NX3diW7WvSo+L+O2eu9pnm6uTpVXwBUEsDBBQAAAgIAEepDF3fow3fvAAAAGUBAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH3QMW7DMAwF0D2nELjHdDsUQWE7Q9ob9AKEQjtKJUowGUO9feFkC+rO/O9/gN2xpugWnjVk6eGlacGx+HwOMvVws3F/gOOw675+CqurKYr2cDEr74jqL5xIm1xYaopjnhOZNnmesJD/ponxtW3f0GcxFtvb2gFD98Ej3aK5z2osj93mquBOj9w61QOVEoMnC1nwSgupn0MxwC2e5b+C9bxBrdqTNK6GJVLYNIuGmkjCyPonrimuFO9fG3a/UEsDBBQACAgIAEWpDF0AAAAAAAAAAAAAAAAWAAAAZXh0ZW5zaW9uL3BhY2thZ2UuanNvbnVU227UMBB9368Y5QUJiLO75bpPVKWICoqKyuWBFslrT5OhWduyJ3tR1X9HdrzJFpWnJHPOzJy55W4CUBi5wmIBhTQ7L3flOiirsXgeIU3BtXL3JTOOEwNurIcfl3Ay0jAoT47JmkTTGnDrWlLEkH1qybiRO1hZjW0A6zNQbrx0DjWcWEetZQjdcgi2Z3PjbVc3+6RPAtibG1IkW2ilqTtZY5mo4Lxdk0YPxxdnohe3Rh+ysKmYiflRb3ae1pJjWew77E3dsqXQoB+70XNbUmhCasH52bfe5tHZQGz9rljA3QQAoOCdS6SaOJEAis632fKsYXZhUVU1cdMthbKrqk/y8Wu1ssbGiOLAVZNHlRMU/VRK3DKaVM4E4D4JQVOTwTCqyANcQPF7JmbzmZiOZCUZa+sp8X/1/OOzfcZzqRoyCJ9RekOmjn7XyW8lKXVQVJoCV4MM8Sf07Rgsn8joMfbG+tvgpMKhHzQGVdLJJbXEdCi/M+y7wKh/7n1HEKAInXPWM+o8uWS/HwqUiuNcyZrTNRo+KNOaS5aeO/eBTJyy3kuy5rs/VGUNe1p2fChqv2bncctOGskXedHGBDBoTEtntP13jzL26FEVGb9Pz+uhnv4WDpQsO2pj7YWxGgFD+harPIe4xVLdyhoX60DbvDkI2QhlaWyp0aHRaBRhgLK0HcOD2xfJNYfbSFbNY/mgLHvs+bj8qkF1G8kcVMp1uhr3mTHwEKgsaRXnCBy2UJYRg6sieFXF1+qpiA/B4arYu/faFs5jvtP/iHLe6k7xgxvRuH5/UPTYzXdRdahMPpj5q/iH2GfM4HhP8ZymYjrgPRIJCT4Sb0fnLKr/7czfiNnQhpDG8kLMj8TLw+b1o47YazEV86R+cj/5C1BLBwi5JKi7mgIAAKQFAABQSwMEFAAICAgAaacMXQAAAAAAAAAAAAAAABUAAABleHRlbnNpb24vTElDRU5TRS50eHRdUUFu2zAQvPMVg5xSQEiLHHrojZFoi6hMGhQd10daoiMWMmmIdAP/vqDsJE1PBHd3ZnZmV1yjcZ310RJShtNlci9Dwn33BY/fHr+D+stkLoSs7XR0Mbrg4SIGO9n9BS+T8cn2BQ6TtQgHdIOZXmyBFGD8BSc7xeAR9sk47/wLDLpwupBwQBpcRAyH9GomC+N7mBhD50yyPfrQnY/WJ5Oy3sGNNuI+DRZ37Q1x92UW6a0ZifPIvbcWXl0awjlhsjFNrsscBZzvxnOfd3hrj+7obgoZPvuOJAWcoy3mPQscQ+8O+bWzrdN5P7o4FOhdpt6fky0Qc3EOsMg+voYJ0Y4j6cLJ2YjZ68d280xe/ZQDTbeIYq68DuH42YmL5HCevIuDnTF9QAyz4m/bpVzJ44cwjuE1W+uC7112FH8QogcLsw9/7OzlelYfkuuucc8HOH1c9daKgxlH7O0tMNvDeZh/7ExZPibjkzMjTmGa9f63+UCIrhlaudBbqhh4i7WSz7xiFe5oC97eFdhyXcuNxpYqRYXeQS5AxQ4/uagKsF9rxdoWUhG+WjecVQW4KJtNxcUSTxsNITUavuKaVdASWfBGxVmbyVZMlTUVmj7xhutdQRZci8y5kAoUa6o0LzcNVVhv1Fq2DFRUEFJwsVBcLNmKCf0ALiAk2DMTGm1NmyZLEbrRtVR5P5RyvVN8WWvUsqmYavHE0HD61LCrlNihbChfFajoii7ZjJK6Zorkset22NYsl7IeFaCl5lJkG6UUWtFSF9BS6XfolresAFW8zYEslFwVJMcpF3mEi4wT7MqSo8ani0g1/zcteydExWjDxbLN4GzxbfiB/AVQSwcIsoZ6jXkCAAAnBAAAUEsDBBQACAgIAEepDF0AAAAAAAAAAAAAAAAbAAAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpz5X1rd9s2tuj3+RUUr5cOMYFpOUkzHaowr+u4bdq8GjvpQ9HYNAlZrClAJSHbqsTfMt/u+V/nl9y18SJISU46c9a5H+7qakyBILCxAey9sV/wFxX1KlHmqfCHt0np/SLIm6vfaCrCtKSJoLLwZ1OW0UnO6NuSz2kplvLdD/aDayre3DHz8jmt0jKfC16qJnZUe53MaCVr/OTWeFtywcVyTt9M8K/2xdyUhtOkchqR3/8oSECxQORoNeFlAEXMy5kn0M8BxQyvrqmIxIiNMWWLGS2Tq4JGvUGNavyCyk8xwxw+zyeB6PehHz7xBCE+l93767VTNlmwVOSc+Qh6K6jwSo9PvJ9FIBDq/SrCNCmKgOIS9ftljxDW7wMcpYIjQORIjMo2LAEnP4hA4BKh9ZqHzasaDUsqFiXzaC3H+tIAjMhRwAjtEbYoivgXEfwkAopQtIJBBWK97lH4P7y4oNUrni0KGv8cMOxndJIsCuHj1W1SLGhEu0iJGKYIYcoIJUcvaPBzsKqx3zRjv4TKmCIJVsnJqh7+KIKS41WSivw2EVSOlXGc0VYJ5zUazmRbIb2f81JUhLKg5KqpV+QlDUr6+yIvaeDfVinPqI8Q/k4QW8p4RqO0XM4F9xH+rftmUh3MSz7LK1r5qtEPxE/YskyW4XUi6F2yPOFskl+Ht4c+/qn77ge6VFtCMMLonXdGRTDyFxUtfewLmsx87OdMUCbsw8vkihY+9itaVbA0xggziUBKCPELnibFlFewkGTBKIoOx/56ffCPw8d/C+LoY/gxWx3iJzVaPan3DkJBK5hN/Cs0IVelWn60R3zYs+zaR2pd+P5QlMsVrEIhgX3/7mVAQ1HmswDZxaM3UMqLHiH+VIh55Pf7m6VVBEvdFhOnco+xQIQwCJbMKIJqgBH4IT9JquqOl5l6FlMoh1YPZIMVTcp0Ck/TpJrGvh+JkJf5dc7qNBHpdGUGU9f4RxgzLF5nzHYbHpcwT3kl/wYUxas60iRiUvLZKRNlTqtAF1H9k6JwkheClkEwEpiNYQsyACUQyG53Rixu+30WFpRdi+nRoHn+ijz+4lm/3zsYfVwMBoPBPvw5nMC/f5uM9aQxhMJZMm86Un8Rfk5hXGZMbl8H/0jKm4vR8f6vyf4fg/2/X+yPV48H+IvDx85SiGl0y/PMG+C9nQ1RB2jaAD0YfApot/nvzZLrdXGtV9xoPFSrbTTGdn8MDSnkQAppWBV5SoMBfvYUIdkYt/PJd88nRyjlTORsQWUfJeE4J3s0KMM8Q7hSj3L9DXv5et2r1ms1jzlarwMWJlkW5AiLcL6opsEqz6IcQ/WoqhGqzWao8fuG7OOSjGCe5BbKya+w7SrynAYCDQFw3Q2HxZzyeV5wsV/RRPj9vizTNGM/mec+EtOS33mAk9Oy5GXg5+w2KfLM07W8VJKdRZkoBiJHWZDvg1J2xkmnwX6/0PNICBl8uvkZz2ix0Yke9/dnb16HarHkk2WwuqUl0KroEOvP35dFlOOGCEYVnlGRZIlIoh8DhjA0H3FT4xV0VkUF8NE/5KLUZGhVW5qUENnrPCkrGtA49n00TOyWSxoO2+931luC+v0k1DASQg77/UCQBGmCUUPrjPwaiLCBHmEuZ84h5AiX5MdAhGYgCOdEhDCQLq6BOpny1kTHqtxskIrkcdyugWEKba8KLwbtKwe5zEUub5BbKsxWXczivDrRc0mzyKVJsPQUPP1+7jwH1Qb463VhP0S1kiIoJWmRVNUq5awS5SIVvAwEWolpXoUlTTIiavgznFOW5ex6eE1FIDeyrKFLkdlQTpmmDbahAIVywgJGjlZq/brVCSECJtYtUmNBmDXCT+u9wKLWCz8RNNBQt7/W4/zjIcEAf0u7EsU0L7KLeclTWkGFl533wNh8hOfUyJtysWRJeZczP/YPXuZXZVIuD47n8yJP5fbzzhZzEHEOjqWIcXDFuahEmczD3yrO/Ei2cJezJ4/9+GUoH8LfeA689m3Jr8tk9jwRSRz7J9HHj06Jj33Voo/9TpsoCgb4pWwFBf4BFamPtYSzpTLm7M/xky8OH/f7ozAM6Tikt7RcBkLvfEZEmE6T8oRn9FgEAzt97Ig8edzvsx4hh4//VqN+P5Ag5tXxVcWLhaAoAJHCIKApB7aDS0YO/qH547hBg/dNXtAq8D4G918++4hQ/PHjQY6v7eQIB7UlM5wu6g3wjJKkWrJU8QDyR1iJRBj5v/lKr+/ewJIzTpK7JBceC6gdHA8XeQbkud8PuKQU/cMvERS0ZJveYV3jpdMx+UNuEBgEdG26YLoLEVDsL8TkS1+yBiOkNAIgsD49P08Hf3+mgV3NS1pRJqLeYT1UIDsUmFk2A6eGz2PJcCC5hZlrqodVxTck0Y2eS8LDq5wNu68H+CpnEWdBieIyMvvVxZXbVF3jqZ1SueziER1HozEOw9Cd4tE4Gullvp9yxmA04zGumPvxlMofUkRj5ChYTfKCRgwn5XX1tqST/B5aFvmM8oV4VUVzViO0rSf1oc/m937rY39/f0kru+EMJP+7SGD9+W7bv9N6PMYJaw50wNnfKvoUcHK0Cgb4Wzgj0VSuEllvpRuIGJ4l918vJhNaRs+e/vVw8PgpvstZxu+q7/JMHs9wUOLcyDYVKfW8x4NIz2QZppLj+Wwxu6KlH6uCOD6MoOKQByt6n4sTxZ0qkUHHeRwKfibnPkDA0msE/+GMOTKAOYKE1bzIRXD5l0sUzvlcfTBsFruzOJXAxbqLkzWLU680va6Z3LaLSi5pEMUY53MjllFW8qKgmfl9VfD0hmatJkqSW9ywUT623EZ1XDW0MK7MOjWrWXUdcbwoi6gM/EVZ+AgD8uCXOrPiGa2q5FqW6EcftVd6XeOCWYmbrteW5n5x+NjQn0OJL0NLzRkPbRzTqsjfJDnpTvJuaepg/+/749VTfPjMPXsuGHlGn+IJI4eDv8LTXBX8Tsnhl/QpvmbkMX2KZ4wcPpbvv4FtSlY1chbBvEjEhJezONZc1ZZgRmhI2W3zhrJbzAm1VDGOGwqJS0LldEMh/MU51FywOE4YrggNGRf5ZBnHgSKwiBz1DhEuCA35nLLTewFn1cJ9v6oRTuSXd3H8PBHyCWfQUUHpPI6Du/aWvCBHFRXnav8FF/gOIYRT8lrunfD16bfH5y8+nF68eP3Ni9cvzn/BM7zY/XJKeof4XLED706rrgBtF3CCqlhwhwVCEpEnmiXkwQWcYykGSnYRNmQH1DOa3ih9yT4Ikv4YX4SW3Bg5TI9cnm1O1uuT0GzwHpwwWsevM5Kx4CRU215+cWZofcpns4Rl0QW+pWWWpyI6A0o9ccZjYL5rYL5rwby/LzgvgFZqedXHmnqO8e+0A2+N507bAPwUrabE4c0XJAnQoxmTR9FhEqCvLoYonwQKjiy4ZggHnwRqXuZM7N/QpT/Gh1/QJx0wUGzxJU9kepST4M7IA3U9yVlSFEuADtiXoRgK+glIk0hye4AtQPvpVwtmqFIKY5C4vyNzGgBXwBd69pc0uMNcTdxFqDmkS85OyAXwW+c0cE0DWYRBzaFamUEroGjEZ7rd8+AklrU0iVM9nDkt29n+zc72aU3OoN6ppsHEJbkNVn6zWHHquuR4ve4VLDgNF2WB1uteCs+wgI2yQcKiy3qEzGAcAdpffDVhaDV32p8RVQkvAIUYXmEFRRVcKkk58qr8WimGuUcZKDybc/k0Eer0XHkfF48Hh0+9JV+UHjTp5ZW3t1LN15fYfzOnTDa1nzPfIrbQozDn01ofQb7unCE4HCz2th8s7h88rny/cVzRClDZz3e73uLXD7b6W/c7CeBSKS9jLR8Q//T1m9PX5z7+0BadgwH+raHyKEBaioZVaKRotRqCAX4dllQqb6QMZmZOMfPLvZWoQ03EeJHt760sx8izen8PhKHvaFgmLOOz9+9fPEcBqi9xSTR7VOqbpqtCyvRWixPmFfCRAPX78sfZcnbFizx9mbObAG1qVko6WVQ5u4a1UtJ5kaTUSzzG2T4QDi+jlciZUbBsDlBgDpqHnj4DBLnSgi1ZkJvO8hrA3o6b1lcl2l6R24qrLviXkyQvaAbAzxdXRV5NPQl2wjKvpJXgJfXElHrzkt7mfFG54xl6JU05HOy8lM+XXklnSc4qLxHe3orXl6g28Jd67SuoZgARcLFUG1fU8qdE6/D3pzB1k0nl4ymzhSVNaT4XlY9/oeQxvmPk8OnTwV+fDf56SJ/gW0a+xD9Q4ooqoB49fIYPH39Z7x3gY1dFL8UuLP/s56zKM1oCe5Fd5YsZaOV/lo0N9v+uj5PNY/hof7wa4GeggMc/yWrJ/mSw//fx6tlTKHtlTxJGWPscDfVupV1LTedp7GidICNUCsNGAdYj5BcKJz7GWQqUUDTycXiblHnChHs07B0rvah9+S/AkU+CgIGFhqaCZiBBMQDlg4VI8QuAaqPS87wSZ9Pk8RfPbD049VuQd7fqjOFnqnXqO6sjBwsPwuC0+tPuVpsv0L+GLxYm0jQIFBMYtD2yeObE8WvAWgrLnLDtWkdA6zY1Zcw62sjvmxaN5tGBRKmttQ4Rhl+u16DTzjdVzZWjanbwmhY5ZeIHumxh8TOMFs6n/wI2tdQUhiFz9dNaVZp3VKVVXeO7FmvCHJjT1+GUz2iWlw1r6v1AzRnnc6GSm07NsLMob+0adNZU5iyhna1Ts+C8q0VeZF6eUSZysdSbvwTI97QCj2M/NMq7rym+3FvRWqruLhHOLefLLOe7N5xPmRSyDV63Xvcyyw3X6yys8j/o0eGzJ18+3YR4wapkQh8kEYBkRwBoGD9o+TKlEHv2BMqbVWVY+zUVUnnW2NT7/Qz0aT1C2nWCbTvyU9CRVyxwFAwNiqziLSiNkg1M2ZrtZkgz1OaDBStydgNIbZ8HcFYr/cGOGZuyRjq4D2c3ciVWeFXSdFFW+S2V6khY0U+fflkbe5DTWAUznhsqbmc+0YehTJ+1UxCgijqUYtL3XTEpFLP55dCVIu7DuzIXVOEghT52WYd+oVgu/4hiRVGiDNMOGY7sZmheNbQ0cncF6NIy0iJK/X7ukE233LWd5A7Z1DRArq26RvVfLvFKFj358mlt5P4PNEhxgexxzJn9GYzZEVU6R01zZPN2wZV/miv2+8GDtSzG1ust9Vrss0VUYn2ETUBELXiS7WvpPfMR3iyKgu1jiLWSObRFQQvBeUO78Y9B7prPJNbx9019zXVQZNqUnC8w85BYEHTJwxvKVq7xrxtnDZecg61PK20Ubd8gnaxFOg25zEmbDsjWStRWy6lNPRpbu3YCWhktxSchZVn1Uy6mga+tKG3FSUYSawHf/0LxDcN1sk7d1IW4xAnCM0vVF5tUPZWtLbZR9YWl6k0PM7IIZ6ADelXpAZpXcCLn+7OjO4ZWm9OSdtVF9rNK29YVUciwbj2a1aiuwoqXIggSnCFylJme9xPzZAjcq0RMw1nOAiNz4FuGGlyTwTD5qhgmjx6hDoPz7mhQjZKxkoOxUpxLPteTIldn+esWNbBpDZo1PTPJo0OENgfemozLvVVqSG4XIZpEZPa8L48719udl+S7b+FIrfWBMFMsl/atfp8eDWKJkZIvWAY2qgEWWy20dsVroyfjd0QM5WMlklLQ7FjbXuWuqBm/G9oXQz4X+Sz/g55tlDznjB6LIQBOK3FGmTgWw0leVuJtUsJzkdjHeQIOW4NhSZXr1qDdrrHHbnTmwmVenrJsZ32XlLZqKGCd5sCzwwIeWCu2Mxa377kDpBzLI3LoWq1lLYVTBwOkC437TiAsyxosSfs54KcBR2LrETkEhpRXUzC3q5PeSkIRNQBhXTlyv8QpXzBxkhRFFX0bKCfDCpnSdEq/y4V5o38hLLhIiley2A5tv71cUN0ysj80DVtmwZ0kZt+9qsi32+Zsf3sXSKOvNWXdfh18tzu1L5penbr7my2b7ra32JnIdl+VKGkyazpq6u13m0TgwFDjHynx7/fbynnp6obPWUutEV4cRKDZMIoN2ji1qmUyupSzSfZWNNTzWl82NisH0HNt7AatL1Pk+lLqNgko2S4Rpi7SnA9NZftWdubUVR8bLGz5Ur2Sn5la6ptmaWz5yryU3zU14UtTRVEdeC+f3FeGEMFL/ey+bvaNrNH83KgEe8ato7eRqiedMnzsoxoL4Rg6R3YKdgxSfGKQs+qBGRGfnBH9+ZY5EQ/MifxK7MateBi3wkXbBl4PtuBQEqXM+XRzMUuYLkETH3kSoXsrodHu+ai+VByWCeIf3B4e2INGdaC21YHBqY9PmKoDbR2kfDYvKIiUlY/z7q6yUyEPj7ExKdsp1ZSDSI2bK95LzUoCjj4082t8xcjhF4MBvmDkKX2G7xn5kj7Dp0ypEa3eEitV4hkjOxwy8a10f+1R6yRHH3CSA19FtRgbJ2DX4c6KKbeBQLEwRuyOBfq5xAl4t6I/4wgk+v3emfWrwTeNHTvo3Up/HhpCaz33fL9ew7vQ/Eagjw96zwMKHp7rtXwyL0PjaaxBal4k5fViRpmoWjopgGNLHWSMSeAPCv1gaDBqYMLmKVpJZ9EOBNi2FG1rHuyeb5qxq5H3rL94UlV5JRLpKw72Tn8c5iwtFhmtAu1EQcOSF9SCOTTGcygdGpekpp1mZcDpDbzPe625soXGj6L32Z/DlGnPbbPO5YyYiQBA5CB0OTxfgCRyIWdP9qTft1862uINcJyaDflycaGtgFvr9fsbjspONbUG7U+zjB9/8QzchUnrHbgE3TDrKf415wVNGJB+9VWPkC1toWZ1wXRFAmukRha90n3IoBww6W4ts+LgTw01Wb+/anqJWN363MVpqxn3RdSuBwv03b+5Obtb0inJdLhPW/uxuWdb9dwFZ2vMkzKZUUFLd3pbEDlVGrz/yd3sonMbcC20OuXR9upyfnbB2O+vml/R1jpgKMZv26YlM0FSaANjj3oCs05nqWu3IrXQzY+WHn+j+OiQPm3tLuJUgU3wZnMTKIuCsw86bXYcs+id9yqZ49KY5nDuqlImoEoRDejW82UOLybOHovj0ViqXLg0Zs2BR5iueAhKJijCap7nO6n2fBvVBk2TFmKSooj2VtAUWDfzSTCRpNchdpM2pZNWWQlS54UBrpSRCJ2XtsOSVotCRHurdgXoXCueDN4K+5RsYJB9EnHKj4SDBl3hDqaxalC5Xt/Fhtx3sLde37lMlmxDoRlsJQcrW8TJ5+JUQTcnbRRIQq8wOwcuWtnHQj/ZlaY6bXq0SJ1bPGYbCANFUSwNHvJZwWSZlrSMZLSggu6aWGUt0d6+meFVQ1ep1h2o/rIpdnlfa9L0ZpItG6P2pMui5uRI7QNUK/XhoD3KRC2LYfpVbtvLR+m4R8hkiFJQduSTICWE5J3Nm0rlhNtWhZqFDryg0I/udp9Bc4rhONx7WwCRqmNZskOPnqzXwYyYYhjluy2MeNZlxA0PduCZWNQFQtWSm0G2ekeO7jqsDOG5jWHKJ8EsrPiMBsHKMpE78GfsTeTI7wz7m7s/494gCuZyPeoS3Du07KlWilxpnygiTcmNZ2gVMWAfM83AQYsq+ZM+qDlscKVKIvMK3KIJxedktLqhy8gXdDanZSJAuY9nOYsG4B4cPa6xfs/nF3P3zaF5M0vuLwS/oXA8cj6kf8cQ2nhNS+lJ3NRtzlOf/ZlyVkvpxZyypBBL9cX+4zaIE3nWYulyRzVL/2T1iXw5l+/ubJ8XoOI9N26T09FkjM+IGE3GMLknpFmfWgQ4a3yf+/1gMZqMyVl7O+uKJz1bcb3udbW4J2i9Pvlqvl6fHN2t1xf9flPjhYJMVgkmsP8dhK/XtmQTrY7DxJnb+8nRmV3xEuITE9m2qHEij4PBytfC5z604EfqpKpCUg6kyQInCzHlpT74Rpdf06SkpQcH8iZICdzdrPbK2ID8qGsrBK98ayLCsJIj69OpXMNFY8lxz95TmoCPjuRQFmK1qbVDhT7FgLfyx+yRdS1A/b7CcMDQkUCOudaj4RXPlnGYJiylRdC1LznmY+UWaH0AFRJp5iXM49I69wfNZNQc+EzNOauMD4Dqwrh2dC3MIKbTewHht0oeUtVhkO/keAOkRaNzei+eU1BelDgn4MzhQyyZ9miTZHyIdBydaprroCoAIwkzzihaVY9IGWaymQA8nnuD4VVJkxtYvfkjkoQyXDu8Wgr6Uhlbcouyfxcbbt+6I2xIlXQC28RR1Zhki/XaDGvHbMF4C5pU9CVPbwJU1/j3jju73b0bO06ZVoi2rYC1ieLH9O/IuM68bjnef5YvV/uAjhlp14A0CWkulVIodn4YVlaCZqe0h6PyAc1O2QQml+FNzlqnvVOtdVFvEHLDbSWjK4EEwLtIVQGm8ntQhuDlN0sEzc4liTlLbmmGXC6zrUK088u6Rhab3PHDM2ox7Fc3+Xwun7K8Ao9beNQ+6T72KSw9f+x6+5hECy293ItsV+DChaMz11rvzpdwCGuXRN0q7hlbWI/mpkN1/DBvkOTGMvzDFNUKwSKEMB+WLl9VLaza0qhdxx747UrR532o9q/O1Y4v4ZhZiJZBfUJFOoUIaDdIaKU1npGoNa1zg1ANzSvj8C4pWeAbpaunZzqyBIRxYT1zpHdCpY2/sE6Or3gpTjgT0mW8xAmBHV+EyZW0mQ15rB5pFtvCCAqz7PQW8i3klaCMloEvX/o4wStp4wWio23wTqxGq3F8xZA1sac2ou/SYX3vy6LeWzFRg2MJFVOeRf7bN2fnPtYcK4Klmki9ZxiGeb+/Gv1Ix1Fe1xho/QaHbJCKMLiOJ0VUhOoBl+DQQFMR6e2ggjPKOMzZhDd2Aw8A8CRU3v6Rt7dKzeK7RLiXhvzGTI5C9EyPLBNBii/UGb53G8xQu9qCvGXBzOi5G79sbxFbqBfY3S/Ra/jALUF1pN0LghStOkukGYBuzlPOyREMwcsZHIVS2HmSD8WpFKEtLi4Rriy/SAualGZOM4R5HJZ0xm/pjjUB/IJR8uwpTqV6G99S+edY/qFP8AtGDukzzAV5TJ/hb5pIPOAKVIkeTaKNrXk4nJCtTaZ6+VlMFQQmmNj60sn2gheiDY4w3RzTfdqcwnUpRK/r9y/YfnNKVxz/87l9ByrbjY+GTqePiMDdPh4RA0GNJ5tmFnWCBUFPx/k1nrHyAKneS19EwujnAyw492YJWyp4ZSu+EbxA4e/7KgOE7zsaId+vGxOP7hkgA699XuOXbiSjtG7IzfMnhCbj6bmBxCYHxR5rz6+xHHRPzemU5ymtUFvHZsvDSc4yYPi3UmaAVBkso/dxPJAxyApyaBwieeEPaDhEgpzThS4y+uo252u96vdZoPWtIOL6WGUC6tSqEe51hmFqOKp5pDV73RdmGf/7i2BL2xNeniYgX2qep/BebvEtfWDntiYX2tULriIW+blDLKrtR0cjpoJGpPpqsF5Xf27hbwPEk93bvCITWNIVeIveBmWj1o+bZ0gXlZFvZIIVnArsy1ZePFcHHaXpLMI8g0Qk0oqT/QkAJfsv8lSoOBoDo2wdmiOZVmF9EyRKZ3tLsQ8PqvvULIVbul/ICkbh868dXiQIunnV3iOS4oUICgwQ2G2Kjyn2nU0LcTbASsouVeskvxlhPuYTnRpBecJBoq9RDvllyv1cp8J5HnClfVUhGvLHvzntZsJUBhzZIpb9KB3Xv9y4Rpawm57zYl+ueAz/vsgi6EsRWNUZztl8IaKXLOCOplii7/n/K4KnlW1tkqcLtxO9zsudZK9TbyvhM3W2kL7NV/+dxG9L67vIn0SUQyH+m8ihpD85Glaw2bcRGVwpg+g3TuddSgAbtMKtGp/cqXPRDgXBpTrs2Nit1qHGmNo+nc6pg4Xjty9k0ChEiHaPO0MnINErt5wuTtju04U6WWw7SQh7fuA7Dg69HI4Cn5ZEXVncCyDIQB8n0KWZv5W2QWt7Xlveiwa17m6rFk/qHVHcODvIrXNAQVLfVxoiH6HVcxbYY0qO7xnCFQQ9lyKolGAG/r1NDHEvV6q3z16fjFt1lQdfWt6Ybyrlkg2lXAYKuRQi9Wdkocn+lCx0UouDj2X8kR1YS8U5OTpXjpXaOVwmd/J1Rjj1VipqvkAyO4b2l0XKyQlSZABCp5I4TGWawOdvXp+OfbRKQamnsbDXimmZKoTVdaMy7KVaaajdx73CURoulJKu319sqAWP+L+qFVTT6cm51ZID6B21XnDR1QsupOIS1MKG3P139SznRyUAmBI1PWqOZBKVIEMaM+ckszqzqeIfCmxbrksfTUeDsZE68Cw4RzhFVruqBqJ/91KIXVJZT/r9WZB1Qk+8YpeSs+goOVuLX3m9ldQkqYx8/J6REUTHPqFP8CF9ip/Qp2N8rRX/eRZd7q1KWgPBAeur4s5m/3+8//pvUskvHU4u8SSZ5cUSXBPkAzZhP9RG9MyS+xfA05UyKaJhuwDev1mIpsIhHKyBF4h8Hvm/QBT9ibIF6PR0d7mYehocV4vg44yKJC8i/9tcfLe4sp9ViyvrbqEGYFQKmceZJ5NQecqpNk3myVVe5CKnVSRtauCSmLNriLPKZ8k1laDLxEII/8E6Ap2jMnJC1GGeWqoHCE7hD6VQy+i8IqKGP0Pl+Qjm+0SAlU6QwVAthHc0ndL0ZqhCudQe1YdOHUpj2gqLvAK1mE3n2Xh4xMoTuYJOFhD8oUKhCu09rnrHlUhMetdAe0SrGB2nEriZJPPgWjzYxGGN6nRRlsrV3nUdV/Vq3fJKu5lDzh/Vix0+GJmvqeMavwnKaFxneTXnFW23VKs/K13XwWIcNk04xSYfXIMfm8WuVa+t2n/PRi7I4+FmNIJ+9Ygcbus1aKZOr6kyjv9gSO35nWAaP3hZFoCrMUK1WR668OEV4iiKVIKSzuowXKQ9IzuWQdM6Z8e3SV6ABj8wSQSXOxPyfsvIF/QJnrl+0sEAL01q6e+SaooCv5IhbT7CjHAlmEmZWeW0CvPqQ07vICfoSoSLucz1J5Mf5Ux8aYTrK1kXc8nG3kwmFRX6h1Z8ucLDRrLRpmF/5DfxRzKdM0eQoAw3NTAchOyvse+2zK2xhjc2Hbf5lQ3thYym3aSpFSQlKVEuT28Vcsr5xNO5bG/osgJFxdZKcObM9ZkTIdvtZlhnheoI3NmDclSN3dENW6Orm9G5jZkx1tFGwxwSey2YShOegd7WatggWR4WYZZfg3nGn4KCosZTe5i+1Jzq40D6tks+pH9oHiR/ORm4TVauy2pvNQOFYn0ZXc7sc32J8+3hU98yvSFmyT0R9Sy5H+ocwcZpbTiF7D4LBlR6lleVeVaKS5PmEJrQH7oqTde/QPZiGgCvG41Pl2KaviwRMW1qJySzBU2x0lGCT2oNsnplCfBqmptwIdMmhs6pLrSA1LVpQ/uCbqijIJ6dfTVAMnbuzwA1bJeCItegWktdvI04uaJRyKStfKh0gVacGm7rmitJEnKoATs2fMDU0oX1NeyK/A/a4U8uaJqE/a4UvUZRR8WLGYSXJoK6brGx+wLC81piwgDVuPq0MDA0yDiZJmUliax6jONnT0Ficuk0EfYxjn9nSpAwGU59f2heZuArYBqypUPpESfUFDc0PK/gaANJ6hVckwKquVReh6wJl7S5yVUfkaYunObeTOxq0DWMQE9ao2132GJBdiTrdVuQyUhv0EaKwzvd8WO3bUjzrB+72Wpdrthi9q30ta1csr6/BTm2YJbcUINRvZ7ud7FElaKp47pgbf9Ue7ngO0sUv5NJuaVRmhDyOG48wOm947Af9w6jgIZFzujXsG2+phNewhc9GQDUhG2YsJu/NCE4qi2EewMU2Z4OYxrC6u3JjMv2+fFWPV1eZCVlCIBofuqksIwc3YkAUo+hqHcY9Q7xK2r9Lb5Tmr/vILTAyfblyaST3biqO6GrYYhh0RFBPpIZKmt8K4g/WrCSskxdYuBpDcTYx8fCdauGTuWqaNDq+KkDLhrWglb/HlKdDdSgtt8PFEKJzKZqnx+jfn8nchsvX6ZSq9s3xwq9Nu+chuBWoBq/Ep/E9a3YwPSxg2ncYFqt7W8YeYy/Y+QQ/8bIE3wlZ5NKWVGQI2HcW39jsYqE+I6pk6dQCj0TFiGssjQSCJ9KOI3a5ZRJtUuAQiqfIMml47b0oZXKMlbMoB2npLTSlg/jc9H+xLxvvmnetUMz8MknP+3MWWxGhvD3HUhn+Yyey2iLVgodWCofDw5yHUNlq6EY1na0RRqmoczCEHcUVQEyyhZdQW4O/PUOMNo4gw962suu1wDhaO4OfITPRCtcddw89v7XXv8fF036rI8Hn1Vt7wD/Yj2wtoa7maOO3aPb4D8Tm9i79OBZBheawvoy8n29zi/3Vhv3SPgJPPmR6buWobJWWtMQ1Pi9YvQqhU9WKWXVqsY/sHZMaHvTIucOD7axcOGgILcu0/JNywHV1G8uqrDft/DEySvatOCkeW4RV90Td/pwXtvxNnsfX7X2QWeXxK34JbAmXlBy8F///D8fD+KkjOYR5FdL9ieQsq3+r3/+58E1/pnJCvJt4L5G//XP/wxGH6uPZ+O/xki2ISt9PFQf/sTax8n7/7+Pk63m3UMiR59xECzNQZCPyj95ENRRixsHQOQe+cztQnrxYrMPI4cMYakfp7GkQMagaCltvXFotCrbw2eoxjfi08RtK3EYJUIk6RQsGV6LRIwvIxAlKpWxn2aOJHHuXLukd9tPbhJ4pkKn5WGIY4rw5cfF47+dPpMLGNImyp9/g4hmnU0yuKAY9peqd9CpeFnjpElkH9POVxHFv7ZCxnYyRbP5E2ANairUYZV2yQrdTlYYkBVqyIoZrhZY44RKGSQ6h7zqr4StCIY4XVe+upEGLZBMMik3bNDfy5GcimQeZBQ5wfbjy2grb4gvV3srd9VTs+qNRLK55gUCxQUwyZEYo/rS7ae+jLavawgRebORi2HcufAG6exDozHEuoVhyI0wMIYLQ4yF6ESnIxVNtj2QI6smsiXfdHF4H/iz/F77L+yrOCfPBJB4SUml7RGy0h6/2NflHoQTJCK/KqhDKhIV1KMS6khVIYJURRpSibiUHP3KghTEdssDhrSoqPaW/IEF9gNkIokkl2kBrA7BYAlVZmEFdaV0/5BFFUQfs7/sGESZsKpIRKLAzkhalzrdkBQpVUQVbsW6JppcWAEzq1VkVNGgPSFHvRMRJEhC7FyHon3rnelMAUWF5NfnIkidVEr5JPjAoGSlQ84SGqR2Szn8VDlffs90rqaZ3ivud7P2F7AkvlZty0kxNc8hhdkNgNGu76L60iVYzewrxAJRAtvuL9A4GHZ1YBxJmsmVihctvH/DkJ7nwho14YTRmgQnot3iHLxgr0TApTts6ixtN5Y5lStspq1UMzNxn4jfnXXDOTsbdBZKl5M4lqnb4CiOaliwXhtqFY6/CXAtoxOFinSz2/AQyavKzsDO+0pvNbDB2p2QkIwG5WgwRhg05jqprlQGJmiYxZmRs6LmJTCHBI/4GNU670gYhqUllKzG95I4vpHE8p2rPdc5gmxkrWrR/u6CCmYazMgbbcYy/kkcl2Pp4q6/R6WNwYPDrIHTaNusW74TrQZJddOkjARELVuy2EaAPLihOKym+QQMO683ySfmoFwpyQDn0vN7xQnv8DjMbYKYFVCLiEM8CAHXzZZ+HLiGSKfHRRH8DMdl/oiY+8dKXGnjLi6JfnxUNRZd7QogNPMG2KvR4VhRCUeZyx+RavR47GzYwKaOWUHW5Fsqr8HSE+lCgLCsW+MXonVeDj4Vti6aaHU33LwTky42QtGF2g5n6ZTOEjdcwAlEb9WpYdPgC/En846cWPFkg5d3gmJAjyWvxFOXbJ5IkQF2AYpo1LsQSj9xIWTNz7vNT92wxzCXN+wxLLMbOpjwWwJ096wPV4E6Rxj4GZ1QyKc9YmMEl/W9FO1Uz+bqO8DveNg4/71K5oEaHCdHI97xYYIhNibbSZGIV6qmFhaYXHHaSc9ULOMRxBZwJySl/HN5CrZXl4uD71ocTrFEhVsPl1tzG9Q13MIDNzP8yB5MQbPrUtWNVSWsbkqYrHo7U+g2HgBdF+sa77W3mnKeN9HX1bISdLbFt+vDmQfXOnhFwq4XwET1dQAZl7KJZrKe+t7KXzZftw0f2nAojG0ZOKHzpubWo7SwR+lhC+6G67byjbjcWFJJGVCsVs/W2HLrFAFkoBNbLsPG9DmstI6dXdc85eH5I9vqkSc18B3QdcC/FHzbYfUbk9CZVi3s5pUHFixwI85FpT2dsyZJdEs4VEiAH+9USgAzonbfumJd161GlJjgYLKulfL+uSDNPSWn1h1nX/snRT6m3BIN576ee9gDOjhGWd2YG/Ty3i55E++j+IkHF6ruA34W11MIlWHGn1OmI5OqHIU8yO4CHcOMI+ceGal5EkY3RONwxMaOVzrfGjup45m53Ym8rvEv5rJMwIe54IFsy9Qjb2MwAORK72GWexyO8nEr3JpCAZPXJKBhuV4HdMRHg/GYgH9NsdWkBmlgpdeU9OnUDlTKJnRNhXLpNLY2zt6zxiOTMFVa8GvChzodIlwZRMrafjpsfzMs+PVQ1Rqm04Rd09NZLgRV0bvXoQw70kVDyNqbnchaLzUJkZlxT6aJeMEgO7b0clLmplZroXRfG0Lad5VLVzbPabACpw51Y7T8SC0/VQcS4DZOGU6lVsvqupkaDSEUi2av+YnbBsxWSZNCwQneH9YMLmPQT1R6NyjLqbE/ni9K9p3y+FSmg0lJq6kByl4h6TRqDLPKmOa03H7RjL/jErRtRF3voOZb+2bb1/al9qrpoNTduMrB5josZmFFC5oKmEhdcXVLWcbL6Lmozd4WbWNzwa9N/FuWV+o+jch05xWc3yzmjvOtUOaHOPZPtSvvJcKjcV1DE51ZM2PeOqXGjLpjvrVJVa3p4Bru3JIhdILCdeyx8RKsKAWPZq/jiKc5Yq7G6O2tug3UnrqBLrSfANK8csH0VxAECJWdFPhwpbS5c0cSxqKQFTUoTUXuNoDhmUHLXvumPQ8kRwWfguU/Kk/QcgaumOFl5H/OCEPvBHytPAHAd2rIAeWVAZVmWN8llGF5vQp4Z8sAsNCXiWn1RmicR8CPxri7CNfdRVh3l0vMybZ9BOKivsLR0mdNd/Wig2X1zukzBCwFOTkK8vV6W5P6rMcQzuEyitYdrburdm5m7VSEvcvgiqlS77JNuOx9oXnmekyXFCy8uXHCLW3ADxxZMjg6k8/bljjPImacW0XXubXBdHOLpwZ1XvLbPHuQgiv3mcK5DrTNf5QzS49vDZzewpm20D/jIIlHY6Wf2XYTiF0C7UTsUpKrGlfgU3AFrhxXYBVzYZADbyxiTPt+1+v38PGX4ND3oKtvx2FbbqXGp/f47Qu4Vg10fJNJnio/3pIvhHTpdgX6q6XnOiuDLLbPWaEu6XrQxfdww8VXR0Xl1Yn0tizkBL5TsQ+dSXHQb/1b5e1n2he21B6wee3OeotpSSd7c3eAcRSVnECJdg4nYNwyA01Vb/MK1LVeoAgc2aSucewzzqhfI+xVtLwFeXhvZXQ4tefkWK3ygjKht/xWHtLszl1L/p2Omwh0CA3Okc4R8MCqr9qrXlGT67DVuGRx4Wv+FshyJfMeWHf/jUia0Hu3SeOT60QSWK3AqbbuDx3PISho6LqSh/afwymeKTESWlrurndDklAn7tZRMUtwtaseLUPlaLcfZKog0wUI20Tcuu6+qlErhVxncQgR3KC2M5UjaWnnEhHc4BSh4a5aWpv35RDtqqF1cjVekCJWAnzkTKfLr+R8gk/A4uFpFN/ItPX++ZR6UhUH63IbX1WT6xWcXdPSS4zsauZxSgrQQrY5wmmbI5w2HEEBL1V1kAR0KtPFtSmhzuWVZ9ESsngtCSHTbffIvNBKhW0UzFNcRl301sxZRq8W14HOVmyTawOVlb8IkFx5PYnVFBA4w+mtqiOszvFEwo/06qMcVGO6D4X/T4c6WTUF+w+4JLLRVEha6PGysbfssMrABJyTZW2V20vyTgoa52Rp0zTiCVmGWvtbq9x9vMmvhu9MhrMinkYL4ClWaXwO58Z51yZQRS9EMFcpUN5pDle8kaqqCrfSmbWSnjgvok98tqtplQkN/r7ttA1vtrXa+mJHs24aNfhxrpN4uR00dbb0squBB/rbkooNyk9s8S4gNj7cAc9nd7ADyM3Eb7borS5pwdatvwWsz2lyBzRbEsw1ZVvh2fhiC0Cf16pWv8LKf6V4VYeaAsc912/Dd/oGE2s/k6HPkW9vNqlxk2RLWWHtvrPUZFuenRuSh5xtFYake+3SJMlBw3yX1NTv21o4CVtXbzR3THlziNq9w1dwE3Co7tyQtdWlGLg0j1fGPVKFVsdKs9JCDTi6Qbb74Ep7F0TbKmlBUFfUtsUrJeteKX02QjVe6rQ7TXTejaMymAXGiiNp3IUOI17iGyQH0h4tVLnS0tAirCjLNJLgAzhQvZGTUNFgpZyvo2NydOyq/3aMFCvvalndONBob2MoewhHx0hfHwIVV9swfgwmUhMuqu84g5Ecg77uSueXRHbS3ijZ47hB2BvrOj6TKdlOpAR1EVzJw6G6ongSb9hPtdqiEXl8xT23KjyBZyWCz/LUGrWnOZgYl765WOokaN0he7Z1wf/2iQV/9lkL3tbCXZFeDQHOMUoaP7fSuAY7qJCnRyXVF4Ztm/NOqWWB02HSvhlFr6+3lHxClpNTeWpifdW2U6m9zkyKKQM1fkudqNSwdQ0P/s3Rjhnf+Y2RWrA9k7OMwN3I2y5RsMcVL8+2VGqnYItjf19me9o5C86N0LkITuH29dXWhfC2k5Xv1OzaJuW0NUc576QM11hj7JvoDr+m5KUI3ipxBztij/ae+NNU3ZWGXtNWvN7WIX0QZA8AsAPAE0qW2jo5McfYpVwwN+Q10J+JPYneKDn4ihz5aqv5OfOuUHwjNQVQLCkvFH6C+krX9ghoKjSDom0tqFqR7yPHh/R7QT4o/yJDShXpnMRv3WGNbsZ44kr2V937ALwrGoyuxmg0kIqR5TbzmGz7DRnpGhJoWXZMJtQUDPUCOHam/Ljf18TuYQKLojfWfQPIorZ3SPq5DK19rUnC/bUgx4oD2YWnfzsObboEDH8PQOFyuWPD5Y4Vl/taIOuDsGUdajocHhtUBW/sMozfgG1yqUzRdQuzOgW6GpgyqRkUK3Ta4lbow0MQvK9oGYx2DE+1JQfYatzxFgKHV2fetrZkpusNGkdv0PhzECPBapaIRQfCL4i0ybckP3A4qoe/BC9wRyJ8GzrHkM6ZBG+vDweM7jlje9XmlBDH6teGjL7zKPEnZfrtAHTl78+TyLe3tSE6f640rSWAi+B7gfVp8jXFhgxHDUUGqdv1En2B3HOoC070AhzHWhqxc6sHUiow4+T5gPqr/J9Vf0mnta26YX1pogkZcHYL6zrQ3dMA/F7sxj2F3Iq1m75mu2oo/59RC1VkqqNei031nHTZUv5aG6xCRZKZzMm5upFKLW7pimRV/7skDq0+bakDoT+4pDPREX8p7UT8TaqDeclneQW+Ifj9RkAgRG9d6LuNdVyg4B3/uGCA34uwmid3DEnT+wq06KDchTQWlchyHvn5NeMlKIOHLOQs0DmAsM1zHUJQ3ARUfX/YbEhkVaOWpw61VzfHsblw2ZRgSNtI2W3zhrJbDJm4zPXJcZw2P3AJXm8iEbIUHnAOJTCKOBYcV2ROzUSqOVnSoIKUiwkpwqvcvT7mmgayCMMddqryDCoLMCtlZEqDJJYVTPphYUSCXiMoBhke+RcXevNIQPa1udofo/bFnWeUyONIeLXkN+8F2BeUFvE5nSSLQvj4xvp87KoTzhKWXEOK42+VB9LG3e3+LMnZ8TUkq2kypONvmtqmbL2mKjG8qY5/aGdQbw7a0t72SvUMLu5mWPj3ThKs9mfC/Yy1r7/tHdYbhnDZzbcFv0oKOOX12reI6Uo/qBSaYHrBb1q39zZxE+B8WMF9xyoNOmxhAwZYIL8RQYni0hECS2dd5M49nKZLhvW+x7lTk4fXEtgPKqiBWOPFt8KJ26jgDcSv/q5ofIVzKyk0rZlLl92+eocoavXhXHHFwzte3lTzJKUPvPqGFxkt2xUcUCScprsav6PbUuiLNvo4oI+hmDno46TpnTa474BuDcruLmwmtRn18MGVYept+XLQXWJq4y0oWWmgImuIoeRVg6eGyeor3gNkh3Fmp3LljAeCiJyfuD0b8LZdgrfNSauaU15DuL8eb6TkBfB+VCP+BNgmggpuLn4Vtt6eJ2DyDVW74EKnmjYedh7jAUWrP4xaQJBVM/MScVQP+UzAHcHAGG/gesCmkmpwYWFtf6BBu6F4IdMmA+03rhfhPElvkmsqBQdtK3ZcyZz7vHZaKxo3Dt2WN00k29fNNTl7jS2a4eba8ygY4O92hPsZyM1dzr8Jy5JQQMOkOr6qeLEQ9G0ic7LllWgujwx/q3yEUDc5iXLwojRQWw6Roz+ayx0qmpZUyx4fEELahb2UBZAm2c1XZSx39ivHTSyAuQgWIJkSQj6s1+bxJ9TvQ1pLaZWCsYFXpRaGvqFw9za476gJDRYY0hra5af8b6opv3NcFvQJR9UlZIr5nDK4bb5kdhEvnEUMdme3SvAqfF/m2qV3ARkDQIeIC2I7VFOjvANgdIwWZu59vCr4tcrMvhU5BdKSGiC9oEGuhJjK+HrhAgNwrcH9lJQsZ9d2YPKWEbKygnODHHyOJ3iOnGVvpkJGLAQf8Hvq1DO0q6mm/V5+AhWqOye64hsaTLCMAaqx9FuL7KLZ6FE39eFPd/KOBqqLGqekad/N8vcrDTLMu9eUBwslVmi0+Ou1LJCAyhtmCq3e03c2eIlXCSAX3t5qUXvThGV8MgHfK7ha/VLp8Fsef8Z4q8VsfRCatg9CdjKxGYlRb72BXHtwDtA43L5EEnnH7Wb5K/ADKuk1pH4vNw72b9U5DjLC65WYoIcacvam41UEqNwcNdJJ9nuH2yG2q9VA977Mv0tYVtAyWE3lw/syd/aezCc4T2T4kX/QzJjrXzuVW+T9u5dnNCnT6Vvwxq+CRfj7gpZLpBJwyrvufUjH5NtbDs717NzRYIozraI/VwsB5nXfGpbQaiYv4+oN8EP7zZ5XjReclwDRp6VD6K8WeQHnV9mDZ9zrBfeUH4Xx+QOleOpyQjgPJgXQ8KVei9irONQrTabVqcoo7ZV0v1xITzuznDYmCn+KJp63N0hshqbt6s5R3Lc+Tm14pRcrvDdSdKtLyQe7eEv5osjkUf+WlvlkKbHAGd2Hu1Esrtrd6L34oEZABfOkAaqt4MB5gFY15K2bcciZE9J7dafzKklFfpuAfww1jzUa/uX/AlBLBwhJWCqlszgAABqoAABQSwECPwMUAAAICABHqQxdO1mCNAgDAAC0CQAAFgAAAAAAAAAAAAAAtIEAAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdFBLAQI/AxQAAAgIAEepDF3fow3fvAAAAGUBAAATAAAAAAAAAAAAAAC0gTwDAABbQ29udGVudF9UeXBlc10ueG1sUEsBAj8DFAAICAgARakMXbkkqLuaAgAApAUAABYAAAAAAAAAAAAAAKSBKQQAAGV4dGVuc2lvbi9wYWNrYWdlLmpzb25QSwECPwMUAAgICABppwxdsoZ6jXkCAAAnBAAAFQAAAAAAAAAAAAAApIEHBwAAZXh0ZW5zaW9uL0xJQ0VOU0UudHh0UEsBAj8DFAAICAgAR6kMXUlYKqWzOAAAGqgAABsAAAAAAAAAAAAAAKSBwwkAAGV4dGVuc2lvbi9kaXN0L2V4dGVuc2lvbi5qc1BLBQYAAAAABQAFAFUBAAC/QgAAAAA=";var ie="anyray.anyray-vscode",of="vscode-handoffs",ak="vscode-receipts",Bs=2,_P=OP(vP),Ln={Code:{slug:"code",scheme:"vscode",macAppName:"Visual Studio Code",commands:["code","/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"]},"Code - Insiders":{slug:"code-insiders",scheme:"vscode-insiders",macAppName:"Visual Studio Code - Insiders",commands:["code-insiders","/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin/code-insiders"]},VSCodium:{slug:"vscodium",scheme:"vscodium",macAppName:"VSCodium",commands:["codium","/Applications/VSCodium.app/Contents/Resources/app/bin/codium"]}},TP={Code:{directory:"Microsoft VS Code",executable:"Code.exe"},"Code - Insiders":{directory:"Microsoft VS Code Insiders",executable:"Code - Insiders.exe"},VSCodium:{directory:"VSCodium",executable:"VSCodium.exe"}},PP=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),sk=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&PP(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ws=e=>{if(sk(e))try{return new URL(e.trim()).origin}catch{return}},LP=(e,t)=>{if(!e.endsWith(".app"))return!1;let n=e.slice(0,-4);if(n===t)return!0;if(!n.startsWith(`${t} `))return!1;let r=n.slice(t.length+1);return r.length>0&&/^\d+$/.test(r)},DP=e=>{try{return SP(e)}catch{return[]}},NP=e=>{try{return EP(e).mtimeMs}catch{return}},$P=(e,t,n,r,o)=>{if(!jr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=Ln[e].commands[0],s=vt(t,Ss[e]),i=[];for(let{directory:c,suffix:l}of[{directory:vt(s,"bin"),suffix:["bin","remote-cli"]},{directory:vt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=vt(c,d,...l,a),f=o(u);f!==void 0&&i.push({path:u,mtime:f})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},MP=(e,t,n)=>{let{macAppName:r,commands:o}=Ln[e],a=o[0],s=[];for(let i of["/Applications",qb.join(t,"Applications")])for(let c of n(i))LP(c,r)&&s.push(qb.join(i,c,"Contents/Resources/app/bin",a));return s},FP=(e,t=rf(),n=ea(),r=process.env,o=DP,a=NP)=>{let s=$P(e,n,r,o,a);if(t==="darwin")return[...new Set([...Ln[e].commands,...MP(e,n,o),...s])];if(t!=="win32"){let u=Ln[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=TP[e],c=RP.join,l=r.LOCALAPPDATA??c(n,"AppData","Local"),d=[c(l,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(u=>!!u);return[...new Set([...d.map(u=>c(u,i.directory,i.executable)),Ln[e].commands[0],...s])]},ik={run:async(e,t)=>({stdout:(await _P(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>IP(24).toString("base64url"),home:"",commandCandidates:e=>FP(e)},eo=(e,t)=>vt(e,".anyray",ak,`${t}.json`),af=(e,t)=>vt(e,".anyray",ak,`${t}.applied.json`),ck=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Mc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},qp=async(e,t,n)=>{try{let r=await t.run(e,[...n===void 0?[]:["--profile",n],"--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===ie.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===yn}catch{return}},lk=async(e,t)=>{let n=await ck(e,t);if(n)return qp(n.command,t)},UP=async(e,t,n)=>{let r=vt(e,".anyray",of);for(let o of n){if(!o.endsWith(".json"))continue;let a=vt(r,o);try{if(!(await ef(a)).isFile()||JSON.parse(await gn(a,"utf8")).variant!==t)continue;await hl(a)}catch{}}},BP=async(e,t)=>{let n=vt(e,".anyray",of),r;try{r=await rk(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=vt(n,o);try{if(!(await ef(a)).isFile()||JSON.parse(await gn(a,"utf8")).variant!==t)continue;await hl(a)}catch{}}},WP=async(e,t)=>{try{let n=JSON.parse(await gn(eo(e,t),"utf8"));return n.extensionVersion===yn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==gr}catch{return!1}},dk=250,HP=9e4,KP=HP/dk,GP=async(e,t,n,r)=>{for(let o=0;o<KP;o++){try{let a=JSON.parse(await gn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Bs&&a.action===n?"confirmed":a.extensionVersion!==yn||a.extensionDistSha256!==gr?"reload-required":a.version===Bs&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(dk)}return"timeout"},jP=200,Qb=(e,t)=>{let n=e,r=[typeof n?.name=="string"&&n.name?n.name:"Error"];typeof n?.code=="number"?r.push(`exit ${n.code}`):typeof n?.code=="string"&&n.code&&r.push(n.code);let a=(typeof n?.stderr=="string"?n.stderr:"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0);if(a){let s=a;t&&(s=s.replaceAll(t,"<nonce>")),s=s.replace(/\b(ark_|sk-|adt_|enl_)[A-Za-z0-9_-]+/g,"$1\u2026"),r.push(s.slice(0,jP))}return r.join(": ")},VP=async e=>{try{let t=await ef(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},ek=e=>tk("sha256").update(e).digest("hex"),YP=async(e=ea())=>{let t=Buffer.from(zb,"base64");if(t.length<4||t[0]!==80||t[1]!==75||ek(t)!==fl)throw new Error("bundled VS Code extension failed integrity validation");let n=vt(e,".anyray","vscode-extension"),r=vt(n,`anyray-vscode-${yn}-${fl.slice(0,12)}.vsix`);try{if(ek(await gn(r))===fl)return r}catch{}await tf(n,{recursive:!0,mode:448});let o=`${r}.${nk()}.tmp`;try{await nf(o,t,{mode:384}),await he(o,r),rf()!=="win32"&&await xP(r,384)}finally{await ok(o,{force:!0})}return r},Qp=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=>Qp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Qp(t[n])}`).join(",")}}`},uk=(e,t,n)=>tk("sha256").update(Qp({gatewayUrl:Ws(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:yn,extensionDistSha256:gr,profiles:[...n].sort()})).digest("hex"),ZP=async(e,t,n,r,o,a)=>{let s=JSON.parse(await gn(af(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==uk(t,n,r))return!1;let i=JSON.parse(await gn(eo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===yn&&i.extensionDistSha256===gr&&i.gatewayUrl===Ws(t.origin)?await lk(e,a)===!0:!1},JP=async(e,t,n,r)=>{let o=af(e,t),a=`${o}.${nk()}.tmp`;try{await tf(zp(o),{recursive:!0,mode:448}),await nf(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
109
- `,{mode:384}),await he(a,o)}catch{}finally{await ok(a,{force:!0})}},XP=async(e,t)=>{await hl(af(e,t)).catch(()=>{})},pk=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...ik,...r,home:r.home??ea()},s=Ln[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!sk(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,A,v)=>typeof b.id=="string"&&b.id.length>0&&b.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.id)&&typeof b.name=="string"&&b.name.length>0&&b.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.name)&&v.findIndex(E=>E.id===b.id)===A);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await ck(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!mp(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>_w(b,rf(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await ZP(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:eo(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let f=a.extensionPath;if(n==="configure"){try{f??=await YP(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await VP(f))return{ok:!1,reason:"extension-missing"}}let p=a.nonce(),h=vt(a.home,".anyray",of,`${p}.json`),m=eo(a.home,s.slug);await tf(zp(h),{recursive:!0,mode:448});let w=await rk(zp(h)).catch(()=>[]);await nf(h,`${JSON.stringify({version:Bs,action:n,nonce:p,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:yn,expectedExtensionDistSha256:gr})}
110
- `,{mode:384}),await UP(a.home,s.slug,w).catch(()=>{});let g={installed:[],failed:[]},y=!1;try{if(n==="configure"){let A=await WP(a.home,s.slug);if(A||await qp(l,a)!==!0)try{await a.run(l,["--install-extension",f,"--force"])}catch(v){return y=!0,{ok:!1,reason:"install-failed",detail:Qb(v,p)}}for(let v of u)try{(A||await qp(l,a,v)!==!0)&&await a.run(l,["--profile",v,"--install-extension",f,"--force"]),g.installed.push(v)}catch{g.failed.push(v)}}try{await a.run(l,["--open-url",`${s.scheme}://${ie}/configure?nonce=${encodeURIComponent(p)}`])}catch(A){return{ok:!1,reason:"handoff-undeliverable",detail:Qb(A,p)}}let b=await GP(m,p,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(y=!0,n==="configure")g.failed.length===0&&await JP(a.home,s.slug,uk(t,o,u),p);else{await XP(a.home,s.slug),await BP(a.home,s.slug).catch(()=>{});for(let A of[void 0,...u])try{await a.run(l,[...A?["--profile",A]:[],"--uninstall-extension",ie])}catch{}}return{ok:!0,receipt:m,profiles:g}}catch{return{ok:!1,reason:"failed"}}finally{y&&await hl(h).catch(()=>{})}},fk=async(e,t=ea())=>{try{let n=JSON.parse(await gn(eo(t,Ln[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==yn||n.extensionDistSha256!==gr)}catch{return!1}},hk=async(e,t=ea())=>{try{let n=JSON.parse(await gn(eo(t,Ln[e].slug),"utf8"));return n.version!==Bs||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},mk=async(e,t,n=ea(),r={})=>{try{let o=Ws(t);if(!o)return!1;let a=JSON.parse(await gn(eo(n,Ln[e].slug),"utf8"));if(!(a.version===Bs&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===yn&&a.extensionDistSha256===gr))return!1;let i={...ik,...r,home:n};return await lk(e,i)===!0}catch{return!1}};var wr="Anyray",wn="anyray",Ck="--anyray-owner=vscode-profile-v1",Hs=e=>kk(ot(e),"User","chatLanguageModels.json"),rL=e=>kk(ot(e),"User","settings.json"),Ks="github.copilot.advanced",yl="debug.overrideCapiUrl",St=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oL=e=>{if(typeof e!="string")return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&!t.username&&!t.password&&!t.search&&!t.hash&&/^\/v1\/copilot\/[^/]+\/ark_[A-Za-z0-9_-]{20,512}\/?$/.test(t.pathname)}catch{return!1}},Ak=e=>{let t=e[Ks];if(!St(t)||!oL(t[yl]))return{next:e,removed:!1};let n={...t};delete n[yl];let r={...e};return Object.keys(n).length>0?r[Ks]=n:delete r[Ks],{next:r,removed:!0}},Gs="anyray-default",js=()=>{let e=(process.env.ANYRAY_COPILOT_MODEL??"").split(",").map(t=>t.trim()).filter(t=>t.length>0&&t.length<=200&&!/[\u0000-\u001f\u007f]/.test(t)).filter((t,n,r)=>r.indexOf(t)===n).slice(0,64);return e.length?e:[Gs]},vk=e=>e===Gs?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),ml=async e=>{if(!await R(e))return{kind:"missing"};try{let t=await bk(e,"utf-8");if(!t.trim())return{kind:"array",entries:[]};let n=JSON.parse(t);return Array.isArray(n)?{kind:"array",entries:n}:{kind:"unrecognized"}}catch{return{kind:"unrecognized"}}},Sk=async(e,t)=>{await qP(nL(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${tL()}`;try{await eL(n,`${JSON.stringify(t,null,2)}
111
- `,{flag:"wx",mode:384}),await he(n,e),await zP(e,384)}finally{await QP(n,{force:!0}).catch(()=>{})}},sf=e=>{if(!St(e))return!1;let t=e,n=Object.keys(t).sort(),r=["apiType",...t.apiKey===void 0?[]:["apiKey"],"models","name","vendor"].sort();return n.length!==r.length||!n.every((o,a)=>o===r[a])||t.name!==wr||t.vendor!=="customendpoint"||t.apiType!=="chat-completions"||!(t.apiKey===void 0||typeof t.apiKey=="string"&&t.apiKey.length>0&&t.apiKey.length<=512&&!/[\u0000-\u001f\u007f]/.test(t.apiKey))||!Array.isArray(t.models)||t.models.length===0||t.models.length>64?!1:t.models.every(o=>{if(!St(o))return!1;let a=["id","maxInputTokens","maxOutputTokens","name",...o.requestHeaders===void 0?[]:["requestHeaders"],"toolCalling","url","vision"].sort(),s=Object.keys(o).sort();if(s.length!==a.length||!s.every((i,c)=>i===a[c])||typeof o.id!="string"||o.id.length===0||o.id.length>200||o.name!==vk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!St(o.requestHeaders)||Object.keys(o.requestHeaders).length!==1||typeof o.requestHeaders["x-anyray-metadata"]!="string"||o.requestHeaders["x-anyray-metadata"].length>8192))return!1;try{let i=new URL(o.url);return(i.protocol==="https:"||i.protocol==="http:")&&!i.username&&!i.password&&!i.search&&!i.hash&&i.pathname==="/v1/chat/completions"}catch{return!1}})},cf=e=>{let t=e.filter(n=>!sf(n));return{next:t,removed:t.length!==e.length}},aL=async(e,t)=>{let n=Hs(e),r=await ml(n);if(r.kind==="missing")return{changedFiles:[],messages:[],manual:!1};if(r.kind==="unrecognized")return{changedFiles:[],manual:!0,messages:[`Could not recognize ${n}; left it untouched. Remove the legacy "${wr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=cf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${wr}" Custom Endpoint from ${n}.`]};try{return await Sk(n,o),await ae(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${wr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${wr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},sL=async e=>{try{let t=yr(await bk(e,"utf-8"));if(St(t))return Ak(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Ks}.${yl} in ${e}, which uses JSONC that Connect will not rewrite; remove it manually.`]}:{changedFiles:[],messages:[],manual:!1}}catch{}return{changedFiles:[],manual:!0,messages:[`Could not parse ${e}; remove an old Anyray ${Ks}.${yl} value manually if present.`]}},Ek=async(e,t)=>{let n=rL(e),r;try{r=await U(n)}catch{return sL(n)}let{next:o,removed:a}=Ak(r);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the retired Anyray Copilot debug override from ${n}.`]};try{return await J(n,o,{backup:!1}),await ae(n),{changedFiles:[n],manual:!1,messages:[`Removed the retired Anyray Copilot debug override from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the retired Anyray Copilot debug override from ${n}; remove it manually.`]}}},iL=async(e,t)=>{let n=await aL(e,t),r=await Ek(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},Ik=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,Ck]}},xk=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},Rk=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),cL=e=>Array.isArray(e.args)&&e.args.at(-1)===Ck,Ok=(e,t)=>{if(!t.hookBinaryIsDurable()||!St(e)||!xk(e,["type","command","args"]))return!1;let n=Ik(t);return e.type==="stdio"&&e.command===n.command&&Rk(e.args,n.args)},lL=(e,t)=>{if(!St(e)||!xk(e,["type","command","args"])||e.type!=="stdio"||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(i=>typeof i=="string"))return!1;let n=t.mcpServerCommand("profile");if(e.command===n.command&&Rk(e.args,n.args))return!0;if(je(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===or&&r.at(-1)==="profile"))return!1;let a=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(a))return r.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(a)||r.length!==3)return!1;let s=r[0].replaceAll("\\","/");return!je(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},lf=(e,t)=>Ok(e,t)?"exact":St(e)&&cL(e)||lL(e,t)?"stale-owned":"foreign",yk=e=>`MCP name conflict in ${e}: servers.${wn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,dL=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let p of a)try{let h=await U(p);if(i){if("servers"in h&&!St(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${p} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let y=St(h.servers)?{...h.servers}:{},b=Ik(o),A=y[wn],v=A===void 0?void 0:lf(A,o);if(v==="exact"){d+=1;continue}if(v==="foreign"){u=!0,l.push(yk(p));continue}if(t){d+=1;continue}y[wn]=b,f.push({path:p,next:{...h,servers:y},backup:v!=="stale-owned",clearBackupAfter:!1});continue}if(!St(h.servers)||!(wn in h.servers))continue;if(lf(h.servers[wn],o)==="foreign"){u=!0,l.push(yk(p));continue}if(t)continue;let w={...h.servers};delete w[wn];let g={...h};Object.keys(w).length===0?delete g.servers:g.servers=w,f.push({path:p,next:g,backup:!1,clearBackupAfter:!0})}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let p of f)try{await J(p.path,p.next,p.backup?{}:{backup:!1}),p.clearBackupAfter&&await ae(p.path),c.push(p.path),i&&(d+=1)}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p.path} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`);break}return i?l.unshift(t?d===a.length?`Would register the Anyray retrieval MCP server in ${a.length} VS Code user profile config(s).`:`Would register the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); resolve the conflicts below first.`:d===a.length?`Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) in ${a.length} VS Code user profile config(s).`:`Registered the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); see the profile-specific errors below.`):n?l.unshift(t?`Would skip the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary.`:`Skipped the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary; removed any stale owned registration. Re-run via the installer or a global install to enable retrieval.`):l.unshift(`${t?"Would skip":"Skipped"} the Anyray retrieval MCP server because this VS Code build predates profile-scoped mcp.json support (${Iw}+).`),{changedFiles:c,messages:l,manual:u}},uL=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await R(c))try{let l=await U(c);if(!St(l.servers)||!(wn in l.servers)||lf(l.servers[wn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[wn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await J(c,u,{backup:!1}),await ae(c),a.push(c)}catch{}return t&&i>0?s.push(`would remove the Anyray retrieval MCP server from ${i} VS Code user profile config(s)`):a.length>0&&s.push("Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."),{changedFiles:a,messages:s,manual:!1}},_k=e=>[...e.installed.length>0?[`Also installed into ${e.installed.length} additional VS Code profile(s): ${e.installed.join(", ")}. Config is shared through SecretStorage \u2014 no further steps.`]:[],...e.failed.length>0?[`Couldn\u2019t install into profile(s): ${e.failed.join(", ")}. Open VS Code with that profile and use \u201CApply Extension to all Profiles\u201D, or re-run anyray-connect.`]:[]],Tk=()=>`${ie} is already installed and configured for this gateway \u2014 skipped the VSIX reinstall and the VS Code URI confirmation prompt. (Run --revert first to force re-delivery.)`,gk=e=>[`${ie} mirrors the GitHub Copilot models available to this VS Code install.`,`Gateway: ${e.origin} (client key stored by VS Code SecretStorage).`,"Mode: SUBSCRIPTION \u2014 requests use your existing Copilot sign-in and model; Anyray supplies a supported before-request optimization provider.","Inline completions remain native GitHub Copilot traffic. Choose an \u201CAnyray \xB7 \u2026\u201D model in Chat for optimized requests.",'Copilot\u2019s internal utility models (chat titles, summaries) keep working with an Anyray main model: the extension sets VS Code\u2019s chat.byokUtilityModelDefault to "copilot" unless you already set it yourself.',"VS Code profiles scope extensions; Connect installs the provider into every profile registered at apply time. A profile created later needs a Connect re-run (or VS Code\u2019s \u201CApply Extension to all Profiles\u201D action).","Copilot Business/Enterprise administrators must allow language-model providers in GitHub\u2019s Bring Your Own Language Model Key policy."],Pk=(e,t,n,r)=>({runMcp:o=>dL(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):iL(e,o)}),Lk=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${ie} VSIX${a}. Nothing was configured. Run \`${n?"code":t.toLowerCase()} --install-extension\` by hand on that VSIX to see the full error.`;case"handoff-undeliverable":return n?`Installed ${ie} and staged its configuration, but could not hand it over${a}. A remote VS Code server's command-line launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\`. Reload the VS Code window attached to this machine (Developer: Reload Window): the extension applies the staged configuration as it loads, so there is nothing to re-run.`:`Installed ${ie} and staged its configuration, but could not hand it to ${t}${a}. Reload ${t} (quit and reopen): the extension applies the staged configuration as it loads, so there is nothing to re-run.`;case"reload-required":return`A newer ${ie} build was installed, but ${t} is still running the previous build. Reload VS Code completely \u2014 the new build applies the staged configuration as it loads, so there is nothing to re-run.`;case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher on this machine. Run anyray-connect from the integrated terminal of the VS Code window attached here (Terminal \u2192 New Terminal in that window) \u2014 a plain SSH shell has no "code" on PATH and cannot hand the key to a running window. No VS Code configuration was written.`:`The ${t} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`;case"unsupported-version":return`The Anyray language-model provider requires VS Code ${hp} or newer. Upgrade ${t}, then re-run anyray-connect; no extension configuration was written.`;case"unsafe-gateway":return"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.";case"extension-missing":return`This anyray-connect installation is missing its bundled ${ie} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${ie} installed and VS Code accepted the ${r}, but its extension host never confirmed. Reload the VS Code window attached to this machine (Developer: Reload Window): the staged configuration applies as it loads.`:`${ie} installed and ${t} accepted the ${r}, but its extension host never confirmed. Reload ${t} completely (quit and reopen): the staged configuration applies as it loads.`;default:return n?`VS Code did not confirm the one-time ${ie} ${r}${a}. The configuration is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension applies it as it loads.`:`VS Code did not confirm the one-time ${ie} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},pL=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${ie} still holds its SecretStorage configuration`;switch(e){case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher, so Anyray could not ask ${ie} to clear its SecretStorage configuration. Re-run revert from the integrated terminal of the VS Code window attached to this machine.`:`The ${t} command-line launcher was not found, so Anyray could not ask ${ie} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${ie} reset to VS Code${o}, so ${a} until it reloads. A remote VS Code server's launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\` \u2014 but the reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`Could not hand the ${ie} reset to ${t}${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;case"activation-timeout":return n?`VS Code accepted the ${ie} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`${t} accepted the ${ie} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;default:return n?`VS Code did not confirm the ${ie} reset${o}, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`VS Code did not confirm the ${ie} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},fL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Pk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${ie} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...gk(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${ie}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"copilot-seat"});if(!d.ok)return{status:"manual",messages:[Lk(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[Tk()]:[],...gk(t),...d.alreadyCurrent?[]:_k(d.profiles),...f.messages,...u.messages]}},wk=e=>[`${ie} exposes the configured Anyray gateway models without writing a key to chatLanguageModels.json.`,`Gateway: ${e.origin} (personal client key and attribution stored together in VS Code SecretStorage).`,"Mode: API KEY \u2014 the extension streams normal /v1/chat/completions requests through Anyray. Text chat only: the models register without tool calling (the OpenAI bridge cannot carry VS Code's structured tool results).",`Models in the picker: ${js().join(", ")}.`,"Inline GitHub Copilot completions remain native GitHub traffic; choose an Anyray model in Chat for gateway-routed requests.",'Copilot\u2019s internal utility models (chat titles, summaries) follow the selected Anyray model: the extension sets VS Code\u2019s chat.byokUtilityModelDefault to "mainAgent" unless you already set it yourself.',"VS Code profiles scope extensions; Connect installs the provider into every profile registered at apply time. A profile created later needs a Connect re-run (or VS Code\u2019s \u201CApply Extension to all Profiles\u201D action).","Copilot Business/Enterprise administrators must allow language-model providers in GitHub\u2019s Bring Your Own Language Model Key policy."],hL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Pk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${ie} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...wk(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${ie}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:js().map(p=>({id:p,name:vk(p)}))});if(!d.ok)return{status:"manual",messages:[Lk(d.reason,e,a,"gateway API configuration",d.detail)]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[Tk()]:[],...wk(t),...d.alreadyCurrent?[]:_k(d.profiles),...f.messages,...u.messages]}},mL=async(e,t,n)=>{let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null};let o=[];for(let s of r){if(!await R(s))return{registered:!1,command:null};try{let i=await U(s),c=St(i.servers)?i.servers[wn]:void 0;if(!Ok(c,n))return{registered:!1,command:null};o.push(c.command)}catch{return{registered:!1,command:null}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var yL=async(e={installedVariant:Fc,remoteServerVariant:gp,isRemoteDevContext:jr})=>{let t=await e.installedVariant();if(t)return{variant:t,remote:!1};if(!e.isRemoteDevContext())return{remote:!1};let n=await e.remoteServerVariant();return n?{variant:n,remote:!0}:{remote:!1}},gL={installedVariant:Fc,remoteServerVariant:gp,detectVscodeLmProviderEligibility:Lw,configureVscodeExtension:pk,vscodeExtensionPointsAt:mk,vscodeExtensionAwaitingReload:fk,vscodeExtensionReceiptMode:hk,hookBinaryIsDurable:le,hookBinaryPath:Oe,mcpServerCommand:Ve,vscodeUserMcpConfigPaths:Tw,isRemoteDevContext:jr},wL=(e={})=>{let t={...gL,...e},n=()=>yL(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Us,quitTarget:pl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Jo(r,!0)}`:Hs(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!xe(r.clientKey))return{status:"manual",messages:["Enrollment required: Copilot setup needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; no VS Code configuration was written."]};let{variant:a,remote:s}=await n();if(!a)return{status:"manual",messages:[t.isRemoteDevContext()?"No VS Code server found here yet \u2014 this looks like a dev container, Codespace, or SSH remote. `--tools copilot` now configures the Anyray provider directly in a remote VS Code window, but only after VS Code has attached to this machine and installed its server. Open this machine with the VS Code Remote-SSH (or Dev Containers) extension, then re-run anyray-connect --tools copilot in that window\u2019s integrated terminal. To route this shell through Anyray without the Copilot UI, use an in-container tool instead: anyray-connect --tools opencode --sso <link> --subscription.":"No VS Code install found. Install VS Code, then re-run anyray-connect; the personal key will be transferred directly into SecretStorage."]};let i=await t.detectVscodeLmProviderEligibility(a);if(i.status==="needs-update")return{status:"manual",messages:[`${a} ${i.version??""} cannot expose public third-party models in Chat's picker. Upgrade to VS Code ${hp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||xw(i.version);return X(r,"copilot")?fL(a,r,o,t.configureVscodeExtension,c,s,t):hL(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?mL(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ws(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await ml(Hs(o));if(s.kind==="array"){let c=s.entries.find(sf)?.models?.[0]?.url;if(typeof c=="string"&&new URL(c).origin===a)return!0}return!1},async routingExpected(r){if(r.includes("copilot"))return!0;let{variant:o}=await n();return o?(await t.detectVscodeLmProviderEligibility(o)).status!=="needs-update":!1},async routingPendingReload(){let{variant:r}=await n();return r?t.vscodeExtensionAwaitingReload(r):!1},async inferenceAuthLanes(){try{let{variant:r}=await n();if(!r)return["unknown"];let o=await ml(Hs(r));if(o.kind==="array"&&o.entries.some(sf))return["api_key"];let a=await t.vscodeExtensionReceiptMode(r);if(a==="copilot-seat")return["subscription"];if(a==="gateway-api")return["api_key"]}catch{}return["unknown"]},async revert(r){let{variant:o,remote:a}=await n();if(!o)return{status:"not-found",messages:["no VS Code install found \u2014 nothing to revert"]};let s=await uL(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await Ek(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${ie} to clear its global configuration and SecretStorage key`);else{let y=await t.configureVscodeExtension(o,void 0,"reset");y.ok?(c=!0,d=y.receipt,u.push(`Cleared ${ie} gateway configuration and secret.`)):(l=!0,u.push(pL(y.reason,o,a,y.detail)))}let f=Hs(o),p=await ml(f),h=p.kind==="missing"||p.kind==="array"&&!cf(p.entries).removed,m=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),h)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:m.length?m:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:m.length?m:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:m,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(p.kind==="unrecognized")return{status:"manual",changedFiles:m.length?m:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${wr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=cf(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${wr} Custom Endpoint from ${f}`]};await Sk(f,w);let g=[...u,`Removed the ${wr} Custom Endpoint from ${f}.`];return await ae(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},Dk=wL();import{accessSync as BL,constants as jk,statSync as WL}from"node:fs";import{readFile as Vk,rm as Ys}from"node:fs/promises";import{homedir as bf,platform as Qk}from"node:os";import{delimiter as HL,join as kf,resolve as KL}from"node:path";import{execFile as vL}from"node:child_process";import{readFile as SL}from"node:fs/promises";import{homedir as pf,platform as EL}from"node:os";import{join as Vs}from"node:path";import{join as bL}from"node:path";var df="Iv1.b507a08c87ecfe98",kL="https://github.com/login/device/code",CL="https://github.com/login/oauth/access_token",AL="read:user",Nk=1e4,ta=()=>bL(Q(),"copilot-seat-login.json"),$k={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},uf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Mk=async(e={})=>{let t={...$k,...e};try{let n=await t.fetch(kL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:df,scope:AL}),signal:AbortSignal.timeout(Nk)});if(!n.ok)return;let r=await n.json();if(!uf(r))return;let o=r.device_code,a=r.user_code,s=r.verification_uri;if(typeof o!="string"||typeof a!="string"||typeof s!="string")return;let i=r.interval,c=r.expires_in;return{deviceCode:o,userCode:a,verificationUri:s,intervalSeconds:typeof i=="number"&&i>0?i:5,expiresInSeconds:typeof c=="number"&&c>0?c:900}}catch{return}},Fk=async(e,t={})=>{let n={...$k,...t},r=n.now()+e.expiresInSeconds*1e3,o=e.intervalSeconds*1e3;for(;n.now()<r;){await n.sleep(o);try{let s=await(await n.fetch(CL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:df,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(Nk)})).json();if(!uf(s))continue;let i=s.access_token;if(typeof i=="string"&&i.length>0)return{status:"ok",token:i};let c=s.error;if(c==="authorization_pending")continue;if(c==="slow_down"){let l=s.interval;o=(typeof l=="number"&&l>0?l:o/1e3+5)*1e3;continue}return c==="access_denied"?{status:"denied"}:c==="expired_token"?{status:"expired"}:{status:"failed"}}catch{continue}}return{status:"expired"}},Uk=async(e,t)=>{let n=ta();return await pe(n,`${JSON.stringify({token:e,clientId:df,mintedAtIso:t},null,2)}
112
- `),n},gl=async()=>{try{let e=await U(ta());if(!uf(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var IL=5e3,ff=5e3,xL=["copilot-cli","CopilotCLI"],RL="https://api.github.com/copilot_internal/user",Wk="~/.copilot/config.json",Hk="macOS Keychain (Copilot CLI)",Kk=e=>e===Wk||e===Hk,na=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),nn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),OL=()=>process.env.XDG_CONFIG_HOME?.trim()||Vs(pf(),".config"),_L=()=>process.env.XDG_DATA_HOME?.trim()||Vs(pf(),".local","share"),TL=async()=>{try{let e=await SL(Vs(pf(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return na(t)?t:void 0}catch{}},PL=async e=>{try{let t=await U(Vs(OL(),"github-copilot",e));if(!nn(t))return;for(let n of Object.values(t))if(nn(n)&&na(n.oauth_token))return n.oauth_token}catch{}},LL=async()=>{try{let e=await U(Vs(_L(),"opencode","auth.json")),t=nn(e)?e["github-copilot"]:void 0;if(!nn(t)||t.type!=="oauth")return;if(na(t.access))return t.access;if(na(t.refresh))return t.refresh}catch{}},DL=(e,t)=>new Promise((n,r)=>{try{vL(e,[...t],{timeout:IL},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),NL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return na(r)?r:void 0}catch{return}},$L=async(e=DL)=>{for(let t of xL){let n=await NL(t,e);if(n)return n}};var wl={env:process.env,platform:EL,tokenFromDeviceLogin:gl,tokenFromCopilotCliConfig:TL,tokenFromSharedConfig:PL,tokenFromOpenCode:LL,tokenFromKeychain:$L,fetch:(...e)=>fetch(...e)},ML=new Set([401,403,404]),Gk=/^[a-z][a-z0-9-]{0,30}$/,FL=e=>e!=="default"&&Gk.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",UL=e=>typeof e!="string"?"default":/^https:\/\/api\.([a-z][a-z0-9-]{0,30})\.githubcopilot\.com\/?$/.exec(e.trim())?.[1]??"default",hf=async(e,t={})=>{let n={...wl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),ff);try{let a=await n.fetch(RL,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=nn(i)&&nn(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:UL(s)}}return{verdict:ML.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var ra=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${Gk.test(n)?n:"default"}/header/models`,a=await Bk(o,e,r.clientKey,t);if(a.length>0)return a}return Bk(`${FL(n)}/models`,e,void 0,t)},Bk=async(e,t,n,r={})=>{let o={...wl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),ff);try{let i=await o.fetch(e,{headers:{authorization:`Bearer ${t}`,...n?{"x-anyray-api-key":n}:{}},signal:a.signal});if(!i.ok)return[];let c=await i.json(),l=nn(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!nn(u))continue;let f=u.id;if(typeof f!="string"||f.length===0||u.model_picker_enabled!==!0)continue;let p=u.policy;if(nn(p)&&p.state!=="enabled")continue;let h=u.supported_endpoints,m=Array.isArray(h)?h.filter(E=>typeof E=="string"):[],w=u.capabilities,g=nn(w)?w.limits:void 0,y=E=>{let I=nn(g)?g[E]:void 0;return typeof I=="number"&&Number.isFinite(I)&&I>0?Math.floor(I):void 0},b={id:f,endpoints:m},A=y("max_prompt_tokens"),v=y("max_output_tokens");A!==void 0&&(b.maxPromptTokens=A),v!==void 0&&(b.maxOutputTokens=v),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},bl=async(e,t,n,r={})=>{let o={...wl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),ff);try{let i=/\/responses\/?$/.test(new URL(e).pathname),c=await o.fetch(e,{method:"POST",headers:{...t,"content-type":"application/json"},body:JSON.stringify(i?{model:n,max_output_tokens:16,input:"ping"}:{model:n,max_tokens:1,messages:[{role:"user",content:"ping"}]}),signal:a.signal});return c.ok?"ok":c.status===400||c.status===404||c.status===422?"rejected":"unreachable"}catch{return"unreachable"}finally{clearTimeout(s)}},kl=async(e={},t={})=>{let n={...wl,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return na(a)?a:void 0}},{source:"~/.config/github-copilot/apps.json",read:()=>n.tokenFromSharedConfig("apps.json")},{source:"~/.config/github-copilot/hosts.json",read:()=>n.tokenFromSharedConfig("hosts.json")},{source:"OpenCode github-copilot login",read:()=>n.tokenFromOpenCode()},{source:"Anyray Copilot sign-in (device login)",read:()=>n.tokenFromDeviceLogin()},...e.allowKeychainPrompt===!0&&n.platform()==="darwin"?[{source:Hk,read:()=>n.tokenFromKeychain()}]:[],{source:Wk,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await hf(s,t);if(i.verdict==="no-copilot"){o.push(a.source);continue}return{token:{token:s,source:a.source},rejected:o,capiSegment:i.capiSegment}}return{rejected:o}};var ro="copilot-cli",bn="copilot-cli",GL=Us,jL=()=>GL()?["VS Code is open \u2014 its Copilot CLI runs inside the extension host, which","captured your shell environment when the editor launched. Restart VS Code,","or its CLI chat and Autopilot sessions stay on native GitHub traffic and","never reach the gateway (no spend, no traces) even though this block is set."]:[],eC=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],Cf=()=>Object.fromEntries(eC.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),mf=()=>kf(bf(),".anyray","copilot-cli.sh"),tC="# Managed by anyray-connect. Do not source this file anywhere else.",Yk=e=>e.split(/\r?\n/,1)[0]===tC,VL=["COPILOT_PROVIDER_TYPE","COPILOT_PROVIDER_BASE_URL","COPILOT_PROVIDER_WIRE_API","COPILOT_PROVIDER_HEADERS","COPILOT_MODEL","COPILOT_PROVIDER_MAX_PROMPT_TOKENS","COPILOT_PROVIDER_MAX_OUTPUT_TOKENS","COPILOT_PROVIDER_API_KEY"],Cl="COPILOT_PROVIDER_API_KEY",Zk=e=>e.startsWith(`export ${Cl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Nn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",YL=()=>js()[0],Zs=(e="default")=>`/copilot/${e}/header`,kq=Zs(),to=e=>e.replace(/\/+$/,""),ZL=(e,t="default")=>`${to(e.openaiBaseUrl)}${Zs(t)}`,yf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),wf="claude-sonnet-5",JL=()=>{let e=js()[0];return e===Gs?wf:e},nC=e=>e.endpoints.includes(Nn(e.id)==="responses"?"/responses":"/chat/completions"),Af=e=>{let t=e.filter(nC),n=a=>{let s=/^claude-sonnet-(\d+(?:\.\d+)*)$/.exec(a);return s?s[1].split(".").map(Number):void 0},r=t.map(a=>({m:a,version:n(a.id)})).filter(a=>!!a.version).sort((a,s)=>Jk(a.version,s.version)?-1:Jk(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var Jk=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n+=1){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r>0}return!1},Xk=(e,t,n,r,o,a="default")=>{let s=de({...e.metadata,tool:ro}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...eC];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(ZL(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Nn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...o?.maxPromptTokens?[`export COPILOT_PROVIDER_MAX_PROMPT_TOKENS='${o.maxPromptTokens}'`]:[],...o?.maxOutputTokens?[`export COPILOT_PROVIDER_MAX_OUTPUT_TOKENS='${o.maxOutputTokens}'`]:[],...i.length>0?[`export COPILOT_PROVIDER_HEADERS=${ve(i.join(`
113
- `))}`]:[],`export ${Cl}=${ve(n)}`]},gf=(e,t,n)=>{let r=de({...e.metadata,tool:ro});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Nn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${ve(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${Cl}=${ve(n)}`]:[]]},XL=(e,t)=>t||!X(e,"copilot"),zk=()=>{let e=VL.filter(t=>(process.env[t]??"")!=="");return e.length===0?[]:[`This shell still exports ${e.join(", ")} \u2014 Copilot CLI keeps using BYOK until you`,`run \`unset ${e.join(" ")}\` or open a new terminal (fully quit a long-lived parent app).`]},qk=(e,t=[])=>["Left on native GitHub Copilot inference \u2014 a Copilot seat was detected, but no","Copilot sign-in Connect can read. To route the CLI through Anyray with billing","KEPT on your Copilot plan, give Connect a seat token and re-run:",...e==="darwin"?[" - run `copilot` once and `/login` (macOS Keychain; read on",` \`anyray-connect --tools ${ro}\`), or`]:[" - run `copilot` once and `/login` (say YES to storing credentials locally),"," then re-run \u2014 Connect reads the sign-in left in ~/.copilot/ or"," ~/.config/github-copilot/ on any run, with no extra flag, or"]," - set COPILOT_GITHUB_TOKEN to a Copilot OAuth token, or sign into"," OpenCode\u2019s github-copilot provider.",...t.length>0?[`GitHub rejected the sign-in Connect did find (${t.join(", ")}):`,"it is expired, or its account holds no Copilot seat. Sign in again."]:[],"To route on org API billing instead (replaces seat inference), re-run with `--org`."],zL=(e=process.env.PATH,t=Qk())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(HL)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=KL(o,n);try{if(!WL(a).isFile())continue;return BL(a,t==="win32"?jk.F_OK:jk.X_OK),a}catch{}}},qL=()=>kf(bf(),".copilot","config.json"),Dn=()=>kf(bf(),".copilot","mcp-config.json"),no="anyray",QL=()=>({type:"local",...Ve("profile"),tools:["*"]}),br=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eD=async()=>{let e=Dn(),t;try{t=await U(e)}catch{return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because ${e} could not be parsed; it was left unchanged.`}}if("mcpServers"in t&&!br(t.mcpServers))return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because mcpServers in ${e} is not an object; it was left unchanged.`};let r=(br(t.mcpServers)?t.mcpServers:{})[no];return r!==void 0&&!zt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${no} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},tD=async e=>{let t=Dn(),n=e.json,r=br(n.mcpServers)?n.mcpServers:{};r[no]=QL(),n.mcpServers=r,await J(t,n)},nD=async()=>{let e=Dn(),t;try{let r=await U(e);if(!br(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!br(n)||!(no in n)||!zt(n[no],"profile")?!1:(delete n[no],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Ys(e,{force:!0}):await J(e,t,{backup:!1}),await ae(e),!0)},rD={resolveCopilotCommand:zL,platform:Qk,detectCopilotSeat:wp,discoverSeatToken:kl,readDeviceLoginToken:gl,fetchSeatModelCatalog:ra,probeSeatChatModel:bl},oD=e=>`'${e.replace(/'/g,"''")}'`,aD=e=>e.split(`
114
- `).map(oD).join(" + [Environment]::NewLine + "),sD=(e={})=>{let t={...rD,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await zc(At(),bn))?.find(c=>c.startsWith("export COPILOT_PROVIDER_BASE_URL="));if(i)return i.slice(i.indexOf("=")+1).replace(/^'|'$/g,"")},o=(s,i)=>s!==void 0&&to(s)===`${to(i)}/v1`,a=(s,i)=>s!==void 0&&yf(s)&&to(s).startsWith(`${to(i)}/v1/copilot/`);return{id:ro,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Us,quitTarget:pl},async usesDynamicCredential(s){let i=await r();return a(i,s)||!o(i,s)?!1:!await R(mf())},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=qL();return await R(i)?{installed:!0,detail:i}:{installed:!1,detail:"no `copilot` on PATH and no ~/.copilot state"}},async apply(s,i){let c=At(),l=async(E,I,C)=>{let x=E.filter(Zk),T=E.filter(De=>!Zk(De)),$=mf(),Y=[...T,...x.length>0?[`[ -r ${ve($)} ] && . ${ve($)}`]:[]],Z=await R($),W=Z?await Vk($,"utf8"):void 0,z=W===void 0||Yk(W);if(x.length>0&&!z)return{status:"manual",messages:[`Refused to overwrite user-managed ${$}; move or rename that file, then run Connect again.`]};let me=le(),Le=me?await eD():void 0,ne=[`${c} \u2190 managed Anyray block (${bn})`,...I.map(De=>` ${De}`),...x.length>0?[`${$} \u2190 owner-only credential (mode 0600)`]:["No key exported \u2014 the local refresh daemon injects a freshly minted","key per request, so a running CLI session never carries a stale one."],...C,Le?.status==="skipped"?Le.message:me?`${Dn()} \u2190 Anyray retrieval MCP server (anyray_retrieve / anyray_recall)`:`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable retrieval.`,"Inline `copilot` completions and GitHub-hosted features stay native GitHub traffic.",`Run \`source ${c}\` or open a new terminal to apply.`,...jL()];if(i.dryRun)return{status:"configured",messages:ne};let Ke=!1;Le?.status==="installable"&&(await tD(Le),Ke=!0);try{x.length>0?await pe($,[tC,...x,""].join(`
115
- `)):Z&&z&&await Ys($,{force:!0}),await Xc(c,Y,bn)}catch(De){try{W!==void 0&&z?await pe($,W):z&&await Ys($,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw De}return{status:"configured",messages:ne,changedFiles:[c,...x.length>0||Z&&z?[$]:[],...Ke?[Dn()]:[]]}},d=await r(),u=d!==void 0&&!yf(d),f=s.authMode==="placeholder",p=u&&!s.viaLocalProxy,h=u&&(!p||!X(s,"copilot")),m=f?void 0:await t.readDeviceLoginToken().catch(()=>{}),w=f||h&&!m?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),g=w.token,y=w.rejected;if(g){let E=w.capiSegment??"default",I=JL(),C=I!==wf||!!process.env.ANYRAY_COPILOT_MODEL,x=await t.fetchSeatModelCatalog(g.token,{},E,{laneOrigin:to(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),T=x.find(ne=>ne.id===I);if(!C){let ne=Af(x);if(T=ne[0],!i.dryRun&&ne.length>0){let Ke=H=>`${to(s.origin)}/v1${Zs(E)}/${Nn(H)==="responses"?"responses":"chat/completions"}`,De={...Cf(),authorization:`Bearer ${g.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},O=new Set,P;for(let H of ne.slice(0,4)){let fe=await t.probeSeatChatModel(Ke(H.id),De,H.id);if(fe==="ok"){P=H;break}if(fe==="unreachable")break;O.add(H.id)}T=P??ne.find(H=>!O.has(H.id))??ne[0]}I=T?.id??wf}let $=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,Y=$&&s.clientKey?Mt($):$,Z=Xk(s,I,g.token,$,T,E),W=Xk(s,I,Mt(g.token),Y,T,E),z=Nn(I),me=x.filter(ne=>nC(ne)&&Nn(ne.id)===z).map(ne=>ne.id).filter(ne=>ne!==I),Le=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${g.source}).`,`Model: ${I}${C?" (pinned via ANYRAY_COPILOT_MODEL)":x.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...x.length===0&&Kk(g.source)?["GitHub served no current models for this sign-in \u2014 the Copilot CLI's own login is","entitled to legacy models only. Fix it with: `anyray-connect copilot-login`","(one browser step), then re-run this command."]:[],...me.length>0?[`Your plan also serves: ${me.slice(0,8).join(", ")}${me.length>8?", \u2026":""} \u2014 switch anytime with \`copilot --model <id>\`.`]:[]];return n()?{status:"manual",messages:["Windows: run these in PowerShell (persists user env), then restart your terminal \u2014",...W.map(ne=>{let Ke=ne.indexOf("="),De=ne.slice(7,Ke),O=ne.slice(Ke+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${De}', ${aD(O)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${g.source}, and the gateway key from \`anyray-connect print-key\`.)`,...Le]}:l(Z,W,Le)}if(!XL(s,h)){if(p&&!i.dryRun){let E=At();if(await Rs(E,bn))return{status:"reverted",changedFiles:[E],messages:[`removed a stale Anyray ${bn} block from ${E}`,"It routed the CLI on ORG API billing, which predates the Copilot","seat lane and is not a lane you chose. Nothing replaces it yet:",...qk(t.platform(),y),...zk()]}}return{status:"held",messages:[...p&&i.dryRun?[`would remove a stale Anyray ${bn} block from ${At()} (org lane, not chosen)`]:[],...qk(t.platform(),y)]}}let b=YL(),A=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,v=A&&s.clientKey?Mt(A):A;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...gf(s,b,v).map(E=>{let[I,...C]=E.replace(/^export /,"").split("=");return` setx ${I} "${C.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${Cl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(gf(s,b,A),gf(s,b,v),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===Gs?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=At(),c=mf(),l=await R(c),d=l?Yk(await Vk(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${bn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Dn()} if registered`,...await R(ta())?[`would remove the Copilot sign-in Connect minted (${ta()})`]:[]]};let u=await Rs(i,bn);d&&await Ys(c,{force:!0});let f=await nD(),p=ta(),h=await R(p);h&&await Ys(p,{force:!0});let m=[...u?[i]:[],...d?[c]:[],...f?[Dn()]:[],...h?[p]:[]];return{status:m.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${bn} block from ${i}`:`no Anyray ${bn} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...h?[`removed the Copilot sign-in Connect minted (${p})`]:[],...f?[`removed the Anyray MCP server from ${Dn()}`]:[],...zk()],changedFiles:m.length>0?m:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){try{let s=await U(Dn()),i=br(s)?s.mcpServers:void 0,c=br(i)?i[no]:void 0;return!br(c)||!zt(c,"profile")?{registered:!1,command:null}:{registered:!0,command:typeof c.command=="string"?c.command:null}}catch{return{registered:!1,command:null}}},async inferenceAuthLanes(){try{let s=await r();return s===void 0?["native"]:yf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(ro)?!0:!await t.detectCopilotSeat()}}},rC=sD();import{homedir as uC}from"node:os";import{join as Cr}from"node:path";import{constants as lD,chmod as dD,copyFile as uD,readFile as Sl}from"node:fs/promises";import{applyEdits as pD,modify as fD}from"jsonc-parser";import{readFile as oC,rm as iD}from"node:fs/promises";var aC="// Managed by anyray-connect: OpenCode trim carrier v1",cD=5e3,vf=e=>`${aC}
102
+ `).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");ob(o?.slice(1).map(Number))},sP=(e,t)=>{let n=z_(rb(nP(),"anyray-cursor-"));try{let o=[".bail on",".timeout 5000","BEGIN IMMEDIATE;",...t.map((a,s)=>{if(a.value===void 0)return`DELETE FROM ItemTable WHERE key=${el(a.key)};`;let i=rb(n,`value-${s}`);return eP(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${el(a.key)}, CAST(readfile(${el(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
103
+ `);tl("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:$p,stdio:["pipe","ignore","pipe"]})}finally{try{Q_(n,{recursive:!0,force:!0})}catch{}}},iP={kind:"sqlite3-cli",readItem:(e,t)=>sb(e,t),checkpointWal:e=>ib(e),mutateRows:sP},cP=()=>{try{let t=tP(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Np=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},lP=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),dP=e=>({kind:"node-sqlite",readItem:(t,n)=>Np(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:lP(o.value)}),checkpointWal:t=>Np(e,t,n=>{let r=n.prepare("PRAGMA wal_checkpoint(TRUNCATE);").get(),o=[r?.busy,r?.log,r?.checkpointed].map(a=>typeof a=="bigint"?Number(a):a);ob(o)}),mutateRows:(t,n)=>Np(e,t,r=>{r.exec("BEGIN IMMEDIATE;");try{for(let o of n)o.value===void 0?r.prepare("DELETE FROM ItemTable WHERE key = ?").run(o.key):r.prepare("INSERT INTO ItemTable(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(o.key,o.value);r.exec("COMMIT;")}catch(o){try{r.exec("ROLLBACK;")}catch{}throw o}})}),Qc,Ls=()=>{if(Qc!==void 0)return Qc;let e=cP();return Qc=e?dP(e):ab()?iP:null,Qc};import{spawn as uP}from"node:child_process";import{randomUUID as cb}from"node:crypto";import{constants as lb}from"node:fs";import{chmod as pP,copyFile as db,mkdir as fP,readdir as hP,readFile as mP,rename as yP,rm as Ds,writeFile as gP}from"node:fs/promises";import{join as Mp}from"node:path";var Fp=/^[a-z0-9][a-z0-9-]{0,31}$/,wP=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,ub=/^[a-z0-9][a-z0-9-]{0,31}$/,bP=/^[0-9TZ:.+-]{1,40}$/,Up=()=>Mp(Q(),"pending"),rl=e=>{if(!Fp.test(e)||wP.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Mp(Up(),`${e}.json`)},pb=()=>Mp(Q(),"cursor-pending.json"),kP=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),CP=(e,t)=>{if(!kP(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Fp.test(n)||typeof e.op!="string"||!ub.test(e.op)||typeof e.requestedAt!="string"||!bP.test(e.requestedAt)||Number.isNaN(Date.parse(e.requestedAt))))return{version:1,adapter:n,op:e.op,requestedAt:e.requestedAt,watcherPid:typeof e.watcherPid=="number"&&Number.isSafeInteger(e.watcherPid)&&e.watcherPid>0?e.watcherPid:void 0,...typeof e.generation=="string"&&e.generation?{generation:e.generation}:{}}},Bp=async(e,t)=>{try{return CP(JSON.parse(await mP(e,"utf-8")),t)}catch{return}},fb=async()=>{let e=pb(),t=await Bp(e,"cursor");if(!t)return;let n=!1;try{await hb(),await db(e,rl("cursor"),lb.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await Ds(e,{force:!0})}catch{}return t},ol=async e=>{let t=await Bp(rl(e),e);return t||(e==="cursor"?fb():void 0)},hr=async()=>{let e;try{e=await hP(Up())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Fp.test(r))continue;let o=await ol(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await fb();n&&t.push(n)}return t},hb=async()=>{await kt();let e=Up();await fP(e,{recursive:!0,mode:448});try{await pP(e,448)}catch{}},nl=async e=>{await hb();let t=rl(e.adapter),n=`${t}.${process.pid}.tmp`;await gP(n,`${JSON.stringify(e)}
104
+ `,{mode:384}),await he(n,t)},AP=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,mr=async(e,t)=>await Wp(e,t)==="claimed",Wp=async(e,t)=>{let n=rl(e);if(t){let o=`${n}.${process.pid}.${cb()}.claimed`;try{await yP(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Bp(o,e);if(a&&AP(a,t))return await Ds(o,{force:!0}),"claimed";let s=!1;try{await db(o,n,lb.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await Ds(o,{force:!0})}return"superseded"}let r=!1;try{await Ds(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await Ds(pb(),{force:!0})}catch{}return r?"claimed":"absent"},yr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},vP=e=>{let{command:t,args:n}=fn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},SP=e=>{let{exe:t,args:n}=vP(e),r=uP(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},mb=SP;var yb=async()=>{let e=[],t;try{t=await hr()}catch{return e}for(let n of t)if(!yr(n.watcherPid))try{let r=mb(n.adapter);if(!r)continue;await nl({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},Ns=async(e,t)=>{if(!ub.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await ol(e),r=new Date().toISOString(),o=cb();if(n&&yr(n.watcherPid))return await nl({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await nl({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=mb(e)}catch{a=void 0}return a&&await nl({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as EP,spawnSync as wb}from"node:child_process";import{existsSync as al}from"node:fs";import{homedir as xP,platform as gr}from"node:os";import{join as bb,win32 as gb}from"node:path";var kb=(e,t={})=>{let n=t.env??process.env,r=t.exists??al,o=(t.home??xP)(),a={localAppData:n.LOCALAPPDATA??gb.join(o,"AppData","Local"),programFiles:n.ProgramFiles,programFilesX86:n["ProgramFiles(x86)"]};for(let s of e.win32Install??[]){let i=a[s.root];if(!i)continue;let c=gb.join(i,s.path);if(r(c))return c}},Jr=/^[A-Za-z0-9 ._-]{1,64}$/,IP=/^[A-Za-z0-9.-]{1,128}$/,sl=e=>e.darwinBundleId&&IP.test(e.darwinBundleId)?e.darwinBundleId:void 0,Cb=(e,t=gr())=>t==="darwin"?sl(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",Ab=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",vb=(e,t=gr(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return kb(e,r)!==void 0;let o=e.linuxProcess;return!o||!Jr.test(o)?!1:n.split(":").filter(Boolean).some(a=>al(bb(a,o)))},Sb=(e,t=gr())=>{if(t==="darwin"&&sl(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Jr.test(n))},Eb=1e4,$s=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=bb(t,"System32",e);return al(n)?n:e},OP=e=>{let t=`/usr/bin/${e}`;return al(t)?t:e},RP=(e,t)=>{try{let n=wb(e,t,{encoding:"utf-8",timeout:Eb,windowsHide:!0,...gr()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:gr()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},_P=e=>new Promise(t=>setTimeout(t,e)),xb=(e,t={})=>{let n=t.runtimePlatform??gr(),r=t.run??RP;if(n==="darwin"){let a=sl(e);if(a&&r("/usr/bin/osascript",["-e",`if application id "${a}" is running then tell application id "${a}" to quit`]))return!0;let s=e.darwinAppName;return!s||!Jr.test(s)?!1:r("/usr/bin/osascript",["-e",`if application "${s}" is running then tell application "${s}" to quit`])}if(n==="win32"){let a=e.win32Image;return!a||!Jr.test(a)?!1:r($s("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Jr.test(o)?!1:r(OP("pkill"),["-TERM","-o","-x",o])},Ib=async(e,t=2e4,n={})=>{let r=n.sleep??_P,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},PP=(e,t,n={})=>{let r=gr();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=wb(e,t,{stdio:"ignore",timeout:Eb,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=EP(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},Ob=(e,t={})=>{let n=t.runtimePlatform??gr(),r=t.launch??PP;if(n==="darwin"){let a=sl(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Jr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=kb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Jr.test(o)?!1:r(o,[])};var WP={darwinAppName:"Cursor",darwinBundleId:"com.todesktop.230313mzl4w4u92",win32Image:"Cursor.exe",linuxProcess:"cursor",win32Install:[{root:"localAppData",path:"Programs\\cursor\\Cursor.exe"},{root:"programFiles",path:"cursor\\Cursor.exe"},{root:"programFilesX86",path:"cursor\\Cursor.exe"}]},HP=e=>e==="apply"||e==="native"||e==="revert",Mb=()=>Ye("Cursor"),qr=()=>ea(Mb(),"User","globalStorage","state.vscdb"),Fs=()=>`${qr()}.anyray-bak.json`,Qo=()=>`${qr()}.anyray-bak`,qe="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",ct="cursorAuth/openAIKey";var Gp="/seat/cursor",Jp="Prefer the anyray_search and anyray_read tools over the built-in codebase search and file read. anyray_search returns relevance-filtered matches; anyray_read returns the pertinent slice of a file plus a retrieve handle you can pass to anyray_retrieve to recover any elided detail. Use them when finding or reading code.",Ms=ea(".cursor","rules","anyray.mdc"),Fb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",KP=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",Fb,"",Jp,""].join(`
105
+ `),GP=e=>{let t=BP(e);for(;;){if(Se(ea(t,".git")))return t;let n=$b(t);if(n===t)return null;t=n}},jP=e=>e.authMode!=="placeholder",en=()=>ea(Nb(),".cursor","hooks.json"),tn=()=>ea(Nb(),".cursor","mcp.json"),Mt="anyray",Ub="--anyray-owner=cursor-v1",VP="postToolUse",YP="beforeSubmitPrompt",Rb="preToolUse",ZP="^MCP:",XP="UserPromptSubmit",JP="Shell",qP="^(Read|Grep)$",ul="--anyray-owner=cursor-hook-v1",zr=[{event:VP,flag:Je,trailingArgs:["cursor"],matcher:ZP},{event:YP,flag:or,trailingArgs:[],matcher:XP},{event:Rb,flag:Bg,trailingArgs:[],matcher:JP},{event:Rb,flag:Wg,trailingArgs:[],matcher:qP}];var _b={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},zP=(e,t,n)=>TP(e,t,n),Pb=zP,QP,eT=()=>{let e=QP??UP();if(e==="win32"){let t=Pb($s("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],_b);return t.error||t.signal||t.status!==0?!0:/(?:^|\r?\n)"Cursor\.exe",/iu.test(t.stdout??"")}for(let t of e==="linux"?["cursor","Cursor"]:["Cursor"]){let n=Pb("pgrep",["-x",t],_b);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},tT=eT,ll=()=>tT();var nT=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,qe)??null,openAIKey:e.readItem(n,ct)??null,lastWritten:r};Xp(t,`${JSON.stringify(o,null,2)}
106
+ `,{encoding:"utf-8",flag:"wx",mode:384})},Bb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Xp(n,`${JSON.stringify(t,null,2)}
107
+ `,{encoding:"utf-8",flag:"wx",mode:384});try{FP(n,e)}catch(r){throw mn(n,{force:!0}),r}},rT=(e,t)=>{let n=qo(e);Bb(e,{...n,lastWritten:t})},oe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Tb=e=>oe(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),qo=e=>{let t=Db(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(oe(n)&&(Object.keys(n).length===2||Object.keys(n).length===3)&&Object.prototype.hasOwnProperty.call(n,"applicationUser")&&Object.prototype.hasOwnProperty.call(n,"openAIKey")&&(typeof n.applicationUser=="string"||n.applicationUser===null)&&(typeof n.openAIKey=="string"||n.openAIKey===null)&&(n.lastWritten===void 0||oe(n.lastWritten)&&Object.keys(n.lastWritten).length===2&&typeof n.lastWritten.applicationUser=="string"&&typeof n.lastWritten.openAIKey=="string"))return{applicationUser:n.applicationUser,openAIKey:n.openAIKey,...n.lastWritten?{lastWritten:{applicationUser:n.lastWritten.applicationUser,openAIKey:n.lastWritten.openAIKey}}:{}};if(!oe(n)||n.version!==1||!oe(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[qe],o=n.rows[ct];if(!Tb(r)||!Tb(o))throw new Error("Cursor value backup is missing an exact managed row");return{applicationUser:r.exists?r.value:null,openAIKey:o.exists?o.value:null}},Lb=e=>{let t=Buffer.alloc(16),n=$P(e,"r");try{return MP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{LP(n)}},oT=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return oe(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Wb=e=>{let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".lan")||t.endsWith(".internal")||t.endsWith(".home")||!t.includes(".")&&Hp(t)===0||t==="0.0.0.0")return!0;if(Hp(t)===4){let[n,r,o]=t.split(".").map(Number);return n===10||n===0||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===192&&r===0&&(o===0||o===2)||n===198&&(r===18||r===19)||n===198&&r===51&&o===100||n===203&&r===0&&o===113||n>=224}if(Hp(t)===6){let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return Wb(`${r>>>8}.${r&255}.${o>>>8}.${o&255}`)}return t==="::"||t==="::1"||t.startsWith("fc")||t.startsWith("fd")?!0:/^fe[89a-f]/.test(t)}return!1},jp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Wb(t.hostname)}catch{return!1}},aT=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},sT=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Xe(e.origin)}/v1${Gp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Gp}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),zo=(e,t=!1)=>[...t?[`Cursor's server-side BYOK lane bypasses the local key-refresh proxy and points directly at ${e.openaiBaseUrl}.`]:[],"Route capability: only custom-model requests Cursor actually sends to its OpenAI BYOK endpoint. Cursor's Agent wire behavior varies by release; native Team models, Tab, indexing, and other first-party traffic stay on Cursor-hosted services.","Billing: this lane bills as an Anyray subscription seat \u2014 each distinct attributed developer with usage in a month is one seat. Attribution rides your per-user ark_ key (Cursor sends no metadata header), so enroll each developer with their own key."],Hb=()=>{let e=qr();if(!Se(e))return"clear";let t=Ls();if(!t)return"unverifiable";let n;try{n=t.readItem(e,qe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return oe(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},iT=(e,t)=>{if(!jp(e))return{routed:!1,problem:"gateway-not-public-https"};let n=qr();if(!Se(n))return{routed:!1,problem:"state-db-missing"};let r=Ls();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,qe),a=r.readItem(n,ct)}catch{return{routed:!1,problem:"state-db-unreadable"}}if(o===void 0)return{routed:!1,problem:"settings-missing"};let s;try{s=JSON.parse(o)}catch{return{routed:!1,problem:"settings-malformed"}}if(!oe(s))return{routed:!1,problem:"settings-malformed"};let i=`${Xe(e)}/v1${Gp}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!xe(a)||!xe(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},cT=(e,t=[])=>({command:Tt(e,[...t,ul])}),qp=(e,t,n)=>{if(!oe(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Tt(t,[...n,ul])||r===Tt(t,n)||r.endsWith(` ${ul}`)&&r.includes(` ${t} `)},lT=(e,t)=>oe(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Kb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(qp(a,t,n)){r=!0;continue}if(!oe(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!lT(c,t));if(s.length===a.hooks.length){o.push(a);continue}r=!0;let i=Object.keys(a).every(c=>c==="matcher"||c==="hooks");s.length===0&&i||o.push({...a,hooks:s})}return{entries:o,changed:r}},zp=(e,t)=>{let n=e[t];if(n===void 0)return[];if(!Array.isArray(n))throw new Error(`Cursor hook event ${t} is not an array`);return n},Gb=(e,t,n,r,o)=>oe(e.hooks)&&zp(e.hooks,t).some(a=>oe(a)&&a.matcher===o&&qp(a,n,r)),dT=(e,t,n,r,o)=>oe(e.hooks)&&zp(e.hooks,t).some(a=>oe(a)&&a.matcher===o&&qp(a,n,r)&&kc(a.command,n,[...r,ul])),jb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!oe(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=oe(e.hooks)?{...e.hooks}:{},{entries:s}=Kb(zp(a,t),n,r);return s.push({...cT(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},uT=(e,t,n,r=[])=>{if(!oe(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Kb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},pT=async()=>{let e=en();if(!le()){let t=await Yb();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await U(e);for(let n of zr)t=jb(t,n.event,n.flag,n.trailingArgs,n.matcher);return await X(e,t),{changedFiles:[e],messages:[`Installed Cursor global hooks in ${e} (postToolUse trims oversized MCP tool outputs; preToolUse trims recognized Shell command output and redirects bulky built-in Read/Grep to Anyray's context tools; beforeSubmitPrompt beacons oversized pasted-data prompts). Cursor hook cache/tee persistence is disabled; gateway request logs and savings/spend rows remain metadata-only, while trace decision content follows the deployment's ANYRAY_CONTENT_MODE.`],complete:!0}}catch{return{changedFiles:[],messages:[`Could not install Cursor hooks in ${e}. Chat can still route through Anyray, but hook-based trimming/beacons are unavailable until this is fixed.`],complete:!1}}},dl=()=>{let e=Ve("profile");return{command:e.command,args:[...e.args,Ub]}},Vp=e=>oe(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===dl().command&&e.args.length===dl().args.length&&e.args.every((t,n)=>t===dl().args[n]),fT=e=>{if(!oe(e)||Object.keys(e).some(o=>o!=="command"&&o!=="args")||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(o=>typeof o=="string")||je(e.command))return!1;let t=e.args;if(t.at(-2)!==sr||t.at(-1)!=="profile")return!1;let n=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(n))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(n)||t.length!==3)return!1;let r=t[0].replaceAll("\\","/");return!je(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},pl=e=>oe(e)&&Array.isArray(e.args)&&e.args.at(-1)===Ub||fT(e),hT=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,mT=async()=>{if(!le())return Vb();let e=tn();try{let t=await U(e);if(t.mcpServers!==void 0&&!oe(t.mcpServers))throw new Error("mcpServers is not an object");let n=oe(t.mcpServers)?{...t.mcpServers}:{},r=n[Mt];return r!==void 0&&!pl(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Mt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Mt]=dl(),await X(e,{...t,mcpServers:n}),{changedFiles:[e],messages:[`Registered the Anyray retrieval MCP server (anyray_retrieve) in ${e} for explicit recovery of stashed context.`],complete:!0})}catch{return{changedFiles:[],messages:[`Could not register the Anyray MCP server in ${e}; retrieval via anyray_retrieve is unavailable until this is fixed.`],complete:!1}}},Vb=async()=>{let e=tn();if(!await O(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await U(e);if(!oe(t.mcpServers)||!(Mt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!pl(t.mcpServers[Mt]))return{changedFiles:[],messages:[`Preserved the foreign ${Mt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Mt];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await X(e,r,{backup:!1}),{changedFiles:[e],messages:["Removed the Anyray retrieval MCP server (anyray_retrieve)."],complete:!0}}catch{return{changedFiles:[],messages:[`Could not remove the Anyray MCP server from ${e}; the registration was left in place.`],complete:!1}}},Yb=async()=>{let e=en();if(!await O(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await U(e),n=t;for(let r of zr)n=uT(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await X(e,n,{backup:!1}),{changedFiles:[e],messages:["Removed Cursor global Anyray hooks."],complete:!0})}catch{return{changedFiles:[],messages:[`Could not remove Cursor hooks from ${e}; the hooks were left in place.`],complete:!1}}},yT=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=GP(e);if(!n)return t;let r=ea(n,Ms),o=KP();try{if(Se(r)){let a=Db(r,"utf8");if(a===o)return t;if(!a.includes(Fb))return{...t,messages:[`Left ${Ms} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Jp}"`]}}return NP($b(r),{recursive:!0}),Xp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Ms} so Cursor agents in this repo default to Anyray's tools (that is what produces gateway traces \u2014 Cursor's built-in search and read never reach Anyray). Commit it to share with the team.`],complete:!0}}catch{return{...t,messages:[`Could not write ${Ms} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Zb=async()=>{let e=await pT(),t=await mT(),n=await yT();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Yp=async()=>{let e=await Yb(),t=await Vb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Xb=async()=>{if(!le()){let e=await Yp();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${Oe()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await U(en());for(let r of zr)e=jb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await U(tn());if(t.mcpServers!==void 0&&!oe(t.mcpServers))throw new Error("mcpServers is not an object");let n=oe(t.mcpServers)?t.mcpServers[Mt]:void 0;return n!==void 0&&!pl(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${tn()} already contains a foreign ${Mt} MCP registration. Rename or remove that entry explicitly, then re-run Connect.`],complete:!1}:{changedFiles:[],messages:[],complete:!0}}catch{return{changedFiles:[],messages:[`Cursor routing was not changed because its hook or MCP configuration could not be validated safely. Repair ${en()} and ${tn()}, then re-run Connect.`],complete:!1}}},gT=async()=>{if(!le())return!1;try{let e=await U(en());if(!oe(e.hooks)||!zr.every(r=>Gb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await U(tn()),n=oe(t.mcpServers)?t.mcpServers[Mt]:void 0;return Vp(n)}catch{return!1}},Jb=["openAIBaseUrl","useOpenAIKey"],Us=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!oe(t))throw new Error("Cursor application-user settings are not an object");return t},wT=(e,t,n)=>{let r=Us(e),o=Us(t??void 0),a=n===void 0?void 0:Us(n),s={...r},i=[];for(let c of Jb){let l=Object.prototype.hasOwnProperty.call(r,c),d=a!==void 0&&Object.prototype.hasOwnProperty.call(a,c);if(a===void 0||l!==d||l&&!Object.is(r[c],a[c])){i.push(c);continue}Object.prototype.hasOwnProperty.call(o,c)?s[c]=o[c]:delete s[c]}return{mutation:Object.keys(s).length===0?{key:qe}:{key:qe,value:JSON.stringify(s)},conflicts:i}},Kp=(e,t)=>{let n=Us(e),r=Us(t??void 0),o={...n};for(let a of Jb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:qe}:{key:qe,value:JSON.stringify(o)}},il=e=>typeof e=="string"&&e.startsWith("ark_"),cl=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);oe(o)&&(n=o)}catch{}let r=il(t)||n!==null&&(il(n.useOpenAIKey)||il(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,il(o.openAIKey)&&delete o.openAIKey,{applicationUser:Object.keys(o).length===0?null:JSON.stringify(o),openAIKey:null}}if(Object.prototype.hasOwnProperty.call(n,"useOpenAIKey")&&typeof n.useOpenAIKey!="boolean"){let o={...n};return delete o.useOpenAIKey,{applicationUser:Object.keys(o).length===0?null:JSON.stringify(o),openAIKey:t}}return{applicationUser:e,openAIKey:t}},it=(e,t)=>{if(!e.clientKey)return[...t?[t]:[],"Enrollment required: Cursor needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; do not save a placeholder Custom Endpoint.",...zo(e)];let n=de(e.metadata);return[...t?[t]:[],"Configure Cursor by hand: Cursor \u2192 Settings \u2192 Models \u2192 OpenAI API Key:",` \u2022 Override OpenAI Base URL: ${e.openaiBaseUrl}`," \u2022 API key: run `anyray-connect print-key` and paste the returned personal gateway key (the key is not shown here).",n?` \u2022 Cursor has no custom-header field, so attribution rides your per-user key, not ${n}.`:" \u2022 (No attribution metadata resolved; set --user, or use --enroll for a per-user key.)","This is Cursor's OpenAI-BYOK lane: usage counts toward your Anyray subscription seat, but the upstream still needs a provider API key. It does not consume the native Cursor Team entitlement; exact custom-model Agent compatibility varies by Cursor release.",...zo(e)]},Zp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!le())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await Ns("cursor",e)}catch{return n}return{status:"queued",messages:[`Cursor is running \u2014 ${o} queued. It completes automatically the next time Cursor fully quits; relaunch Cursor afterwards to pick it up.`,a.alreadyWatching?"A queue watcher was already waiting; it will run the latest queued operation.":a.watcherPid?"A background watcher is now waiting for Cursor to quit.":"The queue was saved, but a background watcher could not be started; the next Connect run will service it.",...r]}},bT=async(e,t)=>{if(!xe(e.clientKey))return{status:"manual",messages:["Cursor native subscription mode was not changed: a valid personal ark_ gateway key is required for Anyray hooks and MCP retrieval."]};if(!t.dryRun&&!t.preservePendingOp)try{await mr("cursor")}catch{return{status:"manual",messages:["Cursor native subscription mode was not changed because Connect could not cancel Cursor's stale queued operation. Repair the owner-only ~/.anyray cursor queue and re-run."]}}let n=await Xb();if(!n.complete)return{status:"manual",messages:n.messages};let r=Se(Fs())||Se(Qo());if(r&&ll())return Zp("native",t,{status:"manual",messages:["Cursor is running \u2014 fully quit it and re-run so Connect can restore the journaled BYOK override before enabling native subscription mode."]},["No native Claude/Opus request will be redirected: the queued operation restores Cursor\u2019s prior settings, then installs only Anyray hooks/MCP."]);if(!r){let c=Hb();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Se(Qo())?Qo():Fs()}, then install Anyray's local hooks and retrieval MCP server.`:`Would leave Cursor's native Team sign-in and model route unchanged, install global hooks in ${en()}, and register the Anyray retrieval MCP server in ${tn()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Bs.revert({dryRun:!1,preservePendingOp:!0}),o.status!=="reverted"))return{...o,messages:[...o.messages,"Cursor native subscription mode was not reported active because the prior BYOK route could not be restored safely."]};let a=await Zb(),s=[];if(!t.preservePendingOp)try{await mr("cursor")}catch{s.push("Could not clear Cursor's stale queue marker.")}return{status:a.complete&&s.length===0?"configured":"manual",changedFiles:[...new Set([...o?.changedFiles??[],...a.changedFiles])],messages:[...o?.messages??[],"Kept Cursor's native Team sign-in and Claude/Opus model route; no Anyray OpenAI override or model credential was written.",...a.messages,...s,"Claude/Opus inference remains Cursor-hosted and will not produce gateway inference traces. Anyray records content-free hook savings only when a supported oversized Shell/MCP result is actually reduced.",`Make it seamless org-wide: paste this into Cursor's dashboard Team Rules and mark it Required, so every member's agent uses Anyray's tools without being asked -- "${Jp}" (connect already writes ${Ms} when run inside a repo, which covers that repo once committed; see docs/integrations/cursor.md).`,"Restart Cursor so its MCP registration is loaded; hooks.json itself is watched and reloads automatically."]}},Bs={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>ll(),quitTarget:WP,needsTarget:e=>e!=="revert",async complete(e,t,n){return HP(e)?e!=="revert"&&t?Bs.apply(t,n):Bs.revert(n):{status:"manual",messages:[`Cursor could not service a queued "${e}" operation it does not recognise; the queue entry was dropped.`]}}},async detect(){let e=Mb(),t=Se(e);return{installed:t,detail:t?qr():"Cursor user dir not found"}},async watchPaths(){return[en(),tn()]},async mcpStatus(){let e=tn();if(!await O(e))return{registered:!1,command:null};try{let t=await U(e),n=oe(t.mcpServers)?t.mcpServers[Mt]:void 0;return Vp(n)?{registered:!0,command:hT(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=en();if(!await O(n))e="missing";else try{let s=await U(n);if(s.hooks===void 0)e="missing";else if(!oe(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(zr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=zr.every(c=>Gb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=zr.every(c=>dT(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=tn();if(!await O(a))r="missing";else try{let s=await U(a);if(s.mcpServers===void 0)r="missing";else if(!oe(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Mt];r=i===void 0?"missing":pl(i)?"owned":"foreign",r==="owned"&&(o=Vp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Br()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await D();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(jP(e))return bT(e,t);let n=sT(e),r=aT(e.openaiBaseUrl),o=qr(),a=Fs(),s=Qo();if(!xe(e.clientKey))return{status:"manual",messages:it(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let i={changedFiles:[],messages:[],complete:!0},c=y=>{let b=y.status==="configured"&&!i.complete;return{...y,status:b?"manual":y.status,changedFiles:[...y.changedFiles??[],...i.changedFiles],messages:[...y.messages,...i.messages,...b?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!jp(n.openaiBaseUrl))return c({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach loopback/LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect. No proxy, DNS, certificate, or interception workaround is installed.",...zo(n)]});let l=await Xb();if(!l.complete)return{status:"manual",messages:l.messages};let d=Ls();if(!d)return c({status:"manual",messages:it(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Se(o))return c({status:"manual",messages:it(n,`No Cursor state DB at ${o} (open Cursor once first).`)});let u=null,f;if(Se(s)){if(Se(a))return c({status:"manual",messages:it(n,`Both a legacy Cursor Anyray backup (${s}) and a current value backup (${a}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{Lb(s)?u="sqlite":(qo(s),u="value")}catch{u=null}if(!u)return c({status:"manual",messages:it(n,`Legacy Cursor Anyray backup at ${s} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(Se(a))try{p=qo(a)}catch{return c({status:"manual",messages:it(n,`Existing Cursor backup at ${a} is invalid \u2014 refusing to write or replace recovery data.`)})}if(ll())return c(await Zp("apply",t,{status:"manual",messages:it(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...zo(n,r),...u?[`The legacy Anyray backup at ${s} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...u?[`Would migrate the legacy Anyray backup at ${s}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${o}, ${Se(a)?`retain the original value backup at ${a}`:`create a mode-0600 value backup at ${a}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${en()}, and register the Anyray retrieval MCP server in ${tn()}.`,...zo(n,r)]};if(u){try{d.checkpointWal(o)}catch(b){return c({status:"manual",messages:it(n,`Couldn't checkpoint Cursor's state DB at ${o} while migrating the legacy Anyray backup at ${s}${Ts(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=cl(d.readItem(s,qe)??null,d.readItem(s,ct)??null);else{let b=qo(s);y=cl(b.applicationUser,b.openAIKey)}}catch{return c({status:"manual",messages:it(n,`Couldn't read the legacy Anyray backup at ${s} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{d.mutateRows(o,[Kp(d.readItem(o,qe),y.applicationUser),y.openAIKey===null?{key:ct}:{key:ct,value:y.openAIKey}])}catch{return c({status:"manual",messages:it(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${s} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{mn(s,{force:!0}),mn(`${s}-wal`,{force:!0}),mn(`${s}-shm`,{force:!0}),f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held and removed it.`}catch{f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{d.checkpointWal(o)}catch(y){return c({status:"manual",messages:it(n,`Couldn't checkpoint Cursor's state DB at ${o}${Ts(y)} \u2014 refusing to write; set it by hand:`)})}let h;try{h=d.readItem(o,qe)}catch{return c({status:"manual",messages:it(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=oT(h,n);if(!m)return c({status:"manual",messages:it(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let w={applicationUser:m.value,openAIKey:e.clientKey};if(Se(a))try{rT(a,w)}catch{return c({status:"manual",messages:it(n,`Couldn't update three-way ownership in the protected Cursor backup at ${a} \u2014 refusing to write; set it by hand:`)})}else try{nT(d,a,o,w)}catch{return c({status:"manual",messages:it(n,`Couldn't create the protected Cursor value backup at ${a} \u2014 refusing to write; set it by hand:`)})}try{d.mutateRows(o,[{key:qe,value:m.value},{key:ct,value:e.clientKey}])}catch{let y=!0;if(p)try{Bb(a,p)}catch{y=!1}return c({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${a}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${a} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}i=await Zb();let g=[];if(!t.preservePendingOp)try{await mr("cursor")}catch{g.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return c({status:"configured",changedFiles:[o],messages:[...f?[f]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${a}).`,"Stored the API key in Cursor's credential row (not shown here).",...g,...zo(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await D().catch(()=>{}),n=e;if(!jp(n)){let o=t&&rt(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&Xe(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Se(Fs())||Se(Qo())||Hb()!=="clear"?!1:gT():iT(n,r).routed},async revert(e){let t=qr(),n=Fs(),r=Qo(),o=Se(n),a=Se(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${en()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${en()} and unregister its owned retrieval MCP server.`]};if((o||a)&&ll()){if(e.fullRevert){let h=await Yp(),m=!0;try{await mr("cursor")}catch{m=!1}return{status:"manual",changedFiles:h.changedFiles,messages:[...h.messages,...m?[]:["Could not clear Cursor's stale queue marker."],`Cursor is running, so its saved settings in ${a?r:n} were left in place and nothing was queued. Quit Cursor and re-run --revert to restore them.`]}}return Zp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Ls(),i=!1,c=!1,l,d=[];if(a)try{if(Lb(r))if(Se(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let h=cl(s.readItem(r,qe)??null,s.readItem(r,ct)??null);s.mutateRows(t,[Kp(s.readItem(t,qe),h.applicationUser),h.openAIKey===null?{key:ct}:{key:ct,value:h.openAIKey}]),c=!0}else i=!0,DP(r,t),mn(`${t}-wal`,{force:!0}),mn(`${t}-shm`,{force:!0});else{let h=qo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let m=cl(h.applicationUser,h.openAIKey);s.mutateRows(t,[Kp(s.readItem(t,qe),m.applicationUser),m.openAIKey===null?{key:ct}:{key:ct,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${Ts(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=qo(n)}catch{return{status:"manual",messages:[`Couldn't read a supported Cursor value backup from ${n}; the backup was retained.`]}}if(l){if(!l.lastWritten)return{status:"manual",messages:[`The Cursor backup at ${n} predates three-way ownership, so Connect cannot prove which current values are still its own. The backup was retained and no hook or MCP cleanup was attempted.`]};if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let h=wT(s.readItem(t,qe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,ct);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:ct}:{key:ct,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${Ts(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{mn(r,{force:!0}),mn(`${r}-wal`,{force:!0}),mn(`${r}-shm`,{force:!0}),mn(n,{force:!0})}catch{f=!1,u.push("Cursor values were restored, but a recovery sidecar could not be removed; retain it until a later revert can finish cleanup.")}if(!e.preservePendingOp)try{await mr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await Yp();return f=f&&p.complete,{status:f?"reverted":"manual",changedFiles:[...o||a?[t]:[],...p.changedFiles],messages:[i?"Restored Cursor's state DB from the legacy Anyray backup.":c?"Restored Cursor's managed settings fields and credential from the legacy Anyray backup while preserving current unrelated settings and rows.":l?"Restored Cursor's managed settings fields and credential from the Anyray backup while preserving current unrelated settings.":"No Cursor row backup was present; only owned hook and MCP integrations were considered for cleanup.",...u,...d.length>0?[`Preserved Cursor values changed after Connect configured them: ${[...new Set(d)].join(", ")}.`]:[],...p.messages,"Restart Cursor."]}}};import{chmod as nL,mkdir as rL,readFile as kk,rm as oL,writeFile as aL}from"node:fs/promises";import{randomUUID as sL}from"node:crypto";import{dirname as iL,join as Ck}from"node:path";var kT=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
108
+ `;)r+=1;r-=1;continue}if(o==="/"&&e[r+1]==="*"){let a=e.indexOf("*/",r+2);r=a===-1?e.length:a+1,t+=" ";continue}t+=o}return t},CT=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o===","){let a=r+1;for(;a<e.length&&/\s/.test(e[a]);)a+=1;if(e[a]==="}"||e[a]==="]")continue}t+=o}return t},yn=e=>JSON.parse(CT(kT(e)));import{spawnSync as AT}from"node:child_process";import{platform as vT}from"node:os";var qb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},ST=(e,t,n)=>AT(e,t,n),zb=ST,ET,xT=()=>{let e=ET??vT();if(e==="win32"){let n=zb($s("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],qb);return n.error||n.signal||n.status!==0?!0:/(?:^|\r?\n)"Code\.exe",/iu.test(n.stdout??"")}let t=e==="linux"?[["-f","Visual Studio Code"],["-x","code"]]:[["-f","Visual Studio Code"]];for(let[n,r]of t){let o=zb("pgrep",[n,r],qb);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},IT=xT,Ws=()=>IT();var fl={darwinAppName:"Visual Studio Code",darwinBundleId:"com.microsoft.VSCode",win32Image:"Code.exe",linuxProcess:"code",win32Install:[{root:"localAppData",path:"Programs\\Microsoft VS Code\\Code.exe"},{root:"programFiles",path:"Microsoft VS Code\\Code.exe"},{root:"programFilesX86",path:"Microsoft VS Code\\Code.exe"}]};import{execFile as OT}from"node:child_process";import{readdirSync as RT,statSync as _T}from"node:fs";import{createHash as rk,randomBytes as PT,randomUUID as ok}from"node:crypto";import{chmod as TT,lstat as nf,mkdir as rf,readdir as ak,readFile as wn,rm as sk,unlink as ml,writeFile as of}from"node:fs/promises";import{homedir as ta,platform as af}from"node:os";import{dirname as Qp,join as vt,posix as ek,win32 as LT}from"node:path";import{promisify as DT}from"node:util";var gn="0.1.25";var wr="ea7f1b82becbd0f6d1f5df2f4fdb43a6be23001baedc417d11e38e68496602c4",hl="e9214937212c52226c55db7b1b952f688bb57de03b17e6aa7fcc48feb66b8e9a",Qb="UEsDBBQAAAgIADKJDV1C224VCAMAALQJAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1W224bNxB9tr+CYIE+RUvLQIHCXW0gKHYiVAoUyPVjgRE5Wk1NkQSHK0v5+mB3dbOStpEd5G2XM3MO58JD5m/XSytWGJm868ludiUFOu0NubInqzTv/C7fFpcX+QT0I5Q4Bkdz5CQediHX2VUdtF5axz25SCncKMV6gUvgbEk6evbzlGm/VAZXaH3AqFa87rQ+6vqq292G35gXAHQMMpWuxSkuLy7yMSYwkKD+uciHBl2itBEjcGUFJfYkus5fUymGpifBbSJsOivW3qA8ZHWVdbPr36SYVDNLvMC4c5VCtbjviIOFzUdYYtFvTGLuo3iYioE3mKtjexuArCOFRN7V6d5wAI09GSIyxhXKom+MwHWwpCmJLWQJCZ9gI5beoGXh49bQeYoQAhox8IGsT4Kr2QF+650W0VflYrenXyF4/oOFn89JE1hhtxXpNP4iRL8ig1H0J8MsV0f7bRO4h5KL5zGcq2a1sQ8gYekjIRf94Zsx6AU5FCOE6MiVuTqyN/7vwVqMmztbIzSF1rl6tli7Na6TWHc97UL3C5umieP9kDwQV2CnqTLkszrn7NaV5OrOgq2wJ//uZt3rZsrV2UjrhK6ejncY0Bl0mpD3wK8BrM/WDwH6k5zZAz35+NjM2JuKXgA68hosfUazOzevy9XBzKLpB6pDPIP9BtzZaaOuEvKgPbotWIoVvgBwinFFGjkbkXvkbOqrqA+gtSjxjVIlpUU1a6SoVYMPn9TSOx8x+KykdF5hTjjfY+IEMaH5ybyUPlSzn8s5rULwMZ1Fqoi5qqfwFbyNGJ3F+ktEMMuTkXoBf1vlOwsrH9GMIT4a/+S+PbbnIQ+8S+hSNomkyZV7yLuIKFVx+XzbuTrR0nxEGh1jgTsVUaPh4Pbj9DZL65SrnXmrxbk6vl7zoeME1sLhljheuYdYYvq/gyybtHN1ipUfC23r02fGtN138y3uNwH/WyZ2TxYpJpAWPXnIM7Rvmuwf9k6KvjERmWudet6P72H6qhvbsn1NelTcf+fM1T7TXJ08vYovUEsDBBQAAAgIADKJDV3fow3fvAAAAGUBAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH3QMW7DMAwF0D2nELjHdDsUQWE7Q9ob9AKEQjtKJUowGUO9feFkC+rO/O9/gN2xpugWnjVk6eGlacGx+HwOMvVws3F/gOOw675+CqurKYr2cDEr74jqL5xIm1xYaopjnhOZNnmesJD/ponxtW3f0GcxFtvb2gFD98Ej3aK5z2osj93mquBOj9w61QOVEoMnC1nwSgupn0MxwC2e5b+C9bxBrdqTNK6GJVLYNIuGmkjCyPonrimuFO9fG3a/UEsDBBQACAgIACeJDV0AAAAAAAAAAAAAAAAWAAAAZXh0ZW5zaW9uL3BhY2thZ2UuanNvbnVU227bMAx9z1cQfhmw1XKSrrvkaUXXYcXWoUN3eVg7QJFYm6sjCRKdJij674NkxU6H7sk2zyF5ePP9BKAwcoXFAgpptl5uy3VQVmNxECFNwbVy+yUzjhMDbqyHH5dwMtIwKE+OyZpE0xpw41pSxJB9asl4J7ewshrbANZnoLzz0jnUcGIdtZYhdMsh2I7Njbdd3eySPgtgb25IkWyhlabuZI1looLzdk0aPRxfnIle3Bp9yMKmYibmR73ZeVpLjmWx77A3dcuWQoN+7EbPbUmhCakF52ffeptHZwOx9dtiAfcTAICCty6RauJEAig632bLi4bZhUVV1cRNtxTKrqo+ycev1coaGyOKPVdNHlVOUPRTKXHDaFI5E4CHJARNTQbDqCIPcAHF75mYzWdiOpKVZKytp8T/1fOPz3YZz6VqyCB8RukNmTr6XSe/laTUQVFpClwNMsSf0LdjsHwio8fYd9bfBicVDv2gMaiSTi6pJaZ9+Z1h3wVG/XPnO4IAReics55R58kl+8NQoFQc50rWnK7R8F6Z1lyy9Ny5D2TilPVOkjXf/b4qa9jTsuN9Ubs1O49bdtJIvsiLNiaAQWNaOqPtv3uUsSePqsj4Q3peD/X0t7CnZNlRG2svjNUIGNK3WOU5xC2W6lbWuFgH2uTNQchGKEtjS40OjUajCAOUpe0YHt2+SK453J1k1TyVD8qyxw7G5VcNqttI5qBSrtPVuM+MgYdAZUmrOEfgsIGyjBhcFcGrKr5Wz0V8CA5Xxc6917ZwHvOd/keU81Z3ih/diMb1+72ix26+i6pDZfLBzF/FP8QuYwbHe4rnNBXTAe+RSEjwoXg7OmdR/W9n/kbMhjaENJaXYn4ojvab1486Yq/FVMyT+snD5C9QSwcIRgAhPpsCAACkBQAAUEsDBBQACAgIABtt8FwAAAAAAAAAAAAAAAAVAAAAZXh0ZW5zaW9uL0xJQ0VOU0UudHh0XVFBbtswELzzFYOcUkBIixx66I2RaIuoTBoUHddHWqIjFjJpiHQD/76g7CRNTwR3d2Z2Zldco3Gd9dESUobTZXIvQ8J99wWP3x6/g/rLZC6ErO10dDG64OEiBjvZ/QUvk/HJ9gUOk7UIB3SDmV5sgRRg/AUnO8XgEfbJOO/8Cwy6cLqQcEAaXEQMh/RqJgvje5gYQ+dMsj360J2P1ieTst7BjTbiPg0Wd+0NcfdlFumtGYnzyL23Fl5dGsI5YbIxTa7LHAWc78Zzn3d4a4/u6G4KGT77jiQFnKMt5j0LHEPvDvm1s63TeT+6OBToXaben5MtEHNxDrDIPr6GCdGOI+nCydmI2evHdvNMXv2UA023iGKuvA7h+NmJi+RwnryLg50xfUAMs+Jv26VcyeOHMI7hNVvrgu9ddhR/EKIHC7MPf+zs5XpWH5LrrnHPBzh9XPXWioMZR+ztLTDbw3mYf+xMWT4m45MzI05hmvX+t/lAiK4ZWrnQW6oYeIu1ks+8YhXuaAve3hXYcl3LjcaWKkWF3kEuQMUOP7moCrBfa8XaFlIRvlo3nFUFuCibTcXFEk8bDSE1Gr7imlXQElnwRsVZm8lWTJU1FZo+8YbrXUEWXIvMuZAKFGuqNC83DVVYb9RatgxUVBBScLFQXCzZign9AC4gJNgzExptTZsmSxG60bVUeT+Ucr1TfFlr1LKpmGrxxNBw+tSwq5TYoWwoXxWo6Iou2YySumaK5LHrdtjWLJeyHhWgpeZSZBulFFrRUhfQUul36Ja3rABVvM2BLJRcFSTHKRd5hIuME+zKkqPGp4tINf83LXsnRMVow8WyzeBs8W34gfwFUEsHCLKGeo15AgAAJwQAAFBLAwQUAAgICAAxiQ1dAAAAAAAAAAAAAAAAGwAAAGV4dGVuc2lvbi9kaXN0L2V4dGVuc2lvbi5qc+V9a3fbNrbo9/kVEq+XDjGBaTtJMx2qMK/jOE3avJo47bSOxqZJSEJNASoJ+VGJv2W+3fO/zi+5a+NFkJKctHPWuR/u6mpMgSCwsQHsvbFfCBYV7VWyZJkMhtdp2Vtw8vbyV5rJKCtpKqkq/MGW5XTMOH1Xijkt5Z16N3YfTKh8e8Pty2e0yko2l6JU1eZbqr1JZ7RSNSZ+jXelkELezenbMZ65F3NbGk3TymtEfX/HSUixRORwORZlCEW8x3hPoh9CijleTqiM5RkfYcoXM1qmlwWN+/s1qvF3VH2KORbwORuHcjCAfsS4JwkJhOo+WK28svGCZ5IJHiDoraCyV/bEuDfnoUSoP+NRlhZFSHGJBoOyTwgfDACOUsMRInIoz8o2LKEgYx5KXCK0WomoeVWjYUnlouQ9Wqux/mwBRuQw5IT2CV8URbLg4YSHFKF4CYMK5WrVp/B/dH5Oq9ciXxQ0+SHkOMjpOF0UMsDL67RY0Jh2kRJzTBHCU04oOfyOhj+EyxoHTTPuS6iMKVJgnQiyrId3PDwReJlmkl2nkqqxnguc01bJB1Gj4Uy1FdHbuShlRabwpW7qiPxMw5L+tmAlDYPrKhM5DRDCFSeulIucxll5N5ciQDjtvhlXe/NSzFhFq0A3+hMJUn5XpnfRJJX0Jr07FnzMJtH1QYAp7b78nt7pPXHDCac3vQ9UhmfBoqJlgANJ01mAA8Yl5dI9vEovaRHgoKJVBWtjhPCRwiAlhASFyNJiKipYSargLI4PRsFqtffPg4d/C5P4U/QpXx7gRzVaPqp39iJJKxlShCWFNtS61AuQ9kkAu5ZPAqRXRhAMZXm3hHUoFbQf378KaSRLNguRWz5mC2Wi6BMSTKWcx8FgsF5axbDYXTHxKvePeCgjGAVPZxRBNUAJ/FCfpFV1I8pcP8splEOre6rBiqZlNoWnaVpNkyCIZSRKNmG8zlKZTZd2MHWNuRo0rF9v0G4nHpUwU6xSf0OKkmUdGyoxLsXshMuS0So0RdT8pCgas0LSMgzPJOYjRA5vOMASSuR2PCcOuYMBjwrKJ3J6uN88f0MefvVkMOjvnX1a7O/v7+/Cn4Mx/Pu38chMG0comqXzpiP9F+F/qHHZMfl97f0zLa/Oz452f0l3f9/f/fv57mj5cB9/dfDQWwwJja8Fy3v7+PutDVEPaNoAvb//OaD95p/aNdfv4tosubPRUC+3sxF2O2RoqaEAakijqmAZDffxk8cIqcaEm0+xfT4FQpngkvEFVX2URGBGvqdhGbEc4Uo/qgU47LPVql+tVnoeGVqtQh6leR4yhGU0X1TTcMnymGGoHlc1QrXdDTX+paH8uCRnME9qDzEiKey8ivyDhhINAXLTj4DlnIk5K4TcrWgqg8FAlRmysZvOWYDktBQ3PUDKSVmKMgwYv04LlvdMrV6mSM+iTDUTUcPMydOwVJ0J0mlwMMjNRBJC9j/f/EzktFjrxAz8uw9v30R6tbDxXbi8piWQq/gAm88/lkXMcEMH4wrPqEzzVKYxpyFHGNqPha3yGnqr4hyY6Q+aWOmlsawdWUqJ6naelhUNaZIEARqmbtOlDZsFGtNaDSkaDNLIAEkIORgMQklSZGhGDa1zmDAZNfAjLNTcedQc4ZJwKLJjQZgRGcFQuugGEmXLW3Od6HK7SSrCkqRdA8Msum41Zizmlx5+uY9f0eC31LiturjFrDo200nz2KdLsPo0PIMB857Dag381Sp3H6JaCxOCkqxIq2qZCV7JcpFJUYYSLeWUVVFJ05zIGv4M55TnjE+GEypDtZlVDVOK7Kbyygx9cA2FKFJTFnJyuNRL2K9OCJEwtX6RHgvCvJGBWu8llrVZ+6mkoYG6/bUZ5+/3yQeYyq5gMWVFfj4vRUYrqPCq8x64W4DwEbVip1oseVreMB4kwd4rdlmm5d3e0XxesEztwN6HxRwknb0jJWjsXQohK1mm8+jXSvAgVi3cMP7oYZC8itRD9KtgwHDflWJSprNnqUyTJDiOP33ySgIc6BYDHHTaRHG4j1+pVlAY7FGZBdjIORsq42v+x3jKVwcPB4OzKIroKKLXtLwLpdn7nMgom6blscjpkQz33fTxQ/Lo4WDA+4QcPPxbjQaDUIHIqqPLShQLSVEIcoVFQFMOrAe/5mTvn4ZHjho09J6zglZh71N4+/WTTwglnz7tMXztJkd6qH3NLbeL+/v4NSVpdcczzQfI71ElU2mPAc1XZn339x1BEyS9SZnsgcRtByeiBcuBQg8GoVCUYnDwNYKCloDTP6hrfOl1TH5XGwQGAV3bLrjpQoYUBws5/jpQ3MEKKo0UCOzPzM/j/b8/McAu5yWtKJdx/6AeapA9Gswdp4HDw5exZTiXXMPMNdWjqhJr4uhazyUR0SXjw+7rfXzJeHzNwxIlZWz3q48rv6m6xqduStWyS87oKD4b4SiK/Ck+G8VnZpnvZoJzGM1ohC+5//EpVT+UmMbJYbgcs4LGHKflpHpX0jG7hZYlm1GxkK+r+JbXCG3qSX8Y8Plt0Po42N29o5XbcBaS/12ksP4Cv20p69EIn/LmXAfM/Z2mT6Egh8twH1MZ0VuaqVWi6i1NAzHHs/T26WI8pmX85PFfD/YfPsY3jOfipnrBcnVKw2GJmZVvKlKaeU/2YzOTZZQpjhfwxeySlkGiC5LkIIaKQxEu6S2Tx5o7VTKHjlkSSfFBzX2IgKnXCP7Dx9yTAuw5JKrmBZPhxV8uUDQXc/3BsFns3uLUMhfvLk7eLE6z0sy65mrbLiq1pEEa40LMrWRGeSmKgub292Uhsiuat5ooCXO44Wds5LiN7rhqaGFS2XVqV7PuOhZ4URZxGQaLsggQBuTBL310xTNaVelElZjHALVXel3jc+6kbrpaOZr71cFDS38OFL4sLbUHPbR2VqviYJ3kfNhK3h1N3d/9++5o+RgfPPFPoCecPKGP8RUnB/t/hadbXSAlOfiaPsZvOXlIH+P3nBw8VO+5JCElyxp5i2BepHIsylmSGK7qSjAnNKL8unlD+TUWhDqqmCQNhcQloWq6oRD+YgY1FzxJTjmuCI24kGx8lyShJrCIHPYPEM4JjcSc8pNbCQfWwn+/rBFO1Zc3SfIsleoJF9BRQek8ScJZe0teksOKylO9/8JLPEMI4Yy8UXsnenPy7dHpyx9Pzl++ef7yzcvTn/EE32x/eU36B3is2UFvZjRYgLZLOEVd8nCGJUIKkceGJbDwEs6yFAMlu4wasgNaGkNvtNpkFwTJYIQvI0durBxmRq6ON8er1XFkN3gfDhmtI9gVOebhcaS3vfriytL6TMxmKc/jS3xNy5xlMr4CSr3wxmNhnjUwz1ow7+5KIQqglUZeDbChniMsZQfeGs+9tgH4a7S8Jh5vviRpiB685+o4OkxD9M3lELFxqOEowrcc4fCzQM1LxuXuFb0LRvjgK/qoAwZKHL7UocyMchHOrDxQ12PG06K4A+iAfVmKoaEfgzSJFLcH2EK0m31zwi1VymAMCvczckRD4Ar40sz+JQ1nWOiJu4wMh/TJ2TG5BH7rnQauaaiKMKg6dCuvoRXQN+Ir0+44PE5ULUPidA9XXstutn91s31Skyuod2JoMPFJboOVXx1WvLo+OV6t+uc8PIkWZYFWq/4HeIYFbBUOChZT1idkAuMI0e7NN1ccLede+xOiK+EbQCGGV1hDUYUXWlKOexWbaP2w6FEOes/maD5NpT5AV71Pi4f7B497d2JR9qDJHqt6O0vdfH2Bg7dzylVTu4wHDrG5GYU9odbmCPJd5wwh4GDxbPPB4sO9x5Vq7bhi9KD6SLftLX5zb6tl9zsF4DutwkyMfECCkzdvT96cBpjJlugc7uNSOpqOQmSkaFiFVorWqyHcx2+ikioFjpLB7MxpZn6xs5R1ZIiYKPLdnaXjGCyvd3dAGBIyKlOei9nHjy+foRDVF7gkhj1qFU7TVaFkeqfIiVgFfCREg4H68eFudikKlr1i/CpE68qVko4XFeMTWCslnRdpRntpjwu+C4Sjl9NKMm51LOsDlFiA6qFvzgAh05qwdzxktjNWA9ibcdP6qkSbKwpXcdkF/2KcsoLmAPx8cVmwatpTYKc875W0kqKkPTmlvXlJr5lYVP54hr2SZgIOdr1MzO96JZ2ljFe9VPZ2lqK+QLWFvzRrX0M1A4iAi2XGxqKWZSqJUeXvTmHqxuMqwG+4KyxpRtlcVgHOJXmIX3Jy8Pjx/l+f7P/1gD7Crzj5GheS+KIKqEgPnuCDh1/XO3v4ma+oV2IXVn92Ga9YTktgL6ortpiBbj5Tje3v/t0cJ5vH6MHuaLmPn4AaHi9UtXR3vL/799HyyWMo22msTUZY+xIt9Xa9XUtT1zPYMWpBTqgShq0KrE9ILuHExwXPgBLKRj6OrtOSpVz6R8P+M60bdS//BBxsHIYcDDU0kzQHCYoDKD86iDS/AKjWKj1jlfwwTR9+9cTVg1O/A3l7q94YMmn06lurIw8L98LgtbrY3mrzBfpz+OJRqiyEQDGBQbsjS8+eOCQNeUtlyQjfrHYEvG7SUya8o4582rRoVY8eKFp1bZSIMP5ytQK9NltXN1eeutlDbFYwyuX39K6Fxi+wXHif/gl0GrEpiiLu66iNrpR1dKVVXePjlloHC+BO30VTMaM5Kxve1C+kPeR8KVRq1+kp9lbltVuE3qLKvTW0tXVqV1zvcsGKvMdyyiWTd2b3lwD5M6PBEziIrPYulfhiZ0lrpbu7QJg51lc41vfBsj5tVijWmN1q1S8cO1ytiqhiv9PDgyePvn68DvGCV+mY3ksjAMmeBNBwflDzFVoj9uQRlDeryvL2CZVKe9bY1geDAhRqfULadcJNW/Jz0JEdHnoahgZFTvMWllbLBiZtw3cLZDhq88GCF4xfAVLbBwJc1FqBsGXG3vBGPPgQza7USqzwsqTZoqzYNfBKvaIfP/66tjYhr7EKZpxZMu5mPjWnocIctjOQoPI6UnJS1ZWTIjmbXwx9MeJDdFMySTUOMuhjm4Uol1gt/5hiTVHiAtMOHY7dZmheNcQ09ncFKNMK0iJKgwHz6KZf7htPmEc2DQ1Qa6uuUf2XC7xURY++flxbwZ/JMMM5cucxb/ZnMGZPVumcNe2ZrbcNLvZ5tjgYhPfWchhbrTbUa/HPFlFJzBk2BRm1EGm+a8T3PEB4vSgON48hMVrmyBWFLQSzhnZjDu88A5pCO37afGDYDopto4r3hXYiUgeDKbl/R7nKNR6vnTZ8eo4FsWobTdzXaCdv0U5LLxlpEwLVWonaijm9q89Gzrqdgl7GyPFpRHle/cTkNAyMHaWtOilI6uzgu19pxmHZTtGpm/kQlzhFeOLI+s06Wc9UazebyPqNI+tNDxNyE81AC/S6MgO0r+BMLnYnhy85Wq5PS9ZVGLnPKmNh11ShwKb1eFKjuooqUcowTHGByGFhe95N7ZOlcK9TOY1mjIdW6MCvOGpwTfaH6Tf5MH3wAHU4XO+YhtVZOtKSMNaqc8Xo+kro6qx/06IBNqtBr2tmJn1wgND6wFuTcbGzzCzN7SLE0IjCnfjVgecDJYGjgVVUafPf0YRyWf2k1PMBPqEkAI1DlELxC1HJ6PJOXOltFGnVRB7gq8Y/KfW+j2YpTydQofQq+Oq/AH9sXJDalurvbbkRH7/tqoedRR5OGaCId/Z6agcD+hshCpoCt3YvYQTeG8y6viobWl7zM8G/K3gYGP4Gg5KCtobiW+oV0rOSjggh/X38XKvO7aqRPTE+o9GNKK+qeZrR56LIafkj+Kxhr9gWTApxmRbq1wgUhb8rPz4zq7dgj6jxC41Hv6538Ok2uvmVB4argOeyMfvQRCaBWJRVEAd5ycaS5kHMk0BOKVOF45LSAO80tNAaDPWOoFFF5Wu9KELZaKDweWOoXq1ksjTzF1MMkxXL2h4iJobO9nwDzqRpVG2wb338yKH0WJ2GYyek2Jz1avwbbwvjuGwDLX2gBeoaLnyLh113ax2qgRsD+7dqhkJXGWGuluTmj57eiSv3BVRDuN+21/bsmJSyVJlS3rbOF/Y08ZE3/lG9n5XOdujbiifgGIZLIiPGK2DzBuBQu6KYQgAoBOej52AXxTmZy1AkzY6D5V6pP4PBLXhCeSsS4ao5ZcNM5cotwayk1Up9d7ABxNT0orcudMH8dnXRC6WzwgVRreqlmJG0+TEh5zQsViv1Xi1jnK1WqftluN9g0M8sDB1ZcwKHg06ZQM2y4ngCUzDUHJF1h5+0fpo1bcnzb+BeyzGcI4tmB8DPGwyUBOS/GpxnoyjKkqXaGP19KKnxBAtU45/b+8430k+kZ7U0E+CMdnoR0PVpL5tCM+2gBDCgqekVneklepEOBuXa/Gj15mDQr9DawrWeNAaYHHSlbByywYB1+0DGYQsQ03pTD3NaUEl7KWBr2KE67c1nXC+v6F0Vpsgw9iS1hgWck+2b7JyG/X2zZ5HecGwcVqjTobdxv7TVA9zfRwjn9Vb85Jp13212QFbvngMfMMY8ELI4k4YdHe4nSpgpxYLn4GCyj6uN7lVOWDUeS1zcEDlUj5VMS0nzI+M4pQTamouboXsxFHPJZux3+mGt5Jng9EgOAXBayQ+UyyM5HLOyku/SEp6L1D3OU3C6hs2h3a/32+1aZ6q1zny47MsTnm+t7x+DWjU0sF5z4JrpAA+dC5o3Fr/vuQekGssDcuC7nKlaGqceBkgXGv+dRFiVNVhSzm96r1pwFLYekAM4TLJqCr5ymg4sFRRxAxA2lWP/S5yJBZfHaVFU8fNQqkCBCtnSbEpfMGnfmF8ISyHT4rUqdkPbbS8XVLc85O6bhg2z4E8Sd+9eV+T5pjnb3dwFMuhrTVm3Xw/f7U7di6ZXr+7uesu2u80tdiay3VclS5rOmo6aervdJhF4H9Z4Jklwu9u2rCtndfwjb9kkovO9GMwS1ipxJ0mbXZxdqNkkO0samXmtLxqHEw/QH42nGphsuT5pXSjDJAEL2QXC1Eea96Gt7N6qzry6+mOLhQ1f6lfqM1tLf9MsjQ1f2Zfqu6YmfGmraKoD79WT/8oSInhpnv3Xzb5RNZqfa5Vgz/h1zDbS9ZRHZYADVOOp9LyUztwUbBmk/MwgZ9U9MyI/OyPm8w1zIu+ZE/WV3I5beT9upY+2NbzubcChIkq59+n6YlYwXcChNu4phO4spUF7L0D1heawN5IEe9cHe80BeU9vqz2L0wD/ynUdaGsvE7N5QUEbVAX4dXdXualQit/E+oO5KTWUgyhzma+aU1aRFLx0aR7U+CdODr7a38dPOXlMn+DvOPmaPsE/c20DdEZHrO2A33OyJaICv1bxK33aHIvv8XGnCF/qxdiE8fj+8k7D8DqUKJHWA63jPvZR4QTCU9Af8eKVg0H/e+cUi//ROKGF/dfKGZdG0Frf182vVvAusr8RGNPD/seQQojGaqWe7MvIxgpZ/YB7kZaTxQzUGS170qUMN9VB9mgFAR3QD4YG4wYmbJ/ipYr26ECAXUvxpubBaemXZux65H0X8pVWFatkqsK9wFkpGEWMZ8Uip1VoPCBpVIqCOjCH9vQMpUPrT9y04ylMQKFGfbMtzI8rtE6Q/S/+HKbMxF7Zda5mxE4EAKIGYcrh+RwkkXM1e6on87790lNrrIHj1fQOoR4ujAvPxnqDwVqkkVdNr0H30y7jh189gXgf0noH/rz/4C7U66lWQgHp11/1CdnQFmpWF0xXLLFBauzQq3x/LcoBk/7WsisO/qgDJB8Mlk0vMa9bn/s4bTXjv4jb9WCB/vBvbs7ulvRKchOy27ZcrO/ZVj1/wbka87RMZ1TS0p/eFkRelQbvf3A3++jcBFwLrV55vLm6mp9tMA4Gy+ZXvLEOeHlhKlp+IXaClNAGnhr6abVaW+rGJ1gvdPujZYNfKz48oI9bu4t4VWAT/LK+CbQ3gLcPOm12vKrpTe91OldxU8qvBjPfCrIAK4hsQHfK1zm8WHh7LEnORspaIpQnyhx4hO1KwFFeFWE9z/OtVHu+iWqDkcgIMWlRxDtLaApck9g4XCjS6xG7RZvSKZcqBVLnhQWuVKGEnZeuw5JWi0LGO8t2Bejc2Iws3nL3lK5hkH8WcdoJVIAWVuMOprFqULlazRJL7jvYW61mPpMlm1BoB1upwaoWcfqlONXQzUkbBYrQa8zOgYtW7jE3T7bTXHfa9OiQOnd4LNYQBjaeRDkrqGcNk2NayqtBq6q2Taz2dDChOoVTmPr2sO5AzZdNsc/7WpNmNpNq2XqkLbosak4O9T5Atbb87bdHmeplMcy+Ya49dpaN+oQshigDZQcbhxkhhHU2b6aUE35bFWoWOvCC3Dz6230CzWmG43HvTRHAuo5jyR49erRahRNii2GUP2xgxJMuI254sAfPwqEulLqW2gyq1Rk5nHVYGcJzF4TMxuEkqsSMhuHSMZEZBCP0F2rkM8v+5v7PpL8fh3O1Hk0J7h849lRrjbPyLShiQ8ltWEcVc2AfE8PAwQCq+JM5qHlscKlLYvuqrvE1oXhMzpZX9C4OJJ3NaZlKMMzjGePxPsT2xA9rbN6L+fncf3Ng38zS23Mprigcj7wP6d8xZCeY0FKFATV1m/PUF3+mPc0zej6nPC3knf5i92EbxLE6a/Hsbks1R/9U9YV6OVfvZq7PS7DOjm3Mw/XZYoSviDxbjGByjxsN+9KIAFdN4NJgEN6cLUbkqr2dTcXjvqu4WvW7WtxjtFodfzNfrY4PZ6vV5WDQ1HipIVNVwgXsfw/hq5UrWUer5+145fd+fHjlVryC+NiqpW9qfKqOg+EyMMLnLrQQxPqkquNJ95S3AU4XcipKc/CNL57StKRlDw7kTYQx+Ko77ZV13wjirp8PhNQ57w4MKzl2ARk6rktuMoDQaEpTcLBVHMpBrDe18YZ0dt69f37KHzi3QDQYaAyHHB1K5LlagRlZ5HdJlKU8o0XYdQ3xXL+0T79z4NdIpHkv5T2hPGt+p7myM4HD81zwyvrv6S5alijPOwzEdHorIYGGtd9AdRjkezXeEBnR6JTeymcUlBclZgSscwEEght3dEXGh9aqopsWJiIawEijXHCKltUDUka5aibUpozhZUnTK1i97AFJI5VyJbq8k/SV9pNgDmX/Ljb8vk1H2JIq5cG9jqOqcafKVys7rC2zBeMtaFrRVyK7ClFd4xcdlwC3e9d2nDatEGNbAUcRih/SvyNrsZbCj5r7Ikfs9gEdc9KuAamOMqaUUijxflhWVoJmp3SHo/IezU7ZZBYpoyvGW6e9n43WRb9ByM+XoRhdCSQA3sW6CjCVF2EZgYv+LJU0P1Uk5kN6TXPkc5lNFeKtX9Y1ctgUnhO9VYvhoLpi87l6ylllfFICE1AW4IDC0gtGvqeuTZbU0su9zLdFHZ57OnOj9e58CYewdkncreKfsaULR2o61McP+wYpbqxiN21RrREsI4jR5dnd66qFVVcat+u4A79bKea8D9X+7Fxt+RKOmedtX7gxldkU3Cr8CN+l0XjGsja0zs8gYWlemUQ3acnDwCpde2amY0dAuJDOq1Z5FlbGggzr5OhSlPJYcKnivUqcEtjxeZReKpvZUCT6keaJK4yhMM9PriFlEqsk5bQMA/UywCleKvcsIDrGfc4LtGw1jn/iyHnHZS4c/8JjfR/Lot5Z3sganEKpnIo8Dt69/XAaYMOxlPX/VOk9oyhig8HybCZHMYMAfZHfrXHIBqkIQ9xXWsR5pB9wCb6INJOx2Q46srJMIsbHorEb9ACAnoKqt3vY21lmdvFdINzPImHj7Xoa0RPr7AY+rE/1Gb7/OpygdrUbQkU4sXruJqiqd5M4qG+wv19iCR/4JaiOjWdgmKFlZ4k0AzDN9XRkUQxD6DEOR6EMdp7iQ0mmRGiHiwuEK8cvsoKmpZ1TyNWSRCWdiWu6ZU0Av0gpefIYf1Dqbfyeqj/v1B/6CHNBDugTfCTJQ/oE/0ZabjlUix5NqqyNmbS8eOt1pnrxRUwVBKbezpLXF17GNnwi2+BI2807ukubU7gphdQz5j0Xu80pXXP8L+f2HahcNwEaep0+IBJ3+3hALAQ1vlo3s+gTLAh6xt2lCWtRB0j9XsURkJR+OcBSiN4s5XcaXtVKYAUvUPgHgU7hFASeRigI6sbEY3oGyCDkTtRYCM/AB1YFvXn+gNBkozTWkNgkkSpFe36t5aB7as6mgmW0Qm0dmyuPxoznwPBfK5kBcl3xnN4myb5KIKIhh8YhDQf8AQ2HTJF3ujBFVl/d5nytV4MBD42+FUTcAOtsfp1aNcL9zjBsDU81j4xmr/vCLuN/fxFsaHssypMU5EvD8zTeyw1xIffs3NbkQrtmwVXEIZ95xKLafHS0YipoRKpv9ler6o8t/E2A9FT3Li/YFSzpCiI9Xodlo9ZPmmfwWivIbypDGv4gcaBaeflMH3QKNUV5xHJIJKasOMUfAFCx/4JlUgfBWhhV69AcKYwK67cw1Trb9xQH8KC7z+xSeE93c1XBKnz+3OFFgWCa1+09IBk+kWGOAQK3TfE7igNv00KQLLCS6y5V62SvO8NiJMYmr5F2YodknWcMEsSVu8zksvsYCq191fGV6se/Oe12wnQKO9UiVv1oHdefbtwgS7pNL0Sxq1Y8hn9f5jH0pQms7gwzPl/IWIhQeJpihT72/4rgGWVbm+SZws1Er/NyK9nr1NtI+GydDaRv/dV/J/Hb0Po28qcQ5VGI/yZyqOgPQ8MKNvsmIoMrbRD9zeu8Swlgg1a4VeOzO/VWdj3H9WHHBV63DjXW1Pb5dIwdLBy9e6kyPkB6h+5xZ+hlE+iVG04Xv/Ltpwt9sth0kpDu/CC2HBz6DI4Cn5dEfVm8F0KAoDlOoAs7f0tjgzb2vLa8F+/XpruNWjyld0RJ4+ygts4eBUl9V2uIAtgHInTHFIa/4whXkLHkWoaVFszA0bxJANJnWvX2xeuTC6eu6sGXjjeydaVcuqaUK0Ahl0GanQm5MWT/mtyYjFR7n8rkE99zlooxORxrx0oT16UyMwYmpat+qxQ1XyGV2sr4yyLt5AT5rQCh14o4XKtMv8/evjkZBWiZgVLPYKEUfjzqtUZYXTcqw35mlIYm8quXe0rDG62kGwxu1tSCh0d/Viuop7On5tZIDqB3NHrBm65e8EYpLiHw1ZK7/66e1fzo7D3XRE+PniOVAS0skMHMmBROZ3at+YcG25Wb0gfXZ/sjK3XgSThGOENOu6oHYn73M4g71inLBoNJWHTCRnv5NiVn3lFytha/9norXJhWHOBKkDNIbfGIPsIH9DF+RB+P8Fuj+Gd5fLGzLGgNBAesr5o72/3/6fbp35SSXzmcXOBxOmPFHbgmqAdsQ3api8adpbcvgadrZVJMo3YBvH+7kE2FAzhYAy+QbB4HP0MKnGNtCzDpZW+YnPYMOL4WIcA5lSkr4uBbJl8sLt1n1eLSuVvoAViVQt4TvKcySPa0U22WztNLVjDJaBUrmxq4JDI+gRhpNksnVIGusgIinIqOQOepjLz8MjBPLdUDxJXm9+U/zem8IrKGP0Pt+Qjm+1SClU6S/aFeCO9pNqXZ1VDHTek9ag6dJsDJthUVrAK1mEvI3Xh4JNoTuYJOFhC3qcOYC+M9rnvHlUxtivbQeETr8FqvEriZpPPwrby3iYMa1dmiLLWrve86ruvVpuWlcTOHhH26Fzd8MDJPqOcavw7K2ajOWTUXFW23VOs/S1PXw2ISNU14xTaZa4Mfl4K2Va+t2q/EmQ/yaLgejWBePSAHm3oNm6kza6pMklQgvee3gmn94FVZiGrI31bb5WEK718hnqJIZxfrrA7LRdozsmUZNK0LfnSdsgI0+KHNAPxua7qoQpCv6CP83veTDvfxO3s9xIu0mqIwqFQ4eoAwJ0ILZkpm1gkpI1b9yOgNJPVeymgxV4l6VeZCxuXXVri+VHWxUGzs7XhcUWl+GMWXLzysZQtvGg7OgiZ0WF3JIJCKomtqYDgIuV+jwG9ZOGONaGw6fvNLl5YDUpJ3s55XEKNaIqZObxXyysW450dElWhzJThzMnPmRMh1u56SoUJ1DO7sYXlWjfzRDVujq5vR+Y3ZMdbxWsMCsnIuuL7qIwe9rdOwcXUZQZSzCZhngikoKGr8xh2mLwyn+rSvfNsVHzI/DA9Sv7xbNGxKzYtqZ/keFIr1RXwxc8/1Bc42h08VwmyIWXpLZD1Lb4cmyb91WhtOITXfggOVnrGqss9acWlzFEMT5kNfpen7F6hebAPgdWPFN49i2r4cEbFtGickuwVtsdZRgk9qDbJ65QjwcspsuJBtE0Pn1BQ6QOratmF8QdfUUZCLhn+zj1TY+x8BatguBUWuRbWRukQbcWpFo4grW/lQ6wKdODXc1LXQkiQkQAV2bPmArWUK6wnsCvY77fAnHzRDwjKt6LWKOipfziAzRCqp7xab+C8gPK8lJkCk8uLzwsDQIuN4mpaVIrL6MUmePAaJyafTRLrHJMmEFiRsevIgGNqXylfANuRKh8ojTuopbmg4q+BoAwHYGq5xAdV8Km9C1qRP2vzM6A9IUxdOc2/HbjWYGlagJ63RtjtssSA3ktWqLciAH0MbKR7v9MeP/bbhngbz2E0173PFFrNv5Z5vJYIPgg3IcQWz9IpajJr19OLe/Io/fi6bAX7piOKP6lYNZZQmhDxMGg9weus57Cf9gzikUcE4fQrb5ikdi5KaIG/phW3YsJu/NCE4ui2IWkex6+kgoRGs3r66MME9P9yop2NFXlKOAIjmp8nozsnhSxlC3lAU9w/i/gF+4+6j6f+oNX8/QmiBl6qzpzJGd+OqXkpTDUMMi4kICpBKL13jV5IEZwteUp7ri4h6RgMxCvAz6btVQ6dqVTRo9fzUARcNa0HLfw+p3gZqUDsYhBqhRKVCd88P0WCwFbmNly/Xd6O4N880el3SWAPBK0g6sSM/i+tXcg3TzzxM4wbTem0vBHmIx4Ic4Lkgj/AzqtNagKwoyaG07q1zkehIiLHQJ0+pFXo2LEI6ZWksEf5NwWnVLidcqV1CFFH1BBmqPbelifA3UKKZQTtOSWulm9wkH2X7E/u++aZ51w7NwN9+9tPOnCV2ZHDPSfvbGZvRUxVt0Up/B0vl094eMzFUrhpKYG3HG6RhGqkESklHURUiq2wxFdTmwHdbwGjjDD7o22wqDRCe5m4vQPjHdgrNUfPY/187g3+eN7kvP+19UbWdPTx1Hlgbw93sUcft0U3w/yjXsXfRg2cVXGgL64s4CMw6v9hZrl0EFaTwFMS271qFyjppzUBQ4281o9fp9/JKK6uWNb4R7ZjQ9qZF3i1cfG3hwkFBbV1u5JuWA6qt39w05b5v4UmQN7RpwbujoUVcTU/C68N77cbb7H38e2sfdHZJ0opfAmviDiV7//Wv//NpL0nLeB5DctR0dwz5Vuv/+td/7k3wkVAV1NvQf43+61//GZ59qj59GP01QaoNVenTgf7wWrSPky/+/z5Otpr3D4kCfcFBsLQHQXFW/sGDoIlaXDsAIv/IZ28INIsX230Ye2QIK/04TRQFsgZFR2nrtUOjU9kePEE1/lV+nrhtJA5nqZRpNgVLRq9FIkYXMYgSJosKzT1J4qV3daLZbdfCi6/lOnRaHYYEpghffFo8/NvJE7WAIeex+vk3iGg2qaDDHYphf+l6e52KFzUeN7fQJLTzVUzx61bI2FamaDf/GFiDngp9WKVdskI3kxUOZIVasmKHawTWZEyVDBK/hEtRdqSrCIY4K77Bq1/1jYSQg1/JDWv09+JMTQUEuFDkBduPLuKNvCG5WO4s/VVP7aq3Esn6mpcIFBdzGtIzOUL1hd9PfRFvXtcQIvLTWi6GUefGOmQSB56NINZNJcCxiwdu+7IWom9NLnHZZMoFObJqIlvYuovDt2EwY7fGf2FXxzn1bABJLy2psj1CSvmjl7umvAfhBKlklwX1SEWqg3p0LjylKkSQZdBAqhCXkcPXIsxAbHc8YEiLihpvyRsRug+QjSRSXKYFsD4EgyVUm4U11JXW/UMKdBB97P5yY5BlyqsilakGuyBZXZpMgUqk1BFVuBXrmhpy4QTMotaRUXmD9pQc9r+VYYp0aqvmLjPjW+9NZwYo0hF+H2WYeVkQITpIQMnShJyNaZi5LeXxU+18ORMmzeLE7BX/u0n7C1gSd7ptNSm25ksaZrB1MtSu76P6widYzexrxAJRAtvuFBoHw64JjCNpM7lK8WKE94VAZp5zi7uPcMJoTYIX0e5wDl6wv8tQKHfYzFvafixzplbYxFipJnbiPhO/O+mGc3Yzf0XK5SRJVNpVOIqjGhZsrw21DsdfB7hW0YlSR7q5bXiA1GWjH8DO+9psNbDBup2QkjkNy7P9EaQ1U9lKISO+UgamaFgkhZWz4uYlMIcUn4kRqk3ekSiKSkcoeY0/KuL4kyKWT33tuckR5CJrdYvudxdUMNNgTn4yZizrnyRwOVIu7uZ7VLoYPDjMWjitts255XvRapARP0vLWNY1/s6RxTYC5urOtSSqpmwMhp2f18knFqBcKck+ZsrzeymI6PA4LFyCmCVQi1hAPAgB182Wfhy4hsymR0URHoEQJh4Qe4FoiStj3MUlMY8Pqsaia1wBpGHeAHt1djByCfCsMlc8INXZw5G3YUOXOmYJVx5cU3WLpZlIHwKEVd0afy9b5+Xwc2HrsolW98PNOzHpci0UXert8CGb0lnqhwt4geitOjVsGvxc/sG8I6+ceLLGyztBMaDHUnfa6ouyXymRAXYBimncfy61fuK5VDW/7DpefUUux0JdkcuxykzsYSJoCdDdsz5c5+0dYeBn/IrCZRhnfITUbbuyfU+DvbsW8DsaNs5/r9N5qAcnyOGZ6PgwwRAbk+24SOVrXdMIC1ytOOOkZyuWyZlKoOeFpJR/LE/B5upqcYhti8MrVqjw6+FyY26DuoYr9OBapUtxbwqabRejr60qLzWoTUC6Nf194wHQdbGu8S/traad5230dXVXSTrb4Nv144ce3MnUK1I+WQATNXf55ELJJobJ9vT3Tv5yl2248KE1h8LElYETumhqbjxKS3eUHrbgbrhuK9+Iz40VlVQBxXr1bIwtd04RQAY6seUqbMycw0rn2Nl1zdMenpdio0ee0sB3QDcB/0rwbYfVr01CZ1qNsMuqHliwwI2Yycp4OufNBQ8t4VAjAX681ykB7IjafZuKdV23GtFigofJutbK+x8kaS4Z+9a54+wa/6Q4wKfNicxLPfsR9oAJjtFWN+4HvXzrlryN99H8pAdXou8CfhaTKYTKcOvPqdKRKVWORl5d4/fQMcw48lIZK82TtLohmkRnfOR5pYuNsZMmnlm4nSjqGv/D3nYN+LC3M3WzlRrzdv/AcWem9R52uSfRGRu1wq0pFHB1xxEalqtVSM/E2f5oRMC/ZrLRpAYZ3JXXlPLpNA5U2iY0oVK7dFpbm+AfeeORSbguLcSEiKFJhwj3/ZGydp8O298MCzEZ6lrDbJryCT2ZMSmpjt69i1TYkSkaQsb9/FjVemVIiMrGfTxN5UsON1soLydtbmq1Fin3tSFk19b5u1XzOQ2X4NQRwyj1R3r56TqQu75xyvAqtVrWd8XVaAihWDR/I479NmC2SpoWGk7w/nBmcBWDfqzTu0FZRq398XRR8hfa41ObDsYlraYWKHf/s9eoNcxqY5rXcvtFM/6OS9CmEXW9g5pv3ZtNX7uXxqumg1J/42oHm7uomEUVLWgmYSJNxeU15bko4x9kbfe2bBubCzGx8W85q/RlWLHtrlcIcbWYe863UpsfkiQ4Ma68FwifjeoamujMmh3zxim1ZtQt821MqnpNh3dwYaYKoZP0DXRvvQQrSsGjuddxxDMckekx9naW3Qbqnr4+NnKfANJ65YKbryAIECp719dMRSXthXmKMBaFqmhAaSoKvwEMzxxa7rWvye2B5Kjh07D8R9WTtJyBK2Z0EQdfMsKodwy+Vj0JwHdqqAGxyoJKc2wuAsyxuhsNvLNVAFgUqMS0ZiM0ziPgR2PdXaTv7iKdu8sFFmTTPgJx0dy/7OizvRRKLzpYVu+9PiPAUsjIYchWq01NmrMeR5hBDunWBevbq3auVe9UhL3LIeV5aXbZOlzusm+W+x7TBQULL5Sp01PhAn7gyJLD0Zl82bbELI+5dW6VXefWBtPNFdwG1Hkprll+LwXX7jN+fvY2/9HOLH2xMXB6A2faQP+sgyQ+G2n9zKZbvNwSaN+hoiS5qnEF/hZcgSvPFVjHXFjkwBuHGNt+0PX6PXj4NX30GVffjsO22kqNT+/Ru5dwJyro+MZjlmk/3lIspHLp9gX6y7ue76wMstiu4IW+YfNeF9+DNRdfExXFqmPlbVmoCXyvYx86k+Kh3/m3qqtLjS9saTxgWe3PeotpKSd70yazjqKKE2jRzuMEXDhmYKjqNatAXdsLNYEj69Q1SQIuOA1qhHsVLa9BHt5ZWh1O3fNyrFasoFyaLb+RhzS7c9uSf2/iJkITQoMZMjkC7ln1VXvVa2pyF7UaVywueiPeAVmuVN4D5+6/FkkT9d6v0/h0kioCaxQ41cb9YeI5Kgoauq7kYfzncIYnWoyElqbb692SNDKJu01UzBRc7aoH00g72u2GhS4oTAHCLhG3qbura9RaIddZHFMZ3qK2M5UnaWld050Mb3GG0HBbLaPN+3qIttUwOrka35A80QJ87E2nz6/UfOaDQf/m/mmUz1Xa+uB0SntKFQfrchNf1ZPbKwSf0LKXWtnVzuM1yUEL2eYI37Y5wrcNRzB3NICqDpKAXqt0cW1KaHJ5sTyeQhYv8P263nQH3EujVNhEwXqay+hbWps5y+nlYhKabMUuuTZQWfWLAMlVV4s5TQGBM5zZqibCaowXCn5kVt+pANWY6UPj//Oxrk5Nwf9D9u5oo6lQtLAnysbessUqAxMwJtPaKben5KkSNMZk6tI04gWZRkb7W+vcfaLJr4ZnNsNZnlzHN8BTnNJ4DOfGedcmUMXfy3CuU6C8NxyueKtUVRVupTNrJT3xXsSf+Wxb0zoTGvx912kb3mxqtfXFlmb9NGrw49Qk8fI7aOps6GVbA/f0tyEVG5Qfu+JtQKx9uAWeL+5gC5Drid9c0TtT0oKtW38DWF/S5BZoNiSYa8o2wrP2xQaAvqxVo36Flf9a86oONQWOe2reRu/N5WPOfqZCn+PAXUpW4ybJlrbCun3nqMmmPDu3hEWCbxSGlHvt1CbJQUO2TWoaDFwtnEatqze8u11uIWp3hs/JIVgzU1fbXmBjH8+te6QOrU60ZqWFGnB0g2z34bnxLog3VTKCoKlobIvnWtY91/psBMn7TdqdJjrv1lMZTEJrxVE07tKEEU/xLVIDaY8WqpwbaegmqijPDZLgAzhQvVWTsKDhUjtfx6fk8NRX/20ZKdbe1aq6daAx3sZQdh+OTpG5PgQqLjdh/BRMpDZc1NxPCiM5BX3duckvidykvdWyx2mDsLfOdXyiUrIdKwnqMnymDodCMa5FsmY/NWqLRuQJNPfcqPAEnpVKMWOZM2pPGZgY7wJ7J+Rx2LoA/mrjgv/1Mwv+6osWvKuFuyK9HgKcY7Q0PnbSuAE7rFDPjEqpLyzbtued0sgCJ8O0fTOKWV8/UfIZWU5N5YlZhud62+nUXlc2xZSFGv9EvajUqHUND/7V045Z3/m1kTqwezZnGdlZnmy8RMEdV3os31CpnYItSYJdle1p6yxYPTMbh69leIJnyNw52V0I7zpZ+U7srm1STjtzlPdOyXCNNca9iWf4KSX/kOE7Le5gT+wx3hN/mKr70tBT2orX2ziknJNfAAA3AHxDydRYJxf2GKvt2bfkZ6A/C3cSvdVy8Dk5DPRWCxjvnaPkVmkKoFhRXij8DPVVru0x0FRoBsWbWtC14iBAng9pwUnOtdXWkFJNOhfJd/6wzm5HeOFL9ufd+wB6z2h4dj5CZ/tKMTLdZB5Tbb8lZ6aGAlqVnZIbaguGZgGcelN+OhgYYnc/gUXxW+e+AWTR2DsU/ZxGzr7WJOHOODnVHMgtPPPbc2gzJWD4uwcKn8udWi53alzsOXI+CBvWoaHD0ZFFVfjWLcPkLdgmp9oUXbcwa1Kg64Fpk5pFsUanK26FPtwHwceKluHZluHpttQAW4173kLg8OrN28aW7HS9RaP4LRp9CWIUWM0ScehA+KW51M6X/MDhqB7+I3yJOxLhu8g7hnTOJHhzfThgdM8Zm6s2p4Qk0b/WZPStR4k/KNNvBqArf3+ZRL65rTXR+UulaSMBXIYFx+Y0+ZRiS4bjhiKD1O17ib5E/jnUByd+CY5jLY3YqdMDaRWYdfK8R/1V/s+qv5TT2kbdsLnv2IYMeLuFdx3oPtIQ/F7cxv0NcivWfvqazaoh9j+jFqrIGxP1mq+r55TLlvbXWmMV+dDPnMz0jVR6cStXJKf63yZxGPVpSx0I/cH92qmJ+JvRTsTfuNqbl2LGKvANwZR3AwIheut8XoqMVpWJCzzupqEI9zHlUTVPbzhSpvclaNFBuQtpLCqZMxEHbMJFCcrgIY8ED00OIOzyXEcQFDdWSQTcPbpkWaOWpw6N5kUqwbSRJAYoV4IhbSPl180byq8xZOICTTdcEp4ks+aHupMUJD9VCg+YQQmMIkmOBa7IEbUTafYvDStIuZiSPLpk/vUx1zRURVi6O1xfQ2V1k25BTmmYJqqCS+ZsRYJ+4QTFsMBnwfm52TwKkF1jrg5GqH3n9u/2Pm24PPSjBPuC1iI+o+N0UcgAP29uyt5Sp7lVmzd3Z/u7MglmKePqIu+gyZCOy7WbtiGrqE4Mb6vjX/7w1c2ic33yPZcn8/suT/a6sfcdb7vq+BedQlNddfxi7apjEwNuL67VadBbd0RjRkqIk0lKTwgsvXXBvHs4bZfcXcLKvJqic82tM15w7sVtwL3GDOJXtVkPV5g5SaFpLQnX++ofoFhsudRbbL/UW9x/qbcHioLTuwybbkqhL9voE4A+jhLuoU+Qpnfa4L4DujMo+7uwmVTvGuB7V4att+HL/e4S0xvvR+q5OR812GlY66LUZlfkgHfzt/QvbZaJPybcngJ427m+fdNEtKp55XWNf+1MgB7iZyA2IVOwBY6i1svTFEy8kcYbqvEdJUszPuXM8yMNf4d7my1q4+Z2dd3zr1ABQzIEPG2+Nbcp2yY+6CZadyxvaumDagl7V0rbFk50C82lyZs+P9GAmExG1iuwdw4hUkvJjSpDkmWzWlX71MzYBwn3GgMzf667s5VMg66v9gcGu88pHgMa+Be0f/Un2r8y7QPrc+4o0TzNrtIJVcKUsZ/77nVNqO9WC07j2mLa6k1TJQqZ5lzOmKW1zwucs0p+UIGOcbiPK745BNJCrpV7+zjljk2jkEZpdXRZiWIh6btU5aljlWwu1Ix+rQKEUDdhi05bI2iodwEihz80F15UNCupkcd+QgjuG4caTBVA6mg/h1dlQ+XtV57rHKTJW4ZjkNYJIT+tVvaRwnUOLDL+vzA4cDW1KeVluNQ+TXpGwzFeIHLotqh2Sqqm4sbz4zDHPl2XkAUWc8pPbiUtuVvlY2+jgzHerxIeRR9LZvycx+qGcJVUjLgO9dxolwkYHqeFnfwALwsx0enqN2IntWnsAeugRtSSXW4d4HCKAbjW4H5KS874xA0Mjq4ZWbrTRIMcPMczfIm8dW/nQoVxhD/hX6hXzxL0pppxBqJUaey8STE1X9Bwhu9UIoHvw6OOI4OT6d5CrSmFNHdY+fzFbnGtAWZ6/OmPw/IbDT8Lyc+hBqPGE9LAoHMF6hpjyKNfdnL3DcOxFtsMhoPVShWowagbfFKjPjV3YvTSXiWB9ICuuO5NU56L8Rh82wqRgu9GEXU8KpG51kpDUZmD5qJ90HTrAt8/WDNMq1t8ARedwSHsvql66yqpb7VL2ZwcLueDgRmdpWjGFm0c4npgXwCdN6T46Vn/eiXPWue8AJYo3MreZR03xhnTn4Gje52+jHAOByKL8/nismDVVCO7UcyrQyyo5YXvJ3hhPTnHEH+nXTdNA/G6w+Z4g8NmXW/cyYW6n3m9XA2npBO4tqBcU0q90zoIuM3AEIwC3deQR0M95MAyXV9R1t+if7CZ9jiiYqH7WLIXKc8LWobLqXr4WDKPRLJxOI7mqQqdC/aa3bB+MdvH968+0LTMpu8gkqQKx9FvC1reIZ08lsMdHgGkEgvcDR1ze48FDRcYdiCs/7neZLBndp1RFC2vV6vwGrxc7yOLTtdiPTh7KTBnWnoM+XLBCtC9qB7c0pWip32ArL8qLO7Ml+pAl5EWwGvvzD7HvQqWGS1tluCpzobeK+luuVBeok7T350oPG8Tl8HgJkT4c/ys81HS2ZyebilwTnvtQSi3bHhvj4WtLtWC7yIzE4siV7qra1qy8Z1CjeB0Fy77cQhsd2OI370qLh2dBnZGRxo+iBAta0jEOBOQBCqit/qS8mWaSXadSopzah9rNPzL/wVQSwcIhHhf7vg7AACvsgAAUEsBAj8DFAAACAgAMokNXULbbhUIAwAAtAkAABYAAAAAAAAAAAAAALSBAAAAAGV4dGVuc2lvbi52c2l4bWFuaWZlc3RQSwECPwMUAAAICAAyiQ1d36MN37wAAABlAQAAEwAAAAAAAAAAAAAAtIE8AwAAW0NvbnRlbnRfVHlwZXNdLnhtbFBLAQI/AxQACAgIACeJDV1GACE+mwIAAKQFAAAWAAAAAAAAAAAAAACkgSkEAABleHRlbnNpb24vcGFja2FnZS5qc29uUEsBAj8DFAAICAgAG23wXLKGeo15AgAAJwQAABUAAAAAAAAAAAAAAKSBCAcAAGV4dGVuc2lvbi9MSUNFTlNFLnR4dFBLAQI/AxQACAgIADGJDV2EeF/u+DsAAK+yAAAbAAAAAAAAAAAAAACkgcQJAABleHRlbnNpb24vZGlzdC9leHRlbnNpb24uanNQSwUGAAAAAAUABQBVAQAABUYAAAAA";var ae="anyray.anyray-vscode",sf="vscode-handoffs",ik="vscode-receipts",Hs=2,NT=DT(OT),Nn={Code:{slug:"code",scheme:"vscode",macAppName:"Visual Studio Code",commands:["code","/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"]},"Code - Insiders":{slug:"code-insiders",scheme:"vscode-insiders",macAppName:"Visual Studio Code - Insiders",commands:["code-insiders","/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin/code-insiders"]},VSCodium:{slug:"vscodium",scheme:"vscodium",macAppName:"VSCodium",commands:["codium","/Applications/VSCodium.app/Contents/Resources/app/bin/codium"]}},$T={Code:{directory:"Microsoft VS Code",executable:"Code.exe"},"Code - Insiders":{directory:"Microsoft VS Code Insiders",executable:"Code - Insiders.exe"},VSCodium:{directory:"VSCodium",executable:"VSCodium.exe"}},MT=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),ck=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&MT(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ks=e=>{if(ck(e))try{return new URL(e.trim()).origin}catch{return}},FT=(e,t)=>{if(!e.endsWith(".app"))return!1;let n=e.slice(0,-4);if(n===t)return!0;if(!n.startsWith(`${t} `))return!1;let r=n.slice(t.length+1);return r.length>0&&/^\d+$/.test(r)},UT=e=>{try{return RT(e)}catch{return[]}},BT=e=>{try{return _T(e).mtimeMs}catch{return}},WT=(e,t,n,r,o)=>{if(!Gr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=Nn[e].commands[0],s=vt(t,xs[e]),i=[];for(let{directory:c,suffix:l}of[{directory:vt(s,"bin"),suffix:["bin","remote-cli"]},{directory:vt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=vt(c,d,...l,a),f=o(u);f!==void 0&&i.push({path:u,mtime:f})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},HT=(e,t,n)=>{let{macAppName:r,commands:o}=Nn[e],a=o[0],s=[];for(let i of["/Applications",ek.join(t,"Applications")])for(let c of n(i))FT(c,r)&&s.push(ek.join(i,c,"Contents/Resources/app/bin",a));return s},KT=(e,t=af(),n=ta(),r=process.env,o=UT,a=BT)=>{let s=WT(e,n,r,o,a);if(t==="darwin")return[...new Set([...Nn[e].commands,...HT(e,n,o),...s])];if(t!=="win32"){let u=Nn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=$T[e],c=LT.join,l=r.LOCALAPPDATA??c(n,"AppData","Local"),d=[c(l,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(u=>!!u);return[...new Set([...d.map(u=>c(u,i.directory,i.executable)),Nn[e].commands[0],...s])]},lk={run:async(e,t)=>({stdout:(await NT(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>PT(24).toString("base64url"),home:"",commandCandidates:e=>KT(e)},Qr=(e,t)=>vt(e,".anyray",ik,`${t}.json`),cf=(e,t)=>vt(e,".anyray",ik,`${t}.applied.json`),dk=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Uc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},ef=async(e,t,n)=>{try{let r=await t.run(e,[...n===void 0?[]:["--profile",n],"--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===ae.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===gn}catch{return}},uk=async(e,t)=>{let n=await dk(e,t);if(n)return ef(n.command,t)},GT=async(e,t,n)=>{let r=vt(e,".anyray",sf);for(let o of n){if(!o.endsWith(".json"))continue;let a=vt(r,o);try{if(!(await nf(a)).isFile()||JSON.parse(await wn(a,"utf8")).variant!==t)continue;await ml(a)}catch{}}},jT=async(e,t)=>{let n=vt(e,".anyray",sf),r;try{r=await ak(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=vt(n,o);try{if(!(await nf(a)).isFile()||JSON.parse(await wn(a,"utf8")).variant!==t)continue;await ml(a)}catch{}}},VT=async(e,t)=>{try{let n=JSON.parse(await wn(Qr(e,t),"utf8"));return n.extensionVersion===gn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==wr}catch{return!1}},pk=250,YT=9e4,ZT=YT/pk,XT=async(e,t,n,r)=>{for(let o=0;o<ZT;o++){try{let a=JSON.parse(await wn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Hs&&a.action===n?"confirmed":a.extensionVersion!==gn||a.extensionDistSha256!==wr?"reload-required":a.version===Hs&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(pk)}return"timeout"},JT=200,tk=(e,t)=>{let n=e,r=[typeof n?.name=="string"&&n.name?n.name:"Error"];typeof n?.code=="number"?r.push(`exit ${n.code}`):typeof n?.code=="string"&&n.code&&r.push(n.code);let a=(typeof n?.stderr=="string"?n.stderr:"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0);if(a){let s=a;t&&(s=s.replaceAll(t,"<nonce>")),s=s.replace(/\b(ark_|sk-|adt_|enl_)[A-Za-z0-9_-]+/g,"$1\u2026"),r.push(s.slice(0,JT))}return r.join(": ")},qT=async e=>{try{let t=await nf(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},nk=e=>rk("sha256").update(e).digest("hex"),zT=async(e=ta())=>{let t=Buffer.from(Qb,"base64");if(t.length<4||t[0]!==80||t[1]!==75||nk(t)!==hl)throw new Error("bundled VS Code extension failed integrity validation");let n=vt(e,".anyray","vscode-extension"),r=vt(n,`anyray-vscode-${gn}-${hl.slice(0,12)}.vsix`);try{if(nk(await wn(r))===hl)return r}catch{}await rf(n,{recursive:!0,mode:448});let o=`${r}.${ok()}.tmp`;try{await of(o,t,{mode:384}),await he(o,r),af()!=="win32"&&await TT(r,384)}finally{await sk(o,{force:!0})}return r},tf=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=>tf(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${tf(t[n])}`).join(",")}}`},fk=(e,t,n)=>rk("sha256").update(tf({gatewayUrl:Ks(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:gn,extensionDistSha256:wr,profiles:[...n].sort()})).digest("hex"),QT=async(e,t,n,r,o,a)=>{let s=JSON.parse(await wn(cf(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==fk(t,n,r))return!1;let i=JSON.parse(await wn(Qr(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===gn&&i.extensionDistSha256===wr&&i.gatewayUrl===Ks(t.origin)?await uk(e,a)===!0:!1},eL=async(e,t,n,r)=>{let o=cf(e,t),a=`${o}.${ok()}.tmp`;try{await rf(Qp(o),{recursive:!0,mode:448}),await of(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
109
+ `,{mode:384}),await he(a,o)}catch{}finally{await sk(a,{force:!0})}},tL=async(e,t)=>{await ml(cf(e,t)).catch(()=>{})},hk=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...lk,...r,home:r.home??ta()},s=Nn[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!ck(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,A,v)=>typeof b.id=="string"&&b.id.length>0&&b.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.id)&&typeof b.name=="string"&&b.name.length>0&&b.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.name)&&v.findIndex(E=>E.id===b.id)===A);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await dk(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!gp(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>Tw(b,af(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await QT(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:Qr(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let f=a.extensionPath;if(n==="configure"){try{f??=await zT(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await qT(f))return{ok:!1,reason:"extension-missing"}}let p=a.nonce(),h=vt(a.home,".anyray",sf,`${p}.json`),m=Qr(a.home,s.slug);await rf(Qp(h),{recursive:!0,mode:448});let w=await ak(Qp(h)).catch(()=>[]);await of(h,`${JSON.stringify({version:Hs,action:n,nonce:p,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:gn,expectedExtensionDistSha256:wr})}
110
+ `,{mode:384}),await GT(a.home,s.slug,w).catch(()=>{});let g={installed:[],failed:[]},y=!1;try{if(n==="configure"){let A=await VT(a.home,s.slug);if(A||await ef(l,a)!==!0)try{await a.run(l,["--install-extension",f,"--force"])}catch(v){return y=!0,{ok:!1,reason:"install-failed",detail:tk(v,p)}}for(let v of u)try{(A||await ef(l,a,v)!==!0)&&await a.run(l,["--profile",v,"--install-extension",f,"--force"]),g.installed.push(v)}catch{g.failed.push(v)}}try{await a.run(l,["--open-url",`${s.scheme}://${ae}/configure?nonce=${encodeURIComponent(p)}`])}catch(A){return{ok:!1,reason:"handoff-undeliverable",detail:tk(A,p)}}let b=await XT(m,p,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(y=!0,n==="configure")g.failed.length===0&&await eL(a.home,s.slug,fk(t,o,u),p);else{await tL(a.home,s.slug),await jT(a.home,s.slug).catch(()=>{});for(let A of[void 0,...u])try{await a.run(l,[...A?["--profile",A]:[],"--uninstall-extension",ae])}catch{}}return{ok:!0,receipt:m,profiles:g}}catch{return{ok:!1,reason:"failed"}}finally{y&&await ml(h).catch(()=>{})}},mk=async(e,t=ta())=>{try{let n=JSON.parse(await wn(Qr(t,Nn[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==gn||n.extensionDistSha256!==wr)}catch{return!1}},yl=async(e,t=ta())=>{try{let n=JSON.parse(await wn(Qr(t,Nn[e].slug),"utf8"));return n.version!==Hs||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},yk=async(e,t,n=ta(),r={})=>{try{let o=Ks(t);if(!o)return!1;let a=JSON.parse(await wn(Qr(n,Nn[e].slug),"utf8"));if(!(a.version===Hs&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===gn&&a.extensionDistSha256===wr))return!1;let i={...lk,...r,home:n};return await uk(e,i)===!0}catch{return!1}};var br="Anyray",bn="anyray",Ak="--anyray-owner=vscode-profile-v1",Gs=e=>Ck(Ye(e),"User","chatLanguageModels.json"),cL=e=>Ck(Ye(e),"User","settings.json"),js="github.copilot.advanced",wl="debug.overrideCapiUrl",St=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lL=e=>{if(typeof e!="string")return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&!t.username&&!t.password&&!t.search&&!t.hash&&/^\/v1\/copilot\/[^/]+\/ark_[A-Za-z0-9_-]{20,512}\/?$/.test(t.pathname)}catch{return!1}},vk=e=>{let t=e[js];if(!St(t)||!lL(t[wl]))return{next:e,removed:!1};let n={...t};delete n[wl];let r={...e};return Object.keys(n).length>0?r[js]=n:delete r[js],{next:r,removed:!0}},Vs="anyray-default",Ys=()=>{let e=(process.env.ANYRAY_COPILOT_MODEL??"").split(",").map(t=>t.trim()).filter(t=>t.length>0&&t.length<=200&&!/[\u0000-\u001f\u007f]/.test(t)).filter((t,n,r)=>r.indexOf(t)===n).slice(0,64);return e.length?e:[Vs]},Sk=e=>e===Vs?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),gl=async e=>{if(!await O(e))return{kind:"missing"};try{let t=await kk(e,"utf-8");if(!t.trim())return{kind:"array",entries:[]};let n=JSON.parse(t);return Array.isArray(n)?{kind:"array",entries:n}:{kind:"unrecognized"}}catch{return{kind:"unrecognized"}}},Ek=async(e,t)=>{await rL(iL(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${sL()}`;try{await aL(n,`${JSON.stringify(t,null,2)}
111
+ `,{flag:"wx",mode:384}),await he(n,e),await nL(e,384)}finally{await oL(n,{force:!0}).catch(()=>{})}},lf=e=>{if(!St(e))return!1;let t=e,n=Object.keys(t).sort(),r=["apiType",...t.apiKey===void 0?[]:["apiKey"],"models","name","vendor"].sort();return n.length!==r.length||!n.every((o,a)=>o===r[a])||t.name!==br||t.vendor!=="customendpoint"||t.apiType!=="chat-completions"||!(t.apiKey===void 0||typeof t.apiKey=="string"&&t.apiKey.length>0&&t.apiKey.length<=512&&!/[\u0000-\u001f\u007f]/.test(t.apiKey))||!Array.isArray(t.models)||t.models.length===0||t.models.length>64?!1:t.models.every(o=>{if(!St(o))return!1;let a=["id","maxInputTokens","maxOutputTokens","name",...o.requestHeaders===void 0?[]:["requestHeaders"],"toolCalling","url","vision"].sort(),s=Object.keys(o).sort();if(s.length!==a.length||!s.every((i,c)=>i===a[c])||typeof o.id!="string"||o.id.length===0||o.id.length>200||o.name!==Sk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!St(o.requestHeaders)||Object.keys(o.requestHeaders).length!==1||typeof o.requestHeaders["x-anyray-metadata"]!="string"||o.requestHeaders["x-anyray-metadata"].length>8192))return!1;try{let i=new URL(o.url);return(i.protocol==="https:"||i.protocol==="http:")&&!i.username&&!i.password&&!i.search&&!i.hash&&i.pathname==="/v1/chat/completions"}catch{return!1}})},df=e=>{let t=e.filter(n=>!lf(n));return{next:t,removed:t.length!==e.length}},dL=async(e,t)=>{let n=Gs(e),r=await gl(n);if(r.kind==="missing")return{changedFiles:[],messages:[],manual:!1};if(r.kind==="unrecognized")return{changedFiles:[],manual:!0,messages:[`Could not recognize ${n}; left it untouched. Remove the legacy "${br}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=df(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${br}" Custom Endpoint from ${n}.`]};try{return await Ek(n,o),await se(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${br}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${br}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},uL=async e=>{try{let t=yn(await kk(e,"utf-8"));if(St(t))return vk(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${js}.${wl} in ${e}, which uses JSONC that Connect will not rewrite; remove it manually.`]}:{changedFiles:[],messages:[],manual:!1}}catch{}return{changedFiles:[],manual:!0,messages:[`Could not parse ${e}; remove an old Anyray ${js}.${wl} value manually if present.`]}},xk=async(e,t)=>{let n=cL(e),r;try{r=await U(n)}catch{return uL(n)}let{next:o,removed:a}=vk(r);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the retired Anyray Copilot debug override from ${n}.`]};try{return await X(n,o,{backup:!1}),await se(n),{changedFiles:[n],manual:!1,messages:[`Removed the retired Anyray Copilot debug override from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the retired Anyray Copilot debug override from ${n}; remove it manually.`]}}},pL=async(e,t)=>{let n=await dL(e,t),r=await xk(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},Ik=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,Ak]}},Ok=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},Rk=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),fL=e=>Array.isArray(e.args)&&e.args.at(-1)===Ak,_k=(e,t)=>{if(!t.hookBinaryIsDurable()||!St(e)||!Ok(e,["type","command","args"]))return!1;let n=Ik(t);return e.type==="stdio"&&e.command===n.command&&Rk(e.args,n.args)},hL=(e,t)=>{if(!St(e)||!Ok(e,["type","command","args"])||e.type!=="stdio"||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(i=>typeof i=="string"))return!1;let n=t.mcpServerCommand("profile");if(e.command===n.command&&Rk(e.args,n.args))return!0;if(je(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===sr&&r.at(-1)==="profile"))return!1;let a=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(a))return r.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(a)||r.length!==3)return!1;let s=r[0].replaceAll("\\","/");return!je(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},uf=(e,t)=>_k(e,t)?"exact":St(e)&&fL(e)||hL(e,t)?"stale-owned":"foreign",gk=e=>`MCP name conflict in ${e}: servers.${bn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,mL=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let p of a)try{let h=await U(p);if(i){if("servers"in h&&!St(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${p} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let y=St(h.servers)?{...h.servers}:{},b=Ik(o),A=y[bn],v=A===void 0?void 0:uf(A,o);if(v==="exact"){d+=1;continue}if(v==="foreign"){u=!0,l.push(gk(p));continue}if(t){d+=1;continue}y[bn]=b,f.push({path:p,next:{...h,servers:y},backup:v!=="stale-owned",clearBackupAfter:!1});continue}if(!St(h.servers)||!(bn in h.servers))continue;if(uf(h.servers[bn],o)==="foreign"){u=!0,l.push(gk(p));continue}if(t)continue;let w={...h.servers};delete w[bn];let g={...h};Object.keys(w).length===0?delete g.servers:g.servers=w,f.push({path:p,next:g,backup:!1,clearBackupAfter:!0})}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let p of f)try{await X(p.path,p.next,p.backup?{}:{backup:!1}),p.clearBackupAfter&&await se(p.path),c.push(p.path),i&&(d+=1)}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p.path} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`);break}return i?l.unshift(t?d===a.length?`Would register the Anyray retrieval MCP server in ${a.length} VS Code user profile config(s).`:`Would register the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); resolve the conflicts below first.`:d===a.length?`Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) in ${a.length} VS Code user profile config(s).`:`Registered the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); see the profile-specific errors below.`):n?l.unshift(t?`Would skip the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary.`:`Skipped the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary; removed any stale owned registration. Re-run via the installer or a global install to enable retrieval.`):l.unshift(`${t?"Would skip":"Skipped"} the Anyray retrieval MCP server because this VS Code build predates profile-scoped mcp.json support (${Ow}+).`),{changedFiles:c,messages:l,manual:u}},yL=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await O(c))try{let l=await U(c);if(!St(l.servers)||!(bn in l.servers)||uf(l.servers[bn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[bn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await X(c,u,{backup:!1}),await se(c),a.push(c)}catch{}return t&&i>0?s.push(`would remove the Anyray retrieval MCP server from ${i} VS Code user profile config(s)`):a.length>0&&s.push("Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."),{changedFiles:a,messages:s,manual:!1}},Pk=e=>[...e.installed.length>0?[`Also installed into ${e.installed.length} additional VS Code profile(s): ${e.installed.join(", ")}. Config is shared through SecretStorage \u2014 no further steps.`]:[],...e.failed.length>0?[`Couldn\u2019t install into profile(s): ${e.failed.join(", ")}. Open VS Code with that profile and use \u201CApply Extension to all Profiles\u201D, or re-run anyray-connect.`]:[]],Tk=()=>`${ae} is already installed and configured for this gateway \u2014 skipped the VSIX reinstall and the VS Code URI confirmation prompt. (Run --revert first to force re-delivery.)`;var wk=(e,t)=>[`${ae} mirrors the GitHub Copilot models available to this VS Code install.`,`Gateway: ${e.origin} (client key stored by VS Code SecretStorage).`,"Mode: SUBSCRIPTION \u2014 requests use your existing Copilot sign-in and model; Anyray supplies a supported before-request optimization provider.","Inline completions remain native GitHub Copilot traffic. Choose an \u201CAnyray \xB7 \u2026\u201D model in Chat for optimized requests.",'Copilot\u2019s internal utility models (chat titles, summaries) keep working with an Anyray main model: the extension sets VS Code\u2019s chat.byokUtilityModelDefault to "copilot" unless you already set it yourself.',"VS Code profiles scope extensions; Connect installs the provider into every profile registered at apply time. A profile created later needs a Connect re-run (or VS Code\u2019s \u201CApply Extension to all Profiles\u201D action).","Copilot Business/Enterprise administrators must allow language-model providers in GitHub\u2019s Bring Your Own Language Model Key policy."],Lk=(e,t,n,r)=>({runMcp:o=>mL(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):pL(e,o)}),Dk=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${ae} VSIX${a}. Nothing was configured. Run \`${n?"code":t.toLowerCase()} --install-extension\` by hand on that VSIX to see the full error.`;case"handoff-undeliverable":return n?`Installed ${ae} and staged its configuration, but could not hand it over${a}. A remote VS Code server's command-line launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\`. Reload the VS Code window attached to this machine (Developer: Reload Window): the extension applies the staged configuration as it loads, so there is nothing to re-run.`:`Installed ${ae} and staged its configuration, but could not hand it to ${t}${a}. Reload ${t} (quit and reopen): the extension applies the staged configuration as it loads, so there is nothing to re-run.`;case"reload-required":return`A newer ${ae} build was installed, but ${t} is still running the previous build. Reload VS Code completely \u2014 the new build applies the staged configuration as it loads, so there is nothing to re-run.`;case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher on this machine. Run anyray-connect from the integrated terminal of the VS Code window attached here (Terminal \u2192 New Terminal in that window) \u2014 a plain SSH shell has no "code" on PATH and cannot hand the key to a running window. No VS Code configuration was written.`:`The ${t} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`;case"unsupported-version":return`The Anyray language-model provider requires VS Code ${yp} or newer. Upgrade ${t}, then re-run anyray-connect; no extension configuration was written.`;case"unsafe-gateway":return"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.";case"extension-missing":return`This anyray-connect installation is missing its bundled ${ae} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${ae} installed and VS Code accepted the ${r}, but its extension host never confirmed. Reload the VS Code window attached to this machine (Developer: Reload Window): the staged configuration applies as it loads.`:`${ae} installed and ${t} accepted the ${r}, but its extension host never confirmed. Reload ${t} completely (quit and reopen): the staged configuration applies as it loads.`;default:return n?`VS Code did not confirm the one-time ${ae} ${r}${a}. The configuration is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension applies it as it loads.`:`VS Code did not confirm the one-time ${ae} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},gL=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${ae} still holds its SecretStorage configuration`;switch(e){case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher, so Anyray could not ask ${ae} to clear its SecretStorage configuration. Re-run revert from the integrated terminal of the VS Code window attached to this machine.`:`The ${t} command-line launcher was not found, so Anyray could not ask ${ae} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${ae} reset to VS Code${o}, so ${a} until it reloads. A remote VS Code server's launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\` \u2014 but the reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`Could not hand the ${ae} reset to ${t}${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;case"activation-timeout":return n?`VS Code accepted the ${ae} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`${t} accepted the ${ae} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;default:return n?`VS Code did not confirm the ${ae} reset${o}, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`VS Code did not confirm the ${ae} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},wL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Lk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${ae} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...wk(t,a),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${ae}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"copilot-seat"});if(!d.ok)return{status:"manual",messages:[Dk(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[Tk()]:[],...wk(t,a),...d.alreadyCurrent?[]:Pk(d.profiles),...f.messages,...u.messages]}},bk=e=>[`${ae} exposes the configured Anyray gateway models without writing a key to chatLanguageModels.json.`,`Gateway: ${e.origin} (personal client key and attribution stored together in VS Code SecretStorage).`,"Mode: API KEY \u2014 the extension streams normal /v1/chat/completions requests through Anyray. Text chat only: the models register without tool calling (the OpenAI bridge cannot carry VS Code's structured tool results).",`Models in the picker: ${Ys().join(", ")}.`,"Inline GitHub Copilot completions remain native GitHub traffic; choose an Anyray model in Chat for gateway-routed requests.",'Copilot\u2019s internal utility models (chat titles, summaries) follow the selected Anyray model: the extension sets VS Code\u2019s chat.byokUtilityModelDefault to "mainAgent" unless you already set it yourself.',"VS Code profiles scope extensions; Connect installs the provider into every profile registered at apply time. A profile created later needs a Connect re-run (or VS Code\u2019s \u201CApply Extension to all Profiles\u201D action).","Copilot Business/Enterprise administrators must allow language-model providers in GitHub\u2019s Bring Your Own Language Model Key policy."],bL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Lk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${ae} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...bk(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${ae}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Ys().map(p=>({id:p,name:Sk(p)}))});if(!d.ok)return{status:"manual",messages:[Dk(d.reason,e,a,"gateway API configuration",d.detail)]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[Tk()]:[],...bk(t),...d.alreadyCurrent?[]:Pk(d.profiles),...f.messages,...u.messages]}},kL=async(e,t,n)=>{let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null};let o=[];for(let s of r){if(!await O(s))return{registered:!1,command:null};try{let i=await U(s),c=St(i.servers)?i.servers[bn]:void 0;if(!_k(c,n))return{registered:!1,command:null};o.push(c.command)}catch{return{registered:!1,command:null}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var CL=async(e={installedVariant:Jo,remoteServerVariant:bp,isRemoteDevContext:Gr})=>{let t=await e.installedVariant();if(t)return{variant:t,remote:!1};if(!e.isRemoteDevContext())return{remote:!1};let n=await e.remoteServerVariant();return n?{variant:n,remote:!0}:{remote:!1}},AL={installedVariant:Jo,remoteServerVariant:bp,detectVscodeLmProviderEligibility:Nw,configureVscodeExtension:hk,vscodeExtensionPointsAt:yk,vscodeExtensionAwaitingReload:mk,vscodeExtensionReceiptMode:yl,hookBinaryIsDurable:le,hookBinaryPath:Oe,mcpServerCommand:Ve,vscodeUserMcpConfigPaths:Lw,isRemoteDevContext:Gr},vL=(e={})=>{let t={...AL,...e},n=()=>CL(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Ws,quitTarget:fl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Xo(r,!0)}`:Gs(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!xe(r.clientKey))return{status:"manual",messages:["Enrollment required: Copilot setup needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; no VS Code configuration was written."]};let{variant:a,remote:s}=await n();if(!a)return{status:"manual",messages:[t.isRemoteDevContext()?"No VS Code server found here yet \u2014 this looks like a dev container, Codespace, or SSH remote. `--tools copilot` now configures the Anyray provider directly in a remote VS Code window, but only after VS Code has attached to this machine and installed its server. Open this machine with the VS Code Remote-SSH (or Dev Containers) extension, then re-run anyray-connect --tools copilot in that window\u2019s integrated terminal. To route this shell through Anyray without the Copilot UI, use an in-container tool instead: anyray-connect --tools opencode --sso <link> --subscription.":"No VS Code install found. Install VS Code, then re-run anyray-connect; the personal key will be transferred directly into SecretStorage."]};let i=await t.detectVscodeLmProviderEligibility(a);if(i.status==="needs-update")return{status:"manual",messages:[`${a} ${i.version??""} cannot expose public third-party models in Chat's picker. Upgrade to VS Code ${yp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||Rw(i.version);return J(r,"copilot")?wL(a,r,o,t.configureVscodeExtension,c,s,t):bL(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?kL(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ks(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await gl(Gs(o));if(s.kind==="array"){let c=s.entries.find(lf)?.models?.[0]?.url;if(typeof c=="string"&&new URL(c).origin===a)return!0}return!1},async routingExpected(r){if(r.includes("copilot"))return!0;let{variant:o}=await n();return o?(await t.detectVscodeLmProviderEligibility(o)).status!=="needs-update":!1},async routingPendingReload(){let{variant:r}=await n();return r?t.vscodeExtensionAwaitingReload(r):!1},async inferenceAuthLanes(){try{let{variant:r}=await n();if(!r)return["unknown"];let o=await gl(Gs(r));if(o.kind==="array"&&o.entries.some(lf))return["api_key"];let a=await t.vscodeExtensionReceiptMode(r);if(a==="copilot-seat")return["subscription"];if(a==="gateway-api")return["api_key"]}catch{}return["unknown"]},async revert(r){let{variant:o,remote:a}=await n();if(!o)return{status:"not-found",messages:["no VS Code install found \u2014 nothing to revert"]};let s=await yL(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await xk(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${ae} to clear its global configuration and SecretStorage key`);else{let y=await t.configureVscodeExtension(o,void 0,"reset");y.ok?(c=!0,d=y.receipt,u.push(`Cleared ${ae} gateway configuration and secret.`)):(l=!0,u.push(gL(y.reason,o,a,y.detail)))}let f=Gs(o),p=await gl(f),h=p.kind==="missing"||p.kind==="array"&&!df(p.entries).removed,m=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),h)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:m.length?m:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:m.length?m:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:m,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(p.kind==="unrecognized")return{status:"manual",changedFiles:m.length?m:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${br}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=df(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${br} Custom Endpoint from ${f}`]};await Ek(f,w);let g=[...u,`Removed the ${br} Custom Endpoint from ${f}.`];return await se(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},Nk=vL();import{accessSync as jL,constants as Vk,statSync as VL}from"node:fs";import{readFile as Yk,rm as Xs}from"node:fs/promises";import{homedir as Cf,platform as eC}from"node:os";import{delimiter as YL,join as Af,resolve as ZL}from"node:path";import{execFile as OL}from"node:child_process";import{readFile as RL}from"node:fs/promises";import{homedir as hf,platform as _L}from"node:os";import{join as Zs}from"node:path";import{join as SL}from"node:path";var pf="Iv1.b507a08c87ecfe98",EL="https://github.com/login/device/code",xL="https://github.com/login/oauth/access_token",IL="read:user",$k=1e4,na=()=>SL(Q(),"copilot-seat-login.json"),Mk={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},ff=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fk=async(e={})=>{let t={...Mk,...e};try{let n=await t.fetch(EL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:pf,scope:IL}),signal:AbortSignal.timeout($k)});if(!n.ok)return;let r=await n.json();if(!ff(r))return;let o=r.device_code,a=r.user_code,s=r.verification_uri;if(typeof o!="string"||typeof a!="string"||typeof s!="string")return;let i=r.interval,c=r.expires_in;return{deviceCode:o,userCode:a,verificationUri:s,intervalSeconds:typeof i=="number"&&i>0?i:5,expiresInSeconds:typeof c=="number"&&c>0?c:900}}catch{return}},Uk=async(e,t={})=>{let n={...Mk,...t},r=n.now()+e.expiresInSeconds*1e3,o=e.intervalSeconds*1e3;for(;n.now()<r;){await n.sleep(o);try{let s=await(await n.fetch(xL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:pf,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout($k)})).json();if(!ff(s))continue;let i=s.access_token;if(typeof i=="string"&&i.length>0)return{status:"ok",token:i};let c=s.error;if(c==="authorization_pending")continue;if(c==="slow_down"){let l=s.interval;o=(typeof l=="number"&&l>0?l:o/1e3+5)*1e3;continue}return c==="access_denied"?{status:"denied"}:c==="expired_token"?{status:"expired"}:{status:"failed"}}catch{continue}}return{status:"expired"}},Bk=async(e,t)=>{let n=na();return await pe(n,`${JSON.stringify({token:e,clientId:pf,mintedAtIso:t},null,2)}
112
+ `),n},bl=async()=>{try{let e=await U(na());if(!ff(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var PL=5e3,mf=5e3,TL=["copilot-cli","CopilotCLI"],LL="https://api.github.com/copilot_internal/user",Hk="~/.copilot/config.json",Kk="macOS Keychain (Copilot CLI)",Gk=e=>e===Hk||e===Kk,ra=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),nn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),DL=()=>process.env.XDG_CONFIG_HOME?.trim()||Zs(hf(),".config"),NL=()=>process.env.XDG_DATA_HOME?.trim()||Zs(hf(),".local","share"),$L=async()=>{try{let e=await RL(Zs(hf(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return ra(t)?t:void 0}catch{}},ML=async e=>{try{let t=await U(Zs(DL(),"github-copilot",e));if(!nn(t))return;for(let n of Object.values(t))if(nn(n)&&ra(n.oauth_token))return n.oauth_token}catch{}},FL=async()=>{try{let e=await U(Zs(NL(),"opencode","auth.json")),t=nn(e)?e["github-copilot"]:void 0;if(!nn(t)||t.type!=="oauth")return;if(ra(t.access))return t.access;if(ra(t.refresh))return t.refresh}catch{}},UL=(e,t)=>new Promise((n,r)=>{try{OL(e,[...t],{timeout:PL},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),BL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return ra(r)?r:void 0}catch{return}},WL=async(e=UL)=>{for(let t of TL){let n=await BL(t,e);if(n)return n}};var kl={env:process.env,platform:_L,tokenFromDeviceLogin:bl,tokenFromCopilotCliConfig:$L,tokenFromSharedConfig:ML,tokenFromOpenCode:FL,tokenFromKeychain:WL,fetch:(...e)=>fetch(...e)},HL=new Set([401,403,404]),jk=/^[a-z][a-z0-9-]{0,30}$/,KL=e=>e!=="default"&&jk.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",GL=e=>typeof e!="string"?"default":/^https:\/\/api\.([a-z][a-z0-9-]{0,30})\.githubcopilot\.com\/?$/.exec(e.trim())?.[1]??"default",yf=async(e,t={})=>{let n={...kl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),mf);try{let a=await n.fetch(LL,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=nn(i)&&nn(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:GL(s)}}return{verdict:HL.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var oa=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${jk.test(n)?n:"default"}/header/models`,a=await Wk(o,e,r.clientKey,t);if(a.length>0)return a}return Wk(`${KL(n)}/models`,e,void 0,t)},Wk=async(e,t,n,r={})=>{let o={...kl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),mf);try{let i=await o.fetch(e,{headers:{authorization:`Bearer ${t}`,...n?{"x-anyray-api-key":n}:{}},signal:a.signal});if(!i.ok)return[];let c=await i.json(),l=nn(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!nn(u))continue;let f=u.id;if(typeof f!="string"||f.length===0||u.model_picker_enabled!==!0)continue;let p=u.policy;if(nn(p)&&p.state!=="enabled")continue;let h=u.supported_endpoints,m=Array.isArray(h)?h.filter(E=>typeof E=="string"):[],w=u.capabilities,g=nn(w)?w.limits:void 0,y=E=>{let x=nn(g)?g[E]:void 0;return typeof x=="number"&&Number.isFinite(x)&&x>0?Math.floor(x):void 0},b={id:f,endpoints:m},A=y("max_prompt_tokens"),v=y("max_output_tokens");A!==void 0&&(b.maxPromptTokens=A),v!==void 0&&(b.maxOutputTokens=v),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},Cl=async(e,t,n,r={})=>{let o={...kl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),mf);try{let i=/\/responses\/?$/.test(new URL(e).pathname),c=await o.fetch(e,{method:"POST",headers:{...t,"content-type":"application/json"},body:JSON.stringify(i?{model:n,max_output_tokens:16,input:"ping"}:{model:n,max_tokens:1,messages:[{role:"user",content:"ping"}]}),signal:a.signal});return c.ok?"ok":c.status===400||c.status===404||c.status===422?"rejected":"unreachable"}catch{return"unreachable"}finally{clearTimeout(s)}},Al=async(e={},t={})=>{let n={...kl,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return ra(a)?a:void 0}},{source:"~/.config/github-copilot/apps.json",read:()=>n.tokenFromSharedConfig("apps.json")},{source:"~/.config/github-copilot/hosts.json",read:()=>n.tokenFromSharedConfig("hosts.json")},{source:"OpenCode github-copilot login",read:()=>n.tokenFromOpenCode()},{source:"Anyray Copilot sign-in (device login)",read:()=>n.tokenFromDeviceLogin()},...e.allowKeychainPrompt===!0&&n.platform()==="darwin"?[{source:Kk,read:()=>n.tokenFromKeychain()}]:[],{source:Hk,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await yf(s,t);if(i.verdict==="no-copilot"){o.push(a.source);continue}return{token:{token:s,source:a.source},rejected:o,capiSegment:i.capiSegment}}return{rejected:o}};var no="copilot-cli",kn="copilot-cli",XL=Ws,JL=()=>XL()?["VS Code is open \u2014 its Copilot CLI runs inside the extension host, which","captured your shell environment when the editor launched. Restart VS Code,","or its CLI chat and Autopilot sessions stay on native GitHub traffic and","never reach the gateway (no spend, no traces) even though this block is set."]:[],tC=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],vf=()=>Object.fromEntries(tC.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),gf=()=>Af(Cf(),".anyray","copilot-cli.sh"),nC="# Managed by anyray-connect. Do not source this file anywhere else.",Zk=e=>e.split(/\r?\n/,1)[0]===nC,qL=["COPILOT_PROVIDER_TYPE","COPILOT_PROVIDER_BASE_URL","COPILOT_PROVIDER_WIRE_API","COPILOT_PROVIDER_HEADERS","COPILOT_MODEL","COPILOT_PROVIDER_MAX_PROMPT_TOKENS","COPILOT_PROVIDER_MAX_OUTPUT_TOKENS","COPILOT_PROVIDER_API_KEY"],vl="COPILOT_PROVIDER_API_KEY",Xk=e=>e.startsWith(`export ${vl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Mn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",zL=()=>Ys()[0],Js=(e="default")=>`/copilot/${e}/header`,Mz=Js(),eo=e=>e.replace(/\/+$/,""),QL=(e,t="default")=>`${eo(e.openaiBaseUrl)}${Js(t)}`,wf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),kf="claude-sonnet-5",eD=()=>{let e=Ys()[0];return e===Vs?kf:e},rC=e=>e.endpoints.includes(Mn(e.id)==="responses"?"/responses":"/chat/completions"),Sf=e=>{let t=e.filter(rC),n=a=>{let s=/^claude-sonnet-(\d+(?:\.\d+)*)$/.exec(a);return s?s[1].split(".").map(Number):void 0},r=t.map(a=>({m:a,version:n(a.id)})).filter(a=>!!a.version).sort((a,s)=>Jk(a.version,s.version)?-1:Jk(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var Jk=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n+=1){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r>0}return!1},qk=(e,t,n,r,o,a="default")=>{let s=de({...e.metadata,tool:no}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...tC];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(QL(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Mn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...o?.maxPromptTokens?[`export COPILOT_PROVIDER_MAX_PROMPT_TOKENS='${o.maxPromptTokens}'`]:[],...o?.maxOutputTokens?[`export COPILOT_PROVIDER_MAX_OUTPUT_TOKENS='${o.maxOutputTokens}'`]:[],...i.length>0?[`export COPILOT_PROVIDER_HEADERS=${ve(i.join(`
113
+ `))}`]:[],`export ${vl}=${ve(n)}`]},bf=(e,t,n)=>{let r=de({...e.metadata,tool:no});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Mn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${ve(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${vl}=${ve(n)}`]:[]]},tD=(e,t)=>t||!J(e,"copilot"),zk=()=>{let e=qL.filter(t=>(process.env[t]??"")!=="");return e.length===0?[]:[`This shell still exports ${e.join(", ")} \u2014 Copilot CLI keeps using BYOK until you`,`run \`unset ${e.join(" ")}\` or open a new terminal (fully quit a long-lived parent app).`]},Qk=(e,t=[])=>["Left on native GitHub Copilot inference \u2014 a Copilot seat was detected, but no","Copilot sign-in Connect can read. To route the CLI through Anyray with billing","KEPT on your Copilot plan, give Connect a seat token and re-run:",...e==="darwin"?[" - run `copilot` once and `/login` (macOS Keychain; read on",` \`anyray-connect --tools ${no}\`), or`]:[" - run `copilot` once and `/login` (say YES to storing credentials locally),"," then re-run \u2014 Connect reads the sign-in left in ~/.copilot/ or"," ~/.config/github-copilot/ on any run, with no extra flag, or"]," - set COPILOT_GITHUB_TOKEN to a Copilot OAuth token, or sign into"," OpenCode\u2019s github-copilot provider.",...t.length>0?[`GitHub rejected the sign-in Connect did find (${t.join(", ")}):`,"it is expired, or its account holds no Copilot seat. Sign in again."]:[],"To route on org API billing instead (replaces seat inference), re-run with `--org`."],nD=(e=process.env.PATH,t=eC())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(YL)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=ZL(o,n);try{if(!VL(a).isFile())continue;return jL(a,t==="win32"?Vk.F_OK:Vk.X_OK),a}catch{}}},rD=()=>Af(Cf(),".copilot","config.json"),$n=()=>Af(Cf(),".copilot","mcp-config.json"),to="anyray",oD=()=>({type:"local",...Ve("profile"),tools:["*"]}),kr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),aD=async()=>{let e=$n(),t;try{t=await U(e)}catch{return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because ${e} could not be parsed; it was left unchanged.`}}if("mcpServers"in t&&!kr(t.mcpServers))return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because mcpServers in ${e} is not an object; it was left unchanged.`};let r=(kr(t.mcpServers)?t.mcpServers:{})[to];return r!==void 0&&!qt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${to} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},sD=async e=>{let t=$n(),n=e.json,r=kr(n.mcpServers)?n.mcpServers:{};r[to]=oD(),n.mcpServers=r,await X(t,n)},iD=async()=>{let e=$n(),t;try{let r=await U(e);if(!kr(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!kr(n)||!(to in n)||!qt(n[to],"profile")?!1:(delete n[to],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Xs(e,{force:!0}):await X(e,t,{backup:!1}),await se(e),!0)},cD={resolveCopilotCommand:nD,platform:eC,detectCopilotSeat:kp,discoverSeatToken:Al,readDeviceLoginToken:bl,fetchSeatModelCatalog:oa,probeSeatChatModel:Cl},lD=e=>`'${e.replace(/'/g,"''")}'`,dD=e=>e.split(`
114
+ `).map(lD).join(" + [Environment]::NewLine + "),uD=(e={})=>{let t={...cD,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await zc(At(),kn))?.find(c=>c.startsWith("export COPILOT_PROVIDER_BASE_URL="));if(i)return i.slice(i.indexOf("=")+1).replace(/^'|'$/g,"")},o=(s,i)=>s!==void 0&&eo(s)===`${eo(i)}/v1`,a=(s,i)=>s!==void 0&&wf(s)&&eo(s).startsWith(`${eo(i)}/v1/copilot/`);return{id:no,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Ws,quitTarget:fl},async usesDynamicCredential(s){let i=await r();return a(i,s)||!o(i,s)?!1:!await O(gf())},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=rD();return await O(i)?{installed:!0,detail:i}:{installed:!1,detail:"no `copilot` on PATH and no ~/.copilot state"}},async apply(s,i){let c=At(),l=async(E,x,C)=>{let I=E.filter(Xk),P=E.filter(Le=>!Xk(Le)),$=gf(),Y=[...P,...I.length>0?[`[ -r ${ve($)} ] && . ${ve($)}`]:[]],Z=await O($),W=Z?await Yk($,"utf8"):void 0,q=W===void 0||Zk(W);if(I.length>0&&!q)return{status:"manual",messages:[`Refused to overwrite user-managed ${$}; move or rename that file, then run Connect again.`]};let me=le(),Te=me?await aD():void 0,ne=[`${c} \u2190 managed Anyray block (${kn})`,...x.map(Le=>` ${Le}`),...I.length>0?[`${$} \u2190 owner-only credential (mode 0600)`]:["No key exported \u2014 the local refresh daemon injects a freshly minted","key per request, so a running CLI session never carries a stale one."],...C,Te?.status==="skipped"?Te.message:me?`${$n()} \u2190 Anyray retrieval MCP server (anyray_retrieve / anyray_recall)`:`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable retrieval.`,"Inline `copilot` completions and GitHub-hosted features stay native GitHub traffic.",`Run \`source ${c}\` or open a new terminal to apply.`,...JL()];if(i.dryRun)return{status:"configured",messages:ne};let Ke=!1;Te?.status==="installable"&&(await sD(Te),Ke=!0);try{I.length>0?await pe($,[nC,...I,""].join(`
115
+ `)):Z&&q&&await Xs($,{force:!0}),await qc(c,Y,kn)}catch(Le){try{W!==void 0&&q?await pe($,W):q&&await Xs($,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw Le}return{status:"configured",messages:ne,changedFiles:[c,...I.length>0||Z&&q?[$]:[],...Ke?[$n()]:[]]}},d=await r(),u=d!==void 0&&!wf(d),f=s.authMode==="placeholder",p=u&&!s.viaLocalProxy,h=u&&(!p||!J(s,"copilot")),m=f?void 0:await t.readDeviceLoginToken().catch(()=>{}),w=f||h&&!m?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),g=w.token,y=w.rejected;if(g){let E=w.capiSegment??"default",x=eD(),C=x!==kf||!!process.env.ANYRAY_COPILOT_MODEL,I=await t.fetchSeatModelCatalog(g.token,{},E,{laneOrigin:eo(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),P=I.find(ne=>ne.id===x);if(!C){let ne=Sf(I);if(P=ne[0],!i.dryRun&&ne.length>0){let Ke=H=>`${eo(s.origin)}/v1${Js(E)}/${Mn(H)==="responses"?"responses":"chat/completions"}`,Le={...vf(),authorization:`Bearer ${g.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},R=new Set,T;for(let H of ne.slice(0,4)){let fe=await t.probeSeatChatModel(Ke(H.id),Le,H.id);if(fe==="ok"){T=H;break}if(fe==="unreachable")break;R.add(H.id)}P=T??ne.find(H=>!R.has(H.id))??ne[0]}x=P?.id??kf}let $=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,Y=$&&s.clientKey?$t($):$,Z=qk(s,x,g.token,$,P,E),W=qk(s,x,$t(g.token),Y,P,E),q=Mn(x),me=I.filter(ne=>rC(ne)&&Mn(ne.id)===q).map(ne=>ne.id).filter(ne=>ne!==x),Te=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${g.source}).`,`Model: ${x}${C?" (pinned via ANYRAY_COPILOT_MODEL)":I.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...I.length===0&&Gk(g.source)?["GitHub served no current models for this sign-in \u2014 the Copilot CLI's own login is","entitled to legacy models only. Fix it with: `anyray-connect copilot-login`","(one browser step), then re-run this command."]:[],...me.length>0?[`Your plan also serves: ${me.slice(0,8).join(", ")}${me.length>8?", \u2026":""} \u2014 switch anytime with \`copilot --model <id>\`.`]:[]];return n()?{status:"manual",messages:["Windows: run these in PowerShell (persists user env), then restart your terminal \u2014",...W.map(ne=>{let Ke=ne.indexOf("="),Le=ne.slice(7,Ke),R=ne.slice(Ke+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${Le}', ${dD(R)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${g.source}, and the gateway key from \`anyray-connect print-key\`.)`,...Te]}:l(Z,W,Te)}if(!tD(s,h)){if(p&&!i.dryRun){let E=At();if(await _s(E,kn))return{status:"reverted",changedFiles:[E],messages:[`removed a stale Anyray ${kn} block from ${E}`,"It routed the CLI on ORG API billing, which predates the Copilot","seat lane and is not a lane you chose. Nothing replaces it yet:",...Qk(t.platform(),y),...zk()]}}return{status:"held",messages:[...p&&i.dryRun?[`would remove a stale Anyray ${kn} block from ${At()} (org lane, not chosen)`]:[],...Qk(t.platform(),y)]}}let b=zL(),A=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,v=A&&s.clientKey?$t(A):A;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...bf(s,b,v).map(E=>{let[x,...C]=E.replace(/^export /,"").split("=");return` setx ${x} "${C.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${vl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(bf(s,b,A),bf(s,b,v),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===Vs?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=At(),c=gf(),l=await O(c),d=l?Zk(await Yk(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${kn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${$n()} if registered`,...await O(na())?[`would remove the Copilot sign-in Connect minted (${na()})`]:[]]};let u=await _s(i,kn);d&&await Xs(c,{force:!0});let f=await iD(),p=na(),h=await O(p);h&&await Xs(p,{force:!0});let m=[...u?[i]:[],...d?[c]:[],...f?[$n()]:[],...h?[p]:[]];return{status:m.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${kn} block from ${i}`:`no Anyray ${kn} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...h?[`removed the Copilot sign-in Connect minted (${p})`]:[],...f?[`removed the Anyray MCP server from ${$n()}`]:[],...zk()],changedFiles:m.length>0?m:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){try{let s=await U($n()),i=kr(s)?s.mcpServers:void 0,c=kr(i)?i[to]:void 0;return!kr(c)||!qt(c,"profile")?{registered:!1,command:null}:{registered:!0,command:typeof c.command=="string"?c.command:null}}catch{return{registered:!1,command:null}}},async inferenceAuthLanes(){try{let s=await r();return s===void 0?["native"]:wf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(no)?!0:!await t.detectCopilotSeat()}}},oC=uD();import{homedir as pC}from"node:os";import{join as Ar}from"node:path";import{constants as hD,chmod as mD,copyFile as yD,readFile as xl}from"node:fs/promises";import{applyEdits as gD,modify as wD}from"jsonc-parser";import{readFile as aC,rm as pD}from"node:fs/promises";var sC="// Managed by anyray-connect: OpenCode trim carrier v1",fD=5e3,Ef=e=>`${sC}
116
116
  import { spawn } from "node:child_process"
117
117
 
118
118
  const hookCommand = ${JSON.stringify([e.command,...e.args])}
119
- const hookTimeoutMs = ${cD}
119
+ const hookTimeoutMs = ${fD}
120
120
 
121
121
  const invokeHook = (payload) =>
122
122
  new Promise((resolve) => {
@@ -183,38 +183,38 @@ export const AnyrayTrimPlugin = async () => ({
183
183
  }
184
184
  },
185
185
  })
186
- `,Js=async e=>await R(e)?(await oC(e,"utf-8")).startsWith(`${aC}
187
- `)?"owned":"foreign":"absent",sC=async(e,t)=>{let n=vf(t),r=await Js(e);return r==="foreign"?"foreign":r==="owned"&&await oC(e,"utf-8")===n?"unchanged":(await pe(e,n),"installed")},Sf=async e=>{let t=await Js(e);return t!=="owned"?t:(await iD(e,{force:!0}),"removed")};var Ef="https://opencode.ai/config.json",Fn="x-anyray-metadata",Ut="x-anyray-api-key",If=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],$n="Authorization",kr=["anthropic","openai"],Un="github-copilot",hD="header",Mn="anyray",mD=()=>process.env.XDG_CONFIG_HOME?.trim()||Cr(uC(),".config"),yD=()=>process.env.XDG_DATA_HOME?.trim()||Cr(uC(),".local","share"),El=()=>Cr(mD(),"opencode"),Al=()=>Cr(El(),"plugins","anyrayTrim.js"),pC=()=>Cr(yD(),"opencode"),fC=async()=>{try{let e=await Sl(Cr(pC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return B(t)?{chatGptOAuth:B(t.openai)&&t.openai.type==="oauth",readable:!0}:{chatGptOAuth:!1,readable:!1}}catch(e){return e.code==="ENOENT"?{chatGptOAuth:!1,readable:!0}:{chatGptOAuth:!1,readable:!1}}},iC=async()=>(await fC()).chatGptOAuth,gD=["opencode.jsonc","opencode.json","config.json"],aa=async()=>{let e=El(),t=[];for(let n of gD){let r=Cr(e,n);await R(r)&&t.push(r)}return t},cC=async()=>(await aa())[0]??Cr(El(),"opencode.json"),oa=async e=>{let t=await R(e),n=t?await Sl(e,"utf8"):`{}
188
- `,r=n.trim()?yr(n):{};if(!B(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},hC=(e,t,n=[])=>{if(B(e)&&B(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...hC(e[o],t[o],[...n,o])):r.push({path:[...n,o],value:t[o]}):r.push({path:[...n,o],value:void 0});return r}return JSON.stringify(e)===JSON.stringify(t)?[]:[{path:n,value:t}]},lC=async(e,t,n,r)=>{let o=hC(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await uD(e,`${e}.anyray-bak`,lD.COPYFILE_EXCL),await dD(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await pe(`${e}.anyray-bak`,`{}
186
+ `,qs=async e=>await O(e)?(await aC(e,"utf-8")).startsWith(`${sC}
187
+ `)?"owned":"foreign":"absent",iC=async(e,t)=>{let n=Ef(t),r=await qs(e);return r==="foreign"?"foreign":r==="owned"&&await aC(e,"utf-8")===n?"unchanged":(await pe(e,n),"installed")},xf=async e=>{let t=await qs(e);return t!=="owned"?t:(await pD(e,{force:!0}),"removed")};var If="https://opencode.ai/config.json",Bn="x-anyray-metadata",Ft="x-anyray-api-key",Of=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Fn="Authorization",Cr=["anthropic","openai"],Wn="github-copilot",bD="header",Un="anyray",kD=()=>process.env.XDG_CONFIG_HOME?.trim()||Ar(pC(),".config"),CD=()=>process.env.XDG_DATA_HOME?.trim()||Ar(pC(),".local","share"),Il=()=>Ar(kD(),"opencode"),Sl=()=>Ar(Il(),"plugins","anyrayTrim.js"),fC=()=>Ar(CD(),"opencode"),hC=async()=>{try{let e=await xl(Ar(fC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return B(t)?{chatGptOAuth:B(t.openai)&&t.openai.type==="oauth",readable:!0}:{chatGptOAuth:!1,readable:!1}}catch(e){return e.code==="ENOENT"?{chatGptOAuth:!1,readable:!0}:{chatGptOAuth:!1,readable:!1}}},cC=async()=>(await hC()).chatGptOAuth,AD=["opencode.jsonc","opencode.json","config.json"],sa=async()=>{let e=Il(),t=[];for(let n of AD){let r=Ar(e,n);await O(r)&&t.push(r)}return t},lC=async()=>(await sa())[0]??Ar(Il(),"opencode.json"),aa=async e=>{let t=await O(e),n=t?await xl(e,"utf8"):`{}
188
+ `,r=n.trim()?yn(n):{};if(!B(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},mC=(e,t,n=[])=>{if(B(e)&&B(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...mC(e[o],t[o],[...n,o])):r.push({path:[...n,o],value:t[o]}):r.push({path:[...n,o],value:void 0});return r}return JSON.stringify(e)===JSON.stringify(t)?[]:[{path:n,value:t}]},dC=async(e,t,n,r)=>{let o=mC(t.data,n);if(o.length===0)return!1;if(r&&!await O(`${e}.anyray-bak`))if(t.existed)try{await yD(e,`${e}.anyray-bak`,hD.COPYFILE_EXCL),await mD(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await pe(`${e}.anyray-bak`,`{}
189
189
  `);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
190
190
  `)?`\r
191
191
  `:`
192
- `},s=t.raw;for(let i of o)s=pD(s,fD(s,i.path,i.value,{formattingOptions:a}));return await pe(e,s.endsWith(`
192
+ `},s=t.raw;for(let i of o)s=gD(s,wD(s,i.path,i.value,{formattingOptions:a}));return await pe(e,s.endsWith(`
193
193
  `)?s:`${s}
194
- `),!0},wD=async e=>{try{let t=yr(await Sl(`${e}.anyray-bak`,"utf8"));return B(t)?t:void 0}catch{return}},xf=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",Rf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${xf()}/${hD}`,B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},bD=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===kr[0]||n===kr[1]||n===Un?[]:B(r)&&B(r.options)&&Lf(r.options.baseURL,t)?[n]:[]),Of=/claude/i,Df=["model","small_model"],mC=(e,t)=>{if(typeof e!="string")return;let n=e.indexOf("/");if(n<=0)return;let r=e.slice(0,n),o=e.slice(n+1);if(!(!t.includes(r)||!Of.test(o)))return`${kr[0]}/${o}`},_f=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)_f(n,t);return t}if(!B(e))return t;for(let[n,r]of Object.entries(e))Df.includes(n)&&typeof r=="string"?t.push(r):_f(r,t);return t},kD=(e,t,n)=>{if(!B(e)||!B(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Of.test(a)))return!1;let o=`${n}/`;return _f(t).filter(a=>a.startsWith(o)).every(a=>Of.test(a.slice(o.length)))},Tf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Tf(o,t,n));if(!B(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Df.includes(o)?mC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Tf(a,t,n)}return r},Pf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Pf(o,t[a],n));if(!B(e)||!B(t))return e;let r={};for(let[o,a]of Object.entries(e))Df.includes(o)&&typeof a=="string"&&mC(t[o],n)===a?r[o]=t[o]:r[o]=Pf(a,t[o],n);return r},CD=e=>{if(B(e))for(let t of kr){let n=e[t];if(B(n)&&B(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Xs=e=>{if(!B(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&zt({command:t,args:n},"profile")},vl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),AD=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return B(t)&&t.tool==="opencode"}catch{return!1}},Nf=e=>X(e,"copilot")&&!!e.clientKey,vD=e=>e.byoUpstream?[]:X(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],SD=(e,t)=>X(e,"openai")?[`OpenAI subscription: OpenCode's built-in ChatGPT Pro/Plus OAuth is ${t?"detected":"not signed in yet (run `opencode auth login`)"}. Its Codex endpoint is hard-coded to chatgpt.com, so provider.baseURL cannot redirect it. Connect leaves machine networking untouched. Use the Codex app/CLI/IDE for ChatGPT subscription pass-through, or sign OpenCode into an API-key/Copilot provider that Connect can route.`]:[],ED=e=>Nf(e)?["Tip: to spend your Copilot subscription (incl. Claude & GPT), pick the github-copilot/* models in OpenCode \u2014 e.g. github-copilot/claude-sonnet-4.5. The anthropic/* and openai/* entries are the direct providers (api-key mode, separate billing) \u2014 not your Copilot plan."]:[],ID=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Ef);let o=!1;if(n)if("mcp"in r&&!B(r.mcp))o=!0;else{let y=B(r.mcp)?{...r.mcp}:{},b=y[Mn];b!==void 0&&!Xs(b)?o=!0:(y[Mn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(B(r.mcp)&&Xs(r.mcp[Mn])){let y={...r.mcp};delete y[Mn],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=B(r.provider)?{...r.provider}:{},s=bD(a,t.origin),i=s.every(y=>kD(a[y],e,y))?s:[],c=s.filter(y=>!i.includes(y)),l=[];if(i.length>0){for(let y of i)delete a[y];r=Tf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,h=de({...t.metadata,tool:"opencode"});for(let y of c){let b={...a[y]},A={...b.options};if("headers"in A&&!B(A.headers)){u.push(y);continue}let v=B(A.headers)?{...A.headers}:{},E=!1;for(let[I,C]of[[Ut,p],...h?[[Fn,h]]:[]])I in v?(typeof v[I]!="string"||v[I].trim()==="")&&u.push(`${y}.${I}`):(v[I]=C,d.push(`${y}.${I}`),E=!0);E&&(A.headers=v,b.options=A,a[y]=b)}let m=c.length>0?[]:kr.filter(y=>y!=="openai"||!X(t,"openai")),w=t.byoUpstream;for(let y of m){let b=B(a[y])?{...a[y]}:{},A=B(b.options)?{...b.options}:{};A.baseURL=f;let v=B(A.headers)?{...A.headers}:{};if(y==="anthropic"&&w)A.apiKey=w.key,v[$n]=`Bearer ${w.key}`,v["x-anyray-provider"]="anthropic",v["x-anyray-auth-mode"]="passthrough",v["x-anyray-custom-host"]=w.url;else{A.apiKey=p,"x-anyray-custom-host"in v&&delete v[$n];for(let E of If)delete v[E]}v[Ut]=p,h&&(v[Fn]=h),A.headers=v,b.options=A,a[y]=b}let g=c.length===0&&Nf(t);if(g){let y=B(a[Un])?{...a[Un]}:{},b=B(y.options)?{...y.options}:{};b.baseURL=Rf(t);let A=B(b.headers)?{...b.headers}:{};A[Ut]=t.clientKey,h&&(A[Fn]=h),b.headers=A,y.options=b,a[Un]=y}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:g,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},xD=["baseURL","apiKey"],dC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!B(s)||!B(s.options))return!1;let i={...s},c={...s.options},l=!1;if(n){let d=typeof c.baseURL=="string"&&c.baseURL.includes("/v1/copilot/"),u=B(c.headers)?{...c.headers}:void 0,f=u?.[Ut],p=vl(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let h=u,m=B(r)?r.options:void 0,w=B(m)&&B(m.headers)?m.headers:void 0;for(let g of[Ut,Fn])w&&g in w?h[g]!==w[g]&&(h[g]=w[g],l=!0):g in h&&(delete h[g],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}else{let d=B(r)?r.options:void 0,u=B(d)?d:{},f=B(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Ut]=="string"||typeof f[Fn]=="string"||If.some(h=>h in f);if(!o&&!p)return!1;for(let h of xD)h in u?c[h]!==u[h]&&(c[h]=u[h],l=!0):h in c&&(delete c[h],l=!0);if(B(c.headers)){let h={...c.headers},m=B(u.headers)?u.headers:{};"x-anyray-custom-host"in h&&$n in h&&($n in m?h[$n]!==m[$n]&&(h[$n]=m[$n],l=!0):(delete h[$n],l=!0));for(let w of[Ut,Fn,...If])w in m?h[w]!==m[w]&&(h[w]=m[w],l=!0):w in h&&(delete h[w],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}return l?(Object.keys(c).length===0?delete i.options:i.options=c,Object.keys(i).length===0?delete e[t]:e[t]=i,!0):!1},RD=(e,t,n)=>{let r=e[t];if(!B(r)||!B(r.options)||!B(n)||!B(n.options))return!1;let o={...r.options};if(!B(o.headers)||"headers"in n.options&&!B(n.options.headers))return!1;let a={...o.headers},s=B(n.options.headers)?n.options.headers:{},i=!1;return!(Ut in s)&&vl(a[Ut])&&(delete a[Ut],i=!0),!(Fn in s)&&AD(a[Fn])&&(delete a[Fn],i=!0),i?(Object.keys(a).length===0?"headers"in n.options?o.headers=s:delete o.headers:o.headers=a,e[t]={...r,options:o},!0):!1},OD=(e,t)=>{let n={...e},r=!1,o=CD(e.provider);if(B(n.mcp)&&Xs(n.mcp[Mn])){let c={...n.mcp};delete c[Mn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!B(n.provider))return{next:n,removed:r};let a={...n.provider},s=B(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Ef&&kr.every(c=>{let l=a[c];return B(l)&&B(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of kr)dC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...kr,Un]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;RD(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&B(u)&&B(u.options)&&Lf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Pf(n,t,l))}return dC(a,Un,!0,s[Un])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Ef&&(delete n.$schema,r=!0),{next:n,removed:r}},yC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=El(),t=pC(),n=await R(e)||await R(t),r=n&&await iC();return{installed:n,detail:n?`${await cC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await cC(),r=e.openaiBaseUrl,o=de({...e.metadata,tool:"opencode"}),a=Nf(e),s=X(e,"openai"),i=await iC(),c;try{c=await oa(n)}catch{return e.clientKey?{status:"manual",messages:[`Couldn't parse ${n} \u2014 set it by hand. Under "provider", add:`,e.byoUpstream?` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your upstream key>", "headers": { "Authorization": "Bearer <your upstream key>", "x-anyray-auth-mode": "passthrough", "x-anyray-provider": "anthropic", "x-anyray-custom-host": ${JSON.stringify(e.byoUpstream.url)}, "x-anyray-api-key": "<your personal ark_ key>" } } }`:` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`,...s?[]:[` "openai": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`],...a?[` "github-copilot": { "options": { "baseURL": ${JSON.stringify(Rf(e))}, "headers": { "${Ut}": "<your personal ark_ key>" } } }`]:[]]}:{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Enroll with --enroll or --sso before configuring OpenCode.`]}}let l=await Wr()?Ve("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=ID(c.data,e,l),g=u.length>0,y=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(C=>`provider.${C}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...p.length>0?[`Updated model references: ${p.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=g?[`${n} already routes through ${e.origin} via ${u.map(C=>`provider.${C}`).join(", ")}; existing provider values were preserved.`,h.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${h.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...m.length>0?[`Could not safely add required headers at ${m.join(", ")} because the existing values have incompatible shapes. Fix those values manually; no existing value was replaced.`]:[],"Canonical anthropic, openai, and github-copilot provider blocks were left untouched.","Restart OpenCode (or start a new session) to pick up the change."]:[...y,s?`${n} \u2192 provider.anthropic options.baseURL = ${r}; provider.openai left untouched because OpenCode's ChatGPT OAuth loader has no configurable endpoint.`:`${n} \u2192 provider.anthropic + provider.openai options.baseURL = ${r}`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${o??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...vD(e),...SD(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Rf(e)} with the personal gateway key in options.headers (never the URL). OpenCode keeps its Copilot sign-in, GitHub bills your plan, and the gateway meters it. ${xf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${xf()} plan-specific host selected by ANYRAY_COPILOT_PLAN.`}`:"GitHub Copilot: not routed \u2014 needs a Copilot seat plus enrollment (a detected Copilot plan or --subscription, and --enroll for the seat key).",...ED(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Mn} is not owned by Anyray Connect, so it was left untouched.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let A=m.length>0?"manual":"configured";if(t.dryRun)return{status:A,messages:b};let E=await lC(n,c,d,!0)?[n]:[],I=Al();if(le())try{let C=await sC(I,cs(Je,["opencode"]));C==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${I} already exists and is not owned by Anyray.`):(C==="installed"&&E.push(I),b.push(`The OpenCode tool.execute.after carrier is active in ${I}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${I}. Gateway-side optimization remains active.`)}else{try{await Sf(I)==="removed"&&E.push(I)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:A,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await aa())try{let{data:n}=await oa(t);if(!B(n.provider))continue;for(let r of Object.values(n.provider))if(!(!B(r)||!B(r.options))&&Lf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await aa())try{let{data:t}=await oa(e);if(!B(t.mcp))continue;let n=t.mcp[Mn];if(!Xs(n)||!B(n))continue;return{registered:!0,command:Array.isArray(n.command)&&typeof n.command[0]=="string"?n.command[0]:null}}catch{}return{registered:!1,command:null}},async integrationStatus(){let e,t=!0;try{let i=await Js(Al());e=i==="absent"?"missing":i,e==="owned"&&(t=await Sl(Al(),"utf-8")===vf(cs(Je,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await aa()){let c;try{c=await oa(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!B(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Mn];if(l!==void 0)if(Xs(l))if(n=!0,!B(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;bc({command:d,args:u},"profile")||(a=!1)}else r=!0}return{hook_registration:e,mcp_registration:o?"unreadable":r?"foreign":n?"owned":"missing",hook_binary:t&&a&&await Wr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await fC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await aa()){let{data:o}=await oa(r);if(B(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!B(s)||!B(s.options)){e.add("unknown");continue}let i=s.options,c=B(i.headers)?i.headers:{};if(a===Un&&typeof i.baseURL=="string"&&i.baseURL.includes("/v1/copilot/")){e.add("subscription");continue}if(a==="openai"&&n&&i.baseURL===void 0&&i.apiKey===void 0){e.add("native");continue}if(a===Un&&i.baseURL===void 0&&i.apiKey===void 0){e.add("native");continue}if(typeof c["x-anyray-custom-host"]=="string"){e.add("byo");continue}if(c["x-anyray-auth-mode"]==="passthrough"){e.add("subscription");continue}if(vl(c[Ut])||vl(i.apiKey)||typeof i.apiKey=="string"&&i.apiKey.length>0||typeof c.Authorization=="string"&&c.Authorization.length>0){e.add("api_key");continue}e.add("unknown")}}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=await aa(),n=Al(),r="absent";try{r=await Js(n)}catch{}if(t.length===0&&r!=="owned")return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[...t.map(i=>`would remove Anyray provider settings from ${i}`),...r==="owned"?[`would remove the Anyray OpenCode trim carrier from ${n}`]:[]]};let o=[],a=[],s=[];for(let i of t){let c;try{c=await oa(i)}catch{s.push(i);continue}let{next:l,removed:d}=OD(c.data,await wD(i));d&&(await lC(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await ae(i)}for(let i of s)o.push(`Couldn't parse ${i} \u2014 if you added Anyray settings there by hand, remove the baseURL/apiKey from provider.anthropic, provider.openai, and provider.github-copilot yourself.`);if(r==="owned")try{await Sf(n)==="removed"&&(a.push(n),o.push(`removed the Anyray OpenCode trim carrier from ${n}`))}catch{o.push(`Could not remove the Anyray OpenCode trim carrier from ${n}. Remove that file manually.`)}return a.length===0&&s.length===0&&o.push("no Anyray provider settings found"),{status:a.length===0&&s.length>0?"manual":"reverted",messages:o,changedFiles:a.length?a:void 0}}};import{homedir as CC}from"node:os";import{join as xl}from"node:path";import{constants as DD,chmod as ND,copyFile as $D,readFile as AC}from"node:fs/promises";import{applyEdits as MD,modify as FD}from"jsonc-parser";import{homedir as _D}from"node:os";import{dirname as TD,join as zs}from"node:path";import{mkdir as PD,readFile as wC,rm as LD}from"node:fs/promises";var $f="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",gC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfQogICAgfQogIH0sCiAgImNvbmZpZ1NjaGVtYSI6IHsKICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAiYWRkaXRpb25hbFByb3BlcnRpZXMiOiBmYWxzZSwKICAgICJyZXF1aXJlZCI6IFsiZ2F0ZXdheVVybCJdLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkFueXJheSBnYXRld2F5IG9yaWdpbiwgZS5nLiBodHRwczovL2dhdGV3YXkuZXhhbXBsZS5hbnlyYXkuYWkgKG5vIC92MSBzdWZmaXgpLiIKICAgICAgfSwKICAgICAgImFwaUtleSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJQZXJzb25hbCBBbnlyYXkgY2xpZW50IGtleSAoYXJrX+KApikuIFN1cHBvcnRzICR7RU5WX1ZBUn0gc3Vic3RpdHV0aW9uOyBkZWZhdWx0cyB0byAke0FOWVJBWV9DTElFTlRfS0VZfS4iCiAgICAgIH0sCiAgICAgICJ1c2VyIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkF0dHJpYnV0aW9uIHVzZXIgKGNvbnRlbnQtZnJlZTsgdXN1YWxseSBhbiBlbWFpbCkuIE9wdGlvbmFsIOKAlCB0aGUgY2xpZW50IGtleSBhbHJlYWR5IGF0dHJpYnV0ZXMgdGhlIGVucm9sbGVkIHVzZXIuIgogICAgICB9LAogICAgICAidGVhbSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB0ZWFtIChjb250ZW50LWZyZWUpLiBPcHRpb25hbC4iCiAgICAgIH0KICAgIH0sCiAgICAidWlIaW50cyI6IHsKICAgICAgImdhdGV3YXlVcmwiOiB7CiAgICAgICAgImxhYmVsIjogIkdhdGV3YXkgVVJMIiwKICAgICAgICAiaGVscCI6ICJZb3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IG9yaWdpbi4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgImxhYmVsIjogIkNsaWVudCBrZXkiLAogICAgICAgICJoZWxwIjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudC4gTGVhdmUgdW5zZXQgdG8gcmVhZCAkQU5ZUkFZX0NMSUVOVF9LRVkuIgogICAgICB9CiAgICB9CiAgfQp9Cg=="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjEuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJEZXBlbmRlbmNpZXMiOiB7CiAgICAib3BlbmNsYXciOiAiPj0yMDI2LjcuMSIKICB9LAogICJkZXZEZXBlbmRlbmNpZXMiOiB7CiAgICAidHN4IjogIl40LjIzLjUiLAogICAgInR5cGVzY3JpcHQiOiAiXjUuNi4zIgogIH0KfQo="},{path:"src/index.ts",contentBase64:"LyoqCiAqIEFueXJheSBPcGVuQ2xhdyBwbHVnaW4g4oCUIHJvdXRlcyBPcGVuQ2xhdydzIG1vZGVsIGNhbGxzIHRocm91Z2ggYW4gb3JnJ3MKICogQW55cmF5IGdhdGV3YXkgYXMgdGhlIGBhbnlyYXlgIHByb3ZpZGVyLgogKgogKiBXaGF0IGl0IGFkZHMgb3ZlciB0aGUgcGxhaW4gYG1vZGVscy5wcm92aWRlcnNgIGNvbmZpZyB0aGUgY29ubmVjdCBhZGFwdGVyCiAqIHdyaXRlczoKICogIC0gcGVyLWNhbGwgc2Vzc2lvbiBpZGVudGl0eSAoYG1ldGFkYXRhLnVzZXJfaWRgKSB2aWEgdGhlIHN0cmVhbSB3cmFwcGVyLCBzbwogKiAgICB0aGUgZ2F0ZXdheSBnZXRzIENsYXVkZSBDb2RlLWdyYWRlIHBlci1jb252ZXJzYXRpb24gb3B0aW1pemVyIHNlc3Npb25zCiAqICAgIGluc3RlYWQgb2YgYW5jaG9yIGZpbmdlcnByaW50czsKICogIC0gYSBjYWNoZS1yZXRlbnRpb24gZGVmYXVsdCBvbiBldmVyeSBjYWxsIChPcGVuQ2xhdyBoYXMgbm8gYXV0by1zZWVkIG9uCiAqICAgIGN1c3RvbSBob3N0cyk7CiAqICAtIHRoZSB3aG9sZSBwcm92aWRlciBlbnRyeSAoYmFzZSBVUkwsIGFwaSBraW5kLCBwZXItbW9kZWwgbWF4VG9rZW5zLCBiZXRhCiAqICAgIHJlc3RvcmUsIGF0dHJpYnV0aW9uIGhlYWRlcnMpIGNvbnRyaWJ1dGVkIGZyb20gb25lIHBsdWdpbiBjb25maWcgYmxvY2suCiAqCiAqIFRoZSBtYW5pZmVzdCdzIHN0YXRpYyBgbW9kZWxDYXRhbG9nYCBibG9jayBpcyB3aGF0IE9wZW5DbGF3IG1hdGVyaWFsaXplcyBmb3IKICogbW9kZWwgZGlzY292ZXJ5IGJlZm9yZSB0aGlzIHJ1bnRpbWUgY2F0YWxvZyByZXNvbHZlcyAobGl2ZS1jb250YWluZXIgZmFjdDoKICogd2l0aG91dCBpdCwgYGFueXJheS8qYCByZWZzIGFyZSB1bmtub3duIHRvIHRoZSBhZ2VudCBydW50aW1lKTsgdGhlIHJ1bnRpbWUKICogYGNhdGFsb2cucnVuYCB0aGVuIHN1cHBsaWVzIHRoZSByZWFsIGdhdGV3YXkgY29vcmRpbmF0ZXMgZnJvbSBwbHVnaW4gY29uZmlnLgogKgogKiBQUklWQUNZOiBldmVyeXRoaW5nIGluamVjdGVkIGlzIGNvbnRlbnQtZnJlZSDigJQgYW4gb3BhcXVlIHNlc3Npb24gaWQgaGFzaCwKICogdGhlIGVucm9sbG1lbnQga2V5LCBhbmQgdXNlci90ZWFtIGF0dHJpYnV0aW9uIHRoZSBvcGVyYXRvciBjb25maWd1cmVkLgogKi8KCmltcG9ydCB7IGRlZmluZVNpbmdsZVByb3ZpZGVyUGx1Z2luRW50cnkgfSBmcm9tICdvcGVuY2xhdy9wbHVnaW4tc2RrL3Byb3ZpZGVyLWVudHJ5JzsKaW1wb3J0IHR5cGUgeyBQcm92aWRlckNhdGFsb2dDb250ZXh0IH0gZnJvbSAnb3BlbmNsYXcvcGx1Z2luLXNkay9wcm92aWRlci10eXBlcyc7CmltcG9ydCBtYW5pZmVzdCBmcm9tICcuLi9vcGVuY2xhdy5wbHVnaW4uanNvbicgd2l0aCB7IHR5cGU6ICdqc29uJyB9OwppbXBvcnQgeyBidWlsZEFueXJheVByb3ZpZGVyLCB0eXBlIEFueXJheVBsdWdpbkNvbmZpZyB9IGZyb20gJy4vY2F0YWxvZy5qcyc7CmltcG9ydCB7IGNyZWF0ZUFueXJheVN0cmVhbVdyYXBwZXIgfSBmcm9tICcuL3N0cmVhbVdyYXBwZXIuanMnOwoKLyoqIFRoZSBwbHVnaW4ncyBvd24gYHBsdWdpbnMuZW50cmllcy5hbnlyYXkuY29uZmlnYCBibG9jayBmcm9tIHRoZSByZXNvbHZlZAogKiAgZ2F0ZXdheSBjb25maWcuIFRoZSBwbGFpbi1vYmplY3QgYHByb3ZpZGVyYCBmb3JtICh0aGUgc2hhcGUgdGhlIHNoaXBwZWQKICogIDIwMjYuNy54IFNESyBub3JtYWxpemVzOyB0aGUgYChhcGkpID0+IOKApmAgZnVuY3Rpb24gZm9ybSBpcyBuZXdlcikgaGFzIG5vCiAqICBgYXBpLnBsdWdpbkNvbmZpZ2AgY2xvc3VyZSwgc28gdGhlIGNhdGFsb2cgcmVhZHMgaXQgZnJvbSBgY3R4LmNvbmZpZ2AuICovCmNvbnN0IHBsdWdpbkNvbmZpZ09mID0gKGN0eDogUHJvdmlkZXJDYXRhbG9nQ29udGV4dCk6IEFueXJheVBsdWdpbkNvbmZpZyA9PiB7CiAgY29uc3QgcGx1Z2lucyA9IGN0eC5jb25maWcucGx1Z2luczsKICBpZiAodHlwZW9mIHBsdWdpbnMgIT09ICdvYmplY3QnIHx8IHBsdWdpbnMgPT09IG51bGwpIHJldHVybiB7fTsKICBjb25zdCBlbnRyaWVzID0gKHBsdWdpbnMgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4pLmVudHJpZXM7CiAgaWYgKHR5cGVvZiBlbnRyaWVzICE9PSAnb2JqZWN0JyB8fCBlbnRyaWVzID09PSBudWxsKSByZXR1cm4ge307CiAgY29uc3QgZW50cnkgPSAoZW50cmllcyBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPikuYW55cmF5OwogIGlmICh0eXBlb2YgZW50cnkgIT09ICdvYmplY3QnIHx8IGVudHJ5ID09PSBudWxsKSByZXR1cm4ge307CiAgY29uc3QgY29uZmlnID0gKGVudHJ5IGFzIFJlY29yZDxzdHJpbmcsIHVua25vd24+KS5jb25maWc7CiAgaWYgKHR5cGVvZiBjb25maWcgIT09ICdvYmplY3QnIHx8IGNvbmZpZyA9PT0gbnVsbCkgcmV0dXJuIHt9OwogIHJldHVybiBjb25maWcgYXMgQW55cmF5UGx1Z2luQ29uZmlnOwp9OwoKZXhwb3J0IGRlZmF1bHQgZGVmaW5lU2luZ2xlUHJvdmlkZXJQbHVnaW5FbnRyeSh7CiAgaWQ6ICdhbnlyYXknLAogIG5hbWU6ICdBbnlyYXknLAogIGRlc2NyaXB0aW9uOgogICAgIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogIG1hbmlmZXN0LAogIHByb3ZpZGVyOiB7CiAgICBsYWJlbDogJ0FueXJheScsCiAgICBkb2NzUGF0aDogJ2h0dHBzOi8vZG9jcy5hbnlyYXkuYWkvaW50ZWdyYXRpb25zL29wZW5jbGF3JywKICAgIGNhdGFsb2c6IHsKICAgICAgcnVuOiBhc3luYyAoY3R4OiBQcm92aWRlckNhdGFsb2dDb250ZXh0KSA9PiAoewogICAgICAgIHByb3ZpZGVyOiBidWlsZEFueXJheVByb3ZpZGVyKHBsdWdpbkNvbmZpZ09mKGN0eCksIGN0eC5lbnYpLAogICAgICB9KSwKICAgIH0sCiAgICB3cmFwU3RyZWFtRm46IGNyZWF0ZUFueXJheVN0cmVhbVdyYXBwZXIsCiAgfSwKfSk7Cg=="},{path:"src/catalog.ts",contentBase64:"LyoqCiAqIEFueXJheSBwcm92aWRlciBjYXRhbG9nIOKAlCB0aGUgYG1vZGVscy5wcm92aWRlcnMuYW55cmF5YCBlbnRyeSB0aGlzIHBsdWdpbgogKiBjb250cmlidXRlcyBmcm9tIGl0cyBvd24gY29uZmlnLCByZXBsYWNpbmcgdGhlIGhhbmQtd3JpdHRlbiBKU09OIHRoZSBjb25uZWN0CiAqIGFkYXB0ZXIgb3RoZXJ3aXNlIG1haW50YWlucyAoYmFzZSBVUkwsIGFwaSBraW5kLCBwZXItbW9kZWwgbWF4VG9rZW5zLCB0aGUKICogb2ZmLWhvc3QgYmV0YS1oZWFkZXIgcmVzdG9yZSkuCiAqCiAqIFB1cmU6IGNvbmZpZyBpbiwgTW9kZWxQcm92aWRlckNvbmZpZyBvdXQuIFRoZSBFMkUtcHJvdmVuIGxhbmRtaW5lcyBmcm9tIHRoZQogKiBjb25maWctZmlsZSBpbnRlZ3JhdGlvbiBhcmUgZW5jb2RlZCBoZXJlIG9uY2U6IGV4cGxpY2l0IGBhcGlgIChhIGN1c3RvbWl6ZWQKICogZW50cnkgb3RoZXJ3aXNlIHNpbGVudGx5IGZhbGxzIHRvIHRoZSBPcGVuQUktY29tcGF0aWJsZSBkaWFsZWN0KSBhbmQKICogcGVyLW1vZGVsIGBtYXhUb2tlbnNgIChhIGN1c3RvbWl6ZWQgZW50cnkgc3RvcHMgaW5oZXJpdGluZyB0aGUgY2F0YWxvZydzKS4KICovCgppbXBvcnQgdHlwZSB7IE1vZGVsUHJvdmlkZXJDb25maWcgfSBmcm9tICdvcGVuY2xhdy9wbHVnaW4tc2RrL3Byb3ZpZGVyLXR5cGVzJzsKCmV4cG9ydCBpbnRlcmZhY2UgQW55cmF5UGx1Z2luQ29uZmlnIHsKICBnYXRld2F5VXJsPzogdW5rbm93bjsKICBhcGlLZXk/OiB1bmtub3duOwogIHVzZXI/OiB1bmtub3duOwogIHRlYW0/OiB1bmtub3duOwp9CgovKiogT3BlbkNsYXcgc3VwcHJlc3NlcyBpbXBsaWNpdCBiZXRhIGhlYWRlcnMgb2ZmLWhvc3Q7IHJlc3RvcmUgdGhlIEFQSS1rZXkgc2V0LiAqLwpjb25zdCBBTlRIUk9QSUNfQkVUQSA9ICdpbnRlcmxlYXZlZC10aGlua2luZy0yMDI1LTA1LTE0JzsKCi8qKiBEZWZhdWx0IGtleSByZWZlcmVuY2Ug4oCUIE9wZW5DbGF3IHN1YnN0aXR1dGVzICR7RU5WfSBpbiBjb25maWcgc3RyaW5ncywgYnV0CiAqICBwbHVnaW4gY29uZmlnIGFycml2ZXMgcmVzb2x2ZWQsIHNvIGFuIHVuc2V0IGtleSBmYWxscyBiYWNrIHRvIHRoZSBlbnYgdmFyCiAqICB0aGUgY29ubmVjdCBlbnJvbGxtZW50IHdyaXRlcy4gKi8KY29uc3QgS0VZX0VOViA9ICdBTllSQVlfQ0xJRU5UX0tFWSc7Cgpjb25zdCBNT0RFTFM6IFJlYWRvbmx5QXJyYXk8UmVjb3JkPHN0cmluZywgdW5rbm93bj4+ID0gWwogIHsKICAgIGlkOiAnY2xhdWRlLXNvbm5ldC00LTUnLAogICAgbmFtZTogJ0NsYXVkZSBTb25uZXQgNC41IChBbnlyYXkpJywKICAgIHJlYXNvbmluZzogdHJ1ZSwKICAgIGlucHV0OiBbJ3RleHQnLCAnaW1hZ2UnXSwKICAgIGNvbnRleHRXaW5kb3c6IDIwMDAwMCwKICAgIG1heFRva2VuczogNjQwMDAsCiAgfSwKICB7CiAgICBpZDogJ2NsYXVkZS1oYWlrdS00LTUnLAogICAgbmFtZTogJ0NsYXVkZSBIYWlrdSA0LjUgKEFueXJheSknLAogICAgcmVhc29uaW5nOiB0cnVlLAogICAgaW5wdXQ6IFsndGV4dCcsICdpbWFnZSddLAogICAgY29udGV4dFdpbmRvdzogMjAwMDAwLAogICAgbWF4VG9rZW5zOiA2NDAwMCwKICB9LAogIHsKICAgIGlkOiAnY2xhdWRlLW9wdXMtNC04JywKICAgIG5hbWU6ICdDbGF1ZGUgT3B1cyA0LjggKEFueXJheSknLAogICAgcmVhc29uaW5nOiB0cnVlLAogICAgaW5wdXQ6IFsndGV4dCcsICdpbWFnZSddLAogICAgY29udGV4dFdpbmRvdzogMjAwMDAwLAogICAgbWF4VG9rZW5zOiAzMjAwMCwKICB9LApdOwoKY29uc3QgdHJpbW1lZFN0cmluZyA9ICh2OiB1bmtub3duKTogc3RyaW5nIHwgdW5kZWZpbmVkID0+CiAgdHlwZW9mIHYgPT09ICdzdHJpbmcnICYmIHYudHJpbSgpICE9PSAnJyA/IHYudHJpbSgpIDogdW5kZWZpbmVkOwoKLyoqIENvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbiBoZWFkZXIgdmFsdWU7IHVuZGVmaW5lZCB3aGVuIG5vdGhpbmcgdG8gYXR0cmlidXRlLiAqLwpleHBvcnQgY29uc3QgYXR0cmlidXRpb25IZWFkZXJWYWx1ZSA9ICgKICBjb25maWc6IEFueXJheVBsdWdpbkNvbmZpZwopOiBzdHJpbmcgfCB1bmRlZmluZWQgPT4gewogIGNvbnN0IHVzZXIgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy51c2VyKTsKICBjb25zdCB0ZWFtID0gdHJpbW1lZFN0cmluZyhjb25maWcudGVhbSk7CiAgaWYgKCF1c2VyICYmICF0ZWFtKSByZXR1cm4gdW5kZWZpbmVkOwogIHJldHVybiBKU09OLnN0cmluZ2lmeSh7CiAgICAuLi4odXNlciA/IHsgdXNlciB9IDoge30pLAogICAgLi4uKHRlYW0gPyB7IHRlYW0gfSA6IHt9KSwKICAgIHRvb2w6ICdvcGVuY2xhdycsCiAgfSk7Cn07CgovKiogQnVpbGQgdGhlIHByb3ZpZGVyIGVudHJ5LiBUaHJvd3Mgb24gYSBtaXNzaW5nIGdhdGV3YXlVcmwg4oCUIHRoZSBwbHVnaW4gaXMKICogIG1pc2NvbmZpZ3VyZWQgYW5kIGEgaGFsZi1jb25maWd1cmVkIHByb3ZpZGVyIHdvdWxkIHJvdXRlIG5vd2hlcmUuICovCmV4cG9ydCBjb25zdCBidWlsZEFueXJheVByb3ZpZGVyID0gKAogIGNvbmZpZzogQW55cmF5UGx1Z2luQ29uZmlnLAogIGVudjogUmVjb3JkPHN0cmluZywgc3RyaW5nIHwgdW5kZWZpbmVkPiA9IHByb2Nlc3MuZW52Cik6IE1vZGVsUHJvdmlkZXJDb25maWcgPT4gewogIGNvbnN0IGdhdGV3YXlVcmwgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy5nYXRld2F5VXJsKTsKICBpZiAoIWdhdGV3YXlVcmwpIHsKICAgIHRocm93IG5ldyBFcnJvcigKICAgICAgJ2FueXJheSBwbHVnaW46IHBsdWdpbnMuZW50cmllcy5hbnlyYXkuY29uZmlnLmdhdGV3YXlVcmwgaXMgcmVxdWlyZWQnCiAgICApOwogIH0KICBjb25zdCBhcGlLZXkgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy5hcGlLZXkpID8/IGVudltLRVlfRU5WXTsKICBjb25zdCBhdHRyaWJ1dGlvbiA9IGF0dHJpYnV0aW9uSGVhZGVyVmFsdWUoY29uZmlnKTsKICByZXR1cm4gewogICAgLy8gQmFyZSBvcmlnaW46IHRoZSBhbnRocm9waWMtbWVzc2FnZXMgdHJhbnNwb3J0IGFwcGVuZHMgL3YxL21lc3NhZ2VzLgogICAgYmFzZVVybDogZ2F0ZXdheVVybC5yZXBsYWNlKC9cLyskLywgJycpLAogICAgYXBpOiAnYW50aHJvcGljLW1lc3NhZ2VzJywKICAgIC4uLihhcGlLZXkgPyB7IGFwaUtleSB9IDoge30pLAogICAgaGVhZGVyczogewogICAgICAnYW50aHJvcGljLWJldGEnOiBBTlRIUk9QSUNfQkVUQSwKICAgICAgLi4uKGFwaUtleSA/IHsgJ3gtYW55cmF5LWFwaS1rZXknOiBhcGlLZXkgfSA6IHt9KSwKICAgICAgLi4uKGF0dHJpYnV0aW9uID8geyAneC1hbnlyYXktbWV0YWRhdGEnOiBhdHRyaWJ1dGlvbiB9IDoge30pLAogICAgfSwKICAgIG1vZGVsczogTU9ERUxTLAogIH07Cn07Cg=="},{path:"src/sessionIdentity.ts",contentBase64:"LyoqCiAqIFBlci1zZXNzaW9uIGlkZW50aXR5IGZvciB0aGUgQW55cmF5IGdhdGV3YXksIGluamVjdGVkIGludG8gdGhlIEFudGhyb3BpYwogKiBNZXNzYWdlcyBib2R5IGFzIGBtZXRhZGF0YS51c2VyX2lkYC4KICoKICogVGhlIGdhdGV3YXkgZGVyaXZlcyBpdHMgb3B0aW1pemVyIHNlc3Npb24gZnJvbSBhIGBfc2Vzc2lvbl88dXVpZD5gIHN1ZmZpeCBvbgogKiBgbWV0YWRhdGEudXNlcl9pZGAgKHRoZSBDbGF1ZGUgQ29kZSBjb252ZW50aW9uOyBnYXRld2F5CiAqIGBjbGllbnRTZXNzaW9uLnRzI21ldGFkYXRhU2Vzc2lvblV1aWRgKS4gV2l0aG91dCBpdCwgT3BlbkNsYXcgdHJhZmZpYyBmYWxscwogKiB0byBhIGNvbnZlcnNhdGlvbi1hbmNob3IgZmluZ2VycHJpbnQsIGFuZCBjb25jdXJyZW50IGNvbnZlcnNhdGlvbnMgdGhhdCBvcGVuCiAqIGlkZW50aWNhbGx5IHNoYXJlIG9uZSBzZXNzaW9uIOKAlCBvbmUgb3B0aW1pemVyIGZhaWwtb3BlbiB0aGVuIHBhdXNlcwogKiBvcHRpbWl6YXRpb24gZm9yIGFsbCBvZiB0aGVtICh0aGUgY29vbG9mZi1hbXBsaWZpY2F0aW9uIGZhaWx1cmUgbW9kZSkuCiAqCiAqIE9wZW5DbGF3J3Mgc3RyZWFtIGxheWVyIGhhbmRzIHVzIGFuIG9wYXF1ZSBgc2Vzc2lvbklkYCBwZXIgY2FsbC4gV2hlbiBpdCBpcwogKiBhbHJlYWR5IGEgVVVJRCBpdCBpcyB1c2VkIGFzLWlzOyBhbnl0aGluZyBlbHNlIGlzIGZvbGRlZCBpbnRvIGEgc3RhYmxlCiAqIFVVSUQtc2hhcGVkIHZhbHVlIHZpYSBTSEEtMjU2IHNvIHRoZSBzYW1lIHNlc3Npb24gYWx3YXlzIG1hcHMgdG8gdGhlIHNhbWUKICogaWQuIFRoZSB2YWx1ZSBpcyBhbiBvcGFxdWUgaWRlbnRpZmllciBlaXRoZXIgd2F5IOKAlCBubyBjb250ZW50LCBubyB1c2VyIGRhdGEuCiAqLwoKaW1wb3J0IHsgY3JlYXRlSGFzaCB9IGZyb20gJ25vZGU6Y3J5cHRvJzsKCmNvbnN0IFVVSURfUkUgPQogIC9eWzAtOWEtZl17OH0tWzAtOWEtZl17NH0tWzAtOWEtZl17NH0tWzAtOWEtZl17NH0tWzAtOWEtZl17MTJ9JC9pOwoKLyoqIFByZWZpeCBtYXJraW5nIGdhdGV3YXktdmlzaWJsZSB1c2VyX2lkcyBhcyBvdXJzIChjb250ZW50LWZyZWUpLiAqLwpjb25zdCBVU0VSX0lEX1BSRUZJWCA9ICdvcGVuY2xhdyc7CgovKiogQSBzdGFibGUgVVVJRC1zaGFwZWQgdmFsdWUgZm9yIGFueSBvcGFxdWUgc2Vzc2lvbiBrZXkuICovCmV4cG9ydCBjb25zdCBzZXNzaW9uVXVpZEZvciA9IChzZXNzaW9uSWQ6IHN0cmluZyk6IHN0cmluZyA9PiB7CiAgaWYgKFVVSURfUkUudGVzdChzZXNzaW9uSWQpKSByZXR1cm4gc2Vzc2lvbklkLnRvTG93ZXJDYXNlKCk7CiAgY29uc3QgaGV4ID0gY3JlYXRlSGFzaCgnc2hhMjU2JykudXBkYXRlKHNlc3Npb25JZCwgJ3V0ZjgnKS5kaWdlc3QoJ2hleCcpOwogIHJldHVybiBbCiAgICBoZXguc2xpY2UoMCwgOCksCiAgICBoZXguc2xpY2UoOCwgMTIpLAogICAgaGV4LnNsaWNlKDEyLCAxNiksCiAgICBoZXguc2xpY2UoMTYsIDIwKSwKICAgIGhleC5zbGljZSgyMCwgMzIpLAogIF0uam9pbignLScpOwp9OwoKLyoqIFRoZSBgbWV0YWRhdGEudXNlcl9pZGAgdmFsdWUgdGhlIGdhdGV3YXkncyBzZXNzaW9uIGV4dHJhY3RvciByZWNvZ25pemVzLiAqLwpleHBvcnQgY29uc3QgYW55cmF5VXNlcklkRm9yID0gKHNlc3Npb25JZDogc3RyaW5nKTogc3RyaW5nID0+CiAgYCR7VVNFUl9JRF9QUkVGSVh9X3Nlc3Npb25fJHtzZXNzaW9uVXVpZEZvcihzZXNzaW9uSWQpfWA7CgovKioKICogUGF0Y2ggYW4gb3V0Ym91bmQgQW50aHJvcGljIE1lc3NhZ2VzIHBheWxvYWQgaW4gcGxhY2Ugd2l0aCB0aGUgc2Vzc2lvbgogKiBpZGVudGl0eS4gRXhpc3RpbmcgYG1ldGFkYXRhLnVzZXJfaWRgIHZhbHVlcyBhcmUgbmV2ZXIgb3ZlcndyaXR0ZW4gKGEgdmFsdWUKICogcHJlc2VudCBtZWFucyBzb21lb25lIHVwc3RyZWFtIOKAlCBjb25maWcsIGFub3RoZXIgcGx1Z2luIOKAlCBtYWRlIGEgY2hvaWNlKSwKICogYW5kIGEgbWFsZm9ybWVkIGBtZXRhZGF0YWAgc2hhcGUgaXMgbGVmdCB1bnRvdWNoZWQgcmF0aGVyIHRoYW4gcmVwYWlyZWQuCiAqLwpleHBvcnQgY29uc3QgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5ID0gKAogIHBheWxvYWQ6IFJlY29yZDxzdHJpbmcsIHVua25vd24+LAogIHNlc3Npb25JZDogc3RyaW5nIHwgdW5kZWZpbmVkCik6IHZvaWQgPT4gewogIGlmICghc2Vzc2lvbklkKSByZXR1cm47CiAgY29uc3QgbWV0YWRhdGEgPSBwYXlsb2FkLm1ldGFkYXRhOwogIGlmIChtZXRhZGF0YSA9PT0gdW5kZWZpbmVkKSB7CiAgICBwYXlsb2FkLm1ldGFkYXRhID0geyB1c2VyX2lkOiBhbnlyYXlVc2VySWRGb3Ioc2Vzc2lvbklkKSB9OwogICAgcmV0dXJuOwogIH0KICBpZiAodHlwZW9mIG1ldGFkYXRhICE9PSAnb2JqZWN0JyB8fCBtZXRhZGF0YSA9PT0gbnVsbCB8fCBBcnJheS5pc0FycmF5KG1ldGFkYXRhKSkKICAgIHJldHVybjsKICBjb25zdCByZWNvcmQgPSBtZXRhZGF0YSBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPjsKICBpZiAocmVjb3JkLnVzZXJfaWQgPT09IHVuZGVmaW5lZCkgewogICAgcmVjb3JkLnVzZXJfaWQgPSBhbnlyYXlVc2VySWRGb3Ioc2Vzc2lvbklkKTsKICB9Cn07Cg=="},{path:"src/streamWrapper.ts",contentBase64:"LyoqCiAqIFRoZSBwZXItY2FsbCBzZWFtOiB3cmFwcyB0aGUgYnVpbHQtaW4gYW50aHJvcGljLW1lc3NhZ2VzIHRyYW5zcG9ydCBzbyBldmVyeQogKiBvdXRib3VuZCBjYWxsIHRvIHRoZSBBbnlyYXkgZ2F0ZXdheSBjYXJyaWVzIHBlci1zZXNzaW9uIGlkZW50aXR5LCBhbmQgcHJvbXB0CiAqIGNhY2hpbmcgaXMgbmV2ZXIgc2lsZW50bHkgb2ZmLgogKgogKiBEZWxlZ2F0aW9uIGNvbnRyYWN0IChtaXJyb3JzIE9wZW5DbGF3J3Mgb3duIGJ1bmRsZWQgd3JhcHBlcnMpOiByZXR1cm4gYQogKiBTdHJlYW1GbiB0aGF0IGNoYWlucyBhbnkgY2FsbGVyLXN1cHBsaWVkIGBvblBheWxvYWRgIGFmdGVyIG91cnMsIGFuZCBhbHdheXMKICogaGFuZCBvZmYgdG8gYGN0eC5zdHJlYW1GbmAg4oCUIHRoaXMgd3JhcHBlciBvbmx5IGRlY29yYXRlcywgaXQgbmV2ZXIKICogdHJhbnNwb3J0cy4gR3VhcmRlZCB0byBvdXIgcHJvdmlkZXIgKyBhcGkgc28gYSBtaXMtcmVnaXN0cmF0aW9uIGNhbiBuZXZlcgogKiB0b3VjaCBzb21lb25lIGVsc2UncyB0cmFmZmljLgogKi8KCmltcG9ydCB0eXBlIHsKICBQcm92aWRlcldyYXBTdHJlYW1GbkNvbnRleHQsCiAgU3RyZWFtRm4sCiAgU3RyZWFtT3B0aW9ucywKfSBmcm9tICdvcGVuY2xhdy9wbHVnaW4tc2RrL3Byb3ZpZGVyLXR5cGVzJzsKaW1wb3J0IHsgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5IH0gZnJvbSAnLi9zZXNzaW9uSWRlbnRpdHkuanMnOwoKZXhwb3J0IGNvbnN0IEFOWVJBWV9QUk9WSURFUl9JRCA9ICdhbnlyYXknOwoKLyoqIENhY2hlIHJldGVudGlvbiBkZWZhdWx0IGZvciB0aGUgZ2F0ZXdheSBob3N0OiBPcGVuQ2xhdyBhdXRvLXNlZWRzIHByb21wdAogKiAgY2FjaGluZyBvbmx5IG9uIGFwaS5hbnRocm9waWMuY29tL1ZlcnRleCwgc28gdW5zZXQgaGVyZSBtZWFucyAibm8KICogIGNhY2hlX2NvbnRyb2wgYXQgYWxsIiDigJQgYSBjb2xkIHByb3ZpZGVyIGNhY2hlIG9uIGV2ZXJ5IHdhcm0gdHVybi4gKi8KY29uc3QgQ0FDSEVfUkVURU5USU9OX0RFRkFVTFQgPSAnc2hvcnQnOwoKZXhwb3J0IGNvbnN0IGNyZWF0ZUFueXJheVN0cmVhbVdyYXBwZXIgPSAoCiAgY3R4OiBQcm92aWRlcldyYXBTdHJlYW1GbkNvbnRleHQKKTogU3RyZWFtRm4gfCB1bmRlZmluZWQgPT4gewogIGNvbnN0IGlubmVyID0gY3R4LnN0cmVhbUZuOwogIGlmICghaW5uZXIpIHJldHVybiB1bmRlZmluZWQ7CiAgaWYgKGN0eC5wcm92aWRlciAhPT0gQU5ZUkFZX1BST1ZJREVSX0lEKSByZXR1cm4gdW5kZWZpbmVkOwoKICBjb25zdCB3cmFwcGVkOiBTdHJlYW1GbiA9IChtb2RlbCwgY29udGV4dCwgb3B0aW9ucykgPT4gewogICAgaWYgKG1vZGVsLnByb3ZpZGVyICE9PSBBTllSQVlfUFJPVklERVJfSUQgfHwgbW9kZWwuYXBpICE9PSAnYW50aHJvcGljLW1lc3NhZ2VzJykgewogICAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdGlvbnMpOwogICAgfQogICAgY29uc3Qgb3B0czogU3RyZWFtT3B0aW9ucyA9IHsgLi4uKG9wdGlvbnMgPz8ge30pIH07CiAgICBpZiAob3B0cy5jYWNoZVJldGVudGlvbiA9PT0gdW5kZWZpbmVkKSB7CiAgICAgIG9wdHMuY2FjaGVSZXRlbnRpb24gPSBDQUNIRV9SRVRFTlRJT05fREVGQVVMVDsKICAgIH0KICAgIC8vIExpdmUtY29udGFpbmVyIGZhY3QgKDIwMjYuNy4xKTogdGhlIHRyYW5zcG9ydCBkcm9wcyB0aGUgY2F0YWxvZydzCiAgICAvLyBwcm92aWRlci1sZXZlbCBgaGVhZGVyc2AgZm9yIHBsdWdpbiBwcm92aWRlcnMsIHNvIHRoZSBjb250ZW50LWZyZWUKICAgIC8vIGF0dHJpYnV0aW9uIHJpZGVzIHRoZSBwZXItY2FsbCBoZWFkZXIgbGV2ZXIgaW5zdGVhZC4gVGhlIEFueXJheSBnYXRld2F5CiAgICAvLyBuZWVkcyBubyBhbnRocm9waWMtYmV0YSBmcm9tIHVzIChpdHMgb3JnIGxhbmUgbWludHMgcHJvdmlkZXIgaGVhZGVycwogICAgLy8gc2VydmVyLXNpZGUpLCBhbmQgYXV0aCBhbHJlYWR5IHJpZGVzIHgtYXBpLWtleTsgdGhpcyBpcyBkaWFnbm9zdGljcwogICAgLy8gYXR0cmlidXRpb24gb25seS4gRXhpc3RpbmcgdmFsdWVzIGFyZSBuZXZlciBvdmVyd3JpdHRlbi4KICAgIGNvbnN0IGhlYWRlcnMgPSB7IC4uLihvcHRzLmhlYWRlcnMgPz8ge30pIH07CiAgICBpZiAoaGVhZGVyc1sneC1hbnlyYXktbWV0YWRhdGEnXSA9PT0gdW5kZWZpbmVkKSB7CiAgICAgIGhlYWRlcnNbJ3gtYW55cmF5LW1ldGFkYXRhJ10gPSAneyJ0b29sIjoib3BlbmNsYXcifSc7CiAgICB9CiAgICBpZiAoCiAgICAgIGhlYWRlcnNbJ3gtYW55cmF5LWFwaS1rZXknXSA9PT0gdW5kZWZpbmVkICYmCiAgICAgIHR5cGVvZiBvcHRzLmFwaUtleSA9PT0gJ3N0cmluZycgJiYKICAgICAgb3B0cy5hcGlLZXkuc3RhcnRzV2l0aCgnYXJrXycpCiAgICApIHsKICAgICAgaGVhZGVyc1sneC1hbnlyYXktYXBpLWtleSddID0gb3B0cy5hcGlLZXk7CiAgICB9CiAgICBvcHRzLmhlYWRlcnMgPSBoZWFkZXJzOwogICAgY29uc3Qgc2Vzc2lvbklkID0KICAgICAgdHlwZW9mIG9wdHMuc2Vzc2lvbklkID09PSAnc3RyaW5nJyA/IG9wdHMuc2Vzc2lvbklkIDogdW5kZWZpbmVkOwogICAgY29uc3QgY2FsbGVyT25QYXlsb2FkID0gb3B0cy5vblBheWxvYWQ7CiAgICBvcHRzLm9uUGF5bG9hZCA9IGFzeW5jIChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpID0+IHsKICAgICAgaWYgKHBheWxvYWQgJiYgdHlwZW9mIHBheWxvYWQgPT09ICdvYmplY3QnICYmICFBcnJheS5pc0FycmF5KHBheWxvYWQpKSB7CiAgICAgICAgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5KAogICAgICAgICAgcGF5bG9hZCBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPiwKICAgICAgICAgIHNlc3Npb25JZAogICAgICAgICk7CiAgICAgIH0KICAgICAgcmV0dXJuIGNhbGxlck9uUGF5bG9hZCA/IGNhbGxlck9uUGF5bG9hZChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpIDogcGF5bG9hZDsKICAgIH07CiAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdHMpOwogIH07CiAgcmV0dXJuIHdyYXBwZWQ7Cn07Cg=="}];var Mf=".anyray-source-sha",rn=()=>zs(_D(),".anyray","openclaw-plugin"),bC=async(e=rn())=>{try{if((await wC(zs(e,Mf),"utf8")).trim()===$f)return"current"}catch{}for(let t of gC){let n=zs(e,t.path);await PD(TD(n),{recursive:!0,mode:448}),await pe(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await pe(zs(e,Mf),`${$f}
195
- `),"installed"},Il=async(e=rn())=>{try{await wC(zs(e,Mf),"utf8")}catch{return!1}return await LD(e,{recursive:!0,force:!0}),!0};var Wf="x-anyray-metadata",sa="x-anyray-api-key",Hf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],ao="Authorization",so="anthropic-beta",Rl="interleaved-thinking-2025-05-14",Ol=["anthropic","openai"],vC="short",Gf="anthropic-messages",jf=32e3,_l="anthropic/claude-sonnet-4-5",Vf=["anthropic/claude-haiku-4-5"],Yf="anyray/claude-sonnet-4-5",Zf=["anyray/claude-haiku-4-5"],UD=[_l,Yf],BD=[Vf,Zf],ze="anyray",Ar="ANYRAY_API_KEY",Qs="openclaw",SC=()=>process.env.OPENCLAW_STATE_DIR?.trim()||xl(CC(),".openclaw"),oo=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||xl(SC(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},qs=async e=>{let t=await R(e),n=t?await AC(e,"utf8"):`{}
196
- `,r=n.trim()?yr(n):{};if(!N(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},EC=(e,t,n=[])=>{if(N(e)&&N(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...EC(e[o],t[o],[...n,o])):r.push({path:[...n,o],value:t[o]}):r.push({path:[...n,o],value:void 0});return r}return JSON.stringify(e)===JSON.stringify(t)?[]:[{path:n,value:t}]},Ff=async(e,t,n,r)=>{let o=EC(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await $D(e,`${e}.anyray-bak`,DD.COPYFILE_EXCL),await ND(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await pe(`${e}.anyray-bak`,`{}
194
+ `),!0},vD=async e=>{try{let t=yn(await xl(`${e}.anyray-bak`,"utf8"));return B(t)?t:void 0}catch{return}},Rf=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",_f=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Rf()}/${bD}`,B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Nf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},SD=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===Cr[0]||n===Cr[1]||n===Wn?[]:B(r)&&B(r.options)&&Nf(r.options.baseURL,t)?[n]:[]),Pf=/claude/i,$f=["model","small_model"],yC=(e,t)=>{if(typeof e!="string")return;let n=e.indexOf("/");if(n<=0)return;let r=e.slice(0,n),o=e.slice(n+1);if(!(!t.includes(r)||!Pf.test(o)))return`${Cr[0]}/${o}`},Tf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Tf(n,t);return t}if(!B(e))return t;for(let[n,r]of Object.entries(e))$f.includes(n)&&typeof r=="string"?t.push(r):Tf(r,t);return t},ED=(e,t,n)=>{if(!B(e)||!B(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Pf.test(a)))return!1;let o=`${n}/`;return Tf(t).filter(a=>a.startsWith(o)).every(a=>Pf.test(a.slice(o.length)))},Lf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Lf(o,t,n));if(!B(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=$f.includes(o)?yC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Lf(a,t,n)}return r},Df=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Df(o,t[a],n));if(!B(e)||!B(t))return e;let r={};for(let[o,a]of Object.entries(e))$f.includes(o)&&typeof a=="string"&&yC(t[o],n)===a?r[o]=t[o]:r[o]=Df(a,t[o],n);return r},xD=e=>{if(B(e))for(let t of Cr){let n=e[t];if(B(n)&&B(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},zs=e=>{if(!B(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&qt({command:t,args:n},"profile")},El=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),ID=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return B(t)&&t.tool==="opencode"}catch{return!1}},Mf=e=>J(e,"copilot")&&!!e.clientKey,OD=e=>e.byoUpstream?[]:J(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],RD=(e,t)=>J(e,"openai")?[`OpenAI subscription: OpenCode's built-in ChatGPT Pro/Plus OAuth is ${t?"detected":"not signed in yet (run `opencode auth login`)"}. Its Codex endpoint is hard-coded to chatgpt.com, so provider.baseURL cannot redirect it. Connect leaves machine networking untouched. Use the Codex app/CLI/IDE for ChatGPT subscription pass-through, or sign OpenCode into an API-key/Copilot provider that Connect can route.`]:[],_D=e=>Mf(e)?["Tip: to spend your Copilot subscription (incl. Claude & GPT), pick the github-copilot/* models in OpenCode \u2014 e.g. github-copilot/claude-sonnet-4.5. The anthropic/* and openai/* entries are the direct providers (api-key mode, separate billing) \u2014 not your Copilot plan."]:[],PD=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=If);let o=!1;if(n)if("mcp"in r&&!B(r.mcp))o=!0;else{let y=B(r.mcp)?{...r.mcp}:{},b=y[Un];b!==void 0&&!zs(b)?o=!0:(y[Un]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(B(r.mcp)&&zs(r.mcp[Un])){let y={...r.mcp};delete y[Un],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=B(r.provider)?{...r.provider}:{},s=SD(a,t.origin),i=s.every(y=>ED(a[y],e,y))?s:[],c=s.filter(y=>!i.includes(y)),l=[];if(i.length>0){for(let y of i)delete a[y];r=Lf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,h=de({...t.metadata,tool:"opencode"});for(let y of c){let b={...a[y]},A={...b.options};if("headers"in A&&!B(A.headers)){u.push(y);continue}let v=B(A.headers)?{...A.headers}:{},E=!1;for(let[x,C]of[[Ft,p],...h?[[Bn,h]]:[]])x in v?(typeof v[x]!="string"||v[x].trim()==="")&&u.push(`${y}.${x}`):(v[x]=C,d.push(`${y}.${x}`),E=!0);E&&(A.headers=v,b.options=A,a[y]=b)}let m=c.length>0?[]:Cr.filter(y=>y!=="openai"||!J(t,"openai")),w=t.byoUpstream;for(let y of m){let b=B(a[y])?{...a[y]}:{},A=B(b.options)?{...b.options}:{};A.baseURL=f;let v=B(A.headers)?{...A.headers}:{};if(y==="anthropic"&&w)A.apiKey=w.key,v[Fn]=`Bearer ${w.key}`,v["x-anyray-provider"]="anthropic",v["x-anyray-auth-mode"]="passthrough",v["x-anyray-custom-host"]=w.url;else{A.apiKey=p,"x-anyray-custom-host"in v&&delete v[Fn];for(let E of Of)delete v[E]}v[Ft]=p,h&&(v[Bn]=h),A.headers=v,b.options=A,a[y]=b}let g=c.length===0&&Mf(t);if(g){let y=B(a[Wn])?{...a[Wn]}:{},b=B(y.options)?{...y.options}:{};b.baseURL=_f(t);let A=B(b.headers)?{...b.headers}:{};A[Ft]=t.clientKey,h&&(A[Bn]=h),b.headers=A,y.options=b,a[Wn]=y}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:g,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},TD=["baseURL","apiKey"],uC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!B(s)||!B(s.options))return!1;let i={...s},c={...s.options},l=!1;if(n){let d=typeof c.baseURL=="string"&&c.baseURL.includes("/v1/copilot/"),u=B(c.headers)?{...c.headers}:void 0,f=u?.[Ft],p=El(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let h=u,m=B(r)?r.options:void 0,w=B(m)&&B(m.headers)?m.headers:void 0;for(let g of[Ft,Bn])w&&g in w?h[g]!==w[g]&&(h[g]=w[g],l=!0):g in h&&(delete h[g],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}else{let d=B(r)?r.options:void 0,u=B(d)?d:{},f=B(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Ft]=="string"||typeof f[Bn]=="string"||Of.some(h=>h in f);if(!o&&!p)return!1;for(let h of TD)h in u?c[h]!==u[h]&&(c[h]=u[h],l=!0):h in c&&(delete c[h],l=!0);if(B(c.headers)){let h={...c.headers},m=B(u.headers)?u.headers:{};"x-anyray-custom-host"in h&&Fn in h&&(Fn in m?h[Fn]!==m[Fn]&&(h[Fn]=m[Fn],l=!0):(delete h[Fn],l=!0));for(let w of[Ft,Bn,...Of])w in m?h[w]!==m[w]&&(h[w]=m[w],l=!0):w in h&&(delete h[w],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}return l?(Object.keys(c).length===0?delete i.options:i.options=c,Object.keys(i).length===0?delete e[t]:e[t]=i,!0):!1},LD=(e,t,n)=>{let r=e[t];if(!B(r)||!B(r.options)||!B(n)||!B(n.options))return!1;let o={...r.options};if(!B(o.headers)||"headers"in n.options&&!B(n.options.headers))return!1;let a={...o.headers},s=B(n.options.headers)?n.options.headers:{},i=!1;return!(Ft in s)&&El(a[Ft])&&(delete a[Ft],i=!0),!(Bn in s)&&ID(a[Bn])&&(delete a[Bn],i=!0),i?(Object.keys(a).length===0?"headers"in n.options?o.headers=s:delete o.headers:o.headers=a,e[t]={...r,options:o},!0):!1},DD=(e,t)=>{let n={...e},r=!1,o=xD(e.provider);if(B(n.mcp)&&zs(n.mcp[Un])){let c={...n.mcp};delete c[Un],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!B(n.provider))return{next:n,removed:r};let a={...n.provider},s=B(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===If&&Cr.every(c=>{let l=a[c];return B(l)&&B(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of Cr)uC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...Cr,Wn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;LD(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&B(u)&&B(u.options)&&Nf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Df(n,t,l))}return uC(a,Wn,!0,s[Wn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===If&&(delete n.$schema,r=!0),{next:n,removed:r}},gC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=Il(),t=fC(),n=await O(e)||await O(t),r=n&&await cC();return{installed:n,detail:n?`${await lC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await lC(),r=e.openaiBaseUrl,o=de({...e.metadata,tool:"opencode"}),a=Mf(e),s=J(e,"openai"),i=await cC(),c;try{c=await aa(n)}catch{return e.clientKey?{status:"manual",messages:[`Couldn't parse ${n} \u2014 set it by hand. Under "provider", add:`,e.byoUpstream?` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your upstream key>", "headers": { "Authorization": "Bearer <your upstream key>", "x-anyray-auth-mode": "passthrough", "x-anyray-provider": "anthropic", "x-anyray-custom-host": ${JSON.stringify(e.byoUpstream.url)}, "x-anyray-api-key": "<your personal ark_ key>" } } }`:` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`,...s?[]:[` "openai": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`],...a?[` "github-copilot": { "options": { "baseURL": ${JSON.stringify(_f(e))}, "headers": { "${Ft}": "<your personal ark_ key>" } } }`]:[]]}:{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Enroll with --enroll or --sso before configuring OpenCode.`]}}let l=await Br()?Ve("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=PD(c.data,e,l),g=u.length>0,y=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(C=>`provider.${C}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...p.length>0?[`Updated model references: ${p.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=g?[`${n} already routes through ${e.origin} via ${u.map(C=>`provider.${C}`).join(", ")}; existing provider values were preserved.`,h.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${h.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...m.length>0?[`Could not safely add required headers at ${m.join(", ")} because the existing values have incompatible shapes. Fix those values manually; no existing value was replaced.`]:[],"Canonical anthropic, openai, and github-copilot provider blocks were left untouched.","Restart OpenCode (or start a new session) to pick up the change."]:[...y,s?`${n} \u2192 provider.anthropic options.baseURL = ${r}; provider.openai left untouched because OpenCode's ChatGPT OAuth loader has no configurable endpoint.`:`${n} \u2192 provider.anthropic + provider.openai options.baseURL = ${r}`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${o??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...OD(e),...RD(e,i),a?`provider.github-copilot options.baseURL \u2192 ${_f(e)} with the personal gateway key in options.headers (never the URL). OpenCode keeps its Copilot sign-in, GitHub bills your plan, and the gateway meters it. ${Rf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Rf()} plan-specific host selected by ANYRAY_COPILOT_PLAN.`}`:"GitHub Copilot: not routed \u2014 needs a Copilot seat plus enrollment (a detected Copilot plan or --subscription, and --enroll for the seat key).",..._D(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Un} is not owned by Anyray Connect, so it was left untouched.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let A=m.length>0?"manual":"configured";if(t.dryRun)return{status:A,messages:b};let E=await dC(n,c,d,!0)?[n]:[],x=Sl();if(le())try{let C=await iC(x,ds(Je,["opencode"]));C==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${x} already exists and is not owned by Anyray.`):(C==="installed"&&E.push(x),b.push(`The OpenCode tool.execute.after carrier is active in ${x}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${x}. Gateway-side optimization remains active.`)}else{try{await xf(x)==="removed"&&E.push(x)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:A,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await sa())try{let{data:n}=await aa(t);if(!B(n.provider))continue;for(let r of Object.values(n.provider))if(!(!B(r)||!B(r.options))&&Nf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await sa())try{let{data:t}=await aa(e);if(!B(t.mcp))continue;let n=t.mcp[Un];if(!zs(n)||!B(n))continue;return{registered:!0,command:Array.isArray(n.command)&&typeof n.command[0]=="string"?n.command[0]:null}}catch{}return{registered:!1,command:null}},async integrationStatus(){let e,t=!0;try{let i=await qs(Sl());e=i==="absent"?"missing":i,e==="owned"&&(t=await xl(Sl(),"utf-8")===Ef(ds(Je,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await sa()){let c;try{c=await aa(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!B(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Un];if(l!==void 0)if(zs(l))if(n=!0,!B(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;Cc({command:d,args:u},"profile")||(a=!1)}else r=!0}return{hook_registration:e,mcp_registration:o?"unreadable":r?"foreign":n?"owned":"missing",hook_binary:t&&a&&await Br()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await hC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await sa()){let{data:o}=await aa(r);if(B(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!B(s)||!B(s.options)){e.add("unknown");continue}let i=s.options,c=B(i.headers)?i.headers:{};if(a===Wn&&typeof i.baseURL=="string"&&i.baseURL.includes("/v1/copilot/")){e.add("subscription");continue}if(a==="openai"&&n&&i.baseURL===void 0&&i.apiKey===void 0){e.add("native");continue}if(a===Wn&&i.baseURL===void 0&&i.apiKey===void 0){e.add("native");continue}if(typeof c["x-anyray-custom-host"]=="string"){e.add("byo");continue}if(c["x-anyray-auth-mode"]==="passthrough"){e.add("subscription");continue}if(El(c[Ft])||El(i.apiKey)||typeof i.apiKey=="string"&&i.apiKey.length>0||typeof c.Authorization=="string"&&c.Authorization.length>0){e.add("api_key");continue}e.add("unknown")}}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=await sa(),n=Sl(),r="absent";try{r=await qs(n)}catch{}if(t.length===0&&r!=="owned")return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[...t.map(i=>`would remove Anyray provider settings from ${i}`),...r==="owned"?[`would remove the Anyray OpenCode trim carrier from ${n}`]:[]]};let o=[],a=[],s=[];for(let i of t){let c;try{c=await aa(i)}catch{s.push(i);continue}let{next:l,removed:d}=DD(c.data,await vD(i));d&&(await dC(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await se(i)}for(let i of s)o.push(`Couldn't parse ${i} \u2014 if you added Anyray settings there by hand, remove the baseURL/apiKey from provider.anthropic, provider.openai, and provider.github-copilot yourself.`);if(r==="owned")try{await xf(n)==="removed"&&(a.push(n),o.push(`removed the Anyray OpenCode trim carrier from ${n}`))}catch{o.push(`Could not remove the Anyray OpenCode trim carrier from ${n}. Remove that file manually.`)}return a.length===0&&s.length===0&&o.push("no Anyray provider settings found"),{status:a.length===0&&s.length>0?"manual":"reverted",messages:o,changedFiles:a.length?a:void 0}}};import{homedir as AC}from"node:os";import{join as Rl}from"node:path";import{constants as UD,chmod as BD,copyFile as WD,readFile as vC}from"node:fs/promises";import{applyEdits as HD,modify as KD}from"jsonc-parser";import{homedir as ND}from"node:os";import{dirname as $D,join as Qs}from"node:path";import{mkdir as MD,readFile as bC,rm as FD}from"node:fs/promises";var Ff="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",wC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfQogICAgfQogIH0sCiAgImNvbmZpZ1NjaGVtYSI6IHsKICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAiYWRkaXRpb25hbFByb3BlcnRpZXMiOiBmYWxzZSwKICAgICJyZXF1aXJlZCI6IFsiZ2F0ZXdheVVybCJdLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkFueXJheSBnYXRld2F5IG9yaWdpbiwgZS5nLiBodHRwczovL2dhdGV3YXkuZXhhbXBsZS5hbnlyYXkuYWkgKG5vIC92MSBzdWZmaXgpLiIKICAgICAgfSwKICAgICAgImFwaUtleSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJQZXJzb25hbCBBbnlyYXkgY2xpZW50IGtleSAoYXJrX+KApikuIFN1cHBvcnRzICR7RU5WX1ZBUn0gc3Vic3RpdHV0aW9uOyBkZWZhdWx0cyB0byAke0FOWVJBWV9DTElFTlRfS0VZfS4iCiAgICAgIH0sCiAgICAgICJ1c2VyIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkF0dHJpYnV0aW9uIHVzZXIgKGNvbnRlbnQtZnJlZTsgdXN1YWxseSBhbiBlbWFpbCkuIE9wdGlvbmFsIOKAlCB0aGUgY2xpZW50IGtleSBhbHJlYWR5IGF0dHJpYnV0ZXMgdGhlIGVucm9sbGVkIHVzZXIuIgogICAgICB9LAogICAgICAidGVhbSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB0ZWFtIChjb250ZW50LWZyZWUpLiBPcHRpb25hbC4iCiAgICAgIH0KICAgIH0sCiAgICAidWlIaW50cyI6IHsKICAgICAgImdhdGV3YXlVcmwiOiB7CiAgICAgICAgImxhYmVsIjogIkdhdGV3YXkgVVJMIiwKICAgICAgICAiaGVscCI6ICJZb3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IG9yaWdpbi4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgImxhYmVsIjogIkNsaWVudCBrZXkiLAogICAgICAgICJoZWxwIjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudC4gTGVhdmUgdW5zZXQgdG8gcmVhZCAkQU5ZUkFZX0NMSUVOVF9LRVkuIgogICAgICB9CiAgICB9CiAgfQp9Cg=="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjEuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJEZXBlbmRlbmNpZXMiOiB7CiAgICAib3BlbmNsYXciOiAiPj0yMDI2LjcuMSIKICB9LAogICJkZXZEZXBlbmRlbmNpZXMiOiB7CiAgICAidHN4IjogIl40LjIzLjUiLAogICAgInR5cGVzY3JpcHQiOiAiXjUuNi4zIgogIH0KfQo="},{path:"src/index.ts",contentBase64:"LyoqCiAqIEFueXJheSBPcGVuQ2xhdyBwbHVnaW4g4oCUIHJvdXRlcyBPcGVuQ2xhdydzIG1vZGVsIGNhbGxzIHRocm91Z2ggYW4gb3JnJ3MKICogQW55cmF5IGdhdGV3YXkgYXMgdGhlIGBhbnlyYXlgIHByb3ZpZGVyLgogKgogKiBXaGF0IGl0IGFkZHMgb3ZlciB0aGUgcGxhaW4gYG1vZGVscy5wcm92aWRlcnNgIGNvbmZpZyB0aGUgY29ubmVjdCBhZGFwdGVyCiAqIHdyaXRlczoKICogIC0gcGVyLWNhbGwgc2Vzc2lvbiBpZGVudGl0eSAoYG1ldGFkYXRhLnVzZXJfaWRgKSB2aWEgdGhlIHN0cmVhbSB3cmFwcGVyLCBzbwogKiAgICB0aGUgZ2F0ZXdheSBnZXRzIENsYXVkZSBDb2RlLWdyYWRlIHBlci1jb252ZXJzYXRpb24gb3B0aW1pemVyIHNlc3Npb25zCiAqICAgIGluc3RlYWQgb2YgYW5jaG9yIGZpbmdlcnByaW50czsKICogIC0gYSBjYWNoZS1yZXRlbnRpb24gZGVmYXVsdCBvbiBldmVyeSBjYWxsIChPcGVuQ2xhdyBoYXMgbm8gYXV0by1zZWVkIG9uCiAqICAgIGN1c3RvbSBob3N0cyk7CiAqICAtIHRoZSB3aG9sZSBwcm92aWRlciBlbnRyeSAoYmFzZSBVUkwsIGFwaSBraW5kLCBwZXItbW9kZWwgbWF4VG9rZW5zLCBiZXRhCiAqICAgIHJlc3RvcmUsIGF0dHJpYnV0aW9uIGhlYWRlcnMpIGNvbnRyaWJ1dGVkIGZyb20gb25lIHBsdWdpbiBjb25maWcgYmxvY2suCiAqCiAqIFRoZSBtYW5pZmVzdCdzIHN0YXRpYyBgbW9kZWxDYXRhbG9nYCBibG9jayBpcyB3aGF0IE9wZW5DbGF3IG1hdGVyaWFsaXplcyBmb3IKICogbW9kZWwgZGlzY292ZXJ5IGJlZm9yZSB0aGlzIHJ1bnRpbWUgY2F0YWxvZyByZXNvbHZlcyAobGl2ZS1jb250YWluZXIgZmFjdDoKICogd2l0aG91dCBpdCwgYGFueXJheS8qYCByZWZzIGFyZSB1bmtub3duIHRvIHRoZSBhZ2VudCBydW50aW1lKTsgdGhlIHJ1bnRpbWUKICogYGNhdGFsb2cucnVuYCB0aGVuIHN1cHBsaWVzIHRoZSByZWFsIGdhdGV3YXkgY29vcmRpbmF0ZXMgZnJvbSBwbHVnaW4gY29uZmlnLgogKgogKiBQUklWQUNZOiBldmVyeXRoaW5nIGluamVjdGVkIGlzIGNvbnRlbnQtZnJlZSDigJQgYW4gb3BhcXVlIHNlc3Npb24gaWQgaGFzaCwKICogdGhlIGVucm9sbG1lbnQga2V5LCBhbmQgdXNlci90ZWFtIGF0dHJpYnV0aW9uIHRoZSBvcGVyYXRvciBjb25maWd1cmVkLgogKi8KCmltcG9ydCB7IGRlZmluZVNpbmdsZVByb3ZpZGVyUGx1Z2luRW50cnkgfSBmcm9tICdvcGVuY2xhdy9wbHVnaW4tc2RrL3Byb3ZpZGVyLWVudHJ5JzsKaW1wb3J0IHR5cGUgeyBQcm92aWRlckNhdGFsb2dDb250ZXh0IH0gZnJvbSAnb3BlbmNsYXcvcGx1Z2luLXNkay9wcm92aWRlci10eXBlcyc7CmltcG9ydCBtYW5pZmVzdCBmcm9tICcuLi9vcGVuY2xhdy5wbHVnaW4uanNvbicgd2l0aCB7IHR5cGU6ICdqc29uJyB9OwppbXBvcnQgeyBidWlsZEFueXJheVByb3ZpZGVyLCB0eXBlIEFueXJheVBsdWdpbkNvbmZpZyB9IGZyb20gJy4vY2F0YWxvZy5qcyc7CmltcG9ydCB7IGNyZWF0ZUFueXJheVN0cmVhbVdyYXBwZXIgfSBmcm9tICcuL3N0cmVhbVdyYXBwZXIuanMnOwoKLyoqIFRoZSBwbHVnaW4ncyBvd24gYHBsdWdpbnMuZW50cmllcy5hbnlyYXkuY29uZmlnYCBibG9jayBmcm9tIHRoZSByZXNvbHZlZAogKiAgZ2F0ZXdheSBjb25maWcuIFRoZSBwbGFpbi1vYmplY3QgYHByb3ZpZGVyYCBmb3JtICh0aGUgc2hhcGUgdGhlIHNoaXBwZWQKICogIDIwMjYuNy54IFNESyBub3JtYWxpemVzOyB0aGUgYChhcGkpID0+IOKApmAgZnVuY3Rpb24gZm9ybSBpcyBuZXdlcikgaGFzIG5vCiAqICBgYXBpLnBsdWdpbkNvbmZpZ2AgY2xvc3VyZSwgc28gdGhlIGNhdGFsb2cgcmVhZHMgaXQgZnJvbSBgY3R4LmNvbmZpZ2AuICovCmNvbnN0IHBsdWdpbkNvbmZpZ09mID0gKGN0eDogUHJvdmlkZXJDYXRhbG9nQ29udGV4dCk6IEFueXJheVBsdWdpbkNvbmZpZyA9PiB7CiAgY29uc3QgcGx1Z2lucyA9IGN0eC5jb25maWcucGx1Z2luczsKICBpZiAodHlwZW9mIHBsdWdpbnMgIT09ICdvYmplY3QnIHx8IHBsdWdpbnMgPT09IG51bGwpIHJldHVybiB7fTsKICBjb25zdCBlbnRyaWVzID0gKHBsdWdpbnMgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4pLmVudHJpZXM7CiAgaWYgKHR5cGVvZiBlbnRyaWVzICE9PSAnb2JqZWN0JyB8fCBlbnRyaWVzID09PSBudWxsKSByZXR1cm4ge307CiAgY29uc3QgZW50cnkgPSAoZW50cmllcyBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPikuYW55cmF5OwogIGlmICh0eXBlb2YgZW50cnkgIT09ICdvYmplY3QnIHx8IGVudHJ5ID09PSBudWxsKSByZXR1cm4ge307CiAgY29uc3QgY29uZmlnID0gKGVudHJ5IGFzIFJlY29yZDxzdHJpbmcsIHVua25vd24+KS5jb25maWc7CiAgaWYgKHR5cGVvZiBjb25maWcgIT09ICdvYmplY3QnIHx8IGNvbmZpZyA9PT0gbnVsbCkgcmV0dXJuIHt9OwogIHJldHVybiBjb25maWcgYXMgQW55cmF5UGx1Z2luQ29uZmlnOwp9OwoKZXhwb3J0IGRlZmF1bHQgZGVmaW5lU2luZ2xlUHJvdmlkZXJQbHVnaW5FbnRyeSh7CiAgaWQ6ICdhbnlyYXknLAogIG5hbWU6ICdBbnlyYXknLAogIGRlc2NyaXB0aW9uOgogICAgIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogIG1hbmlmZXN0LAogIHByb3ZpZGVyOiB7CiAgICBsYWJlbDogJ0FueXJheScsCiAgICBkb2NzUGF0aDogJ2h0dHBzOi8vZG9jcy5hbnlyYXkuYWkvaW50ZWdyYXRpb25zL29wZW5jbGF3JywKICAgIGNhdGFsb2c6IHsKICAgICAgcnVuOiBhc3luYyAoY3R4OiBQcm92aWRlckNhdGFsb2dDb250ZXh0KSA9PiAoewogICAgICAgIHByb3ZpZGVyOiBidWlsZEFueXJheVByb3ZpZGVyKHBsdWdpbkNvbmZpZ09mKGN0eCksIGN0eC5lbnYpLAogICAgICB9KSwKICAgIH0sCiAgICB3cmFwU3RyZWFtRm46IGNyZWF0ZUFueXJheVN0cmVhbVdyYXBwZXIsCiAgfSwKfSk7Cg=="},{path:"src/catalog.ts",contentBase64:"LyoqCiAqIEFueXJheSBwcm92aWRlciBjYXRhbG9nIOKAlCB0aGUgYG1vZGVscy5wcm92aWRlcnMuYW55cmF5YCBlbnRyeSB0aGlzIHBsdWdpbgogKiBjb250cmlidXRlcyBmcm9tIGl0cyBvd24gY29uZmlnLCByZXBsYWNpbmcgdGhlIGhhbmQtd3JpdHRlbiBKU09OIHRoZSBjb25uZWN0CiAqIGFkYXB0ZXIgb3RoZXJ3aXNlIG1haW50YWlucyAoYmFzZSBVUkwsIGFwaSBraW5kLCBwZXItbW9kZWwgbWF4VG9rZW5zLCB0aGUKICogb2ZmLWhvc3QgYmV0YS1oZWFkZXIgcmVzdG9yZSkuCiAqCiAqIFB1cmU6IGNvbmZpZyBpbiwgTW9kZWxQcm92aWRlckNvbmZpZyBvdXQuIFRoZSBFMkUtcHJvdmVuIGxhbmRtaW5lcyBmcm9tIHRoZQogKiBjb25maWctZmlsZSBpbnRlZ3JhdGlvbiBhcmUgZW5jb2RlZCBoZXJlIG9uY2U6IGV4cGxpY2l0IGBhcGlgIChhIGN1c3RvbWl6ZWQKICogZW50cnkgb3RoZXJ3aXNlIHNpbGVudGx5IGZhbGxzIHRvIHRoZSBPcGVuQUktY29tcGF0aWJsZSBkaWFsZWN0KSBhbmQKICogcGVyLW1vZGVsIGBtYXhUb2tlbnNgIChhIGN1c3RvbWl6ZWQgZW50cnkgc3RvcHMgaW5oZXJpdGluZyB0aGUgY2F0YWxvZydzKS4KICovCgppbXBvcnQgdHlwZSB7IE1vZGVsUHJvdmlkZXJDb25maWcgfSBmcm9tICdvcGVuY2xhdy9wbHVnaW4tc2RrL3Byb3ZpZGVyLXR5cGVzJzsKCmV4cG9ydCBpbnRlcmZhY2UgQW55cmF5UGx1Z2luQ29uZmlnIHsKICBnYXRld2F5VXJsPzogdW5rbm93bjsKICBhcGlLZXk/OiB1bmtub3duOwogIHVzZXI/OiB1bmtub3duOwogIHRlYW0/OiB1bmtub3duOwp9CgovKiogT3BlbkNsYXcgc3VwcHJlc3NlcyBpbXBsaWNpdCBiZXRhIGhlYWRlcnMgb2ZmLWhvc3Q7IHJlc3RvcmUgdGhlIEFQSS1rZXkgc2V0LiAqLwpjb25zdCBBTlRIUk9QSUNfQkVUQSA9ICdpbnRlcmxlYXZlZC10aGlua2luZy0yMDI1LTA1LTE0JzsKCi8qKiBEZWZhdWx0IGtleSByZWZlcmVuY2Ug4oCUIE9wZW5DbGF3IHN1YnN0aXR1dGVzICR7RU5WfSBpbiBjb25maWcgc3RyaW5ncywgYnV0CiAqICBwbHVnaW4gY29uZmlnIGFycml2ZXMgcmVzb2x2ZWQsIHNvIGFuIHVuc2V0IGtleSBmYWxscyBiYWNrIHRvIHRoZSBlbnYgdmFyCiAqICB0aGUgY29ubmVjdCBlbnJvbGxtZW50IHdyaXRlcy4gKi8KY29uc3QgS0VZX0VOViA9ICdBTllSQVlfQ0xJRU5UX0tFWSc7Cgpjb25zdCBNT0RFTFM6IFJlYWRvbmx5QXJyYXk8UmVjb3JkPHN0cmluZywgdW5rbm93bj4+ID0gWwogIHsKICAgIGlkOiAnY2xhdWRlLXNvbm5ldC00LTUnLAogICAgbmFtZTogJ0NsYXVkZSBTb25uZXQgNC41IChBbnlyYXkpJywKICAgIHJlYXNvbmluZzogdHJ1ZSwKICAgIGlucHV0OiBbJ3RleHQnLCAnaW1hZ2UnXSwKICAgIGNvbnRleHRXaW5kb3c6IDIwMDAwMCwKICAgIG1heFRva2VuczogNjQwMDAsCiAgfSwKICB7CiAgICBpZDogJ2NsYXVkZS1oYWlrdS00LTUnLAogICAgbmFtZTogJ0NsYXVkZSBIYWlrdSA0LjUgKEFueXJheSknLAogICAgcmVhc29uaW5nOiB0cnVlLAogICAgaW5wdXQ6IFsndGV4dCcsICdpbWFnZSddLAogICAgY29udGV4dFdpbmRvdzogMjAwMDAwLAogICAgbWF4VG9rZW5zOiA2NDAwMCwKICB9LAogIHsKICAgIGlkOiAnY2xhdWRlLW9wdXMtNC04JywKICAgIG5hbWU6ICdDbGF1ZGUgT3B1cyA0LjggKEFueXJheSknLAogICAgcmVhc29uaW5nOiB0cnVlLAogICAgaW5wdXQ6IFsndGV4dCcsICdpbWFnZSddLAogICAgY29udGV4dFdpbmRvdzogMjAwMDAwLAogICAgbWF4VG9rZW5zOiAzMjAwMCwKICB9LApdOwoKY29uc3QgdHJpbW1lZFN0cmluZyA9ICh2OiB1bmtub3duKTogc3RyaW5nIHwgdW5kZWZpbmVkID0+CiAgdHlwZW9mIHYgPT09ICdzdHJpbmcnICYmIHYudHJpbSgpICE9PSAnJyA/IHYudHJpbSgpIDogdW5kZWZpbmVkOwoKLyoqIENvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbiBoZWFkZXIgdmFsdWU7IHVuZGVmaW5lZCB3aGVuIG5vdGhpbmcgdG8gYXR0cmlidXRlLiAqLwpleHBvcnQgY29uc3QgYXR0cmlidXRpb25IZWFkZXJWYWx1ZSA9ICgKICBjb25maWc6IEFueXJheVBsdWdpbkNvbmZpZwopOiBzdHJpbmcgfCB1bmRlZmluZWQgPT4gewogIGNvbnN0IHVzZXIgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy51c2VyKTsKICBjb25zdCB0ZWFtID0gdHJpbW1lZFN0cmluZyhjb25maWcudGVhbSk7CiAgaWYgKCF1c2VyICYmICF0ZWFtKSByZXR1cm4gdW5kZWZpbmVkOwogIHJldHVybiBKU09OLnN0cmluZ2lmeSh7CiAgICAuLi4odXNlciA/IHsgdXNlciB9IDoge30pLAogICAgLi4uKHRlYW0gPyB7IHRlYW0gfSA6IHt9KSwKICAgIHRvb2w6ICdvcGVuY2xhdycsCiAgfSk7Cn07CgovKiogQnVpbGQgdGhlIHByb3ZpZGVyIGVudHJ5LiBUaHJvd3Mgb24gYSBtaXNzaW5nIGdhdGV3YXlVcmwg4oCUIHRoZSBwbHVnaW4gaXMKICogIG1pc2NvbmZpZ3VyZWQgYW5kIGEgaGFsZi1jb25maWd1cmVkIHByb3ZpZGVyIHdvdWxkIHJvdXRlIG5vd2hlcmUuICovCmV4cG9ydCBjb25zdCBidWlsZEFueXJheVByb3ZpZGVyID0gKAogIGNvbmZpZzogQW55cmF5UGx1Z2luQ29uZmlnLAogIGVudjogUmVjb3JkPHN0cmluZywgc3RyaW5nIHwgdW5kZWZpbmVkPiA9IHByb2Nlc3MuZW52Cik6IE1vZGVsUHJvdmlkZXJDb25maWcgPT4gewogIGNvbnN0IGdhdGV3YXlVcmwgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy5nYXRld2F5VXJsKTsKICBpZiAoIWdhdGV3YXlVcmwpIHsKICAgIHRocm93IG5ldyBFcnJvcigKICAgICAgJ2FueXJheSBwbHVnaW46IHBsdWdpbnMuZW50cmllcy5hbnlyYXkuY29uZmlnLmdhdGV3YXlVcmwgaXMgcmVxdWlyZWQnCiAgICApOwogIH0KICBjb25zdCBhcGlLZXkgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy5hcGlLZXkpID8/IGVudltLRVlfRU5WXTsKICBjb25zdCBhdHRyaWJ1dGlvbiA9IGF0dHJpYnV0aW9uSGVhZGVyVmFsdWUoY29uZmlnKTsKICByZXR1cm4gewogICAgLy8gQmFyZSBvcmlnaW46IHRoZSBhbnRocm9waWMtbWVzc2FnZXMgdHJhbnNwb3J0IGFwcGVuZHMgL3YxL21lc3NhZ2VzLgogICAgYmFzZVVybDogZ2F0ZXdheVVybC5yZXBsYWNlKC9cLyskLywgJycpLAogICAgYXBpOiAnYW50aHJvcGljLW1lc3NhZ2VzJywKICAgIC4uLihhcGlLZXkgPyB7IGFwaUtleSB9IDoge30pLAogICAgaGVhZGVyczogewogICAgICAnYW50aHJvcGljLWJldGEnOiBBTlRIUk9QSUNfQkVUQSwKICAgICAgLi4uKGFwaUtleSA/IHsgJ3gtYW55cmF5LWFwaS1rZXknOiBhcGlLZXkgfSA6IHt9KSwKICAgICAgLi4uKGF0dHJpYnV0aW9uID8geyAneC1hbnlyYXktbWV0YWRhdGEnOiBhdHRyaWJ1dGlvbiB9IDoge30pLAogICAgfSwKICAgIG1vZGVsczogTU9ERUxTLAogIH07Cn07Cg=="},{path:"src/sessionIdentity.ts",contentBase64:"LyoqCiAqIFBlci1zZXNzaW9uIGlkZW50aXR5IGZvciB0aGUgQW55cmF5IGdhdGV3YXksIGluamVjdGVkIGludG8gdGhlIEFudGhyb3BpYwogKiBNZXNzYWdlcyBib2R5IGFzIGBtZXRhZGF0YS51c2VyX2lkYC4KICoKICogVGhlIGdhdGV3YXkgZGVyaXZlcyBpdHMgb3B0aW1pemVyIHNlc3Npb24gZnJvbSBhIGBfc2Vzc2lvbl88dXVpZD5gIHN1ZmZpeCBvbgogKiBgbWV0YWRhdGEudXNlcl9pZGAgKHRoZSBDbGF1ZGUgQ29kZSBjb252ZW50aW9uOyBnYXRld2F5CiAqIGBjbGllbnRTZXNzaW9uLnRzI21ldGFkYXRhU2Vzc2lvblV1aWRgKS4gV2l0aG91dCBpdCwgT3BlbkNsYXcgdHJhZmZpYyBmYWxscwogKiB0byBhIGNvbnZlcnNhdGlvbi1hbmNob3IgZmluZ2VycHJpbnQsIGFuZCBjb25jdXJyZW50IGNvbnZlcnNhdGlvbnMgdGhhdCBvcGVuCiAqIGlkZW50aWNhbGx5IHNoYXJlIG9uZSBzZXNzaW9uIOKAlCBvbmUgb3B0aW1pemVyIGZhaWwtb3BlbiB0aGVuIHBhdXNlcwogKiBvcHRpbWl6YXRpb24gZm9yIGFsbCBvZiB0aGVtICh0aGUgY29vbG9mZi1hbXBsaWZpY2F0aW9uIGZhaWx1cmUgbW9kZSkuCiAqCiAqIE9wZW5DbGF3J3Mgc3RyZWFtIGxheWVyIGhhbmRzIHVzIGFuIG9wYXF1ZSBgc2Vzc2lvbklkYCBwZXIgY2FsbC4gV2hlbiBpdCBpcwogKiBhbHJlYWR5IGEgVVVJRCBpdCBpcyB1c2VkIGFzLWlzOyBhbnl0aGluZyBlbHNlIGlzIGZvbGRlZCBpbnRvIGEgc3RhYmxlCiAqIFVVSUQtc2hhcGVkIHZhbHVlIHZpYSBTSEEtMjU2IHNvIHRoZSBzYW1lIHNlc3Npb24gYWx3YXlzIG1hcHMgdG8gdGhlIHNhbWUKICogaWQuIFRoZSB2YWx1ZSBpcyBhbiBvcGFxdWUgaWRlbnRpZmllciBlaXRoZXIgd2F5IOKAlCBubyBjb250ZW50LCBubyB1c2VyIGRhdGEuCiAqLwoKaW1wb3J0IHsgY3JlYXRlSGFzaCB9IGZyb20gJ25vZGU6Y3J5cHRvJzsKCmNvbnN0IFVVSURfUkUgPQogIC9eWzAtOWEtZl17OH0tWzAtOWEtZl17NH0tWzAtOWEtZl17NH0tWzAtOWEtZl17NH0tWzAtOWEtZl17MTJ9JC9pOwoKLyoqIFByZWZpeCBtYXJraW5nIGdhdGV3YXktdmlzaWJsZSB1c2VyX2lkcyBhcyBvdXJzIChjb250ZW50LWZyZWUpLiAqLwpjb25zdCBVU0VSX0lEX1BSRUZJWCA9ICdvcGVuY2xhdyc7CgovKiogQSBzdGFibGUgVVVJRC1zaGFwZWQgdmFsdWUgZm9yIGFueSBvcGFxdWUgc2Vzc2lvbiBrZXkuICovCmV4cG9ydCBjb25zdCBzZXNzaW9uVXVpZEZvciA9IChzZXNzaW9uSWQ6IHN0cmluZyk6IHN0cmluZyA9PiB7CiAgaWYgKFVVSURfUkUudGVzdChzZXNzaW9uSWQpKSByZXR1cm4gc2Vzc2lvbklkLnRvTG93ZXJDYXNlKCk7CiAgY29uc3QgaGV4ID0gY3JlYXRlSGFzaCgnc2hhMjU2JykudXBkYXRlKHNlc3Npb25JZCwgJ3V0ZjgnKS5kaWdlc3QoJ2hleCcpOwogIHJldHVybiBbCiAgICBoZXguc2xpY2UoMCwgOCksCiAgICBoZXguc2xpY2UoOCwgMTIpLAogICAgaGV4LnNsaWNlKDEyLCAxNiksCiAgICBoZXguc2xpY2UoMTYsIDIwKSwKICAgIGhleC5zbGljZSgyMCwgMzIpLAogIF0uam9pbignLScpOwp9OwoKLyoqIFRoZSBgbWV0YWRhdGEudXNlcl9pZGAgdmFsdWUgdGhlIGdhdGV3YXkncyBzZXNzaW9uIGV4dHJhY3RvciByZWNvZ25pemVzLiAqLwpleHBvcnQgY29uc3QgYW55cmF5VXNlcklkRm9yID0gKHNlc3Npb25JZDogc3RyaW5nKTogc3RyaW5nID0+CiAgYCR7VVNFUl9JRF9QUkVGSVh9X3Nlc3Npb25fJHtzZXNzaW9uVXVpZEZvcihzZXNzaW9uSWQpfWA7CgovKioKICogUGF0Y2ggYW4gb3V0Ym91bmQgQW50aHJvcGljIE1lc3NhZ2VzIHBheWxvYWQgaW4gcGxhY2Ugd2l0aCB0aGUgc2Vzc2lvbgogKiBpZGVudGl0eS4gRXhpc3RpbmcgYG1ldGFkYXRhLnVzZXJfaWRgIHZhbHVlcyBhcmUgbmV2ZXIgb3ZlcndyaXR0ZW4gKGEgdmFsdWUKICogcHJlc2VudCBtZWFucyBzb21lb25lIHVwc3RyZWFtIOKAlCBjb25maWcsIGFub3RoZXIgcGx1Z2luIOKAlCBtYWRlIGEgY2hvaWNlKSwKICogYW5kIGEgbWFsZm9ybWVkIGBtZXRhZGF0YWAgc2hhcGUgaXMgbGVmdCB1bnRvdWNoZWQgcmF0aGVyIHRoYW4gcmVwYWlyZWQuCiAqLwpleHBvcnQgY29uc3QgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5ID0gKAogIHBheWxvYWQ6IFJlY29yZDxzdHJpbmcsIHVua25vd24+LAogIHNlc3Npb25JZDogc3RyaW5nIHwgdW5kZWZpbmVkCik6IHZvaWQgPT4gewogIGlmICghc2Vzc2lvbklkKSByZXR1cm47CiAgY29uc3QgbWV0YWRhdGEgPSBwYXlsb2FkLm1ldGFkYXRhOwogIGlmIChtZXRhZGF0YSA9PT0gdW5kZWZpbmVkKSB7CiAgICBwYXlsb2FkLm1ldGFkYXRhID0geyB1c2VyX2lkOiBhbnlyYXlVc2VySWRGb3Ioc2Vzc2lvbklkKSB9OwogICAgcmV0dXJuOwogIH0KICBpZiAodHlwZW9mIG1ldGFkYXRhICE9PSAnb2JqZWN0JyB8fCBtZXRhZGF0YSA9PT0gbnVsbCB8fCBBcnJheS5pc0FycmF5KG1ldGFkYXRhKSkKICAgIHJldHVybjsKICBjb25zdCByZWNvcmQgPSBtZXRhZGF0YSBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPjsKICBpZiAocmVjb3JkLnVzZXJfaWQgPT09IHVuZGVmaW5lZCkgewogICAgcmVjb3JkLnVzZXJfaWQgPSBhbnlyYXlVc2VySWRGb3Ioc2Vzc2lvbklkKTsKICB9Cn07Cg=="},{path:"src/streamWrapper.ts",contentBase64:"LyoqCiAqIFRoZSBwZXItY2FsbCBzZWFtOiB3cmFwcyB0aGUgYnVpbHQtaW4gYW50aHJvcGljLW1lc3NhZ2VzIHRyYW5zcG9ydCBzbyBldmVyeQogKiBvdXRib3VuZCBjYWxsIHRvIHRoZSBBbnlyYXkgZ2F0ZXdheSBjYXJyaWVzIHBlci1zZXNzaW9uIGlkZW50aXR5LCBhbmQgcHJvbXB0CiAqIGNhY2hpbmcgaXMgbmV2ZXIgc2lsZW50bHkgb2ZmLgogKgogKiBEZWxlZ2F0aW9uIGNvbnRyYWN0IChtaXJyb3JzIE9wZW5DbGF3J3Mgb3duIGJ1bmRsZWQgd3JhcHBlcnMpOiByZXR1cm4gYQogKiBTdHJlYW1GbiB0aGF0IGNoYWlucyBhbnkgY2FsbGVyLXN1cHBsaWVkIGBvblBheWxvYWRgIGFmdGVyIG91cnMsIGFuZCBhbHdheXMKICogaGFuZCBvZmYgdG8gYGN0eC5zdHJlYW1GbmAg4oCUIHRoaXMgd3JhcHBlciBvbmx5IGRlY29yYXRlcywgaXQgbmV2ZXIKICogdHJhbnNwb3J0cy4gR3VhcmRlZCB0byBvdXIgcHJvdmlkZXIgKyBhcGkgc28gYSBtaXMtcmVnaXN0cmF0aW9uIGNhbiBuZXZlcgogKiB0b3VjaCBzb21lb25lIGVsc2UncyB0cmFmZmljLgogKi8KCmltcG9ydCB0eXBlIHsKICBQcm92aWRlcldyYXBTdHJlYW1GbkNvbnRleHQsCiAgU3RyZWFtRm4sCiAgU3RyZWFtT3B0aW9ucywKfSBmcm9tICdvcGVuY2xhdy9wbHVnaW4tc2RrL3Byb3ZpZGVyLXR5cGVzJzsKaW1wb3J0IHsgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5IH0gZnJvbSAnLi9zZXNzaW9uSWRlbnRpdHkuanMnOwoKZXhwb3J0IGNvbnN0IEFOWVJBWV9QUk9WSURFUl9JRCA9ICdhbnlyYXknOwoKLyoqIENhY2hlIHJldGVudGlvbiBkZWZhdWx0IGZvciB0aGUgZ2F0ZXdheSBob3N0OiBPcGVuQ2xhdyBhdXRvLXNlZWRzIHByb21wdAogKiAgY2FjaGluZyBvbmx5IG9uIGFwaS5hbnRocm9waWMuY29tL1ZlcnRleCwgc28gdW5zZXQgaGVyZSBtZWFucyAibm8KICogIGNhY2hlX2NvbnRyb2wgYXQgYWxsIiDigJQgYSBjb2xkIHByb3ZpZGVyIGNhY2hlIG9uIGV2ZXJ5IHdhcm0gdHVybi4gKi8KY29uc3QgQ0FDSEVfUkVURU5USU9OX0RFRkFVTFQgPSAnc2hvcnQnOwoKZXhwb3J0IGNvbnN0IGNyZWF0ZUFueXJheVN0cmVhbVdyYXBwZXIgPSAoCiAgY3R4OiBQcm92aWRlcldyYXBTdHJlYW1GbkNvbnRleHQKKTogU3RyZWFtRm4gfCB1bmRlZmluZWQgPT4gewogIGNvbnN0IGlubmVyID0gY3R4LnN0cmVhbUZuOwogIGlmICghaW5uZXIpIHJldHVybiB1bmRlZmluZWQ7CiAgaWYgKGN0eC5wcm92aWRlciAhPT0gQU5ZUkFZX1BST1ZJREVSX0lEKSByZXR1cm4gdW5kZWZpbmVkOwoKICBjb25zdCB3cmFwcGVkOiBTdHJlYW1GbiA9IChtb2RlbCwgY29udGV4dCwgb3B0aW9ucykgPT4gewogICAgaWYgKG1vZGVsLnByb3ZpZGVyICE9PSBBTllSQVlfUFJPVklERVJfSUQgfHwgbW9kZWwuYXBpICE9PSAnYW50aHJvcGljLW1lc3NhZ2VzJykgewogICAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdGlvbnMpOwogICAgfQogICAgY29uc3Qgb3B0czogU3RyZWFtT3B0aW9ucyA9IHsgLi4uKG9wdGlvbnMgPz8ge30pIH07CiAgICBpZiAob3B0cy5jYWNoZVJldGVudGlvbiA9PT0gdW5kZWZpbmVkKSB7CiAgICAgIG9wdHMuY2FjaGVSZXRlbnRpb24gPSBDQUNIRV9SRVRFTlRJT05fREVGQVVMVDsKICAgIH0KICAgIC8vIExpdmUtY29udGFpbmVyIGZhY3QgKDIwMjYuNy4xKTogdGhlIHRyYW5zcG9ydCBkcm9wcyB0aGUgY2F0YWxvZydzCiAgICAvLyBwcm92aWRlci1sZXZlbCBgaGVhZGVyc2AgZm9yIHBsdWdpbiBwcm92aWRlcnMsIHNvIHRoZSBjb250ZW50LWZyZWUKICAgIC8vIGF0dHJpYnV0aW9uIHJpZGVzIHRoZSBwZXItY2FsbCBoZWFkZXIgbGV2ZXIgaW5zdGVhZC4gVGhlIEFueXJheSBnYXRld2F5CiAgICAvLyBuZWVkcyBubyBhbnRocm9waWMtYmV0YSBmcm9tIHVzIChpdHMgb3JnIGxhbmUgbWludHMgcHJvdmlkZXIgaGVhZGVycwogICAgLy8gc2VydmVyLXNpZGUpLCBhbmQgYXV0aCBhbHJlYWR5IHJpZGVzIHgtYXBpLWtleTsgdGhpcyBpcyBkaWFnbm9zdGljcwogICAgLy8gYXR0cmlidXRpb24gb25seS4gRXhpc3RpbmcgdmFsdWVzIGFyZSBuZXZlciBvdmVyd3JpdHRlbi4KICAgIGNvbnN0IGhlYWRlcnMgPSB7IC4uLihvcHRzLmhlYWRlcnMgPz8ge30pIH07CiAgICBpZiAoaGVhZGVyc1sneC1hbnlyYXktbWV0YWRhdGEnXSA9PT0gdW5kZWZpbmVkKSB7CiAgICAgIGhlYWRlcnNbJ3gtYW55cmF5LW1ldGFkYXRhJ10gPSAneyJ0b29sIjoib3BlbmNsYXcifSc7CiAgICB9CiAgICBpZiAoCiAgICAgIGhlYWRlcnNbJ3gtYW55cmF5LWFwaS1rZXknXSA9PT0gdW5kZWZpbmVkICYmCiAgICAgIHR5cGVvZiBvcHRzLmFwaUtleSA9PT0gJ3N0cmluZycgJiYKICAgICAgb3B0cy5hcGlLZXkuc3RhcnRzV2l0aCgnYXJrXycpCiAgICApIHsKICAgICAgaGVhZGVyc1sneC1hbnlyYXktYXBpLWtleSddID0gb3B0cy5hcGlLZXk7CiAgICB9CiAgICBvcHRzLmhlYWRlcnMgPSBoZWFkZXJzOwogICAgY29uc3Qgc2Vzc2lvbklkID0KICAgICAgdHlwZW9mIG9wdHMuc2Vzc2lvbklkID09PSAnc3RyaW5nJyA/IG9wdHMuc2Vzc2lvbklkIDogdW5kZWZpbmVkOwogICAgY29uc3QgY2FsbGVyT25QYXlsb2FkID0gb3B0cy5vblBheWxvYWQ7CiAgICBvcHRzLm9uUGF5bG9hZCA9IGFzeW5jIChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpID0+IHsKICAgICAgaWYgKHBheWxvYWQgJiYgdHlwZW9mIHBheWxvYWQgPT09ICdvYmplY3QnICYmICFBcnJheS5pc0FycmF5KHBheWxvYWQpKSB7CiAgICAgICAgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5KAogICAgICAgICAgcGF5bG9hZCBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPiwKICAgICAgICAgIHNlc3Npb25JZAogICAgICAgICk7CiAgICAgIH0KICAgICAgcmV0dXJuIGNhbGxlck9uUGF5bG9hZCA/IGNhbGxlck9uUGF5bG9hZChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpIDogcGF5bG9hZDsKICAgIH07CiAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdHMpOwogIH07CiAgcmV0dXJuIHdyYXBwZWQ7Cn07Cg=="}];var Uf=".anyray-source-sha",rn=()=>Qs(ND(),".anyray","openclaw-plugin"),kC=async(e=rn())=>{try{if((await bC(Qs(e,Uf),"utf8")).trim()===Ff)return"current"}catch{}for(let t of wC){let n=Qs(e,t.path);await MD($D(n),{recursive:!0,mode:448}),await pe(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await pe(Qs(e,Uf),`${Ff}
195
+ `),"installed"},Ol=async(e=rn())=>{try{await bC(Qs(e,Uf),"utf8")}catch{return!1}return await FD(e,{recursive:!0,force:!0}),!0};var Kf="x-anyray-metadata",ia="x-anyray-api-key",Gf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],oo="Authorization",ao="anthropic-beta",_l="interleaved-thinking-2025-05-14",Pl=["anthropic","openai"],SC="short",Vf="anthropic-messages",Yf=32e3,Tl="anthropic/claude-sonnet-4-5",Zf=["anthropic/claude-haiku-4-5"],Xf="anyray/claude-sonnet-4-5",Jf=["anyray/claude-haiku-4-5"],GD=[Tl,Xf],jD=[Zf,Jf],ze="anyray",vr="ANYRAY_API_KEY",ti="openclaw",EC=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Rl(AC(),".openclaw"),ro=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Rl(EC(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),CC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ei=async e=>{let t=await O(e),n=t?await vC(e,"utf8"):`{}
196
+ `,r=n.trim()?yn(n):{};if(!N(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},xC=(e,t,n=[])=>{if(N(e)&&N(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...xC(e[o],t[o],[...n,o])):r.push({path:[...n,o],value:t[o]}):r.push({path:[...n,o],value:void 0});return r}return JSON.stringify(e)===JSON.stringify(t)?[]:[{path:n,value:t}]},Bf=async(e,t,n,r)=>{let o=xC(t.data,n);if(o.length===0)return!1;if(r&&!await O(`${e}.anyray-bak`))if(t.existed)try{await WD(e,`${e}.anyray-bak`,UD.COPYFILE_EXCL),await BD(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await pe(`${e}.anyray-bak`,`{}
197
197
  `);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
198
198
  `)?`\r
199
199
  `:`
200
- `},s=t.raw;for(let i of o)s=MD(s,FD(s,i.path,i.value,{formattingOptions:a}));return await pe(e,s.endsWith(`
200
+ `},s=t.raw;for(let i of o)s=HD(s,KD(s,i.path,i.value,{formattingOptions:a}));return await pe(e,s.endsWith(`
201
201
  `)?s:`${s}
202
- `),!0},Uf=async e=>{try{let t=yr(await AC(`${e}.anyray-bak`,"utf8"));return N(t)?t:void 0}catch{return}},Kf=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},WD=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=de({...t.metadata,tool:Qs}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!N(l.models)&&d.push("models");let u=N(l.models)?{...l.models}:{};if("providers"in u&&!N(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=N(u.providers)?{...u.providers}:{},p=!1;if(n){let v=N(l.plugins)?{...l.plugins}:{},E=N(v.load)?{...v.load}:{},I=N(v.entries)?{...v.entries}:{},C=N(I[ze])?{...I[ze]}:{},x=N(C.config)?{...C.config}:{};if("plugins"in l&&!N(l.plugins)||"load"in v&&!N(v.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in v&&!N(v.entries)||ze in I&&!N(I[ze])||"config"in C&&!N(C.config)||"env"in l&&!N(l.env))d.push("plugins");else{let T=Array.isArray(E.paths)?[...E.paths]:[];T.includes(n)||T.push(n),E.paths=T,v.load=E,C.enabled=!0,x.gatewayUrl=t.anthropicBaseUrl,x.apiKey=r;let $=t.metadata.user,Y=t.metadata.team;$&&(x.user=$),Y&&(x.team=Y),C.config=x,I[ze]=C,v.entries=I,l.plugins=v;let Z=N(l.env)?{...l.env}:{};Z[Ar]=r,l.env=Z,p=!0}}let h=Ol.filter(v=>v!=="openai"||!X(t,"openai"));for(let v of h){if(v in f&&!N(f[v])){d.push(`models.providers.${v}`);continue}let E=N(f[v])?{...f[v]}:{};if("headers"in E&&!N(E.headers)){i.push(v);continue}let I=N(E.headers)?{...E.headers}:{};if(E.baseUrl=v==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,v==="anthropic"&&(E.api=Gf,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=jf)),v==="anthropic"&&a)E.apiKey=a.key,I[ao]=`Bearer ${a.key}`,I["x-anyray-provider"]="anthropic",I["x-anyray-auth-mode"]="passthrough",I["x-anyray-custom-host"]=a.url;else{E.apiKey=r,"x-anyray-custom-host"in I&&delete I[ao];for(let C of Hf)delete I[C]}I[sa]=r,o&&(I[Wf]=o),v==="anthropic"&&(so in I?c=I[so]!==Rl:I[so]=Rl),E.headers=I,f[v]=E,s.push(v)}u.providers=f,l.models=u;let m=!1,w=!1,g=!1,y,b=[],A="agents"in l&&!N(l.agents)||N(l.agents)&&"defaults"in l.agents&&!N(l.agents.defaults)||N(l.agents)&&N(l.agents.defaults)&&("params"in l.agents.defaults&&!N(l.agents.defaults.params)||"model"in l.agents.defaults&&!N(l.agents.defaults.model));if(A&&d.push("agents.defaults"),s.includes("anthropic")&&!A){let v=N(l.agents)?{...l.agents}:{},E=N(v.defaults)?{...v.defaults}:{},I=N(E.params)?{...E.params}:{};"cacheRetention"in I||(I.cacheRetention=vC,m=!0,E.params=I);let C=N(E.model)?{...E.model}:{},x=p?[...s,ze]:s,T=$=>typeof $=="string"&&x.some(Y=>$.startsWith(`${Y}/`));typeof C.primary!="string"||C.primary.trim()===""?(C.primary=p?Yf:_l,w=!0,E.model=C,"fallbacks"in C||(C.fallbacks=p?[...Zf]:[...Vf],g=!0)):T(C.primary)||(y=C.primary),b=(Array.isArray(C.fallbacks)?C.fallbacks:[]).filter($=>typeof $=="string"&&!T($)),(m||w)&&(v.defaults=E,l.agents=v)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:g,unroutedPrimary:y,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},HD=["baseUrl","apiKey","api","maxTokens"],Bf=(e,t,n=Ol,r)=>{let o={...e},a=!("models"in o)||N(o.models)&&(!("providers"in o.models)||N(o.models.providers)),s=N(o.models)?{...o.models}:{},i=N(s.providers)?{...s.providers}:{},c=Kf(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!N(f))continue;let p={...f},h=N(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof h[sa]=="string"||typeof h[Wf]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Hf.some(v=>v in h)))continue;let w=N(c[u])?c[u]:{},g=N(w.headers)?w.headers:{},y="x-anyray-custom-host"in h,b=v=>v==="api"?p.api===Gf:v==="maxTokens"?p.maxTokens===jf:v==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let v of HD)b(v)&&(v in w?p[v]!==w[v]&&(p[v]=w[v],l=!0):v in p&&(delete p[v],l=!0));let A=[sa,Wf,...Hf,..."x-anyray-custom-host"in h?[ao]:[]];h[so]===Rl&&A.push(so);for(let v of A)v in g?h[v]!==g[v]&&(h[v]=g[v],l=!0):v in h&&(delete h[v],l=!0);ao in g&&!(ao in h)&&(h[ao]=g[ao],l=!0),Object.keys(h).length===0?delete p.headers:p.headers=h,Object.keys(p).length===0?delete i[u]:i[u]=p}if(a&&(Object.keys(i).length===0?delete s.providers:s.providers=i,Object.keys(s).length===0?delete o.models:o.models=s),r&&n.includes("anthropic")){let u=N(o.plugins)?{...o.plugins}:{},f=N(u.load)?{...u.load}:{},p=N(u.entries)?{...u.entries}:{};if((!("plugins"in o)||N(o.plugins))&&(!("load"in u)||N(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||N(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let w=f.paths.filter(g=>g!==r);w.length===0?delete f.paths:f.paths=w,l=!0}let m=p[ze];if(N(m)){let w=N(m.config)?m.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let y=N(t?.plugins)?t.plugins:{},b=N(y.entries)?y.entries:{};ze in b?JSON.stringify(p[ze])!==JSON.stringify(b[ze])&&(p[ze]=b[ze],l=!0):(delete p[ze],l=!0)}}if(Object.keys(f).length===0?delete u.load:u.load=f,Object.keys(p).length===0?delete u.entries:u.entries=p,Object.keys(u).length===0?delete o.plugins:o.plugins=u,N(o.env)){let w={...o.env},g=w[Ar];if(typeof g=="string"&&g.startsWith("ark_")){let y=N(t?.env)?t.env:{};Ar in y?w[Ar]!==y[Ar]&&(w[Ar]=y[Ar],l=!0):(delete w[Ar],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||N(o.agents)&&(!("defaults"in o.agents)||N(o.agents.defaults)&&(!("params"in o.agents.defaults)||N(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||N(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=N(o.agents)?{...o.agents}:{},f=N(u.defaults)?{...u.defaults}:{},p=N(f.params)?{...f.params}:{},h=N(t.agents)?t.agents:{},m=N(h.defaults)?h.defaults:{},w=N(m.params)?m.params:{};p.cacheRetention===vC&&("cacheRetention"in w?p.cacheRetention!==w.cacheRetention&&(p.cacheRetention=w.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let g=N(f.model)?{...f.model}:{},y=N(m.model)?m.model:{};UD.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),BD.some(b=>JSON.stringify(g.fallbacks)===JSON.stringify(b))&&("fallbacks"in y?JSON.stringify(g.fallbacks)!==JSON.stringify(y.fallbacks)&&(g.fallbacks=y.fallbacks,l=!0):(delete g.fallbacks,l=!0)),Object.keys(g).length===0?delete f.model:f.model=g,Object.keys(p).length===0?delete f.params:f.params=p,Object.keys(f).length===0?delete u.defaults:u.defaults=f,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},IC={id:Qs,title:"OpenClaw",automatic:!0,async detect(){let e=await R(oo())||await R(SC());return{installed:e,detail:e?oo():`no ${xl(CC(),".openclaw")} state dir`}},async apply(e,t){let n=oo();if(!e.byoUpstream&&X(e,"anthropic")){let E=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${Qs}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],I;try{I=await qs(n)}catch{return{status:"held",messages:E}}let{next:C,removed:x}=Bf(I.data,await Uf(n),Ol,rn());return x?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...E]}:(await Ff(n,I,C,!1),await ae(n),await Il(),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...E]}):(t.dryRun||await Il(),{status:"held",messages:E})}let r=rn(),o=!1;if(!t.dryRun)try{await bC(r)}catch{r=void 0,o=!0}let a;try{a=await qs(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Gf}", "maxTokens": ${jf}, "apiKey": "<your personal ark_ key>", "headers": { "${sa}": "<your personal ark_ key>", "${so}": "${Rl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${sa}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${_l}") if none is set,`,'and under "agents.defaults.params" set "cacheRetention": "short" \u2014',"custom Anthropic-compatible hosts get no prompt-cache auto-seed, and","an unset value would leave the provider cache permanently cold.","Then run `openclaw config validate`."]}}let{next:s,routed:i,cacheRetentionSeeded:c,betaPreserved:l,headerConflicts:d,primarySeeded:u,fallbacksSeeded:f,unroutedPrimary:p,unroutedFallbacks:h,structureConflicts:m,pluginConfigured:w}=WD(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=Bf(g,await Uf(n),["openai"]);E.removed&&(g=E.next,y=!0)}let b=[i.includes("openai")?`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; models.providers.openai baseUrl = ${e.openaiBaseUrl}`:`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; openai left on its native ChatGPT sign-in`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${de({...e.metadata,tool:Qs})??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...c?['Seeded agents.defaults.params.cacheRetention = "short": OpenClaw',"skips its prompt-cache auto-seed on custom hosts, and an unset","value would leave the provider cache permanently cold."]:["Kept your existing cacheRetention setting."],...l?[`Kept your existing ${so} header value (OpenClaw suppresses its implicit beta headers off-host; yours replaces our default restore).`]:[],...d.length>0?[`Could not add headers on models.providers.${d.join(", ")}: the existing "headers" value is not an object. Fix it manually; nothing there was replaced.`]:[],...u?[`Seeded agents.defaults.model.primary = ${w?Yf:_l} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?Zf:Vf).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...p!==void 0?[`Your primary model (${p}) resolves to a provider Connect does not route, so those requests bypass the gateway. Pick an anthropic/* or openai/* model to route them; your setting was kept.`]:[],...h.length>0?[`Fallback model(s) ${h.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...y?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...w?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${rn()}) and registered it under plugins.entries.${ze}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${rn()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...m.length>0?[`Left ${m.join(", ")} untouched: the existing value has the wrong shape (array or null where an object belongs), and OpenClaw's strict schema will refuse it as-is. Fix the shape and re-run.`]:[],"OpenClaw hot-reloads model config; run `openclaw config validate` to confirm the merged config passes its strict schema."],A=d.length>0||m.length>0?"manual":"configured";if(t.dryRun)return{status:A,messages:b};let v=await Ff(n,a,g,!0);return{status:A,messages:b,changedFiles:v?[n]:[]}},async pointsAt(e){try{let{data:t}=await qs(oo());for(let a of Object.values(Kf(t)))if(N(a)&&kC(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[ze];if(N(o)&&N(o.config)&&kC(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[oo(),xl(rn(),".anyray-source-sha")]},async routingExpected(e){return e.includes(Qs)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await qs(oo());for(let a of Object.values(Kf(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[sa]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[ze];if(N(o)&&N(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=oo();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await qs(t)}catch{return{status:"manual",messages:[`Couldn't parse ${t} \u2014 if you added Anyray settings there by hand, remove baseUrl/apiKey and the x-anyray-* headers from models.providers.anthropic and models.providers.openai yourself.`]}}let{next:r,removed:o}=Bf(n.data,await Uf(t),Ol,rn()),a=await Il();return o?(await Ff(t,n,r,!1),await ae(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${rn()}`]:[]],changedFiles:[t]}):(await ae(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${rn()}`]:[]]})}};import{execFile as PM}from"node:child_process";import{readFile as LM}from"node:fs/promises";import{homedir as wi,platform as Sr}from"node:os";import{join as vn}from"node:path";import{isDeepStrictEqual as Dh,promisify as DM}from"node:util";var ei=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},Tl=(e,t)=>{let n=ei(e),r=ei(t);if(!(!n||!r)){for(let o=0;o<Math.max(n.length,r.length);o+=1){let a=(n[o]??0)-(r[o]??0);if(a!==0)return a}return 0}};import{randomUUID as J$}from"node:crypto";import{promises as FA}from"node:fs";import{platform as X$,tmpdir as z$}from"node:os";import{join as Jl}from"node:path";import{execFile as KD}from"node:child_process";import{promises as ti}from"node:fs";import{homedir as GD,platform as jD}from"node:os";import{delimiter as VD,join as Pl}from"node:path";import{promisify as YD}from"node:util";var ZD=YD(KD),JD=15*6e4,XD=64*1024*1024,zD=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],xC=async(e={})=>{let t=(e.home??GD)(),n=e.env??process.env,r=zD(e.runtimePlatform??jD()),o=[Pl(t,".local","bin"),Pl(t,".claude","local"),...(n.PATH??"").split(VD).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Pl(a,`claude${s}`);try{return await ti.access(i),i}catch{}}return null},qD=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let{uuid:r,name:o,dirName:a}=n;typeof r!="string"||typeof a!="string"||a.length===0||a.includes("/")||a.includes("\\")||a==="."||a===".."||t.push({uuid:r,name:typeof o=="string"&&o.length>0?o:"Project",dirName:a})}return t},QD=async e=>{let t=Pl(e,"projects"),n;try{n=(await ti.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return[]}let r=[];for(let o of n){let a=o.slice(-36);if(!nN.test(a))continue;let s=o.slice(0,-37).split("-").filter(i=>i.length>0).map(i=>i[0].toUpperCase()+i.slice(1)).join(" ");r.push({uuid:a,name:s.length>0?s:"Project",dirName:o})}return r},eN=e=>{if(!e||!e.startsWith("{"))return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.sessionIds,o=n.jsonlPaths;if(!Array.isArray(r)||!Array.isArray(o))return null;let a=Array.isArray(n.titles)?n.titles:[],s=Array.isArray(n.createdAts)?n.createdAts:[],i=Array.isArray(n.updatedAts)?n.updatedAts:[],c=d=>typeof d=="number"&&Number.isFinite(d)?d:void 0,l=[];for(let d=0;d<r.length;d+=1){let u=r[d],f=o[d];if(typeof u!="string"||typeof f!="string"||u.length===0||f.length===0)continue;let p=a[d];l.push({sessionId:u,transcriptPath:f,title:typeof p=="string"&&p.length>0?p:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:qD(n.projectList)}},tN=async e=>{let t,n;try{let r=await ti.readFile(e,"utf8");for(let o of r.split(`
203
- `)){if(o.length===0)continue;let a;try{a=JSON.parse(o).timestamp}catch{continue}if(typeof a!="string")continue;let s=Date.parse(a);Number.isFinite(s)&&(t??=s,n=s)}}catch{return{}}return{createdAt:t,lastActivityAt:n??t}},nN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,rN=/\.(?:cmd|bat)$/i,oN=(e,t)=>rN.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},RC=async(e,t={})=>{let n=t.exec??ZD,r=["import-conversations",e.exportPath,"--cwd",e.workDir];if([e.binary,...r].some(d=>d.includes('"')))return{ok:!1,reason:"the export path contains an unsupported character"};await ti.mkdir(e.configDir,{recursive:!0,mode:448}),await ti.mkdir(e.workDir,{recursive:!0,mode:448});let o=oN(e.binary,r),a;try{a=(await n(o.file,o.args,{env:{...process.env,CLAUDE_IMPORT_CONVERSATIONS:"1",CLAUDE_CONFIG_DIR:e.configDir},timeout:JD,maxBuffer:XD,windowsVerbatimArguments:o.verbatim})).stdout}catch(d){let u=d.code;return{ok:!1,reason:typeof u=="number"?`the Claude Code importer exited with status ${u}`:"the Claude Code importer could not be run"}}let s=a.split(`
204
- `).filter(d=>d.trim().length>0),i=eN(s.at(-1));if(!i)return{ok:!1,reason:"the Claude Code importer produced no readable summary"};let c=await Promise.all(i.conversations.map(async d=>{if(d.createdAt!==void 0)return d;let u=await tN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await QD(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as aN}from"node:crypto";import{promises as Bn}from"node:fs";import{homedir as sN,platform as iN}from"node:os";import{join as Et}from"node:path";var OC=448,Wn="local_",cN="local-agent-mode-sessions",Jf="-3p",lN="cowork_account_settings.json",io=(e={})=>{let t=(e.home??sN)(),n=e.runtimePlatform??iN(),r=e.env??process.env;if(n==="darwin")return Et(t,"Library","Application Support",`Claude${Jf}`);if(n==="win32"){let o=r.LOCALAPPDATA??Et(t,"AppData","Local");return Et(o,`Claude${Jf}`)}return null},ni=(e={})=>{let t=io(e);return t?t.slice(0,-Jf.length):null},Xf=e=>{let t=e.replace(/[^a-zA-Z0-9]/g,"-");if(t.length<=200)return t;let n=0;for(let r=0;r<e.length;r+=1)n=Math.imul(n,31)+e.charCodeAt(r)|0;return`${t.slice(0,200)}-${Math.abs(n).toString(36)}`},Ll=async e=>{let t=Et(e,cN),n;try{n=(await Bn.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return{ok:!1,reason:"no-profile",found:[]}}let r=[];for(let o of n){let a;try{a=(await Bn.readdir(Et(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=Et(t,o,s);try{await Bn.access(Et(i,lN)),r.push(i)}catch{}}}return r.length===0?{ok:!1,reason:"no-account",found:[]}:r.length>1?{ok:!1,reason:"ambiguous",found:r}:{ok:!0,dir:r[0]}},zf=async e=>{try{let t=await Bn.readdir(e);return new Set(t.filter(n=>n.startsWith(Wn)&&n.endsWith(".json")).map(n=>n.slice(Wn.length,-5)))}catch{return new Set}},ia=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),dN=async(e,t)=>{let n=`${Wn}${t.sessionId}`,r=Et(e,n),o=Et(r,"outputs"),a=Et(r,".claude"),s=Et(a,"projects",Xf(o));await Bn.mkdir(o,{recursive:!0,mode:OC}),await Bn.mkdir(s,{recursive:!0,mode:OC});let i=Et(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${aN()}`;await Bn.copyFile(t.transcriptPath,c),await Bn.chmod(c,384),await Bn.rename(c,i);let l=t.createdAt??Date.now();await J(Et(e,`${n}.json`),{sessionId:n,cliSessionId:t.sessionId,processName:"claude-ai-import",cwd:o,hostLoopMode:!0,title:t.title,createdAt:l,lastActivityAt:t.lastActivityAt??l,isArchived:!1,userSelectedFolders:[],pendingNotifications:[]},{backup:!1})},_C=async(e,t)=>{let n=await zf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!ia(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await dN(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as ca}from"node:fs";import{homedir as uN}from"node:os";import{dirname as pN,join as ri}from"node:path";var fN=448,hN=["Documents","Claude","Projects"],mN="spaces.json",yN=(e={})=>ri((e.home??uN)(),...hN),gN=async e=>{try{let t=JSON.parse(await ca.readFile(e,"utf8"));if(!t||typeof t!="object")return{spaces:[],readable:!1};let n=t.spaces;return Array.isArray(n)?{spaces:n.filter(r=>!!r&&typeof r=="object"&&typeof r.id=="string"),readable:!0}:{spaces:[],readable:!1}}catch(t){return t.code==="ENOENT"?{spaces:[],readable:!0}:{spaces:[],readable:!1}}},wN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},qf=async e=>{try{return await ca.access(e),!0}catch{return!1}},bN=async(e,t,n)=>{let r=ri(t,wN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await qf(r)?o:r;return a===o&&await qf(o)?null:(await ca.mkdir(pN(a),{recursive:!0}),await ca.cp(e,a,{recursive:!0}),a)},kN=async e=>{try{let t=(await ca.readFile(ri(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},TC=async e=>{let t=yN({home:e.home}),n={imported:0,alreadyPresent:0,skippedCollision:0,failed:0,root:t},r=e.projects??[];if(r.length===0)return n;let o=ri(e.storageDir,mN),{spaces:a,readable:s}=await gN(o);if(!s)return n.failed=r.length,n;let i=new Set(a.map(l=>l.id)),c=[];for(let l of r){if(i.has(l.uuid)){n.alreadyPresent+=1;continue}let d=ri(e.stagedProjectsDir,l.dirName);try{if(!await qf(d)){n.failed+=1;continue}let u=await bN(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await kN(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...f?{instructions:f}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await ca.mkdir(e.storageDir,{recursive:!0,mode:fN}),await J(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as SN}from"node:crypto";import{execFile as EN,spawnSync as HC}from"node:child_process";import{constants as KC}from"node:fs";import{access as Ul,chmod as IN,mkdir as xN,readdir as RN,readFile as eh,rename as ON,rm as da,stat as GC,writeFile as _N}from"node:fs/promises";import{homedir as TN,platform as PN,userInfo as LN}from"node:os";import{basename as DN,dirname as jC,isAbsolute as ua,join as Bt,resolve as $C}from"node:path";import{isDeepStrictEqual as ai,promisify as NN}from"node:util";var oi="__anyray-claude-desktop-credential";var Dl=["Heads up: Claude Desktop's third-party mode uses its own app profile, so it opens signed out with empty conversation lists. Nothing is deleted and your Claude account is unchanged \u2014 sign back in with the account you already use.","Your Claude Code sessions and Cowork tasks come across on their own once this new profile has been signed in to and the app is fully quit \u2014 no second command.","Your claude.ai chats live on your Claude account rather than this machine, so those need your data export: `anyray-connect migrate --export <file.zip>`."],Nl=["Your Claude account conversations are reachable in the app again once it reopens.","Chats made while third-party mode was active stay in its separate profile and come back if you configure it again."],PC="Note: third-party mode runs in a separate app profile, so Claude Desktop starts with empty conversation lists while it is active. Nothing is lost \u2014 local sessions come across on their own once the profile is signed in to and Claude Desktop is fully quit (see any queued migration above), claude.ai chats need your data export via `anyray-connect migrate --export <file.zip>`, and `anyray-connect desktop disconnect` restores the first-party profile.";var $l=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],LC=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],CN=new Set(LC),AN=new Set(LC.map(e=>e.toLowerCase())),vN=new Set($l.map(e=>e.toLowerCase())),Ml=(e,t=!1)=>(t?AN:CN).has(t?e.toLowerCase():e),DC=(e,t=!1)=>t?vN.has(e.toLowerCase()):$l.some(n=>n===e),NC=["*"],co=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...NC]}),la=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var si=/^[a-f0-9-]{36}$/,VC="Anyray",th=4,li=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],di=["deploymentMode","awaitingSignIn"],YC=[...li,...di,"configLibrary","_meta.json"],kn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),lt=e=>structuredClone(e),ii=async e=>{try{return await Ul(e),!0}catch{return!1}},$N=async e=>{try{let t=await RN(jC(e)),n=DN(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},MN=async e=>{try{return await Ul(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":$N(e)}},on=(e={})=>{let t=(e.home??TN)(),n=(e.username??(()=>LN().username))(),r=Bt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Bt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Bt(r,"configLibrary"),meta:Bt(r,"configLibrary","_meta.json"),appConfig:Bt(r,"claude_desktop_config.json"),helper:Bt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Bt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Bl=()=>{let e=HC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},ZC=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],FN=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...ZC(t)]}},nh=(e="json")=>{let t=un(ZC(e)),n=$C(t.command),r=$C(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:le()&&(!o||r!==n)}},UN=e=>`'${e.replace(/'/g,`'"'"'`)}'`,rh=e=>[e.command,...e.args].map(UN).join(" "),BN=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ua(e.command))throw new Error("the credential helper executable is not absolute")},JC=(e,t)=>{BN(e);let n=Wl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!ua(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},XC=e=>(JC(e,"--json"),`#!/bin/sh
205
- exec ${rh(e)}
206
- `),WN=`#!/bin/sh
207
- # Anyray subscription pass-through credential helper v2 for Claude Desktop`,zC=e=>{JC(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),oi]};return["#!/bin/sh","# Anyray subscription pass-through credential helper v2 for Claude Desktop.","# The durable credential runtime reads and validates the Keychain JSON,","# combines it with Anyray headers, and writes one credential response.",`exec ${rh(t)}`,""].join(`
208
- `)},HN=e=>e.args.at(-1)==="--passthrough-headers"?zC(e):XC(e),Wl=e=>/[\\/](node|node\.exe)$/i.test(e),oh=e=>{let t=[],n=0;for(;n<e.length;){if(e[n]!=="'")return;n++;let r="";for(;n<e.length;){let o=e.indexOf("'",n);if(o<0)return;if(r+=e.slice(n,o),e.startsWith(`'"'"'`,o)){r+="'",n=o+5;continue}n=o+1;break}if(t.push(r),n===e.length)return t;if(e[n]!==" "||n+1===e.length)return;n++}},KN=e=>{let t=`#!/bin/sh
202
+ `),!0},Wf=async e=>{try{let t=yn(await vC(`${e}.anyray-bak`,"utf8"));return N(t)?t:void 0}catch{return}},jf=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},VD=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=de({...t.metadata,tool:ti}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!N(l.models)&&d.push("models");let u=N(l.models)?{...l.models}:{};if("providers"in u&&!N(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=N(u.providers)?{...u.providers}:{},p=!1;if(n){let v=N(l.plugins)?{...l.plugins}:{},E=N(v.load)?{...v.load}:{},x=N(v.entries)?{...v.entries}:{},C=N(x[ze])?{...x[ze]}:{},I=N(C.config)?{...C.config}:{};if("plugins"in l&&!N(l.plugins)||"load"in v&&!N(v.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in v&&!N(v.entries)||ze in x&&!N(x[ze])||"config"in C&&!N(C.config)||"env"in l&&!N(l.env))d.push("plugins");else{let P=Array.isArray(E.paths)?[...E.paths]:[];P.includes(n)||P.push(n),E.paths=P,v.load=E,C.enabled=!0,I.gatewayUrl=t.anthropicBaseUrl,I.apiKey=r;let $=t.metadata.user,Y=t.metadata.team;$&&(I.user=$),Y&&(I.team=Y),C.config=I,x[ze]=C,v.entries=x,l.plugins=v;let Z=N(l.env)?{...l.env}:{};Z[vr]=r,l.env=Z,p=!0}}let h=Pl.filter(v=>v!=="openai"||!J(t,"openai"));for(let v of h){if(v in f&&!N(f[v])){d.push(`models.providers.${v}`);continue}let E=N(f[v])?{...f[v]}:{};if("headers"in E&&!N(E.headers)){i.push(v);continue}let x=N(E.headers)?{...E.headers}:{};if(E.baseUrl=v==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,v==="anthropic"&&(E.api=Vf,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=Yf)),v==="anthropic"&&a)E.apiKey=a.key,x[oo]=`Bearer ${a.key}`,x["x-anyray-provider"]="anthropic",x["x-anyray-auth-mode"]="passthrough",x["x-anyray-custom-host"]=a.url;else{E.apiKey=r,"x-anyray-custom-host"in x&&delete x[oo];for(let C of Gf)delete x[C]}x[ia]=r,o&&(x[Kf]=o),v==="anthropic"&&(ao in x?c=x[ao]!==_l:x[ao]=_l),E.headers=x,f[v]=E,s.push(v)}u.providers=f,l.models=u;let m=!1,w=!1,g=!1,y,b=[],A="agents"in l&&!N(l.agents)||N(l.agents)&&"defaults"in l.agents&&!N(l.agents.defaults)||N(l.agents)&&N(l.agents.defaults)&&("params"in l.agents.defaults&&!N(l.agents.defaults.params)||"model"in l.agents.defaults&&!N(l.agents.defaults.model));if(A&&d.push("agents.defaults"),s.includes("anthropic")&&!A){let v=N(l.agents)?{...l.agents}:{},E=N(v.defaults)?{...v.defaults}:{},x=N(E.params)?{...E.params}:{};"cacheRetention"in x||(x.cacheRetention=SC,m=!0,E.params=x);let C=N(E.model)?{...E.model}:{},I=p?[...s,ze]:s,P=$=>typeof $=="string"&&I.some(Y=>$.startsWith(`${Y}/`));typeof C.primary!="string"||C.primary.trim()===""?(C.primary=p?Xf:Tl,w=!0,E.model=C,"fallbacks"in C||(C.fallbacks=p?[...Jf]:[...Zf],g=!0)):P(C.primary)||(y=C.primary),b=(Array.isArray(C.fallbacks)?C.fallbacks:[]).filter($=>typeof $=="string"&&!P($)),(m||w)&&(v.defaults=E,l.agents=v)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:g,unroutedPrimary:y,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},YD=["baseUrl","apiKey","api","maxTokens"],Hf=(e,t,n=Pl,r)=>{let o={...e},a=!("models"in o)||N(o.models)&&(!("providers"in o.models)||N(o.models.providers)),s=N(o.models)?{...o.models}:{},i=N(s.providers)?{...s.providers}:{},c=jf(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!N(f))continue;let p={...f},h=N(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof h[ia]=="string"||typeof h[Kf]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Gf.some(v=>v in h)))continue;let w=N(c[u])?c[u]:{},g=N(w.headers)?w.headers:{},y="x-anyray-custom-host"in h,b=v=>v==="api"?p.api===Vf:v==="maxTokens"?p.maxTokens===Yf:v==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let v of YD)b(v)&&(v in w?p[v]!==w[v]&&(p[v]=w[v],l=!0):v in p&&(delete p[v],l=!0));let A=[ia,Kf,...Gf,..."x-anyray-custom-host"in h?[oo]:[]];h[ao]===_l&&A.push(ao);for(let v of A)v in g?h[v]!==g[v]&&(h[v]=g[v],l=!0):v in h&&(delete h[v],l=!0);oo in g&&!(oo in h)&&(h[oo]=g[oo],l=!0),Object.keys(h).length===0?delete p.headers:p.headers=h,Object.keys(p).length===0?delete i[u]:i[u]=p}if(a&&(Object.keys(i).length===0?delete s.providers:s.providers=i,Object.keys(s).length===0?delete o.models:o.models=s),r&&n.includes("anthropic")){let u=N(o.plugins)?{...o.plugins}:{},f=N(u.load)?{...u.load}:{},p=N(u.entries)?{...u.entries}:{};if((!("plugins"in o)||N(o.plugins))&&(!("load"in u)||N(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||N(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let w=f.paths.filter(g=>g!==r);w.length===0?delete f.paths:f.paths=w,l=!0}let m=p[ze];if(N(m)){let w=N(m.config)?m.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let y=N(t?.plugins)?t.plugins:{},b=N(y.entries)?y.entries:{};ze in b?JSON.stringify(p[ze])!==JSON.stringify(b[ze])&&(p[ze]=b[ze],l=!0):(delete p[ze],l=!0)}}if(Object.keys(f).length===0?delete u.load:u.load=f,Object.keys(p).length===0?delete u.entries:u.entries=p,Object.keys(u).length===0?delete o.plugins:o.plugins=u,N(o.env)){let w={...o.env},g=w[vr];if(typeof g=="string"&&g.startsWith("ark_")){let y=N(t?.env)?t.env:{};vr in y?w[vr]!==y[vr]&&(w[vr]=y[vr],l=!0):(delete w[vr],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||N(o.agents)&&(!("defaults"in o.agents)||N(o.agents.defaults)&&(!("params"in o.agents.defaults)||N(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||N(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=N(o.agents)?{...o.agents}:{},f=N(u.defaults)?{...u.defaults}:{},p=N(f.params)?{...f.params}:{},h=N(t.agents)?t.agents:{},m=N(h.defaults)?h.defaults:{},w=N(m.params)?m.params:{};p.cacheRetention===SC&&("cacheRetention"in w?p.cacheRetention!==w.cacheRetention&&(p.cacheRetention=w.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let g=N(f.model)?{...f.model}:{},y=N(m.model)?m.model:{};GD.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),jD.some(b=>JSON.stringify(g.fallbacks)===JSON.stringify(b))&&("fallbacks"in y?JSON.stringify(g.fallbacks)!==JSON.stringify(y.fallbacks)&&(g.fallbacks=y.fallbacks,l=!0):(delete g.fallbacks,l=!0)),Object.keys(g).length===0?delete f.model:f.model=g,Object.keys(p).length===0?delete f.params:f.params=p,Object.keys(f).length===0?delete u.defaults:u.defaults=f,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},IC={id:ti,title:"OpenClaw",automatic:!0,async detect(){let e=await O(ro())||await O(EC());return{installed:e,detail:e?ro():`no ${Rl(AC(),".openclaw")} state dir`}},async apply(e,t){let n=ro();if(!e.byoUpstream&&J(e,"anthropic")){let E=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${ti}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],x;try{x=await ei(n)}catch{return{status:"held",messages:E}}let{next:C,removed:I}=Hf(x.data,await Wf(n),Pl,rn());return I?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...E]}:(await Bf(n,x,C,!1),await se(n),await Ol(),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...E]}):(t.dryRun||await Ol(),{status:"held",messages:E})}let r=rn(),o=!1;if(!t.dryRun)try{await kC(r)}catch{r=void 0,o=!0}let a;try{a=await ei(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Vf}", "maxTokens": ${Yf}, "apiKey": "<your personal ark_ key>", "headers": { "${ia}": "<your personal ark_ key>", "${ao}": "${_l}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${ia}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Tl}") if none is set,`,'and under "agents.defaults.params" set "cacheRetention": "short" \u2014',"custom Anthropic-compatible hosts get no prompt-cache auto-seed, and","an unset value would leave the provider cache permanently cold.","Then run `openclaw config validate`."]}}let{next:s,routed:i,cacheRetentionSeeded:c,betaPreserved:l,headerConflicts:d,primarySeeded:u,fallbacksSeeded:f,unroutedPrimary:p,unroutedFallbacks:h,structureConflicts:m,pluginConfigured:w}=VD(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=Hf(g,await Wf(n),["openai"]);E.removed&&(g=E.next,y=!0)}let b=[i.includes("openai")?`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; models.providers.openai baseUrl = ${e.openaiBaseUrl}`:`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; openai left on its native ChatGPT sign-in`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${de({...e.metadata,tool:ti})??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...c?['Seeded agents.defaults.params.cacheRetention = "short": OpenClaw',"skips its prompt-cache auto-seed on custom hosts, and an unset","value would leave the provider cache permanently cold."]:["Kept your existing cacheRetention setting."],...l?[`Kept your existing ${ao} header value (OpenClaw suppresses its implicit beta headers off-host; yours replaces our default restore).`]:[],...d.length>0?[`Could not add headers on models.providers.${d.join(", ")}: the existing "headers" value is not an object. Fix it manually; nothing there was replaced.`]:[],...u?[`Seeded agents.defaults.model.primary = ${w?Xf:Tl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?Jf:Zf).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...p!==void 0?[`Your primary model (${p}) resolves to a provider Connect does not route, so those requests bypass the gateway. Pick an anthropic/* or openai/* model to route them; your setting was kept.`]:[],...h.length>0?[`Fallback model(s) ${h.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...y?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...w?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${rn()}) and registered it under plugins.entries.${ze}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${rn()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...m.length>0?[`Left ${m.join(", ")} untouched: the existing value has the wrong shape (array or null where an object belongs), and OpenClaw's strict schema will refuse it as-is. Fix the shape and re-run.`]:[],"OpenClaw hot-reloads model config; run `openclaw config validate` to confirm the merged config passes its strict schema."],A=d.length>0||m.length>0?"manual":"configured";if(t.dryRun)return{status:A,messages:b};let v=await Bf(n,a,g,!0);return{status:A,messages:b,changedFiles:v?[n]:[]}},async pointsAt(e){try{let{data:t}=await ei(ro());for(let a of Object.values(jf(t)))if(N(a)&&CC(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[ze];if(N(o)&&N(o.config)&&CC(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[ro(),Rl(rn(),".anyray-source-sha")]},async routingExpected(e){return e.includes(ti)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await ei(ro());for(let a of Object.values(jf(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[ia]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[ze];if(N(o)&&N(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=ro();if(!await O(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await ei(t)}catch{return{status:"manual",messages:[`Couldn't parse ${t} \u2014 if you added Anyray settings there by hand, remove baseUrl/apiKey and the x-anyray-* headers from models.providers.anthropic and models.providers.openai yourself.`]}}let{next:r,removed:o}=Hf(n.data,await Wf(t),Pl,rn()),a=await Ol();return o?(await Bf(t,n,r,!1),await se(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${rn()}`]:[]],changedFiles:[t]}):(await se(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${rn()}`]:[]]})}};import{execFile as MM}from"node:child_process";import{readFile as FM}from"node:fs/promises";import{homedir as ki,platform as Er}from"node:os";import{join as Sn}from"node:path";import{isDeepStrictEqual as $h,promisify as UM}from"node:util";var ni=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},Ll=(e,t)=>{let n=ni(e),r=ni(t);if(!(!n||!r)){for(let o=0;o<Math.max(n.length,r.length);o+=1){let a=(n[o]??0)-(r[o]??0);if(a!==0)return a}return 0}};import{randomUUID as eM}from"node:crypto";import{promises as UA}from"node:fs";import{platform as tM,tmpdir as nM}from"node:os";import{join as ql}from"node:path";import{execFile as ZD}from"node:child_process";import{promises as ri}from"node:fs";import{homedir as XD,platform as JD}from"node:os";import{delimiter as qD,join as Dl}from"node:path";import{promisify as zD}from"node:util";var QD=zD(ZD),eN=15*6e4,tN=64*1024*1024,nN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],OC=async(e={})=>{let t=(e.home??XD)(),n=e.env??process.env,r=nN(e.runtimePlatform??JD()),o=[Dl(t,".local","bin"),Dl(t,".claude","local"),...(n.PATH??"").split(qD).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Dl(a,`claude${s}`);try{return await ri.access(i),i}catch{}}return null},rN=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let{uuid:r,name:o,dirName:a}=n;typeof r!="string"||typeof a!="string"||a.length===0||a.includes("/")||a.includes("\\")||a==="."||a===".."||t.push({uuid:r,name:typeof o=="string"&&o.length>0?o:"Project",dirName:a})}return t},oN=async e=>{let t=Dl(e,"projects"),n;try{n=(await ri.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return[]}let r=[];for(let o of n){let a=o.slice(-36);if(!iN.test(a))continue;let s=o.slice(0,-37).split("-").filter(i=>i.length>0).map(i=>i[0].toUpperCase()+i.slice(1)).join(" ");r.push({uuid:a,name:s.length>0?s:"Project",dirName:o})}return r},aN=e=>{if(!e||!e.startsWith("{"))return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.sessionIds,o=n.jsonlPaths;if(!Array.isArray(r)||!Array.isArray(o))return null;let a=Array.isArray(n.titles)?n.titles:[],s=Array.isArray(n.createdAts)?n.createdAts:[],i=Array.isArray(n.updatedAts)?n.updatedAts:[],c=d=>typeof d=="number"&&Number.isFinite(d)?d:void 0,l=[];for(let d=0;d<r.length;d+=1){let u=r[d],f=o[d];if(typeof u!="string"||typeof f!="string"||u.length===0||f.length===0)continue;let p=a[d];l.push({sessionId:u,transcriptPath:f,title:typeof p=="string"&&p.length>0?p:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:rN(n.projectList)}},sN=async e=>{let t,n;try{let r=await ri.readFile(e,"utf8");for(let o of r.split(`
203
+ `)){if(o.length===0)continue;let a;try{a=JSON.parse(o).timestamp}catch{continue}if(typeof a!="string")continue;let s=Date.parse(a);Number.isFinite(s)&&(t??=s,n=s)}}catch{return{}}return{createdAt:t,lastActivityAt:n??t}},iN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,cN=/\.(?:cmd|bat)$/i,lN=(e,t)=>cN.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},RC=async(e,t={})=>{let n=t.exec??QD,r=["import-conversations",e.exportPath,"--cwd",e.workDir];if([e.binary,...r].some(d=>d.includes('"')))return{ok:!1,reason:"the export path contains an unsupported character"};await ri.mkdir(e.configDir,{recursive:!0,mode:448}),await ri.mkdir(e.workDir,{recursive:!0,mode:448});let o=lN(e.binary,r),a;try{a=(await n(o.file,o.args,{env:{...process.env,CLAUDE_IMPORT_CONVERSATIONS:"1",CLAUDE_CONFIG_DIR:e.configDir},timeout:eN,maxBuffer:tN,windowsVerbatimArguments:o.verbatim})).stdout}catch(d){let u=d.code;return{ok:!1,reason:typeof u=="number"?`the Claude Code importer exited with status ${u}`:"the Claude Code importer could not be run"}}let s=a.split(`
204
+ `).filter(d=>d.trim().length>0),i=aN(s.at(-1));if(!i)return{ok:!1,reason:"the Claude Code importer produced no readable summary"};let c=await Promise.all(i.conversations.map(async d=>{if(d.createdAt!==void 0)return d;let u=await sN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await oN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as dN}from"node:crypto";import{promises as Hn}from"node:fs";import{homedir as uN,platform as pN}from"node:os";import{join as Et}from"node:path";var _C=448,Kn="local_",fN="local-agent-mode-sessions",qf="-3p",hN="cowork_account_settings.json",so=(e={})=>{let t=(e.home??uN)(),n=e.runtimePlatform??pN(),r=e.env??process.env;if(n==="darwin")return Et(t,"Library","Application Support",`Claude${qf}`);if(n==="win32"){let o=r.LOCALAPPDATA??Et(t,"AppData","Local");return Et(o,`Claude${qf}`)}return null},oi=(e={})=>{let t=so(e);return t?t.slice(0,-qf.length):null},zf=e=>{let t=e.replace(/[^a-zA-Z0-9]/g,"-");if(t.length<=200)return t;let n=0;for(let r=0;r<e.length;r+=1)n=Math.imul(n,31)+e.charCodeAt(r)|0;return`${t.slice(0,200)}-${Math.abs(n).toString(36)}`},Nl=async e=>{let t=Et(e,fN),n;try{n=(await Hn.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return{ok:!1,reason:"no-profile",found:[]}}let r=[];for(let o of n){let a;try{a=(await Hn.readdir(Et(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=Et(t,o,s);try{await Hn.access(Et(i,hN)),r.push(i)}catch{}}}return r.length===0?{ok:!1,reason:"no-account",found:[]}:r.length>1?{ok:!1,reason:"ambiguous",found:r}:{ok:!0,dir:r[0]}},Qf=async e=>{try{let t=await Hn.readdir(e);return new Set(t.filter(n=>n.startsWith(Kn)&&n.endsWith(".json")).map(n=>n.slice(Kn.length,-5)))}catch{return new Set}},ca=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),mN=async(e,t)=>{let n=`${Kn}${t.sessionId}`,r=Et(e,n),o=Et(r,"outputs"),a=Et(r,".claude"),s=Et(a,"projects",zf(o));await Hn.mkdir(o,{recursive:!0,mode:_C}),await Hn.mkdir(s,{recursive:!0,mode:_C});let i=Et(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${dN()}`;await Hn.copyFile(t.transcriptPath,c),await Hn.chmod(c,384),await Hn.rename(c,i);let l=t.createdAt??Date.now();await X(Et(e,`${n}.json`),{sessionId:n,cliSessionId:t.sessionId,processName:"claude-ai-import",cwd:o,hostLoopMode:!0,title:t.title,createdAt:l,lastActivityAt:t.lastActivityAt??l,isArchived:!1,userSelectedFolders:[],pendingNotifications:[]},{backup:!1})},PC=async(e,t)=>{let n=await Qf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!ca(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await mN(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as la}from"node:fs";import{homedir as yN}from"node:os";import{dirname as gN,join as ai}from"node:path";var wN=448,bN=["Documents","Claude","Projects"],kN="spaces.json",CN=(e={})=>ai((e.home??yN)(),...bN),AN=async e=>{try{let t=JSON.parse(await la.readFile(e,"utf8"));if(!t||typeof t!="object")return{spaces:[],readable:!1};let n=t.spaces;return Array.isArray(n)?{spaces:n.filter(r=>!!r&&typeof r=="object"&&typeof r.id=="string"),readable:!0}:{spaces:[],readable:!1}}catch(t){return t.code==="ENOENT"?{spaces:[],readable:!0}:{spaces:[],readable:!1}}},vN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},eh=async e=>{try{return await la.access(e),!0}catch{return!1}},SN=async(e,t,n)=>{let r=ai(t,vN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await eh(r)?o:r;return a===o&&await eh(o)?null:(await la.mkdir(gN(a),{recursive:!0}),await la.cp(e,a,{recursive:!0}),a)},EN=async e=>{try{let t=(await la.readFile(ai(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},TC=async e=>{let t=CN({home:e.home}),n={imported:0,alreadyPresent:0,skippedCollision:0,failed:0,root:t},r=e.projects??[];if(r.length===0)return n;let o=ai(e.storageDir,kN),{spaces:a,readable:s}=await AN(o);if(!s)return n.failed=r.length,n;let i=new Set(a.map(l=>l.id)),c=[];for(let l of r){if(i.has(l.uuid)){n.alreadyPresent+=1;continue}let d=ai(e.stagedProjectsDir,l.dirName);try{if(!await eh(d)){n.failed+=1;continue}let u=await SN(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await EN(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...f?{instructions:f}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await la.mkdir(e.storageDir,{recursive:!0,mode:wN}),await X(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as RN}from"node:crypto";import{execFile as _N,spawnSync as KC}from"node:child_process";import{constants as GC}from"node:fs";import{access as Wl,chmod as PN,mkdir as TN,readdir as LN,readFile as nh,rename as DN,rm as ua,stat as jC,writeFile as NN}from"node:fs/promises";import{homedir as $N,platform as MN,userInfo as FN}from"node:os";import{basename as UN,dirname as VC,isAbsolute as pa,join as Ut,resolve as MC}from"node:path";import{isDeepStrictEqual as ii,promisify as BN}from"node:util";var si="__anyray-claude-desktop-credential";var $l=["Heads up: Claude Desktop's third-party mode uses its own app profile, so it opens signed out with empty conversation lists. Nothing is deleted and your Claude account is unchanged \u2014 sign back in with the account you already use.","Your Claude Code sessions and Cowork tasks come across on their own once this new profile has been signed in to and the app is fully quit \u2014 no second command.","Your claude.ai chats live on your Claude account rather than this machine, so those need your data export: `anyray-connect migrate --export <file.zip>`."],Ml=["Your Claude account conversations are reachable in the app again once it reopens.","Chats made while third-party mode was active stay in its separate profile and come back if you configure it again."],LC="Note: third-party mode runs in a separate app profile, so Claude Desktop starts with empty conversation lists while it is active. Nothing is lost \u2014 local sessions come across on their own once the profile is signed in to and Claude Desktop is fully quit (see any queued migration above), claude.ai chats need your data export via `anyray-connect migrate --export <file.zip>`, and `anyray-connect desktop disconnect` restores the first-party profile.";var Fl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],DC=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],xN=new Set(DC),IN=new Set(DC.map(e=>e.toLowerCase())),ON=new Set(Fl.map(e=>e.toLowerCase())),Ul=(e,t=!1)=>(t?IN:xN).has(t?e.toLowerCase():e),NC=(e,t=!1)=>t?ON.has(e.toLowerCase()):Fl.some(n=>n===e),$C=["*"],io=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...$C]}),da=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var ci=/^[a-f0-9-]{36}$/,YC="Anyray",rh=4,ui=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],pi=["deploymentMode","awaitingSignIn"],ZC=[...ui,...pi,"configLibrary","_meta.json"],Cn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),lt=e=>structuredClone(e),li=async e=>{try{return await Wl(e),!0}catch{return!1}},WN=async e=>{try{let t=await LN(VC(e)),n=UN(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},HN=async e=>{try{return await Wl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":WN(e)}},on=(e={})=>{let t=(e.home??$N)(),n=(e.username??(()=>FN().username))(),r=Ut(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Ut("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Ut(r,"configLibrary"),meta:Ut(r,"configLibrary","_meta.json"),appConfig:Ut(r,"claude_desktop_config.json"),helper:Ut(t,".anyray","bin","claude-desktop-credential-helper"),journal:Ut(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Hl=()=>{let e=KC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},XC=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],KN=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...XC(t)]}},oh=(e="json")=>{let t=un(XC(e)),n=MC(t.command),r=MC(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:le()&&(!o||r!==n)}},GN=e=>`'${e.replace(/'/g,`'"'"'`)}'`,ah=e=>[e.command,...e.args].map(GN).join(" "),jN=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!pa(e.command))throw new Error("the credential helper executable is not absolute")},JC=(e,t)=>{jN(e);let n=Kl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!pa(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},qC=e=>(JC(e,"--json"),`#!/bin/sh
205
+ exec ${ah(e)}
206
+ `),VN=`#!/bin/sh
207
+ # Anyray subscription pass-through credential helper v2 for Claude Desktop`,zC=e=>{JC(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),si]};return["#!/bin/sh","# Anyray subscription pass-through credential helper v2 for Claude Desktop.","# The durable credential runtime reads and validates the Keychain JSON,","# combines it with Anyray headers, and writes one credential response.",`exec ${ah(t)}`,""].join(`
208
+ `)},YN=e=>e.args.at(-1)==="--passthrough-headers"?zC(e):qC(e),Kl=e=>/[\\/](node|node\.exe)$/i.test(e),sh=e=>{let t=[],n=0;for(;n<e.length;){if(e[n]!=="'")return;n++;let r="";for(;n<e.length;){let o=e.indexOf("'",n);if(o<0)return;if(r+=e.slice(n,o),e.startsWith(`'"'"'`,o)){r+="'",n=o+5;continue}n=o+1;break}if(t.push(r),n===e.length)return t;if(e[n]!==" "||n+1===e.length)return;n++}},ZN=e=>{let t=`#!/bin/sh
209
209
  exec `;if(!e.startsWith(t)||!e.endsWith(`
210
210
  `))return;let n=e.slice(t.length,-1);if(n.includes(`
211
- `)||n.includes("\r"))return;let r=oh(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Wl(o);if(!ua(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!ua(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return XC(i)===e?i:void 0}catch{return}},GN=e=>{if(!e.startsWith(WN))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=oh(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==oi)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return zC(a)===e?a:void 0}catch{return}},jN=`#!/bin/sh
212
- # Anyray subscription pass-through credential helper`,VN=e=>{let t=Wl(e.command);if(!(!ua(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!ua(e.args[0]):e.args.length!==2)))return["#!/bin/sh","# Anyray subscription pass-through credential helper for Claude Desktop.","# Reads the Claude subscription token from the login keychain at request","# time and wraps it with Anyray pass-through headers. connect never stores","# the token; only this on-machine helper reads it.","set -eu",`headers=$(${rh(e)})`,'if [ -z "${headers}" ]; then'," echo 'Anyray: could not resolve gateway headers; is this machine enrolled? Run: anyray-connect' >&2"," exit 1","fi","token=$(security find-generic-password -s 'Claude Code-credentials' -w 2>/dev/null | grep -oE 'sk-ant-oat[0-9A-Za-z._-]+' | head -n1)",'if [ -z "${token}" ]; then'," echo 'Anyray: no Claude subscription sign-in found; run: claude' >&2"," exit 1","fi",'printf \'{"token":"%s","headers":%s}\\n\' "${token}" "${headers}"',""].join(`
213
- `)},YN=e=>{if(!e.startsWith(jN))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=oh(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return VN(a)===e?a:void 0},qC=e=>KN(e)??GN(e)??YN(e),ZN=async()=>{let e=HC("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},JN=async e=>{let t=[e.command,...Wl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>GC(r)))).every(r=>r.isFile())?(await Ul(e.command,KC.X_OK),!0):!1}catch{return!1}},XN=0,Hl=async(e,t,n)=>{await xN(jC(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${XN++}.tmp`;try{await _N(r,t,{mode:n}),await IN(r,n),await ON(r,e)}catch(o){throw await da(r,{force:!0}).catch(()=>{}),o}},Hn=async(e,t)=>{await Hl(e,`${JSON.stringify(t,null,2)}
214
- `,384)},Cn=async e=>{if(!await ii(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await eh(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!kn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},ui=async e=>{if(!await ii(e))return{present:!1};let t=await GC(e);return{present:!0,content:await eh(e,"utf-8"),mode:t.mode&511}},QC=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:lt(e[t])}:{present:!1},Qf=(e,t,n)=>{n.present?e[t]=lt(n.value):delete e[t]},MC=e=>kn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),zN=e=>kn(e)&&MC(e.original)&&MC(e.lastWritten),qN=e=>kn(e)&&typeof e.present=="boolean"&&(!e.present||typeof e.content=="string"&&typeof e.mode=="number"&&Number.isInteger(e.mode)&&e.mode>=0&&e.mode<=511),FC=(e,t)=>kn(e)&&t.every(n=>zN(e[n])),QN=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],e$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],ah=(e,t,n,r)=>!(!kn(e)||e.version!==n||typeof e.configId!="string"||!si.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!si.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!kn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==VC||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!FC(e.config,r)||r.some(o=>e.config[o].original.present)||!FC(e.deployment,di)||!kn(e.helper)||e.helper.path!==t.helper||!qN(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),t$=(e,t)=>ah(e,t,th,li),n$=(e,t)=>ah(e,t,2,QN),r$=(e,t)=>ah(e,t,3,e$),o$=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),UC=e=>({...e,version:th,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),sh=async e=>{if(!await ii(e.journal))return;let t;try{t=JSON.parse(await eh(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(t$(t,e))return t;if(r$(t,e))return UC(t);if(n$(t,e))return UC(o$(t));throw new Error(`${e.journal} is not a valid ownership journal`)},BC=async(e,t)=>{await Hl(e,`${JSON.stringify(t,null,2)}
215
- `,384)},ci=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!si.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!kn(o)||typeof o.id!="string"||!si.test(o.id)||typeof o.name!="string"||r.has(o.id))throw new Error("Claude config-library metadata has an invalid entry");r.add(o.id)}if(!r.has(t))throw new Error("Claude config-library appliedId is not in entries");return t},a$=async(e,t,n)=>{let r=await Cn(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:lt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[lt(t.metaEntry)]}}}let c=ci(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!ai(d,t.metaEntry))throw new Error("Claude changed the Anyray config-library entry after apply");return{configId:t.configId,meta:r,metaFileExisted:t.metaFileExisted,originalAppliedId:t.originalAppliedId,metaEntry:lt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...lt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=ci(r.value);let c=Bt(e.library,`${o}.json`);if(!await ii(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=lt(r.value.entries)}let s=n();if(!si.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await ii(Bt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:VC};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?lt(r.value):{},appliedId:s,entries:[...a,i]}}},s$=(e,t)=>{let n=co(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},eA=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),i$=async(e,t,n,r,o,a,s)=>{let i=eA(),c=Object.fromEntries(li.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(di.map(d=>[d,{original:s?.deployment[d].original??QC(r.value,d),lastWritten:i[d]}]));return{version:th,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??lt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await ui(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Fl=e=>({status:"manual",messages:[e]}),c$=e=>{let t=[...e.filter(n=>n.audience==="user"),...e.filter(n=>n.audience==="admin")];return{status:"manual",manualAudience:t.some(n=>n.audience==="user")?"user":"admin",messages:t.length===1?[t[0].message]:[`Not configured \u2014 ${t.length} things are in the way:`,...t.map((n,r)=>`${r+1}. ${n.message}`)]}},l$=NN(EN),d$=new Set($l),u$=async e=>{try{let{stdout:t}=await l$("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return kn(n)?Object.keys(n):void 0}catch{return}},lo=async(e,t={})=>{let n=t.readManagedPolicyKeys??u$;for(let r of e.managedPolicies){let o=await MN(r);if(o==="absent")continue;if(o==="unreadable")return{path:r,keys:[],unreadable:!0};let a=await n(r);if(a===void 0)return{path:r,keys:[],unreadable:!0};let s=a.filter(i=>Ml(i)&&!d$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},ih=e=>{if(e.unreadable)return`Claude Desktop may be centrally managed by ${e.path}, which could not be read; Connect did not change its inference configuration.`;let t=e.keys.slice(0,8).map(o=>/^[A-Za-z][A-Za-z0-9]{0,63}$/u.test(o)?o:"<unrecognized key>"),n=e.keys.length-t.length,r=`${t.join(", ")}${n>0?`, +${n} more`:""}`;return`Claude Desktop is centrally managed by ${e.path} (${r}); Connect did not change that managed configuration.`},ch=e=>(e.platform??PN)()==="darwin",tA=async(e,t,n={})=>{if(!ch(n))return Fl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Bl)()&&r.push({audience:"user",message:"Claude Desktop is running. Fully quit it, then re-run connect so its cached state cannot overwrite the change."});let o=on(n),a=await lo(o,n);if(a&&r.push({audience:"admin",message:ih(a)}),r.length>0)return c$(r);let s=!1,i=!1,c=[o.journal];try{let l=X(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??ZN)())throw new Error("Claude subscription mode requires a readable Claude Code sign-in in the macOS Keychain; run `claude` and sign in, then re-run Connect");let d=l?"passthrough":"json",u=FN((n.credentialCommand??(()=>nh(d)))(),d),f=HN(u),p=await sh(o),h=await ui(o.helper);if(p&&h.present&&h.content!==p.helper.lastWritten&&h.content!==p.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!p&&h.present&&h.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let m=await a$(o,p,n.randomUUID??SN),w=Bt(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await Cn(w),y=await Cn(o.appConfig),b=s$(e,o.helper),A=await i$(o,m,g,y,f,b,p);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${m.configId} for ${e.anthropicBaseUrl}, activate it in third-party mode, and install a ${l?"subscription pass-through":"dynamic API-billed"} credential helper at ${o.helper}.`]};s=!0,await BC(o.journal,A),i=!0,await Hl(o.helper,f,448),A.helper.previousWritten!==void 0&&(delete A.helper.previousWritten,await BC(o.journal,A));let v=lt(g.value);for(let C of li)Qf(v,C,b[C]);await Hn(w,v),m.metaToWrite&&await Hn(o.meta,m.metaToWrite);let E=lt(y.value),I=eA();for(let C of di)Qf(E,C,I[C]);return await Hn(o.appConfig,E),{status:"configured",changedFiles:[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig],messages:[`Configured Claude Desktop's native local gateway profile \u2192 ${e.anthropicBaseUrl}.`,l?`Installed a subscription pass-through credential helper at ${o.helper}; the helper reads your Claude Code subscription token on demand and no credential is stored in Claude's config.`:`Installed a dynamic credential helper at ${o.helper}; no gateway key is stored in Claude's config.`,l?"Claude Desktop Gateway requests now ride your Claude subscription through Anyray for content-free metering and optimization. Stay signed in to Claude Code so the token remains available.":"Claude Desktop uses its API-billed third-party inference lane; its first-party subscription remains separate.","Fully quit and reopen Claude Desktop to load the change.",...Dl]}}catch(l){let d=l instanceof Error?l.message:String(l);return s?{status:"manual",changedFiles:c,messages:[i?`Claude Desktop setup stopped after its ownership journal was written (${d}). Some listed files may contain a partial Anyray configuration.`:`Claude Desktop setup stopped while writing its ownership journal (${d}). No app configuration write was attempted, but the journal path may need cleanup.`,i?"Re-run connect to converge the journaled setup, or run --revert to restore the pre-Anyray values.":`Inspect ${o.journal}, then re-run connect.`]}:Fl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},WC=(e,t,n,r)=>{let o=lt(e);for(let a of n){let s=t[a];ai(QC(e,a),s.lastWritten)?Qf(o,a,s.original):r.push(a)}return o},nA=async(e,t={})=>{if(!ch(t))return{status:"not-found",messages:[]};if((t.appRunning??Bl)())return Fl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=on(t);try{let r=await sh(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Bt(n.library,`${r.configId}.json`);if(e.dryRun)return{status:"reverted",messages:[`Would restore Anyray-owned Claude Desktop fields from ${n.journal}, preserving user changes.`]};let a=[],s=await Cn(o),i=s.value;s.present&&(i=WC(s.value,r.config,li,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await Cn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=ci(l.value),m=lt(l.value.entries),w=m.findIndex(b=>b.id===r.configId),g=w>=0?m[w]:void 0,y=g!==void 0&&ai(g,r.metaEntry);if(g!==void 0&&!y&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=lt(l.value),h===r.configId){let b=r.originalAppliedId;b&&m.some(A=>A.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&y?(m.splice(w,1),d.entries=m):c&&g===void 0&&(d.entries=m)}else{let b=ai(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(y&&m.splice(w,1),d={...lt(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await da(o,{force:!0}):await Hn(o,i)),l.present&&(u?await da(n.meta,{force:!0}):ai(l.value,d)||await Hn(n.meta,d));let f=await Cn(n.appConfig);if(f.present){let h=WC(f.value,r.deployment,di,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await da(n.appConfig,{force:!0}):await Hn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await ui(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Hl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await da(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await da(n.journal,{force:!0}),{status:"reverted",changedFiles:[o,n.meta,n.appConfig,n.helper,n.journal],messages:["Restored Claude Desktop fields owned by Anyray.",...a.length>0?[`Preserved values changed after connect: ${[...new Set(a)].join(", ")}.`]:[],"Fully quit and reopen Claude Desktop to load the restored configuration.",...a.length>0?[]:Nl]}}catch(r){return Fl(`Could not safely revert Claude Desktop (${r instanceof Error?r.message:String(r)}). Existing config was left in place where ownership could not be proven.`)}},lh=async(e,t={})=>{if(!ch(t))return!1;let n=on(t);if(await lo(n,t))return!1;try{let r=await Cn(n.meta);if(!r.present)return!1;let o=ci(r.value),a=await Cn(Bt(n.library,`${o}.json`)),s=await Cn(n.appConfig);if(!a.present||!s.present)return!1;await Ul(n.helper,KC.X_OK);let i=Ze(e);return a.value.inferenceProvider==="gateway"&&a.value.inferenceGatewayBaseUrl===i&&a.value.inferenceGatewayAuthScheme==="bearer"&&a.value.inferenceCredentialKind==="helper-script"&&a.value.inferenceCredentialHelper===n.helper&&!Object.prototype.hasOwnProperty.call(a.value,"inferenceGatewayApiKey")&&s.value.deploymentMode==="3p"&&!Object.prototype.hasOwnProperty.call(s.value,"awaitingSignIn")}catch{return!1}},rA=async(e={})=>{try{let t=on(e),n=await ui(t.helper);if(!n.present||typeof n.content!="string")return;let r=qC(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},oA=async(e,t={})=>{if(!await lh(e,t))return!1;let n=on(t);try{let r=await sh(n);if(!r)return!1;let o=await Cn(n.meta);if(!o.present||ci(o.value)!==r.configId)return!1;let a=await ui(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=qC(a.content??"");return s?await(t.helperLauncherAvailable??JN)(s):!1}catch{return!1}};import{createHash as kA,randomUUID as CA}from"node:crypto";import{spawn as p$,spawnSync as f$}from"node:child_process";import{link as yh,mkdir as dh,open as AA,readFile as uh,readdir as vA,rename as SA,rm as an,stat as EA}from"node:fs/promises";import{homedir as gh}from"node:os";import{basename as IA,dirname as fi,join as wa,win32 as h$}from"node:path";import{isDeepStrictEqual as pa}from"node:util";var Te="HKCU\\SOFTWARE\\Policies\\Claude",pi="HKLM\\SOFTWARE\\Policies\\Claude",Vl=5,ba="inferenceGatewayApiKey",$e=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ba],aA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ba],sA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ba],iA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ba],xA="Managed by anyray-connect; dynamic credential only.",m$=e=>/^[A-Za-z]:[\\/]/.test(e)&&h$.isAbsolute(e),cA=e=>{if(!m$(e)||/[\0\r\n"]/u.test(e))return!1;let t=e.replace(/\\/g,"/").toLowerCase();return!/(^|\/)_npx(\/|$)/u.test(t)&&!/\/appdata\/local\/temp(\/|$)/u.test(t)&&!/(^|\/)temp(\/|$)/u.test(t)},RA=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!cA(e.command)||!/\.exe$/iu.test(e.command))throw new Error("the credential helper executable is not durable");if(e.args.length<2||e.args.length>3||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--json"||e.args.length===3&&!cA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},wh=(e={})=>wa((e.home??gh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),y$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},g$=e=>(RA(e),["@echo off",`REM ${xA}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(y$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
216
- `)),w$=e=>{let t="";for(let n=0;n<e.length;n++){if(e[n]!=="%"){t+=e[n];continue}if(e[n+1]!=="%")return;t+="%",n++}return t},OA=e=>{let t=e.split(`\r
217
- `);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${xA}`||t[2]!=="setlocal DisableDelayedExpansion"||t[4]!=="exit /b %ERRORLEVEL%"||t[5]!==""||!t[3].startsWith('"')||!t[3].endsWith('"'))return;let r=t[3].slice(1,-1).split('" "').map(w$);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return RA(s),s}catch{return}},b$=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>EA(r)))).every(r=>r.isFile())}catch{return!1}},k$=async(e,t)=>{let n=OA(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??b$)(n)}catch{return!1}},ph=e=>({sha256:uo(e),content:e}),lA=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Wt(t,["sha256","content"])&&R$(t.sha256)&&typeof t.content=="string"&&uo(t.content)===t.sha256&&OA(t.content)!==void 0},bh=()=>{let e=f$("tasklist.exe",["/FI","IMAGENAME eq Claude.exe","/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0,timeout:2e3,maxBuffer:65536});return e.error||e.signal||e.status!==0?!0:/(?:^|\r?\n)"Claude\.exe",/iu.test(e.stdout??"")},C$=async(e,t)=>{await dh(fi(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await AA(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await yh(n,e)}finally{await an(n,{force:!0}).catch(()=>{})}},A$=e=>`${IA(e)}.anyray-old-`,v$=e=>`${e}.anyray-old-${process.pid}-${CA()}`,_A=async(e,t)=>{try{await yh(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await an(t,{force:!0}),!0},Gl=async(e,t,n,r,o)=>{let a=v$(e),s=n===void 0?void 0:uo(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${CA()}`,c=!1;try{if(i&&n!==void 0){let d=await AA(i,"wx",384);try{await d.writeFile(n,"utf8"),await d.sync()}finally{await d.close()}}await o.helperFileOperationHook?.({operation:r,phase:"before-move",path:e,recoveryPath:a}),await SA(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ya(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await yh(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await ga(e)!==s))throw new Error("credential helper publication verification failed");await an(a,{force:!0}),c=!1}catch(l){throw c&&await _A(e,a).catch(()=>!1),l}finally{i&&await an(i,{force:!0}).catch(()=>{})}},fh=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,S$=String.raw`
211
+ `)||n.includes("\r"))return;let r=sh(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Kl(o);if(!pa(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!pa(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return qC(i)===e?i:void 0}catch{return}},XN=e=>{if(!e.startsWith(VN))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=sh(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==si)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return zC(a)===e?a:void 0}catch{return}},JN=`#!/bin/sh
212
+ # Anyray subscription pass-through credential helper`,qN=e=>{let t=Kl(e.command);if(!(!pa(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!pa(e.args[0]):e.args.length!==2)))return["#!/bin/sh","# Anyray subscription pass-through credential helper for Claude Desktop.","# Reads the Claude subscription token from the login keychain at request","# time and wraps it with Anyray pass-through headers. connect never stores","# the token; only this on-machine helper reads it.","set -eu",`headers=$(${ah(e)})`,'if [ -z "${headers}" ]; then'," echo 'Anyray: could not resolve gateway headers; is this machine enrolled? Run: anyray-connect' >&2"," exit 1","fi","token=$(security find-generic-password -s 'Claude Code-credentials' -w 2>/dev/null | grep -oE 'sk-ant-oat[0-9A-Za-z._-]+' | head -n1)",'if [ -z "${token}" ]; then'," echo 'Anyray: no Claude subscription sign-in found; run: claude' >&2"," exit 1","fi",'printf \'{"token":"%s","headers":%s}\\n\' "${token}" "${headers}"',""].join(`
213
+ `)},zN=e=>{if(!e.startsWith(JN))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=sh(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return qN(a)===e?a:void 0},QC=e=>ZN(e)??XN(e)??zN(e),QN=async()=>{let e=KC("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},e$=async e=>{let t=[e.command,...Kl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>jC(r)))).every(r=>r.isFile())?(await Wl(e.command,GC.X_OK),!0):!1}catch{return!1}},t$=0,Gl=async(e,t,n)=>{await TN(VC(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${t$++}.tmp`;try{await NN(r,t,{mode:n}),await PN(r,n),await DN(r,e)}catch(o){throw await ua(r,{force:!0}).catch(()=>{}),o}},Gn=async(e,t)=>{await Gl(e,`${JSON.stringify(t,null,2)}
214
+ `,384)},An=async e=>{if(!await li(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await nh(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!Cn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},fi=async e=>{if(!await li(e))return{present:!1};let t=await jC(e);return{present:!0,content:await nh(e,"utf-8"),mode:t.mode&511}},eA=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:lt(e[t])}:{present:!1},th=(e,t,n)=>{n.present?e[t]=lt(n.value):delete e[t]},FC=e=>Cn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),n$=e=>Cn(e)&&FC(e.original)&&FC(e.lastWritten),r$=e=>Cn(e)&&typeof e.present=="boolean"&&(!e.present||typeof e.content=="string"&&typeof e.mode=="number"&&Number.isInteger(e.mode)&&e.mode>=0&&e.mode<=511),UC=(e,t)=>Cn(e)&&t.every(n=>n$(e[n])),o$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],a$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],ih=(e,t,n,r)=>!(!Cn(e)||e.version!==n||typeof e.configId!="string"||!ci.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!ci.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!Cn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==YC||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!UC(e.config,r)||r.some(o=>e.config[o].original.present)||!UC(e.deployment,pi)||!Cn(e.helper)||e.helper.path!==t.helper||!r$(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),s$=(e,t)=>ih(e,t,rh,ui),i$=(e,t)=>ih(e,t,2,o$),c$=(e,t)=>ih(e,t,3,a$),l$=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),BC=e=>({...e,version:rh,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),ch=async e=>{if(!await li(e.journal))return;let t;try{t=JSON.parse(await nh(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(s$(t,e))return t;if(c$(t,e))return BC(t);if(i$(t,e))return BC(l$(t));throw new Error(`${e.journal} is not a valid ownership journal`)},WC=async(e,t)=>{await Gl(e,`${JSON.stringify(t,null,2)}
215
+ `,384)},di=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!ci.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!Cn(o)||typeof o.id!="string"||!ci.test(o.id)||typeof o.name!="string"||r.has(o.id))throw new Error("Claude config-library metadata has an invalid entry");r.add(o.id)}if(!r.has(t))throw new Error("Claude config-library appliedId is not in entries");return t},d$=async(e,t,n)=>{let r=await An(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:lt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[lt(t.metaEntry)]}}}let c=di(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!ii(d,t.metaEntry))throw new Error("Claude changed the Anyray config-library entry after apply");return{configId:t.configId,meta:r,metaFileExisted:t.metaFileExisted,originalAppliedId:t.originalAppliedId,metaEntry:lt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...lt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=di(r.value);let c=Ut(e.library,`${o}.json`);if(!await li(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=lt(r.value.entries)}let s=n();if(!ci.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await li(Ut(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:YC};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?lt(r.value):{},appliedId:s,entries:[...a,i]}}},u$=(e,t)=>{let n=io(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},tA=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),p$=async(e,t,n,r,o,a,s)=>{let i=tA(),c=Object.fromEntries(ui.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(pi.map(d=>[d,{original:s?.deployment[d].original??eA(r.value,d),lastWritten:i[d]}]));return{version:rh,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??lt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await fi(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Bl=e=>({status:"manual",messages:[e]}),f$=e=>{let t=[...e.filter(n=>n.audience==="user"),...e.filter(n=>n.audience==="admin")];return{status:"manual",manualAudience:t.some(n=>n.audience==="user")?"user":"admin",messages:t.length===1?[t[0].message]:[`Not configured \u2014 ${t.length} things are in the way:`,...t.map((n,r)=>`${r+1}. ${n.message}`)]}},h$=BN(_N),m$=new Set(Fl),y$=async e=>{try{let{stdout:t}=await h$("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return Cn(n)?Object.keys(n):void 0}catch{return}},co=async(e,t={})=>{let n=t.readManagedPolicyKeys??y$;for(let r of e.managedPolicies){let o=await HN(r);if(o==="absent")continue;if(o==="unreadable")return{path:r,keys:[],unreadable:!0};let a=await n(r);if(a===void 0)return{path:r,keys:[],unreadable:!0};let s=a.filter(i=>Ul(i)&&!m$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},lh=e=>{if(e.unreadable)return`Claude Desktop may be centrally managed by ${e.path}, which could not be read; Connect did not change its inference configuration.`;let t=e.keys.slice(0,8).map(o=>/^[A-Za-z][A-Za-z0-9]{0,63}$/u.test(o)?o:"<unrecognized key>"),n=e.keys.length-t.length,r=`${t.join(", ")}${n>0?`, +${n} more`:""}`;return`Claude Desktop is centrally managed by ${e.path} (${r}); Connect did not change that managed configuration.`},dh=e=>(e.platform??MN)()==="darwin",nA=async(e,t,n={})=>{if(!dh(n))return Bl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Hl)()&&r.push({audience:"user",message:"Claude Desktop is running. Fully quit it, then re-run connect so its cached state cannot overwrite the change."});let o=on(n),a=await co(o,n);if(a&&r.push({audience:"admin",message:lh(a)}),r.length>0)return f$(r);let s=!1,i=!1,c=[o.journal];try{let l=J(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??QN)())throw new Error("Claude subscription mode requires a readable Claude Code sign-in in the macOS Keychain; run `claude` and sign in, then re-run Connect");let d=l?"passthrough":"json",u=KN((n.credentialCommand??(()=>oh(d)))(),d),f=YN(u),p=await ch(o),h=await fi(o.helper);if(p&&h.present&&h.content!==p.helper.lastWritten&&h.content!==p.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!p&&h.present&&h.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let m=await d$(o,p,n.randomUUID??RN),w=Ut(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await An(w),y=await An(o.appConfig),b=u$(e,o.helper),A=await p$(o,m,g,y,f,b,p);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${m.configId} for ${e.anthropicBaseUrl}, activate it in third-party mode, and install a ${l?"subscription pass-through":"dynamic API-billed"} credential helper at ${o.helper}.`]};s=!0,await WC(o.journal,A),i=!0,await Gl(o.helper,f,448),A.helper.previousWritten!==void 0&&(delete A.helper.previousWritten,await WC(o.journal,A));let v=lt(g.value);for(let C of ui)th(v,C,b[C]);await Gn(w,v),m.metaToWrite&&await Gn(o.meta,m.metaToWrite);let E=lt(y.value),x=tA();for(let C of pi)th(E,C,x[C]);return await Gn(o.appConfig,E),{status:"configured",changedFiles:[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig],messages:[`Configured Claude Desktop's native local gateway profile \u2192 ${e.anthropicBaseUrl}.`,l?`Installed a subscription pass-through credential helper at ${o.helper}; the helper reads your Claude Code subscription token on demand and no credential is stored in Claude's config.`:`Installed a dynamic credential helper at ${o.helper}; no gateway key is stored in Claude's config.`,l?"Claude Desktop Gateway requests now ride your Claude subscription through Anyray for content-free metering and optimization. Stay signed in to Claude Code so the token remains available.":"Claude Desktop uses its API-billed third-party inference lane; its first-party subscription remains separate.","Fully quit and reopen Claude Desktop to load the change.",...$l]}}catch(l){let d=l instanceof Error?l.message:String(l);return s?{status:"manual",changedFiles:c,messages:[i?`Claude Desktop setup stopped after its ownership journal was written (${d}). Some listed files may contain a partial Anyray configuration.`:`Claude Desktop setup stopped while writing its ownership journal (${d}). No app configuration write was attempted, but the journal path may need cleanup.`,i?"Re-run connect to converge the journaled setup, or run --revert to restore the pre-Anyray values.":`Inspect ${o.journal}, then re-run connect.`]}:Bl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},HC=(e,t,n,r)=>{let o=lt(e);for(let a of n){let s=t[a];ii(eA(e,a),s.lastWritten)?th(o,a,s.original):r.push(a)}return o},rA=async(e,t={})=>{if(!dh(t))return{status:"not-found",messages:[]};if((t.appRunning??Hl)())return Bl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=on(t);try{let r=await ch(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Ut(n.library,`${r.configId}.json`);if(e.dryRun)return{status:"reverted",messages:[`Would restore Anyray-owned Claude Desktop fields from ${n.journal}, preserving user changes.`]};let a=[],s=await An(o),i=s.value;s.present&&(i=HC(s.value,r.config,ui,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await An(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=di(l.value),m=lt(l.value.entries),w=m.findIndex(b=>b.id===r.configId),g=w>=0?m[w]:void 0,y=g!==void 0&&ii(g,r.metaEntry);if(g!==void 0&&!y&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=lt(l.value),h===r.configId){let b=r.originalAppliedId;b&&m.some(A=>A.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&y?(m.splice(w,1),d.entries=m):c&&g===void 0&&(d.entries=m)}else{let b=ii(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(y&&m.splice(w,1),d={...lt(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await ua(o,{force:!0}):await Gn(o,i)),l.present&&(u?await ua(n.meta,{force:!0}):ii(l.value,d)||await Gn(n.meta,d));let f=await An(n.appConfig);if(f.present){let h=HC(f.value,r.deployment,pi,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await ua(n.appConfig,{force:!0}):await Gn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await fi(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Gl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await ua(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await ua(n.journal,{force:!0}),{status:"reverted",changedFiles:[o,n.meta,n.appConfig,n.helper,n.journal],messages:["Restored Claude Desktop fields owned by Anyray.",...a.length>0?[`Preserved values changed after connect: ${[...new Set(a)].join(", ")}.`]:[],"Fully quit and reopen Claude Desktop to load the restored configuration.",...a.length>0?[]:Ml]}}catch(r){return Bl(`Could not safely revert Claude Desktop (${r instanceof Error?r.message:String(r)}). Existing config was left in place where ownership could not be proven.`)}},uh=async(e,t={})=>{if(!dh(t))return!1;let n=on(t);if(await co(n,t))return!1;try{let r=await An(n.meta);if(!r.present)return!1;let o=di(r.value),a=await An(Ut(n.library,`${o}.json`)),s=await An(n.appConfig);if(!a.present||!s.present)return!1;await Wl(n.helper,GC.X_OK);let i=Xe(e);return a.value.inferenceProvider==="gateway"&&a.value.inferenceGatewayBaseUrl===i&&a.value.inferenceGatewayAuthScheme==="bearer"&&a.value.inferenceCredentialKind==="helper-script"&&a.value.inferenceCredentialHelper===n.helper&&!Object.prototype.hasOwnProperty.call(a.value,"inferenceGatewayApiKey")&&s.value.deploymentMode==="3p"&&!Object.prototype.hasOwnProperty.call(s.value,"awaitingSignIn")}catch{return!1}},oA=async(e={})=>{try{let t=on(e),n=await fi(t.helper);if(!n.present||typeof n.content!="string")return;let r=QC(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},aA=async(e,t={})=>{if(!await uh(e,t))return!1;let n=on(t);try{let r=await ch(n);if(!r)return!1;let o=await An(n.meta);if(!o.present||di(o.value)!==r.configId)return!1;let a=await fi(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=QC(a.content??"");return s?await(t.helperLauncherAvailable??e$)(s):!1}catch{return!1}};import{createHash as CA,randomUUID as AA}from"node:crypto";import{spawn as g$,spawnSync as w$}from"node:child_process";import{link as wh,mkdir as ph,open as vA,readFile as fh,readdir as SA,rename as EA,rm as an,stat as xA}from"node:fs/promises";import{homedir as bh}from"node:os";import{basename as IA,dirname as mi,join as ba,win32 as b$}from"node:path";import{isDeepStrictEqual as fa}from"node:util";var _e="HKCU\\SOFTWARE\\Policies\\Claude",hi="HKLM\\SOFTWARE\\Policies\\Claude",Zl=5,ka="inferenceGatewayApiKey",$e=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ka],sA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ka],iA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ka],cA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ka],OA="Managed by anyray-connect; dynamic credential only.",k$=e=>/^[A-Za-z]:[\\/]/.test(e)&&b$.isAbsolute(e),lA=e=>{if(!k$(e)||/[\0\r\n"]/u.test(e))return!1;let t=e.replace(/\\/g,"/").toLowerCase();return!/(^|\/)_npx(\/|$)/u.test(t)&&!/\/appdata\/local\/temp(\/|$)/u.test(t)&&!/(^|\/)temp(\/|$)/u.test(t)},RA=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!lA(e.command)||!/\.exe$/iu.test(e.command))throw new Error("the credential helper executable is not durable");if(e.args.length<2||e.args.length>3||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--json"||e.args.length===3&&!lA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},kh=(e={})=>ba((e.home??bh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),C$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},A$=e=>(RA(e),["@echo off",`REM ${OA}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(C$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
216
+ `)),v$=e=>{let t="";for(let n=0;n<e.length;n++){if(e[n]!=="%"){t+=e[n];continue}if(e[n+1]!=="%")return;t+="%",n++}return t},_A=e=>{let t=e.split(`\r
217
+ `);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${OA}`||t[2]!=="setlocal DisableDelayedExpansion"||t[4]!=="exit /b %ERRORLEVEL%"||t[5]!==""||!t[3].startsWith('"')||!t[3].endsWith('"'))return;let r=t[3].slice(1,-1).split('" "').map(v$);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return RA(s),s}catch{return}},S$=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>xA(r)))).every(r=>r.isFile())}catch{return!1}},E$=async(e,t)=>{let n=_A(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??S$)(n)}catch{return!1}},hh=e=>({sha256:lo(e),content:e}),dA=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Bt(t,["sha256","content"])&&L$(t.sha256)&&typeof t.content=="string"&&lo(t.content)===t.sha256&&_A(t.content)!==void 0},Ch=()=>{let e=w$("tasklist.exe",["/FI","IMAGENAME eq Claude.exe","/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0,timeout:2e3,maxBuffer:65536});return e.error||e.signal||e.status!==0?!0:/(?:^|\r?\n)"Claude\.exe",/iu.test(e.stdout??"")},x$=async(e,t)=>{await ph(mi(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await vA(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await wh(n,e)}finally{await an(n,{force:!0}).catch(()=>{})}},I$=e=>`${IA(e)}.anyray-old-`,O$=e=>`${e}.anyray-old-${process.pid}-${AA()}`,PA=async(e,t)=>{try{await wh(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await an(t,{force:!0}),!0},Vl=async(e,t,n,r,o)=>{let a=O$(e),s=n===void 0?void 0:lo(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${AA()}`,c=!1;try{if(i&&n!==void 0){let d=await vA(i,"wx",384);try{await d.writeFile(n,"utf8"),await d.sync()}finally{await d.close()}}await o.helperFileOperationHook?.({operation:r,phase:"before-move",path:e,recoveryPath:a}),await EA(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ga(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await wh(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await wa(e)!==s))throw new Error("credential helper publication verification failed");await an(a,{force:!0}),c=!1}catch(l){throw c&&await PA(e,a).catch(()=>!1),l}finally{i&&await an(i,{force:!0}).catch(()=>{})}},mh=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,R$=String.raw`
218
218
  $ErrorActionPreference = 'Stop'
219
219
  try {
220
220
  $request = ConvertFrom-Json ([Console]::In.ReadToEnd())
@@ -283,29 +283,29 @@ try {
283
283
  exit 5
284
284
  } catch {
285
285
  exit 6
286
- }`,Gn=async e=>new Promise((t,n)=>{let r=p$("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",S$],{windowsHide:!0,stdio:["pipe","pipe","pipe"]}),o="",a=!1,s=!1;r.stdout.setEncoding("utf8"),r.stdout.on("data",i=>{o+=i,o.length>1024*1024&&(a=!0,r.kill())}),r.stderr.resume(),r.on("error",i=>{s||(s=!0,n(new Error(fh(i))))}),r.on("close",(i,c)=>{if(!s){if(s=!0,a){n(new Error("registry query output exceeded the safety limit"));return}if(i===null){n(new Error(fh({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Ht=(e={})=>wa((e.home??gh)(),".anyray","claude-desktop-windows.json"),E$=e=>wa((e.home??gh)(),".anyray","claude-desktop-windows.lock"),ma=class extends Error{},I$=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},kh=async e=>{let t=E$(e);await dh(fi(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=kA("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=wa(t,"owner.json");try{await dh(t,{mode:448}),await pe(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
287
- `)}catch(a){if(a.code!=="EEXIST")throw await an(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await uh(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!I$(i.pid)}catch{try{s=Date.now()-(await EA(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new ma;await an(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await uh(o,"utf8")).nonce===r&&await an(t,{recursive:!0,force:!0})}catch{}}}throw new ma},TA=()=>Object.fromEntries($e.map(e=>[e,{present:!1}])),uo=e=>kA("sha256").update(e).digest("hex"),x$=(e,t)=>t.present?e===ba?{present:!0,type:t.type,sha256:uo(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},fa=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?uo(e.value??"")===t.sha256:e.value===t.value:!0,Wt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Yl=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.present!="boolean"?!1:n.present?n.type!=="REG_SZ"&&n.type!=="REG_EXPAND_SZ"?!1:t===ba?Wt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Wt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},dA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,$e)&&$e.every(t=>Yl(e[t],t)),uA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,aA)&&aA.every(t=>Yl(e[t],t)),R$=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),Ch=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=["path",...n.lastWritten===void 0?[]:["lastWritten"],...n.pending===void 0?[]:["pending"]];return Wt(n,r)&&n.path===wh(t)&&(n.lastWritten===void 0||lA(n.lastWritten))&&(n.pending===void 0||lA(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},O$=(e,t)=>Wt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Vl&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&dA(e.lastWritten)&&(e.pending===void 0||dA(e.pending))&&Ch(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),_$=e=>Wt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&uA(e.lastWritten)&&(e.pending===void 0||uA(e.pending)),pA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,sA)&&sA.every(t=>Yl(e[t],t)),T$=(e,t)=>Wt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&pA(e.lastWritten)&&(e.pending===void 0||pA(e.pending))&&Ch(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),fA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,iA)&&iA.every(t=>Yl(e[t],t)),P$=(e,t)=>Wt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&fA(e.lastWritten)&&(e.pending===void 0||fA(e.pending))&&Ch(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),hA=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),Ah=e=>{let{pending:t,...n}=e;return{...n,version:Vl,lastWritten:hA(e.lastWritten),...t?{pending:hA(t)}:{}}},mA=e=>({...e,chatTabEnabled:{present:!1}}),L$=e=>{let{pending:t,...n}=e;return Ah({...n,version:4,lastWritten:mA(e.lastWritten),...t?{pending:mA(t)}:{}})},yA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),D$=(e,t)=>Ah({version:4,registryKey:Te,keyExisted:e.keyExisted,lastWritten:yA(e.lastWritten),...e.pending?{pending:yA(e.pending)}:{},helper:{path:wh(t)}}),vh=async(e,t=!0)=>{let n=Ht(e),r=fi(n),o=`${IA(n)}.anyray-old-`,a=(await vA(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>wa(r,l)),s=n;if(!await R(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await SA(a[0],n):s=a[0]}let i=await U(s),c=_$(i)?D$(i,e):T$(i,e)?L$(i):P$(i,e)?Ah(i):O$(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>an(l,{force:!0}))),c},gA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),N$=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Te,keyExisted:e.keyExisted,lastWritten:gA(e.lastWritten),...e.pending?{pending:gA(e.pending)}:{}}:e,Kl=async(e,t)=>{let n=Ht(t),r=`${JSON.stringify(N$(e),null,2)}
288
- `;t.writeJournalFile?await t.writeJournalFile(n,r):await pe(n,r)},$$=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,M$=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),F$=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),U$=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),B$=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===U$(t).toUpperCase(),wA=(e,t,n,r,o)=>{let a=$e.find(i=>i.toLowerCase()===t.toLowerCase());if(!a)return!1;let s=n==="String"?"REG_SZ":n==="ExpandString"?"REG_EXPAND_SZ":n;if(s!=="REG_SZ"&&s!=="REG_EXPAND_SZ"){if(o)throw new Error("an owned Claude policy value has an unsupported type");return!1}if(e[a].present)throw new Error("a Claude policy value was returned more than once");return e[a]={present:!0,type:s,value:r},!0},W$=e=>e==="String"?"REG_SZ":e==="ExpandString"?"REG_EXPAND_SZ":e==="DWord"?"REG_DWORD":e==="QWord"?"REG_QWORD":e==="MultiString"?"REG_MULTI_SZ":e==="Binary"?"REG_BINARY":e==="None"?"REG_NONE":e,H$=(e,t)=>{if(!Ml(e,!0))return!1;let n=W$(t);if(F$.has(n))return!1;if(M$.has(n))return n==="REG_EXPAND_SZ"?!0:!DC(e,!0)},K$=(e,t)=>{let n=TA(),r=!1,o=!1,a=!1,s=t.toUpperCase()===pi.toUpperCase(),i=(l,d)=>{if(!s)return;let u=H$(l,d);u===void 0?a=!0:u&&(o=!0)},c=e.trim();if(c.startsWith("{")){let l=JSON.parse(c);if(l.anyrayRegistry!==1||typeof l.key!="string"||l.key.toUpperCase()!==t.toUpperCase()||!Array.isArray(l.values))throw new Error("invalid registry bridge response");for(let d of l.values){if(!d||typeof d!="object"||Array.isArray(d))throw new Error("invalid registry bridge value");let u=d;if(typeof u.name!="string"||typeof u.kind!="string"||typeof u.value!="string")throw new Error("invalid registry bridge value");i(u.name,u.kind),wA(n,u.name,u.kind,u.value,!s)||(r=!0)}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}}for(let l of e.split(/\r?\n/)){let d=l.trim();if(!d||B$(d,t))continue;let u=$$.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),wA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Kn=async(e,t=Te)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:TA(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return K$(n.stdout,t)},vr=async e=>{let t=await Kn(e,pi);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...$e.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},Sh=e=>e.unparsed?`This machine may have a Claude policy under ${pi} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${pi} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${pi} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Zl=(e,t)=>la(co(e,t)),PA=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],G$=(e,t)=>{let n=Zl(e,t);return Object.fromEntries($e.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},j$=(e,t)=>({inferenceProvider:{present:!0,type:"REG_SZ",value:"gateway"},inferenceGatewayBaseUrl:{present:!0,type:"REG_SZ",value:e.anthropicBaseUrl},inferenceGatewayAuthScheme:{present:!0,type:"REG_SZ",value:"bearer"},chatTabEnabled:{present:!1},coworkEgressAllowedHosts:{present:!1},inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},inferenceGatewayApiKey:{present:!0,type:"REG_SZ",value:t}}),V$=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,hh=e=>Object.fromEntries($e.map(t=>[t,x$(t,e[t])])),bA=(e,t,n,r)=>({version:Vl,registryKey:Te,keyExisted:e,lastWritten:hh(t),helper:{path:n,lastWritten:ph(r)}}),Y$=(e,t,n,r,o,a)=>({version:Vl,registryKey:Te,keyExisted:e,lastWritten:hh(t),pending:hh(n),helper:{path:r,...o?{lastWritten:ph(o)}:{},pending:ph(a)}}),mh=(e,t,n)=>fa(n,e.lastWritten[t])||e.pending!==void 0&&fa(n,e.pending[t]),ya=async e=>{try{let t=await uh(e,"utf8");return{content:t,sha256:uo(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ga=async e=>(await ya(e))?.sha256,ha=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,jl=async(e,t)=>{let n=A$(e),r;try{r=await vA(fi(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>wa(fi(e),c));if(o.length===0)return;if(o.length!==1)throw new Error("ambiguous credential helper recovery files");let a=o[0],[s,i]=await Promise.all([ya(e),ya(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ha(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await _A(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ha(t,s.sha256)&&ha(t,i.sha256)){await an(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Eh=async(e,t,n)=>(n.present?await e(PA(Te,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Te,"/v",t,"/f"])).code===0,Z$=async(e,t,n)=>{let r=!0,o=await Kn(e);for(let a of $e)if(!pa(o.values[a],t[a])){if(!pa(o.values[a],n[a])){r=!1;continue}await Eh(e,a,t[a])||(r=!1),o=await Kn(e)}return r&&$e.every(a=>pa(o.values[a],t[a]))},qe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Ht(n)]}}),LA=async(e,t,n,r={})=>{if(!xe(t))return qe("A valid personal ark_ gateway key is required.",!1,r);let o=wh(r),a;try{a=g$((r.credentialCommand??nh)())}catch{return qe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=uo(a),i=r.runReg??Gn,c=Ht(r),l;if(!n.dryRun)try{l=await kh(r)}catch(m){return qe(m instanceof ma?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; the registry was left unchanged.",!1,r)}let d,u,f,p,h=!1;try{let m=await vr(i);if(m)return qe(Sh(m),!1,r);let w=await vh(r,!n.dryRun);n.dryRun||await jl(o,w);let g=await Kn(i),y=G$(e,o),b=await ya(o),A=b?.sha256,v=!1;if(d=w,u=g,f=y,w){let C=$e.find(x=>!mh(w,x,g.values[x]));if(C)return qe(`Claude's ${C} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(A!==void 0&&!ha(w,A))return qe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);v=V$(w)}else{if(A!==void 0&&A!==s)return qe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let C=g.foreignState||$e.some($=>g.values[$].present),x=$e.every($=>pa(g.values[$],y[$])),T=$e.every($=>pa(g.values[$],j$(e,t.trim())[$]));if(C&&!x&&!T)return qe(`Existing Claude third-party-inference policy values under ${Te} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(v=T,x&&A===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Te} into an owner-only journal without rewriting them.`]}:(await Kl(bA(g.keyPresent,y,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Te} into the ownership journal.`]})}if(v){let C=!0;try{C=(r.appRunning??bh)()}catch{}if(C)return qe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=Y$(w?.keyExisted??g.keyPresent,g.values,y,o,b?.content,a);if(p=E,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Te}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Kl(E,r),h=!0;for(let C of $e){let x=await Kn(i);if(!fa(x.values[C],E.lastWritten[C])&&!fa(x.values[C],E.pending[C]))throw new Error("registry value changed during apply");if(!pa(x.values[C],y[C])&&!await Eh(i,C,y[C]))throw new Error("registry write failed")}let I=await Kn(i);if(!$e.every(C=>fa(I.values[C],E.pending[C])))throw new Error("registry verification failed");if(A!==s&&(A===void 0?await C$(o,a):await Gl(o,A,a,"apply",r)),await ga(o)!==s)throw new Error("credential helper verification failed");return await Kl(bA(E.keyExisted,y,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Te}.`,`Installed or updated the dynamic credential helper at ${o}; no personal key is stored in policy or the ownership journal.`,"Fully quit and reopen Claude Desktop to load the policy.",...Dl]}}catch{if(!h||!u||!f||!p)return qe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await jl(o,p);let m=!0,w=await ya(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await Gl(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await ga(o)===p.helper.lastWritten.sha256):await Gl(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await Z$(i,u.values,f))return d?await Kl(d,r):await an(c,{force:!0}),qe("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return qe("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},DA=async(e,t={})=>{let n=t.runReg??Gn,r=Ht(t),o;if(!e.dryRun)try{o=await kh(t)}catch(a){return qe(a instanceof ma?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; no registry value was removed.",!1,t)}try{let a=await vh(t,!e.dryRun);a&&!e.dryRun&&await jl(a.helper.path,a);let s=await Kn(n);if(!a)return $e.filter(h=>s.values[h].present).length>0?qe(`Claude policy values exist under ${Te}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=$e.filter(p=>s.values[p].present&&!mh(a,p,s.values[p])),c=await ga(a.helper.path),l=c!==void 0&&!ha(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Te}.`,`Would remove the Anyray-owned credential helper at ${a.helper.path}.`,...i.length||l?[`Would preserve changed values: ${[...i,...l?["credential helper"]:[]].join(", ")}.`]:[]]};let d=!1,u=new Set(i);for(let p of $e){let m=(await Kn(n)).values[p];if(m.present){if(!mh(a,p,m)){u.add(p);continue}await Eh(n,p,{present:!1})||(d=!0)}}let f=await ga(a.helper.path);if(f!==void 0)if(ha(a,f))try{await Gl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?qe(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await an(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Te}.`,"Removed the Anyray-owned dynamic credential helper when its content still matched the journal.",...u.size?[`Preserved values changed after Connect: ${[...u].join(", ")}.`]:[],...u.size?[]:Nl]})}catch{return qe(`Could not safely inspect or revert ${Te}; no unproven value was removed.`,!1,t)}finally{await o?.()}},NA=async(e,t={})=>{let n=t.runReg??Gn;if(!await R(Ht(t)))return;let r;try{r=await kh(t);let o=await vh(t);if(o&&await jl(o.helper.path,o),!o||o.pending||await vr(n)!==void 0)return;let a=await Kn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ze(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&$e.every(l=>fa(a.values[l],o.lastWritten[l]))))return;let i=await ga(o.helper.path),c=o.helper.lastWritten;return a.values.inferenceCredentialKind.value==="helper-script"&&a.values.inferenceCredentialHelper.value===o.helper.path&&!a.values.inferenceGatewayApiKey.present&&c!==void 0&&i===c.sha256&&await k$(c,t)?"dynamic":o.helper.lastWritten===void 0&&!a.values.inferenceCredentialKind.present&&!a.values.inferenceCredentialHelper.present&&a.values.inferenceGatewayApiKey.present?"legacy-static":void 0}catch{return}finally{await r?.()}},$A=async(e,t={})=>await NA(e,t)!==void 0,MA=async(e,t={})=>await NA(e,t)==="dynamic";var ka=(e=X$())=>e==="win32"?bh:Bl,Ih="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Xl=async(e,t={})=>{let n=(t.profileRoot??io)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Ih};if((t.appRunning??ka(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await FA.access(e)}catch{return{ok:!1,reason:`no such file: ${e}`,remedy:"Point at the .zip Anthropic emailed you (claude.ai -> Settings -> Privacy -> Export data)."}}let r=await Ll(n);if(!r.ok)return r.reason==="ambiguous"?{ok:!1,reason:"this Claude Desktop profile holds more than one account",remedy:"Choosing which one gets the history is your call, not ours \u2014 "+Ih}:{ok:!1,reason:"no Claude Desktop third-party session store found \u2014 the app has not run in this mode yet",remedy:"Open Claude Desktop with Anyray configured, sign in with your usual Claude account, quit it, then run this again."};let o=await(t.findBinary??xC)();if(!o)return{ok:!1,reason:"the Claude Code CLI was not found",remedy:"Install Claude Code (the conversion step uses its importer), then run this again."};let a=Jl(t.stagingRoot??z$(),`anyray-history-${process.pid}-${J$()}`);try{let s=await(t.runImporter??RC)({binary:o,exportPath:e,configDir:Jl(a,"config"),workDir:Jl(a,"work")});if(!s.ok)return{ok:!1,reason:s.reason,remedy:"This step uses an unsupported Claude Code subcommand, so a version change can break it. "+Ih};if(s.conversations.length===0)return{ok:!1,reason:"that export contains no conversations",remedy:"Check you pointed at the export archive itself."};let i=await _C(r.dir,s.conversations),c=await TC({stagedProjectsDir:Jl(a,"work","projects"),storageDir:r.dir,projects:s.projects,now:t.now?.()??Date.now()});return{ok:!0,storageDir:r.dir,...i,projects:c}}finally{await FA.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as xt}from"node:fs";import{homedir as bM}from"node:os";import{join as cn,sep as kM}from"node:path";import{isDeepStrictEqual as ed}from"node:util";import{constants as q$}from"node:fs";import{promises as G}from"node:fs";import{dirname as Ca,isAbsolute as Rh,join as te,relative as zl,resolve as sn,sep as hi}from"node:path";import{randomUUID as td}from"node:crypto";var An=448,mi=384,HA=448,Q$=4,Oh=3e4,KA=5e3,eM=10*6e4,xh=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),dt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yi=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),GA=(e,t)=>{let n=zl(sn(e),sn(t));return n===""||!n.startsWith(`..${hi}`)&&n!==".."&&!Rh(n)},po=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return dt(n)?{raw:t,value:n}:void 0}catch(t){return It(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},It=e=>e instanceof Error&&"code"in e,tM=e=>{try{return process.kill(e,0),!0}catch(t){return It(t)&&t.code==="EPERM"}},jA=e=>e===0?"owner.json":`owner.${e}.json`,ql=async e=>{let t;try{t=await G.readdir(e)}catch{return}let r=t.map(d=>{if(d==="owner.json")return{name:d,generation:0};let u=/^owner\.(\d+)\.json$/.exec(d);if(!u)return;let f=Number(u[1]);return Number.isSafeInteger(f)&&f>0?{name:d,generation:f}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=te(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));dt(d)&&typeof d.pid=="number"&&Number.isSafeInteger(d.pid)&&d.pid>0&&typeof d.nonce=="string"&&d.nonce.length>0&&(a=d.pid,s=d.nonce,typeof d.createdAt=="number"&&Number.isFinite(d.createdAt)&&d.createdAt>=0&&(i=d.createdAt))}catch{}let c=await G.stat(o).then(d=>d.mtimeMs),l=i!==void 0&&i<=Date.now()+6e4?i:c;return{generation:r.generation,pid:a,nonce:s,createdAtMs:l,mtimeMs:c}},VA=e=>{if(e.pid===void 0||!tM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Oh&&t-e.createdAtMs>eM},nM=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(Ca(t),{recursive:!0,mode:An});let n=td(),r,o=!1;try{await G.mkdir(t,{mode:An}),o=!0}catch(i){if(!It(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await ql(t);if(d){if(!VA(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=Oh)return}let l=te(t,jA(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
289
- `,{flag:"wx",mode:mi}),r=l}catch(d){if(It(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await G.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await G.readFile(a,"utf8"));if(!dt(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},KA);return s.unref(),async()=>{clearInterval(s);try{(await ql(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},rM=async(e,t,n)=>{await G.mkdir(Ca(e),{recursive:!0,mode:An});let r=await nM(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!It(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${td()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
290
- `,{mode:mi,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},nd=async(e,t)=>{for(let n=0;n<Q$;n+=1){let r=await po(e);if(!r)return"failed";let o=t(r.value);if(!o||ed(o,r.value))return"unchanged";try{if(await rM(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},UA=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},rd=async e=>{let t=[];for(let n of await UA(e))for(let r of await UA(te(e,n)))t.push(te(e,n,r));return t},oM=e=>Array.isArray(e.skills)?e.skills.filter(t=>dt(t)&&yi(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],aM=async e=>{let t=te(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await rd(t)){let o=await po(te(r,"manifest.json"));if(!o)continue;let a=r.split(hi).at(-1)??"";for(let s of oM(o.value))n.push({account:a,packageDir:r,entry:s})}return n},sM=async e=>{let t=await po(te(e,".claude-plugin","plugin.json"));return!!t&&yi(t.value.name)},iM=(e,t)=>{let n=Rh(t)?sn(t):sn(e,t);if(!GA(e,n)||n===sn(e))return;let r=zl(sn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},cM=async e=>{let t=await rd(te(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(hi).includes("skills-plugin"))continue;let o=te(r,"cowork_plugins"),a=await po(te(o,"installed_plugins.json"));if(!a||!dt(a.value.plugins))continue;let s=r.split(hi).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!yi(i)||!Array.isArray(c)))for(let l of c){if(!dt(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=iM(o,l.installPath);!d||!await sM(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:te(r,"cowork_account_settings.json")})}}return n},lM=async e=>{let t=await po(te(e,"claude_desktop_config.json"));return!t||!dt(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>yi(n)&&n.toLowerCase()!=="anyray"&&dt(r)))},YA=async e=>{let[t,n,r]=await Promise.all([aM(e),cM(e),lM(e)]);return{skills:t,plugins:n,localMcpServers:r}},_h=async e=>{let t=await YA(e);return{skills:t.skills.length,plugins:t.plugins.length,localMcpServers:Object.keys(t.localMcpServers).length,accounts:[...new Set([...t.skills.map(n=>n.account),...t.plugins.map(n=>n.account)])].filter(n=>n.length>0)}},BA=async e=>{try{let n=await G.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())return!1}catch{return!1}let t=async n=>{let r;try{r=await G.readdir(n,{withFileTypes:!0})}catch{return!1}for(let o of r){if(!yi(o.name))return!1;let a=te(n,o.name);if(o.isSymbolicLink())return!1;if(o.isDirectory()){if(!await t(a))return!1}else if(!o.isFile())return!1}return!0};return t(e)},dM=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=te(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,An);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?HA:mi)}}};await t(e),await G.chmod(e,An)},ZA=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},Ql=async(e,t)=>{try{let[n,r]=await Promise.all([G.readdir(e,{withFileTypes:!0}),G.readdir(t,{withFileTypes:!0})]),o=n.map(s=>s.name).sort(),a=r.map(s=>s.name).sort();if(!ed(o,a))return!1;for(let s of o){let i=n.find(l=>l.name===s),c=r.find(l=>l.name===s);if(!i||!c||i.isDirectory()!==c.isDirectory()||i.isFile()!==c.isFile())return!1;if(i.isDirectory()){if(!await Ql(te(e,s),te(t,s)))return!1}else if(!i.isFile()||!await ZA(te(e,s),te(t,s)))return!1}return!0}catch{return!1}},JA=e=>`${e}.anyray-incomplete`,XA=async(e,t)=>{let n=!1;if(t){await G.mkdir(Ca(e),{recursive:!0,mode:An});try{await G.mkdir(e,{mode:An}),n=!0}catch(l){if(!It(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=td(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await ql(e)}catch{return}if(f){if(!VA(f)||!Number.isSafeInteger(f.generation+1))return;d=f.generation+1}else if(await G.stat(e).then(h=>Date.now()-h.mtimeMs).catch(()=>0)<=Oh)return}let u=te(e,jA(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
291
- `,{flag:"wx",mode:mi}),o=u}catch(f){if(It(f)&&f.code==="EEXIST"){n=!1;continue}n&&await G.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await G.readFile(a,"utf8"));if(!dt(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},KA);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await ql(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},zA=async e=>{let t=await XA(e,!1);t&&await t.complete()},uM=async(e,t,n)=>{let r=JA(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Ql(e,t))return await zA(r),"present"}catch(c){if(!It(c)||c.code!=="ENOENT")return"failed"}if(o)try{let c=await G.lstat(r);if(!c.isDirectory()||c.isSymbolicLink())return"conflict"}catch{return"conflict"}let a=await XA(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:An})}catch(c){if(!It(c)||c.code!=="EEXIST")return a.abandon(),"failed";try{let l=await G.lstat(t);if(!l.isDirectory()||l.isSymbolicLink())return await a.complete(),"conflict"}catch{return a.abandon(),"failed"}}let s=async(c,l)=>{let d;try{d=await G.readdir(c,{withFileTypes:!0})}catch{return"failed"}for(let u of d){let f=te(c,u.name),p=te(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(p,{mode:An})}catch(m){if(!It(m)||m.code!=="EEXIST")throw m;let w=await G.lstat(p);if(!w.isDirectory()||w.isSymbolicLink())return"conflict"}let h=await s(f,p);if(h!=="copied")return h}else if(u.isFile())try{await G.copyFile(f,p,q$.COPYFILE_EXCL);let h=await G.stat(f);await G.chmod(p,(h.mode&73)!==0?HA:mi)}catch(h){if(!It(h)||h.code!=="EEXIST")throw h;if(!await ZA(f,p))return"conflict"}else return"failed"}catch(h){return It(h)&&h.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await Ql(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},qA=async(e,t,n,r)=>{if(!await BA(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Ql(e,t))return await zA(JA(t)),"present"}catch(a){if(!It(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(Ca(t),{recursive:!0,mode:An});let o=te(Ca(t),`.anyray-stage-${td()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await BA(o)?(await dM(o),await n?.(t),await uM(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},WA=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),pM=async e=>{let t=await rd(te(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await po(te(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},fM=async e=>{let t=await rd(te(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(hi).includes("skills-plugin"))try{await G.access(te(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},hM=async(e,t,n,r,o)=>{let a=te(t,"manifest.json");for(let s of e){let i=te(s.packageDir,"skills",s.entry.name);try{await G.access(te(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=te(t,"skills",s.entry.name),l=await qA(i,c,r,o);if(l==="conflict"){n.conflicts+=1;continue}if(l==="invalid"){n.invalid+=1;continue}if(l==="failed"){n.failed+=1;continue}let d=!1;await nd(a,f=>{let p=Array.isArray(f.skills)?f.skills:[];if(p.find(m=>dt(m)&&typeof m.name=="string"&&m.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...f,skills:[...p,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},QA=(e,t)=>({...e,installPath:t}),mM=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=Rh(r.installPath)?sn(r.installPath):sn(o,r.installPath),s=QA(e,zl(sn(t),sn(n))),i={...r,installPath:zl(sn(o),a)};return ed(s,i)},yM=async(e,t,n)=>{let r=await po(e);if(!r||!dt(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":nd(t,a=>{let s=dt(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},gM=async(e,t,n,r,o)=>{let a=te(t,"cowork_plugins"),s=te(a,"installed_plugins.json"),i=te(t,"cowork_account_settings.json");for(let c of e){let l=te(a,c.relativeInstallPath);if(!GA(a,l)){n.invalid+=1;continue}let d=await qA(c.packageDir,l,r,o);if(d==="conflict"){n.conflicts+=1;continue}if(d==="invalid"){n.invalid+=1;continue}if(d==="failed"){n.failed+=1;continue}let u=!1,f=!1;await nd(s,h=>{let m=dt(h.plugins)?h.plugins:{},w=m[c.id],g=Array.isArray(w)?w:[],y=g.find(A=>dt(A)&&A.scope==="user");if(y){u=mM(c.entry,Ca(c.settingsFile),c.packageDir,y,t),f=!u;return}let b=QA(c.entry,l);return{...h,version:typeof h.version=="number"?h.version:2,plugins:{...m,[c.id]:[...g,b]}}})==="failed"?n.failed+=1:f?n.conflicts+=1:await yM(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},wM=async(e,t,n)=>{let r=te(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await nd(r,c=>{let l=dt(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=ed(l[o],a)?"present":"conflict";return}return{...c,mcpServers:{...l,[o]:a}}})==="failed"?n.failed+=1:s.value==="present"?n.alreadyPresent+=1:s.value==="conflict"?n.conflicts+=1:n.migrated+=1}},ev=async(e,t,n={})=>{let r=await YA(e),o=xh("skill"),a=xh("plugin"),s=xh("local-mcp"),i=[],c=[],l=WA(r.skills,n.account,n.allAccounts),d=WA(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let f=new Set(n.allowedAccounts);if([...new Set([...l.map(h=>h.account),...d.map(h=>h.account)])].some(h=>!f.has(h)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,sourceChanged:!0,retryable:[]}}if(l.length>0){let f=await pM(t);f.state==="found"?await hM(l,f.path,o,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("skill"):(o.conflicts+=l.length,c.push("skill"))}if(d.length>0){let f=await fM(t);f.state==="found"?await gM(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await wM(r.localMcpServers,t,s);let u=[o,a,s];return{outcomes:u,blocked:i,ambiguous:c,sourceChanged:!1,retryable:u.filter(f=>f.failed>0).map(f=>f.kind)}};var CM=async e=>{try{return await xt.access(e),!0}catch{return!1}},tv=448,AM=384,rv={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},vM=["code","cowork"],Lh=(e,t,n,r=!1)=>r?"Claude Desktop has not been set up on Anyray yet \u2014 run `anyray-connect desktop` first, then open Claude Desktop once and fully quit it.":e==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${t} store, so which one to fill is your call \u2014 re-run \`${n}\` with \`--account <id>\`.`:t==="cowork"?"Open Claude Desktop, sign in, and open the Cowork tab once \u2014 that is what creates the store \u2014 then fully quit it and run this again.":"Open Claude Desktop, sign in, and start a Claude Code session once \u2014 that is what creates the store \u2014 then fully quit it and run this again.",Th=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),ov=async e=>{let t;try{t=(await xt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&ia(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await xt.readdir(cn(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&ia(a.name)).map(a=>a.name);for(let a of o)n.push(cn(e,r,a))}catch{}return n},SM=async e=>{try{return(await xt.readdir(e)).filter(t=>t.startsWith(Wn)&&t.endsWith(".json")).map(t=>t.slice(Wn.length,-5)).filter(ia)}catch{return[]}},EM=async(e,t)=>{let n=await ov(cn(e,rv[t])),r=[];for(let o of n){let a=await SM(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(kM).slice(-2)[0]})}return r},IM=async(e,t)=>{if(t==="cowork"){let r=await Ll(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await ov(cn(e,rv.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},xM=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await xt.copyFile(e,n),await xt.chmod(n,AM),await xt.rename(n,t)},RM=async(e,t)=>{try{let n=JSON.parse(await xt.readFile(e,"utf8"));if(!n||typeof n!="object")return!1;let{cwd:r,cliSessionId:o}=n;return typeof r!="string"||typeof o!="string"||r.length===0||!ia(o)?!1:(await xt.access(cn(t,".claude","projects",Xf(r),`${o}.jsonl`)),!0)}catch{return!1}},OM=async(e,t,n,r)=>{let o=Th(e),a=await zf(n);for(let s of t)await _M(e,s,n,r,a,o);return o},_M=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Wn}${s}.json`,c=cn(t.dir,i);try{if(e==="code"){if(!await RM(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=cn(t.dir,`${Wn}${s}`),d=cn(n,`${Wn}${s}`),u=await xt.readdir(l);await xt.mkdir(d,{mode:tv});for(let f of u)await xt.cp(cn(l,f),cn(d,f),{recursive:!0,force:!1,errorOnExist:!0});await xt.chmod(d,tv)}await xM(c,cn(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},nv=(e,t,n,r=[])=>{let o=new Map;for(let{sources:s}of e)for(let i of s){let c=o.get(i.account)??{sessions:0,portable:!1};c.sessions+=i.ids.length,o.set(i.account,c)}for(let s of r){let i=o.get(s)??{sessions:0,portable:!1};i.portable=!0,o.set(s,i)}let a=[...o.entries()].sort((s,i)=>i[1].sessions-s[1].sessions).map(([s,i])=>{let c=i.sessions===0?"portable configuration":`${i.sessions} session${i.sessions===1?"":"s"}${i.portable?" plus portable configuration":""}`;return` ${t} --account ${s.slice(0,8)} (${c})`});return{ok:!1,kind:"account-ambiguous",reason:n,remedy:["Pick the one you want, or take everything:",...a,` ${t} --all-accounts`].join(`
292
- `)}},Ph=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),av=async e=>{let t=[];for(let n of vM)t.push({lane:n,sources:await EM(e,n)});return t},sv=async(e={})=>{let t=(e.firstPartyRoot??(()=>ni()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([av(t),_h(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Ph(n);for(let s of r.accounts)a.add(s);return{sessions:o,accounts:a.size,userSkills:r.skills,userPlugins:r.plugins,localMcpServers:r.localMcpServers}},fo=async(e={})=>{let t=(e.home??bM)(),n=(e.firstPartyRoot??(()=>ni()))(),r=(e.thirdPartyRoot??(()=>io()))();if(!n||!r)return{ok:!1,kind:"platform-unsupported",reason:"this platform has no Claude Desktop third-party profile",remedy:"Migration applies to macOS and Windows, where Desktop runs third-party mode in its own profile."};if((e.appRunning??ka())())return{ok:!1,kind:"app-running",reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop and run this again \u2014 it rewrites its session list on exit, which would undo the migration."};let[o,a]=await Promise.all([av(n),_h(n)]),s;if(e.account){let p=e.account;for(let w of o)w.sources=w.sources.filter(g=>g.account.startsWith(p));let h=a.accounts.filter(w=>w.startsWith(p));if(o.every(w=>w.sources.length===0)&&h.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${p}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let m=Ph(o);for(let w of h)m.add(w);if(m.size>1)return nv(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=Ph(o);for(let h of a.accounts)p.add(h);if(p.size>1)return nv(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${p.size} accounts`,a.accounts);s=[...p]}let i=e.command??"anyray-connect desktop --migrate",c=!await CM(r),l=await ev(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:s});if(l.sourceChanged)return{ok:!1,kind:"account-ambiguous",reason:"the previous Claude Desktop profile changed during migration and now holds local data for another account",remedy:`Re-run \`${i}\` so the account choice is made from a fresh snapshot.`};let d=[],u=[];for(let{lane:p,sources:h}of o){if(h.length===0){d.push(Th(p));continue}let m=await IM(r,p);if("missing"in m){u.push({lane:p,reason:m.missing,waiting:h.reduce((w,g)=>w+g.ids.length,0)}),d.push(Th(p));continue}d.push(await OM(p,h,m.dir,t))}if(!(d.some(p=>p.migrated>0||p.alreadyPresent>0)||l.outcomes.some(p=>p.migrated>0||p.alreadyPresent>0||p.conflicts>0))&&(u.length>0||l.blocked.length>0)){let p=u[0];return p?{ok:!1,kind:p.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:p.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${p.lane} store`:`Claude Desktop has no ${p.lane} store in its third-party profile yet`,remedy:Lh(p.reason,p.lane,i,c)}:{ok:!1,kind:"store-missing",reason:"Claude Desktop's third-party profile has no extension store yet",remedy:"Open Claude Desktop once after connecting it to Anyray, then fully quit it so the portable extensions can be copied safely."}}return{ok:!0,lanes:d,portableAssets:l.outcomes,...u.length>0?{blocked:u}:{},...l.blocked.length>0?{blockedAssets:l.blocked}:{},...l.ambiguous.length>0?{ambiguousAssets:l.ambiguous}:{},...l.retryable.length>0?{retryableAssets:l.retryable}:{}}};var TM=e=>[ot(e)],iv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...TM(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await R(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var cv="1.21459.0",NM=DM(PM),$M=async e=>{try{let{stdout:t}=await NM("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},MM=async e=>{try{return await LM(e)}catch{return}},lv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",FM=["Admin policy setup (no JSON): open Developer \u2192 Configure Third-Party Inference; the Anyray connection is already filled in.",'Add approved remote MCP connectors under "Connectors & extensions" and use "Test this connection"; add approved Git marketplaces under "Plugins & skills".',`Choose "Apply locally" to test. For Jamf, first select IT's fleet-wide credential-helper path, then choose Export \u2192 .mobileconfig and deploy the complete profile.`,"If Claude Desktop is already MDM-managed, this window is read-only. Author and export on an unmanaged admin Mac, then redeploy through Jamf."],Aa=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(dv??=uv({}),dv):uv(e),dv,uv=async e=>{let t=(e.home??wi)(),n=["/Applications/Claude.app",vn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??$M,o=e.readClaudeAppBundle??MM;for(let a of n){let s=await r(vn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${lv}`}),c=Tl(s,cv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${cv} or newer.`);let l=await o(vn(a,"Contents","Resources","app.asar"));return l?YC.some(d=>!l.includes(d))?i("its local config seam no longer matches the shape Connect writes."):{supported:!0,detectedVersion:s,appPath:a}:i("its app bundle could not be read to verify the local config seam.")}return{supported:!1,message:`Could not verify the installed Claude Desktop version. ${lv}`}},od="anyray",hv="--anyray-owner=claude-desktop-v1",ad=(e={})=>{let t=(e.platform??Sr)(),n=(e.home??wi)();return t==="darwin"?on(e).appConfig:t==="win32"?vn(process.env.APPDATA??vn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):vn(n,".config","Claude","claude_desktop_config.json")},Fh=(e={})=>vn((e.home??wi)(),"Library","Application Support","Claude","claude_desktop_config.json"),mv=()=>{let e=Ve("profile");return{command:e.command,args:[...e.args,hv]}},ho=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),yv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},UM=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),BM=e=>{if(!ho(e)||!yv(e,["command","args"]))return!1;let t=mv();return e.command===t.command&&UM(e.args,t.args)},WM=e=>ho(e)&&Array.isArray(e.args)&&e.args.at(-1)===hv,HM=e=>{if(!ho(e)||!yv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||je(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===or&&t.at(-1)==="profile"))return!1;let r=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(r))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(r)||t.length!==3)return!1;let o=t[0].replaceAll("\\","/");return!je(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},KM=e=>e===void 0?"absent":BM(e)?"exact":WM(e)||HM(e)?"stale-owned":"foreign",He=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},mo=async e=>{let t=await R(e),n;try{n=await U(e)}catch{throw new He(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!ho(n.mcpServers))throw new He(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(ho(n.mcpServers)?n.mcpServers:void 0)?.[od];return{path:e,fileExisted:t,json:n,entry:o,ownership:KM(o)}},sd=e=>{if(e.ownership==="foreign")throw new He(`MCP name conflict in ${e.path}: mcpServers.${od} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},gv=(e,t)=>{let n={...e},r=ho(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[od]:r[od]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Nh=async(e,t)=>{if(Dh(e.entry,t))return;let n=await mo(e.path);if(!Dh(n.entry,e.entry))throw new He(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Hn(e.path,gv(n.json,t)),{reading:e,afterEntry:t}},$h=async e=>{let t=await mo(e.reading.path);if(!Dh(t.entry,e.afterEntry))throw new He(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=gv(t.json,e.reading.entry);await Hn(e.reading.path,n)},GM=async e=>{if(!le())throw new He(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Oe()} is temporary); no inference setting was changed.`);let t=await mo(ad(e));sd(t);let n=Fh(e),r=(e.platform??Sr)()==="darwin"&&n!==t.path?await mo(n):void 0;return r&&sd(r),{active:t,...r?{legacy:r}:{}}},pv=async e=>{let t=await mo(ad(e));sd(t);let n=Fh(e),r=(e.platform??Sr)()==="darwin"&&n!==t.path?await mo(n):void 0;return r&&sd(r),{active:t,...r?{legacy:r}:{}}},jM=async e=>{let t=[];try{let n=await Nh(e.active,mv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Nh(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await $h(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new He(`Claude Desktop MCP setup failed and could not restore ${r.join(", ")}. Re-run \`anyray-connect desktop disconnect\` to recover safely.`,r):n}return{changedFiles:t.map(n=>n.reading.path),async rollback(){let n=[];for(let r of[...t].reverse())await $h(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new He(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},VM=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Nh(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await $h(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new He(`Claude Desktop MCP cleanup failed and could not restore ${r.join(", ")}. Re-run revert after resolving the file conflict.`,r):n}return t.map(n=>n.reading.path)},fv=e=>{let t=e.clientKey?`${e.clientKey} (your personal gateway key - keep it private)`:`${e.placeholderKey} (placeholder - the gateway holds the real key)`;return["Step 1 - Turn on Developer Mode."," In the menu bar at the VERY TOP of the screen (NOT the in-app help panel):"," Help -> Troubleshooting -> Enable Developer Mode"," (Windows: open the menu at the top-left of the sign-in screen.)",' A "Developer" menu then appears in that same top-of-screen menu bar.',"","Step 2 - Open the Developer MENU in the menu bar (shown below) - NOT Settings:",""," +----------------------------------------------------------------+"," | Claude File Edit View Window [Developer] Help | <- macOS menu bar (very top of screen)"," +-------------------------------------^--------------------------+"," |",' click Developer -> "Configure Third-Party Inference..."',"",' Heads up: use the "Developer" MENU in the bar above - NOT',' Settings -> Developer, which is the "Local MCP servers" pane'," (that's where Anyray's retrieval server appears, not inference)."," A separate setup window then opens.","","Step 3 - In that window's Connection section, paste:",""," Inference provider: Gateway",` Gateway base URL: ${e.anthropicBaseUrl}`," Auth scheme: Bearer",` API key: ${t}`,"",'Step 4 - Click "Apply locally", then fully quit and reopen Claude'," (the config is read once at launch).","","Billing: this route uses an Anyray gateway credential and provider/API billing, not a Claude subscription allowance.","Fleet/MDM: generate a managed profile with `anyray-connect desktop claude --mobileconfig` (applies with no Developer Mode and no paste)."]},YM={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},id="claude-desktop",Mh="migrate",wv=new Set(["app-running","store-missing"]),ZM={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},JM={skill:{one:"user-created skill",many:"user-created skills"},plugin:{one:"user-installed plugin",many:"user-installed plugins"},"local-mcp":{one:"local MCP server",many:"local MCP servers"}},XM="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",bv=e=>{let t=(e.platform??Sr)(),n=e.home??wi;return{home:n,appRunning:e.appRunning??ka(t),firstPartyRoot:()=>ni({home:n,runtimePlatform:t}),thirdPartyRoot:()=>io({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},kv=e=>{let t=e.filter(a=>a.migrated>0);if(t.length===0)return;let n=e.reduce((a,s)=>a+s.skippedNoTranscript,0),r=e.reduce((a,s)=>a+s.failed,0);return`Brought your existing Claude Desktop sessions into its third-party profile: ${t.map(a=>{let s=ZM[a.lane];return`${a.migrated} ${a.migrated===1?s.one:s.many}`}).join(", ")}.`+(n>0?` ${n} skipped \u2014 the transcript is no longer on disk.`:"")+(r>0?` ${r} could not be copied.`:"")},Cv=e=>{let t=e.filter(s=>s.migrated>0),n=e.reduce((s,i)=>s+i.conflicts,0),r=e.reduce((s,i)=>s+i.invalid,0),o=e.reduce((s,i)=>s+i.failed,0);if(t.length===0&&n+r+o===0)return;let a=t.map(s=>{let i=JM[s.kind];return`${s.migrated} ${s.migrated===1?i.one:i.many}`});return(a.length>0?`Brought your portable Claude Desktop configuration across: ${a.join(", ")}.`:"Portable Claude Desktop configuration was checked; existing target entries were kept.")+(n>0?` ${n} conflicting target ${n===1?"entry was":"entries were"} preserved.`:"")+(r>0?` ${r} unsafe or incomplete ${r===1?"entry was":"entries were"} skipped.`:"")+(o>0?` ${o} could not be copied.`:"")},gi=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=bv(e),r=await(e.pendingDesktopMigrationCount??sv)(n),o=r.userSkills+r.userPlugins+r.localMcpServers;if(r.sessions+o===0)return[];if(t.dryRun)return[`Would bring ${[r.sessions>0?`${r.sessions} existing Claude Desktop session${r.sessions===1?"":"s"}`:"",o>0?`${o} portable configuration ${o===1?"entry":"entries"}`:""].filter(Boolean).join(" and ")} into Claude Desktop's third-party profile, now or automatically the next time Claude Desktop is fully quit.`];let a=await(e.migrateDesktopProfile??fo)(n);if(a.ok){let c=kv(a.lanes),l=Cv(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(a.blocked??[]).filter(y=>y.reason!=="ambiguous"),p=a.blockedAssets??[],h=a.retryableAssets??[];if(f.length===0&&p.length===0&&h.length===0)return[c,l,u].filter(y=>!!y);if(t.preservePendingOp)return[c,l,u].filter(y=>!!y);await Ls(id,Mh);let m=f.reduce((y,b)=>y+b.waiting,0),w=[m>0?`${m} more session${m===1?"":"s"}`:"",p.length>0?`${p.length} extension ${p.length===1?"store":"stores"}`:""].filter(Boolean),g=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...h.length>0?[`Queued: ${h.length} portable configuration ${h.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...g]}if(!wv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
293
- ${a.remedy}`];if(t.preservePendingOp)return[];await Ls(id,Mh);let s=r.sessions+o,i=`${s} Claude Desktop local ${s===1?"item":"items"}`;return[a.kind==="store-missing"?`Queued: the ${i} still in your previous profile move across once Claude Desktop's new profile has been signed in to and the app is fully quit.`:`Queued: the ${i} still in your previous profile will move across the next time you fully quit Claude Desktop.`]}catch{return["Could not check whether Claude Desktop had existing sessions to bring across; run `anyray-connect migrate` if its lists look empty."]}},zM=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await fr(id),[]}catch{return["Could not clear Claude Desktop's queued profile-migration marker; a background watcher may still be waiting for the app to quit. Delete it by hand if it persists."]}},qM=e=>iv({id,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Sr)(),n=(e.home??wi)();return t==="darwin"?["/Applications/Claude.app",vn(n,"Applications","Claude.app")]:t==="win32"?[vn(process.env.LOCALAPPDATA??vn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>X(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",...fv(t)]:["Claude desktop org/API lane:",...fv(t),"This Gateway route uses provider/API billing. On verified macOS builds, subscription mode instead installs the Keychain-backed Claude Code credential helper automatically."],revertMessages:["Claude Desktop third-party inference: switch back to the first-party Claude provider in Developer settings (or remove the managed profile). Native setup is restored automatically by `--revert`."]}),QM=(e={})=>{let t=qM(e),n=()=>(e.platform??Sr)()==="darwin",r=()=>(e.platform??Sr)()==="win32",o=(s,i)=>n()?tA(s,i,e):LA(s,s.clientKey??"",i,e),a=s=>n()?nA(s,e):DA(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ka((e.platform??Sr)()))(),quitTarget:YM,needsTarget:()=>!1,async complete(s){if(s!==Mh)return{status:"manual",messages:[`Claude Desktop could not service a queued "${s}" operation it does not recognise; the queue entry was dropped.`]};let i=await(e.migrateDesktopProfile??fo)(bv(e));if(i.ok){let c=kv(i.lanes),l=Cv(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let f=(i.blocked??[]).filter(m=>m.reason!=="ambiguous"),p=i.blockedAssets??[],h=i.retryableAssets??[];return f.length>0||p.length>0||h.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...f.length>0||p.length>0?["Still waiting on Claude Desktop to create the remaining third-party stores, which appear the first time those parts of the app are opened."]:[],...h.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(m=>!!m):["No portable Claude Desktop data was left to bring across."]}}return wv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?oA(s,e):r()?MA(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=on(e),p=await lo(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[ih(p),...await gi(e,i)]}}if(r()){let f;try{f=await vr(e.runReg??Gn)}catch{return{status:"manual",manualAudience:"admin",messages:[XM,...await gi(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[Sh(f),...await gi(e,i)]}}if(r()&&X(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let f=await Aa(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await GM(e)}catch(f){let p=f instanceof He?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof He?f.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no inference setting was changed."]}}let l=await o(s,{dryRun:!0});if(l.status!=="configured")return l;if(i.dryRun){let f=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...f&&f.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${f.path}.`]:[],...await gi(e,i)]}}let d;try{d=await jM(c)}catch(f){let p=f instanceof He?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof He?f.message:"Could not safely register Claude Desktop retrieval; the inference route was left unchanged."]}}let u;try{u=await o(s,{dryRun:!1})}catch{u={status:"manual",messages:["Claude Desktop inference setup failed before it returned a result."]}}if(u.status!=="configured")try{return await d.rollback(),{...u,changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])],messages:[...u.messages,"Restored the prior Claude Desktop MCP registration because inference setup did not complete. A config file that was absent before setup may remain as an inert object to avoid racing unrelated concurrent writes."]}}catch{return{status:"manual",changedFiles:[...u.changedFiles??[],...d.changedFiles],messages:[...u.messages,"Inference setup did not complete, and the prior MCP registration could not be fully restored. Re-run `anyray-connect desktop disconnect` to recover safely."]}}return{...u,messages:[...u.messages,"Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) with an ownership marker.",...await gi(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?FM:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=ad(e),c=await zM(s),l=m=>c.length===0?m:{...m,messages:[...m.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await pv(e)}catch(m){return l({status:"manual",messages:[m instanceof He?m.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let m=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...m&&m.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${m.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let m=r()?Ht(e):void 0;if(!(m!==void 0&&f.changedFiles?.includes(m)===!0&&!await R(m)))return l(f)}let p;try{p=await VM(await pv(e))}catch(m){let w=m instanceof He?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof He?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await ae(i);let h=Fh(e);return n()&&h!==i&&await ae(h),l({...f,messages:[...f.messages,...p.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...p])]})},async mcpStatus(){if(!le())return{registered:!1,command:null};try{let s=await mo(ad(e));return s.ownership!=="exact"||!ho(s.entry)?{registered:!1,command:null}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null}}},async pointsAt(s){return n()?(await Aa(e)).supported?lh(s,e):!1:r()?$A(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await Aa(e)).supported)return["unknown"];let s=await rA(e);return s?[s]:["unknown"]}if(r())return await R(Ht(e))?await vr(e.runReg??Gn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=on(e);return!await R(s.journal)||await lo(s,e)?!1:(await Aa(e)).supported}return r()&&await R(Ht(e))?!await vr(e.runReg??Gn):!1}catch{return!1}}}},Av=QM();import{homedir as xF}from"node:os";import{join as RF}from"node:path";import{rm as yd}from"node:fs/promises";import{constants as vv,accessSync as eF,statSync as tF}from"node:fs";import{platform as Uh}from"node:os";import{delimiter as nF,posix as rF,resolve as oF,win32 as aF}from"node:path";var sF="0.59.0",iF="1.1.4",jn="Anyray \xB7 Claude",Vn="Anyray \xB7 Codex",cd="__anyray-acp-agent",Sv=(e,t,n)=>{let{command:r,args:o}=un([cd,e,t,n]);return{command:r,args:o,env:{}}},ld=(e=Uh())=>e==="win32"?"npx.cmd":"npx",dd=(e=process.env.PATH,t=Uh())=>{if(!e)return;let n=ld(t);for(let r of e.split(nF)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=oF(o,n);try{if(!tF(a).isFile())continue;return eF(a,t==="win32"?vv.F_OK:vv.X_OK),a}catch{}}},ud=(e,t=Uh())=>{let n=t==="win32"?aF:rF;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==ld(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},cF="https://chatgpt.com/backend-api/codex",lF="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Ev="ANYRAY_ACP_CODEX_AUTHORIZATION",Iv="ANYRAY_ACP_CODEX_CLIENT_KEY",xv="ANYRAY_ACP_CODEX_METADATA",Rv=e=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),dF=(e,t={})=>{let n=X(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":cF,"x-anyray-forward-headers":lF}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Iv}:{}}:{Authorization:Ev};return Rv(e)&&(o["x-anyray-metadata"]=xv),{model_provider:"anyray",model_providers:{anyray:{name:"Anyray Gateway",base_url:e.openaiBaseUrl,wire_api:"responses",...n?{requires_openai_auth:!0}:{},http_headers:r,env_http_headers:o}},...t.mcpServer?{mcp_servers:{anyray:{command:t.mcpServer.command,args:t.mcpServer.args}}}:{}}},uF=e=>{let t=X(e,"openai"),n=Rv(e);return{...t?e.clientKey?{[Iv]:e.clientKey}:{}:{[Ev]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[xv]:n}:{}}},Ov=(e,t=ld(),n={})=>({[jn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${sF}`],env:pn(e).env},[Vn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${iF}`],env:{CODEX_CONFIG:JSON.stringify(dF(e,n)),...uF(e)}}}),bi=(e=ld(),t="jetbrains")=>({[jn]:Sv("claude",e,t),[Vn]:Sv("codex",e,t)}),yo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as pF}from"node:zlib";import{open as fF,readFile as Gh,readdir as md}from"node:fs/promises";import{dirname as _v,join as ue}from"node:path";import{homedir as Dv,platform as jh}from"node:os";var fd="2025.3.2",va="253.30387.147",ki="com.intellij.ml.llm",Bh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),hF=1e4,mF=256*1024*1024,yF=16*1024*1024,Wh=1024*1024,Hh=22,gF=Hh+65535,Kh=Tl,wF=()=>{let e=Dv(),t=ue(e,".cache","JetBrains","RemoteDev");switch(jh()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:ue(e,"Applications"),layout:"app-bundles"},{path:ue(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:ue(process.env.LOCALAPPDATA??ue(e,"AppData","Local"),"Programs"),layout:"children"},{path:ue(process.env.LOCALAPPDATA??ue(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:ue(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:ue(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},bF=()=>jh()==="linux"?ue(Dv(),".local","share","JetBrains"):ot("JetBrains"),kF=()=>jh()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),CF=async(e,t=hF)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await md(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=ue(r.path,i.name),l=r.layout==="app-bundles"?ue(c,"Contents","Resources","product-info.json"):ue(c,"product-info.json");await R(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=ue(s,"product-info.json"),l=ue(s,"Contents","Resources","product-info.json");if(await R(c)){n.push(c);return}if(await R(l)){n.push(l);return}let d;try{d=await md(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=ue(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(f,i-1)}};await a(r.path,7)}return[...new Set(n)]},AF=e=>{let t=_v(e);return t.endsWith(`${ue("Contents","Resources")}`)?_v(t):t},vF=async e=>{try{let t=JSON.parse(await Gh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!ei(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:AF(e)}}catch{return}},hd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},SF=async(e,t)=>{let n;try{n=await fF(e,"r");let{size:r}=await n.stat();if(r<Hh||r>mF)return;let o=Math.min(r,gF),a=await hd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Hh;u>=0;u-=1)if(a.readUInt32LE(u)===101010256){s=u;break}if(s<0)return;let i=a.readUInt32LE(s+12),c=a.readUInt32LE(s+16);if(i>yF||c+i>r)return;let l=await hd(n,i,c);if(!l)return;let d=0;for(;d+46<=l.length;){if(l.readUInt32LE(d)!==33639248)return;let u=l.readUInt16LE(d+10),f=l.readUInt32LE(d+20),p=l.readUInt32LE(d+24),h=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),g=l.readUInt32LE(d+42),y=d+46+h+m+w;if(y>l.length)return;let b=l.subarray(d+46,d+46+h).toString("utf8");if(d=y,b!==t)continue;if(f===4294967295||p===4294967295||f>Wh||p>Wh)return;let A=await hd(n,30,g);if(!A||A.readUInt32LE(0)!==67324752)return;let v=A.readUInt16LE(26),E=A.readUInt16LE(28),I=await hd(n,f,g+30+v+E);return I?u===0?I.toString("utf8"):u===8?pF(I,{maxOutputLength:Wh}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},Tv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!ei(n)))return{id:t,version:n}},EF=async(e,t)=>{let n=ue(e,"META-INF","plugin.xml");if(await R(n))try{let o=Tv(await Gh(n,"utf8"));return{present:o?.id===ki||t,descriptor:o?.id===ki?o:void 0}}catch{return{present:t}}let r=[];try{r=(await md(ue(e,"lib"),{withFileTypes:!0})).filter(o=>o.isFile()&&o.name.endsWith(".jar")&&/(?:^|[-_.])(ml-?llm|llm|aia|ai[-_.]?assistant)(?:[-_.]|$)/i.test(o.name)).slice(0,32).map(o=>ue(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await SF(o,"META-INF/plugin.xml"),s=a?Tv(a):void 0;if(s?.id===ki)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Pv=async e=>{let t;try{t=await md(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Bh.has(o.name.toLowerCase()),i=Bh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Bh.has(o.name.toLowerCase());if(!a){let i=ue(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await EF(ue(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},IF=async e=>{try{return(await Gh(ue(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(ki)}catch{return!1}},Lv=e=>e.reduce((t,n)=>t?(Kh(n,t)??-1)>0?n:t:n,void 0),Nv=async(e={})=>{let t=e.configRoot??ot("JetBrains"),n=e.userPluginsRoot??bF(),r=await CF(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):wF(),e.scanBudget),o=(await Promise.all(r.map(h=>vF(h)))).filter(h=>h!==void 0),a=o.length>0||await R(t);if(e.wsl??kF())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(h=>(Kh(h.version,fd)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let h of s){let m=ue(t,h.dataDirectoryName);if(!await R(m)){d=!0;continue}let w=[ue(m,"plugins"),ue(n,h.dataDirectoryName),ue(n,h.dataDirectoryName,"plugins")],g;for(let y of[...new Set(w)]){let b=await Pv(y);if(b.present){g=b;break}}if(g??=await Pv(ue(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==ki)){if(i.push(g.descriptor.version),await IF(m)){c=!0;continue}if(!((Kh(g.descriptor.version,va)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${h.version}; AI Assistant ${g.descriptor.version}; ACP supported`,ideVersion:h.version,pluginVersion:g.descriptor.version}}}let u=Lv(o.map(h=>h.version)),f=Lv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${fd}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${fd}+ once, enable AI Assistant ${va}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${va}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${va}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${va}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${va}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${fd}+ from local product-info.json; no ACP config was written.`:p="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:p,ideVersion:u,pluginVersion:f}};var OF=[jn,Vn],Vh=()=>RF(xF(),".jetbrains","acp.json"),go=()=>`${Vh()}.anyray-state`,_F=(e,t,n="npx")=>{let r=yo(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,bi(n,"jetbrains")),{...e,agent_servers:r}},TF=(e,t,n)=>{if(!yo(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=yo(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of OF)if(c in r){if(!pd(r[c],n[c])){s.push(c);continue}c in o?r[c]=o[c]:delete r[c],a.push(c)}let i={...e};return Object.keys(r).length>0?i.agent_servers=r:delete i.agent_servers,{next:i,removed:a,conflicts:s}},PF=(e=Nv)=>({id:"jetbrains",title:"JetBrains AI Assistant",automatic:!0,async detect(){let t=await e();return{installed:t.installed,detail:t.detail}},async apply(t,n){let r=Vh(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=dd();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await R(r),c;try{c=await U(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=bi(a,"jetbrains");return await cc({configPath:r,current:c,next:_F(c,t,a),journalPath:go(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,go()]}},async revert(t){let n=Vh(),r=async()=>{if(!await R(n))return t.dryRun||(await ae(n),await yd(go(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await U(n)}catch{return t.dryRun||(await ae(n),await yd(go(),{force:!0}).catch(()=>{})),{status:"manual",messages:[`Could not parse ${n}; remove the two \u201CAnyray \xB7 \u2026\u201D agent entries manually.`]}}let a={},s=!1,i=!1;try{let u=await U(go());(u.version===1||u.version===2)&&yo(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await R(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await U(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Fr(n);let l=TF(o,c,a),d=[];return l.removed.length&&d.push(`Removed ${l.removed.join(", ")} from ${n}.`),l.conflicts.length&&d.push(`Preserved user-modified ACP entries: ${l.conflicts.join(", ")}.`),!t.dryRun&&l.removed.length&&(s&&Object.keys(l.next).length===0?await yd(n,{force:!0}):await J(n,l.next,{backup:!1})),t.dryRun||(await ae(n),await yd(go(),{force:!0}).catch(()=>{})),{status:l.conflicts.length?"manual":"reverted",messages:d.length?d:["No Anyray ACP entries found."],changedFiles:!t.dryRun&&l.removed.length?[n]:void 0}};return t.dryRun?r():ic(n,go(),r)}}),$v=PF();import{homedir as wd}from"node:os";import{join as bd}from"node:path";import{rm as Yh}from"node:fs/promises";var Zh="1.0.0",kd=["anyray-claude-acp","anyray-codex-acp"],LF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Jh=()=>bd(wd(),".windsurf","acp","registry.json"),Xh=()=>bd(wd(),".windsurf-next","acp","registry.json"),Sa=e=>`${e}.anyray-state`,Mv=e=>({binary:Object.fromEntries(LF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Uv=(e="npx")=>{let t=bi(e,"windsurf");return[{id:kd[0],name:jn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Mv(t[jn])},{id:kd[1],name:Vn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Mv(t[Vn])}]},gd=e=>!Array.isArray(e)||e.some(t=>!yo(t)||typeof t.id!="string")?null:e,DF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Zh||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:gd(e.agents);if(!n)return null;let r=new Set(kd);return{...e,version:typeof e.version=="string"?e.version:Zh,agents:[...n.filter(o=>!r.has(o.id)),...Uv(t)],extensions:e.extensions??[]}},NF=(e,t,n)=>{let r=gd(e.agents);if(!r)return null;let o=gd(t.agents)??[],a=new Map((gd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!kd.includes(u.id)){l.push(u);continue}if(!pd(u,a.get(u.id))){c.push(u.id),l.push(u);continue}let f=s.get(u.id);f&&l.push(f),i.push(u.id)}let d={...e,agents:l};return!Object.prototype.hasOwnProperty.call(t,"agents")&&l.length===0&&delete d.agents,!Object.prototype.hasOwnProperty.call(t,"version")&&d.version===Zh&&delete d.version,!Object.prototype.hasOwnProperty.call(t,"extensions")&&Array.isArray(d.extensions)&&d.extensions.length===0&&delete d.extensions,{next:d,removed:i,conflicts:c}},Fv=async()=>{let e=[];return(await R(Xh())||await R(bd(wd(),".windsurf-next")))&&e.push(Xh()),(await R(Jh())||await R(bd(wd(),".windsurf"))||await R(ot("Devin"))||await R(ot("Windsurf")))&&e.push(Jh()),e},Bv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Fv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Fv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=dd();if(!r)return{status:"manual",messages:["Devin ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP registry was written."]};let o=[],a=[];for(let s of n){let i;try{i=await U(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=DF(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await R(s),d=Uv(r);await cc({configPath:s,current:i,next:c,journalPath:Sa(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Sa(s))}}return o.push("Devin requires a one-time vendor UI enablement for local registry agents: Devin Settings \u2192 Agents \u2192 enable the two Anyray agents, then restart Devin Desktop."),o.push("Native Devin/Cascade subscription requests are not redirected. The official enterprise consumption connector imports content-free usage instead."),o.push("No proxy, certificate, DNS, DEVIN_API_URL, or private first-party endpoint was changed."),{status:"manual",messages:o,changedFiles:a.length?a:void 0}},async revert(e){let t=[Jh(),Xh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await ae(a),await Yh(Sa(a),{force:!0}).catch(()=>{}));return}let i;try{i=await U(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let p=await U(Sa(a));(p.version===1||p.version===2)&&Array.isArray(p.agents)&&(c=p.agents,l=p.version===2&&p.fileExisted===!1,d=p.version===2&&p.fileExisted===!0)}catch{}let u;if(d){let p=`${a}.anyray-bak`;if(!await R(p)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await U(p)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await Fr(a);let f=NF(i,u,c);if(!f){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}f.removed.length&&(n.push(`Removed ${f.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(f.next).length===0?await Yh(a,{force:!0}):await J(a,f.next,{backup:!1}),r.push(a))),f.conflicts.length?(n.push(`Preserved user-modified agents: ${f.conflicts.join(", ")}.`),o=!0):e.dryRun||(await ae(a),await Yh(Sa(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await ic(a,Sa(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var se=[sr,jw,Fs,Dk,rC,yC,IC,$v,Av,Bv,eb],Kt=e=>se.find(t=>t.id===e);var $F=["hook_registration","mcp_registration","hook_binary","beacon_target"],wo=e=>e.status==="configured"||e.status==="queued",bo=async(e,t=se)=>{let n=new Set(e),r=[];for(let o of t)if(n.has(o.id))try{(await o.detect()).installed&&r.push(o)}catch{}return r},Er=async(e,t,n=se)=>{let r=[];for(let o of await bo(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},zh=async(e,t=se)=>{let n=[];for(let r of await bo(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries($F.map(o=>[o,"unreadable"]))})}return n},Wv=e=>e.filter(t=>!t.integrationStatus),MF=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},yt=async(e,t)=>{let n=[];for(let r of e)try{let o=await r.apply(t,{dryRun:!1});n.push({id:r.id,title:r.title,status:o.status})}catch(o){let a=MF(o);if(r.classifyApplyError)try{a=r.classifyApplyError(o)}catch{}n.push({id:r.id,title:r.title,status:"failed",errorClass:a})}return n};import{mkdir as VF,writeFile as YF}from"node:fs/promises";import{join as Zv}from"node:path";import{z as Me}from"zod";var FF=["HTTPS_PROXY","https_proxy"],Hv=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_UNTRUSTED"]),Kv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Gv=new Set(["ENOTFOUND","EAI_AGAIN"]),jv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Vv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),UF=e=>{let t=e;for(let n=0;n<5&&t;n++){let r=t.code;if(typeof r=="string"&&r)return r;t=t.cause}return BF(e)},BF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...Hv,...Kv,...Gv,...jv,...Vv])if(t.includes(n))return n}},WF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",HF=e=>FF.filter(t=>(e[t]??"").trim()!==""),KF=(e,t=process.env)=>{let n=UF(e),r=HF(t);return{kind:n&&Hv.has(n)?"tls-unknown-issuer":n&&Kv.has(n)?"tls-invalid-cert":n&&Gv.has(n)?"dns":WF(e)||n&&Vv.has(n)?"timeout":n&&jv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},GF=e=>{let t=e.proxyVars.length>0?` ${e.proxyVars.join(" and ")} ${e.proxyVars.length>1?"are":"is"} set \u2014 if that proxy is stale or unreachable, unset it and re-run.`:"";switch(e.kind){case"tls-unknown-issuer":return` (TLS certificate signed by an unknown authority: ${e.code}). Your network appears to inspect TLS traffic. curl trusts your system keychain and this binary does not, which is why the download worked and this step did not. Point NODE_EXTRA_CA_CERTS at your organization root certificate (PEM) and re-run.`+t;case"tls-invalid-cert":return` (TLS certificate rejected: ${e.code}). Check this machine's clock and date, and whether a proxy is rewriting HTTPS traffic, then re-run.`+t;case"dns":return` (DNS lookup failed: ${e.code}). Check your VPN or DNS, then re-run.`+t;case"refused":return` (connection failed: ${e.code}).`+(t||" Check your network or firewall, then re-run.");case"timeout":return" (timed out before the control plane answered)."+(t||" Check your connection and re-run.");default:return e.code?` (${e.code}).${t}`:t}},gt=(e,t=process.env)=>GF(KF(e,t));var Ea="required",jF=e=>e==="subscription"?"subscription":"placeholder",Yv=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?jF(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}:{}}},Cd=(e,t,n)=>{let r=new Set(t.enabled??[]),o=e.managedTools??[],a=o.filter(u=>r.has(u)||n),s=new Set(e.revertedTools??[]),i=e.revertedTools!=null,c=u=>t.tiers?.[u]??Ea,l=[],d=[];for(let u of r){if(o.includes(u))continue;let f=c(u);if(f!=="optional"){if(f!=="locked"){if(!i)continue;if(s.has(u)){f==="required"&&d.push(u);continue}}l.push(u)}}return{candidateIds:a,freshIds:l,tombstonedIds:d}};var ZF=1e4,JF=1,XF=Me.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),zF=Me.object({id:XF,name:Me.string().min(1),version:Me.string().min(1),body:Me.string()}),qF=Me.object({version:Me.literal(JF).optional(),skills:Me.array(zF),updatedAt:Me.string().min(1).optional(),routing:Me.object({origin:Me.string().min(1)}).optional(),team:Me.string().min(1).optional(),lane:Me.enum(["subscription","org"]).optional().catch(void 0),tools:Me.object({enabled:Me.array(Me.string().min(1)),tiers:Me.record(Me.string().min(1),Me.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),QF=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",Ad=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",vd=async(e,t,n={})=>{let r=n.timeoutMs??ZF,o=`${e}/connect/policy`,a=new AbortController,s=setTimeout(()=>a.abort(),r),i;try{i=await fetch(o,{method:"GET",headers:{"x-anyray-api-key":t},signal:a.signal})}catch(l){let d=l instanceof Error&&l.name==="AbortError"?` no response within ${r}ms.`:gt(l);throw new Error(`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Error(`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch(l){let d=new Error("team policy fetch failed: the gateway returned a malformed response");throw d.name=Ad(l),d}return qF.parse(c)},Jv=/^[a-z0-9][a-z0-9-]{0,31}$/,Xv=64,eU=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>Jv.test(o)).slice(0,Xv).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>Jv.test(o)).slice(0,Xv).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},Ci=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??Ea)==="locked":!1},Sd=async(e,t={})=>{let n=t.loadProfile??L,r=t.saveProfile??re,o=t.targetFromProfile??_e,a=t.adapters??se,s=t.repairTools??yt,i=t.recordManaged??Qn,c=await n(),l={...c},d=Yv(c,{routingOrigin:e.routing?.origin?dn(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:u,teamUpdated:f,laneUpdated:p}=d;(u||f||p)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),d.authMode!=null&&(l.authMode=d.authMode),await r(l));let h=Cd(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f||p),{candidateIds:m,freshIds:w}=h,g=0,y=0,b=0;if(m.length>0||w.length>0){let E=await o(async()=>l);if(E){let I;if(u||f||p){let T=new Set(m);I=[];for(let $ of a)if(T.has($.id))try{(await $.detect()).installed&&I.push($)}catch{}}else I=await Er(m,E.toolOrigin,a);let C=new Set(w),x=[];for(let T of a)if(C.has(T.id))try{(await T.detect()).installed&&x.push(T)}catch{}if(g=I.length+x.length,g>0){let T=await s([...I,...x],E.target);y=T.filter(wo).length;let $=T.filter(Y=>C.has(Y.id));if(b=$.filter(wo).length,$.length>0)try{await i($,!1)}catch{}}}}let A=eU(e),v=await n();if(JSON.stringify(A??null)!==JSON.stringify(v.fleetToolPolicy??null)){let{fleetToolPolicy:E,...I}=v;await r({...I,...A?{fleetToolPolicy:A}:{}})}return{routingUpdated:u,teamUpdated:f,laneUpdated:p,toolsRequested:g,toolsApplied:y,toolsEnrolled:b,toolsTombstoned:h.tombstonedIds,profileUpdated:u||f||p}},zv=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!QF(i.id))continue;if(o[i.id]=i.version,n[i.id]===i.version){s+=1,r.push({id:i.id,name:i.name,version:i.version,written:!1,files:[]});continue}let l=[];for(let d of t){let u=Zv(d,i.id),f=Zv(u,"SKILL.md");await VF(u,{recursive:!0}),await YF(f,tU(i.body),"utf-8"),l.push(f)}a+=1,r.push({id:i.id,name:i.name,version:i.version,written:!0,files:l})}return{results:r,changed:a,unchanged:s,versions:o,updatedAt:e.updatedAt}},tU=e=>e.endsWith(`
286
+ }`,Vn=async e=>new Promise((t,n)=>{let r=g$("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",R$],{windowsHide:!0,stdio:["pipe","pipe","pipe"]}),o="",a=!1,s=!1;r.stdout.setEncoding("utf8"),r.stdout.on("data",i=>{o+=i,o.length>1024*1024&&(a=!0,r.kill())}),r.stderr.resume(),r.on("error",i=>{s||(s=!0,n(new Error(mh(i))))}),r.on("close",(i,c)=>{if(!s){if(s=!0,a){n(new Error("registry query output exceeded the safety limit"));return}if(i===null){n(new Error(mh({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Wt=(e={})=>ba((e.home??bh)(),".anyray","claude-desktop-windows.json"),_$=e=>ba((e.home??bh)(),".anyray","claude-desktop-windows.lock"),ya=class extends Error{},P$=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Ah=async e=>{let t=_$(e);await ph(mi(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=CA("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=ba(t,"owner.json");try{await ph(t,{mode:448}),await pe(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
287
+ `)}catch(a){if(a.code!=="EEXIST")throw await an(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await fh(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!P$(i.pid)}catch{try{s=Date.now()-(await xA(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new ya;await an(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await fh(o,"utf8")).nonce===r&&await an(t,{recursive:!0,force:!0})}catch{}}}throw new ya},TA=()=>Object.fromEntries($e.map(e=>[e,{present:!1}])),lo=e=>CA("sha256").update(e).digest("hex"),T$=(e,t)=>t.present?e===ka?{present:!0,type:t.type,sha256:lo(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},ha=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?lo(e.value??"")===t.sha256:e.value===t.value:!0,Bt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Xl=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.present!="boolean"?!1:n.present?n.type!=="REG_SZ"&&n.type!=="REG_EXPAND_SZ"?!1:t===ka?Bt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Bt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},uA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,$e)&&$e.every(t=>Xl(e[t],t)),pA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,sA)&&sA.every(t=>Xl(e[t],t)),L$=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),vh=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=["path",...n.lastWritten===void 0?[]:["lastWritten"],...n.pending===void 0?[]:["pending"]];return Bt(n,r)&&n.path===kh(t)&&(n.lastWritten===void 0||dA(n.lastWritten))&&(n.pending===void 0||dA(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},D$=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Zl&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&uA(e.lastWritten)&&(e.pending===void 0||uA(e.pending))&&vh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),N$=e=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&pA(e.lastWritten)&&(e.pending===void 0||pA(e.pending)),fA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,iA)&&iA.every(t=>Xl(e[t],t)),$$=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&fA(e.lastWritten)&&(e.pending===void 0||fA(e.pending))&&vh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),hA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,cA)&&cA.every(t=>Xl(e[t],t)),M$=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&hA(e.lastWritten)&&(e.pending===void 0||hA(e.pending))&&vh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),mA=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),Sh=e=>{let{pending:t,...n}=e;return{...n,version:Zl,lastWritten:mA(e.lastWritten),...t?{pending:mA(t)}:{}}},yA=e=>({...e,chatTabEnabled:{present:!1}}),F$=e=>{let{pending:t,...n}=e;return Sh({...n,version:4,lastWritten:yA(e.lastWritten),...t?{pending:yA(t)}:{}})},gA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),U$=(e,t)=>Sh({version:4,registryKey:_e,keyExisted:e.keyExisted,lastWritten:gA(e.lastWritten),...e.pending?{pending:gA(e.pending)}:{},helper:{path:kh(t)}}),Eh=async(e,t=!0)=>{let n=Wt(e),r=mi(n),o=`${IA(n)}.anyray-old-`,a=(await SA(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>ba(r,l)),s=n;if(!await O(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await EA(a[0],n):s=a[0]}let i=await U(s),c=N$(i)?U$(i,e):$$(i,e)?F$(i):M$(i,e)?Sh(i):D$(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>an(l,{force:!0}))),c},wA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),B$=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:_e,keyExisted:e.keyExisted,lastWritten:wA(e.lastWritten),...e.pending?{pending:wA(e.pending)}:{}}:e,jl=async(e,t)=>{let n=Wt(t),r=`${JSON.stringify(B$(e),null,2)}
288
+ `;t.writeJournalFile?await t.writeJournalFile(n,r):await pe(n,r)},W$=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,H$=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),K$=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),G$=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),j$=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===G$(t).toUpperCase(),bA=(e,t,n,r,o)=>{let a=$e.find(i=>i.toLowerCase()===t.toLowerCase());if(!a)return!1;let s=n==="String"?"REG_SZ":n==="ExpandString"?"REG_EXPAND_SZ":n;if(s!=="REG_SZ"&&s!=="REG_EXPAND_SZ"){if(o)throw new Error("an owned Claude policy value has an unsupported type");return!1}if(e[a].present)throw new Error("a Claude policy value was returned more than once");return e[a]={present:!0,type:s,value:r},!0},V$=e=>e==="String"?"REG_SZ":e==="ExpandString"?"REG_EXPAND_SZ":e==="DWord"?"REG_DWORD":e==="QWord"?"REG_QWORD":e==="MultiString"?"REG_MULTI_SZ":e==="Binary"?"REG_BINARY":e==="None"?"REG_NONE":e,Y$=(e,t)=>{if(!Ul(e,!0))return!1;let n=V$(t);if(K$.has(n))return!1;if(H$.has(n))return n==="REG_EXPAND_SZ"?!0:!NC(e,!0)},Z$=(e,t)=>{let n=TA(),r=!1,o=!1,a=!1,s=t.toUpperCase()===hi.toUpperCase(),i=(l,d)=>{if(!s)return;let u=Y$(l,d);u===void 0?a=!0:u&&(o=!0)},c=e.trim();if(c.startsWith("{")){let l=JSON.parse(c);if(l.anyrayRegistry!==1||typeof l.key!="string"||l.key.toUpperCase()!==t.toUpperCase()||!Array.isArray(l.values))throw new Error("invalid registry bridge response");for(let d of l.values){if(!d||typeof d!="object"||Array.isArray(d))throw new Error("invalid registry bridge value");let u=d;if(typeof u.name!="string"||typeof u.kind!="string"||typeof u.value!="string")throw new Error("invalid registry bridge value");i(u.name,u.kind),bA(n,u.name,u.kind,u.value,!s)||(r=!0)}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}}for(let l of e.split(/\r?\n/)){let d=l.trim();if(!d||j$(d,t))continue;let u=W$.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),bA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},jn=async(e,t=_e)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:TA(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return Z$(n.stdout,t)},Sr=async e=>{let t=await jn(e,hi);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...$e.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},xh=e=>e.unparsed?`This machine may have a Claude policy under ${hi} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${hi} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${hi} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Jl=(e,t)=>da(io(e,t)),LA=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],X$=(e,t)=>{let n=Jl(e,t);return Object.fromEntries($e.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},J$=(e,t)=>({inferenceProvider:{present:!0,type:"REG_SZ",value:"gateway"},inferenceGatewayBaseUrl:{present:!0,type:"REG_SZ",value:e.anthropicBaseUrl},inferenceGatewayAuthScheme:{present:!0,type:"REG_SZ",value:"bearer"},chatTabEnabled:{present:!1},coworkEgressAllowedHosts:{present:!1},inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},inferenceGatewayApiKey:{present:!0,type:"REG_SZ",value:t}}),q$=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,yh=e=>Object.fromEntries($e.map(t=>[t,T$(t,e[t])])),kA=(e,t,n,r)=>({version:Zl,registryKey:_e,keyExisted:e,lastWritten:yh(t),helper:{path:n,lastWritten:hh(r)}}),z$=(e,t,n,r,o,a)=>({version:Zl,registryKey:_e,keyExisted:e,lastWritten:yh(t),pending:yh(n),helper:{path:r,...o?{lastWritten:hh(o)}:{},pending:hh(a)}}),gh=(e,t,n)=>ha(n,e.lastWritten[t])||e.pending!==void 0&&ha(n,e.pending[t]),ga=async e=>{try{let t=await fh(e,"utf8");return{content:t,sha256:lo(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},wa=async e=>(await ga(e))?.sha256,ma=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Yl=async(e,t)=>{let n=I$(e),r;try{r=await SA(mi(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>ba(mi(e),c));if(o.length===0)return;if(o.length!==1)throw new Error("ambiguous credential helper recovery files");let a=o[0],[s,i]=await Promise.all([ga(e),ga(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ma(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await PA(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ma(t,s.sha256)&&ma(t,i.sha256)){await an(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Ih=async(e,t,n)=>(n.present?await e(LA(_e,t,n.value??"",n.type??"REG_SZ")):await e(["delete",_e,"/v",t,"/f"])).code===0,Q$=async(e,t,n)=>{let r=!0,o=await jn(e);for(let a of $e)if(!fa(o.values[a],t[a])){if(!fa(o.values[a],n[a])){r=!1;continue}await Ih(e,a,t[a])||(r=!1),o=await jn(e)}return r&&$e.every(a=>fa(o.values[a],t[a]))},Qe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Wt(n)]}}),DA=async(e,t,n,r={})=>{if(!xe(t))return Qe("A valid personal ark_ gateway key is required.",!1,r);let o=kh(r),a;try{a=A$((r.credentialCommand??oh)())}catch{return Qe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=lo(a),i=r.runReg??Vn,c=Wt(r),l;if(!n.dryRun)try{l=await Ah(r)}catch(m){return Qe(m instanceof ya?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; the registry was left unchanged.",!1,r)}let d,u,f,p,h=!1;try{let m=await Sr(i);if(m)return Qe(xh(m),!1,r);let w=await Eh(r,!n.dryRun);n.dryRun||await Yl(o,w);let g=await jn(i),y=X$(e,o),b=await ga(o),A=b?.sha256,v=!1;if(d=w,u=g,f=y,w){let C=$e.find(I=>!gh(w,I,g.values[I]));if(C)return Qe(`Claude's ${C} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(A!==void 0&&!ma(w,A))return Qe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);v=q$(w)}else{if(A!==void 0&&A!==s)return Qe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let C=g.foreignState||$e.some($=>g.values[$].present),I=$e.every($=>fa(g.values[$],y[$])),P=$e.every($=>fa(g.values[$],J$(e,t.trim())[$]));if(C&&!I&&!P)return Qe(`Existing Claude third-party-inference policy values under ${_e} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(v=P,I&&A===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${_e} into an owner-only journal without rewriting them.`]}:(await jl(kA(g.keyPresent,y,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${_e} into the ownership journal.`]})}if(v){let C=!0;try{C=(r.appRunning??Ch)()}catch{}if(C)return Qe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=z$(w?.keyExisted??g.keyPresent,g.values,y,o,b?.content,a);if(p=E,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${_e}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await jl(E,r),h=!0;for(let C of $e){let I=await jn(i);if(!ha(I.values[C],E.lastWritten[C])&&!ha(I.values[C],E.pending[C]))throw new Error("registry value changed during apply");if(!fa(I.values[C],y[C])&&!await Ih(i,C,y[C]))throw new Error("registry write failed")}let x=await jn(i);if(!$e.every(C=>ha(x.values[C],E.pending[C])))throw new Error("registry verification failed");if(A!==s&&(A===void 0?await x$(o,a):await Vl(o,A,a,"apply",r)),await wa(o)!==s)throw new Error("credential helper verification failed");return await jl(kA(E.keyExisted,y,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${_e}.`,`Installed or updated the dynamic credential helper at ${o}; no personal key is stored in policy or the ownership journal.`,"Fully quit and reopen Claude Desktop to load the policy.",...$l]}}catch{if(!h||!u||!f||!p)return Qe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Yl(o,p);let m=!0,w=await ga(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await Vl(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await wa(o)===p.helper.lastWritten.sha256):await Vl(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await Q$(i,u.values,f))return d?await jl(d,r):await an(c,{force:!0}),Qe("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return Qe("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},NA=async(e,t={})=>{let n=t.runReg??Vn,r=Wt(t),o;if(!e.dryRun)try{o=await Ah(t)}catch(a){return Qe(a instanceof ya?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; no registry value was removed.",!1,t)}try{let a=await Eh(t,!e.dryRun);a&&!e.dryRun&&await Yl(a.helper.path,a);let s=await jn(n);if(!a)return $e.filter(h=>s.values[h].present).length>0?Qe(`Claude policy values exist under ${_e}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=$e.filter(p=>s.values[p].present&&!gh(a,p,s.values[p])),c=await wa(a.helper.path),l=c!==void 0&&!ma(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${_e}.`,`Would remove the Anyray-owned credential helper at ${a.helper.path}.`,...i.length||l?[`Would preserve changed values: ${[...i,...l?["credential helper"]:[]].join(", ")}.`]:[]]};let d=!1,u=new Set(i);for(let p of $e){let m=(await jn(n)).values[p];if(m.present){if(!gh(a,p,m)){u.add(p);continue}await Ih(n,p,{present:!1})||(d=!0)}}let f=await wa(a.helper.path);if(f!==void 0)if(ma(a,f))try{await Vl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?Qe(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await an(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${_e}.`,"Removed the Anyray-owned dynamic credential helper when its content still matched the journal.",...u.size?[`Preserved values changed after Connect: ${[...u].join(", ")}.`]:[],...u.size?[]:Ml]})}catch{return Qe(`Could not safely inspect or revert ${_e}; no unproven value was removed.`,!1,t)}finally{await o?.()}},$A=async(e,t={})=>{let n=t.runReg??Vn;if(!await O(Wt(t)))return;let r;try{r=await Ah(t);let o=await Eh(t);if(o&&await Yl(o.helper.path,o),!o||o.pending||await Sr(n)!==void 0)return;let a=await jn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Xe(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&$e.every(l=>ha(a.values[l],o.lastWritten[l]))))return;let i=await wa(o.helper.path),c=o.helper.lastWritten;return a.values.inferenceCredentialKind.value==="helper-script"&&a.values.inferenceCredentialHelper.value===o.helper.path&&!a.values.inferenceGatewayApiKey.present&&c!==void 0&&i===c.sha256&&await E$(c,t)?"dynamic":o.helper.lastWritten===void 0&&!a.values.inferenceCredentialKind.present&&!a.values.inferenceCredentialHelper.present&&a.values.inferenceGatewayApiKey.present?"legacy-static":void 0}catch{return}finally{await r?.()}},MA=async(e,t={})=>await $A(e,t)!==void 0,FA=async(e,t={})=>await $A(e,t)==="dynamic";var Ca=(e=tM())=>e==="win32"?Ch:Hl,Oh="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",zl=async(e,t={})=>{let n=(t.profileRoot??so)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Oh};if((t.appRunning??Ca(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await UA.access(e)}catch{return{ok:!1,reason:`no such file: ${e}`,remedy:"Point at the .zip Anthropic emailed you (claude.ai -> Settings -> Privacy -> Export data)."}}let r=await Nl(n);if(!r.ok)return r.reason==="ambiguous"?{ok:!1,reason:"this Claude Desktop profile holds more than one account",remedy:"Choosing which one gets the history is your call, not ours \u2014 "+Oh}:{ok:!1,reason:"no Claude Desktop third-party session store found \u2014 the app has not run in this mode yet",remedy:"Open Claude Desktop with Anyray configured, sign in with your usual Claude account, quit it, then run this again."};let o=await(t.findBinary??OC)();if(!o)return{ok:!1,reason:"the Claude Code CLI was not found",remedy:"Install Claude Code (the conversion step uses its importer), then run this again."};let a=ql(t.stagingRoot??nM(),`anyray-history-${process.pid}-${eM()}`);try{let s=await(t.runImporter??RC)({binary:o,exportPath:e,configDir:ql(a,"config"),workDir:ql(a,"work")});if(!s.ok)return{ok:!1,reason:s.reason,remedy:"This step uses an unsupported Claude Code subcommand, so a version change can break it. "+Oh};if(s.conversations.length===0)return{ok:!1,reason:"that export contains no conversations",remedy:"Check you pointed at the export archive itself."};let i=await PC(r.dir,s.conversations),c=await TC({stagedProjectsDir:ql(a,"work","projects"),storageDir:r.dir,projects:s.projects,now:t.now?.()??Date.now()});return{ok:!0,storageDir:r.dir,...i,projects:c}}finally{await UA.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as It}from"node:fs";import{homedir as SM}from"node:os";import{join as cn,sep as EM}from"node:path";import{isDeepStrictEqual as nd}from"node:util";import{constants as rM}from"node:fs";import{promises as G}from"node:fs";import{dirname as Aa,isAbsolute as _h,join as te,relative as Ql,resolve as sn,sep as yi}from"node:path";import{randomUUID as rd}from"node:crypto";var vn=448,gi=384,KA=448,oM=4,Ph=3e4,GA=5e3,aM=10*6e4,Rh=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),dt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wi=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),jA=(e,t)=>{let n=Ql(sn(e),sn(t));return n===""||!n.startsWith(`..${yi}`)&&n!==".."&&!_h(n)},uo=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return dt(n)?{raw:t,value:n}:void 0}catch(t){return xt(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},xt=e=>e instanceof Error&&"code"in e,sM=e=>{try{return process.kill(e,0),!0}catch(t){return xt(t)&&t.code==="EPERM"}},VA=e=>e===0?"owner.json":`owner.${e}.json`,ed=async e=>{let t;try{t=await G.readdir(e)}catch{return}let r=t.map(d=>{if(d==="owner.json")return{name:d,generation:0};let u=/^owner\.(\d+)\.json$/.exec(d);if(!u)return;let f=Number(u[1]);return Number.isSafeInteger(f)&&f>0?{name:d,generation:f}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=te(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));dt(d)&&typeof d.pid=="number"&&Number.isSafeInteger(d.pid)&&d.pid>0&&typeof d.nonce=="string"&&d.nonce.length>0&&(a=d.pid,s=d.nonce,typeof d.createdAt=="number"&&Number.isFinite(d.createdAt)&&d.createdAt>=0&&(i=d.createdAt))}catch{}let c=await G.stat(o).then(d=>d.mtimeMs),l=i!==void 0&&i<=Date.now()+6e4?i:c;return{generation:r.generation,pid:a,nonce:s,createdAtMs:l,mtimeMs:c}},YA=e=>{if(e.pid===void 0||!sM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Ph&&t-e.createdAtMs>aM},iM=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(Aa(t),{recursive:!0,mode:vn});let n=rd(),r,o=!1;try{await G.mkdir(t,{mode:vn}),o=!0}catch(i){if(!xt(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await ed(t);if(d){if(!YA(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=Ph)return}let l=te(t,VA(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
289
+ `,{flag:"wx",mode:gi}),r=l}catch(d){if(xt(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await G.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await G.readFile(a,"utf8"));if(!dt(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},GA);return s.unref(),async()=>{clearInterval(s);try{(await ed(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},cM=async(e,t,n)=>{await G.mkdir(Aa(e),{recursive:!0,mode:vn});let r=await iM(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!xt(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${rd()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
290
+ `,{mode:gi,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},od=async(e,t)=>{for(let n=0;n<oM;n+=1){let r=await uo(e);if(!r)return"failed";let o=t(r.value);if(!o||nd(o,r.value))return"unchanged";try{if(await cM(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},BA=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},ad=async e=>{let t=[];for(let n of await BA(e))for(let r of await BA(te(e,n)))t.push(te(e,n,r));return t},lM=e=>Array.isArray(e.skills)?e.skills.filter(t=>dt(t)&&wi(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],dM=async e=>{let t=te(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await ad(t)){let o=await uo(te(r,"manifest.json"));if(!o)continue;let a=r.split(yi).at(-1)??"";for(let s of lM(o.value))n.push({account:a,packageDir:r,entry:s})}return n},uM=async e=>{let t=await uo(te(e,".claude-plugin","plugin.json"));return!!t&&wi(t.value.name)},pM=(e,t)=>{let n=_h(t)?sn(t):sn(e,t);if(!jA(e,n)||n===sn(e))return;let r=Ql(sn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},fM=async e=>{let t=await ad(te(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(yi).includes("skills-plugin"))continue;let o=te(r,"cowork_plugins"),a=await uo(te(o,"installed_plugins.json"));if(!a||!dt(a.value.plugins))continue;let s=r.split(yi).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!wi(i)||!Array.isArray(c)))for(let l of c){if(!dt(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=pM(o,l.installPath);!d||!await uM(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:te(r,"cowork_account_settings.json")})}}return n},hM=async e=>{let t=await uo(te(e,"claude_desktop_config.json"));return!t||!dt(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>wi(n)&&n.toLowerCase()!=="anyray"&&dt(r)))},ZA=async e=>{let[t,n,r]=await Promise.all([dM(e),fM(e),hM(e)]);return{skills:t,plugins:n,localMcpServers:r}},Th=async e=>{let t=await ZA(e);return{skills:t.skills.length,plugins:t.plugins.length,localMcpServers:Object.keys(t.localMcpServers).length,accounts:[...new Set([...t.skills.map(n=>n.account),...t.plugins.map(n=>n.account)])].filter(n=>n.length>0)}},WA=async e=>{try{let n=await G.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())return!1}catch{return!1}let t=async n=>{let r;try{r=await G.readdir(n,{withFileTypes:!0})}catch{return!1}for(let o of r){if(!wi(o.name))return!1;let a=te(n,o.name);if(o.isSymbolicLink())return!1;if(o.isDirectory()){if(!await t(a))return!1}else if(!o.isFile())return!1}return!0};return t(e)},mM=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=te(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,vn);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?KA:gi)}}};await t(e),await G.chmod(e,vn)},XA=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},td=async(e,t)=>{try{let[n,r]=await Promise.all([G.readdir(e,{withFileTypes:!0}),G.readdir(t,{withFileTypes:!0})]),o=n.map(s=>s.name).sort(),a=r.map(s=>s.name).sort();if(!nd(o,a))return!1;for(let s of o){let i=n.find(l=>l.name===s),c=r.find(l=>l.name===s);if(!i||!c||i.isDirectory()!==c.isDirectory()||i.isFile()!==c.isFile())return!1;if(i.isDirectory()){if(!await td(te(e,s),te(t,s)))return!1}else if(!i.isFile()||!await XA(te(e,s),te(t,s)))return!1}return!0}catch{return!1}},JA=e=>`${e}.anyray-incomplete`,qA=async(e,t)=>{let n=!1;if(t){await G.mkdir(Aa(e),{recursive:!0,mode:vn});try{await G.mkdir(e,{mode:vn}),n=!0}catch(l){if(!xt(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=rd(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await ed(e)}catch{return}if(f){if(!YA(f)||!Number.isSafeInteger(f.generation+1))return;d=f.generation+1}else if(await G.stat(e).then(h=>Date.now()-h.mtimeMs).catch(()=>0)<=Ph)return}let u=te(e,VA(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
291
+ `,{flag:"wx",mode:gi}),o=u}catch(f){if(xt(f)&&f.code==="EEXIST"){n=!1;continue}n&&await G.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await G.readFile(a,"utf8"));if(!dt(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},GA);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await ed(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},zA=async e=>{let t=await qA(e,!1);t&&await t.complete()},yM=async(e,t,n)=>{let r=JA(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await td(e,t))return await zA(r),"present"}catch(c){if(!xt(c)||c.code!=="ENOENT")return"failed"}if(o)try{let c=await G.lstat(r);if(!c.isDirectory()||c.isSymbolicLink())return"conflict"}catch{return"conflict"}let a=await qA(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:vn})}catch(c){if(!xt(c)||c.code!=="EEXIST")return a.abandon(),"failed";try{let l=await G.lstat(t);if(!l.isDirectory()||l.isSymbolicLink())return await a.complete(),"conflict"}catch{return a.abandon(),"failed"}}let s=async(c,l)=>{let d;try{d=await G.readdir(c,{withFileTypes:!0})}catch{return"failed"}for(let u of d){let f=te(c,u.name),p=te(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(p,{mode:vn})}catch(m){if(!xt(m)||m.code!=="EEXIST")throw m;let w=await G.lstat(p);if(!w.isDirectory()||w.isSymbolicLink())return"conflict"}let h=await s(f,p);if(h!=="copied")return h}else if(u.isFile())try{await G.copyFile(f,p,rM.COPYFILE_EXCL);let h=await G.stat(f);await G.chmod(p,(h.mode&73)!==0?KA:gi)}catch(h){if(!xt(h)||h.code!=="EEXIST")throw h;if(!await XA(f,p))return"conflict"}else return"failed"}catch(h){return xt(h)&&h.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await td(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},QA=async(e,t,n,r)=>{if(!await WA(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await td(e,t))return await zA(JA(t)),"present"}catch(a){if(!xt(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(Aa(t),{recursive:!0,mode:vn});let o=te(Aa(t),`.anyray-stage-${rd()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await WA(o)?(await mM(o),await n?.(t),await yM(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},HA=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),gM=async e=>{let t=await ad(te(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await uo(te(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},wM=async e=>{let t=await ad(te(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(yi).includes("skills-plugin"))try{await G.access(te(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},bM=async(e,t,n,r,o)=>{let a=te(t,"manifest.json");for(let s of e){let i=te(s.packageDir,"skills",s.entry.name);try{await G.access(te(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=te(t,"skills",s.entry.name),l=await QA(i,c,r,o);if(l==="conflict"){n.conflicts+=1;continue}if(l==="invalid"){n.invalid+=1;continue}if(l==="failed"){n.failed+=1;continue}let d=!1;await od(a,f=>{let p=Array.isArray(f.skills)?f.skills:[];if(p.find(m=>dt(m)&&typeof m.name=="string"&&m.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...f,skills:[...p,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},ev=(e,t)=>({...e,installPath:t}),kM=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=_h(r.installPath)?sn(r.installPath):sn(o,r.installPath),s=ev(e,Ql(sn(t),sn(n))),i={...r,installPath:Ql(sn(o),a)};return nd(s,i)},CM=async(e,t,n)=>{let r=await uo(e);if(!r||!dt(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":od(t,a=>{let s=dt(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},AM=async(e,t,n,r,o)=>{let a=te(t,"cowork_plugins"),s=te(a,"installed_plugins.json"),i=te(t,"cowork_account_settings.json");for(let c of e){let l=te(a,c.relativeInstallPath);if(!jA(a,l)){n.invalid+=1;continue}let d=await QA(c.packageDir,l,r,o);if(d==="conflict"){n.conflicts+=1;continue}if(d==="invalid"){n.invalid+=1;continue}if(d==="failed"){n.failed+=1;continue}let u=!1,f=!1;await od(s,h=>{let m=dt(h.plugins)?h.plugins:{},w=m[c.id],g=Array.isArray(w)?w:[],y=g.find(A=>dt(A)&&A.scope==="user");if(y){u=kM(c.entry,Aa(c.settingsFile),c.packageDir,y,t),f=!u;return}let b=ev(c.entry,l);return{...h,version:typeof h.version=="number"?h.version:2,plugins:{...m,[c.id]:[...g,b]}}})==="failed"?n.failed+=1:f?n.conflicts+=1:await CM(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},vM=async(e,t,n)=>{let r=te(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await od(r,c=>{let l=dt(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=nd(l[o],a)?"present":"conflict";return}return{...c,mcpServers:{...l,[o]:a}}})==="failed"?n.failed+=1:s.value==="present"?n.alreadyPresent+=1:s.value==="conflict"?n.conflicts+=1:n.migrated+=1}},tv=async(e,t,n={})=>{let r=await ZA(e),o=Rh("skill"),a=Rh("plugin"),s=Rh("local-mcp"),i=[],c=[],l=HA(r.skills,n.account,n.allAccounts),d=HA(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let f=new Set(n.allowedAccounts);if([...new Set([...l.map(h=>h.account),...d.map(h=>h.account)])].some(h=>!f.has(h)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,sourceChanged:!0,retryable:[]}}if(l.length>0){let f=await gM(t);f.state==="found"?await bM(l,f.path,o,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("skill"):(o.conflicts+=l.length,c.push("skill"))}if(d.length>0){let f=await wM(t);f.state==="found"?await AM(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await vM(r.localMcpServers,t,s);let u=[o,a,s];return{outcomes:u,blocked:i,ambiguous:c,sourceChanged:!1,retryable:u.filter(f=>f.failed>0).map(f=>f.kind)}};var xM=async e=>{try{return await It.access(e),!0}catch{return!1}},nv=448,IM=384,ov={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},OM=["code","cowork"],Nh=(e,t,n,r=!1)=>r?"Claude Desktop has not been set up on Anyray yet \u2014 run `anyray-connect desktop` first, then open Claude Desktop once and fully quit it.":e==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${t} store, so which one to fill is your call \u2014 re-run \`${n}\` with \`--account <id>\`.`:t==="cowork"?"Open Claude Desktop, sign in, and open the Cowork tab once \u2014 that is what creates the store \u2014 then fully quit it and run this again.":"Open Claude Desktop, sign in, and start a Claude Code session once \u2014 that is what creates the store \u2014 then fully quit it and run this again.",Lh=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),av=async e=>{let t;try{t=(await It.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&ca(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await It.readdir(cn(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&ca(a.name)).map(a=>a.name);for(let a of o)n.push(cn(e,r,a))}catch{}return n},RM=async e=>{try{return(await It.readdir(e)).filter(t=>t.startsWith(Kn)&&t.endsWith(".json")).map(t=>t.slice(Kn.length,-5)).filter(ca)}catch{return[]}},_M=async(e,t)=>{let n=await av(cn(e,ov[t])),r=[];for(let o of n){let a=await RM(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(EM).slice(-2)[0]})}return r},PM=async(e,t)=>{if(t==="cowork"){let r=await Nl(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await av(cn(e,ov.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},TM=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await It.copyFile(e,n),await It.chmod(n,IM),await It.rename(n,t)},LM=async(e,t)=>{try{let n=JSON.parse(await It.readFile(e,"utf8"));if(!n||typeof n!="object")return!1;let{cwd:r,cliSessionId:o}=n;return typeof r!="string"||typeof o!="string"||r.length===0||!ca(o)?!1:(await It.access(cn(t,".claude","projects",zf(r),`${o}.jsonl`)),!0)}catch{return!1}},DM=async(e,t,n,r)=>{let o=Lh(e),a=await Qf(n);for(let s of t)await NM(e,s,n,r,a,o);return o},NM=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Kn}${s}.json`,c=cn(t.dir,i);try{if(e==="code"){if(!await LM(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=cn(t.dir,`${Kn}${s}`),d=cn(n,`${Kn}${s}`),u=await It.readdir(l);await It.mkdir(d,{mode:nv});for(let f of u)await It.cp(cn(l,f),cn(d,f),{recursive:!0,force:!1,errorOnExist:!0});await It.chmod(d,nv)}await TM(c,cn(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},rv=(e,t,n,r=[])=>{let o=new Map;for(let{sources:s}of e)for(let i of s){let c=o.get(i.account)??{sessions:0,portable:!1};c.sessions+=i.ids.length,o.set(i.account,c)}for(let s of r){let i=o.get(s)??{sessions:0,portable:!1};i.portable=!0,o.set(s,i)}let a=[...o.entries()].sort((s,i)=>i[1].sessions-s[1].sessions).map(([s,i])=>{let c=i.sessions===0?"portable configuration":`${i.sessions} session${i.sessions===1?"":"s"}${i.portable?" plus portable configuration":""}`;return` ${t} --account ${s.slice(0,8)} (${c})`});return{ok:!1,kind:"account-ambiguous",reason:n,remedy:["Pick the one you want, or take everything:",...a,` ${t} --all-accounts`].join(`
292
+ `)}},Dh=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),sv=async e=>{let t=[];for(let n of OM)t.push({lane:n,sources:await _M(e,n)});return t},iv=async(e={})=>{let t=(e.firstPartyRoot??(()=>oi()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([sv(t),Th(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Dh(n);for(let s of r.accounts)a.add(s);return{sessions:o,accounts:a.size,userSkills:r.skills,userPlugins:r.plugins,localMcpServers:r.localMcpServers}},po=async(e={})=>{let t=(e.home??SM)(),n=(e.firstPartyRoot??(()=>oi()))(),r=(e.thirdPartyRoot??(()=>so()))();if(!n||!r)return{ok:!1,kind:"platform-unsupported",reason:"this platform has no Claude Desktop third-party profile",remedy:"Migration applies to macOS and Windows, where Desktop runs third-party mode in its own profile."};if((e.appRunning??Ca())())return{ok:!1,kind:"app-running",reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop and run this again \u2014 it rewrites its session list on exit, which would undo the migration."};let[o,a]=await Promise.all([sv(n),Th(n)]),s;if(e.account){let p=e.account;for(let w of o)w.sources=w.sources.filter(g=>g.account.startsWith(p));let h=a.accounts.filter(w=>w.startsWith(p));if(o.every(w=>w.sources.length===0)&&h.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${p}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let m=Dh(o);for(let w of h)m.add(w);if(m.size>1)return rv(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=Dh(o);for(let h of a.accounts)p.add(h);if(p.size>1)return rv(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${p.size} accounts`,a.accounts);s=[...p]}let i=e.command??"anyray-connect desktop --migrate",c=!await xM(r),l=await tv(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:s});if(l.sourceChanged)return{ok:!1,kind:"account-ambiguous",reason:"the previous Claude Desktop profile changed during migration and now holds local data for another account",remedy:`Re-run \`${i}\` so the account choice is made from a fresh snapshot.`};let d=[],u=[];for(let{lane:p,sources:h}of o){if(h.length===0){d.push(Lh(p));continue}let m=await PM(r,p);if("missing"in m){u.push({lane:p,reason:m.missing,waiting:h.reduce((w,g)=>w+g.ids.length,0)}),d.push(Lh(p));continue}d.push(await DM(p,h,m.dir,t))}if(!(d.some(p=>p.migrated>0||p.alreadyPresent>0)||l.outcomes.some(p=>p.migrated>0||p.alreadyPresent>0||p.conflicts>0))&&(u.length>0||l.blocked.length>0)){let p=u[0];return p?{ok:!1,kind:p.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:p.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${p.lane} store`:`Claude Desktop has no ${p.lane} store in its third-party profile yet`,remedy:Nh(p.reason,p.lane,i,c)}:{ok:!1,kind:"store-missing",reason:"Claude Desktop's third-party profile has no extension store yet",remedy:"Open Claude Desktop once after connecting it to Anyray, then fully quit it so the portable extensions can be copied safely."}}return{ok:!0,lanes:d,portableAssets:l.outcomes,...u.length>0?{blocked:u}:{},...l.blocked.length>0?{blockedAssets:l.blocked}:{},...l.ambiguous.length>0?{ambiguousAssets:l.ambiguous}:{},...l.retryable.length>0?{retryableAssets:l.retryable}:{}}};var $M=e=>[Ye(e)],cv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...$M(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await O(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var lv="1.21459.0",BM=UM(MM),WM=async e=>{try{let{stdout:t}=await BM("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},HM=async e=>{try{return await FM(e)}catch{return}},dv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",KM=["Admin policy setup (no JSON): open Developer \u2192 Configure Third-Party Inference; the Anyray connection is already filled in.",'Add approved remote MCP connectors under "Connectors & extensions" and use "Test this connection"; add approved Git marketplaces under "Plugins & skills".',`Choose "Apply locally" to test. For Jamf, first select IT's fleet-wide credential-helper path, then choose Export \u2192 .mobileconfig and deploy the complete profile.`,"If Claude Desktop is already MDM-managed, this window is read-only. Author and export on an unmanaged admin Mac, then redeploy through Jamf."],va=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(uv??=pv({}),uv):pv(e),uv,pv=async e=>{let t=(e.home??ki)(),n=["/Applications/Claude.app",Sn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??WM,o=e.readClaudeAppBundle??HM;for(let a of n){let s=await r(Sn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${dv}`}),c=Ll(s,lv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${lv} or newer.`);let l=await o(Sn(a,"Contents","Resources","app.asar"));return l?ZC.some(d=>!l.includes(d))?i("its local config seam no longer matches the shape Connect writes."):{supported:!0,detectedVersion:s,appPath:a}:i("its app bundle could not be read to verify the local config seam.")}return{supported:!1,message:`Could not verify the installed Claude Desktop version. ${dv}`}},sd="anyray",mv="--anyray-owner=claude-desktop-v1",id=(e={})=>{let t=(e.platform??Er)(),n=(e.home??ki)();return t==="darwin"?on(e).appConfig:t==="win32"?Sn(process.env.APPDATA??Sn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):Sn(n,".config","Claude","claude_desktop_config.json")},Bh=(e={})=>Sn((e.home??ki)(),"Library","Application Support","Claude","claude_desktop_config.json"),yv=()=>{let e=Ve("profile");return{command:e.command,args:[...e.args,mv]}},fo=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),gv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},GM=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),jM=e=>{if(!fo(e)||!gv(e,["command","args"]))return!1;let t=yv();return e.command===t.command&&GM(e.args,t.args)},VM=e=>fo(e)&&Array.isArray(e.args)&&e.args.at(-1)===mv,YM=e=>{if(!fo(e)||!gv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||je(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===sr&&t.at(-1)==="profile"))return!1;let r=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(r))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(r)||t.length!==3)return!1;let o=t[0].replaceAll("\\","/");return!je(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},ZM=e=>e===void 0?"absent":jM(e)?"exact":VM(e)||YM(e)?"stale-owned":"foreign",He=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},ho=async e=>{let t=await O(e),n;try{n=await U(e)}catch{throw new He(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!fo(n.mcpServers))throw new He(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(fo(n.mcpServers)?n.mcpServers:void 0)?.[sd];return{path:e,fileExisted:t,json:n,entry:o,ownership:ZM(o)}},cd=e=>{if(e.ownership==="foreign")throw new He(`MCP name conflict in ${e.path}: mcpServers.${sd} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},wv=(e,t)=>{let n={...e},r=fo(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[sd]:r[sd]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Mh=async(e,t)=>{if($h(e.entry,t))return;let n=await ho(e.path);if(!$h(n.entry,e.entry))throw new He(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Gn(e.path,wv(n.json,t)),{reading:e,afterEntry:t}},Fh=async e=>{let t=await ho(e.reading.path);if(!$h(t.entry,e.afterEntry))throw new He(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=wv(t.json,e.reading.entry);await Gn(e.reading.path,n)},XM=async e=>{if(!le())throw new He(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Oe()} is temporary); no inference setting was changed.`);let t=await ho(id(e));cd(t);let n=Bh(e),r=(e.platform??Er)()==="darwin"&&n!==t.path?await ho(n):void 0;return r&&cd(r),{active:t,...r?{legacy:r}:{}}},fv=async e=>{let t=await ho(id(e));cd(t);let n=Bh(e),r=(e.platform??Er)()==="darwin"&&n!==t.path?await ho(n):void 0;return r&&cd(r),{active:t,...r?{legacy:r}:{}}},JM=async e=>{let t=[];try{let n=await Mh(e.active,yv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Mh(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Fh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new He(`Claude Desktop MCP setup failed and could not restore ${r.join(", ")}. Re-run \`anyray-connect desktop disconnect\` to recover safely.`,r):n}return{changedFiles:t.map(n=>n.reading.path),async rollback(){let n=[];for(let r of[...t].reverse())await Fh(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new He(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},qM=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Mh(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Fh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new He(`Claude Desktop MCP cleanup failed and could not restore ${r.join(", ")}. Re-run revert after resolving the file conflict.`,r):n}return t.map(n=>n.reading.path)},hv=e=>{let t=e.clientKey?`${e.clientKey} (your personal gateway key - keep it private)`:`${e.placeholderKey} (placeholder - the gateway holds the real key)`;return["Step 1 - Turn on Developer Mode."," In the menu bar at the VERY TOP of the screen (NOT the in-app help panel):"," Help -> Troubleshooting -> Enable Developer Mode"," (Windows: open the menu at the top-left of the sign-in screen.)",' A "Developer" menu then appears in that same top-of-screen menu bar.',"","Step 2 - Open the Developer MENU in the menu bar (shown below) - NOT Settings:",""," +----------------------------------------------------------------+"," | Claude File Edit View Window [Developer] Help | <- macOS menu bar (very top of screen)"," +-------------------------------------^--------------------------+"," |",' click Developer -> "Configure Third-Party Inference..."',"",' Heads up: use the "Developer" MENU in the bar above - NOT',' Settings -> Developer, which is the "Local MCP servers" pane'," (that's where Anyray's retrieval server appears, not inference)."," A separate setup window then opens.","","Step 3 - In that window's Connection section, paste:",""," Inference provider: Gateway",` Gateway base URL: ${e.anthropicBaseUrl}`," Auth scheme: Bearer",` API key: ${t}`,"",'Step 4 - Click "Apply locally", then fully quit and reopen Claude'," (the config is read once at launch).","","Billing: this route uses an Anyray gateway credential and provider/API billing, not a Claude subscription allowance.","Fleet/MDM: generate a managed profile with `anyray-connect desktop claude --mobileconfig` (applies with no Developer Mode and no paste)."]},zM={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},ld="claude-desktop",Uh="migrate",bv=new Set(["app-running","store-missing"]),QM={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},eF={skill:{one:"user-created skill",many:"user-created skills"},plugin:{one:"user-installed plugin",many:"user-installed plugins"},"local-mcp":{one:"local MCP server",many:"local MCP servers"}},tF="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",kv=e=>{let t=(e.platform??Er)(),n=e.home??ki;return{home:n,appRunning:e.appRunning??Ca(t),firstPartyRoot:()=>oi({home:n,runtimePlatform:t}),thirdPartyRoot:()=>so({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Cv=e=>{let t=e.filter(a=>a.migrated>0);if(t.length===0)return;let n=e.reduce((a,s)=>a+s.skippedNoTranscript,0),r=e.reduce((a,s)=>a+s.failed,0);return`Brought your existing Claude Desktop sessions into its third-party profile: ${t.map(a=>{let s=QM[a.lane];return`${a.migrated} ${a.migrated===1?s.one:s.many}`}).join(", ")}.`+(n>0?` ${n} skipped \u2014 the transcript is no longer on disk.`:"")+(r>0?` ${r} could not be copied.`:"")},Av=e=>{let t=e.filter(s=>s.migrated>0),n=e.reduce((s,i)=>s+i.conflicts,0),r=e.reduce((s,i)=>s+i.invalid,0),o=e.reduce((s,i)=>s+i.failed,0);if(t.length===0&&n+r+o===0)return;let a=t.map(s=>{let i=eF[s.kind];return`${s.migrated} ${s.migrated===1?i.one:i.many}`});return(a.length>0?`Brought your portable Claude Desktop configuration across: ${a.join(", ")}.`:"Portable Claude Desktop configuration was checked; existing target entries were kept.")+(n>0?` ${n} conflicting target ${n===1?"entry was":"entries were"} preserved.`:"")+(r>0?` ${r} unsafe or incomplete ${r===1?"entry was":"entries were"} skipped.`:"")+(o>0?` ${o} could not be copied.`:"")},bi=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=kv(e),r=await(e.pendingDesktopMigrationCount??iv)(n),o=r.userSkills+r.userPlugins+r.localMcpServers;if(r.sessions+o===0)return[];if(t.dryRun)return[`Would bring ${[r.sessions>0?`${r.sessions} existing Claude Desktop session${r.sessions===1?"":"s"}`:"",o>0?`${o} portable configuration ${o===1?"entry":"entries"}`:""].filter(Boolean).join(" and ")} into Claude Desktop's third-party profile, now or automatically the next time Claude Desktop is fully quit.`];let a=await(e.migrateDesktopProfile??po)(n);if(a.ok){let c=Cv(a.lanes),l=Av(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(a.blocked??[]).filter(y=>y.reason!=="ambiguous"),p=a.blockedAssets??[],h=a.retryableAssets??[];if(f.length===0&&p.length===0&&h.length===0)return[c,l,u].filter(y=>!!y);if(t.preservePendingOp)return[c,l,u].filter(y=>!!y);await Ns(ld,Uh);let m=f.reduce((y,b)=>y+b.waiting,0),w=[m>0?`${m} more session${m===1?"":"s"}`:"",p.length>0?`${p.length} extension ${p.length===1?"store":"stores"}`:""].filter(Boolean),g=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...h.length>0?[`Queued: ${h.length} portable configuration ${h.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...g]}if(!bv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
293
+ ${a.remedy}`];if(t.preservePendingOp)return[];await Ns(ld,Uh);let s=r.sessions+o,i=`${s} Claude Desktop local ${s===1?"item":"items"}`;return[a.kind==="store-missing"?`Queued: the ${i} still in your previous profile move across once Claude Desktop's new profile has been signed in to and the app is fully quit.`:`Queued: the ${i} still in your previous profile will move across the next time you fully quit Claude Desktop.`]}catch{return["Could not check whether Claude Desktop had existing sessions to bring across; run `anyray-connect migrate` if its lists look empty."]}},nF=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await mr(ld),[]}catch{return["Could not clear Claude Desktop's queued profile-migration marker; a background watcher may still be waiting for the app to quit. Delete it by hand if it persists."]}},rF=e=>cv({id:ld,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Er)(),n=(e.home??ki)();return t==="darwin"?["/Applications/Claude.app",Sn(n,"Applications","Claude.app")]:t==="win32"?[Sn(process.env.LOCALAPPDATA??Sn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>J(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",...hv(t)]:["Claude desktop org/API lane:",...hv(t),"This Gateway route uses provider/API billing. On verified macOS builds, subscription mode instead installs the Keychain-backed Claude Code credential helper automatically."],revertMessages:["Claude Desktop third-party inference: switch back to the first-party Claude provider in Developer settings (or remove the managed profile). Native setup is restored automatically by `--revert`."]}),oF=(e={})=>{let t=rF(e),n=()=>(e.platform??Er)()==="darwin",r=()=>(e.platform??Er)()==="win32",o=(s,i)=>n()?nA(s,i,e):DA(s,s.clientKey??"",i,e),a=s=>n()?rA(s,e):NA(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??Ca((e.platform??Er)()))(),quitTarget:zM,needsTarget:()=>!1,async complete(s){if(s!==Uh)return{status:"manual",messages:[`Claude Desktop could not service a queued "${s}" operation it does not recognise; the queue entry was dropped.`]};let i=await(e.migrateDesktopProfile??po)(kv(e));if(i.ok){let c=Cv(i.lanes),l=Av(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let f=(i.blocked??[]).filter(m=>m.reason!=="ambiguous"),p=i.blockedAssets??[],h=i.retryableAssets??[];return f.length>0||p.length>0||h.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...f.length>0||p.length>0?["Still waiting on Claude Desktop to create the remaining third-party stores, which appear the first time those parts of the app are opened."]:[],...h.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(m=>!!m):["No portable Claude Desktop data was left to bring across."]}}return bv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?aA(s,e):r()?FA(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=on(e),p=await co(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[lh(p),...await bi(e,i)]}}if(r()){let f;try{f=await Sr(e.runReg??Vn)}catch{return{status:"manual",manualAudience:"admin",messages:[tF,...await bi(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[xh(f),...await bi(e,i)]}}if(r()&&J(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let f=await va(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await XM(e)}catch(f){let p=f instanceof He?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof He?f.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no inference setting was changed."]}}let l=await o(s,{dryRun:!0});if(l.status!=="configured")return l;if(i.dryRun){let f=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...f&&f.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${f.path}.`]:[],...await bi(e,i)]}}let d;try{d=await JM(c)}catch(f){let p=f instanceof He?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof He?f.message:"Could not safely register Claude Desktop retrieval; the inference route was left unchanged."]}}let u;try{u=await o(s,{dryRun:!1})}catch{u={status:"manual",messages:["Claude Desktop inference setup failed before it returned a result."]}}if(u.status!=="configured")try{return await d.rollback(),{...u,changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])],messages:[...u.messages,"Restored the prior Claude Desktop MCP registration because inference setup did not complete. A config file that was absent before setup may remain as an inert object to avoid racing unrelated concurrent writes."]}}catch{return{status:"manual",changedFiles:[...u.changedFiles??[],...d.changedFiles],messages:[...u.messages,"Inference setup did not complete, and the prior MCP registration could not be fully restored. Re-run `anyray-connect desktop disconnect` to recover safely."]}}return{...u,messages:[...u.messages,"Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) with an ownership marker.",...await bi(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?KM:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=id(e),c=await nF(s),l=m=>c.length===0?m:{...m,messages:[...m.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await fv(e)}catch(m){return l({status:"manual",messages:[m instanceof He?m.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let m=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...m&&m.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${m.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let m=r()?Wt(e):void 0;if(!(m!==void 0&&f.changedFiles?.includes(m)===!0&&!await O(m)))return l(f)}let p;try{p=await qM(await fv(e))}catch(m){let w=m instanceof He?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof He?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await se(i);let h=Bh(e);return n()&&h!==i&&await se(h),l({...f,messages:[...f.messages,...p.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...p])]})},async mcpStatus(){if(!le())return{registered:!1,command:null};try{let s=await ho(id(e));return s.ownership!=="exact"||!fo(s.entry)?{registered:!1,command:null}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null}}},async pointsAt(s){return n()?(await va(e)).supported?uh(s,e):!1:r()?MA(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await va(e)).supported)return["unknown"];let s=await oA(e);return s?[s]:["unknown"]}if(r())return await O(Wt(e))?await Sr(e.runReg??Vn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=on(e);return!await O(s.journal)||await co(s,e)?!1:(await va(e)).supported}return r()&&await O(Wt(e))?!await Sr(e.runReg??Vn):!1}catch{return!1}}}},vv=oF();import{homedir as TF}from"node:os";import{join as LF}from"node:path";import{rm as wd}from"node:fs/promises";import{constants as Sv,accessSync as aF,statSync as sF}from"node:fs";import{platform as Wh}from"node:os";import{delimiter as iF,posix as cF,resolve as lF,win32 as dF}from"node:path";var uF="0.59.0",pF="1.1.4",Yn="Anyray \xB7 Claude",Zn="Anyray \xB7 Codex",dd="__anyray-acp-agent",Ev=(e,t,n)=>{let{command:r,args:o}=un([dd,e,t,n]);return{command:r,args:o,env:{}}},ud=(e=Wh())=>e==="win32"?"npx.cmd":"npx",pd=(e=process.env.PATH,t=Wh())=>{if(!e)return;let n=ud(t);for(let r of e.split(iF)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=lF(o,n);try{if(!sF(a).isFile())continue;return aF(a,t==="win32"?Sv.F_OK:Sv.X_OK),a}catch{}}},fd=(e,t=Wh())=>{let n=t==="win32"?dF:cF;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==ud(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},fF="https://chatgpt.com/backend-api/codex",hF="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",xv="ANYRAY_ACP_CODEX_AUTHORIZATION",Iv="ANYRAY_ACP_CODEX_CLIENT_KEY",Ov="ANYRAY_ACP_CODEX_METADATA",Rv=e=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),mF=(e,t={})=>{let n=J(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":fF,"x-anyray-forward-headers":hF}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Iv}:{}}:{Authorization:xv};return Rv(e)&&(o["x-anyray-metadata"]=Ov),{model_provider:"anyray",model_providers:{anyray:{name:"Anyray Gateway",base_url:e.openaiBaseUrl,wire_api:"responses",...n?{requires_openai_auth:!0}:{},http_headers:r,env_http_headers:o}},...t.mcpServer?{mcp_servers:{anyray:{command:t.mcpServer.command,args:t.mcpServer.args}}}:{}}},yF=e=>{let t=J(e,"openai"),n=Rv(e);return{...t?e.clientKey?{[Iv]:e.clientKey}:{}:{[xv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[Ov]:n}:{}}},_v=(e,t=ud(),n={})=>({[Yn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${uF}`],env:pn(e).env},[Zn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${pF}`],env:{CODEX_CONFIG:JSON.stringify(mF(e,n)),...yF(e)}}}),Ci=(e=ud(),t="jetbrains")=>({[Yn]:Ev("claude",e,t),[Zn]:Ev("codex",e,t)}),mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as gF}from"node:zlib";import{open as wF,readFile as Vh,readdir as gd}from"node:fs/promises";import{dirname as Pv,join as ue}from"node:path";import{homedir as Nv,platform as Yh}from"node:os";var md="2025.3.2",Sa="253.30387.147",Ai="com.intellij.ml.llm",Hh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),bF=1e4,kF=256*1024*1024,CF=16*1024*1024,Kh=1024*1024,Gh=22,AF=Gh+65535,jh=Ll,vF=()=>{let e=Nv(),t=ue(e,".cache","JetBrains","RemoteDev");switch(Yh()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:ue(e,"Applications"),layout:"app-bundles"},{path:ue(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:ue(process.env.LOCALAPPDATA??ue(e,"AppData","Local"),"Programs"),layout:"children"},{path:ue(process.env.LOCALAPPDATA??ue(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:ue(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:ue(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},SF=()=>Yh()==="linux"?ue(Nv(),".local","share","JetBrains"):Ye("JetBrains"),EF=()=>Yh()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),xF=async(e,t=bF)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await gd(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=ue(r.path,i.name),l=r.layout==="app-bundles"?ue(c,"Contents","Resources","product-info.json"):ue(c,"product-info.json");await O(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=ue(s,"product-info.json"),l=ue(s,"Contents","Resources","product-info.json");if(await O(c)){n.push(c);return}if(await O(l)){n.push(l);return}let d;try{d=await gd(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=ue(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(f,i-1)}};await a(r.path,7)}return[...new Set(n)]},IF=e=>{let t=Pv(e);return t.endsWith(`${ue("Contents","Resources")}`)?Pv(t):t},OF=async e=>{try{let t=JSON.parse(await Vh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!ni(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:IF(e)}}catch{return}},yd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},RF=async(e,t)=>{let n;try{n=await wF(e,"r");let{size:r}=await n.stat();if(r<Gh||r>kF)return;let o=Math.min(r,AF),a=await yd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Gh;u>=0;u-=1)if(a.readUInt32LE(u)===101010256){s=u;break}if(s<0)return;let i=a.readUInt32LE(s+12),c=a.readUInt32LE(s+16);if(i>CF||c+i>r)return;let l=await yd(n,i,c);if(!l)return;let d=0;for(;d+46<=l.length;){if(l.readUInt32LE(d)!==33639248)return;let u=l.readUInt16LE(d+10),f=l.readUInt32LE(d+20),p=l.readUInt32LE(d+24),h=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),g=l.readUInt32LE(d+42),y=d+46+h+m+w;if(y>l.length)return;let b=l.subarray(d+46,d+46+h).toString("utf8");if(d=y,b!==t)continue;if(f===4294967295||p===4294967295||f>Kh||p>Kh)return;let A=await yd(n,30,g);if(!A||A.readUInt32LE(0)!==67324752)return;let v=A.readUInt16LE(26),E=A.readUInt16LE(28),x=await yd(n,f,g+30+v+E);return x?u===0?x.toString("utf8"):u===8?gF(x,{maxOutputLength:Kh}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},Tv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!ni(n)))return{id:t,version:n}},_F=async(e,t)=>{let n=ue(e,"META-INF","plugin.xml");if(await O(n))try{let o=Tv(await Vh(n,"utf8"));return{present:o?.id===Ai||t,descriptor:o?.id===Ai?o:void 0}}catch{return{present:t}}let r=[];try{r=(await gd(ue(e,"lib"),{withFileTypes:!0})).filter(o=>o.isFile()&&o.name.endsWith(".jar")&&/(?:^|[-_.])(ml-?llm|llm|aia|ai[-_.]?assistant)(?:[-_.]|$)/i.test(o.name)).slice(0,32).map(o=>ue(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await RF(o,"META-INF/plugin.xml"),s=a?Tv(a):void 0;if(s?.id===Ai)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Lv=async e=>{let t;try{t=await gd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Hh.has(o.name.toLowerCase()),i=Hh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Hh.has(o.name.toLowerCase());if(!a){let i=ue(e,o.name,"META-INF","plugin.xml");if(!await O(i))continue}let s=await _F(ue(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},PF=async e=>{try{return(await Vh(ue(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(Ai)}catch{return!1}},Dv=e=>e.reduce((t,n)=>t?(jh(n,t)??-1)>0?n:t:n,void 0),$v=async(e={})=>{let t=e.configRoot??Ye("JetBrains"),n=e.userPluginsRoot??SF(),r=await xF(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):vF(),e.scanBudget),o=(await Promise.all(r.map(h=>OF(h)))).filter(h=>h!==void 0),a=o.length>0||await O(t);if(e.wsl??EF())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(h=>(jh(h.version,md)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let h of s){let m=ue(t,h.dataDirectoryName);if(!await O(m)){d=!0;continue}let w=[ue(m,"plugins"),ue(n,h.dataDirectoryName),ue(n,h.dataDirectoryName,"plugins")],g;for(let y of[...new Set(w)]){let b=await Lv(y);if(b.present){g=b;break}}if(g??=await Lv(ue(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==Ai)){if(i.push(g.descriptor.version),await PF(m)){c=!0;continue}if(!((jh(g.descriptor.version,Sa)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${h.version}; AI Assistant ${g.descriptor.version}; ACP supported`,ideVersion:h.version,pluginVersion:g.descriptor.version}}}let u=Dv(o.map(h=>h.version)),f=Dv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${md}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${md}+ once, enable AI Assistant ${Sa}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${Sa}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${Sa}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${Sa}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${Sa}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${md}+ from local product-info.json; no ACP config was written.`:p="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:p,ideVersion:u,pluginVersion:f}};var DF=[Yn,Zn],Zh=()=>LF(TF(),".jetbrains","acp.json"),yo=()=>`${Zh()}.anyray-state`,NF=(e,t,n="npx")=>{let r=mo(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,Ci(n,"jetbrains")),{...e,agent_servers:r}},$F=(e,t,n)=>{if(!mo(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=mo(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of DF)if(c in r){if(!hd(r[c],n[c])){s.push(c);continue}c in o?r[c]=o[c]:delete r[c],a.push(c)}let i={...e};return Object.keys(r).length>0?i.agent_servers=r:delete i.agent_servers,{next:i,removed:a,conflicts:s}},MF=(e=$v)=>({id:"jetbrains",title:"JetBrains AI Assistant",automatic:!0,async detect(){let t=await e();return{installed:t.installed,detail:t.detail}},async apply(t,n){let r=Zh(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=pd();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await O(r),c;try{c=await U(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=Ci(a,"jetbrains");return await dc({configPath:r,current:c,next:NF(c,t,a),journalPath:yo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,yo()]}},async revert(t){let n=Zh(),r=async()=>{if(!await O(n))return t.dryRun||(await se(n),await wd(yo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await U(n)}catch{return t.dryRun||(await se(n),await wd(yo(),{force:!0}).catch(()=>{})),{status:"manual",messages:[`Could not parse ${n}; remove the two \u201CAnyray \xB7 \u2026\u201D agent entries manually.`]}}let a={},s=!1,i=!1;try{let u=await U(yo());(u.version===1||u.version===2)&&mo(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await O(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await U(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Mr(n);let l=$F(o,c,a),d=[];return l.removed.length&&d.push(`Removed ${l.removed.join(", ")} from ${n}.`),l.conflicts.length&&d.push(`Preserved user-modified ACP entries: ${l.conflicts.join(", ")}.`),!t.dryRun&&l.removed.length&&(s&&Object.keys(l.next).length===0?await wd(n,{force:!0}):await X(n,l.next,{backup:!1})),t.dryRun||(await se(n),await wd(yo(),{force:!0}).catch(()=>{})),{status:l.conflicts.length?"manual":"reverted",messages:d.length?d:["No Anyray ACP entries found."],changedFiles:!t.dryRun&&l.removed.length?[n]:void 0}};return t.dryRun?r():lc(n,yo(),r)}}),Mv=MF();import{homedir as kd}from"node:os";import{join as Cd}from"node:path";import{rm as Xh}from"node:fs/promises";var Jh="1.0.0",Ad=["anyray-claude-acp","anyray-codex-acp"],FF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],qh=()=>Cd(kd(),".windsurf","acp","registry.json"),zh=()=>Cd(kd(),".windsurf-next","acp","registry.json"),Ea=e=>`${e}.anyray-state`,Fv=e=>({binary:Object.fromEntries(FF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Bv=(e="npx")=>{let t=Ci(e,"windsurf");return[{id:Ad[0],name:Yn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Fv(t[Yn])},{id:Ad[1],name:Zn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Fv(t[Zn])}]},bd=e=>!Array.isArray(e)||e.some(t=>!mo(t)||typeof t.id!="string")?null:e,UF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Jh||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:bd(e.agents);if(!n)return null;let r=new Set(Ad);return{...e,version:typeof e.version=="string"?e.version:Jh,agents:[...n.filter(o=>!r.has(o.id)),...Bv(t)],extensions:e.extensions??[]}},BF=(e,t,n)=>{let r=bd(e.agents);if(!r)return null;let o=bd(t.agents)??[],a=new Map((bd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!Ad.includes(u.id)){l.push(u);continue}if(!hd(u,a.get(u.id))){c.push(u.id),l.push(u);continue}let f=s.get(u.id);f&&l.push(f),i.push(u.id)}let d={...e,agents:l};return!Object.prototype.hasOwnProperty.call(t,"agents")&&l.length===0&&delete d.agents,!Object.prototype.hasOwnProperty.call(t,"version")&&d.version===Jh&&delete d.version,!Object.prototype.hasOwnProperty.call(t,"extensions")&&Array.isArray(d.extensions)&&d.extensions.length===0&&delete d.extensions,{next:d,removed:i,conflicts:c}},Uv=async()=>{let e=[];return(await O(zh())||await O(Cd(kd(),".windsurf-next")))&&e.push(zh()),(await O(qh())||await O(Cd(kd(),".windsurf"))||await O(Ye("Devin"))||await O(Ye("Windsurf")))&&e.push(qh()),e},Wv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Uv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Uv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=pd();if(!r)return{status:"manual",messages:["Devin ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP registry was written."]};let o=[],a=[];for(let s of n){let i;try{i=await U(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=UF(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await O(s),d=Bv(r);await dc({configPath:s,current:i,next:c,journalPath:Ea(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Ea(s))}}return o.push("Devin requires a one-time vendor UI enablement for local registry agents: Devin Settings \u2192 Agents \u2192 enable the two Anyray agents, then restart Devin Desktop."),o.push("Native Devin/Cascade subscription requests are not redirected. The official enterprise consumption connector imports content-free usage instead."),o.push("No proxy, certificate, DNS, DEVIN_API_URL, or private first-party endpoint was changed."),{status:"manual",messages:o,changedFiles:a.length?a:void 0}},async revert(e){let t=[qh(),zh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await O(a)){e.dryRun||(await se(a),await Xh(Ea(a),{force:!0}).catch(()=>{}));return}let i;try{i=await U(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let p=await U(Ea(a));(p.version===1||p.version===2)&&Array.isArray(p.agents)&&(c=p.agents,l=p.version===2&&p.fileExisted===!1,d=p.version===2&&p.fileExisted===!0)}catch{}let u;if(d){let p=`${a}.anyray-bak`;if(!await O(p)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await U(p)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await Mr(a);let f=BF(i,u,c);if(!f){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}f.removed.length&&(n.push(`Removed ${f.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(f.next).length===0?await Xh(a,{force:!0}):await X(a,f.next,{backup:!1}),r.push(a))),f.conflicts.length?(n.push(`Preserved user-modified agents: ${f.conflicts.join(", ")}.`),o=!0):e.dryRun||(await se(a),await Xh(Ea(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await lc(a,Ea(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var ie=[cr,Yw,Bs,Nk,oC,gC,IC,Mv,vv,Wv,nb],Ht=e=>ie.find(t=>t.id===e);var WF=["hook_registration","mcp_registration","hook_binary","beacon_target"],go=e=>e.status==="configured"||e.status==="queued",wo=async(e,t=ie)=>{let n=new Set(e),r=[];for(let o of t)if(n.has(o.id))try{(await o.detect()).installed&&r.push(o)}catch{}return r},xr=async(e,t,n=ie)=>{let r=[];for(let o of await wo(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},Qh=async(e,t=ie)=>{let n=[];for(let r of await wo(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(WF.map(o=>[o,"unreadable"]))})}return n},Hv=e=>e.filter(t=>!t.integrationStatus),HF=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},gt=async(e,t)=>{let n=[];for(let r of e)try{let o=await r.apply(t,{dryRun:!1});n.push({id:r.id,title:r.title,status:o.status})}catch(o){let a=HF(o);if(r.classifyApplyError)try{a=r.classifyApplyError(o)}catch{}n.push({id:r.id,title:r.title,status:"failed",errorClass:a})}return n};import{mkdir as qF,writeFile as zF}from"node:fs/promises";import{join as Xv}from"node:path";import{z as Me}from"zod";var KF=["HTTPS_PROXY","https_proxy"],Kv=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_UNTRUSTED"]),Gv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),jv=new Set(["ENOTFOUND","EAI_AGAIN"]),Vv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Yv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),GF=e=>{let t=e;for(let n=0;n<5&&t;n++){let r=t.code;if(typeof r=="string"&&r)return r;t=t.cause}return jF(e)},jF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...Kv,...Gv,...jv,...Vv,...Yv])if(t.includes(n))return n}},VF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",YF=e=>KF.filter(t=>(e[t]??"").trim()!==""),ZF=(e,t=process.env)=>{let n=GF(e),r=YF(t);return{kind:n&&Kv.has(n)?"tls-unknown-issuer":n&&Gv.has(n)?"tls-invalid-cert":n&&jv.has(n)?"dns":VF(e)||n&&Yv.has(n)?"timeout":n&&Vv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},XF=e=>{let t=e.proxyVars.length>0?` ${e.proxyVars.join(" and ")} ${e.proxyVars.length>1?"are":"is"} set \u2014 if that proxy is stale or unreachable, unset it and re-run.`:"";switch(e.kind){case"tls-unknown-issuer":return` (TLS certificate signed by an unknown authority: ${e.code}). Your network appears to inspect TLS traffic. curl trusts your system keychain and this binary does not, which is why the download worked and this step did not. Point NODE_EXTRA_CA_CERTS at your organization root certificate (PEM) and re-run.`+t;case"tls-invalid-cert":return` (TLS certificate rejected: ${e.code}). Check this machine's clock and date, and whether a proxy is rewriting HTTPS traffic, then re-run.`+t;case"dns":return` (DNS lookup failed: ${e.code}). Check your VPN or DNS, then re-run.`+t;case"refused":return` (connection failed: ${e.code}).`+(t||" Check your network or firewall, then re-run.");case"timeout":return" (timed out before the control plane answered)."+(t||" Check your connection and re-run.");default:return e.code?` (${e.code}).${t}`:t}},wt=(e,t=process.env)=>XF(ZF(e,t));var xa="required",JF=e=>e==="subscription"?"subscription":"placeholder",Zv=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?JF(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}:{}}},vd=(e,t,n)=>{let r=new Set(t.enabled??[]),o=e.managedTools??[],a=o.filter(u=>r.has(u)||n),s=new Set(e.revertedTools??[]),i=e.revertedTools!=null,c=u=>t.tiers?.[u]??xa,l=[],d=[];for(let u of r){if(o.includes(u))continue;let f=c(u);if(f!=="optional"){if(f!=="locked"){if(!i)continue;if(s.has(u)){f==="required"&&d.push(u);continue}}l.push(u)}}return{candidateIds:a,freshIds:l,tombstonedIds:d}};var QF=1e4,eU=1,tU=Me.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),nU=Me.object({id:tU,name:Me.string().min(1),version:Me.string().min(1),body:Me.string()}),rU=Me.object({version:Me.literal(eU).optional(),skills:Me.array(nU),updatedAt:Me.string().min(1).optional(),routing:Me.object({origin:Me.string().min(1)}).optional(),team:Me.string().min(1).optional(),lane:Me.enum(["subscription","org"]).optional().catch(void 0),tools:Me.object({enabled:Me.array(Me.string().min(1)),tiers:Me.record(Me.string().min(1),Me.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),oU=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",Sd=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",Ed=async(e,t,n={})=>{let r=n.timeoutMs??QF,o=`${e}/connect/policy`,a=new AbortController,s=setTimeout(()=>a.abort(),r),i;try{i=await fetch(o,{method:"GET",headers:{"x-anyray-api-key":t},signal:a.signal})}catch(l){let d=l instanceof Error&&l.name==="AbortError"?` no response within ${r}ms.`:wt(l);throw new Error(`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Error(`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch(l){let d=new Error("team policy fetch failed: the gateway returned a malformed response");throw d.name=Sd(l),d}return rU.parse(c)},Jv=/^[a-z0-9][a-z0-9-]{0,31}$/,qv=64,aU=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>Jv.test(o)).slice(0,qv).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>Jv.test(o)).slice(0,qv).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},vi=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??xa)==="locked":!1},xd=async(e,t={})=>{let n=t.loadProfile??D,r=t.saveProfile??re,o=t.targetFromProfile??Re,a=t.adapters??ie,s=t.repairTools??gt,i=t.recordManaged??tr,c=await n(),l={...c},d=Zv(c,{routingOrigin:e.routing?.origin?dn(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:u,teamUpdated:f,laneUpdated:p}=d;(u||f||p)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),d.authMode!=null&&(l.authMode=d.authMode),await r(l));let h=vd(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f||p),{candidateIds:m,freshIds:w}=h,g=0,y=0,b=0;if(m.length>0||w.length>0){let E=await o(async()=>l);if(E){let x;if(u||f||p){let P=new Set(m);x=[];for(let $ of a)if(P.has($.id))try{(await $.detect()).installed&&x.push($)}catch{}}else x=await xr(m,E.toolOrigin,a);let C=new Set(w),I=[];for(let P of a)if(C.has(P.id))try{(await P.detect()).installed&&I.push(P)}catch{}if(g=x.length+I.length,g>0){let P=await s([...x,...I],E.target);y=P.filter(go).length;let $=P.filter(Y=>C.has(Y.id));if(b=$.filter(go).length,$.length>0)try{await i($,!1)}catch{}}}}let A=aU(e),v=await n();if(JSON.stringify(A??null)!==JSON.stringify(v.fleetToolPolicy??null)){let{fleetToolPolicy:E,...x}=v;await r({...x,...A?{fleetToolPolicy:A}:{}})}return{routingUpdated:u,teamUpdated:f,laneUpdated:p,toolsRequested:g,toolsApplied:y,toolsEnrolled:b,toolsTombstoned:h.tombstonedIds,profileUpdated:u||f||p}},zv=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!oU(i.id))continue;if(o[i.id]=i.version,n[i.id]===i.version){s+=1,r.push({id:i.id,name:i.name,version:i.version,written:!1,files:[]});continue}let l=[];for(let d of t){let u=Xv(d,i.id),f=Xv(u,"SKILL.md");await qF(u,{recursive:!0}),await zF(f,sU(i.body),"utf-8"),l.push(f)}a+=1,r.push({id:i.id,name:i.name,version:i.version,written:!0,files:l})}return{results:r,changed:a,unchanged:s,versions:o,updatedAt:e.updatedAt}},sU=e=>e.endsWith(`
294
294
  `)?e:`${e}
295
- `;import{createHash as nU,createPrivateKey as rU,generateKeyPairSync as oU,randomBytes as qh,sign as aU}from"node:crypto";var Qh=1e4,ko=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ko).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${ko(e[n])}`).join(",")}}`,Ai="stable-key-heartbeat-v1",qv="key-heartbeat",sU=["reapply_config","remint","revert"];var Qv=e=>nU("sha256").update(e).digest("hex"),Qe=e=>typeof e=="string"&&e.trim()?e.trim():void 0,iU=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],em=async e=>{try{let t=await e.json(),n=Qe(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},Rt=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Ir=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},tm=(e,t,n)=>{try{let r=rU(t),o=new TextEncoder().encode(ko(e));return aU(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Ed=()=>{let{publicKey:e,privateKey:t}=oU("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},ln=async(e,t,n,r={})=>{let o=r.timeoutMs??Qh,a=`${e}/connect/verify`,s=Qe(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:qh(16).toString("hex")},c=tm(i,n,"verification"),l=new AbortController,d=setTimeout(()=>l.abort(),o),u;try{u=await fetch(a,{method:"POST",headers:{"content-type":"application/json","x-anyray-connect-version":we},body:JSON.stringify({cert:t,challenge:i,sig:c,...r.health?{health:r.health}:{},...r.ack?{ack:r.ack}:{},...r.telemetryOnly?{telemetryOnly:!0}:{}}),signal:l.signal})}catch(y){let b=y instanceof Error&&y.name==="AbortError"?` no response within ${o}ms.`:gt(y);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:y})}finally{clearTimeout(d)}if(!u.ok)throw new Rt(u.status,await em(u));let f;try{f=await u.text()}catch{f=""}let p;try{p=JSON.parse(f)}catch{let y=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(y)||/^\s*<(?:!doctype|html)/i.test(f);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let h=Qe(p?.key);if(!h)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(h))throw new Error("developer verification failed: the gateway returned a malformed key");let m=Qe(p.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=cU(p.directive),g=iU(p.capabilities);return{key:h,user:m,team:Qe(p.team),expiresAt:Qe(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},Id=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Qh,s=`${e}/connect/key/heartbeat`,i=Qe(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:qh(16).toString("hex"),purpose:qv},l=tm(c,r,"heartbeat"),d=new AbortController,u=setTimeout(()=>d.abort(),a),f;try{f=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(m){let w=m instanceof Error&&m.name==="AbortError"?` no response within ${a}ms.`:gt(m);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:m})}finally{clearTimeout(u)}if(!f.ok)throw new Ir(f.status,await em(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=Qe(p.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||p.credentialMode!==Ai||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:Ai}},eS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Qh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=Qe(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:qh(16).toString("hex"),purpose:qv},d=tm(l,r,"heartbeat"),u=new AbortController,f=setTimeout(()=>u.abort(),s);try{return(await fetch(i,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(p){return console.error("connect machine report skipped:",p instanceof Error?p.name:"error"),!1}finally{clearTimeout(f)}},cU=e=>{if(e===null||typeof e!="object")return null;let t=e,n=Qe(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!sU.includes(r)?null:{id:n,kind:r}},lU=1e4,dU=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!Qe(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!Qe(r.deploymentId)&&!!Qe(r.user)&&!!Qe(r.devPublicKey)&&!!Qe(r.issuedAt)&&!!Qe(r.expiresAt)},uU=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??lU,s=`${e}/v1/enroll`,i=new AbortController,c=setTimeout(()=>i.abort(),a),l;try{l=await fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:t,devPublicKey:n,...r.email?{email:r.email}:{},...r.team?{team:r.team}:{},...r.machineId?{machineId:r.machineId}:{},...r.deploymentId?{deploymentId:r.deploymentId}:{}}),signal:i.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${a}ms.`:gt(u);throw new Error(`could not reach the control plane at ${s}.${f}`)}finally{clearTimeout(c)}if(!l.ok)throw new Error(`enrollment failed: ${await em(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!dU(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},tS=(e,t,n,r,o,a,s)=>{if(!e)return!1;let i=t?Date.parse(t):NaN;return!(!Number.isFinite(i)||i<=r||n&&e.payload.deploymentId!==n||o&&o!==a||s&&e.payload.user.trim().toLowerCase()!==s.trim().toLowerCase())},nS=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=Ed();return{cert:await uU(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),privateKeyPem:s.privateKeyPem,publicKeyPem:s.publicKeyPem}})(),a=await ln(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};import{createPrivateKey as gU,randomBytes as wU,sign as bU}from"node:crypto";var pU="https://app.anyray.ai",fU=new Set(["localhost","::1","[::1]"]),hU=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,mU=e=>fU.has(e)||hU.test(e),nm=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&mU(t.hostname)},yU=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Yn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!nm(e)?pU:yU(e)};var kU=1e4,CU="machine:",rS=e=>e.startsWith(CU),AU="cert-renew",vU=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||typeof t.sig!="string"||!t.sig.trim())return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n,o=a=>typeof a=="string"&&!!a.trim();return typeof r.v=="number"&&o(r.deploymentId)&&o(r.user)&&o(r.devPublicKey)&&o(r.issuedAt)&&o(r.expiresAt)},oS=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Yn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:wU(16).toString("hex"),purpose:AU},c;try{let h=gU(t),m=new TextEncoder().encode(ko(i));c=bU(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),kU),u;try{u=await r(`${a}/v1/cert/renew`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({cert:e,challenge:i,sig:c}),signal:l.signal})}finally{clearTimeout(d)}if(!u.ok)return{ok:!1,refused:u.status>=400&&u.status<500&&u.status!==429};let p=(await u.json().catch(()=>null))?.cert;return vU(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var rm=async(e,t=e.origin,n=se)=>{let r=0,o=0,a=!0;for(let s of n)try{if(!s.pointsAt||!await s.pointsAt(t)||await s.usesDynamicCredential?.(t))continue;r+=1,(await s.apply(e,{dryRun:!1})).status==="configured"?o+=1:a=!1}catch{a=!1}return{matched:r,rewritten:o,complete:a}},vi=async(e,t=e.origin,n=se)=>(await rm(e,t,n)).complete;var SU=["claude","codex","cursor","opencode"],EU=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],IU=new Set(["missing_key","key_expired"]);var xU=600*1e3,RU=600*1e3,aS=1440*60*1e3,OU=1440*60*1e3,_U=10080*60*1e3,TU=3600*1e3,PU=720*60*1e3,LU=e=>Math.min(PU,TU*2**Math.max(0,e-1)),Si=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ia=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,sS=e=>typeof e=="string"&&EU.includes(e),Sn=e=>{if(!Si(e))return{};let t={};if(Ia(e.watchSince)&&(t.watchSince=e.watchSince),Si(e.invoked)){let n={};for(let r of SU){let o=e.invoked[r];Ia(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return Si(e.authFailure)&&Ia(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...sS(e.authFailure.code)?{code:e.authFailure.code}:{}}),Si(e.repair)&&Ia(e.repair.at)&&(e.repair.outcome==="repaired"||e.repair.outcome==="repair_failed"||e.repair.outcome==="unverified")&&(t.repair={at:e.repair.at,outcome:e.repair.outcome,...Ia(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},xd=e=>{try{let n=JSON.parse(e);if(Si(n)&&sS(n.code)&&n.code!=="key_invalid")return n.code}catch{}let t=e.toLowerCase();if(t.includes("valid client key required"))return"key_invalid";if(t.includes("client key required"))return"missing_key"},om=e=>e!==void 0&&IU.has(e),am=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=xU},iS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),sm=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=RU},cS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),lS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,dS=(e,t,n)=>{if(n==="repair_failed"||n==="unverified")return{...e,repair:{at:t,outcome:n,failures:(e.repair?.failures??0)+1}};let{authFailure:r,...o}=e;return n==="repaired"?{...o,repair:{at:t,outcome:n}}:o},uS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>aS||!om(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<LU(r.failures??1))},Rd=e=>{let t=Object.values(e?.invoked??{}).filter(Ia);return t.length>0?Math.max(...t):null},im=(e,t)=>{if(Rd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=_U},pS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=OU)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=aS)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var cm="x-anyray-retrieve-probe",Od=8e3,DU=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",fS=(e,t)=>{let n=qt(e);return t?.probe&&(n[cm]="1"),n},xa=async(e,t,n)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let r=new AbortController,o=setTimeout(()=>r.abort(),Od);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:fS(e,n),body:JSON.stringify({handle:t,...n?.startLine!==void 0&&{startLine:n.startLine},...n?.endLine!==void 0&&{endLine:n.endLine},...n?.grep!==void 0&&{grep:n.grep}}),signal:r.signal});if(a.status===404)return await a.json().then(c=>typeof c=="object"&&c!==null).catch(()=>!1)?{ok:!1,kind:"not-found",message:`No stashed content for handle ${t} (unknown or expired).`}:{ok:!1,kind:"unsupported",message:"Gateway has no /connect/retrieve route (update the gateway image)."};if(!a.ok){let i=await a.json().catch(()=>{}),c=DU(i)&&i.code==="slice_unsupported";return{ok:!1,kind:a.status===401||a.status===403?"auth":c?"slice-unsupported":"unavailable",message:`Retrieval unavailable (gateway returned HTTP ${a.status}).`}}let s;try{s=await a.json()}catch{return{ok:!1,kind:"malformed",message:"Retrieval returned malformed JSON."}}return typeof s?.content!="string"?{ok:!1,kind:"malformed",message:"Retrieval returned no content."}:{ok:!0,content:s.content,...typeof s.totalLines=="number"&&{totalLines:s.totalLines},...typeof s.totalChars=="number"&&{totalChars:s.totalChars},...typeof s.partial=="boolean"&&{partial:s.partial},...typeof s.startLine=="number"&&{startLine:s.startLine},...typeof s.endLine=="number"&&{endLine:s.endLine},...typeof s.grepMatches=="number"&&{grepMatches:s.grepMatches},...typeof s.grepTruncated=="boolean"&&{grepTruncated:s.grepTruncated}}}catch(a){let s=a instanceof Error&&a.name==="AbortError";return{ok:!1,kind:s?"timeout":"network",message:s?"Retrieval timed out.":`Retrieval failed: ${a instanceof Error?a.message:String(a)}`}}finally{clearTimeout(o)}},_d=async(e,t,n,r)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let o=new AbortController,a=setTimeout(()=>o.abort(),Od);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:fS(e,r),body:JSON.stringify({query:t,...typeof n=="number"?{k:n}:{}}),signal:o.signal});if(!s.ok)return{ok:!1,kind:s.status===401||s.status===403?"auth":"unavailable",message:`Recall unavailable (gateway returned HTTP ${s.status}).`};let i;try{i=await s.json()}catch{return{ok:!1,kind:"malformed",message:"Recall returned malformed JSON."}}return Array.isArray(i?.matches)?{ok:!0,matches:i.matches}:{ok:!1,kind:"malformed",message:"Recall returned no matches list."}}catch(s){let i=s instanceof Error&&s.name==="AbortError";return{ok:!1,kind:i?"timeout":"network",message:i?"Recall timed out.":`Recall failed: ${s instanceof Error?s.message:String(s)}`}}finally{clearTimeout(a)}};var NU=5e3,$U=2048,MU=e=>{let t=e.toLowerCase();return t.includes("client key required")?!0:["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},Ra=async(e={})=>{let t=e.readTarget??rt,n=e.fetch??fetch,r=e.timeoutMs??NU,o=null;try{o=await t()}catch{o=null}if(!o)return{verdict:"dark",reason:"target_null"};let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let i=qt(o);i["content-type"]="application/json",i[cm]="1";let c=await n(`${o.origin}/connect/optimize-output`,{method:"POST",headers:i,body:JSON.stringify({}),signal:a.signal});if(c.status===401||c.status===403){let u=(await c.text().catch(()=>"")).slice(0,$U);if(!MU(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=xd(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...f?{code:f}:{}}}if(!c.ok)return{verdict:"indeterminate",reason:c.status>=500?"unreachable":"unsupported",status:c.status};let l;try{l=await c.json()}catch{return{verdict:"indeterminate",reason:"unsupported",status:c.status}}return typeof l=="object"&&l!==null&&l.handled===!0?{verdict:"live",reason:"ok",status:c.status}:{verdict:"indeterminate",reason:"gateway_mismatch",status:c.status}}catch{return{verdict:"indeterminate",reason:"unreachable"}}finally{clearTimeout(s)}},lm=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{createPrivateKey as FU,randomBytes as UU,sign as BU}from"node:crypto";var WU=500,hS=2e3,HU=2e3,KU=250,mS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),WU);try{return(await fetch(`${e}/connect/health`,{method:"POST",headers:{...t,"x-anyray-connect-version":r},body:JSON.stringify({events:n}),signal:o.signal})).ok}catch{return!1}finally{clearTimeout(a)}},GU=e=>{let t=e.headers?.get?.("retry-after");if(!t)return;let n=Number(t.trim());return Number.isFinite(n)&&n>=0?n*1e3:void 0},jU=e=>new Promise(t=>setTimeout(t,e)),VU=async(e,t,n=jU)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),hS),s;try{let i=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:t,signal:o.signal});if(i.ok)return!0;let c=i.status===429||i.status>=500;if(r>0||!c||(s=GU(i)??KU,s>HU))return!1}finally{clearTimeout(a)}await n(s)}},YU=async e=>{try{let n=(await L()).enrolledCert,r=await We(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:UU(16).toString("hex"),events:e},s;try{let i=FU(r),c=new TextEncoder().encode(ko(a));s=BU(null,c,i).toString("base64url")}catch{return!1}return await VU(`${Yn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},ZU=async(e,t)=>{try{let r=(await L()).enrolledCert,o=await We();if(!r||!o)return;await ln(e,r,o,{timeoutMs:hS,health:{events:t},telemetryOnly:!0})}catch{}},yS=async(e,t)=>{if(e.length!==0)try{let n=await rt(),r=n&&await mS(n.origin,qt(n),e,t);if(n&&await ZU(n.origin,e),r)return;await YU(e)}catch{}},dm=async(e,t,n={readTarget:()=>rt("profile"),post:mS})=>{if(e.length===0)return!1;try{let r=await n.readTarget();return r?await n.post(r.origin,{"content-type":"application/json"},e,t):!1}catch{return!1}};var Ao=["hook_registration","mcp_registration","hook_binary","beacon_target"];var wS=128,bS=300*1e3,JU=["repaired","repair_failed","flapping","pending"],XU=["settings_not_writable","apply_unconfirmed","apply_threw"],kS=["rebroke_same_day","repeat_days"],CS=new Set(se.map(e=>e.id)),Co=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ii=(e,t)=>typeof e=="string"&&t.some(n=>n===e),AS=e=>Ii(e,Ao),Td=e=>{if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=Date.parse(`${e}T00:00:00.000Z`);return Number.isFinite(t)&&new Date(t).toISOString().slice(0,10)===e},xr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Ei=e=>{if(!(!Array.isArray(e)||!e.every(AS)))return Zn(e)},zU=e=>{if(!Co(e))return;let t=Ei(e.checks);if(!(!xr(e.since)||!Ii(e.reason,kS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},qU=e=>{if(!Co(e))return;let t={};Td(e.day)&&(t.day=e.day),xr(e.attempts)&&(t.attempts=e.attempts);let n=Ei(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=Ei(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=Ei(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=Ei(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Td(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),xr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),Co(e.lastRepaired)){let i={};for(let c of Ao){let l=e.lastRepaired[c];xr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=zU(e.flapping);return s&&(t.flapping=s),t},QU=e=>{if(!Co(e)||!Td(e.day)||!xr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!CS.has(e.tool)||!AS(e.checkId)||!Ii(e.status,JU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!Ii(e.errorClass,XU))return;t=e.errorClass}else if(e.status==="flapping"){if(!Ii(e.errorClass,kS))return;t=e.errorClass}else if(e.errorClass!==void 0)return;return{day:e.day,sequence:e.sequence,tool:e.tool,checkId:e.checkId,status:e.status,...t?{errorClass:t}:{},delivered:e.delivered,...xr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},gS=e=>{if(!Co(e))return{};let t={};if(Co(e.adapters)){let n={};for(let r of CS){let o=qU(e.adapters[r]);o&&(n[r]=o)}Object.keys(n).length>0&&(t.adapters=n)}return Array.isArray(e.events)&&(t.events=e.events.map(QU).filter(n=>n!==void 0).slice(-wS)),xr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Co(e.report)&&Td(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...xr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},eB=e=>new Date(e).toISOString().slice(0,10),tB=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Zn=e=>[...new Set(e)],Pd=(e,t)=>{let n=e??{};if(n.day===t)return n;let r=n.day!==void 0&&n.dayHadNeed===!1;return{...n,day:t,attempts:0,attemptedChecks:[],confirmedChecks:[],brokenReportedChecks:[],dayHadNeed:!1,...r?{consecutiveRepairDays:0,lastConfirmedDay:void 0,flapping:void 0}:{}}},xi=(e,t,n)=>{let r=e.nextSequence??1,o=n.map(a=>({...a,day:t,sequence:r++,delivered:!1}));return{...e,events:[...(e.events??[]).filter(a=>a.day===t),...o].slice(-wS),nextSequence:r}},nB=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),rB=async e=>await _e(async()=>e,void 0,be)??null,oB=async(e,t,n)=>{let r=new Map(e.map(({adapter:o,checks:a})=>[o.id,Object.values(a).some(s=>s==="missing")]));await n.claimState(o=>{let a={...o.adapters??{}};for(let{adapter:s}of e){let i=Pd(a[s.id],t);a[s.id]={...i,dayHadNeed:!!(i.dayHadNeed||r.get(s.id))}}return{next:{...o,adapters:a,events:(o.events??[]).filter(s=>s.day===t)},result:void 0}},void 0)},vS=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:tB(e.lastConfirmedDay,n)?(e.consecutiveRepairDays??0)+1:1,a=o>=3,s={...e.lastRepaired??{}};for(let c of t)s[c]=r;let i=e.flapping;return{adapter:{...e,confirmedChecks:Zn([...e.confirmedChecks??[],...t]),brokenReportedChecks:(e.brokenReportedChecks??[]).filter(c=>!t.includes(c)),lastConfirmedDay:n,consecutiveRepairDays:o,lastRepaired:s,...a?{flapping:{since:i?.since??r,reason:"repeat_days",checks:Zn([...i?.checks??[],...t])}}:{}},slowFlap:a}},aB=async(e,t,n,r,o)=>{let a=new Map(e.map(s=>[s.adapter.id,s]));await o.claimState(s=>{let i=s,c={...s.adapters??{}};for(let[l,d]of Object.entries(c)){let u=Pd(d,n),f=u.awaiting??[],p=a.get(l);if(f.length===0||t.has(l)||!p){c[l]=u;continue}let h=f.filter(y=>p.checks[y]==="owned"),m=f.filter(y=>{let b=p.checks[y];return b==="missing"||b==="foreign"}),w=f.filter(y=>{let b=p.checks[y];return b===void 0||b==="unreadable"}),g=vS(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=xi(i,n,[...h.map(y=>({tool:l,checkId:y,status:"repaired"})),...m.map(y=>({tool:l,checkId:y,status:"repair_failed",errorClass:"apply_unconfirmed"})),...g.slowFlap?h.map(y=>({tool:l,checkId:y,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},sB=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Pd(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(g=>!d.includes(g)||u.includes(g)),p=f.filter(g=>u.includes(g)),h=l.attempts??0;if(h>=2||f.length===0&&!n){let g=p.filter(A=>!(l.brokenReportedChecks??[]).includes(A));if(g.length===0)return{result:void 0};let y=l.flapping;return c[e]={...l,brokenReportedChecks:Zn([...l.brokenReportedChecks??[],...g]),flapping:{since:y?.since??a,reason:"rebroke_same_day",checks:Zn([...y?.checks??[],...g])}},{next:xi({...i,adapters:c},o,g.map(A=>({tool:e,checkId:A,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let m=l.flapping;return c[e]={...l,attempts:h+1,attemptedChecks:Zn([...d,...f]),confirmedChecks:u.filter(g=>!f.includes(g)),brokenReportedChecks:Zn([...l.brokenReportedChecks??[],...p]),...p.length>0?{flapping:{since:m?.since??a,reason:"rebroke_same_day",checks:Zn([...m?.checks??[],...p])}}:{}},{next:xi({...i,adapters:c},o,p.map(g=>({tool:e,checkId:g,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),iB=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Pd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:Zn([...l.awaiting??[],...t])},{next:xi({...i,adapters:c},o,t.map(h=>({tool:e,checkId:h,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(h=>r[h]==="owned"):[],u=n.status==="configured"&&r?t.filter(h=>{let m=r[h];return m==="missing"||m==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=vS(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:xi({...i,adapters:c},o,[...d.map(h=>({tool:e,checkId:h,status:"repaired"})),...u.map(h=>({tool:e,checkId:h,status:"repair_failed",errorClass:p})),...f.slowFlap?d.map(h=>({tool:e,checkId:h,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},cB=async(e,t,n,r)=>{let o=await r.claimState(i=>{let c=(i.events??[]).filter(u=>u.day===e&&!u.delivered&&(u.attemptedAt===void 0||u.attemptedAt>t||t-u.attemptedAt>=bS));if(c.length===0)return{result:[]};let l=new Set(c.map(u=>`${u.day}:${u.sequence}`)),d=(i.events??[]).map(u=>l.has(`${u.day}:${u.sequence}`)?{...u,attemptedAt:t}:u);return{next:{...i,events:d},result:c.map(u=>({...u,attemptedAt:t}))}},[]);if(o.length===0||!await(r.report??dm)(o.map(nB),n).catch(()=>!1))return;let s=new Set(o.map(i=>`${i.day}:${i.sequence}`));await r.claimState(i=>({next:{...i,events:(i.events??[]).map(c=>s.has(`${c.day}:${c.sequence}`)?{...c,delivered:!0}:c)},result:void 0}),void 0)},lB=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:f}of t){let p=r.adapters?.[u.id];for(let h of Ao){let m=f[h];if(!m||m==="unreadable")continue;let w,g;p?.awaiting?.includes(h)&&c.has(u.id)?w="pending":m==="missing"&&p?.flapping?.checks.includes(h)?(w="flapping",g=p.flapping.reason):w=m==="owned"?"ok":m,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:h,status:w,...g?{errorClass:g}:{}})}}let l=Date.parse(e.enrolledCert?.payload.expiresAt??e.enrolledCertExpiry??"");e.enrolledCert&&Number.isFinite(l)&&(l<=o?(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"expired"})):l-o<=336*60*60*1e3&&(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"problems",errorClass:"cert_expiring"}))),e.refreshSchedulerEnabled&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Yo)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??hr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=pS(await a.readHookLane?.().catch(()=>({})),o);return d&&(d.status!=="repaired"&&(i=!0),s.push({tool:"connect",checkId:"hook_lane",status:d.status,...d.errorClass?{errorClass:d.errorClass}:{}})),s.push({tool:"connect",checkId:"selfcheck_report",status:i?"problems":"ok"}),s},dB=async(e,t,n,r,o,a,s)=>{if(!await s.claimState(u=>u.report?.day===r&&u.report.delivered?{result:!1}:u.report?.day===r&&u.report.attemptedAt!==void 0&&u.report.attemptedAt<=o&&o-u.report.attemptedAt<bS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await lB(e,t,n,c,o,s);await(s.report??dm)(l,a).catch(()=>!1)&&await s.claimState(u=>u.report?.day===r?{next:{...u,report:{day:r,delivered:!0}},result:void 0}:{result:void 0},void 0)},SS=async(e,t,n)=>{let r=n.now??Date.now,o=eB(r()),a=e.managedTools??[],s={...n,readState:async()=>gS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(gS(l)),c)};try{let i=await(s.findIntegrations??zh)(a);await oB(i,o,s);let c=await(s.listPending??pr)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await aB(i,l,o,r(),s);let d=await(s.resolveTarget??rB)(e),u=d?await(s.findDrifted??Er)(a,d.toolOrigin):[],f=new Set(u.map(g=>g.id)),p=new Map(i.map(g=>[g.adapter.id,g]));for(let g of u)p.has(g.id)||p.set(g.id,{adapter:g,checks:{}});let h=!1,m=(s.runtimeDurable??le)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?Ao.filter(T=>y[T]==="missing"):[];if(b.length===0&&!f.has(g.id))continue;let A=y;if(g.integrationStatus)try{A=await g.integrationStatus()}catch{A=Object.fromEntries(Ao.map(T=>[T,"unreadable"]))}let v=b.filter(T=>A[T]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),v.length===0&&!E)continue;let I=await sB(g.id,v,E,l.has(g.id),o,r(),s);if(!I)continue;let[C]=await(s.repair??yt)([g],d.target);if(!C)continue;h=!0;let x;C.status==="configured"&&g.integrationStatus&&(x=await g.integrationStatus().catch(()=>{})),await iB(g.id,I.checks,C,x,o,r(),s)}await cB(o,r(),t,s),i=await(s.findIntegrations??zh)(a);let w=await(s.listPending??pr)().catch(()=>[]);return await dB(e,i,w,o,r(),t,s),h}catch{return!1}};var wB=14,bB=.35,kB=900*1e3,IS=360*60*1e3,CB=.2,AB=1800*1e3,xS=3600*1e3,vB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),SB=300*1e3,EB=30*1e3,IB=900*1e3,xB=(e=0)=>Math.min(IB,EB*2**Math.max(0,e)),RS=e=>{let t=e;for(let n=0;n<5&&t;n++){let r=t.code;if(typeof r=="string")return r;t=t.cause}},RB=720*60*1e3,OS=1440*60*1e3,OB=300*1e3,_B=.25,TB=.5,_S=3600*1e3,PB=720*60*60*1e3,LB=360*60*1e3,DB=1440*60*1e3,NB=4,Ld=e=>fB("sha256").update(e).digest("hex").slice(0,32),MS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Gt)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??L)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(Ld(e))},um=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,NB)}),$B=()=>NS(hB(),".anyray"),fm=()=>NS($B(),"refresh-state.json"),hm=e=>process.env?.[e],FS=()=>hm("ANYRAY_REFRESH_DISABLE")==="true",mm=()=>{let e=hm("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:wB)*DB},Oi=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},US=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),MB=10080*60*1e3,Dd=(e,t,n=Date.now())=>{let r=[],o=Oi(e);o!==void 0&&r.push(o);let a=Date.parse(t??e.clientKeyExpiresAt??"");Number.isFinite(a)&&r.push(a-n);let s=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??"");return Number.isFinite(s)&&r.push(s-n),r.length===0?!1:Math.min(...r)<=MB},_i=e=>{let t=mm(),n=e?Oi(e):void 0;if(!n)return t;let r=Math.max(kB,Math.round(n*bB));return Math.min(t,r)},FB=e=>{let t=hm("ANYRAY_REFRESH_THROTTLE_MS"),n=t?Number.parseInt(t,10):NaN;return Number.isFinite(n)&&n>0?n:typeof e=="number"&&Number.isFinite(e)&&e>0?Math.min(IS,Math.max(AB,Math.round(e*CB))):IS},Gt=async()=>{try{let e=await mB(fm(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Nd=async e=>{try{let t=fm(),n=`${t}.${process.pid}.tmp`;await $S(n,JSON.stringify(e),{mode:384}),await he(n,t),await yB(t,384).catch(()=>{})}catch{}},UB=3e4,BB=()=>`${fm()}.lock`,TS=async e=>{try{return await $S(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},ut=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Gt,a=n.writeState??Nd,s=BB(),i=!1;try{if(i=await TS(s),!i){if(await gB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<UB)return t;await ES(s).catch(()=>{}),i=await TS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await ES(s).catch(()=>{})}},Ri=async(e,t={})=>{await ut(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Oa=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0),a=await(t.loadProfile??L)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?Ld(a.clientKey):void 0;await ut(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:um(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},vo=async(e={})=>{let t=e.now??Date.now;await ut(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},WB=e=>{let t=e.enrolledCertLifetimeMs,n=Date.parse(e.enrolledCert?.payload.issuedAt??""),r=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??""),o=typeof t=="number"&&Number.isFinite(t)&&t>0?t:Number.isFinite(n)&&Number.isFinite(r)&&r>n?r-n:void 0;return o?Math.min(PB,Math.max(_S,Math.round(o*TB))):_S},pm=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,ym=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??re,a=n.loadProfile??L,s=n.loadDevKey??We,i=n.renew??oS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(rS(c.payload.user))return{outcome:"not-due",profile:e};let l=Date.parse(e.enrolledCertExpiry??c.payload.expiresAt??"");if(!Number.isFinite(l))return{outcome:"not-due",profile:e};if(l-r()>WB(e))return{outcome:"not-due",profile:e};if(!await ut(w=>r()-(w.lastCertRenewAt??0)<LB?{result:!1}:{next:{...w,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await pm(f,c.sig,t,s))return{outcome:"superseded",profile:f};let p=u.cert.payload.expiresAt,h=Date.parse(p)-r(),m={...f,enrolledCert:u.cert,enrolledCertExpiry:p,...Number.isFinite(h)&&h>0?{enrolledCertLifetimeMs:h}:{}};return await o(m),{outcome:"renewed",profile:m}},PS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*_B):OS,r=Math.min(OS,n);return Math.min(r,OB*2**Math.max(0,e-1))},HB=()=>{let{command:e,args:t}=fn(rr);return{exe:e,args:t}},Rr=async(e={})=>{if(FS())return;let t=e.now??Date.now,n=e.readState??Gt,r=e.writeState??Nd,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=HB();pB(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await ut(s=>t()-(s.lastSpawnAt??0)<FB(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},KB=vi,GB=async(e,t=be,n=!1)=>{try{let r=e.managedTools??[];if(r.length===0)return!1;let o=await _e(async()=>e,void 0,t);if(!o)return!1;let a=await Er(r,o.toolOrigin),s=n?Wv(a):a;return s.length===0?!1:(await yt(s,o.target),!0)}catch{return!1}},jB=async(e,t,n,r,o,a)=>{try{let s=new Set(e.managedTools??[]),i=se.filter(p=>s.has(p.id));if(i.length===0)return!1;let c=await r().catch(()=>{}),l=ge({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:c,user:e.name,team:e.team}),d=e.fallbackPort,u=nt(e)&&Number.isInteger(d)&&d>0&&d<=65535&&await o(d)!==null,f=await a(u?In(l,d):l,u?`http://${ft}:${d}`:l.origin,i);return f.matched>0&&f.complete}catch{return!1}},VB=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Gt,a=t.writeState??Nd;return SS(e,we,{now:r,deadWatcherObserved:n,readHookLane:()=>$d({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>ut(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},$d=async(e={})=>{let n=await(e.readState??Gt)().catch(()=>({}));return Sn(n.hookLane)},BS=async(e,t={})=>{try{let n=t.now??Date.now,r=await $d(t);if(!am(r,e,n()))return;await ut(o=>{let a=Sn(o.hookLane);return am(a,e,n())?{next:{...o,hookLane:iS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},WS=async(e,t={})=>{try{let n=t.now??Date.now,r=await $d(t);if(!sm(r,n()))return;await ut(o=>{let a=Sn(o.hookLane);return sm(a,n())?{next:{...o,hookLane:cS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},YB=async(e={})=>{try{let t=e.now??Date.now;if((await $d(e)).watchSince!==void 0)return;await ut(n=>{let r=Sn(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:lS(r,t())},result:void 0}},void 0,e)}catch{}},LS=async(e,t={})=>{try{let n=t.now??Date.now;await ut(r=>{let o=Sn(r.hookLane),a=dS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},HS=async(e={})=>{try{if((await(e.readState??Gt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>ut(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??Dg)())return await r()?"stamped":"skipped";let o=await(e.load??L)(),s=await(e.findTools??bo)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await _e(async()=>o,void 0,e.probe??be);return!i||!await r()?"skipped":(await(e.repair??yt)(s,i.target),"repathed")}catch{return"skipped"}},KS=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Gt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>ut(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??L)(),i=await(e.findTools??bo)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await _e(async()=>a,void 0,e.probe??be);return!c||!await o()?"skipped":(await(e.repair??yt)(i,c.target)).some(d=>d.status==="failed")?(await ut(d=>{if(d.appliedRevision!==t)return{result:void 0};let u={...d};return r===void 0?delete u.appliedRevision:u.appliedRevision=r,{next:u,result:void 0}},void 0,e).catch(()=>{}),"retry"):"swept"}catch{return"skipped"}},ZB=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await vd(e.gateway,e.clientKey),n=await Sd(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},DS=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??ZB)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>GB(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},et=async(e={})=>{if(FS())return"disabled";let t=e.now??Date.now,n=e.loadProfile??L,r=e.saveProfile??re,o=e.loadDevKey??We,a=e.readState??Gt,s=e.writeState??Nd,i=e.remint??ln,c=e.heartbeat??Id,l=e.detectSeat??$t,d=e.rewriteTools??KB,u=e.rewriteHookLaneTools??rm,f=e.probeHookLane??Ra,p=e.classifyBeacon??Sc,h=e.probe??be,m=e.installProxy??Nt,w=e.pickProxyPort??Oc,g=e.force===!0,y=!1,b=!1,A=!1,v=!1;e.hookLaneRepair===!0&&(g=!0,v=!0);let E=async C=>{if(!v){C==="repaired"&&await LS("none",{now:t,readState:a,writeState:s});return}let x=C;if(C==="repaired"){let T=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));x=T.verdict==="live"?"repaired":T.verdict==="dark"?"repair_failed":"unverified"}await LS(x,{now:t,readState:a,writeState:s})},I=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(T=>VB(T,{now:t,readState:a,writeState:s},A)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(A=await pr().then(O=>O.some(P=>!hr(P.watcherPid))).catch(()=>!1),await YB({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??hb)();let C=await n();if(y=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let x=C.gateway,T=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(T)||T<=t())return"cert-expired";let $=await o();if(!$)return"not-enrolled";let Y=await ym(C,$,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=Y.profile;let Z=Y.outcome==="renewed",W=C.enrolledCert;if(!W)return"not-enrolled";let z=Date.parse(C.clientKeyExpiresAt??""),me=Number.isFinite(z)?z-t():0,Le=await a(),ne=!C.clientKey||me<=_i(C),Ke=C.credentialProtocol!=="stable-heartbeat-v1"&&t()-(Le.lastSuccessAt??0)>=RB;if(!g&&uS(Sn(Le.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,v=!0),C.credentialProtocol==="stable-heartbeat-v1"&&C.clientKey&&(g||ne)){let O=await ut(P=>{let H=t()-(P.lastAttemptAt??0);return H<xS?{result:"throttled"}:P.failureCount&&H<PS(P.failureCount,P.keyTtlMs)?{result:"backoff"}:{next:{...P,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(O!=="ok")return O;try{let P=await c(x,C.clientKey,W,$),H=await n().catch(()=>C);return H.clientKey!==C.clientKey||H.enrolledCert?.sig!==W.sig?"failed":(await r({...H,clientKeyExpiresAt:P.expiresAt}),await Ri(({lastError:fe,...q})=>({...q,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Oi(C)??q.keyTtlMs}),{now:t,readState:a,writeState:s}),v&&await E(await jB(C,x,C.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(P){let H=P;if(P instanceof Ir&&P.status===404)try{let q=await i(x,W,$),Ye=await l().catch(()=>{}),Ue=ge({origin:x,clientKey:q.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Ye,user:C.name,team:C.team}),ee=C.fallbackPort,Be=Number.isInteger(ee)&&ee>0&&ee<=65535?ee:await w();if(!(await m({port:Be,remoteOrigin:x})).ok||await h(Be)===null)throw new Error("key-refresh proxy recovery failed");let V=await n().catch(()=>C);if(!await pm(V,W.sig,$,o))throw new Error("enrollment changed during proxy recovery");if(await r({...V,clientKey:q.key,clientKeyExpiresAt:q.expiresAt??V.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:Be}),await d(In(Ue,Be),Ue.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let Ee=q.expiresAt?Date.parse(q.expiresAt):NaN,bt=Oi(C)??(Number.isFinite(Ee)&&Ee-t()>0?Ee-t():void 0);return await Ri(({lastError:qn,...Tt})=>({...Tt,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:bt??Tt.keyTtlMs,ownKeys:um(Tt.ownKeys,W.sig,Ld(q.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(q){H=q}let fe=RS(H);return await Ri(q=>({...q,lastAttemptAt:t(),failureCount:(q.failureCount??0)+1,lastError:{name:H instanceof Error?H.name:"Error",...fe!==void 0?{code:fe}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),H instanceof Ir?"cert-rejected":"failed"}}if(!g&&C.clientKey&&!ne&&!Ke){let O=await DS(C,e,n,h),P=await I();return O||P?"repaired":Z?"cert-renewed":"not-due"}let De=await ut(O=>{let P=t()-(O.lastAttemptAt??0);if(g)return P<xB(O.failureCount)?{result:"throttled"}:{next:{...O,lastAttemptAt:t()},result:"ok"};let H=O.lastError?.code!==void 0&&vB.has(O.lastError.code)?SB:xS;return P<H?{result:"throttled"}:O.failureCount&&P<PS(O.failureCount,O.keyTtlMs)?{result:"backoff"}:{next:{...O,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(De!=="ok")return De;try{let O=await i(x,W,$),P=await l().catch(()=>{}),H=ge({origin:x,clientKey:O.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:P,user:C.name,team:C.team}),fe=H,q=H.origin;if(nt(C)){if(!Number.isInteger(C.fallbackPort)||C.fallbackPort<1||C.fallbackPort>65535)throw new Error("key-refresh proxy profile has no valid port");await h(C.fallbackPort)!==null&&(fe=In(H,C.fallbackPort),q=`http://${ft}:${C.fallbackPort}`)}let Ye=await d(fe,q);if(C.directMigration==="pending"&&fe.viaLocalProxy===!0){let Ee=await d(fe,H.origin);Ye=Ye!==!1&&Ee!==!1}if(Ye===!1)throw new Error("one or more configured tools rejected the refreshed key");let Ue=await n().catch(()=>C),ee=null,Be;Ue.enrolledCert&&await pm(Ue,W.sig,$,o)&&(Be=Ld(O.key),ee={...Ue,clientKey:O.key,clientKeyExpiresAt:O.expiresAt??Ue.clientKeyExpiresAt},await r(ee));let Ne=O.expiresAt?Date.parse(O.expiresAt):NaN,V=Oi(C)??(Number.isFinite(Ne)&&Ne-t()>0?Ne-t():void 0);return await Ri(({lastError:Ee,...bt})=>({...bt,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:V??bt.keyTtlMs,...Be?{ownKeys:um(bt.ownKeys,W.sig,Be)}:{}}),{now:t,readState:a,writeState:s}),ee&&await DS(ee,e,n,h),await E(ee?"repaired":"repair_failed"),await I(),"refreshed"}catch(O){let P=RS(O);return await Ri(H=>({...H,lastAttemptAt:t(),failureCount:(H.failureCount??0)+1,lastError:{name:O instanceof Error?O.name:"Error",...P!==void 0?{code:P}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),O instanceof Rt?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await I()}catch{}}};import{readFile as tW}from"node:fs/promises";import{isAbsolute as nW,posix as ZS,win32 as bm}from"node:path";var gm=1e4,JB=900*1e3,jS="tnt_",XB=/^\/sso\/([^/]+)\/?$/,zB=/^\/i\/([^/]+)\/?$/,qB=e=>{let t=e.match(XB);if(t)return t[1];let n=e.match(zB);return n?.[1].startsWith(jS)?n[1]:void 0},Ot=e=>{let t=e.trim();if(!t)return;let n;try{n=new URL(t)}catch{n=void 0}if(n){if(n.protocol!=="http:"&&n.protocol!=="https:")return;let r=qB(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(jS))return{cpOrigin:Yn(),tenantId:t}},So=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},jt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},wm=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await r(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:o.signal}),i={};try{i=await s.json()}catch{}return{status:s.status,json:i}}finally{clearTimeout(a)}},QB=e=>new Promise(t=>setTimeout(t,e)),Md=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Ed)(),a;try{a=await wm(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},gm,n)}catch(h){throw new So("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${gt(h)}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new So(h?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${m}). Ask your admin to confirm SSO is configured.`,a.status)}let s=a.json;if(!s.device_code||!s.user_code||!s.verification_uri_complete)throw new So("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??JB,l=typeof s.expires_in=="number"&&s.expires_in>0?s.expires_in*1e3:c,d=typeof s.verification_uri=="string"?s.verification_uri:void 0,u=e.gatewayUrl??(typeof s.gateway_url=="string"?s.gateway_url:void 0),f={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:s.device_code,userCode:s.user_code,verificationUri:d,verificationUriComplete:s.verification_uri_complete,intervalMs:Math.max(1,s.interval||5)*1e3,grantExpiresAt:i+Math.min(c,l),startedAt:i,privateKeyPem:o,publicKeyPem:r,gatewayUrl:u},p=e.log??(()=>{});return p("To finish, sign in with your organization at:"),p(` ${f.verificationUriComplete}`),p(`Confirm this code matches your browser: ${f.userCode}`),eW(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},eW=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Fd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??QB,o=t.fetch??fetch,a=t.pollIntervalMs??e.intervalMs;for(;n()<e.grantExpiresAt&&(await r(Math.min(a,e.grantExpiresAt-n())),!(n()>=e.grantExpiresAt));){let s;try{s=await wm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},gm,o)}catch(c){throw new jt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${gt(c)}`)}if(s.status===200&&s.json.cert)return{cert:s.json.cert,privateKeyPem:e.privateKeyPem,gatewayUrl:t.gatewayUrl??(typeof s.json.gatewayUrl=="string"?s.json.gatewayUrl:e.gatewayUrl),deploymentId:typeof s.json.deploymentId=="string"?s.json.deploymentId:""};let i=typeof s.json.error=="string"?s.json.error:"";if(i!=="authorization_pending"){if(i==="slow_down"){a+=5e3;continue}throw i==="expired_token"?new jt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new jt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new jt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var GS="sdc_",VS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(GS))return{cpOrigin:Yn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!nm(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(GS)))return{cpOrigin:n.origin,claim:r}},YS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Ed)(),o;try{o=await wm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},gm,t)}catch(s){throw new jt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${gt(s)}`)}if(o.status===200&&o.json.cert)return{cert:o.json.cert,privateKeyPem:r,gatewayUrl:e.gatewayUrl??(typeof o.json.gatewayUrl=="string"?o.json.gatewayUrl:void 0),deploymentId:typeof o.json.deploymentId=="string"?o.json.deploymentId:"",...typeof o.json.ssoLink=="string"&&o.json.ssoLink?{ssoLink:o.json.ssoLink}:{}};let a=typeof o.json.error=="string"?o.json.error:"";throw a==="expired_token"?new jt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new jt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new jt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};var Ti=(e=process.platform,t=process.env)=>e==="darwin"?ZS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?bm.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):ZS.join("/etc","anyray","bootstrap.json"),rW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),JS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(nW(e)||bm.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),oW=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&!t.username&&!t.password}catch{return!1}},Vt=async(e=Ti())=>{try{let t=await tW(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!rW(n)||n.v!==1||typeof n.sso!="string")return;let r=Ot(n.sso);if(!r)return;let o=oW(n.gateway)?n.gateway:void 0,a=JS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},XS=(e,t,n)=>{let r=Ot(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!JS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&bm.isAbsolute(n)&&/^[A-Za-z]:\\/.test(n)&&!/^[A-Za-z]:\\Program Files( \(x86\))?\\/i.test(n))throw new Error("--bin on Windows must live under Program Files (admin-only writable)");return`${JSON.stringify({v:1,sso:`${r.cpOrigin}/sso/${r.tenantId}`,...t?{gateway:t}:{},...n?{bin:n}:{}},null,2)}
296
- `};import{execFile as OW}from"node:child_process";import{chmod as aW,readFile as sW,rm as zS,writeFile as iW}from"node:fs/promises";import{join as cW}from"node:path";var km=()=>cW(Q(),"sso-gate.json"),lW=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=a=>t[a]===void 0||typeof t[a]=="number"&&Number.isFinite(t[a]),r=a=>t[a]===void 0||typeof t[a]=="string",o=new Set(["cp-unreachable","sso-unavailable","denied","expired","gateway-unreachable"]);return t.v===1&&(t.status===void 0||t.status==="pending")&&r("userCode")&&r("verificationUriComplete")&&n("grantExpiresAt")&&n("startedAt")&&n("pollerPid")&&n("lastAttemptAt")&&n("failureCount")&&(t.lastFailure===void 0||typeof t.lastFailure=="string"&&o.has(t.lastFailure))},Or=async()=>{try{let e=JSON.parse(await sW(km(),"utf-8"));return lW(e)?e:null}catch{return null}},dW=0,Ud=async e=>{await kt();let t=km(),n=`${t}.${process.pid}.${dW++}.tmp`;try{await iW(n,`${JSON.stringify(e)}
297
- `,{mode:384}),await aW(n,384),await he(n,t)}catch(r){throw await zS(n,{force:!0}).catch(()=>{}),r}},qS=async()=>{await zS(km(),{force:!0}).catch(()=>{})},QS=e=>{if(!e||!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}};import{spawn as fW}from"node:child_process";import{homedir as hW}from"node:os";import{join as mW}from"node:path";import{spawn as uW}from"node:child_process";import{platform as pW}from"node:os";var _a=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=pW(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=uW(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var yW=3e4,gW=5*6e4,wW=30*6e4,bW=e=>{let t={};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--sso":t.sso=o();break;case"--gateway":t.gateway=o();break;case"--team":t.team=o();break;case"--session-start":t.sessionStart=!0;break;default:throw new Error("invalid SSO gate arguments")}}if(!t.sso)throw new Error("missing --sso");return t},kW=()=>mW(hW(),".claude","settings.json"),CW=async e=>{try{let n=(await U(kW())).env;if(!n)return!1;let r=pn(e).env;for(let[o,a]of Object.entries(r))if(n[o]!==a)return!1;return n.ANTHROPIC_AUTH_TOKEN===void 0}catch{return!1}},AW=async e=>{await sr.apply(e,{dryRun:!1})},vW=()=>{let{command:e,args:t}=fn("__anyray-sso-poll");return{exe:e,args:t}},SW=()=>{let{exe:e,args:t}=vW(),n=fW(e,t,{detached:!0,stdio:["pipe","ignore","ignore"]});return n.on("error",()=>{}),n.unref(),n.stdin?.on("error",()=>{}),{pid:n.pid,handoff:r=>{n.stdin?.end(JSON.stringify(r))}}},EW=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},eE=(e,t,n,r)=>ge({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),Ta=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},tE=e=>`Anyray: one-time sign-in required to use AI tools on this device.
295
+ `;import{createHash as iU,createPrivateKey as cU,generateKeyPairSync as lU,randomBytes as em,sign as dU}from"node:crypto";var tm=1e4,bo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(bo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${bo(e[n])}`).join(",")}}`,Si="stable-key-heartbeat-v1",Qv="key-heartbeat",uU=["reapply_config","remint","revert"];var eS=e=>iU("sha256").update(e).digest("hex"),et=e=>typeof e=="string"&&e.trim()?e.trim():void 0,pU=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],nm=async e=>{try{let t=await e.json(),n=et(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},Ot=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Ir=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},rm=(e,t,n)=>{try{let r=cU(t),o=new TextEncoder().encode(bo(e));return dU(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Id=()=>{let{publicKey:e,privateKey:t}=lU("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},ln=async(e,t,n,r={})=>{let o=r.timeoutMs??tm,a=`${e}/connect/verify`,s=et(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:em(16).toString("hex")},c=rm(i,n,"verification"),l=new AbortController,d=setTimeout(()=>l.abort(),o),u;try{u=await fetch(a,{method:"POST",headers:{"content-type":"application/json","x-anyray-connect-version":we},body:JSON.stringify({cert:t,challenge:i,sig:c,...r.health?{health:r.health}:{},...r.ack?{ack:r.ack}:{},...r.telemetryOnly?{telemetryOnly:!0}:{}}),signal:l.signal})}catch(y){let b=y instanceof Error&&y.name==="AbortError"?` no response within ${o}ms.`:wt(y);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:y})}finally{clearTimeout(d)}if(!u.ok)throw new Ot(u.status,await nm(u));let f;try{f=await u.text()}catch{f=""}let p;try{p=JSON.parse(f)}catch{let y=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(y)||/^\s*<(?:!doctype|html)/i.test(f);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let h=et(p?.key);if(!h)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(h))throw new Error("developer verification failed: the gateway returned a malformed key");let m=et(p.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=fU(p.directive),g=pU(p.capabilities);return{key:h,user:m,team:et(p.team),expiresAt:et(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},Od=async(e,t,n,r,o={})=>{let a=o.timeoutMs??tm,s=`${e}/connect/key/heartbeat`,i=et(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:em(16).toString("hex"),purpose:Qv},l=rm(c,r,"heartbeat"),d=new AbortController,u=setTimeout(()=>d.abort(),a),f;try{f=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(m){let w=m instanceof Error&&m.name==="AbortError"?` no response within ${a}ms.`:wt(m);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:m})}finally{clearTimeout(u)}if(!f.ok)throw new Ir(f.status,await nm(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=et(p.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||p.credentialMode!==Si||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:Si}},tS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??tm,i=`${e.replace(/\/$/,"")}/connect/machine`,c=et(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:em(16).toString("hex"),purpose:Qv},d=rm(l,r,"heartbeat"),u=new AbortController,f=setTimeout(()=>u.abort(),s);try{return(await fetch(i,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(p){return console.error("connect machine report skipped:",p instanceof Error?p.name:"error"),!1}finally{clearTimeout(f)}},fU=e=>{if(e===null||typeof e!="object")return null;let t=e,n=et(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!uU.includes(r)?null:{id:n,kind:r}},hU=1e4,mU=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!et(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!et(r.deploymentId)&&!!et(r.user)&&!!et(r.devPublicKey)&&!!et(r.issuedAt)&&!!et(r.expiresAt)},yU=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??hU,s=`${e}/v1/enroll`,i=new AbortController,c=setTimeout(()=>i.abort(),a),l;try{l=await fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:t,devPublicKey:n,...r.email?{email:r.email}:{},...r.team?{team:r.team}:{},...r.machineId?{machineId:r.machineId}:{},...r.deploymentId?{deploymentId:r.deploymentId}:{}}),signal:i.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${a}ms.`:wt(u);throw new Error(`could not reach the control plane at ${s}.${f}`)}finally{clearTimeout(c)}if(!l.ok)throw new Error(`enrollment failed: ${await nm(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!mU(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},nS=(e,t,n,r,o,a,s)=>{if(!e)return!1;let i=t?Date.parse(t):NaN;return!(!Number.isFinite(i)||i<=r||n&&e.payload.deploymentId!==n||o&&o!==a||s&&e.payload.user.trim().toLowerCase()!==s.trim().toLowerCase())},rS=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=Id();return{cert:await yU(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),privateKeyPem:s.privateKeyPem,publicKeyPem:s.publicKeyPem}})(),a=await ln(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};import{createPrivateKey as AU,randomBytes as vU,sign as SU}from"node:crypto";var gU="https://app.anyray.ai",wU=new Set(["localhost","::1","[::1]"]),bU=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,kU=e=>wU.has(e)||bU.test(e),om=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&kU(t.hostname)},CU=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Xn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!om(e)?gU:CU(e)};var EU=1e4,xU="machine:",oS=e=>e.startsWith(xU),IU="cert-renew",OU=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||typeof t.sig!="string"||!t.sig.trim())return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n,o=a=>typeof a=="string"&&!!a.trim();return typeof r.v=="number"&&o(r.deploymentId)&&o(r.user)&&o(r.devPublicKey)&&o(r.issuedAt)&&o(r.expiresAt)},aS=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Xn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:vU(16).toString("hex"),purpose:IU},c;try{let h=AU(t),m=new TextEncoder().encode(bo(i));c=SU(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),EU),u;try{u=await r(`${a}/v1/cert/renew`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({cert:e,challenge:i,sig:c}),signal:l.signal})}finally{clearTimeout(d)}if(!u.ok)return{ok:!1,refused:u.status>=400&&u.status<500&&u.status!==429};let p=(await u.json().catch(()=>null))?.cert;return OU(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var am=async(e,t=e.origin,n=ie)=>{let r=0,o=0,a=!0;for(let s of n)try{if(!s.pointsAt||!await s.pointsAt(t)||await s.usesDynamicCredential?.(t))continue;r+=1,(await s.apply(e,{dryRun:!1})).status==="configured"?o+=1:a=!1}catch{a=!1}return{matched:r,rewritten:o,complete:a}},Ei=async(e,t=e.origin,n=ie)=>(await am(e,t,n)).complete;var RU=["claude","codex","cursor","opencode"],_U=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],PU=new Set(["missing_key","key_expired"]);var TU=600*1e3,LU=600*1e3,sS=1440*60*1e3,DU=1440*60*1e3,NU=10080*60*1e3,$U=3600*1e3,MU=720*60*1e3,FU=e=>Math.min(MU,$U*2**Math.max(0,e-1)),xi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ia=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,iS=e=>typeof e=="string"&&_U.includes(e),En=e=>{if(!xi(e))return{};let t={};if(Ia(e.watchSince)&&(t.watchSince=e.watchSince),xi(e.invoked)){let n={};for(let r of RU){let o=e.invoked[r];Ia(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return xi(e.authFailure)&&Ia(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...iS(e.authFailure.code)?{code:e.authFailure.code}:{}}),xi(e.repair)&&Ia(e.repair.at)&&(e.repair.outcome==="repaired"||e.repair.outcome==="repair_failed"||e.repair.outcome==="unverified")&&(t.repair={at:e.repair.at,outcome:e.repair.outcome,...Ia(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Rd=e=>{try{let n=JSON.parse(e);if(xi(n)&&iS(n.code)&&n.code!=="key_invalid")return n.code}catch{}let t=e.toLowerCase();if(t.includes("valid client key required"))return"key_invalid";if(t.includes("client key required"))return"missing_key"},sm=e=>e!==void 0&&PU.has(e),im=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=TU},cS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),cm=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=LU},lS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),dS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,uS=(e,t,n)=>{if(n==="repair_failed"||n==="unverified")return{...e,repair:{at:t,outcome:n,failures:(e.repair?.failures??0)+1}};let{authFailure:r,...o}=e;return n==="repaired"?{...o,repair:{at:t,outcome:n}}:o},pS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>sS||!sm(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<FU(r.failures??1))},_d=e=>{let t=Object.values(e?.invoked??{}).filter(Ia);return t.length>0?Math.max(...t):null},lm=(e,t)=>{if(_d(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=NU},fS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=DU)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=sS)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var dm="x-anyray-retrieve-probe",Pd=8e3,UU=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",hS=(e,t)=>{let n=zt(e);return t?.probe&&(n[dm]="1"),n},Oa=async(e,t,n)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let r=new AbortController,o=setTimeout(()=>r.abort(),Pd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:hS(e,n),body:JSON.stringify({handle:t,...n?.startLine!==void 0&&{startLine:n.startLine},...n?.endLine!==void 0&&{endLine:n.endLine},...n?.grep!==void 0&&{grep:n.grep}}),signal:r.signal});if(a.status===404)return await a.json().then(c=>typeof c=="object"&&c!==null).catch(()=>!1)?{ok:!1,kind:"not-found",message:`No stashed content for handle ${t} (unknown or expired).`}:{ok:!1,kind:"unsupported",message:"Gateway has no /connect/retrieve route (update the gateway image)."};if(!a.ok){let i=await a.json().catch(()=>{}),c=UU(i)&&i.code==="slice_unsupported";return{ok:!1,kind:a.status===401||a.status===403?"auth":c?"slice-unsupported":"unavailable",message:`Retrieval unavailable (gateway returned HTTP ${a.status}).`}}let s;try{s=await a.json()}catch{return{ok:!1,kind:"malformed",message:"Retrieval returned malformed JSON."}}return typeof s?.content!="string"?{ok:!1,kind:"malformed",message:"Retrieval returned no content."}:{ok:!0,content:s.content,...typeof s.totalLines=="number"&&{totalLines:s.totalLines},...typeof s.totalChars=="number"&&{totalChars:s.totalChars},...typeof s.partial=="boolean"&&{partial:s.partial},...typeof s.startLine=="number"&&{startLine:s.startLine},...typeof s.endLine=="number"&&{endLine:s.endLine},...typeof s.grepMatches=="number"&&{grepMatches:s.grepMatches},...typeof s.grepTruncated=="boolean"&&{grepTruncated:s.grepTruncated}}}catch(a){let s=a instanceof Error&&a.name==="AbortError";return{ok:!1,kind:s?"timeout":"network",message:s?"Retrieval timed out.":`Retrieval failed: ${a instanceof Error?a.message:String(a)}`}}finally{clearTimeout(o)}},Td=async(e,t,n,r)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let o=new AbortController,a=setTimeout(()=>o.abort(),Pd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:hS(e,r),body:JSON.stringify({query:t,...typeof n=="number"?{k:n}:{}}),signal:o.signal});if(!s.ok)return{ok:!1,kind:s.status===401||s.status===403?"auth":"unavailable",message:`Recall unavailable (gateway returned HTTP ${s.status}).`};let i;try{i=await s.json()}catch{return{ok:!1,kind:"malformed",message:"Recall returned malformed JSON."}}return Array.isArray(i?.matches)?{ok:!0,matches:i.matches}:{ok:!1,kind:"malformed",message:"Recall returned no matches list."}}catch(s){let i=s instanceof Error&&s.name==="AbortError";return{ok:!1,kind:i?"timeout":"network",message:i?"Recall timed out.":`Recall failed: ${s instanceof Error?s.message:String(s)}`}}finally{clearTimeout(a)}};var BU=5e3,WU=2048,HU=e=>{let t=e.toLowerCase();return t.includes("client key required")?!0:["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},Ra=async(e={})=>{let t=e.readTarget??ot,n=e.fetch??fetch,r=e.timeoutMs??BU,o=null;try{o=await t()}catch{o=null}if(!o)return{verdict:"dark",reason:"target_null"};let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let i=zt(o);i["content-type"]="application/json",i[dm]="1";let c=await n(`${o.origin}/connect/optimize-output`,{method:"POST",headers:i,body:JSON.stringify({}),signal:a.signal});if(c.status===401||c.status===403){let u=(await c.text().catch(()=>"")).slice(0,WU);if(!HU(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Rd(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...f?{code:f}:{}}}if(!c.ok)return{verdict:"indeterminate",reason:c.status>=500?"unreachable":"unsupported",status:c.status};let l;try{l=await c.json()}catch{return{verdict:"indeterminate",reason:"unsupported",status:c.status}}return typeof l=="object"&&l!==null&&l.handled===!0?{verdict:"live",reason:"ok",status:c.status}:{verdict:"indeterminate",reason:"gateway_mismatch",status:c.status}}catch{return{verdict:"indeterminate",reason:"unreachable"}}finally{clearTimeout(s)}},um=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{createPrivateKey as KU,randomBytes as GU,sign as jU}from"node:crypto";var VU=500,mS=2e3,YU=2e3,ZU=250,yS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),VU);try{return(await fetch(`${e}/connect/health`,{method:"POST",headers:{...t,"x-anyray-connect-version":r},body:JSON.stringify({events:n}),signal:o.signal})).ok}catch{return!1}finally{clearTimeout(a)}},XU=e=>{let t=e.headers?.get?.("retry-after");if(!t)return;let n=Number(t.trim());return Number.isFinite(n)&&n>=0?n*1e3:void 0},JU=e=>new Promise(t=>setTimeout(t,e)),qU=async(e,t,n=JU)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),mS),s;try{let i=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:t,signal:o.signal});if(i.ok)return!0;let c=i.status===429||i.status>=500;if(r>0||!c||(s=XU(i)??ZU,s>YU))return!1}finally{clearTimeout(a)}await n(s)}},zU=async e=>{try{let n=(await D()).enrolledCert,r=await We(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:GU(16).toString("hex"),events:e},s;try{let i=KU(r),c=new TextEncoder().encode(bo(a));s=jU(null,c,i).toString("base64url")}catch{return!1}return await qU(`${Xn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},QU=async(e,t)=>{try{let r=(await D()).enrolledCert,o=await We();if(!r||!o)return;await ln(e,r,o,{timeoutMs:mS,health:{events:t},telemetryOnly:!0})}catch{}},gS=async(e,t)=>{if(e.length!==0)try{let n=await ot(),r=n&&await yS(n.origin,zt(n),e,t);if(n&&await QU(n.origin,e),r)return;await zU(e)}catch{}},pm=async(e,t,n={readTarget:()=>ot("profile"),post:yS})=>{if(e.length===0)return!1;try{let r=await n.readTarget();return r?await n.post(r.origin,{"content-type":"application/json"},e,t):!1}catch{return!1}};var Co=["hook_registration","mcp_registration","hook_binary","beacon_target"];var bS=128,kS=300*1e3,eB=["repaired","repair_failed","flapping","pending"],tB=["settings_not_writable","apply_unconfirmed","apply_threw"],CS=["rebroke_same_day","repeat_days"],AS=new Set(ie.map(e=>e.id)),ko=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Oi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),vS=e=>Oi(e,Co),Ld=e=>{if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=Date.parse(`${e}T00:00:00.000Z`);return Number.isFinite(t)&&new Date(t).toISOString().slice(0,10)===e},Or=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Ii=e=>{if(!(!Array.isArray(e)||!e.every(vS)))return Jn(e)},nB=e=>{if(!ko(e))return;let t=Ii(e.checks);if(!(!Or(e.since)||!Oi(e.reason,CS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},rB=e=>{if(!ko(e))return;let t={};Ld(e.day)&&(t.day=e.day),Or(e.attempts)&&(t.attempts=e.attempts);let n=Ii(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=Ii(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=Ii(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=Ii(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Ld(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Or(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),ko(e.lastRepaired)){let i={};for(let c of Co){let l=e.lastRepaired[c];Or(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=nB(e.flapping);return s&&(t.flapping=s),t},oB=e=>{if(!ko(e)||!Ld(e.day)||!Or(e.sequence)||e.sequence===0||typeof e.tool!="string"||!AS.has(e.tool)||!vS(e.checkId)||!Oi(e.status,eB)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!Oi(e.errorClass,tB))return;t=e.errorClass}else if(e.status==="flapping"){if(!Oi(e.errorClass,CS))return;t=e.errorClass}else if(e.errorClass!==void 0)return;return{day:e.day,sequence:e.sequence,tool:e.tool,checkId:e.checkId,status:e.status,...t?{errorClass:t}:{},delivered:e.delivered,...Or(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},wS=e=>{if(!ko(e))return{};let t={};if(ko(e.adapters)){let n={};for(let r of AS){let o=rB(e.adapters[r]);o&&(n[r]=o)}Object.keys(n).length>0&&(t.adapters=n)}return Array.isArray(e.events)&&(t.events=e.events.map(oB).filter(n=>n!==void 0).slice(-bS)),Or(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),ko(e.report)&&Ld(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Or(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},aB=e=>new Date(e).toISOString().slice(0,10),sB=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Jn=e=>[...new Set(e)],Dd=(e,t)=>{let n=e??{};if(n.day===t)return n;let r=n.day!==void 0&&n.dayHadNeed===!1;return{...n,day:t,attempts:0,attemptedChecks:[],confirmedChecks:[],brokenReportedChecks:[],dayHadNeed:!1,...r?{consecutiveRepairDays:0,lastConfirmedDay:void 0,flapping:void 0}:{}}},Ri=(e,t,n)=>{let r=e.nextSequence??1,o=n.map(a=>({...a,day:t,sequence:r++,delivered:!1}));return{...e,events:[...(e.events??[]).filter(a=>a.day===t),...o].slice(-bS),nextSequence:r}},iB=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),cB=async e=>await Re(async()=>e,void 0,be)??null,lB=async(e,t,n)=>{let r=new Map(e.map(({adapter:o,checks:a})=>[o.id,Object.values(a).some(s=>s==="missing")]));await n.claimState(o=>{let a={...o.adapters??{}};for(let{adapter:s}of e){let i=Dd(a[s.id],t);a[s.id]={...i,dayHadNeed:!!(i.dayHadNeed||r.get(s.id))}}return{next:{...o,adapters:a,events:(o.events??[]).filter(s=>s.day===t)},result:void 0}},void 0)},SS=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:sB(e.lastConfirmedDay,n)?(e.consecutiveRepairDays??0)+1:1,a=o>=3,s={...e.lastRepaired??{}};for(let c of t)s[c]=r;let i=e.flapping;return{adapter:{...e,confirmedChecks:Jn([...e.confirmedChecks??[],...t]),brokenReportedChecks:(e.brokenReportedChecks??[]).filter(c=>!t.includes(c)),lastConfirmedDay:n,consecutiveRepairDays:o,lastRepaired:s,...a?{flapping:{since:i?.since??r,reason:"repeat_days",checks:Jn([...i?.checks??[],...t])}}:{}},slowFlap:a}},dB=async(e,t,n,r,o)=>{let a=new Map(e.map(s=>[s.adapter.id,s]));await o.claimState(s=>{let i=s,c={...s.adapters??{}};for(let[l,d]of Object.entries(c)){let u=Dd(d,n),f=u.awaiting??[],p=a.get(l);if(f.length===0||t.has(l)||!p){c[l]=u;continue}let h=f.filter(y=>p.checks[y]==="owned"),m=f.filter(y=>{let b=p.checks[y];return b==="missing"||b==="foreign"}),w=f.filter(y=>{let b=p.checks[y];return b===void 0||b==="unreadable"}),g=SS(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=Ri(i,n,[...h.map(y=>({tool:l,checkId:y,status:"repaired"})),...m.map(y=>({tool:l,checkId:y,status:"repair_failed",errorClass:"apply_unconfirmed"})),...g.slowFlap?h.map(y=>({tool:l,checkId:y,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},uB=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Dd(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(g=>!d.includes(g)||u.includes(g)),p=f.filter(g=>u.includes(g)),h=l.attempts??0;if(h>=2||f.length===0&&!n){let g=p.filter(A=>!(l.brokenReportedChecks??[]).includes(A));if(g.length===0)return{result:void 0};let y=l.flapping;return c[e]={...l,brokenReportedChecks:Jn([...l.brokenReportedChecks??[],...g]),flapping:{since:y?.since??a,reason:"rebroke_same_day",checks:Jn([...y?.checks??[],...g])}},{next:Ri({...i,adapters:c},o,g.map(A=>({tool:e,checkId:A,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let m=l.flapping;return c[e]={...l,attempts:h+1,attemptedChecks:Jn([...d,...f]),confirmedChecks:u.filter(g=>!f.includes(g)),brokenReportedChecks:Jn([...l.brokenReportedChecks??[],...p]),...p.length>0?{flapping:{since:m?.since??a,reason:"rebroke_same_day",checks:Jn([...m?.checks??[],...p])}}:{}},{next:Ri({...i,adapters:c},o,p.map(g=>({tool:e,checkId:g,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),pB=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Dd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:Jn([...l.awaiting??[],...t])},{next:Ri({...i,adapters:c},o,t.map(h=>({tool:e,checkId:h,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(h=>r[h]==="owned"):[],u=n.status==="configured"&&r?t.filter(h=>{let m=r[h];return m==="missing"||m==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=SS(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:Ri({...i,adapters:c},o,[...d.map(h=>({tool:e,checkId:h,status:"repaired"})),...u.map(h=>({tool:e,checkId:h,status:"repair_failed",errorClass:p})),...f.slowFlap?d.map(h=>({tool:e,checkId:h,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},fB=async(e,t,n,r)=>{let o=await r.claimState(i=>{let c=(i.events??[]).filter(u=>u.day===e&&!u.delivered&&(u.attemptedAt===void 0||u.attemptedAt>t||t-u.attemptedAt>=kS));if(c.length===0)return{result:[]};let l=new Set(c.map(u=>`${u.day}:${u.sequence}`)),d=(i.events??[]).map(u=>l.has(`${u.day}:${u.sequence}`)?{...u,attemptedAt:t}:u);return{next:{...i,events:d},result:c.map(u=>({...u,attemptedAt:t}))}},[]);if(o.length===0||!await(r.report??pm)(o.map(iB),n).catch(()=>!1))return;let s=new Set(o.map(i=>`${i.day}:${i.sequence}`));await r.claimState(i=>({next:{...i,events:(i.events??[]).map(c=>s.has(`${c.day}:${c.sequence}`)?{...c,delivered:!0}:c)},result:void 0}),void 0)},hB=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:f}of t){let p=r.adapters?.[u.id];for(let h of Co){let m=f[h];if(!m||m==="unreadable")continue;let w,g;p?.awaiting?.includes(h)&&c.has(u.id)?w="pending":m==="missing"&&p?.flapping?.checks.includes(h)?(w="flapping",g=p.flapping.reason):w=m==="owned"?"ok":m,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:h,status:w,...g?{errorClass:g}:{}})}}let l=Date.parse(e.enrolledCert?.payload.expiresAt??e.enrolledCertExpiry??"");e.enrolledCert&&Number.isFinite(l)&&(l<=o?(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"expired"})):l-o<=336*60*60*1e3&&(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"problems",errorClass:"cert_expiring"}))),e.refreshSchedulerEnabled&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Yo)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??yr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=fS(await a.readHookLane?.().catch(()=>({})),o);return d&&(d.status!=="repaired"&&(i=!0),s.push({tool:"connect",checkId:"hook_lane",status:d.status,...d.errorClass?{errorClass:d.errorClass}:{}})),s.push({tool:"connect",checkId:"selfcheck_report",status:i?"problems":"ok"}),s},mB=async(e,t,n,r,o,a,s)=>{if(!await s.claimState(u=>u.report?.day===r&&u.report.delivered?{result:!1}:u.report?.day===r&&u.report.attemptedAt!==void 0&&u.report.attemptedAt<=o&&o-u.report.attemptedAt<kS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await hB(e,t,n,c,o,s);await(s.report??pm)(l,a).catch(()=>!1)&&await s.claimState(u=>u.report?.day===r?{next:{...u,report:{day:r,delivered:!0}},result:void 0}:{result:void 0},void 0)},ES=async(e,t,n)=>{let r=n.now??Date.now,o=aB(r()),a=e.managedTools??[],s={...n,readState:async()=>wS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(wS(l)),c)};try{let i=await(s.findIntegrations??Qh)(a);await lB(i,o,s);let c=await(s.listPending??hr)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await dB(i,l,o,r(),s);let d=await(s.resolveTarget??cB)(e),u=d?await(s.findDrifted??xr)(a,d.toolOrigin):[],f=new Set(u.map(g=>g.id)),p=new Map(i.map(g=>[g.adapter.id,g]));for(let g of u)p.has(g.id)||p.set(g.id,{adapter:g,checks:{}});let h=!1,m=(s.runtimeDurable??le)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?Co.filter(P=>y[P]==="missing"):[];if(b.length===0&&!f.has(g.id))continue;let A=y;if(g.integrationStatus)try{A=await g.integrationStatus()}catch{A=Object.fromEntries(Co.map(P=>[P,"unreadable"]))}let v=b.filter(P=>A[P]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),v.length===0&&!E)continue;let x=await uB(g.id,v,E,l.has(g.id),o,r(),s);if(!x)continue;let[C]=await(s.repair??gt)([g],d.target);if(!C)continue;h=!0;let I;C.status==="configured"&&g.integrationStatus&&(I=await g.integrationStatus().catch(()=>{})),await pB(g.id,x.checks,C,I,o,r(),s)}await fB(o,r(),t,s),i=await(s.findIntegrations??Qh)(a);let w=await(s.listPending??hr)().catch(()=>[]);return await mB(e,i,w,o,r(),t,s),h}catch{return!1}};var vB=14,SB=.35,EB=900*1e3,IS=360*60*1e3,xB=.2,IB=1800*1e3,OS=3600*1e3,OB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),RB=300*1e3,_B=30*1e3,PB=900*1e3,TB=(e=0)=>Math.min(PB,_B*2**Math.max(0,e)),RS=e=>{let t=e;for(let n=0;n<5&&t;n++){let r=t.code;if(typeof r=="string")return r;t=t.cause}},LB=720*60*1e3,_S=1440*60*1e3,DB=300*1e3,NB=.25,$B=.5,PS=3600*1e3,MB=720*60*60*1e3,FB=360*60*1e3,UB=1440*60*1e3,BB=4,Nd=e=>wB("sha256").update(e).digest("hex").slice(0,32),FS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Kt)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??D)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(Nd(e))},fm=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,BB)}),WB=()=>$S(bB(),".anyray"),mm=()=>$S(WB(),"refresh-state.json"),ym=e=>process.env?.[e],US=()=>ym("ANYRAY_REFRESH_DISABLE")==="true",gm=()=>{let e=ym("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:vB)*UB},Pi=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},BS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),HB=10080*60*1e3,$d=(e,t,n=Date.now())=>{let r=[],o=Pi(e);o!==void 0&&r.push(o);let a=Date.parse(t??e.clientKeyExpiresAt??"");Number.isFinite(a)&&r.push(a-n);let s=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??"");return Number.isFinite(s)&&r.push(s-n),r.length===0?!1:Math.min(...r)<=HB},Ti=e=>{let t=gm(),n=e?Pi(e):void 0;if(!n)return t;let r=Math.max(EB,Math.round(n*SB));return Math.min(t,r)},KB=e=>{let t=ym("ANYRAY_REFRESH_THROTTLE_MS"),n=t?Number.parseInt(t,10):NaN;return Number.isFinite(n)&&n>0?n:typeof e=="number"&&Number.isFinite(e)&&e>0?Math.min(IS,Math.max(IB,Math.round(e*xB))):IS},Kt=async()=>{try{let e=await kB(mm(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Md=async e=>{try{let t=mm(),n=`${t}.${process.pid}.tmp`;await MS(n,JSON.stringify(e),{mode:384}),await he(n,t),await CB(t,384).catch(()=>{})}catch{}},GB=3e4,jB=()=>`${mm()}.lock`,TS=async e=>{try{return await MS(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},ut=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Kt,a=n.writeState??Md,s=jB(),i=!1;try{if(i=await TS(s),!i){if(await AB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<GB)return t;await xS(s).catch(()=>{}),i=await TS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await xS(s).catch(()=>{})}},_i=async(e,t={})=>{await ut(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},_a=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0),a=await(t.loadProfile??D)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?Nd(a.clientKey):void 0;await ut(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:fm(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},Ao=async(e={})=>{let t=e.now??Date.now;await ut(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},VB=e=>{let t=e.enrolledCertLifetimeMs,n=Date.parse(e.enrolledCert?.payload.issuedAt??""),r=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??""),o=typeof t=="number"&&Number.isFinite(t)&&t>0?t:Number.isFinite(n)&&Number.isFinite(r)&&r>n?r-n:void 0;return o?Math.min(MB,Math.max(PS,Math.round(o*$B))):PS},hm=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,wm=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??re,a=n.loadProfile??D,s=n.loadDevKey??We,i=n.renew??aS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(oS(c.payload.user))return{outcome:"not-due",profile:e};let l=Date.parse(e.enrolledCertExpiry??c.payload.expiresAt??"");if(!Number.isFinite(l))return{outcome:"not-due",profile:e};if(l-r()>VB(e))return{outcome:"not-due",profile:e};if(!await ut(w=>r()-(w.lastCertRenewAt??0)<FB?{result:!1}:{next:{...w,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await hm(f,c.sig,t,s))return{outcome:"superseded",profile:f};let p=u.cert.payload.expiresAt,h=Date.parse(p)-r(),m={...f,enrolledCert:u.cert,enrolledCertExpiry:p,...Number.isFinite(h)&&h>0?{enrolledCertLifetimeMs:h}:{}};return await o(m),{outcome:"renewed",profile:m}},LS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*NB):_S,r=Math.min(_S,n);return Math.min(r,DB*2**Math.max(0,e-1))},YB=()=>{let{command:e,args:t}=fn(ar);return{exe:e,args:t}},Rr=async(e={})=>{if(US())return;let t=e.now??Date.now,n=e.readState??Kt,r=e.writeState??Md,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=YB();gB(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await ut(s=>t()-(s.lastSpawnAt??0)<KB(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},ZB=Ei,XB=async(e,t=be,n=!1)=>{try{let r=e.managedTools??[];if(r.length===0)return!1;let o=await Re(async()=>e,void 0,t);if(!o)return!1;let a=await xr(r,o.toolOrigin),s=n?Hv(a):a;return s.length===0?!1:(await gt(s,o.target),!0)}catch{return!1}},JB=async(e,t,n,r,o,a)=>{try{let s=new Set(e.managedTools??[]),i=ie.filter(p=>s.has(p.id));if(i.length===0)return!1;let c=await r().catch(()=>{}),l=ge({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:c,user:e.name,team:e.team}),d=e.fallbackPort,u=rt(e)&&Number.isInteger(d)&&d>0&&d<=65535&&await o(d)!==null,f=await a(u?On(l,d):l,u?`http://${ht}:${d}`:l.origin,i);return f.matched>0&&f.complete}catch{return!1}},qB=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Kt,a=t.writeState??Md;return ES(e,we,{now:r,deadWatcherObserved:n,readHookLane:()=>Fd({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>ut(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Fd=async(e={})=>{let n=await(e.readState??Kt)().catch(()=>({}));return En(n.hookLane)},WS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Fd(t);if(!im(r,e,n()))return;await ut(o=>{let a=En(o.hookLane);return im(a,e,n())?{next:{...o,hookLane:cS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},HS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Fd(t);if(!cm(r,n()))return;await ut(o=>{let a=En(o.hookLane);return cm(a,n())?{next:{...o,hookLane:lS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},zB=async(e={})=>{try{let t=e.now??Date.now;if((await Fd(e)).watchSince!==void 0)return;await ut(n=>{let r=En(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:dS(r,t())},result:void 0}},void 0,e)}catch{}},DS=async(e,t={})=>{try{let n=t.now??Date.now;await ut(r=>{let o=En(r.hookLane),a=uS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},KS=async(e={})=>{try{if((await(e.readState??Kt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>ut(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??$g)())return await r()?"stamped":"skipped";let o=await(e.load??D)(),s=await(e.findTools??wo)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Re(async()=>o,void 0,e.probe??be);return!i||!await r()?"skipped":(await(e.repair??gt)(s,i.target),"repathed")}catch{return"skipped"}},GS=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Kt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>ut(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??D)(),i=await(e.findTools??wo)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Re(async()=>a,void 0,e.probe??be);return!c||!await o()?"skipped":(await(e.repair??gt)(i,c.target)).some(d=>d.status==="failed")?(await ut(d=>{if(d.appliedRevision!==t)return{result:void 0};let u={...d};return r===void 0?delete u.appliedRevision:u.appliedRevision=r,{next:u,result:void 0}},void 0,e).catch(()=>{}),"retry"):"swept"}catch{return"skipped"}},QB=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await Ed(e.gateway,e.clientKey),n=await xd(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},NS=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??QB)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>XB(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},tt=async(e={})=>{if(US())return"disabled";let t=e.now??Date.now,n=e.loadProfile??D,r=e.saveProfile??re,o=e.loadDevKey??We,a=e.readState??Kt,s=e.writeState??Md,i=e.remint??ln,c=e.heartbeat??Od,l=e.detectSeat??Nt,d=e.rewriteTools??ZB,u=e.rewriteHookLaneTools??am,f=e.probeHookLane??Ra,p=e.classifyBeacon??xc,h=e.probe??be,m=e.installProxy??Dt,w=e.pickProxyPort??Pc,g=e.force===!0,y=!1,b=!1,A=!1,v=!1;e.hookLaneRepair===!0&&(g=!0,v=!0);let E=async C=>{if(!v){C==="repaired"&&await DS("none",{now:t,readState:a,writeState:s});return}let I=C;if(C==="repaired"){let P=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));I=P.verdict==="live"?"repaired":P.verdict==="dark"?"repair_failed":"unverified"}await DS(I,{now:t,readState:a,writeState:s})},x=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(P=>qB(P,{now:t,readState:a,writeState:s},A)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(A=await hr().then(R=>R.some(T=>!yr(T.watcherPid))).catch(()=>!1),await zB({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??yb)();let C=await n();if(y=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let I=C.gateway,P=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(P)||P<=t())return"cert-expired";let $=await o();if(!$)return"not-enrolled";let Y=await wm(C,$,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=Y.profile;let Z=Y.outcome==="renewed",W=C.enrolledCert;if(!W)return"not-enrolled";let q=Date.parse(C.clientKeyExpiresAt??""),me=Number.isFinite(q)?q-t():0,Te=await a(),ne=!C.clientKey||me<=Ti(C),Ke=C.credentialProtocol!=="stable-heartbeat-v1"&&t()-(Te.lastSuccessAt??0)>=LB;if(!g&&pS(En(Te.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,v=!0),C.credentialProtocol==="stable-heartbeat-v1"&&C.clientKey&&(g||ne)){let R=await ut(T=>{let H=t()-(T.lastAttemptAt??0);return H<OS?{result:"throttled"}:T.failureCount&&H<LS(T.failureCount,T.keyTtlMs)?{result:"backoff"}:{next:{...T,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(R!=="ok")return R;try{let T=await c(I,C.clientKey,W,$),H=await n().catch(()=>C);return H.clientKey!==C.clientKey||H.enrolledCert?.sig!==W.sig?"failed":(await r({...H,clientKeyExpiresAt:T.expiresAt}),await _i(({lastError:fe,...z})=>({...z,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Pi(C)??z.keyTtlMs}),{now:t,readState:a,writeState:s}),v&&await E(await JB(C,I,C.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(T){let H=T;if(T instanceof Ir&&T.status===404)try{let z=await i(I,W,$),Ze=await l().catch(()=>{}),Ue=ge({origin:I,clientKey:z.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Ze,user:C.name,team:C.team}),ee=C.fallbackPort,Be=Number.isInteger(ee)&&ee>0&&ee<=65535?ee:await w();if(!(await m({port:Be,remoteOrigin:I})).ok||await h(Be)===null)throw new Error("key-refresh proxy recovery failed");let Xt=await n().catch(()=>C);if(!await hm(Xt,W.sig,$,o))throw new Error("enrollment changed during proxy recovery");if(await r({...Xt,clientKey:z.key,clientKeyExpiresAt:z.expiresAt??Xt.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:Be}),await d(On(Ue,Be),Ue.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let V=z.expiresAt?Date.parse(z.expiresAt):NaN,Ne=Pi(C)??(Number.isFinite(V)&&V-t()>0?V-t():void 0);return await _i(({lastError:er,...ft})=>({...ft,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ne??ft.keyTtlMs,ownKeys:fm(ft.ownKeys,W.sig,Nd(z.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(z){H=z}let fe=RS(H);return await _i(z=>({...z,lastAttemptAt:t(),failureCount:(z.failureCount??0)+1,lastError:{name:H instanceof Error?H.name:"Error",...fe!==void 0?{code:fe}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),H instanceof Ir?"cert-rejected":"failed"}}if(!g&&C.clientKey&&!ne&&!Ke){let R=await NS(C,e,n,h),T=await x();return R||T?"repaired":Z?"cert-renewed":"not-due"}let Le=await ut(R=>{let T=t()-(R.lastAttemptAt??0);if(g)return T<TB(R.failureCount)?{result:"throttled"}:{next:{...R,lastAttemptAt:t()},result:"ok"};let H=R.lastError?.code!==void 0&&OB.has(R.lastError.code)?RB:OS;return T<H?{result:"throttled"}:R.failureCount&&T<LS(R.failureCount,R.keyTtlMs)?{result:"backoff"}:{next:{...R,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(Le!=="ok")return Le;try{let R=await i(I,W,$),T=await l().catch(()=>{}),H=ge({origin:I,clientKey:R.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:T,user:C.name,team:C.team}),fe=H,z=H.origin;if(rt(C)){if(!Number.isInteger(C.fallbackPort)||C.fallbackPort<1||C.fallbackPort>65535)throw new Error("key-refresh proxy profile has no valid port");await h(C.fallbackPort)!==null&&(fe=On(H,C.fallbackPort),z=`http://${ht}:${C.fallbackPort}`)}let Ze=await d(fe,z);if(C.directMigration==="pending"&&fe.viaLocalProxy===!0){let V=await d(fe,H.origin);Ze=Ze!==!1&&V!==!1}if(Ze===!1)throw new Error("one or more configured tools rejected the refreshed key");let Ue=await n().catch(()=>C),ee=null,Be;Ue.enrolledCert&&await hm(Ue,W.sig,$,o)&&(Be=Nd(R.key),ee={...Ue,clientKey:R.key,clientKeyExpiresAt:R.expiresAt??Ue.clientKeyExpiresAt},await r(ee));let De=R.expiresAt?Date.parse(R.expiresAt):NaN,Xt=Pi(C)??(Number.isFinite(De)&&De-t()>0?De-t():void 0);return await _i(({lastError:V,...Ne})=>({...Ne,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Xt??Ne.keyTtlMs,...Be?{ownKeys:fm(Ne.ownKeys,W.sig,Be)}:{}}),{now:t,readState:a,writeState:s}),ee&&await NS(ee,e,n,h),await E(ee?"repaired":"repair_failed"),await x(),"refreshed"}catch(R){let T=RS(R);return await _i(H=>({...H,lastAttemptAt:t(),failureCount:(H.failureCount??0)+1,lastError:{name:R instanceof Error?R.name:"Error",...T!==void 0?{code:T}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),R instanceof Ot?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await x()}catch{}}};import{readFile as s1}from"node:fs/promises";import{isAbsolute as i1,posix as XS,win32 as Cm}from"node:path";var bm=1e4,e1=900*1e3,VS="tnt_",t1=/^\/sso\/([^/]+)\/?$/,n1=/^\/i\/([^/]+)\/?$/,r1=e=>{let t=e.match(t1);if(t)return t[1];let n=e.match(n1);return n?.[1].startsWith(VS)?n[1]:void 0},Rt=e=>{let t=e.trim();if(!t)return;let n;try{n=new URL(t)}catch{n=void 0}if(n){if(n.protocol!=="http:"&&n.protocol!=="https:")return;let r=r1(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(VS))return{cpOrigin:Xn(),tenantId:t}},vo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Gt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},km=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await r(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:o.signal}),i={};try{i=await s.json()}catch{}return{status:s.status,json:i}}finally{clearTimeout(a)}},o1=e=>new Promise(t=>setTimeout(t,e)),Ud=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Id)(),a;try{a=await km(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},bm,n)}catch(h){throw new vo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${wt(h)}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new vo(h?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${m}). Ask your admin to confirm SSO is configured.`,a.status)}let s=a.json;if(!s.device_code||!s.user_code||!s.verification_uri_complete)throw new vo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??e1,l=typeof s.expires_in=="number"&&s.expires_in>0?s.expires_in*1e3:c,d=typeof s.verification_uri=="string"?s.verification_uri:void 0,u=e.gatewayUrl??(typeof s.gateway_url=="string"?s.gateway_url:void 0),f={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:s.device_code,userCode:s.user_code,verificationUri:d,verificationUriComplete:s.verification_uri_complete,intervalMs:Math.max(1,s.interval||5)*1e3,grantExpiresAt:i+Math.min(c,l),startedAt:i,privateKeyPem:o,publicKeyPem:r,gatewayUrl:u},p=e.log??(()=>{});return p("To finish, sign in with your organization at:"),p(` ${f.verificationUriComplete}`),p(`Confirm this code matches your browser: ${f.userCode}`),a1(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},a1=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Bd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??o1,o=t.fetch??fetch,a=t.pollIntervalMs??e.intervalMs;for(;n()<e.grantExpiresAt&&(await r(Math.min(a,e.grantExpiresAt-n())),!(n()>=e.grantExpiresAt));){let s;try{s=await km(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},bm,o)}catch(c){throw new Gt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${wt(c)}`)}if(s.status===200&&s.json.cert)return{cert:s.json.cert,privateKeyPem:e.privateKeyPem,gatewayUrl:t.gatewayUrl??(typeof s.json.gatewayUrl=="string"?s.json.gatewayUrl:e.gatewayUrl),deploymentId:typeof s.json.deploymentId=="string"?s.json.deploymentId:""};let i=typeof s.json.error=="string"?s.json.error:"";if(i!=="authorization_pending"){if(i==="slow_down"){a+=5e3;continue}throw i==="expired_token"?new Gt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Gt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Gt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var jS="sdc_",YS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(jS))return{cpOrigin:Xn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!om(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(jS)))return{cpOrigin:n.origin,claim:r}},ZS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Id)(),o;try{o=await km(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},bm,t)}catch(s){throw new Gt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${wt(s)}`)}if(o.status===200&&o.json.cert)return{cert:o.json.cert,privateKeyPem:r,gatewayUrl:e.gatewayUrl??(typeof o.json.gatewayUrl=="string"?o.json.gatewayUrl:void 0),deploymentId:typeof o.json.deploymentId=="string"?o.json.deploymentId:"",...typeof o.json.ssoLink=="string"&&o.json.ssoLink?{ssoLink:o.json.ssoLink}:{}};let a=typeof o.json.error=="string"?o.json.error:"";throw a==="expired_token"?new Gt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Gt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Gt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};var Li=(e=process.platform,t=process.env)=>e==="darwin"?XS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?Cm.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):XS.join("/etc","anyray","bootstrap.json"),c1=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),JS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(i1(e)||Cm.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),l1=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&!t.username&&!t.password}catch{return!1}},jt=async(e=Li())=>{try{let t=await s1(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!c1(n)||n.v!==1||typeof n.sso!="string")return;let r=Rt(n.sso);if(!r)return;let o=l1(n.gateway)?n.gateway:void 0,a=JS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},qS=(e,t,n)=>{let r=Rt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!JS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&Cm.isAbsolute(n)&&/^[A-Za-z]:\\/.test(n)&&!/^[A-Za-z]:\\Program Files( \(x86\))?\\/i.test(n))throw new Error("--bin on Windows must live under Program Files (admin-only writable)");return`${JSON.stringify({v:1,sso:`${r.cpOrigin}/sso/${r.tenantId}`,...t?{gateway:t}:{},...n?{bin:n}:{}},null,2)}
296
+ `};import{execFile as D1}from"node:child_process";import{chmod as d1,readFile as u1,rm as zS,writeFile as p1}from"node:fs/promises";import{join as f1}from"node:path";var Am=()=>f1(Q(),"sso-gate.json"),h1=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=a=>t[a]===void 0||typeof t[a]=="number"&&Number.isFinite(t[a]),r=a=>t[a]===void 0||typeof t[a]=="string",o=new Set(["cp-unreachable","sso-unavailable","denied","expired","gateway-unreachable"]);return t.v===1&&(t.status===void 0||t.status==="pending")&&r("userCode")&&r("verificationUriComplete")&&n("grantExpiresAt")&&n("startedAt")&&n("pollerPid")&&n("lastAttemptAt")&&n("failureCount")&&(t.lastFailure===void 0||typeof t.lastFailure=="string"&&o.has(t.lastFailure))},_r=async()=>{try{let e=JSON.parse(await u1(Am(),"utf-8"));return h1(e)?e:null}catch{return null}},m1=0,Wd=async e=>{await kt();let t=Am(),n=`${t}.${process.pid}.${m1++}.tmp`;try{await p1(n,`${JSON.stringify(e)}
297
+ `,{mode:384}),await d1(n,384),await he(n,t)}catch(r){throw await zS(n,{force:!0}).catch(()=>{}),r}},QS=async()=>{await zS(Am(),{force:!0}).catch(()=>{})},eE=e=>{if(!e||!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}};import{spawn as w1}from"node:child_process";import{homedir as b1}from"node:os";import{join as k1}from"node:path";import{spawn as y1}from"node:child_process";import{platform as g1}from"node:os";var Pa=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=g1(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=y1(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var C1=3e4,A1=5*6e4,v1=30*6e4,S1=e=>{let t={};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--sso":t.sso=o();break;case"--gateway":t.gateway=o();break;case"--team":t.team=o();break;case"--session-start":t.sessionStart=!0;break;default:throw new Error("invalid SSO gate arguments")}}if(!t.sso)throw new Error("missing --sso");return t},E1=()=>k1(b1(),".claude","settings.json"),x1=async e=>{try{let n=(await U(E1())).env;if(!n)return!1;let r=pn(e).env;for(let[o,a]of Object.entries(r))if(n[o]!==a)return!1;return n.ANTHROPIC_AUTH_TOKEN===void 0}catch{return!1}},I1=async e=>{await cr.apply(e,{dryRun:!1})},O1=()=>{let{command:e,args:t}=fn("__anyray-sso-poll");return{exe:e,args:t}},R1=()=>{let{exe:e,args:t}=O1(),n=w1(e,t,{detached:!0,stdio:["pipe","ignore","ignore"]});return n.on("error",()=>{}),n.unref(),n.stdin?.on("error",()=>{}),{pid:n.pid,handoff:r=>{n.stdin?.end(JSON.stringify(r))}}},_1=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},tE=(e,t,n,r)=>ge({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),Ta=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},nE=e=>`Anyray: one-time sign-in required to use AI tools on this device.
298
298
  1. Open ${e.verificationUriComplete}
299
299
  2. Confirm code ${e.userCode}
300
300
  Your prompt was not sent \u2014 complete sign-in, then resubmit it.
301
- `,Cm=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
301
+ `,vm=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
302
302
  `:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
303
303
  `:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
304
- `,IW=e=>Math.min(gW,yW*2**Math.max(0,e-1)),xW=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?wW:IW(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Jn=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??L,o=t.saveProfile??re,a=t.loadDevKey??We,s=t.readGateState??Or,i=t.writeGateState??Ud,c=t.isProcessAlive??QS,l=t.startGrant??Md,d=t.verify??ln,u=t.routingIntact??CW,f=t.applyClaudeCode??AW,p=t.maybeSpawnRefresh??Rr,h=t.recordMint??Oa,m=t.reserveMint??vo,w=t.spawnPoller??SW,g=t.openBrowser??_a;try{let y=Ot(e.sso);if(!y)return{exitCode:0};let b=await r(),A=await s(),v=b.enrolledCert?await a():void 0,E=EW(b),I=!!(b.enrolledCert&&v)&&Number.isFinite(E)&&E>n(),C=e.gateway??b.gateway;if(I&&b.enrolledCert&&v&&C){let Z=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(Z)&&Z>n()&&b.clientKey){let me=eE(C,b,e.team,b.clientKey);return await u(me)?(Z-n()<=mm()&&await p(),{exitCode:0}):(await f(me),Ta(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
305
- `))}let z;await m();try{z=await d(C,b.enrolledCert,v,{timeoutMs:1e4})}catch(me){if(!(me instanceof Rt))return Ta(e,Cm("gateway-unreachable",y.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(z){let me={...b,gateway:C,name:z.user,team:e.team??z.team??b.team,clientKey:z.key,clientKeyExpiresAt:z.expiresAt,authMode:"subscription"};return await o(me),await h({expiresAt:z.expiresAt}),await f(eE(C,me,e.team,z.key)),{exitCode:0}}}if(A?.status==="pending"&&(A.userCode&&A.verificationUriComplete)&&(A.grantExpiresAt??0)>n()&&c(A.pollerPid)){if(e.sessionStart&&A.verificationUriComplete)try{g(A.verificationUriComplete)}catch{}return Ta(e,tE(A))}if(A){let Z=xW(A,n());if(Z)return Ta(e,Cm(Z,y.cpOrigin))}let x;try{x=await l({cpOrigin:y.cpOrigin,tenantId:y.tenantId,gatewayUrl:e.gateway,now:n})}catch(Z){let W=Z instanceof So?Z.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:A?.lastFailure===W?(A.failureCount??0)+1:1,lastFailure:W}),Ta(e,Cm(W,y.cpOrigin))}let T={v:1,status:"pending",userCode:x.userCode,verificationUriComplete:x.verificationUriComplete,grantExpiresAt:x.grantExpiresAt,startedAt:x.startedAt,lastAttemptAt:n(),failureCount:0};await i(T);let $=w(),Y={...T,pollerPid:$.pid};if(await i(Y),$.handoff({deviceCode:x.deviceCode,privateKeyPem:x.privateKeyPem,publicKeyPem:x.publicKeyPem,cpOrigin:x.cpOrigin,tenantId:x.tenantId,intervalMs:x.intervalMs,grantExpiresAt:x.grantExpiresAt,startedAt:x.startedAt,gatewayUrl:x.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{g(x.verificationUriComplete)}catch{}return Ta(e,tE(Y))}catch{return{exitCode:0}}},RW=async()=>{try{for await(let e of process.stdin);}catch{}},nE=async e=>{await RW();try{let t=await Jn(bW(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var _W=6e4,TW=10*6e4,Xn=(e,t)=>{let n=e[t];return typeof n=="string"?n:Array.isArray(n)?n[0]:void 0},PW=e=>{if(Xn(e,"x-anyray-api-key")?.trim())return!0;let t=Xn(e,"authorization")?.trim()??"";return/^bearer\s+\S+/i.test(t)?!0:(Xn(e,"x-api-key")?.trim()??"").startsWith("ark_")},oE=e=>{if(Xn(e,"x-anyray-api-key")?.trim())return!0;let t=Xn(e,"authorization")?.trim()??"";return/^bearer\s+ark_\S+/i.test(t)?!0:(Xn(e,"x-api-key")?.trim()??"").startsWith("ark_")},aE=e=>{let t=Xn(e,"x-anyray-api-key")?.trim();if(t?.startsWith("ark_"))return{key:t,slot:"x-anyray-api-key"};let r=(Xn(e,"authorization")?.trim()??"").match(/^bearer\s+(ark_\S+)/i);if(r)return{key:r[1],slot:"authorization"};let o=Xn(e,"x-api-key")?.trim()??"";return o.startsWith("ark_")?{key:o,slot:"x-api-key"}:void 0},LW=e=>e.split("?")[0].includes("/v1/"),rE=e=>e.replace(/[^\x20-\x7e]/g,"").replace(/["'`\\$]/g,"").slice(0,300),DW=(e,t,n=process.platform,r=OW)=>{let o=rE(e),a=rE(t);try{n==="darwin"?r("/usr/bin/osascript",["-e",`display notification "${a}" with title "${o}"`],{timeout:5e3},()=>{}):n==="linux"&&r("notify-send",["--app-name=Anyray",o,a],{timeout:5e3},()=>{})}catch{}},sE=(e={})=>{let t=e.readBootstrap??Vt,n=e.ssoGate??Jn,r=e.readState??Or,o=e.notify??DW,a=e.now??Date.now,s=0,i,c=0,l=!1,d=async()=>{let u=await t();if(!u||(await n({sso:u.sso,gateway:u.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}})).exitCode!==2)return;let p=await r();p?.status!=="pending"||!p.userCode||!p.verificationUriComplete||!(p.userCode!==i)&&a()-c<TW||(i=p.userCode,c=a(),o("Anyray \u2014 sign in to use AI tools",`Open ${p.verificationUriComplete} and enter code ${p.userCode}. Requests keep failing until sign-in completes.`))};return{onGatewayUnauthorized(u,f){try{if(!LW(u)||PW(f)||l||a()-s<_W)return;s=a(),l=!0,d().catch(()=>{}).finally(()=>{l=!1})}catch{}}}};import{watch as NW}from"node:fs";import{basename as $W,dirname as MW}from"node:path";var FW=2e3,UW=6e4,Pa=e=>e instanceof Error?e.name:"UnknownError",BW=(e,t,n)=>{let r=NW(e,{persistent:!1},(o,a)=>{t(a==null?null:a.toString())});return r.on("error",n),r},WW=async(e,t)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await _e(async()=>e,void 0,t);if(!r)return!1;let o=await Er(n,r.toolOrigin);return o.length===0?!1:(await yt(o,r.target),!0)}catch{return!1}},iE=(e={})=>{let t=e.loadProfile??L,n=e.adapters??se,r=e.probe??be,o=e.repairDrift??(C=>WW(C,r)),a=e.resolveProfileFile??No,s=e.watchDir??BW,i=e.debounceMs??FW,c=e.repairFloorMs??UW,l=e.now??Date.now,d=e.logError??(C=>console.error(`anyray refresh proxy: drift watcher ${C}`)),u=!1,f=0,p,h=Promise.resolve(),m=new Map,w=C=>{let x=m.get(C);if(x){m.delete(C);try{x.handle.close()}catch{}}},g=()=>{if(u)return;p!==void 0&&clearTimeout(p);let C=setTimeout(()=>{p=void 0,h=h.then(E).catch(()=>{})},i);C.unref?.(),p=C},y=C=>x=>{if(!u)try{let T=m.get(C);if(!T||x!==null&&!T.files.has(x))return;g()}catch(T){d(Pa(T))}},b=C=>x=>{d(Pa(x)),w(C),g()},A=async C=>{let x=[],T=new Set(C.managedTools??[]);for(let Z of n)if(!(!T.has(Z.id)||!Z.watchPaths))try{x.push(...await Z.watchPaths())}catch(W){d(Pa(W))}let $=await a().catch(()=>{});$&&x.push($);let Y=new Map;for(let Z of x){let W=MW(Z),z=Y.get(W)??new Set;z.add($W(Z)),Y.set(W,z)}return Y},v=async C=>{let x=await A(C);if(!u){for(let T of[...m.keys()])x.has(T)||w(T);for(let[T,$]of x){let Y=m.get(T);if(Y){Y.files=$;continue}try{m.set(T,{handle:s(T,y(T),b(T)),files:$})}catch(Z){d(Pa(Z))}}}},E=async()=>{if(!u)try{let C=await t().catch(()=>({}));if(await v(C),u||l()-f<c)return;f=l(),await o(C).catch(()=>!1)}catch(C){d(Pa(C))}};return{ready:t().then(C=>v(C)).catch(C=>d(Pa(C))),stop:()=>{u=!0,p!==void 0&&(clearTimeout(p),p=void 0);for(let C of[...m.keys()])w(C)}}};import{randomBytes as HW}from"node:crypto";import{chmod as KW,readFile as GW,rm as dE,writeFile as jW}from"node:fs/promises";import{join as VW}from"node:path";var YW=/^[A-Za-z0-9_-]{43}$/,ZW=3600*1e3,cE=3900,JW=1e4,Am=()=>VW(Q(),"device-token.json"),XW=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&YW.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},uE=async()=>{try{let e=JSON.parse(await GW(Am(),"utf-8"));return XW(e)?e:null}catch{return null}},zW=0,qW=async e=>{await kt();let t=Am(),n=`${t}.${process.pid}.${zW++}.tmp`;try{await jW(n,`${JSON.stringify(e)}
306
- `,{mode:384}),await KW(n,384),await he(n,t)}catch(r){throw await dE(n,{force:!0}).catch(()=>{}),r}},Bd=async()=>{await dE(Am(),{force:!0}).catch(()=>{})},QW=()=>HW(32).toString("base64url"),eH=e=>e instanceof Error?e.name:"UnknownError",tH=(e,t)=>{let n=setInterval(e,t);return n.unref(),{stop:()=>clearInterval(n)}},lE=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??L)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=QW(),i=new AbortController,c=setTimeout(()=>i.abort(),JW),l;try{l=await n(`${o}/connect/device-token`,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":a},body:JSON.stringify({token:s,ttlSeconds:cE}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await qW({v:1,token:s,expiresAt:t()+cE*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${eH(r)}`),!1}},pE=(e={})=>{lE(e);let n=(e.scheduleRotation??tH)(()=>{lE(e)},ZW);return{stop:()=>n.stop()}};var rH=1800*1e3,fE=50,oH=15e3,aH=1e3,gE=ms*1e3-1e4,hE=15*6e4,sH=75e3,iH=8e4,cH=async(e,t,n={})=>{let r=n.budgetMs??ms*1e3,o=n.delayMs??250,a=Date.now()+r;for(;;)try{await new Promise((s,i)=>{let c=l=>i(l);e.once("error",c),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",c),s()})});return}catch(s){if(s.code!=="EADDRINUSE"||Date.now()+o>a)throw s;await Sm(o)}},Wd=e=>{let t=e instanceof Error?e.name:"unknown",n=e?.code;return typeof n=="string"?`${t} ${n}`:t},lH=(e,t={})=>{let n=t.exit??(f=>process.exit(f)),r=t.exitCode??0,o=t.hardCapMs??gE,a=t.inFlight,s=Date.now()+(t.ceilingMs??o),i=setInterval(()=>e.closeIdleConnections(),500);i.unref();let c,l=!1,d=()=>{l||(l=!0,clearInterval(i),clearTimeout(c),n(r))},u=f=>{c=setTimeout(()=>{let p=s-Date.now();if(a&&a()>0&&p>0){u(Math.min(o,p));return}d()},f),c.unref()};u(o),e.close(d),e.closeIdleConnections()},wE=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),dH=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]),uH=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),pH=45*1e3,fH=600*1e3,hH=new Set(["host","connection","keep-alive","proxy-connection","content-length","transfer-encoding","upgrade"]),mH=new Set(["content-encoding","content-length","transfer-encoding","connection","keep-alive"]),yH=new Set(["missing_key","key_expired"]),gH=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object")return!1;let{status:n,code:r}=t;return n==="failure"&&typeof r=="string"&&yH.has(r)}catch{return!1}},wH=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(hH.has(n.toLowerCase())||(t[n.toLowerCase()]=Array.isArray(r)?r.join(", "):r));return t},bH=e=>new Promise((t,n)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>t(Buffer.concat(r))),e.on("error",o=>n(o))}),kH=(e,t)=>e?wE.has(e)?!0:dH.has(e)&&uH.has(t.toUpperCase()):!1,CH=new Set(["127.0.0.1","localhost","[::1]","::1"]),AH=e=>{if(e[ep]===void 0||e.origin!==void 0)return!1;let t=(e.host??"").replace(/:\d+$/,"");return CH.has(t)},vH=(e,t)=>{let n=(t??"").split("?")[0];return e==="GET"&&n==="/__anyray/health"||e==="POST"&&n==="/__anyray/shutdown"},SH=async(e,t,n,r)=>{try{return{res:await fetch(e,{method:t,headers:n,body:r.length?r:void 0,duplex:"half"})}}catch(o){return{failure:{kind:"transport-error",code:o?.cause?.code}}}},Sm=e=>new Promise(t=>setTimeout(t,e)),mE=async(e,t,n,r,o,a=oH)=>{let s=Date.now()+a,i=fE,c=!1;for(;;){let l=await SH(e,t,n,r);if("res"in l||!o())return l;let d=l.failure.code;if(d!==void 0&&wE.has(d)){if(Date.now()+i>s)return l;await Sm(i),i=Math.min(i*2,aH)}else if(!c&&kH(d,t))c=!0,await Sm(fE);else return l;if(!o())return l}},vm=async(e,t)=>{let n={};if(t.headers.forEach((s,i)=>{mH.has(i.toLowerCase())||(n[i]=s)}),e.writeHead(t.status,n),!t.body){e.end();return}let r=t.body.getReader(),o=()=>{r.cancel().catch(()=>{})};e.once("close",o);let a=!1;try{for(;;){let{done:s,value:i}=await r.read();if(s)break;if(i){if(e.destroyed){r.cancel().catch(()=>{});continue}e.write(i)||await new Promise(c=>{if(e.destroyed||e.writableEnded){c();return}let l=()=>{e.off("close",d),c()},d=()=>{e.off("drain",l),c()};e.once("drain",l),e.once("close",d)})}}}catch{a=!0}finally{e.off("close",o)}a&&!e.writableEnded?e.destroy():e.end()},yE=(e,t,n)=>{e.headersSent||e.destroyed||(e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify({error:{type:"anyray_proxy",message:n}})))},EH=e=>{let t=e.remoteOrigin.replace(/\/+$/,""),n=0,r=async(a,s)=>{let i=a.url??"/",c=a.method??"GET";if(c==="GET"&&i==="/__anyray/health"){s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({status:"ok",mode:"refresh-only",port:e.port,remoteOrigin:t,version:we,inFlight:n}));return}if(c==="POST"&&(i==="/__anyray/shutdown"||i.startsWith("/__anyray/shutdown?"))){if(!AH(a.headers)){s.writeHead(403,{"content-type":"application/json"}),s.end(JSON.stringify({error:"forbidden"}));return}let b=i.includes("?")?i.slice(i.indexOf("?")+1):"",A=new URLSearchParams(b).get("drain")==="idle"?"idle":void 0;s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({status:"stopping"})),e.onShutdown?.({drain:A});return}let l=await bH(a),d=wH(a.headers),u=aE(a.headers),f=b=>{if(!u){d["x-anyray-api-key"]=b;return}d[u.slot]=u.slot==="authorization"?`Bearer ${b}`:b},p,h=!1;if(e.resolveClientKey&&!oE(a.headers)){h=!0;try{p=await e.resolveClientKey(),p&&f(p)}catch{}}let m=await mE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("failure"in m){yE(s,502,`gateway unreachable (${m.failure.code??"transport-error"})`);return}let w=()=>{if(!(m.res.status!==401||!e.onGatewayUnauthorized))try{e.onGatewayUnauthorized(i,a.headers)}catch{}},g=h;!g&&m.res.status===401&&u&&e.isOwnClientKey&&(g=await e.isOwnClientKey(u.key).catch(()=>!1));let y=g&&(h?!!e.recoverInjectedKey:!!e.resolveClientKey);if(m.res.status===401&&y){let b=await m.res.text().catch(()=>"");if(gH(b)){let A=h?await e.recoverInjectedKey().catch(()=>{}):await e.resolveClientKey().catch(()=>{}),v=p??u?.key;if(A!==void 0&&A!==v){f(A);let E=await mE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("res"in E){E.res.status===401&&w(),await vm(s,E.res);return}}}w(),await vm(s,new Response(b,{status:m.res.status,headers:m.res.headers}));return}w(),await vm(s,m.res)},o=nH.createServer((a,s)=>{s.on("error",()=>{}),vH(a.method,a.url)||(n++,s.once("close",()=>{n--})),r(a,s).catch(i=>{console.error(`anyray refresh proxy: request error ${Wd(i)}`),s.headersSent?s.end():yE(s,502,"anyray proxy internal error")})});return o.keepAliveTimeout=sH,o.headersTimeout=iH,o.on("error",a=>{a.code!=="EADDRINUSE"&&console.error(`anyray refresh proxy: server error ${Wd(a)}`)}),{server:o,inFlight:()=>n}},bE=5e3,IH=2e3,xH=(e={})=>{let t=e.now??Date.now,n=e.loadProfile??L,r=e.refresh??(()=>et()),o=e.remintBudgetMs??bE,a,s=-1/0,i=3e4;return Object.assign(async()=>{let l=a===void 0?IH:i;if(t()-s<l)return a;let d=await n().catch(()=>({})),u=Date.parse(d.clientKeyExpiresAt??"");if(Number.isFinite(u)){let f=u-t();if(f<=0){await Promise.race([Promise.resolve().then(r).catch(()=>{}),new Promise(h=>setTimeout(h,o).unref?.())]),d=await n().catch(()=>d);let p=Date.parse(d.clientKeyExpiresAt??"");if(Number.isFinite(p)&&p-t()<=0)return a=void 0,s=t(),a}else f<=_i(d)&&Promise.resolve().then(r).catch(()=>{})}return a=d.clientKey,s=t(),a},{invalidate:()=>{a=void 0,s=-1/0}})},kE=async()=>{let e=await L(),t=e.fallbackPort,n=e.gateway?.replace(/\/+$/,"");if(!t||!n){let p=await Vt().catch(()=>{});p?.gateway&&(n??=p.gateway.replace(/\/+$/,""),t??=ke)}if(!t||!n)return console.error("anyray refresh proxy: not configured (missing loopbackPort/gateway in ~/.anyray, and no fleet bootstrap with a gateway). Run `anyray-connect` first."),1;let r=sE(),o=xH(),a=EH({port:t,remoteOrigin:n,onGatewayUnauthorized:(p,h)=>r.onGatewayUnauthorized(p,h),resolveClientKey:o,recoverInjectedKey:async()=>(o.invalidate(),await Promise.race([et({force:!0}).catch(()=>{}),new Promise(p=>setTimeout(p,bE).unref?.())]),o()),isOwnClientKey:p=>MS(p),onShutdown:p=>f(0,{drain:p.drain})});et().catch(()=>{});let s=setInterval(()=>{et().catch(()=>{})},rH);s.unref();let i=iE(),c=pE(),l=Date.now();a.server.on("request",()=>{l=Date.now()});let d=setInterval(()=>{Date.now()-l>fH||fetch(`${n}/`,{method:"HEAD"}).catch(()=>{})},pH);d.unref();let u=!1,f=(p=0,h={})=>{if(u)return;u=!0,clearInterval(s),clearInterval(d),i.stop(),c.stop();let m=h.drain==="idle"?hE:gE;kw(Date.now()+m),lH(a.server,{exitCode:p,inFlight:a.inFlight,ceilingMs:h.drain==="idle"?hE:void 0,exit:w=>{op(),process.exit(w)}})};return process.once("SIGTERM",()=>f()),process.once("SIGINT",()=>f()),process.on("uncaughtException",p=>{console.error(`anyray refresh proxy: uncaught exception ${Wd(p)}`),f(1)}),process.on("unhandledRejection",p=>{console.error(`anyray refresh proxy: unhandled rejection ${p instanceof Error?Wd(p):typeof p}`),f(1)}),op(),await mw(ps()).catch(()=>{}),await cH(a.server,t),console.error(`anyray refresh proxy listening on 127.0.0.1:${t} \u2192 ${n}`),await new Promise(()=>{}),0};import{platform as RH}from"node:os";import{stat as OH}from"node:fs/promises";import{spawnSync as _H}from"node:child_process";var CE="/Applications/Anyray Connect Tray.app",TH=new Set(["V53XMA78UF"]),PH="ai.anyray.connect-tray",LH=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,DH=e=>{let t=_H("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
307
- ${t.stderr??""}`}},NH=async e=>{try{return(await OH(e)).isDirectory()}catch{return!1}},$H=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},Em=async(e,t={})=>{if((t.os??RH())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??NH)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??DH;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?$H(a.output):void 0;return s?TH.has(s)?LH(a.output)!==PH?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},Eo=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await Em(n,t)).ok?"healthy":"gone"},Im=async(e={})=>{try{let t=e.load??L,n=await t(),r=await Eo(n,e);if(r!=="gone")return r;let o=e.installScheduler??dr,a=e.installDaemon??Nt;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await a({port:n.fallbackPort??ke,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??re)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var MH={"not-macos":"persistence swap: macOS only \u2014 the LaunchAgents stay in place on this OS.","bad-path":"persistence swap: --app-path must point at a .app bundle.",missing:"persistence swap: tray app bundle not found \u2014 nothing changed.",unsigned:"persistence swap: tray app failed codesign verification \u2014 refusing to adopt (RFC 0010 invariant 5).","no-team-identifier":"persistence swap: tray app has no Developer ID TeamIdentifier (adhoc or unsigned) \u2014 refusing to adopt (RFC 0010 invariant 5).","untrusted-team":"persistence swap: tray app is signed by a Developer ID that is not Anyray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgents stay in place.","untrusted-bundle-id":"persistence swap: that bundle is not the Anyray Connect Tray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgents stay in place."},FH=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},UH=async(e,t)=>{let n=t.stderr??console.error,r=FH(e,"--app-path")??CE,o=await Em(r,t);if(!o.ok)return n(MH[o.reason]),1;let s=await(t.load??L)();await(t.save??re)({...s,persistenceOwner:"tray",trayAppPath:r});let c=t.uninstallScheduler??ur,l=t.uninstallDaemon??Qt;return await c().catch(()=>{}),await l(s.fallbackPort).catch(()=>{}),0},BH=async e=>{let t=e.load??L,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??dr,o=e.installDaemon??Nt;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await o({port:n.fallbackPort??ke,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??re)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},AE=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await UH(e,t):e.includes("--release-tray")?await BH(t):(n("persistence swap: expected --adopt-tray or --release-tray."),1)}catch(r){return n(`persistence swap: failed (${r instanceof Error?r.name:"Error"}).`),1}};import{homedir as vE,platform as xm}from"node:os";import{join as La}from"node:path";import{access as WH}from"node:fs/promises";var Rm=(e=xm(),t=vE())=>{let n=a=>[La(t,"Library","LaunchAgents",`${a}.plist`)],r=La(t,".config","systemd","user"),o=a=>[La(t,".anyray","logs",a)];return e==="darwin"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:hs,paths:n(hs),dataPaths:o("connect-daemon.log")},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:Cs,paths:n(Cs),dataPaths:o("connect-refresh.log")}]:e==="linux"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:`${lr}.service`,paths:[La(r,`${lr}.service`)]},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:`${Yr}.timer`,paths:[La(r,`${Yr}.timer`),La(r,`${Yr}.service`)]}]:e==="win32"?[{kind:"scheduler",title:"key-refresh scheduler",supervisorName:Lc,paths:[]}]:[]},SE=async e=>{try{return await WH(e),!0}catch{return!1}},Pi=async(e,t={})=>{let n=t.exists??SE,r=t.os??xm();for(let o of Rm(r,t.home))if(o.kind===e){if(o.paths.length===0){if(await(t.supervisorHolds??HH)(e,r))return!0;continue}for(let a of o.paths)if(await n(a))return!0}return!1},HH=async(e,t)=>{if(e!=="scheduler")return!1;try{return await Yo(t)}catch{return!1}},EE=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable)return t;let n=e.exists??SE,r=Rm(e.os,e.home);for(let o of r)if(o.kind==="daemon"?e.daemonEnabled&&e.daemonHealthy===!1:e.schedulerEnabled&&!e.schedulerInstalled)for(let s of o.paths)await n(s)||(t.missingPaths.push(s),t.kinds.includes(o.kind)||t.kinds.push(o.kind));return t.suspected=t.missingPaths.length>0,t},KH=[hs,`${lr}.service`,Cs,`${Yr}.timer`,`${Yr}.service`,Lc],IE=(e,t=xm(),n=vE(),r=ir())=>{let o=["Anyray connect installs two per-user background services. Both are","unprivileged, run as the logged-in user, and exist only to re-mint the","seat's short-lived gateway key so a long AI-coding session doesn't 401.","","Executable (both services):",` ${r}`,""];for(let a of Rm(t,n)){o.push(`${a.title} \u2014 supervisor name: ${a.supervisorName}`);for(let s of a.paths)o.push(` ${s}`);a.paths.length===0&&o.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let s of a.dataPaths??[])o.push(` ${s} (captured stdout/stderr \u2014 error names only)`);o.push("")}return o.push("Also spawns, detached and short-lived (same executable, hidden","subcommands \u2014 not a separate install):"," - Coding-tool MCP clients (Copilot Chat, Copilot CLI, OpenCode, etc.) run"," `anyray-connect __anyray-mcp-server` as a stdio server, which spawns a"," detached `anyray-connect __anyray-refresh`."," - The Anyray VS Code extension, on activation (including a remote/"," Codespace/dev-container extension host), spawns"," `anyray-connect __anyray-spawn-refresh` \u2014 a cheap gate that may itself"," spawn the same detached `anyray-connect __anyray-refresh`."," Both are throttled independently of the scheduler (up to ~6h between"," spawns) and serialized through the same refresh-state claim, so they can"," never double-mint against it. Neither listens itself; the tick can"," (re)install the loopback daemon disclosed above, whose port is covered"," under Network behavior.","","Network behavior:",` - The daemon listens on 127.0.0.1:${e} ONLY (loopback; it never binds a`," routable interface and accepts no remote connections)."," - Outbound: your org's Anyray gateway over HTTPS, nothing else."," - It relays your AI tools\u2019 requests byte-for-byte; its single mutation is"," filling in a freshly minted gateway key header.","","Why it looks like persistence to a heuristic scanner: the launchd agent is a","KeepAlive login item, which is the same shape a persistence implant uses. It","is a real login item, by design \u2014 that is what keeps keys fresh across","reboots. Allow-list the paths above, or run `anyray-connect --no-key-refresh`","to install no background service at all (tools then point straight at the","gateway, at the cost of a periodic re-run when the key lapses).","","Retired supervisor labels (endpoint v2): on a machine running Fleet\u2019s signed","fleetd, connect retires the services above \u2014 fleetd drives key refresh","instead. If you find any of these labels/units on a fleetd host, they are","orphans safe to remove; connect no longer installs or supervises them:",...KH.map(a=>` - ${a}`)),o};var Om=5e3,xE=3e4,GH=1440*60*1e3,jH=e=>new Promise(t=>setTimeout(t,e)),VH=async(e=L,t=$t)=>(await _e(e,t))?.target,YH=e=>Kt(e)?.quitGated,RE=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??YH,o=t.readPending??rl,a=t.clearPending??Up,s=t.targetFromProfile??VH,i=t.sleep??jH,c=t.now??Date.now,l=t.maxWaitMs??GH;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=Om;for(;;){let h=await o(n);if(!h||c()-f>l)return 0;if(d.isRunning()){await i(p),p=Math.min(xE,p*2);continue}let m;if(d.needsTarget?.(h.op)&&(m=await s(),!m)){if(await a(n,h)!=="superseded")return 0;await i(p),p=Om;continue}if((await u(h.op,m,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(p),p=Math.min(xE,p*2);continue}if(await a(n,h)!=="superseded")return 0;await i(p),p=Om}}catch{return 0}};import{writeFileSync as zH}from"node:fs";import{chmod as _m,stat as qH}from"node:fs/promises";import{platform as Pm}from"node:os";import{dirname as PE,isAbsolute as QH}from"node:path";var Da=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Hd=Da(process.stdout,process.env),OE=Da(process.stderr,process.env),Na=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,j=e=>Na("1",e,Hd),S=e=>Na("2",e,Hd),ZH=e=>Na("32",e,Hd),JH=e=>Na("33",e,OE),XH=e=>Na("31",e,OE),tt=e=>Na("36",e,Hd),k=e=>console.log(e),K=e=>console.log(`
308
- ${j(e)}`),M=e=>console.log(S(e)),F=e=>console.log(`${ZH("\u2713")} ${e}`),D=e=>console.error(`${JH("!")} ${e}`),_=e=>console.error(`${XH("\u2717")} ${e}`);var Tm=`${j("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
304
+ `,P1=e=>Math.min(A1,C1*2**Math.max(0,e-1)),T1=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?v1:P1(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},qn=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??D,o=t.saveProfile??re,a=t.loadDevKey??We,s=t.readGateState??_r,i=t.writeGateState??Wd,c=t.isProcessAlive??eE,l=t.startGrant??Ud,d=t.verify??ln,u=t.routingIntact??x1,f=t.applyClaudeCode??I1,p=t.maybeSpawnRefresh??Rr,h=t.recordMint??_a,m=t.reserveMint??Ao,w=t.spawnPoller??R1,g=t.openBrowser??Pa;try{let y=Rt(e.sso);if(!y)return{exitCode:0};let b=await r(),A=await s(),v=b.enrolledCert?await a():void 0,E=_1(b),x=!!(b.enrolledCert&&v)&&Number.isFinite(E)&&E>n(),C=e.gateway??b.gateway;if(x&&b.enrolledCert&&v&&C){let Z=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(Z)&&Z>n()&&b.clientKey){let me=tE(C,b,e.team,b.clientKey);return await u(me)?(Z-n()<=gm()&&await p(),{exitCode:0}):(await f(me),Ta(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
305
+ `))}let q;await m();try{q=await d(C,b.enrolledCert,v,{timeoutMs:1e4})}catch(me){if(!(me instanceof Ot))return Ta(e,vm("gateway-unreachable",y.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(q){let me={...b,gateway:C,name:q.user,team:e.team??q.team??b.team,clientKey:q.key,clientKeyExpiresAt:q.expiresAt,authMode:"subscription"};return await o(me),await h({expiresAt:q.expiresAt}),await f(tE(C,me,e.team,q.key)),{exitCode:0}}}if(A?.status==="pending"&&(A.userCode&&A.verificationUriComplete)&&(A.grantExpiresAt??0)>n()&&c(A.pollerPid)){if(e.sessionStart&&A.verificationUriComplete)try{g(A.verificationUriComplete)}catch{}return Ta(e,nE(A))}if(A){let Z=T1(A,n());if(Z)return Ta(e,vm(Z,y.cpOrigin))}let I;try{I=await l({cpOrigin:y.cpOrigin,tenantId:y.tenantId,gatewayUrl:e.gateway,now:n})}catch(Z){let W=Z instanceof vo?Z.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:A?.lastFailure===W?(A.failureCount??0)+1:1,lastFailure:W}),Ta(e,vm(W,y.cpOrigin))}let P={v:1,status:"pending",userCode:I.userCode,verificationUriComplete:I.verificationUriComplete,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,lastAttemptAt:n(),failureCount:0};await i(P);let $=w(),Y={...P,pollerPid:$.pid};if(await i(Y),$.handoff({deviceCode:I.deviceCode,privateKeyPem:I.privateKeyPem,publicKeyPem:I.publicKeyPem,cpOrigin:I.cpOrigin,tenantId:I.tenantId,intervalMs:I.intervalMs,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,gatewayUrl:I.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{g(I.verificationUriComplete)}catch{}return Ta(e,nE(Y))}catch{return{exitCode:0}}},L1=async()=>{try{for await(let e of process.stdin);}catch{}},rE=async e=>{await L1();try{let t=await qn(S1(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var N1=6e4,$1=10*6e4,zn=(e,t)=>{let n=e[t];return typeof n=="string"?n:Array.isArray(n)?n[0]:void 0},M1=e=>{if(zn(e,"x-anyray-api-key")?.trim())return!0;let t=zn(e,"authorization")?.trim()??"";return/^bearer\s+\S+/i.test(t)?!0:(zn(e,"x-api-key")?.trim()??"").startsWith("ark_")},aE=e=>{if(zn(e,"x-anyray-api-key")?.trim())return!0;let t=zn(e,"authorization")?.trim()??"";return/^bearer\s+ark_\S+/i.test(t)?!0:(zn(e,"x-api-key")?.trim()??"").startsWith("ark_")},sE=e=>{let t=zn(e,"x-anyray-api-key")?.trim();if(t?.startsWith("ark_"))return{key:t,slot:"x-anyray-api-key"};let r=(zn(e,"authorization")?.trim()??"").match(/^bearer\s+(ark_\S+)/i);if(r)return{key:r[1],slot:"authorization"};let o=zn(e,"x-api-key")?.trim()??"";return o.startsWith("ark_")?{key:o,slot:"x-api-key"}:void 0},F1=e=>e.split("?")[0].includes("/v1/"),oE=e=>e.replace(/[^\x20-\x7e]/g,"").replace(/["'`\\$]/g,"").slice(0,300),U1=(e,t,n=process.platform,r=D1)=>{let o=oE(e),a=oE(t);try{n==="darwin"?r("/usr/bin/osascript",["-e",`display notification "${a}" with title "${o}"`],{timeout:5e3},()=>{}):n==="linux"&&r("notify-send",["--app-name=Anyray",o,a],{timeout:5e3},()=>{})}catch{}},iE=(e={})=>{let t=e.readBootstrap??jt,n=e.ssoGate??qn,r=e.readState??_r,o=e.notify??U1,a=e.now??Date.now,s=0,i,c=0,l=!1,d=async()=>{let u=await t();if(!u||(await n({sso:u.sso,gateway:u.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}})).exitCode!==2)return;let p=await r();p?.status!=="pending"||!p.userCode||!p.verificationUriComplete||!(p.userCode!==i)&&a()-c<$1||(i=p.userCode,c=a(),o("Anyray \u2014 sign in to use AI tools",`Open ${p.verificationUriComplete} and enter code ${p.userCode}. Requests keep failing until sign-in completes.`))};return{onGatewayUnauthorized(u,f){try{if(!F1(u)||M1(f)||l||a()-s<N1)return;s=a(),l=!0,d().catch(()=>{}).finally(()=>{l=!1})}catch{}}}};import{watch as B1}from"node:fs";import{basename as W1,dirname as H1}from"node:path";var K1=2e3,G1=6e4,La=e=>e instanceof Error?e.name:"UnknownError",j1=(e,t,n)=>{let r=B1(e,{persistent:!1},(o,a)=>{t(a==null?null:a.toString())});return r.on("error",n),r},V1=async(e,t)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Re(async()=>e,void 0,t);if(!r)return!1;let o=await xr(n,r.toolOrigin);return o.length===0?!1:(await gt(o,r.target),!0)}catch{return!1}},cE=(e={})=>{let t=e.loadProfile??D,n=e.adapters??ie,r=e.probe??be,o=e.repairDrift??(C=>V1(C,r)),a=e.resolveProfileFile??No,s=e.watchDir??j1,i=e.debounceMs??K1,c=e.repairFloorMs??G1,l=e.now??Date.now,d=e.logError??(C=>console.error(`anyray refresh proxy: drift watcher ${C}`)),u=!1,f=0,p,h=Promise.resolve(),m=new Map,w=C=>{let I=m.get(C);if(I){m.delete(C);try{I.handle.close()}catch{}}},g=()=>{if(u)return;p!==void 0&&clearTimeout(p);let C=setTimeout(()=>{p=void 0,h=h.then(E).catch(()=>{})},i);C.unref?.(),p=C},y=C=>I=>{if(!u)try{let P=m.get(C);if(!P||I!==null&&!P.files.has(I))return;g()}catch(P){d(La(P))}},b=C=>I=>{d(La(I)),w(C),g()},A=async C=>{let I=[],P=new Set(C.managedTools??[]);for(let Z of n)if(!(!P.has(Z.id)||!Z.watchPaths))try{I.push(...await Z.watchPaths())}catch(W){d(La(W))}let $=await a().catch(()=>{});$&&I.push($);let Y=new Map;for(let Z of I){let W=H1(Z),q=Y.get(W)??new Set;q.add(W1(Z)),Y.set(W,q)}return Y},v=async C=>{let I=await A(C);if(!u){for(let P of[...m.keys()])I.has(P)||w(P);for(let[P,$]of I){let Y=m.get(P);if(Y){Y.files=$;continue}try{m.set(P,{handle:s(P,y(P),b(P)),files:$})}catch(Z){d(La(Z))}}}},E=async()=>{if(!u)try{let C=await t().catch(()=>({}));if(await v(C),u||l()-f<c)return;f=l(),await o(C).catch(()=>!1)}catch(C){d(La(C))}};return{ready:t().then(C=>v(C)).catch(C=>d(La(C))),stop:()=>{u=!0,p!==void 0&&(clearTimeout(p),p=void 0);for(let C of[...m.keys()])w(C)}}};import{randomBytes as Y1}from"node:crypto";import{chmod as Z1,readFile as X1,rm as uE,writeFile as J1}from"node:fs/promises";import{join as q1}from"node:path";var z1=/^[A-Za-z0-9_-]{43}$/,Q1=3600*1e3,lE=3900,eW=1e4,Sm=()=>q1(Q(),"device-token.json"),tW=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&z1.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},pE=async()=>{try{let e=JSON.parse(await X1(Sm(),"utf-8"));return tW(e)?e:null}catch{return null}},nW=0,rW=async e=>{await kt();let t=Sm(),n=`${t}.${process.pid}.${nW++}.tmp`;try{await J1(n,`${JSON.stringify(e)}
306
+ `,{mode:384}),await Z1(n,384),await he(n,t)}catch(r){throw await uE(n,{force:!0}).catch(()=>{}),r}},Hd=async()=>{await uE(Sm(),{force:!0}).catch(()=>{})},oW=()=>Y1(32).toString("base64url"),aW=e=>e instanceof Error?e.name:"UnknownError",sW=(e,t)=>{let n=setInterval(e,t);return n.unref(),{stop:()=>clearInterval(n)}},dE=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??D)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=oW(),i=new AbortController,c=setTimeout(()=>i.abort(),eW),l;try{l=await n(`${o}/connect/device-token`,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":a},body:JSON.stringify({token:s,ttlSeconds:lE}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await rW({v:1,token:s,expiresAt:t()+lE*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${aW(r)}`),!1}},fE=(e={})=>{dE(e);let n=(e.scheduleRotation??sW)(()=>{dE(e)},Q1);return{stop:()=>n.stop()}};var cW=1800*1e3,hE=50,lW=15e3,dW=1e3,wE=gs*1e3-1e4,mE=15*6e4,uW=75e3,pW=8e4,fW=async(e,t,n={})=>{let r=n.budgetMs??gs*1e3,o=n.delayMs??250,a=Date.now()+r;for(;;)try{await new Promise((s,i)=>{let c=l=>i(l);e.once("error",c),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",c),s()})});return}catch(s){if(s.code!=="EADDRINUSE"||Date.now()+o>a)throw s;await xm(o)}},Kd=e=>{let t=e instanceof Error?e.name:"unknown",n=e?.code;return typeof n=="string"?`${t} ${n}`:t},hW=(e,t={})=>{let n=t.exit??(f=>process.exit(f)),r=t.exitCode??0,o=t.hardCapMs??wE,a=t.inFlight,s=Date.now()+(t.ceilingMs??o),i=setInterval(()=>e.closeIdleConnections(),500);i.unref();let c,l=!1,d=()=>{l||(l=!0,clearInterval(i),clearTimeout(c),n(r))},u=f=>{c=setTimeout(()=>{let p=s-Date.now();if(a&&a()>0&&p>0){u(Math.min(o,p));return}d()},f),c.unref()};u(o),e.close(d),e.closeIdleConnections()},bE=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),mW=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]),yW=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),gW=45*1e3,wW=600*1e3,bW=new Set(["host","connection","keep-alive","proxy-connection","content-length","transfer-encoding","upgrade"]),kW=new Set(["content-encoding","content-length","transfer-encoding","connection","keep-alive"]),CW=new Set(["missing_key","key_expired"]),AW=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object")return!1;let{status:n,code:r}=t;return n==="failure"&&typeof r=="string"&&CW.has(r)}catch{return!1}},vW=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(bW.has(n.toLowerCase())||(t[n.toLowerCase()]=Array.isArray(r)?r.join(", "):r));return t},SW=e=>new Promise((t,n)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>t(Buffer.concat(r))),e.on("error",o=>n(o))}),EW=(e,t)=>e?bE.has(e)?!0:mW.has(e)&&yW.has(t.toUpperCase()):!1,xW=new Set(["127.0.0.1","localhost","[::1]","::1"]),IW=e=>{if(e[np]===void 0||e.origin!==void 0)return!1;let t=(e.host??"").replace(/:\d+$/,"");return xW.has(t)},OW=(e,t)=>{let n=(t??"").split("?")[0];return e==="GET"&&n==="/__anyray/health"||e==="POST"&&n==="/__anyray/shutdown"},RW=async(e,t,n,r)=>{try{return{res:await fetch(e,{method:t,headers:n,body:r.length?r:void 0,duplex:"half"})}}catch(o){return{failure:{kind:"transport-error",code:o?.cause?.code}}}},xm=e=>new Promise(t=>setTimeout(t,e)),yE=async(e,t,n,r,o,a=lW)=>{let s=Date.now()+a,i=hE,c=!1;for(;;){let l=await RW(e,t,n,r);if("res"in l||!o())return l;let d=l.failure.code;if(d!==void 0&&bE.has(d)){if(Date.now()+i>s)return l;await xm(i),i=Math.min(i*2,dW)}else if(!c&&EW(d,t))c=!0,await xm(hE);else return l;if(!o())return l}},Em=async(e,t)=>{let n={};if(t.headers.forEach((s,i)=>{kW.has(i.toLowerCase())||(n[i]=s)}),e.writeHead(t.status,n),!t.body){e.end();return}let r=t.body.getReader(),o=()=>{r.cancel().catch(()=>{})};e.once("close",o);let a=!1;try{for(;;){let{done:s,value:i}=await r.read();if(s)break;if(i){if(e.destroyed){r.cancel().catch(()=>{});continue}e.write(i)||await new Promise(c=>{if(e.destroyed||e.writableEnded){c();return}let l=()=>{e.off("close",d),c()},d=()=>{e.off("drain",l),c()};e.once("drain",l),e.once("close",d)})}}}catch{a=!0}finally{e.off("close",o)}a&&!e.writableEnded?e.destroy():e.end()},gE=(e,t,n)=>{e.headersSent||e.destroyed||(e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify({error:{type:"anyray_proxy",message:n}})))},_W=e=>{let t=e.remoteOrigin.replace(/\/+$/,""),n=0,r=async(a,s)=>{let i=a.url??"/",c=a.method??"GET";if(c==="GET"&&i==="/__anyray/health"){s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({status:"ok",mode:"refresh-only",port:e.port,remoteOrigin:t,version:we,inFlight:n}));return}if(c==="POST"&&(i==="/__anyray/shutdown"||i.startsWith("/__anyray/shutdown?"))){if(!IW(a.headers)){s.writeHead(403,{"content-type":"application/json"}),s.end(JSON.stringify({error:"forbidden"}));return}let b=i.includes("?")?i.slice(i.indexOf("?")+1):"",A=new URLSearchParams(b).get("drain")==="idle"?"idle":void 0;s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({status:"stopping"})),e.onShutdown?.({drain:A});return}let l=await SW(a),d=vW(a.headers),u=sE(a.headers),f=b=>{if(!u){d["x-anyray-api-key"]=b;return}d[u.slot]=u.slot==="authorization"?`Bearer ${b}`:b},p,h=!1;if(e.resolveClientKey&&!aE(a.headers)){h=!0;try{p=await e.resolveClientKey(),p&&f(p)}catch{}}let m=await yE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("failure"in m){gE(s,502,`gateway unreachable (${m.failure.code??"transport-error"})`);return}let w=()=>{if(!(m.res.status!==401||!e.onGatewayUnauthorized))try{e.onGatewayUnauthorized(i,a.headers)}catch{}},g=h;!g&&m.res.status===401&&u&&e.isOwnClientKey&&(g=await e.isOwnClientKey(u.key).catch(()=>!1));let y=g&&(h?!!e.recoverInjectedKey:!!e.resolveClientKey);if(m.res.status===401&&y){let b=await m.res.text().catch(()=>"");if(AW(b)){let A=h?await e.recoverInjectedKey().catch(()=>{}):await e.resolveClientKey().catch(()=>{}),v=p??u?.key;if(A!==void 0&&A!==v){f(A);let E=await yE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("res"in E){E.res.status===401&&w(),await Em(s,E.res);return}}}w(),await Em(s,new Response(b,{status:m.res.status,headers:m.res.headers}));return}w(),await Em(s,m.res)},o=iW.createServer((a,s)=>{s.on("error",()=>{}),OW(a.method,a.url)||(n++,s.once("close",()=>{n--})),r(a,s).catch(i=>{console.error(`anyray refresh proxy: request error ${Kd(i)}`),s.headersSent?s.end():gE(s,502,"anyray proxy internal error")})});return o.keepAliveTimeout=uW,o.headersTimeout=pW,o.on("error",a=>{a.code!=="EADDRINUSE"&&console.error(`anyray refresh proxy: server error ${Kd(a)}`)}),{server:o,inFlight:()=>n}},kE=5e3,PW=2e3,TW=(e={})=>{let t=e.now??Date.now,n=e.loadProfile??D,r=e.refresh??(()=>tt()),o=e.remintBudgetMs??kE,a,s=-1/0,i=3e4;return Object.assign(async()=>{let l=a===void 0?PW:i;if(t()-s<l)return a;let d=await n().catch(()=>({})),u=Date.parse(d.clientKeyExpiresAt??"");if(Number.isFinite(u)){let f=u-t();if(f<=0){await Promise.race([Promise.resolve().then(r).catch(()=>{}),new Promise(h=>setTimeout(h,o).unref?.())]),d=await n().catch(()=>d);let p=Date.parse(d.clientKeyExpiresAt??"");if(Number.isFinite(p)&&p-t()<=0)return a=void 0,s=t(),a}else f<=Ti(d)&&Promise.resolve().then(r).catch(()=>{})}return a=d.clientKey,s=t(),a},{invalidate:()=>{a=void 0,s=-1/0}})},CE=async()=>{let e=await D(),t=e.fallbackPort,n=e.gateway?.replace(/\/+$/,"");if(!t||!n){let p=await jt().catch(()=>{});p?.gateway&&(n??=p.gateway.replace(/\/+$/,""),t??=ke)}if(!t||!n)return console.error("anyray refresh proxy: not configured (missing loopbackPort/gateway in ~/.anyray, and no fleet bootstrap with a gateway). Run `anyray-connect` first."),1;let r=iE(),o=TW(),a=_W({port:t,remoteOrigin:n,onGatewayUnauthorized:(p,h)=>r.onGatewayUnauthorized(p,h),resolveClientKey:o,recoverInjectedKey:async()=>(o.invalidate(),await Promise.race([tt({force:!0}).catch(()=>{}),new Promise(p=>setTimeout(p,kE).unref?.())]),o()),isOwnClientKey:p=>FS(p),onShutdown:p=>f(0,{drain:p.drain})});tt().catch(()=>{});let s=setInterval(()=>{tt().catch(()=>{})},cW);s.unref();let i=cE(),c=fE(),l=Date.now();a.server.on("request",()=>{l=Date.now()});let d=setInterval(()=>{Date.now()-l>wW||fetch(`${n}/`,{method:"HEAD"}).catch(()=>{})},gW);d.unref();let u=!1,f=(p=0,h={})=>{if(u)return;u=!0,clearInterval(s),clearInterval(d),i.stop(),c.stop();let m=h.drain==="idle"?mE:wE;Aw(Date.now()+m),hW(a.server,{exitCode:p,inFlight:a.inFlight,ceilingMs:h.drain==="idle"?mE:void 0,exit:w=>{sp(),process.exit(w)}})};return process.once("SIGTERM",()=>f()),process.once("SIGINT",()=>f()),process.on("uncaughtException",p=>{console.error(`anyray refresh proxy: uncaught exception ${Kd(p)}`),f(1)}),process.on("unhandledRejection",p=>{console.error(`anyray refresh proxy: unhandled rejection ${p instanceof Error?Kd(p):typeof p}`),f(1)}),sp(),await gw(hs()).catch(()=>{}),await fW(a.server,t),console.error(`anyray refresh proxy listening on 127.0.0.1:${t} \u2192 ${n}`),await new Promise(()=>{}),0};import{platform as LW}from"node:os";import{stat as DW}from"node:fs/promises";import{spawnSync as NW}from"node:child_process";var AE="/Applications/Anyray Connect Tray.app",$W=new Set(["V53XMA78UF"]),MW="ai.anyray.connect-tray",FW=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,UW=e=>{let t=NW("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
307
+ ${t.stderr??""}`}},BW=async e=>{try{return(await DW(e)).isDirectory()}catch{return!1}},WW=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},Im=async(e,t={})=>{if((t.os??LW())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??BW)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??UW;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?WW(a.output):void 0;return s?$W.has(s)?FW(a.output)!==MW?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},So=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await Im(n,t)).ok?"healthy":"gone"},Om=async(e={})=>{try{let t=e.load??D,n=await t(),r=await So(n,e);if(r!=="gone")return r;let o=e.installScheduler??pr,a=e.installDaemon??Dt;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await a({port:n.fallbackPort??ke,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??re)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var HW={"not-macos":"persistence swap: macOS only \u2014 the LaunchAgents stay in place on this OS.","bad-path":"persistence swap: --app-path must point at a .app bundle.",missing:"persistence swap: tray app bundle not found \u2014 nothing changed.",unsigned:"persistence swap: tray app failed codesign verification \u2014 refusing to adopt (RFC 0010 invariant 5).","no-team-identifier":"persistence swap: tray app has no Developer ID TeamIdentifier (adhoc or unsigned) \u2014 refusing to adopt (RFC 0010 invariant 5).","untrusted-team":"persistence swap: tray app is signed by a Developer ID that is not Anyray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgents stay in place.","untrusted-bundle-id":"persistence swap: that bundle is not the Anyray Connect Tray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgents stay in place."},KW=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},GW=async(e,t)=>{let n=t.stderr??console.error,r=KW(e,"--app-path")??AE,o=await Im(r,t);if(!o.ok)return n(HW[o.reason]),1;let s=await(t.load??D)();await(t.save??re)({...s,persistenceOwner:"tray",trayAppPath:r});let c=t.uninstallScheduler??fr,l=t.uninstallDaemon??Qt;return await c().catch(()=>{}),await l(s.fallbackPort).catch(()=>{}),0},jW=async e=>{let t=e.load??D,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??pr,o=e.installDaemon??Dt;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await o({port:n.fallbackPort??ke,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??re)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},vE=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await GW(e,t):e.includes("--release-tray")?await jW(t):(n("persistence swap: expected --adopt-tray or --release-tray."),1)}catch(r){return n(`persistence swap: failed (${r instanceof Error?r.name:"Error"}).`),1}};import{homedir as SE,platform as Rm}from"node:os";import{join as Da}from"node:path";import{access as VW}from"node:fs/promises";var _m=(e=Rm(),t=SE())=>{let n=a=>[Da(t,"Library","LaunchAgents",`${a}.plist`)],r=Da(t,".config","systemd","user"),o=a=>[Da(t,".anyray","logs",a)];return e==="darwin"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:ys,paths:n(ys),dataPaths:o("connect-daemon.log")},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:vs,paths:n(vs),dataPaths:o("connect-refresh.log")}]:e==="linux"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:`${ur}.service`,paths:[Da(r,`${ur}.service`)]},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:`${Vr}.timer`,paths:[Da(r,`${Vr}.timer`),Da(r,`${Vr}.service`)]}]:e==="win32"?[{kind:"scheduler",title:"key-refresh scheduler",supervisorName:Nc,paths:[]}]:[]},EE=async e=>{try{return await VW(e),!0}catch{return!1}},Di=async(e,t={})=>{let n=t.exists??EE,r=t.os??Rm();for(let o of _m(r,t.home))if(o.kind===e){if(o.paths.length===0){if(await(t.supervisorHolds??YW)(e,r))return!0;continue}for(let a of o.paths)if(await n(a))return!0}return!1},YW=async(e,t)=>{if(e!=="scheduler")return!1;try{return await Yo(t)}catch{return!1}},xE=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable)return t;let n=e.exists??EE,r=_m(e.os,e.home);for(let o of r)if(o.kind==="daemon"?e.daemonEnabled&&e.daemonHealthy===!1:e.schedulerEnabled&&!e.schedulerInstalled)for(let s of o.paths)await n(s)||(t.missingPaths.push(s),t.kinds.includes(o.kind)||t.kinds.push(o.kind));return t.suspected=t.missingPaths.length>0,t},ZW=[ys,`${ur}.service`,vs,`${Vr}.timer`,`${Vr}.service`,Nc],IE=(e,t=Rm(),n=SE(),r=lr())=>{let o=["Anyray connect installs two per-user background services. Both are","unprivileged, run as the logged-in user, and exist only to re-mint the","seat's short-lived gateway key so a long AI-coding session doesn't 401.","","Executable (both services):",` ${r}`,""];for(let a of _m(t,n)){o.push(`${a.title} \u2014 supervisor name: ${a.supervisorName}`);for(let s of a.paths)o.push(` ${s}`);a.paths.length===0&&o.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let s of a.dataPaths??[])o.push(` ${s} (captured stdout/stderr \u2014 error names only)`);o.push("")}return o.push("Also spawns, detached and short-lived (same executable, hidden","subcommands \u2014 not a separate install):"," - Coding-tool MCP clients (Copilot Chat, Copilot CLI, OpenCode, etc.) run"," `anyray-connect __anyray-mcp-server` as a stdio server, which spawns a"," detached `anyray-connect __anyray-refresh`."," - The Anyray VS Code extension, on activation (including a remote/"," Codespace/dev-container extension host), spawns"," `anyray-connect __anyray-spawn-refresh` \u2014 a cheap gate that may itself"," spawn the same detached `anyray-connect __anyray-refresh`."," Both are throttled independently of the scheduler (up to ~6h between"," spawns) and serialized through the same refresh-state claim, so they can"," never double-mint against it. Neither listens itself; the tick can"," (re)install the loopback daemon disclosed above, whose port is covered"," under Network behavior.","","Network behavior:",` - The daemon listens on 127.0.0.1:${e} ONLY (loopback; it never binds a`," routable interface and accepts no remote connections)."," - Outbound: your org's Anyray gateway over HTTPS, nothing else."," - It relays your AI tools\u2019 requests byte-for-byte; its single mutation is"," filling in a freshly minted gateway key header.","","Why it looks like persistence to a heuristic scanner: the launchd agent is a","KeepAlive login item, which is the same shape a persistence implant uses. It","is a real login item, by design \u2014 that is what keeps keys fresh across","reboots. Allow-list the paths above, or run `anyray-connect --no-key-refresh`","to install no background service at all (tools then point straight at the","gateway, at the cost of a periodic re-run when the key lapses).","","Retired supervisor labels (endpoint v2): on a machine running Fleet\u2019s signed","fleetd, connect retires the services above \u2014 fleetd drives key refresh","instead. If you find any of these labels/units on a fleetd host, they are","orphans safe to remove; connect no longer installs or supervises them:",...ZW.map(a=>` - ${a}`)),o};var Pm=5e3,OE=3e4,XW=1440*60*1e3,JW=e=>new Promise(t=>setTimeout(t,e)),qW=async(e=D,t=Nt)=>(await Re(e,t))?.target,zW=e=>Ht(e)?.quitGated,RE=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??zW,o=t.readPending??ol,a=t.clearPending??Wp,s=t.targetFromProfile??qW,i=t.sleep??JW,c=t.now??Date.now,l=t.maxWaitMs??XW;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=Pm;for(;;){let h=await o(n);if(!h||c()-f>l)return 0;if(d.isRunning()){await i(p),p=Math.min(OE,p*2);continue}let m;if(d.needsTarget?.(h.op)&&(m=await s(),!m)){if(await a(n,h)!=="superseded")return 0;await i(p),p=Pm;continue}if((await u(h.op,m,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(p),p=Math.min(OE,p*2);continue}if(await a(n,h)!=="superseded")return 0;await i(p),p=Pm}}catch{return 0}};import{writeFileSync as nH}from"node:fs";import{chmod as Tm,stat as rH}from"node:fs/promises";import{platform as Dm}from"node:os";import{dirname as LE,isAbsolute as oH}from"node:path";var Na=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Gd=Na(process.stdout,process.env),_E=Na(process.stderr,process.env),$a=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,j=e=>$a("1",e,Gd),S=e=>$a("2",e,Gd),QW=e=>$a("32",e,Gd),eH=e=>$a("33",e,_E),tH=e=>$a("31",e,_E),nt=e=>$a("36",e,Gd),k=e=>console.log(e),K=e=>console.log(`
308
+ ${j(e)}`),M=e=>console.log(S(e)),F=e=>console.log(`${QW("\u2713")} ${e}`),L=e=>console.error(`${eH("!")} ${e}`),_=e=>console.error(`${tH("\u2717")} ${e}`);var Lm=`${j("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
309
309
 
310
310
  Emit or install the OS \`managed-settings.json\` that points a managed fleet's
311
311
  Claude Code at the Anyray gateway. It reads at a HIGHER precedence than a user's
@@ -393,13 +393,13 @@ ${j("Examples")}
393
393
  anyray-connect managed --print --tool jetbrains --bin /usr/local/bin/anyray-connect --npx /usr/local/bin/npx > acp.json
394
394
 
395
395
  # Shell/SDK fleet snippet (base URLs only; keys stay per-user):
396
- anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,_E=["claude-code","jetbrains","shell","bootstrap","proxy"],e1=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--print":t.mode="print";break;case"--write":t.mode="write";break;case"--revert":t.mode="revert";break;case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":throw new Error("--key is not valid for managed settings: fleet files never embed credentials; enroll each user instead");case"--scrub-direct-mode":t.scrubDirectMode=!0;break;case"--sso":t.sso=o();break;case"--bin":t.bin=o();break;case"--npx":t.npx=o();break;case"--loopback":t.loopback=!0;break;case"--out":t.out=o();break;case"--platform":{let a=o();if(a!=="launchd"&&a!=="systemd")throw new Error(`unknown --platform ${a} (expected launchd | systemd)`);t.servicePlatform=a;break}case"--tool":{let a=o();if(!_E.includes(a))throw new Error(`unknown --tool ${a} (expected ${_E.join(" | ")}; Codex fleets use \`anyray-connect desktop codex\`)`);t.tool=a;break}case"--subscription":throw new Error("--subscription cannot produce a valid credentialless managed file; use --sso <link> so each user enrolls and receives a personal gateway key");case"--placeholder":case"--org":throw new Error(`${r} is a legacy no-op for managed settings; omit it and enroll each user`);case"--yes":case"-y":break;case"--help":case"-h":t.help=!0;break;default:if(!r.startsWith("-")&&t.gateway===void 0)t.gateway=r;else throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r} (gateway already set to ${t.gateway})`)}}if(t.sso&&!Ot(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function Kd(e,t,n={}){if(!t&&e.authMode==="subscription")throw new Error("subscription managed settings require deferred SSO; a seat OAuth token does not replace the required personal gateway key");if(t){let o=["__anyray-sso-gate","--sso",t.sso,...t.gateway?["--gateway",t.gateway]:[],...t.team?["--team",t.team]:[]];return{hooks:{PostToolUse:[Rn(is(t.binaryPath,[Je]),{matcher:"*"})],UserPromptSubmit:[Rn(is(t.binaryPath,o),{timeout:30}),Rn(is(t.binaryPath,[nr]))],SessionStart:[Rn(is(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=pn(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(On.map(o=>[o.name,""])),...r}}:{env:r}}var t1=(e,t)=>{let n="env"in t||"hooks"in t?t:{env:t},r={...e};e.env&&typeof e.env=="object"&&(r.env={...e.env}),e.hooks&&typeof e.hooks=="object"&&(r.hooks=Object.fromEntries(Object.entries(e.hooks).map(([a,s])=>[a,Array.isArray(s)?[...s]:s])));let o=r.env??{};for(let a of Hr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,Gu(r),n.env&&(r.env={...o,...n.env}),n.hooks){let a=r.hooks??{};for(let[s,i]of Object.entries(n.hooks)){let c=Array.isArray(a[s])?a[s]:[];a[s]=[...c,...i]}r.hooks=a}return r},n1=e=>{let t=e.env,n=Gu(e);if(t){for(let r of Hr)r in t&&(delete t[r],n=!0);for(let{name:r}of On)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},LE=async e=>{let t=async n=>{try{return(await qH(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(PE(e))!==void 0}},DE=async(e,t)=>(t.dirExisted||await _m(PE(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await _m(e,420),{mode:420,keptRestricted:!1}):(await _m(e,t.mode),{mode:t.mode,keptRestricted:!0})),NE=(e,t)=>{t.keptRestricted&&(D(`${e} was already restricted to mode ${t.mode.toString(8).padStart(3,"0")} and keeps it \u2014 widening it would expose whatever else that file holds to every local account.`),k(S(" Claude Code reads this file as the developer, so the routing will NOT take effect until it is readable. Move any secret out of it, then `chmod 644` it.")))},$E=()=>process.getuid?.()===0,Ce=e=>{process.stderr.write(`${e}
397
- `)},Io=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}zH(e.out,t,"utf8"),Ce(S(`# Wrote ${e.out}`))},Lm=e=>ge({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),Gd=e=>QH(e)||/^[A-Za-z]:[\\/]/.test(e),ME=e=>{if(!e.sso)return;let t=Ot(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??Oe();if(!e.bin&&!le())throw new Error("--bin is required because the running binary path is temporary; use a fleet-stable path such as /usr/local/bin/anyray-connect");if(!Gd(n))throw new Error("--bin must be an absolute fleet-stable path");return{sso:`${t.cpOrigin}/sso/${t.tenantId}`,binaryPath:n,gateway:e.gateway,team:e.team}},FE=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${de(e.metadata)??"(none \u2014 pass --team)"}`],Dm=(e,t)=>{try{let{hostname:n}=new URL(e.origin);["localhost","127.0.0.1","::1","0.0.0.0"].includes(n)&&t(`! Gateway is ${e.origin} \u2014 a fleet managed file almost certainly wants your real gateway URL (pass --gateway).`)}catch{}},r1=(e,t)=>({agent_servers:{[jn]:{command:e,args:[cd,"claude",t,"jetbrains"],env:{}},[Vn]:{command:e,args:[cd,"codex",t,"jetbrains"],env:{}}}}),TE=e=>["# Managed by anyray-connect (fleet). Routes shell/SDK traffic through the Anyray gateway.","# Per-user keys come from enrollment (`anyray-connect --enroll/--sso`); never add a key here.",`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,""].join(`
398
- `),o1=e=>{if(e.sso||e.gateway||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool jetbrains takes only --bin and --npx: gateway, attribution, and auth all resolve from each user\u2019s own enrollment at agent launch");if(!e.bin)throw new Error("--bin <absolute path> is required (fleet-stable anyray-connect binary, e.g. /usr/local/bin/anyray-connect)");if(!Gd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");if(!e.npx)throw new Error("--npx <absolute path> is required (fleet-stable npx, e.g. /usr/local/bin/npx) \u2014 a fleet artifact must not absorb the admin machine\u2019s PATH");if(!ud(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return Io(e,`${JSON.stringify(r1(e.bin,e.npx),null,2)}
399
- `),Ce(S("# acp.json for ~/.jetbrains/acp.json (per user).")),Ce(S(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ce(S("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ce(S("# An MDM file drop REPLACES the file \u2014 deploy at provision time, or merge agent_servers in your config tool if devs add their own agents.")),0},a1=e=>{if(e.npx||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool bootstrap takes only --sso, --gateway, and --bin: it carries the enrollment link, never attribution");if(!e.sso)throw new Error("--sso <link> is required: the bootstrap file exists to hand the org SSO link to unenrolled machines");if(e.bin&&!Gd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return Io(e,XS(e.sso,e.gateway,e.bin)),Ce(S(`# Fleet bootstrap for ${Ti("linux")}`)),Ce(S(`# macOS: ${Ti("darwin")}`)),Ce(S(`# Windows: ${Ti("win32",{ProgramData:"C:\\ProgramData"})}`)),Ce(S("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},s1=e=>{if(e.sso||e.bin||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool shell takes only --gateway (or --loopback): the snippet carries base URLs only (keys and attribution ride each user\u2019s enrollment)");if(e.loopback){if(e.gateway)throw new Error("--loopback and --gateway are mutually exclusive: the daemon resolves the real gateway from the fleet bootstrap file");let n=ge({origin:`http://127.0.0.1:${ke}`});return Io(e,TE(n)),Ce(S(`# Loopback shell snippet \u2014 pair with \`managed --tool proxy\` (daemon on :${ke}) and \`--tool bootstrap\`.`)),0}let t=Lm(e);return Io(e,TE(t)),Ce(S("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),Dm(t,Ce),0},i1=e=>{if(e.sso||e.gateway||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session||e.loopback)throw new Error("--tool proxy takes only --bin and --platform: the daemon resolves the gateway and per-user auth at runtime (bootstrap file + profile)");if(!e.bin)throw new Error("--bin <absolute path> is required (fleet-stable anyray-connect binary, e.g. /usr/local/bin/anyray-connect)");if(!Gd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");let t=e.servicePlatform??(Pm()==="darwin"?"launchd":"systemd"),n={command:e.bin,args:[Qu]};return t==="launchd"?(Io(e,gs(n)),Ce(S("# launchd agent \u2014 deploy to /Library/LaunchAgents/ai.anyray.connect.fallback.plist (loads for every user at login)."))):(Io(e,ws(n)),Ce(S("# systemd user unit \u2014 deploy to /etc/systemd/user/anyray-fallback.service, then `systemctl --global enable anyray-fallback.service`."))),Ce(S(`# Pair with \`--tool bootstrap\` (the daemon's fleet boot needs it) and the \`--tool shell --loopback\` snippet (port ${ke}).`)),Ce(S(`# Push the binary to ${e.bin} before this unit.`)),0},c1=e=>{let t=Lm(e),n=ME(e),r=n?Kd(t,n):Kd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(Io(e,`${JSON.stringify(r,null,2)}
400
- `),Ce(S(`# managed-settings.json for ${Dt()}`)),n)Ce(S("# Deferred SSO: hooks only; no credential or managed env block.")),Ce(S(`# Push the binary to ${n.binaryPath} before this file.`)),Ce(S("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of FE(t))Ce(S(`# ${o}`));Dm(t,Ce)}return 0},l1=async e=>{let t=Pm();if(t!=="darwin"&&t!=="linux")return _("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!$E())return _("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),k(S(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=Lm(e),r=ME(e);r||Dm(n,u=>D(u.replace(/^!\s*/,"")));let o=Dt(t),a=await U(o),s=r?Kd(n,r):Kd(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?On.filter(({name:u})=>{let f=a.env?.[u];return typeof f=="string"&&f.trim()!==""}):[],c=t1(a,s),l=await LE(o);await J(o,c);let d=await DE(o,l);F(`Wrote ${o}`),NE(o,d);for(let{name:u,cloud:f}of i)D(`${u} was set in this file and is now pinned empty \u2014 Claude Code no longer talks to ${f} directly. The gateway serves it instead; re-add the key here to undo.`);if(r)k(S(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),k(S(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of FE(n))k(` ${S(u)}`);return k(S(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},d1=async()=>{let e=Pm();if(e!=="darwin"&&e!=="linux")return _("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!$E())return _("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Dt(e);if(!await R(t))return k(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await U(t);if(!n1(n))return k(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await LE(t);await J(t,n);let o=await DE(t,r);return F(`Removed Anyray-owned keys from ${t} (other keys left intact).`),NE(t,o),0},UE=async e=>{let t;try{t=e1(e)}catch(n){return _(n instanceof Error?n.message:"invalid managed arguments"),k(`
401
- `+Tm),1}if(t.help||e.length===0&&!t.mode)return k(Tm),0;if(!t.mode)return _("Specify a mode: --print, --write, or --revert."),k(`
402
- `+Tm),1;if(t.out!==void 0&&t.mode!=="print")return _(`--out is valid with --print only, not --${t.mode}.`),1;if(t.scrubDirectMode){let n=t.sso!==void 0?"--sso emits a hooks-only file with no env block":(t.tool??"claude-code")!=="claude-code"?`--tool ${t.tool} does not write Claude Code env`:t.mode==="revert"?"--revert already removes the pin (and leaves a truthy value alone)":void 0;if(n)return _(`--scrub-direct-mode cannot be combined with this mode: ${n}.`),1}try{let n=t.tool??"claude-code";return n!=="claude-code"?t.mode!=="print"?(_(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?o1(t):n==="bootstrap"?a1(t):n==="proxy"?i1(t):s1(t):t.mode==="print"?c1(t):t.mode==="write"?await l1(t):await d1()}catch(n){return _(n instanceof Error?n.message:"managed settings failed"),1}};var u1=`anyray-connect print-key [--json | --passthrough-headers]
396
+ anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,PE=["claude-code","jetbrains","shell","bootstrap","proxy"],aH=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--print":t.mode="print";break;case"--write":t.mode="write";break;case"--revert":t.mode="revert";break;case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":throw new Error("--key is not valid for managed settings: fleet files never embed credentials; enroll each user instead");case"--scrub-direct-mode":t.scrubDirectMode=!0;break;case"--sso":t.sso=o();break;case"--bin":t.bin=o();break;case"--npx":t.npx=o();break;case"--loopback":t.loopback=!0;break;case"--out":t.out=o();break;case"--platform":{let a=o();if(a!=="launchd"&&a!=="systemd")throw new Error(`unknown --platform ${a} (expected launchd | systemd)`);t.servicePlatform=a;break}case"--tool":{let a=o();if(!PE.includes(a))throw new Error(`unknown --tool ${a} (expected ${PE.join(" | ")}; Codex fleets use \`anyray-connect desktop codex\`)`);t.tool=a;break}case"--subscription":throw new Error("--subscription cannot produce a valid credentialless managed file; use --sso <link> so each user enrolls and receives a personal gateway key");case"--placeholder":case"--org":throw new Error(`${r} is a legacy no-op for managed settings; omit it and enroll each user`);case"--yes":case"-y":break;case"--help":case"-h":t.help=!0;break;default:if(!r.startsWith("-")&&t.gateway===void 0)t.gateway=r;else throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r} (gateway already set to ${t.gateway})`)}}if(t.sso&&!Rt(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function jd(e,t,n={}){if(!t&&e.authMode==="subscription")throw new Error("subscription managed settings require deferred SSO; a seat OAuth token does not replace the required personal gateway key");if(t){let o=["__anyray-sso-gate","--sso",t.sso,...t.gateway?["--gateway",t.gateway]:[],...t.team?["--team",t.team]:[]];return{hooks:{PostToolUse:[_n(ls(t.binaryPath,[Je]),{matcher:"*"})],UserPromptSubmit:[_n(ls(t.binaryPath,o),{timeout:30}),_n(ls(t.binaryPath,[or]))],SessionStart:[_n(ls(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=pn(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(Pn.map(o=>[o.name,""])),...r}}:{env:r}}var sH=(e,t)=>{let n="env"in t||"hooks"in t?t:{env:t},r={...e};e.env&&typeof e.env=="object"&&(r.env={...e.env}),e.hooks&&typeof e.hooks=="object"&&(r.hooks=Object.fromEntries(Object.entries(e.hooks).map(([a,s])=>[a,Array.isArray(s)?[...s]:s])));let o=r.env??{};for(let a of Wr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,Vu(r),n.env&&(r.env={...o,...n.env}),n.hooks){let a=r.hooks??{};for(let[s,i]of Object.entries(n.hooks)){let c=Array.isArray(a[s])?a[s]:[];a[s]=[...c,...i]}r.hooks=a}return r},iH=e=>{let t=e.env,n=Vu(e);if(t){for(let r of Wr)r in t&&(delete t[r],n=!0);for(let{name:r}of Pn)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},DE=async e=>{let t=async n=>{try{return(await rH(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(LE(e))!==void 0}},NE=async(e,t)=>(t.dirExisted||await Tm(LE(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await Tm(e,420),{mode:420,keptRestricted:!1}):(await Tm(e,t.mode),{mode:t.mode,keptRestricted:!0})),$E=(e,t)=>{t.keptRestricted&&(L(`${e} was already restricted to mode ${t.mode.toString(8).padStart(3,"0")} and keeps it \u2014 widening it would expose whatever else that file holds to every local account.`),k(S(" Claude Code reads this file as the developer, so the routing will NOT take effect until it is readable. Move any secret out of it, then `chmod 644` it.")))},ME=()=>process.getuid?.()===0,Ce=e=>{process.stderr.write(`${e}
397
+ `)},Eo=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}nH(e.out,t,"utf8"),Ce(S(`# Wrote ${e.out}`))},Nm=e=>ge({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),Vd=e=>oH(e)||/^[A-Za-z]:[\\/]/.test(e),FE=e=>{if(!e.sso)return;let t=Rt(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??Oe();if(!e.bin&&!le())throw new Error("--bin is required because the running binary path is temporary; use a fleet-stable path such as /usr/local/bin/anyray-connect");if(!Vd(n))throw new Error("--bin must be an absolute fleet-stable path");return{sso:`${t.cpOrigin}/sso/${t.tenantId}`,binaryPath:n,gateway:e.gateway,team:e.team}},UE=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${de(e.metadata)??"(none \u2014 pass --team)"}`],$m=(e,t)=>{try{let{hostname:n}=new URL(e.origin);["localhost","127.0.0.1","::1","0.0.0.0"].includes(n)&&t(`! Gateway is ${e.origin} \u2014 a fleet managed file almost certainly wants your real gateway URL (pass --gateway).`)}catch{}},cH=(e,t)=>({agent_servers:{[Yn]:{command:e,args:[dd,"claude",t,"jetbrains"],env:{}},[Zn]:{command:e,args:[dd,"codex",t,"jetbrains"],env:{}}}}),TE=e=>["# Managed by anyray-connect (fleet). Routes shell/SDK traffic through the Anyray gateway.","# Per-user keys come from enrollment (`anyray-connect --enroll/--sso`); never add a key here.",`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,""].join(`
398
+ `),lH=e=>{if(e.sso||e.gateway||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool jetbrains takes only --bin and --npx: gateway, attribution, and auth all resolve from each user\u2019s own enrollment at agent launch");if(!e.bin)throw new Error("--bin <absolute path> is required (fleet-stable anyray-connect binary, e.g. /usr/local/bin/anyray-connect)");if(!Vd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");if(!e.npx)throw new Error("--npx <absolute path> is required (fleet-stable npx, e.g. /usr/local/bin/npx) \u2014 a fleet artifact must not absorb the admin machine\u2019s PATH");if(!fd(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return Eo(e,`${JSON.stringify(cH(e.bin,e.npx),null,2)}
399
+ `),Ce(S("# acp.json for ~/.jetbrains/acp.json (per user).")),Ce(S(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ce(S("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ce(S("# An MDM file drop REPLACES the file \u2014 deploy at provision time, or merge agent_servers in your config tool if devs add their own agents.")),0},dH=e=>{if(e.npx||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool bootstrap takes only --sso, --gateway, and --bin: it carries the enrollment link, never attribution");if(!e.sso)throw new Error("--sso <link> is required: the bootstrap file exists to hand the org SSO link to unenrolled machines");if(e.bin&&!Vd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return Eo(e,qS(e.sso,e.gateway,e.bin)),Ce(S(`# Fleet bootstrap for ${Li("linux")}`)),Ce(S(`# macOS: ${Li("darwin")}`)),Ce(S(`# Windows: ${Li("win32",{ProgramData:"C:\\ProgramData"})}`)),Ce(S("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},uH=e=>{if(e.sso||e.bin||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool shell takes only --gateway (or --loopback): the snippet carries base URLs only (keys and attribution ride each user\u2019s enrollment)");if(e.loopback){if(e.gateway)throw new Error("--loopback and --gateway are mutually exclusive: the daemon resolves the real gateway from the fleet bootstrap file");let n=ge({origin:`http://127.0.0.1:${ke}`});return Eo(e,TE(n)),Ce(S(`# Loopback shell snippet \u2014 pair with \`managed --tool proxy\` (daemon on :${ke}) and \`--tool bootstrap\`.`)),0}let t=Nm(e);return Eo(e,TE(t)),Ce(S("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),$m(t,Ce),0},pH=e=>{if(e.sso||e.gateway||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session||e.loopback)throw new Error("--tool proxy takes only --bin and --platform: the daemon resolves the gateway and per-user auth at runtime (bootstrap file + profile)");if(!e.bin)throw new Error("--bin <absolute path> is required (fleet-stable anyray-connect binary, e.g. /usr/local/bin/anyray-connect)");if(!Vd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");let t=e.servicePlatform??(Dm()==="darwin"?"launchd":"systemd"),n={command:e.bin,args:[tp]};return t==="launchd"?(Eo(e,bs(n)),Ce(S("# launchd agent \u2014 deploy to /Library/LaunchAgents/ai.anyray.connect.fallback.plist (loads for every user at login)."))):(Eo(e,ks(n)),Ce(S("# systemd user unit \u2014 deploy to /etc/systemd/user/anyray-fallback.service, then `systemctl --global enable anyray-fallback.service`."))),Ce(S(`# Pair with \`--tool bootstrap\` (the daemon's fleet boot needs it) and the \`--tool shell --loopback\` snippet (port ${ke}).`)),Ce(S(`# Push the binary to ${e.bin} before this unit.`)),0},fH=e=>{let t=Nm(e),n=FE(e),r=n?jd(t,n):jd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(Eo(e,`${JSON.stringify(r,null,2)}
400
+ `),Ce(S(`# managed-settings.json for ${Lt()}`)),n)Ce(S("# Deferred SSO: hooks only; no credential or managed env block.")),Ce(S(`# Push the binary to ${n.binaryPath} before this file.`)),Ce(S("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of UE(t))Ce(S(`# ${o}`));$m(t,Ce)}return 0},hH=async e=>{let t=Dm();if(t!=="darwin"&&t!=="linux")return _("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!ME())return _("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),k(S(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=Nm(e),r=FE(e);r||$m(n,u=>L(u.replace(/^!\s*/,"")));let o=Lt(t),a=await U(o),s=r?jd(n,r):jd(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?Pn.filter(({name:u})=>{let f=a.env?.[u];return typeof f=="string"&&f.trim()!==""}):[],c=sH(a,s),l=await DE(o);await X(o,c);let d=await NE(o,l);F(`Wrote ${o}`),$E(o,d);for(let{name:u,cloud:f}of i)L(`${u} was set in this file and is now pinned empty \u2014 Claude Code no longer talks to ${f} directly. The gateway serves it instead; re-add the key here to undo.`);if(r)k(S(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),k(S(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of UE(n))k(` ${S(u)}`);return k(S(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},mH=async()=>{let e=Dm();if(e!=="darwin"&&e!=="linux")return _("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!ME())return _("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Lt(e);if(!await O(t))return k(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await U(t);if(!iH(n))return k(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await DE(t);await X(t,n);let o=await NE(t,r);return F(`Removed Anyray-owned keys from ${t} (other keys left intact).`),$E(t,o),0},BE=async e=>{let t;try{t=aH(e)}catch(n){return _(n instanceof Error?n.message:"invalid managed arguments"),k(`
401
+ `+Lm),1}if(t.help||e.length===0&&!t.mode)return k(Lm),0;if(!t.mode)return _("Specify a mode: --print, --write, or --revert."),k(`
402
+ `+Lm),1;if(t.out!==void 0&&t.mode!=="print")return _(`--out is valid with --print only, not --${t.mode}.`),1;if(t.scrubDirectMode){let n=t.sso!==void 0?"--sso emits a hooks-only file with no env block":(t.tool??"claude-code")!=="claude-code"?`--tool ${t.tool} does not write Claude Code env`:t.mode==="revert"?"--revert already removes the pin (and leaves a truthy value alone)":void 0;if(n)return _(`--scrub-direct-mode cannot be combined with this mode: ${n}.`),1}try{let n=t.tool??"claude-code";return n!=="claude-code"?t.mode!=="print"?(_(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?lH(t):n==="bootstrap"?dH(t):n==="proxy"?pH(t):uH(t):t.mode==="print"?fH(t):t.mode==="write"?await hH(t):await mH()}catch(n){return _(n instanceof Error?n.message:"managed settings failed"),1}};var yH=`anyray-connect print-key [--json | --passthrough-headers]
403
403
 
404
404
  Print the current short-lived Anyray client key for a consuming app.
405
405
 
@@ -411,10 +411,10 @@ Options:
411
411
  "x-anyray-provider":"anthropic","x-anyray-metadata":"..."}).
412
412
  Carries the client key, never the seat OAuth token.
413
413
  --help Show this help.
414
- `,p1=e=>{let t=!1,n=!1,r=!1;for(let o of e)if(o==="--json")t=!0;else if(o==="--passthrough-headers")n=!0;else if(o==="--help"||o==="-h")r=!0;else throw new Error(`Unknown option: ${o}`);if(t&&n)throw new Error("Use only one of --json or --passthrough-headers.");return{json:t,passthroughHeaders:n,help:r}},f1=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=_i(e):!0},BE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},WE=(e,t)=>{if(!xe(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},Nm=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,h1=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Nm(t)}\`.`:"Enrollment certificate expired. Re-run `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"cert-rejected":return t.ssoLink?`Your SSO reconnect credential is no longer valid. Reconnect with \`${Nm(t)}\`.`:"Your enrollment certificate is no longer valid. Reconnect with `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${Nm(t)}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.";case"disabled":return"Automatic key refresh is disabled.";case"backoff":case"throttled":return"Key refresh is temporarily unavailable; retry shortly.";case"not-due":case"repaired":case"cert-renewed":case"heartbeat-refreshed":case"proxy-restored":case"refreshed":return""}},$m=async(e={})=>{let t=e.loadProfile??L,n=e.refreshIfDue??et,r=e.now??Date.now,o=await t();if(BE(o),!o.enrolledCert){if(!WE(o,r))throw new Error("No valid Anyray client key is stored. Set ANYRAY_CLIENT_KEY to a minted ark_ key or enroll this machine.");return{profile:o,token:o.clientKey}}let a;if(!o.clientKey||f1(o,r)){let i=h1(await n(),o);if(i){if(!WE(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(BE(s),!xe(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},HE=e=>de({user:e.name,team:e.team}),m1=({profile:e,token:t})=>{let n={},r=HE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Mm=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=HE(e);return r&&(n["x-anyray-metadata"]=r),n},y1=e=>JSON.stringify(Mm(e)),KE=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=p1(e);if(o.help)return n.write(u1),0;let a=await $m(t);a.warning&&r.write(`${a.warning}
415
- `);let s=o.passthroughHeaders?y1(a):o.json?m1(a):a.token;return n.write(`${s}
414
+ `,gH=e=>{let t=!1,n=!1,r=!1;for(let o of e)if(o==="--json")t=!0;else if(o==="--passthrough-headers")n=!0;else if(o==="--help"||o==="-h")r=!0;else throw new Error(`Unknown option: ${o}`);if(t&&n)throw new Error("Use only one of --json or --passthrough-headers.");return{json:t,passthroughHeaders:n,help:r}},wH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Ti(e):!0},WE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},HE=(e,t)=>{if(!xe(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},Mm=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,bH=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Mm(t)}\`.`:"Enrollment certificate expired. Re-run `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"cert-rejected":return t.ssoLink?`Your SSO reconnect credential is no longer valid. Reconnect with \`${Mm(t)}\`.`:"Your enrollment certificate is no longer valid. Reconnect with `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${Mm(t)}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.";case"disabled":return"Automatic key refresh is disabled.";case"backoff":case"throttled":return"Key refresh is temporarily unavailable; retry shortly.";case"not-due":case"repaired":case"cert-renewed":case"heartbeat-refreshed":case"proxy-restored":case"refreshed":return""}},Fm=async(e={})=>{let t=e.loadProfile??D,n=e.refreshIfDue??tt,r=e.now??Date.now,o=await t();if(WE(o),!o.enrolledCert){if(!HE(o,r))throw new Error("No valid Anyray client key is stored. Set ANYRAY_CLIENT_KEY to a minted ark_ key or enroll this machine.");return{profile:o,token:o.clientKey}}let a;if(!o.clientKey||wH(o,r)){let i=bH(await n(),o);if(i){if(!HE(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(WE(s),!xe(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},KE=e=>de({user:e.name,team:e.team}),kH=({profile:e,token:t})=>{let n={},r=KE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Um=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=KE(e);return r&&(n["x-anyray-metadata"]=r),n},CH=e=>JSON.stringify(Um(e)),GE=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=gH(e);if(o.help)return n.write(yH),0;let a=await Fm(t);a.warning&&r.write(`${a.warning}
415
+ `);let s=o.passthroughHeaders?CH(a):o.json?kH(a):a.token;return n.write(`${s}
416
416
  `),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
417
- `),1}};var GE=`anyray-connect models [<model-id>] [--json]
417
+ `),1}};var jE=`anyray-connect models [<model-id>] [--json]
418
418
 
419
419
  List the Copilot models your seat can run on the Anyray lane, or switch the
420
420
  Copilot CLI's startup model. The CLI's own /models cannot list models on a
@@ -426,8 +426,8 @@ Options:
426
426
  --json Emit {"origin","current","models":[{"id","wire",...caps}]} instead
427
427
  of the table (listing only).
428
428
  --help Show this help.
429
- `,g1=e=>{let t={json:!1,help:!1};for(let n of e)n==="--help"||n==="-h"?t.help=!0:n==="--json"?t.json=!0:n.startsWith("-")?t.error=`unknown option: ${n}`:t.modelId?t.error=`unexpected argument: ${n}`:t.modelId=n;return t},w1=e=>{let t=se.find(n=>n.id===ro);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},b1=e=>{let t=r=>r>=1e3?`${Math.round(r/1e3)}k`:String(r);return[...e.maxPromptTokens?[`${t(e.maxPromptTokens)} in`]:[],...e.maxOutputTokens?[`${t(e.maxOutputTokens)} out`]:[]].join(" / ")},k1=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Zs(t)}/${Nn(n)==="responses"?"responses":"chat/completions"}`,jE=async(e=[],t={})=>{let n=g1(e);if(n.help)return process.stdout.write(GE),0;if(n.error)return _(n.error),process.stdout.write(GE),1;let r=await(t.loadTarget??_e)();if(!r)return _("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??kl)({allowKeychainPrompt:!0});if(!a.token)return _("No Copilot sign-in Connect can read \u2014 run `copilot` once and `/login` (say YES to storing credentials locally), then retry."),1;let s=a.token.token,i=a.capiSegment??"default",c=await(t.fetchCatalog??ra)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=Af(c);if(l.length===0)return _("Could not fetch your seat's model catalog from GitHub (offline, or the sign-in lost its Copilot seat)."),1;if(!n.modelId){let p=process.env.COPILOT_MODEL?.trim();if(n.json)return process.stdout.write(`${JSON.stringify({origin:o.origin,current:p??null,models:l.map(h=>({id:h.id,wire:Nn(h.id),...h.maxPromptTokens?{maxPromptTokens:h.maxPromptTokens}:{},...h.maxOutputTokens?{maxOutputTokens:h.maxOutputTokens}:{}}))})}
430
- `),0;k(j(`Copilot models your seat serves (via ${o.origin})`));for(let h of l){let m=h.id===p?"*":" ",w=b1(h);k(` ${m} ${h.id.padEnd(24)}${w?S(w):""}`)}return M("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),M("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(p=>p.id===n.modelId);if(!d)return _(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??bl)(k1(o,i,d.id),{...Cf(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return _(`GitHub refuses chat as '${d.id}' for this sign-in (it is in the catalog, but chat entitlement is narrower). Pick another id from \`anyray-connect models\`.`),1;u==="unreachable"?D("Could not verify the model over the lane (offline?) \u2014 applying anyway."):F(`'${d.id}' answers on your lane.`);let f=process.env.ANYRAY_COPILOT_MODEL;process.env.ANYRAY_COPILOT_MODEL=d.id;try{let p=await(t.applyCopilotCli??w1)(o);if(p.status!=="configured"){for(let h of p.messages)k(h);return _("Apply did not complete \u2014 see above."),1}}finally{f===void 0?delete process.env.ANYRAY_COPILOT_MODEL:process.env.ANYRAY_COPILOT_MODEL=f}return F(`Copilot CLI startup model \u2192 ${d.id}`),M("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var C1=`anyray-connect copilot-login
429
+ `,AH=e=>{let t={json:!1,help:!1};for(let n of e)n==="--help"||n==="-h"?t.help=!0:n==="--json"?t.json=!0:n.startsWith("-")?t.error=`unknown option: ${n}`:t.modelId?t.error=`unexpected argument: ${n}`:t.modelId=n;return t},vH=e=>{let t=ie.find(n=>n.id===no);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},SH=e=>{let t=r=>r>=1e3?`${Math.round(r/1e3)}k`:String(r);return[...e.maxPromptTokens?[`${t(e.maxPromptTokens)} in`]:[],...e.maxOutputTokens?[`${t(e.maxOutputTokens)} out`]:[]].join(" / ")},EH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Js(t)}/${Mn(n)==="responses"?"responses":"chat/completions"}`,VE=async(e=[],t={})=>{let n=AH(e);if(n.help)return process.stdout.write(jE),0;if(n.error)return _(n.error),process.stdout.write(jE),1;let r=await(t.loadTarget??Re)();if(!r)return _("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??Al)({allowKeychainPrompt:!0});if(!a.token)return _("No Copilot sign-in Connect can read \u2014 run `copilot` once and `/login` (say YES to storing credentials locally), then retry."),1;let s=a.token.token,i=a.capiSegment??"default",c=await(t.fetchCatalog??oa)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=Sf(c);if(l.length===0)return _("Could not fetch your seat's model catalog from GitHub (offline, or the sign-in lost its Copilot seat)."),1;if(!n.modelId){let p=process.env.COPILOT_MODEL?.trim();if(n.json)return process.stdout.write(`${JSON.stringify({origin:o.origin,current:p??null,models:l.map(h=>({id:h.id,wire:Mn(h.id),...h.maxPromptTokens?{maxPromptTokens:h.maxPromptTokens}:{},...h.maxOutputTokens?{maxOutputTokens:h.maxOutputTokens}:{}}))})}
430
+ `),0;k(j(`Copilot models your seat serves (via ${o.origin})`));for(let h of l){let m=h.id===p?"*":" ",w=SH(h);k(` ${m} ${h.id.padEnd(24)}${w?S(w):""}`)}return M("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),M("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(p=>p.id===n.modelId);if(!d)return _(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??Cl)(EH(o,i,d.id),{...vf(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return _(`GitHub refuses chat as '${d.id}' for this sign-in (it is in the catalog, but chat entitlement is narrower). Pick another id from \`anyray-connect models\`.`),1;u==="unreachable"?L("Could not verify the model over the lane (offline?) \u2014 applying anyway."):F(`'${d.id}' answers on your lane.`);let f=process.env.ANYRAY_COPILOT_MODEL;process.env.ANYRAY_COPILOT_MODEL=d.id;try{let p=await(t.applyCopilotCli??vH)(o);if(p.status!=="configured"){for(let h of p.messages)k(h);return _("Apply did not complete \u2014 see above."),1}}finally{f===void 0?delete process.env.ANYRAY_COPILOT_MODEL:process.env.ANYRAY_COPILOT_MODEL=f}return F(`Copilot CLI startup model \u2192 ${d.id}`),M("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var xH=`anyray-connect copilot-login
431
431
 
432
432
  Sign Anyray in to GitHub Copilot (device flow) so the Copilot CLI seat lane
433
433
  can run your plan's current models. Opens no browser for you: it prints a
@@ -435,16 +435,16 @@ code to type at github.com/login/device.
435
435
 
436
436
  Options:
437
437
  --help Show this help.
438
- `,VE=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(C1),0;k(j("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??Mk)();if(!n)return _("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;k(` 1. Open ${tt(n.verificationUri)}`),k(` 2. Enter the code: ${j(n.userCode)}`),M(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??Fk)(n);if(r.status!=="ok")return _(r.status==="denied"?"Sign-in was declined in the browser.":r.status==="expired"?"The code expired before sign-in completed \u2014 run the command again.":"GitHub refused the sign-in. Run the command again."),1;let o=(t.now??(()=>new Date))().toISOString(),a=await(t.save??Uk)(r.token,o);F(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??hf)(r.token);if(s.verdict==="no-copilot")return _("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??_e)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??ra)(r.token,{},s.capiSegment,c);return l.length===0?D("Signed in, but no model list came back \u2014 that is usually this machine or its network, not the sign-in. Continue with `anyray-connect --tools copilot-cli`; it verifies the model with a live check of its own."):F(`${l.length} models available (e.g. ${l[0].id}).`),M("Now run: anyray-connect --tools copilot-cli"),0};var YE=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??L)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=await(e.readState??uE)();return!s||s.expiresAt<=r()?(n.write("No live device token yet \u2014 start the daemon: run `anyray-connect`.\n"),1):(t.write(`${a}/device?dt=${s.token}
439
- `),0)};import{join as rI,dirname as P1}from"node:path";import{mkdir as L1,readFile as Km,rm as oI,writeFile as aI}from"node:fs/promises";import{fstatSync as E1,openSync as I1,statSync as x1}from"node:fs";import{createInterface as R1}from"node:readline/promises";import{ReadStream as O1}from"node:tty";import{execFileSync as ZE}from"node:child_process";import A1 from"node:os";var Fm=e=>{try{return ZE("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},v1=e=>{try{return ZE("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},S1=new Set(["root","unknown","user","admin","administrator","developer","dev","node","ubuntu","debian","ec2-user","vagrant","docker","container","vscode","codespace","devcontainer","runner","builder","jenkins","build","ci"]),Um=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:S1.has(t):!0},JE=()=>{try{return A1.userInfo().username||void 0}catch{return}},XE=()=>Fm("user.name")??Fm("user.email")??JE()??"unknown",zE=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Fm),global:e.globalGitConfig??(t||v1)}},xo=e=>{try{return e()?.trim()||void 0}catch{return}},Bm=(e={})=>{let t=zE(e),n=xo(e.osUsername??JE),r=xo(()=>t.global("user.email"))??xo(()=>t.local("user.email"));return r||(xo(()=>t.global("user.name"))??xo(()=>t.local("user.name"))??n??"unknown")},qE=(e={})=>{let t=Bm(e);if(Um(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=zE(e);return!!(xo(()=>n.global("user.email"))??xo(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var Yt=()=>!!process.stdin.isTTY,_1=()=>{try{let e=E1(0);return e.isCharacterDevice()&&e.rdev===x1("/dev/tty").rdev}catch{return!1}},Wm=()=>{if(_1()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new O1(I1(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},wt=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},QE=async(e,t)=>{let n=t.input??Wm(),r=t.output??process.stdout,o=R1({input:n.stream,output:r});try{return await new Promise((a,s)=>{let i=!1,c=!1,l=d=>{i||(i=!0,d())};o.once("line",()=>{c=!0}),o.once("SIGINT",()=>o.close()),o.once("close",()=>{c||l(()=>s(new wt))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new wt)))})}finally{o.close(),n.close()}},$a=async(e,t={})=>{let n=(await QE(`${e} ${S("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Ma=async(e,t,n={})=>{let r=t?` ${S(`[${t}]`)}`:"";return(await QE(`${e}${r}: `,n)).trim()||t},eI=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return M(`Your name: ${t} ${S("(cached \u2014 pass --user to change)")}`),t;let r=XE();return n||!Yt()?(M(`Your name: ${r} ${S("(auto-detected \u2014 pass --user to change)")}`),r):Ma("? Your name",r)},tI=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return M(`Team: ${t} ${S("(cached \u2014 pass --team to change)")}`),t;if(!(n||!Yt()))return Ma("? Team (optional)")},_r=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return dn(e??n)},nI=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,Fa="claude-desktop",Li=e=>e!=="cursor",Di=(e,t,n)=>Li(e)?n:t,jd=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await vr(e.runReg??Gn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Ht({home:e.home});return await R(s)?{authoritative:!0}:n("no-local-record")}if(t!=="darwin")return n("manual-platform");let r={home:e.home,managedPolicyPaths:e.managedPolicyPaths,readManagedPolicyKeys:e.readManagedPolicyKeys},o=on(r);return await lo(o,r)?n("managed-policy"):(await Aa({home:e.home,readClaudeAppVersion:e.readClaudeAppVersion,readClaudeAppBundle:e.readClaudeAppBundle})).supported?await R(o.journal)?{authoritative:!0}:n("no-local-record"):n("unverified-build")}catch{return n("no-local-record")}},Vd=e=>e.id!==Fa||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",T1={"manual-platform":"Claude Desktop setup is manual on this platform","unverified-build":"this Claude Desktop build's automatic-setup seam is unverified","managed-policy":"Claude Desktop's inference settings are centrally managed on this machine","policy-unreadable":"Claude Desktop's Windows machine-policy ownership could not be read","no-local-record":"connect has no record of configuring Claude Desktop inference on this machine"},Yd=(e,t)=>{if(e==="not-routed")return{headline:"retrieval MCP server registered, but inference is not routed through the gateway \u2014 Claude Desktop model traffic is NOT optimized.",detail:["Fix: fully quit Claude Desktop, then run `anyray-connect desktop` and complete any printed inference steps."]};let n=T1[t.reason??"no-local-record"],r=t.mcpRegistered?`retrieval MCP server registered, but inference routing can't be verified (${n}).`:`inference routing can't be verified (${n}), and the retrieval MCP server is not registered.`;return t.reason==="managed-policy"?{headline:r,detail:["Managed policy is authoritative; Connect will not overwrite or auto-repair it. Update the organization MDM profile or bootstrap service.","Bootstrap changes need no MDM redeployment; Claude applies the refreshed configuration on the next app launch."]}:t.reason==="policy-unreadable"?{headline:r,detail:["Connect could not prove whether HKLM policy is authoritative, so it will not overwrite or auto-repair the per-user route.","Check the organization policy and registry-read permissions, then run `anyray-connect doctor` again."]}:{headline:r,detail:["If Claude Desktop's third-party inference setup was never completed, its traffic bypasses the gateway and is NOT optimized.","Check: Claude Desktop \u2192 Developer \u2192 Configure Third-Party Inference; re-run `anyray-connect desktop` to reprint the steps.",...t.mcpRegistered?[]:["Re-running from a durable install also registers the retrieval MCP server."]]}};var Hm=["claude-code","codex"],D1="anyray-connect print-key",Gm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),N1=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:Qa,authMode:"placeholder",metadata:{}}),jm=e=>rI(e,".claude","settings.json"),$1=async(e,t,n)=>{let r=jm(e),o=await U(r),{env:a}=pn(t,{includeAuthToken:!1,includeClientKey:!1}),s=Gm(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Gr(o)?i.push(`Kept the existing apiKeyHelper in ${r} \u2014 make sure it prints an Anyray client key, or remove it and re-run.`):o.apiKeyHelper=D1,n||await J(r,o,{backup:!1}),i.unshift(`${n?"Would write":"Wrote"} ${r} \u2014 base URL + a PATH-resolved key helper (no credential, no identity).`),{messages:i,changedFiles:n?[]:[r]}},sI=async(e=process.cwd())=>{let t=[],n=jm(e);try{if(await R(n)){let o=await U(n),a=Gm(o.env)?o.env:{};(Hr.some(s=>s in a)||Gr(o))&&t.push(n)}}catch{}let r=Vm(e);try{if(await R(r)){let o=await Km(r,"utf-8");Ap(o)&&t.push(r)}}catch{}return t},M1=async(e,t)=>{let n=jm(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await U(n),o=!1;if(Gm(r.env)){let s={...r.env};for(let i of Hr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Gr(r)&&(delete r.apiKeyHelper,o=!0),!o)return{messages:[`No Anyray keys in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=Object.keys(r).length===0;return t||(a?await oI(n,{force:!0}):await J(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},Vm=e=>rI(e,".codex","config.toml"),F1=async(e,t,n)=>{let r=Vm(e),o=await Km(r,"utf-8").catch(()=>""),a=Gc(o,Is(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await L1(P1(r),{recursive:!0}),await aI(r,a)),{messages:[`${n?"Would write":"Wrote"} ${r} \u2014 gateway provider with command-backed auth (no credential serialized).`,"Codex asks for project-config trust on first launch in a fresh checkout \u2014 that prompt is expected."],changedFiles:n?[]:[r]}},U1=async(e,t)=>{let n=Vm(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Km(n,"utf-8"),o=jc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await oI(n,{force:!0}):await aI(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},iI=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Hm],r=n.filter(s=>!Hm.includes(s));if(r.length>0)return _(`--project supports ${Hm.join(", ")} \u2014 not: ${r.join(", ")}. Other tools keep per-machine state (run anyray-connect without --project there).`),1;let o;if(!e.revert){let s=await L(),i=e.gateway??s.gateway;if(!i)return _("--project needs a gateway: pass --gateway <url>, or run `anyray-connect` once on this machine so it is cached."),1;try{let c=new URL(i.trim());if(c.protocol!=="http:"&&c.protocol!=="https:")throw new Error("not http(s)")}catch{return _(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=N1(Ze(i))}if(k(j(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),K("Project"),k(` Directory: ${t}`),o&&k(` Gateway: ${o.origin}`),k(` Tools: ${n.join(", ")}`),e.revert||(D(`
440
- A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),M(" Each machine still needs `anyray-connect` on PATH and a one-time enrollment (--sso/--enroll); the files carry no credential and no identity.")),!e.yes&&!e.dryRun){if(!Yt())return _(`
441
- Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;let s=e.revert?"remove Anyray project config for":"write committable project config for";if(!await $a(`
438
+ `,YE=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(xH),0;k(j("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??Fk)();if(!n)return _("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;k(` 1. Open ${nt(n.verificationUri)}`),k(` 2. Enter the code: ${j(n.userCode)}`),M(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??Uk)(n);if(r.status!=="ok")return _(r.status==="denied"?"Sign-in was declined in the browser.":r.status==="expired"?"The code expired before sign-in completed \u2014 run the command again.":"GitHub refused the sign-in. Run the command again."),1;let o=(t.now??(()=>new Date))().toISOString(),a=await(t.save??Bk)(r.token,o);F(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??yf)(r.token);if(s.verdict==="no-copilot")return _("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??Re)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??oa)(r.token,{},s.capiSegment,c);return l.length===0?L("Signed in, but no model list came back \u2014 that is usually this machine or its network, not the sign-in. Continue with `anyray-connect --tools copilot-cli`; it verifies the model with a live check of its own."):F(`${l.length} models available (e.g. ${l[0].id}).`),M("Now run: anyray-connect --tools copilot-cli"),0};var ZE=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??D)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=await(e.readState??pE)();return!s||s.expiresAt<=r()?(n.write("No live device token yet \u2014 start the daemon: run `anyray-connect`.\n"),1):(t.write(`${a}/device?dt=${s.token}
439
+ `),0)};import{join as ox,dirname as MH}from"node:path";import{mkdir as FH,readFile as jm,rm as ax,writeFile as sx}from"node:fs/promises";import{fstatSync as _H,openSync as PH,statSync as TH}from"node:fs";import{createInterface as LH}from"node:readline/promises";import{ReadStream as DH}from"node:tty";import{execFileSync as XE}from"node:child_process";import IH from"node:os";var Bm=e=>{try{return XE("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},OH=e=>{try{return XE("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},RH=new Set(["root","unknown","user","admin","administrator","developer","dev","node","ubuntu","debian","ec2-user","vagrant","docker","container","vscode","codespace","devcontainer","runner","builder","jenkins","build","ci"]),Wm=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:RH.has(t):!0},JE=()=>{try{return IH.userInfo().username||void 0}catch{return}},qE=()=>Bm("user.name")??Bm("user.email")??JE()??"unknown",zE=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Bm),global:e.globalGitConfig??(t||OH)}},xo=e=>{try{return e()?.trim()||void 0}catch{return}},Hm=(e={})=>{let t=zE(e),n=xo(e.osUsername??JE),r=xo(()=>t.global("user.email"))??xo(()=>t.local("user.email"));return r||(xo(()=>t.global("user.name"))??xo(()=>t.local("user.name"))??n??"unknown")},QE=(e={})=>{let t=Hm(e);if(Wm(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=zE(e);return!!(xo(()=>n.global("user.email"))??xo(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var Vt=()=>!!process.stdin.isTTY,NH=()=>{try{let e=_H(0);return e.isCharacterDevice()&&e.rdev===TH("/dev/tty").rdev}catch{return!1}},Km=()=>{if(NH()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new DH(PH(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},bt=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},ex=async(e,t)=>{let n=t.input??Km(),r=t.output??process.stdout,o=LH({input:n.stream,output:r});try{return await new Promise((a,s)=>{let i=!1,c=!1,l=d=>{i||(i=!0,d())};o.once("line",()=>{c=!0}),o.once("SIGINT",()=>o.close()),o.once("close",()=>{c||l(()=>s(new bt))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new bt)))})}finally{o.close(),n.close()}},Ma=async(e,t={})=>{let n=(await ex(`${e} ${S("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Fa=async(e,t,n={})=>{let r=t?` ${S(`[${t}]`)}`:"";return(await ex(`${e}${r}: `,n)).trim()||t},tx=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return M(`Your name: ${t} ${S("(cached \u2014 pass --user to change)")}`),t;let r=qE();return n||!Vt()?(M(`Your name: ${r} ${S("(auto-detected \u2014 pass --user to change)")}`),r):Fa("? Your name",r)},nx=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return M(`Team: ${t} ${S("(cached \u2014 pass --team to change)")}`),t;if(!(n||!Vt()))return Fa("? Team (optional)")},Pr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return dn(e??n)},rx=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,Ua="claude-desktop",Ni=e=>e!=="cursor",$i=(e,t,n)=>Ni(e)?n:t,Yd=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await Sr(e.runReg??Vn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Wt({home:e.home});return await O(s)?{authoritative:!0}:n("no-local-record")}if(t!=="darwin")return n("manual-platform");let r={home:e.home,managedPolicyPaths:e.managedPolicyPaths,readManagedPolicyKeys:e.readManagedPolicyKeys},o=on(r);return await co(o,r)?n("managed-policy"):(await va({home:e.home,readClaudeAppVersion:e.readClaudeAppVersion,readClaudeAppBundle:e.readClaudeAppBundle})).supported?await O(o.journal)?{authoritative:!0}:n("no-local-record"):n("unverified-build")}catch{return n("no-local-record")}},Zd=e=>e.id!==Ua||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",$H={"manual-platform":"Claude Desktop setup is manual on this platform","unverified-build":"this Claude Desktop build's automatic-setup seam is unverified","managed-policy":"Claude Desktop's inference settings are centrally managed on this machine","policy-unreadable":"Claude Desktop's Windows machine-policy ownership could not be read","no-local-record":"connect has no record of configuring Claude Desktop inference on this machine"},Xd=(e,t)=>{if(e==="not-routed")return{headline:"retrieval MCP server registered, but inference is not routed through the gateway \u2014 Claude Desktop model traffic is NOT optimized.",detail:["Fix: fully quit Claude Desktop, then run `anyray-connect desktop` and complete any printed inference steps."]};let n=$H[t.reason??"no-local-record"],r=t.mcpRegistered?`retrieval MCP server registered, but inference routing can't be verified (${n}).`:`inference routing can't be verified (${n}), and the retrieval MCP server is not registered.`;return t.reason==="managed-policy"?{headline:r,detail:["Managed policy is authoritative; Connect will not overwrite or auto-repair it. Update the organization MDM profile or bootstrap service.","Bootstrap changes need no MDM redeployment; Claude applies the refreshed configuration on the next app launch."]}:t.reason==="policy-unreadable"?{headline:r,detail:["Connect could not prove whether HKLM policy is authoritative, so it will not overwrite or auto-repair the per-user route.","Check the organization policy and registry-read permissions, then run `anyray-connect doctor` again."]}:{headline:r,detail:["If Claude Desktop's third-party inference setup was never completed, its traffic bypasses the gateway and is NOT optimized.","Check: Claude Desktop \u2192 Developer \u2192 Configure Third-Party Inference; re-run `anyray-connect desktop` to reprint the steps.",...t.mcpRegistered?[]:["Re-running from a durable install also registers the retrieval MCP server."]]}};var Gm=["claude-code","codex"],UH="anyray-connect print-key",Vm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),BH=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:ts,authMode:"placeholder",metadata:{}}),Ym=e=>ox(e,".claude","settings.json"),WH=async(e,t,n)=>{let r=Ym(e),o=await U(r),{env:a}=pn(t,{includeAuthToken:!1,includeClientKey:!1}),s=Vm(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Kr(o)?i.push(`Kept the existing apiKeyHelper in ${r} \u2014 make sure it prints an Anyray client key, or remove it and re-run.`):o.apiKeyHelper=UH,n||await X(r,o,{backup:!1}),i.unshift(`${n?"Would write":"Wrote"} ${r} \u2014 base URL + a PATH-resolved key helper (no credential, no identity).`),{messages:i,changedFiles:n?[]:[r]}},ix=async(e=process.cwd())=>{let t=[],n=Ym(e);try{if(await O(n)){let o=await U(n),a=Vm(o.env)?o.env:{};(Wr.some(s=>s in a)||Kr(o))&&t.push(n)}}catch{}let r=Zm(e);try{if(await O(r)){let o=await jm(r,"utf-8");Sp(o)&&t.push(r)}}catch{}return t},HH=async(e,t)=>{let n=Ym(e);if(!await O(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await U(n),o=!1;if(Vm(r.env)){let s={...r.env};for(let i of Wr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Kr(r)&&(delete r.apiKeyHelper,o=!0),!o)return{messages:[`No Anyray keys in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=Object.keys(r).length===0;return t||(a?await ax(n,{force:!0}):await X(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},Zm=e=>ox(e,".codex","config.toml"),KH=async(e,t,n)=>{let r=Zm(e),o=await jm(r,"utf-8").catch(()=>""),a=jc(o,Os(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await FH(MH(r),{recursive:!0}),await sx(r,a)),{messages:[`${n?"Would write":"Wrote"} ${r} \u2014 gateway provider with command-backed auth (no credential serialized).`,"Codex asks for project-config trust on first launch in a fresh checkout \u2014 that prompt is expected."],changedFiles:n?[]:[r]}},GH=async(e,t)=>{let n=Zm(e);if(!await O(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await jm(n,"utf-8"),o=Vc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await ax(n,{force:!0}):await sx(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},cx=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Gm],r=n.filter(s=>!Gm.includes(s));if(r.length>0)return _(`--project supports ${Gm.join(", ")} \u2014 not: ${r.join(", ")}. Other tools keep per-machine state (run anyray-connect without --project there).`),1;let o;if(!e.revert){let s=await D(),i=e.gateway??s.gateway;if(!i)return _("--project needs a gateway: pass --gateway <url>, or run `anyray-connect` once on this machine so it is cached."),1;try{let c=new URL(i.trim());if(c.protocol!=="http:"&&c.protocol!=="https:")throw new Error("not http(s)")}catch{return _(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=BH(Xe(i))}if(k(j(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),K("Project"),k(` Directory: ${t}`),o&&k(` Gateway: ${o.origin}`),k(` Tools: ${n.join(", ")}`),e.revert||(L(`
440
+ A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),M(" Each machine still needs `anyray-connect` on PATH and a one-time enrollment (--sso/--enroll); the files carry no credential and no identity.")),!e.yes&&!e.dryRun){if(!Vt())return _(`
441
+ Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;let s=e.revert?"remove Anyray project config for":"write committable project config for";if(!await Ma(`
442
442
  ${s} ${n.length} tool(s)?`))return M("Aborted. Nothing changed."),0}e.dryRun&&M(`
443
- Dry run \u2014 no files will be written.`);let a=[];for(let s of n){K(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await $1(t,o,e.dryRun):await F1(t,o,e.dryRun):s==="claude-code"?await M1(t,e.dryRun):await U1(t,e.dryRun);for(let c of i.messages)k(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(K("Next"),e.revert)F(" Project config removed. Commit the change to propagate it.");else{F(" Commit these files to route every checkout of this repo:");for(let s of a)k(` ${s}`);k(S(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as B1}from"node:child_process";var W1="/usr/bin/security",H1=["find-generic-password","-s","Claude Code-credentials","-w"],K1=1e4,G1=64*1024,j1=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,cI="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",V1=(e,t,n)=>new Promise((r,o)=>{B1(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),lI=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Y1=e=>{let t=JSON.parse(e);if(!lI(t)||!lI(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!j1.test(n))throw new Error("unexpected keychain access token");return n},dI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${cI}
444
- `),1;try{let o=await $m(t),a=Mm(o),s=await(t.execSecurity??V1)(W1,[...H1],{encoding:"utf8",timeout:K1,maxBuffer:G1,shell:!1}),i=Y1(s.stdout);return o.warning&&r.write(`${o.warning}
443
+ Dry run \u2014 no files will be written.`);let a=[];for(let s of n){K(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await WH(t,o,e.dryRun):await KH(t,o,e.dryRun):s==="claude-code"?await HH(t,e.dryRun):await GH(t,e.dryRun);for(let c of i.messages)k(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(K("Next"),e.revert)F(" Project config removed. Commit the change to propagate it.");else{F(" Commit these files to route every checkout of this repo:");for(let s of a)k(` ${s}`);k(S(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as jH}from"node:child_process";var VH="/usr/bin/security",YH=["find-generic-password","-s","Claude Code-credentials","-w"],ZH=1e4,XH=64*1024,JH=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,lx="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",qH=(e,t,n)=>new Promise((r,o)=>{jH(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),dx=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zH=e=>{let t=JSON.parse(e);if(!dx(t)||!dx(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!JH.test(n))throw new Error("unexpected keychain access token");return n},ux=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${lx}
444
+ `),1;try{let o=await Fm(t),a=Um(o),s=await(t.execSecurity??qH)(VH,[...YH],{encoding:"utf8",timeout:ZH,maxBuffer:XH,shell:!1}),i=zH(s.stdout);return o.warning&&r.write(`${o.warning}
445
445
  `),n.write(`${JSON.stringify({token:i,headers:a})}
446
- `),0}catch{return r.write(`${cI}
447
- `),1}};import{mkdir as CK,writeFile as AK}from"node:fs/promises";import{dirname as vK}from"node:path";import{Buffer as SK}from"node:buffer";import{constants as uI}from"node:fs";import{access as Z1,chmod as J1,mkdir as X1,open as z1,readFile as q1,realpath as Q1,rm as eK,stat as hI,writeFile as tK}from"node:fs/promises";import{randomUUID as nK}from"node:crypto";import{platform as mI}from"node:os";import{dirname as rK,join as oK,posix as aK,win32 as yI}from"node:path";var Ni="/usr/local/bin/anyray-credential-helper",$i="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Ym="Managed by anyray-connect desktop helper; do not edit.",sK=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
446
+ `),0}catch{return r.write(`${lx}
447
+ `),1}};import{mkdir as xK,writeFile as IK}from"node:fs/promises";import{dirname as OK}from"node:path";import{Buffer as RK}from"node:buffer";import{constants as px}from"node:fs";import{access as QH,chmod as eK,mkdir as tK,open as nK,readFile as rK,realpath as oK,rm as aK,stat as mx,writeFile as sK}from"node:fs/promises";import{randomUUID as iK}from"node:crypto";import{platform as yx}from"node:os";import{dirname as cK,join as lK,posix as dK,win32 as gx}from"node:path";var Mi="/usr/local/bin/anyray-credential-helper",Fi="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Xm="Managed by anyray-connect desktop helper; do not edit.",uK=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
448
448
 
449
449
  Create the credential helper required by Claude Desktop and Codex fleet
450
450
  artifacts. The helper stores no key. It invokes a durable anyray-connect binary
@@ -461,8 +461,8 @@ Required:
461
461
  Options:
462
462
  --platform <target> posix or windows (default: current host).
463
463
  --path <absolute> Helper destination. Defaults by target:
464
- ${Ni}
465
- ${$i}
464
+ ${Mi}
465
+ ${Fi}
466
466
  --help,-h Show this help.
467
467
 
468
468
  Examples:
@@ -474,13 +474,13 @@ Examples:
474
474
 
475
475
  anyray-connect desktop helper --print --platform posix \\
476
476
  --bin /usr/local/bin/anyray-connect > anyray-credential-helper
477
- `,pI=(e=mI())=>e==="win32"?"windows":"posix",iK=e=>e==="windows"?$i:Ni,fI=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},cK=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--write":fI(t,"write");break;case"--print":fI(t,"print");break;case"--bin":t.binaryPath=o();break;case"--path":t.helperPath=o();break;case"--platform":{let a=o();if(a!=="posix"&&a!=="windows")throw new Error("--platform must be posix or windows");t.targetPlatform=a;break}case"--help":case"-h":t.help=!0;break;default:throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r}`)}}return t},lK=e=>/[\0\r\n]/.test(e),dK=e=>/^[A-Za-z]:[\\/]/.test(e)&&yI.isAbsolute(e),Mi=(e,t)=>!lK(e)&&(t==="windows"?dK(e):aK.isAbsolute(e)),Zm=e=>e.replace(/\\/g,"/").toLowerCase(),gI=(e,t)=>{if(!Mi(e,t))return!1;let n=Zm(e);return!(/(^|\/)_npx(\/|$)/.test(n)||n==="/tmp"||n.startsWith("/tmp/")||n==="/private/tmp"||n.startsWith("/private/tmp/")||n==="/var/tmp"||n.startsWith("/var/tmp/")||n.startsWith("/var/folders/")||n.startsWith("/private/var/folders/")||/\/appdata\/local\/temp(\/|$)/.test(n)||t==="windows"&&(/[%!^&|<>()"]/.test(e)||!/\.exe$/i.test(e)))},Jm=(e,t)=>t==="windows"?yI.normalize(e):e,uK=e=>`'${e.replace(/'/g,`'"'"'`)}'`,pK=(e,t)=>{if(!gI(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Jm(t,e);if(e==="windows")return["@echo off",`REM ${Ym}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" print-key --json`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
478
- `);let r=uK(n);return["#!/bin/sh",`# ${Ym}`,'if [ "$#" -eq 0 ]; then',` exec ${r} print-key --json`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
479
- `)},Zd=(e,t)=>{if(!Mi(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Jm(t,e);if(e==="windows"){if(/[%!^&|<>()"]/.test(n)||!/\.cmd$/i.test(n))throw new Error("Windows --helper-path must be a safe absolute .cmd path without batch metacharacters");return{command:"C:\\Windows\\System32\\cmd.exe",args:["/d","/s","/c",`call "${n}" --token`]}}return{command:n,args:["--token"]}},fK=async e=>{try{return await q1(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},hK=async(e,t)=>{try{let n=await Q1(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!gI(r,t))throw new Error;if(!(await hI(n)).isFile())throw new Error;await Z1(n,t==="posix"?uI.X_OK:uI.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},mK=e=>e.slice(0,300).includes(Ym),yK=async(e,t,n)=>{let r=await fK(e);if(r!==void 0&&r!==t&&!mK(r))throw new Error(`refusing to replace non-Anyray file at ${e}; choose another --path`);if(r===t){if(n==="windows")return"unchanged";try{if(((await hI(e)).mode&511)===493)return"unchanged"}catch{}}let o=rK(e);try{await X1(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=oK(o,`.anyray-credential-helper.${process.pid}.${nK()}.tmp`),s=!1;try{await tK(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await J1(a,493);let i=await z1(a,"r");try{await es(i)}finally{await i.close()}await he(a,e),s=!0}catch{throw new Error(`could not install credential helper at ${e}`)}finally{s||await eK(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},wI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=cK(e);if(o.help)return n.write(sK),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");let a=(t.platform??mI)(),s=o.targetPlatform??pI(a),i=Jm(o.helperPath??iK(s),s);if(!Mi(i,s))throw new Error(`--path must be an absolute ${s} path`);if(s==="windows"&&Zd("windows",i),Zm(i)===Zm(o.binaryPath))throw new Error("--path must differ from --bin (the helper cannot invoke itself)");let c=pK(s,o.binaryPath);if(o.mode==="print")return n.write(c),r.write(`Deploy this wrapper at ${i} after deploying the binary at ${o.binaryPath}.
480
- `),0;if(s!==pI(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await hK(o.binaryPath,s);let l=await yK(i,c,s);return r.write(l==="unchanged"?`Credential helper already current at ${i}.
477
+ `,fx=(e=yx())=>e==="win32"?"windows":"posix",pK=e=>e==="windows"?Fi:Mi,hx=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},fK=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--write":hx(t,"write");break;case"--print":hx(t,"print");break;case"--bin":t.binaryPath=o();break;case"--path":t.helperPath=o();break;case"--platform":{let a=o();if(a!=="posix"&&a!=="windows")throw new Error("--platform must be posix or windows");t.targetPlatform=a;break}case"--help":case"-h":t.help=!0;break;default:throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r}`)}}return t},hK=e=>/[\0\r\n]/.test(e),mK=e=>/^[A-Za-z]:[\\/]/.test(e)&&gx.isAbsolute(e),Ui=(e,t)=>!hK(e)&&(t==="windows"?mK(e):dK.isAbsolute(e)),Jm=e=>e.replace(/\\/g,"/").toLowerCase(),wx=(e,t)=>{if(!Ui(e,t))return!1;let n=Jm(e);return!(/(^|\/)_npx(\/|$)/.test(n)||n==="/tmp"||n.startsWith("/tmp/")||n==="/private/tmp"||n.startsWith("/private/tmp/")||n==="/var/tmp"||n.startsWith("/var/tmp/")||n.startsWith("/var/folders/")||n.startsWith("/private/var/folders/")||/\/appdata\/local\/temp(\/|$)/.test(n)||t==="windows"&&(/[%!^&|<>()"]/.test(e)||!/\.exe$/i.test(e)))},qm=(e,t)=>t==="windows"?gx.normalize(e):e,yK=e=>`'${e.replace(/'/g,`'"'"'`)}'`,gK=(e,t)=>{if(!wx(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=qm(t,e);if(e==="windows")return["@echo off",`REM ${Xm}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" print-key --json`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
478
+ `);let r=yK(n);return["#!/bin/sh",`# ${Xm}`,'if [ "$#" -eq 0 ]; then',` exec ${r} print-key --json`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
479
+ `)},Jd=(e,t)=>{if(!Ui(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=qm(t,e);if(e==="windows"){if(/[%!^&|<>()"]/.test(n)||!/\.cmd$/i.test(n))throw new Error("Windows --helper-path must be a safe absolute .cmd path without batch metacharacters");return{command:"C:\\Windows\\System32\\cmd.exe",args:["/d","/s","/c",`call "${n}" --token`]}}return{command:n,args:["--token"]}},wK=async e=>{try{return await rK(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},bK=async(e,t)=>{try{let n=await oK(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!wx(r,t))throw new Error;if(!(await mx(n)).isFile())throw new Error;await QH(n,t==="posix"?px.X_OK:px.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},kK=e=>e.slice(0,300).includes(Xm),CK=async(e,t,n)=>{let r=await wK(e);if(r!==void 0&&r!==t&&!kK(r))throw new Error(`refusing to replace non-Anyray file at ${e}; choose another --path`);if(r===t){if(n==="windows")return"unchanged";try{if(((await mx(e)).mode&511)===493)return"unchanged"}catch{}}let o=cK(e);try{await tK(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=lK(o,`.anyray-credential-helper.${process.pid}.${iK()}.tmp`),s=!1;try{await sK(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await eK(a,493);let i=await nK(a,"r");try{await ns(i)}finally{await i.close()}await he(a,e),s=!0}catch{throw new Error(`could not install credential helper at ${e}`)}finally{s||await aK(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},bx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=fK(e);if(o.help)return n.write(uK),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");let a=(t.platform??yx)(),s=o.targetPlatform??fx(a),i=qm(o.helperPath??pK(s),s);if(!Ui(i,s))throw new Error(`--path must be an absolute ${s} path`);if(s==="windows"&&Jd("windows",i),Jm(i)===Jm(o.binaryPath))throw new Error("--path must differ from --bin (the helper cannot invoke itself)");let c=gK(s,o.binaryPath);if(o.mode==="print")return n.write(c),r.write(`Deploy this wrapper at ${i} after deploying the binary at ${o.binaryPath}.
480
+ `),0;if(s!==fx(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await bK(o.binaryPath,s);let l=await CK(i,c,s);return r.write(l==="unchanged"?`Credential helper already current at ${i}.
481
481
  `:`${l==="installed"?"Installed":"Updated"} credential helper at ${i}.
482
482
  `),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
483
- `),1}};var gK=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),wK=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,bK=e=>{let t=e.toLowerCase();return t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),t.endsWith(".")&&(t=t.slice(0,-1)),t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")},kK=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Jd=(e,t)=>{let n;try{n=new URL(e)}catch{throw new Error(`${t} must be a valid HTTPS URL.`)}if(n.protocol!=="https:"||n.username!==""||n.password!==""||n.hash!==""||bK(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ua=(e,t,n)=>{if(!(e===void 0&&!n)){if(typeof e!="string"||e.trim()==="")throw new Error(`--bootstrap-oidc ${t} must be a non-empty string.`);return e.trim()}},bI=e=>{if(!kK(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!gK.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ua(e.clientId,"clientId",!0),r=Ua(e.scopes,"scopes",!0),o=Ua(e.issuer,"issuer",!1),a=Ua(e.authorizationUrl,"authorizationUrl",!1),s=Ua(e.tokenUrl,"tokenUrl",!1),i=Ua(e.additionalRedirectReferrerHosts,"additionalRedirectReferrerHosts",!1);if(!o&&!(a&&s))throw new Error("--bootstrap-oidc requires issuer, or both authorizationUrl and tokenUrl.");let c=e.redirectPort;if(c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<1||c>65535))throw new Error("--bootstrap-oidc redirectPort must be an integer from 1 to 65535.");return{clientId:n,scopes:r,...o?{issuer:Jd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Jd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Jd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},kI=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return bI(t)},Xm=e=>{let t=Jd(e.url,"--bootstrap-url"),n=e.oidc?bI(e.oidc):void 0,r;if(e.deploymentOrganizationUuid!==void 0&&(r=e.deploymentOrganizationUuid.trim(),!wK.test(r)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:t,...n?{bootstrapOidc:n}:{},...r?{deploymentOrganizationUuid:r}:{}}},zm=e=>la(Xm(e));var EK=`anyray-connect desktop [disconnect] [options]
483
+ `),1}};var AK=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),vK=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,SK=e=>{let t=e.toLowerCase();return t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),t.endsWith(".")&&(t=t.slice(0,-1)),t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")},EK=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qd=(e,t)=>{let n;try{n=new URL(e)}catch{throw new Error(`${t} must be a valid HTTPS URL.`)}if(n.protocol!=="https:"||n.username!==""||n.password!==""||n.hash!==""||SK(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ba=(e,t,n)=>{if(!(e===void 0&&!n)){if(typeof e!="string"||e.trim()==="")throw new Error(`--bootstrap-oidc ${t} must be a non-empty string.`);return e.trim()}},kx=e=>{if(!EK(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!AK.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ba(e.clientId,"clientId",!0),r=Ba(e.scopes,"scopes",!0),o=Ba(e.issuer,"issuer",!1),a=Ba(e.authorizationUrl,"authorizationUrl",!1),s=Ba(e.tokenUrl,"tokenUrl",!1),i=Ba(e.additionalRedirectReferrerHosts,"additionalRedirectReferrerHosts",!1);if(!o&&!(a&&s))throw new Error("--bootstrap-oidc requires issuer, or both authorizationUrl and tokenUrl.");let c=e.redirectPort;if(c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<1||c>65535))throw new Error("--bootstrap-oidc redirectPort must be an integer from 1 to 65535.");return{clientId:n,scopes:r,...o?{issuer:qd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:qd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:qd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},Cx=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return kx(t)},zm=e=>{let t=qd(e.url,"--bootstrap-url"),n=e.oidc?kx(e.oidc):void 0,r;if(e.deploymentOrganizationUuid!==void 0&&(r=e.deploymentOrganizationUuid.trim(),!vK.test(r)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:t,...n?{bootstrapOidc:n}:{},...r?{deploymentOrganizationUuid:r}:{}}},Qm=e=>da(zm(e));var _K=`anyray-connect desktop [disconnect] [options]
484
484
 
485
485
  The minimum Claude Desktop workflow:
486
486
  anyray-connect desktop Connect this machine
@@ -522,8 +522,8 @@ Options:
522
522
 
523
523
  Older flag-based Claude artifacts and Codex fleet output remain accepted for
524
524
  compatibility, but are not part of the recommended Claude Desktop workflow.
525
- `,IK=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",xK=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),RK=e=>{if(e[0]!=="fleet")return e;if(e.includes("--help")||e.includes("-h"))return["--help"];let t=e[1];if(t!=="bootstrap"&&t!=="static")throw new Error("desktop fleet requires bootstrap or static.");let n=e[2];if(n!=="macos"&&n!=="windows"&&n!=="linux")throw new Error("desktop fleet target must be macos, windows, or linux.");let r=e[3];if(!r||r.startsWith("-"))throw new Error(t==="bootstrap"?"desktop fleet bootstrap requires an HTTPS URL.":"desktop fleet static requires an absolute credential-helper path.");let o=e.slice(4),a=o[0]&&!o[0].startsWith("-")?o.shift():void 0;return[IK(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...xK(o)]},OK=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),qm=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>OK.has(r))||t.includes("--apply")&&t.includes("--revert")||n==="disconnect"&&t.includes("--apply")))return n==="disconnect"&&(t=["--revert",...t.slice(1)]),t=t.filter(r=>r!=="--apply"),[...t,"--tools","claude-desktop"]},zn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),CI=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),_K=(e,t)=>` <key>${zn(e)}</key>
526
- <string>${zn(t)}</string>`,Qm=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>_K(i,c)).join(`
525
+ `,PK=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",TK=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),LK=e=>{if(e[0]!=="fleet")return e;if(e.includes("--help")||e.includes("-h"))return["--help"];let t=e[1];if(t!=="bootstrap"&&t!=="static")throw new Error("desktop fleet requires bootstrap or static.");let n=e[2];if(n!=="macos"&&n!=="windows"&&n!=="linux")throw new Error("desktop fleet target must be macos, windows, or linux.");let r=e[3];if(!r||r.startsWith("-"))throw new Error(t==="bootstrap"?"desktop fleet bootstrap requires an HTTPS URL.":"desktop fleet static requires an absolute credential-helper path.");let o=e.slice(4),a=o[0]&&!o[0].startsWith("-")?o.shift():void 0;return[PK(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...TK(o)]},DK=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),ey=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>DK.has(r))||t.includes("--apply")&&t.includes("--revert")||n==="disconnect"&&t.includes("--apply")))return n==="disconnect"&&(t=["--revert",...t.slice(1)]),t=t.filter(r=>r!=="--apply"),[...t,"--tools","claude-desktop"]},Qn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),Ax=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),NK=(e,t)=>` <key>${Qn(e)}</key>
526
+ <string>${Qn(t)}</string>`,ty=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>NK(i,c)).join(`
527
527
  `);return`<?xml version="1.0" encoding="UTF-8"?>
528
528
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
529
529
  <plist version="1.0">
@@ -532,15 +532,15 @@ compatibility, but are not part of the recommended Claude Desktop workflow.
532
532
  <array>
533
533
  <dict>
534
534
  <key>PayloadType</key>
535
- <string>${zn(e)}</string>
535
+ <string>${Qn(e)}</string>
536
536
  <key>PayloadVersion</key>
537
537
  <integer>1</integer>
538
538
  <key>PayloadIdentifier</key>
539
- <string>${zn(t)}.payload</string>
539
+ <string>${Qn(t)}.payload</string>
540
540
  <key>PayloadUUID</key>
541
- <string>${zn(o)}</string>
541
+ <string>${Qn(o)}</string>
542
542
  <key>PayloadDisplayName</key>
543
- <string>${zn(n)}</string>
543
+ <string>${Qn(n)}</string>
544
544
  ${s}
545
545
  </dict>
546
546
  </array>
@@ -549,27 +549,27 @@ ${s}
549
549
  <key>PayloadVersion</key>
550
550
  <integer>1</integer>
551
551
  <key>PayloadIdentifier</key>
552
- <string>${zn(t)}</string>
552
+ <string>${Qn(t)}</string>
553
553
  <key>PayloadUUID</key>
554
- <string>${zn(r)}</string>
554
+ <string>${Qn(r)}</string>
555
555
  <key>PayloadDisplayName</key>
556
- <string>${zn(n)}</string>
556
+ <string>${Qn(n)}</string>
557
557
  </dict>
558
558
  </plist>
559
- `},vI=(e,t)=>Qm("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",la(co(e,t))),TK=(e,t)=>`${JSON.stringify(co(e,t),null,2)}
560
- `,PK=e=>Qm("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",zm(e)),LK=e=>`${JSON.stringify(Xm(e),null,2)}
561
- `,SI=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries(e).map(([n,r])=>`"${CI(n)}"="${CI(r)}"`),""].join(`
562
- `),EI=(e,t)=>{let n=Zl(e,t);return SI(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},DK=e=>SI(zm(e)),II=(e,t,n)=>{if(t==="darwin"){let r=Ni;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:vI(e,r),helperPath:r}}if(t==="win32"){let r=$i;return{path:`${n}\\claude-desktop-anyray.reg`,content:EI(e,r),helperPath:r}}},xI=(e,t)=>[`Generated the complete Claude Desktop profile your administrator can deploy: ${e.path}`,t==="darwin"?"Send it to IT to push through MDM (Jamf, Intune, Kandji). It carries the full Anyray connection \u2014 no hand-merging, and no Developer Mode on the target machines.":"Send it to IT to import into machine policy (HKLM\\SOFTWARE\\Policies\\Claude), or push it through your device-management system.",`It references the shared credential helper at ${e.helperPath}, which IT deploys once per machine with \`anyray-connect desktop helper --write\`. The profile contains no credential.`,"Nothing on this machine changed; the managed policy stays authoritative until IT deploys it."],NK=(e,t)=>{if(e.authMode==="subscription")throw new Error("Codex subscription managed config is not supported: ChatGPT OAuth still requires a personal gateway key in x-anyray-api-key; run per-user Connect enrollment instead");let n=/^[A-Za-z]:[\\/]/.test(t)?"windows":"posix",r=Zd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${Is(e,o).join(`
559
+ `},Sx=(e,t)=>ty("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",da(io(e,t))),$K=(e,t)=>`${JSON.stringify(io(e,t),null,2)}
560
+ `,MK=e=>ty("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",Qm(e)),FK=e=>`${JSON.stringify(zm(e),null,2)}
561
+ `,Ex=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries(e).map(([n,r])=>`"${Ax(n)}"="${Ax(r)}"`),""].join(`
562
+ `),xx=(e,t)=>{let n=Jl(e,t);return Ex(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},UK=e=>Ex(Qm(e)),Ix=(e,t,n)=>{if(t==="darwin"){let r=Mi;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:Sx(e,r),helperPath:r}}if(t==="win32"){let r=Fi;return{path:`${n}\\claude-desktop-anyray.reg`,content:xx(e,r),helperPath:r}}},Ox=(e,t)=>[`Generated the complete Claude Desktop profile your administrator can deploy: ${e.path}`,t==="darwin"?"Send it to IT to push through MDM (Jamf, Intune, Kandji). It carries the full Anyray connection \u2014 no hand-merging, and no Developer Mode on the target machines.":"Send it to IT to import into machine policy (HKLM\\SOFTWARE\\Policies\\Claude), or push it through your device-management system.",`It references the shared credential helper at ${e.helperPath}, which IT deploys once per machine with \`anyray-connect desktop helper --write\`. The profile contains no credential.`,"Nothing on this machine changed; the managed policy stays authoritative until IT deploys it."],BK=(e,t)=>{if(e.authMode==="subscription")throw new Error("Codex subscription managed config is not supported: ChatGPT OAuth still requires a personal gateway key in x-anyray-api-key; run per-user Connect enrollment instead");let n=/^[A-Za-z]:[\\/]/.test(t)?"windows":"posix",r=Jd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${Os(e,o).join(`
563
563
  `)}
564
- `},$K=e=>Qm("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:SK.from(e,"utf-8").toString("base64")}),MK=e=>{let t={target:e[0]==="codex"?"codex":"claude",migrate:!1,allAccounts:!1,help:!1},n=e[0]==="codex"||e[0]==="claude"?1:0,r=()=>e[++n],o=()=>{let a=e[n+1];if(a&&!a.startsWith("-"))return n++,a};for(;n<e.length;n++){let a=e[n];switch(a){case"--mobileconfig":t.artifact="mobileconfig",t.path=o();break;case"--reg":t.artifact="reg",t.path=o();break;case"--json":t.artifact="json",t.path=o();break;case"--migrate":t.migrate=!0;break;case"--account":t.account=r();break;case"--all-accounts":t.allAccounts=!0;break;case"--gateway":t.gateway=r();break;case"--helper-path":t.helperPath=r()??"";break;case"--bootstrap-url":t.bootstrapUrl=r()??"";break;case"--bootstrap-oidc":t.bootstrapOidc=r()??"";break;case"--deployment-organization-uuid":t.deploymentOrganizationUuid=r()??"";break;case"--team":t.team=r();break;case"--intent":t.intent=r();break;case"--intent-label":t.intentLabel=r();break;case"--subscription":throw new Error("--subscription cannot produce a valid credentialless Codex fleet artifact; run normal per-user Connect enrollment so x-anyray-api-key is available");case"--placeholder":case"--org":throw new Error(`${a} is a legacy no-op for Codex fleet artifacts; omit it and enroll each user`);case"--help":case"-h":t.help=!0;break;default:throw new Error(a.startsWith("-")?`unknown option: ${a}`:`unexpected argument: ${a}`)}}return t},FK=e=>{if(!e.gateway?.trim())throw new Error("--gateway is required for static fleet artifacts; local profile and environment values are intentionally ignored.");let t=dn(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:Qa,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},AI=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??CK,o=n.writeFile??AK;await r(vK(t),{recursive:!0}),await o(t,e)},UK=(e,t,n,r,o)=>{o.write(`This artifact requires the credential helper at ${n}; the artifact does not install or update it. Deploy a stable anyray-connect binary through your software-distribution system first, then install/package the helper with:
564
+ `},WK=e=>ty("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:RK.from(e,"utf-8").toString("base64")}),HK=e=>{let t={target:e[0]==="codex"?"codex":"claude",migrate:!1,allAccounts:!1,help:!1},n=e[0]==="codex"||e[0]==="claude"?1:0,r=()=>e[++n],o=()=>{let a=e[n+1];if(a&&!a.startsWith("-"))return n++,a};for(;n<e.length;n++){let a=e[n];switch(a){case"--mobileconfig":t.artifact="mobileconfig",t.path=o();break;case"--reg":t.artifact="reg",t.path=o();break;case"--json":t.artifact="json",t.path=o();break;case"--migrate":t.migrate=!0;break;case"--account":t.account=r();break;case"--all-accounts":t.allAccounts=!0;break;case"--gateway":t.gateway=r();break;case"--helper-path":t.helperPath=r()??"";break;case"--bootstrap-url":t.bootstrapUrl=r()??"";break;case"--bootstrap-oidc":t.bootstrapOidc=r()??"";break;case"--deployment-organization-uuid":t.deploymentOrganizationUuid=r()??"";break;case"--team":t.team=r();break;case"--intent":t.intent=r();break;case"--intent-label":t.intentLabel=r();break;case"--subscription":throw new Error("--subscription cannot produce a valid credentialless Codex fleet artifact; run normal per-user Connect enrollment so x-anyray-api-key is available");case"--placeholder":case"--org":throw new Error(`${a} is a legacy no-op for Codex fleet artifacts; omit it and enroll each user`);case"--help":case"-h":t.help=!0;break;default:throw new Error(a.startsWith("-")?`unknown option: ${a}`:`unexpected argument: ${a}`)}}return t},KK=e=>{if(!e.gateway?.trim())throw new Error("--gateway is required for static fleet artifacts; local profile and environment values are intentionally ignored.");let t=dn(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:ts,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},vx=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??xK,o=n.writeFile??IK;await r(OK(t),{recursive:!0}),await o(t,e)},GK=(e,t,n,r,o)=>{o.write(`This artifact requires the credential helper at ${n}; the artifact does not install or update it. Deploy a stable anyray-connect binary through your software-distribution system first, then install/package the helper with:
565
565
  `),o.write(r==="windows"?` anyray-connect desktop helper --write --platform windows --bin "C:\\Program Files\\Anyray\\anyray-connect.exe" --path "${n}"
566
566
  `:` sudo anyray-connect desktop helper --write --platform posix --bin /usr/local/bin/anyray-connect --path '${n.replace(/'/g,`'"'"'`)}'
567
567
  `),e==="codex"?o.write(`Non-MDM Codex fleets can place this TOML at /etc/codex/managed_config.toml on Unix or %ProgramData%\\OpenAI\\Codex\\managed_config.toml on Windows.
568
568
  `):t==="json"&&o.write(`Deploy this file to /etc/claude-desktop/managed-settings.json.
569
- `)},BK=e=>{e.write(`This artifact is a stable MDM trust anchor; it contains no inference credential. Claude Desktop authenticates the user and fetches the effective configuration from the bootstrap service at launch.
569
+ `)},jK=e=>{e.write(`This artifact is a stable MDM trust anchor; it contains no inference credential. Claude Desktop authenticates the user and fetches the effective configuration from the bootstrap service at launch.
570
570
  `),e.write(`Update the bootstrap response instead of redeploying MDM. Claude polls every 30 minutes, then applies changed values on the next Claude Desktop launch; no managed action is required for each policy update.
571
571
  `),e.write(`Each bootstrap response replaces the allowed managed configuration; omitted keys are unset.
572
- `)},WK=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??fo)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
572
+ `)},VK=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??po)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
573
573
  ${o.remedy}
574
574
  `),1;let a=o.lanes.reduce((c,l)=>c+l.migrated,0),s=o.portableAssets.reduce((c,l)=>c+l.migrated,0),i={code:"Claude Code sessions",cowork:"Cowork tasks"};for(let c of o.lanes){let l=[c.alreadyPresent>0?`${c.alreadyPresent} already there`:"",c.skippedNoTranscript>0?`${c.skippedNoTranscript} skipped, transcript no longer on disk`:"",c.failed>0?`${c.failed} failed`:""].filter(Boolean);n.write(` ${i[c.lane]}: ${c.migrated} migrated`+(l.length>0?` (${l.join("; ")})`:"")+`
575
575
  `)}for(let c of o.portableAssets){let l=c.migrated+c.alreadyPresent,d=c.conflicts+c.invalid+c.failed;if(l+d===0)continue;let u=c.kind==="skill"?"User-created skills":c.kind==="plugin"?"User-installed plugins":"Local MCP servers";n.write(` ${u}: ${c.migrated} migrated`+(c.alreadyPresent>0?` (${c.alreadyPresent} already there)`:"")+(d>0?` (${d} preserved or skipped)`:"")+`
@@ -580,10 +580,10 @@ Reopen Claude Desktop \u2014 migrated ${c} available in the Anyray profile.
580
580
  Your previous profile is untouched, so \`desktop disconnect\` still works.
581
581
  `)}else n.write(`
582
582
  Nothing new to migrate \u2014 no local sessions or portable local data needed copying.
583
- `);return n.write(" claude.ai chats live on your account, not this machine: bring those\n over with `anyray-connect history restore <export.zip>`.\n"),0},RI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=RK(e);if(o[0]==="helper")return wI(o.slice(1),t);let a=MK(o);if(a.help)return n.write(EK),0;let s=a.bootstrapUrl!==void 0||a.bootstrapOidc!==void 0||a.deploymentOrganizationUuid!==void 0;if(s){if(a.target!=="claude")throw new Error("--bootstrap-url is for Claude Desktop only.");if(a.migrate)throw new Error("Bootstrap options emit an MDM artifact; they cannot be combined with --migrate.");if(!a.artifact)throw new Error("--bootstrap-url requires --mobileconfig, --reg or --json to emit the trust anchor.");if(a.bootstrapUrl===void 0){let u=a.bootstrapOidc!==void 0?"--bootstrap-oidc":"--deployment-organization-uuid";throw new Error(`${u} requires --bootstrap-url.`)}if(a.helperPath!==void 0)throw new Error("--bootstrap-url cannot be combined with --helper-path; the bootstrap response supplies the effective inference configuration.");if(a.gateway!==void 0)throw new Error("--bootstrap-url cannot be combined with --gateway; return the inference gateway URL from the bootstrap response.");if(a.team!==void 0||a.intent!==void 0||a.intentLabel!==void 0)throw new Error("--bootstrap-url cannot be combined with --team or --intent flags; return per-user attribution from the bootstrap response.")}if(a.migrate){if(a.artifact)throw new Error("--migrate moves this machine's own sessions; drop --reg/--mobileconfig.");if(a.target==="codex")throw new Error("`desktop --migrate` applies only to Claude Desktop.");return await WK(a,t)}if(a.target==="codex"&&a.artifact==="reg")throw new Error("Codex fleet config does not use a Windows .reg file.");if(a.target==="codex"&&a.artifact==="json")throw new Error("Codex fleet config is managed_config.toml, not Claude's Linux managed-settings.json.");if(a.target==="claude"&&!a.artifact)throw new Error("Local Claude Desktop connect/disconnect is owned by the main Connect lifecycle.");if(s){let u={url:a.bootstrapUrl,...a.bootstrapOidc===void 0?{}:{oidc:kI(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?DK(u):a.artifact==="json"?LK(u):PK(u);return await AI(f,a.path,t),BK(r),a.path&&n.write(`Wrote ${a.path}
584
- `),0}if(!a.helperPath?.trim())throw new Error(`--helper-path is required for fleet artifacts. Deploy it first with \`anyray-connect desktop helper --write\`; use ${Ni} on macOS/Linux or ${$i} on Windows.`);if(a.target==="claude"&&(a.team!==void 0||a.intent!==void 0||a.intentLabel!==void 0))throw new Error("--team and --intent flags do not belong in a Claude Desktop static artifact; each user's enrolled profile supplies attribution.");let i=a.helperPath,c=a.artifact==="reg"||/^[A-Za-z]:[\\/]/.test(i)?"windows":"posix";if(!Mi(i,c))throw new Error(`--helper-path must be an absolute ${c} path for this artifact.`);if(a.artifact==="mobileconfig"&&c!=="posix")throw new Error("--mobileconfig requires a POSIX --helper-path.");a.artifact==="reg"&&Zd("windows",i);let l=FK(a),d;if(a.target==="claude")d=a.artifact==="reg"?EI(l,i):a.artifact==="json"?TK(l,i):vI(l,i);else{let u=NK(l,i);d=a.artifact==="mobileconfig"?$K(u):u}return await AI(d,a.path,t),UK(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
583
+ `);return n.write(" claude.ai chats live on your account, not this machine: bring those\n over with `anyray-connect history restore <export.zip>`.\n"),0},Rx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=LK(e);if(o[0]==="helper")return bx(o.slice(1),t);let a=HK(o);if(a.help)return n.write(_K),0;let s=a.bootstrapUrl!==void 0||a.bootstrapOidc!==void 0||a.deploymentOrganizationUuid!==void 0;if(s){if(a.target!=="claude")throw new Error("--bootstrap-url is for Claude Desktop only.");if(a.migrate)throw new Error("Bootstrap options emit an MDM artifact; they cannot be combined with --migrate.");if(!a.artifact)throw new Error("--bootstrap-url requires --mobileconfig, --reg or --json to emit the trust anchor.");if(a.bootstrapUrl===void 0){let u=a.bootstrapOidc!==void 0?"--bootstrap-oidc":"--deployment-organization-uuid";throw new Error(`${u} requires --bootstrap-url.`)}if(a.helperPath!==void 0)throw new Error("--bootstrap-url cannot be combined with --helper-path; the bootstrap response supplies the effective inference configuration.");if(a.gateway!==void 0)throw new Error("--bootstrap-url cannot be combined with --gateway; return the inference gateway URL from the bootstrap response.");if(a.team!==void 0||a.intent!==void 0||a.intentLabel!==void 0)throw new Error("--bootstrap-url cannot be combined with --team or --intent flags; return per-user attribution from the bootstrap response.")}if(a.migrate){if(a.artifact)throw new Error("--migrate moves this machine's own sessions; drop --reg/--mobileconfig.");if(a.target==="codex")throw new Error("`desktop --migrate` applies only to Claude Desktop.");return await VK(a,t)}if(a.target==="codex"&&a.artifact==="reg")throw new Error("Codex fleet config does not use a Windows .reg file.");if(a.target==="codex"&&a.artifact==="json")throw new Error("Codex fleet config is managed_config.toml, not Claude's Linux managed-settings.json.");if(a.target==="claude"&&!a.artifact)throw new Error("Local Claude Desktop connect/disconnect is owned by the main Connect lifecycle.");if(s){let u={url:a.bootstrapUrl,...a.bootstrapOidc===void 0?{}:{oidc:Cx(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?UK(u):a.artifact==="json"?FK(u):MK(u);return await vx(f,a.path,t),jK(r),a.path&&n.write(`Wrote ${a.path}
584
+ `),0}if(!a.helperPath?.trim())throw new Error(`--helper-path is required for fleet artifacts. Deploy it first with \`anyray-connect desktop helper --write\`; use ${Mi} on macOS/Linux or ${Fi} on Windows.`);if(a.target==="claude"&&(a.team!==void 0||a.intent!==void 0||a.intentLabel!==void 0))throw new Error("--team and --intent flags do not belong in a Claude Desktop static artifact; each user's enrolled profile supplies attribution.");let i=a.helperPath,c=a.artifact==="reg"||/^[A-Za-z]:[\\/]/.test(i)?"windows":"posix";if(!Ui(i,c))throw new Error(`--helper-path must be an absolute ${c} path for this artifact.`);if(a.artifact==="mobileconfig"&&c!=="posix")throw new Error("--mobileconfig requires a POSIX --helper-path.");a.artifact==="reg"&&Jd("windows",i);let l=KK(a),d;if(a.target==="claude")d=a.artifact==="reg"?xx(l,i):a.artifact==="json"?$K(l,i):Sx(l,i);else{let u=BK(l,i);d=a.artifact==="mobileconfig"?WK(u):u}return await vx(d,a.path,t),GK(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
585
585
  `),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
586
- `),1}};var HK=`anyray-connect retrieve <handle> [--source auto|claude|profile]
586
+ `),1}};var YK=`anyray-connect retrieve <handle> [--source auto|claude|profile]
587
587
 
588
588
  Print the original content Anyray externalized behind a "\xB7 retrieve ctx_\u2026"
589
589
  marker. The content is written to stdout byte-for-byte (no trailing newline
@@ -593,7 +593,7 @@ Options:
593
593
  --source <s> Which client config resolves the gateway: auto (default),
594
594
  claude (~/.claude/settings.json), or profile (~/.anyray).
595
595
  --help Show this help.
596
- `,KK=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
596
+ `,ZK=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
597
597
 
598
598
  Semantic search over your externalized tool outputs. Prints one match per line
599
599
  to stdout as: handle<TAB>score<TAB>preview. Fetch a full original with
@@ -604,36 +604,36 @@ Options:
604
604
  --source <s> Which client config resolves the gateway: auto (default),
605
605
  claude (~/.claude/settings.json), or profile (~/.anyray).
606
606
  --help Show this help.
607
- `,OI=(e,t)=>{let n={source:"auto",help:!1};for(let r=0;r<e.length;r++){let o=e[r];if(o==="--help"||o==="-h")n.help=!0;else if(o==="--source"){let a=e[++r];if(a!=="auto"&&a!=="claude"&&a!=="profile")throw new Error("--source must be auto, claude, or profile.");n.source=a}else if(o==="--k"&&t){let a=Number(e[++r]);if(!Number.isInteger(a)||a<1||a>20)throw new Error("--k must be an integer between 1 and 20.");n.k=a}else if(!o.startsWith("-")&&n.positional===void 0)n.positional=o;else throw new Error(`Unknown option: ${o}`)}return n},GK=e=>e.replace(/[\t\r\n]+/g," ").trim(),_I=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=OI(e,!1);if(o.help)return n.write(HK),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
608
- `),1;let s=await(t.readTarget??rt)(o.source),i=await(t.retrieve??xa)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
607
+ `,_x=(e,t)=>{let n={source:"auto",help:!1};for(let r=0;r<e.length;r++){let o=e[r];if(o==="--help"||o==="-h")n.help=!0;else if(o==="--source"){let a=e[++r];if(a!=="auto"&&a!=="claude"&&a!=="profile")throw new Error("--source must be auto, claude, or profile.");n.source=a}else if(o==="--k"&&t){let a=Number(e[++r]);if(!Number.isInteger(a)||a<1||a>20)throw new Error("--k must be an integer between 1 and 20.");n.k=a}else if(!o.startsWith("-")&&n.positional===void 0)n.positional=o;else throw new Error(`Unknown option: ${o}`)}return n},XK=e=>e.replace(/[\t\r\n]+/g," ").trim(),Px=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=_x(e,!1);if(o.help)return n.write(YK),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
608
+ `),1;let s=await(t.readTarget??ot)(o.source),i=await(t.retrieve??Oa)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
609
609
  `),1)}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
610
- `),1}},TI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=OI(e,!0);if(o.help)return n.write(KK),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
611
- `),1;let s=await(t.readTarget??rt)(o.source),i=await(t.recall??_d)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
610
+ `),1}},Tx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=_x(e,!0);if(o.help)return n.write(ZK),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
611
+ `),1;let s=await(t.readTarget??ot)(o.source),i=await(t.recall??Td)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
612
612
  `),1;if(i.matches.length===0)return r.write(`No matching externalized outputs found.
613
- `),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${GK(c.preview)}
613
+ `),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${XK(c.preview)}
614
614
  `)}return r.write(`Fetch a full original: anyray-connect retrieve <handle>
615
615
  `),0}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
616
- `),1}};import{promises as yG}from"node:fs";var En=e=>typeof e=="string"?e:"",jK=e=>{let t=En(e.text).trim();if(t)return t;let n=e.content;if(!Array.isArray(n))return"";let r=[];for(let o of n){if(!o||typeof o!="object")continue;let a=En(o.text).trim();a&&r.push(a)}return r.join(`
616
+ `),1}};import{promises as CG}from"node:fs";var xn=e=>typeof e=="string"?e:"",JK=e=>{let t=xn(e.text).trim();if(t)return t;let n=e.content;if(!Array.isArray(n))return"";let r=[];for(let o of n){if(!o||typeof o!="object")continue;let a=xn(o.text).trim();a&&r.push(a)}return r.join(`
617
617
 
618
- `).trim()},VK=e=>{let t=En(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},YK=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=jK(r);if(!o)continue;let a=En(r.created_at).trim();t.push({role:VK(r),text:o,...a?{createdAt:a}:{}})}return t},Xd=e=>{let t;try{t=JSON.parse(e)}catch{return{ok:!1,conversations:[],skipped:0,message:"the file is not valid JSON"}}let n=Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.conversations)?t.conversations:null;if(!n)return{ok:!1,conversations:[],skipped:0,message:"expected a list of conversations \u2014 is this the conversations.json from a Claude data export?"};let r=[],o=0;for(let a of n){if(!a||typeof a!="object"){o+=1;continue}let s=a,i=YK(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(En(s.uuid)||En(s.id)).trim(),l=(En(s.name)||En(s.title)).trim()||"Untitled conversation",d=En(s.created_at).trim(),u=En(s.updated_at).trim();r.push({uuid:c,title:l,...d?{createdAt:d}:{},...u?{updatedAt:u}:{},messages:i})}return{ok:!0,conversations:r,skipped:o}};import{createHash as dG}from"node:crypto";import{promises as Ui}from"node:fs";import{homedir as FI}from"node:os";import{join as Qd}from"node:path";import{promises as PI}from"node:fs";import ey from"node:path";var ZK=4e4,JK=16*1024*1024,Fi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),zd=async(e,t={})=>{let n=(e??"").trim();if(!n)return Fi("","path is required");let r=t.cwd??process.cwd(),o=ey.resolve(r,n),a=ey.relative(r,o);if(a.startsWith("..")||ey.isAbsolute(a))return Fi(n,"path is outside the workspace");let s=t.maxBytes??ZK,i;try{let w=await PI.stat(o);if(!w.isFile())return Fi(n,"not a regular file");let g=t.maxFileBytes??JK;if(w.size>g)return Fi(n,`file too large to read (${w.size} bytes; limit ${g})`);i=await PI.readFile(o,"utf8")}catch(w){return Fi(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
618
+ `).trim()},qK=e=>{let t=xn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},zK=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=JK(r);if(!o)continue;let a=xn(r.created_at).trim();t.push({role:qK(r),text:o,...a?{createdAt:a}:{}})}return t},zd=e=>{let t;try{t=JSON.parse(e)}catch{return{ok:!1,conversations:[],skipped:0,message:"the file is not valid JSON"}}let n=Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.conversations)?t.conversations:null;if(!n)return{ok:!1,conversations:[],skipped:0,message:"expected a list of conversations \u2014 is this the conversations.json from a Claude data export?"};let r=[],o=0;for(let a of n){if(!a||typeof a!="object"){o+=1;continue}let s=a,i=zK(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(xn(s.uuid)||xn(s.id)).trim(),l=(xn(s.name)||xn(s.title)).trim()||"Untitled conversation",d=xn(s.created_at).trim(),u=xn(s.updated_at).trim();r.push({uuid:c,title:l,...d?{createdAt:d}:{},...u?{updatedAt:u}:{},messages:i})}return{ok:!0,conversations:r,skipped:o}};import{createHash as mG}from"node:crypto";import{promises as Wi}from"node:fs";import{homedir as Ux}from"node:os";import{join as tu}from"node:path";import{promises as Lx}from"node:fs";import ny from"node:path";var QK=4e4,eG=16*1024*1024,Bi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Qd=async(e,t={})=>{let n=(e??"").trim();if(!n)return Bi("","path is required");let r=t.cwd??process.cwd(),o=ny.resolve(r,n),a=ny.relative(r,o);if(a.startsWith("..")||ny.isAbsolute(a))return Bi(n,"path is outside the workspace");let s=t.maxBytes??QK,i;try{let w=await Lx.stat(o);if(!w.isFile())return Bi(n,"not a regular file");let g=t.maxFileBytes??eG;if(w.size>g)return Bi(n,`file too large to read (${w.size} bytes; limit ${g})`);i=await Lx.readFile(o,"utf8")}catch(w){return Bi(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
619
619
  `),l=Math.max(1,t.startLine??1),d=Math.min(c.length,t.endLine??c.length),u=l<=d?c.slice(l-1,d):[],f=u.join(`
620
620
  `),p=l<=d?d:l,h=!1,m=!1;if(Buffer.byteLength(f,"utf8")>s){let w=0,g=0;for(let y of u){let b=Buffer.byteLength(y,"utf8")+(g===0?0:1);if(w+b>s)break;w+=b,g+=1}g===0?(f=Buffer.from(u[0]??"","utf8").subarray(0,s).toString("utf8").replace(/\uFFFD$/,""),p=l,h=!0):(f=u.slice(0,g).join(`
621
- `),p=l+g-1),m=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:m,span:{startLine:l,endLine:p,...h?{partialLine:!0}:{}}}},ty=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
621
+ `),p=l+g-1),m=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:m,span:{startLine:l,endLine:p,...h?{partialLine:!0}:{}}}},ry=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
622
622
  ${e.content}`;let t=e.span?`lines ${e.span.startLine}-${e.span.endLine}`:"a prefix",n=e.span&&!e.span.partialLine&&e.span.endLine<e.lines?` Continue with anyray_read(path="${e.path}", startLine=${e.span.endLine+1}).`:"";return`${e.path} (truncated \u2014 showing ${t} of ${e.lines}).${n}
623
- ${e.content}`};import{spawn as XK}from"node:child_process";import{promises as ny}from"node:fs";import ry from"node:path";var oy=400,zK=240,qK=4e3,QK=4e3,eG=512*1024,tG=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),DI=(e,t)=>e.length>t?e.slice(0,t):e,nG=new Set(["a","about","an","and","are","as","at","be","been","but","by","can","could","did","do","does","for","from","had","has","have","here","how","if","in","is","it","me","my","of","on","or","our","should","so","that","the","their","there","this","to","us","was","we","were","what","when","where","which","who","why","with","would","you","your"]),rG=8,oG=2e3,aG=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],sG=e=>{let t=e.toLowerCase(),n=t.split(/[\\/]/).pop()??t;return/(^|[\\/])\.(ssh|aws|gnupg)([\\/]|$)/.test(t)||n.startsWith(".env")||n.startsWith("id_rsa")||n.startsWith("id_ed25519")||/\.(pem|key|p12|pfx)$/.test(n)?!0:n.includes("secret")||n.includes("credential")},NI=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!nG.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=rG))break}return n},$I=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},iG=(e,t,n)=>{if(t.length<2)return e;let r=n?t:t.map(a=>a.toLowerCase()),o=a=>{let s=n?a.text:a.text.toLowerCase(),i=0;for(let c of r)s.includes(c)&&(i+=1);return i};return e.map((a,s)=>({m:a,i:s,s:o(a)})).sort((a,s)=>s.s-a.s||a.i-s.i).map(a=>a.m)},LI=(e,t,n)=>{let r=[];for(let o of e.split(`
624
- `)){if(r.length>=n)break;if(!o)continue;let a=o.indexOf(":");if(a<=0)continue;let s=o.indexOf(":",a+1);if(s<0)continue;let i=o.slice(0,a).replace(/^\.\//,""),c=Number(o.slice(a+1,s));if(!Number.isInteger(c)||c<=0)continue;let l=o.slice(s+1);r.push({file:i,line:c,text:DI(l,t)})}return r},cG=(e,t,n,r,o,a,s)=>new Promise(i=>{let c=["--line-number","--no-heading","--color","never","--max-columns",String(o),"--max-columns-preview","--smart-case","--max-count","20","--fixed-strings"];for(let h of n)c.push("-g",h);for(let h of aG)c.push("-g",h);if(s?.length){for(let h of s)c.push("-e",h);c.push("--",".")}else c.push("--",e,".");let l;try{l=XK("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,f=h=>{u||(u=!0,clearTimeout(p),i(h))},p=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let h=LI(d,o,r);f({ok:!0,matches:h,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",h=>{if(d+=h,d.length>r*(o+64))try{l.kill("SIGKILL")}catch{}}),l.on("error",()=>{f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"})}),l.on("close",h=>{if(typeof h=="number"&&h>=2){f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let m=LI(d,o,r+1),w=m.length>r;f({ok:!0,matches:w?m.slice(0,r):m,truncated:w,engine:"ripgrep"})})}),lG=async(e,t,n,r,o,a,s)=>{let i=$I(s?.length?s:e),c=m=>i?m:m.toLowerCase(),l=(s?.length?s:[e]).map(c),d=n.map(m=>m.replace(/^\*+/,"")).filter(m=>m.startsWith(".")),u=[],f=0,p=!1,h=async m=>{if(u.length>=r||Date.now()>a){p=!0;return}let w;try{w=await ny.readdir(m,{withFileTypes:!0})}catch{return}for(let g of w){if(u.length>=r||Date.now()>a){p=!0;return}let y=ry.join(m,g.name);if(g.isDirectory()){if(tG.has(g.name))continue;await h(y)}else if(g.isFile()){if(f>=QK){p=!0;return}if(d.length&&!d.some(v=>g.name.endsWith(v))||sG(ry.relative(t,y)))continue;f+=1;let b;try{if((await ny.stat(y)).size>eG)continue;b=await ny.readFile(y,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let A=b.split(`
625
- `);for(let v=0;v<A.length;v+=1){let E=c(A[v]);if(l.some(I=>E.includes(I))&&(u.push({file:ry.relative(t,y),line:v+1,text:DI(A[v],o)}),u.length>=r)){p=!0;return}}}}};return await h(t),{ok:!0,matches:u,truncated:p,engine:"walk"}},qd=async(e,t={})=>{let n=e.trim();if(!n)return{ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"query is required"};let r=t.cwd??process.cwd(),o=t.globs??[],a=t.maxMatches??oy,s=t.maxColumns??zK,i=t.timeoutMs??qK,c=Date.now()+i,l=NI(n),d=l.length>1,u=Math.min(a*4,oG),f=(g,y)=>lG(n,r,o,g,s,c,y),p=async g=>{let y=await g(u,l);if(!y.ok)return y;let b=iG(y.matches,l,$I(l)),A=b.length>a;return{...y,matches:A?b.slice(0,a):b,truncated:y.truncated||A,matched:"tokens",tokens:l}};if(t.engine==="walk"){let g=await f(a);return g.matches.length>0||!d?g:p((y,b)=>f(y,b))}let h=(g,y)=>cG(n,r,o,g,s,Math.max(0,c-Date.now()),y),m=await h(a);if(m.ok){if(m.matches.length>0||!d)return m;let g=await p((y,b)=>h(y,b));return g.ok?g:p((y,b)=>f(y,b))}let w=await f(a);return w.matches.length>0||!d?w:p((g,y)=>f(g,y))},MI=(e,t,n="full")=>{if(!t.ok)return`Search failed: ${t.message??"unknown error"}`;if(t.matches.length===0){if(t.truncated)return`Search for "${e}" hit its time limit before finishing, and found nothing in what it covered. This is NOT proof the term is absent \u2014 narrow it with globs (e.g. ["*.ts"]) and search again.`;let d=NI(e).length>1?" Searched the phrase and each word separately. Try one identifier on its own (a function, type, or error string), or narrow with globs.":" Try a shorter or differently-cased fragment, or narrow with globs.";return`No matches for "${e}".${d}`}let r=t.matched==="tokens"&&t.tokens?.length?`No line contains "${e}"; showing lines matching its terms (${t.tokens.join(", ")}), most complete first.
623
+ ${e.content}`};import{spawn as tG}from"node:child_process";import{promises as oy}from"node:fs";import ay from"node:path";var sy=400,nG=240,rG=4e3,oG=4e3,aG=512*1024,sG=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),Nx=(e,t)=>e.length>t?e.slice(0,t):e,iG=new Set(["a","about","an","and","are","as","at","be","been","but","by","can","could","did","do","does","for","from","had","has","have","here","how","if","in","is","it","me","my","of","on","or","our","should","so","that","the","their","there","this","to","us","was","we","were","what","when","where","which","who","why","with","would","you","your"]),cG=8,lG=2e3,dG=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],uG=e=>{let t=e.toLowerCase(),n=t.split(/[\\/]/).pop()??t;return/(^|[\\/])\.(ssh|aws|gnupg)([\\/]|$)/.test(t)||n.startsWith(".env")||n.startsWith("id_rsa")||n.startsWith("id_ed25519")||/\.(pem|key|p12|pfx)$/.test(n)?!0:n.includes("secret")||n.includes("credential")},$x=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!iG.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=cG))break}return n},Mx=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},pG=(e,t,n)=>{if(t.length<2)return e;let r=n?t:t.map(a=>a.toLowerCase()),o=a=>{let s=n?a.text:a.text.toLowerCase(),i=0;for(let c of r)s.includes(c)&&(i+=1);return i};return e.map((a,s)=>({m:a,i:s,s:o(a)})).sort((a,s)=>s.s-a.s||a.i-s.i).map(a=>a.m)},Dx=(e,t,n)=>{let r=[];for(let o of e.split(`
624
+ `)){if(r.length>=n)break;if(!o)continue;let a=o.indexOf(":");if(a<=0)continue;let s=o.indexOf(":",a+1);if(s<0)continue;let i=o.slice(0,a).replace(/^\.\//,""),c=Number(o.slice(a+1,s));if(!Number.isInteger(c)||c<=0)continue;let l=o.slice(s+1);r.push({file:i,line:c,text:Nx(l,t)})}return r},fG=(e,t,n,r,o,a,s)=>new Promise(i=>{let c=["--line-number","--no-heading","--color","never","--max-columns",String(o),"--max-columns-preview","--smart-case","--max-count","20","--fixed-strings"];for(let h of n)c.push("-g",h);for(let h of dG)c.push("-g",h);if(s?.length){for(let h of s)c.push("-e",h);c.push("--",".")}else c.push("--",e,".");let l;try{l=tG("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,f=h=>{u||(u=!0,clearTimeout(p),i(h))},p=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let h=Dx(d,o,r);f({ok:!0,matches:h,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",h=>{if(d+=h,d.length>r*(o+64))try{l.kill("SIGKILL")}catch{}}),l.on("error",()=>{f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"})}),l.on("close",h=>{if(typeof h=="number"&&h>=2){f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let m=Dx(d,o,r+1),w=m.length>r;f({ok:!0,matches:w?m.slice(0,r):m,truncated:w,engine:"ripgrep"})})}),hG=async(e,t,n,r,o,a,s)=>{let i=Mx(s?.length?s:e),c=m=>i?m:m.toLowerCase(),l=(s?.length?s:[e]).map(c),d=n.map(m=>m.replace(/^\*+/,"")).filter(m=>m.startsWith(".")),u=[],f=0,p=!1,h=async m=>{if(u.length>=r||Date.now()>a){p=!0;return}let w;try{w=await oy.readdir(m,{withFileTypes:!0})}catch{return}for(let g of w){if(u.length>=r||Date.now()>a){p=!0;return}let y=ay.join(m,g.name);if(g.isDirectory()){if(sG.has(g.name))continue;await h(y)}else if(g.isFile()){if(f>=oG){p=!0;return}if(d.length&&!d.some(v=>g.name.endsWith(v))||uG(ay.relative(t,y)))continue;f+=1;let b;try{if((await oy.stat(y)).size>aG)continue;b=await oy.readFile(y,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let A=b.split(`
625
+ `);for(let v=0;v<A.length;v+=1){let E=c(A[v]);if(l.some(x=>E.includes(x))&&(u.push({file:ay.relative(t,y),line:v+1,text:Nx(A[v],o)}),u.length>=r)){p=!0;return}}}}};return await h(t),{ok:!0,matches:u,truncated:p,engine:"walk"}},eu=async(e,t={})=>{let n=e.trim();if(!n)return{ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"query is required"};let r=t.cwd??process.cwd(),o=t.globs??[],a=t.maxMatches??sy,s=t.maxColumns??nG,i=t.timeoutMs??rG,c=Date.now()+i,l=$x(n),d=l.length>1,u=Math.min(a*4,lG),f=(g,y)=>hG(n,r,o,g,s,c,y),p=async g=>{let y=await g(u,l);if(!y.ok)return y;let b=pG(y.matches,l,Mx(l)),A=b.length>a;return{...y,matches:A?b.slice(0,a):b,truncated:y.truncated||A,matched:"tokens",tokens:l}};if(t.engine==="walk"){let g=await f(a);return g.matches.length>0||!d?g:p((y,b)=>f(y,b))}let h=(g,y)=>fG(n,r,o,g,s,Math.max(0,c-Date.now()),y),m=await h(a);if(m.ok){if(m.matches.length>0||!d)return m;let g=await p((y,b)=>h(y,b));return g.ok?g:p((y,b)=>f(y,b))}let w=await f(a);return w.matches.length>0||!d?w:p((g,y)=>f(g,y))},Fx=(e,t,n="full")=>{if(!t.ok)return`Search failed: ${t.message??"unknown error"}`;if(t.matches.length===0){if(t.truncated)return`Search for "${e}" hit its time limit before finishing, and found nothing in what it covered. This is NOT proof the term is absent \u2014 narrow it with globs (e.g. ["*.ts"]) and search again.`;let d=$x(e).length>1?" Searched the phrase and each word separately. Try one identifier on its own (a function, type, or error string), or narrow with globs.":" Try a shorter or differently-cased fragment, or narrow with globs.";return`No matches for "${e}".${d}`}let r=t.matched==="tokens"&&t.tokens?.length?`No line contains "${e}"; showing lines matching its terms (${t.tokens.join(", ")}), most complete first.
626
626
  `:"";if(n==="paths"){let d=new Map;for(let f of t.matches)d.set(f.file,(d.get(f.file)??0)+1);let u=[...d].map(([f,p])=>`${f} (${p} match${p===1?"":"es"})`);return[`${r}${d.size}${t.truncated?"+":""} file${d.size===1?"":"s"} match "${e}":`,...u].join(`
627
627
  `)}let o=`${r}${t.matches.length}${t.truncated?"+":""} matches for "${e}":`,a=t.matches.map(d=>n==="lines"?`${d.file}:${d.line}`:`${d.file}:${d.line}: ${d.text}`),s=d=>`\u2026 ${d} more match${d===1?"":"es"} not shown (output limit). Narrow with globs or a more specific query, or set resultShape:"paths" to see every file.`,i=s(a.length).length+1,c=o.length,l=0;for(let d of a){if(c+1+d.length+i>4e4)break;c+=1+d.length,l+=1}return l>=a.length?[o,...a].join(`
628
628
  `):[o,...a.slice(0,Math.max(1,l)),s(a.length-Math.max(1,l))].join(`
629
- `)};var UI=448,uG=384,pG=4e4,Pr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=Qd(FI(),".anyray");try{if((await Ui.stat(t)).isDirectory())return Qd(t,"history")}catch{}return Qd(FI(),".anyray-history")},fG=e=>{let t=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),n=(e.createdAt??"").slice(0,10),r=(e.uuid||"").replace(/[^a-zA-Z0-9-]/g,"").slice(0,65),o=r.length>0&&r.length<=64?r:hG(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},hG=e=>{let t=dG("sha256");t.update(e.title),t.update("\0"),t.update(e.createdAt??""),t.update("\0");for(let n of e.messages)t.update(n.role),t.update("\0"),t.update(n.text),t.update("\0");return t.digest("hex").slice(0,16)},mG=e=>{let t=[`# ${e.title}`,"",e.createdAt?`- Created: ${e.createdAt}`:"",e.updatedAt?`- Updated: ${e.updatedAt}`:"",e.uuid?`- Claude conversation id: ${e.uuid}`:"",""].filter((r,o,a)=>!(r===""&&a[o-1]==="")),n=e.messages.map(r=>{let o=r.role==="user"?"User":"Claude",a=r.createdAt?` (${r.createdAt})`:"";return`## ${o}${a}
629
+ `)};var Bx=448,yG=384,gG=4e4,Lr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=tu(Ux(),".anyray");try{if((await Wi.stat(t)).isDirectory())return tu(t,"history")}catch{}return tu(Ux(),".anyray-history")},wG=e=>{let t=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),n=(e.createdAt??"").slice(0,10),r=(e.uuid||"").replace(/[^a-zA-Z0-9-]/g,"").slice(0,65),o=r.length>0&&r.length<=64?r:bG(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},bG=e=>{let t=mG("sha256");t.update(e.title),t.update("\0"),t.update(e.createdAt??""),t.update("\0");for(let n of e.messages)t.update(n.role),t.update("\0"),t.update(n.text),t.update("\0");return t.digest("hex").slice(0,16)},kG=e=>{let t=[`# ${e.title}`,"",e.createdAt?`- Created: ${e.createdAt}`:"",e.updatedAt?`- Updated: ${e.updatedAt}`:"",e.uuid?`- Claude conversation id: ${e.uuid}`:"",""].filter((r,o,a)=>!(r===""&&a[o-1]==="")),n=e.messages.map(r=>{let o=r.role==="user"?"User":"Claude",a=r.createdAt?` (${r.createdAt})`:"";return`## ${o}${a}
630
630
 
631
631
  ${r.text}
632
632
  `});return[...t,...n].join(`
633
633
  `).replace(/\n{3,}/g,`
634
634
 
635
635
  `)+`
636
- `},eu=async e=>{let t=await Pr();await Ui.mkdir(t,{recursive:!0,mode:UI});try{await Ui.chmod(t,UI)}catch{}let n=0,r=0;for(let o of e)try{await Ui.writeFile(Qd(t,fG(o)),mG(o),{mode:uG}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Ba=async()=>{try{let e=await Pr();return(await Ui.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},BI=async e=>{let t=await Pr();return qd(e,{cwd:t,globs:["*.md"]})},WI=async e=>{let t=await Pr();return zd(e,{cwd:t,maxBytes:pG})};var HI=`anyray-connect history <command>
636
+ `},nu=async e=>{let t=await Lr();await Wi.mkdir(t,{recursive:!0,mode:Bx});try{await Wi.chmod(t,Bx)}catch{}let n=0,r=0;for(let o of e)try{await Wi.writeFile(tu(t,wG(o)),kG(o),{mode:yG}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Wa=async()=>{try{let e=await Lr();return(await Wi.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},Wx=async e=>{let t=await Lr();return eu(e,{cwd:t,globs:["*.md"]})},Hx=async e=>{let t=await Lr();return Qd(e,{cwd:t,maxBytes:gG})};var Kx=`anyray-connect history <command>
637
637
 
638
638
  Make past Claude conversations searchable from any Anyray-connected client.
639
639
 
@@ -654,7 +654,7 @@ Which one you want:
654
654
  conversation into the chat when you ask for it. Recall, not a list.
655
655
 
656
656
  Running both is fine, and gets you both.
657
- `,gG=async e=>{try{return{raw:await yG.readFile(e,"utf8")}}catch(t){let n=t?.code;return n==="ENOENT"?{error:`no such file: ${e}`}:n==="EACCES"?{error:`not readable: ${e}`}:n==="EISDIR"?{error:`${e} is a directory \u2014 point at the conversations.json inside it`}:{error:`could not read ${e} (${n??"read failed"})`}}},wG=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return _("Usage: anyray-connect history import <conversations.json>"),k(S("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await gG(t);if("error"in n)return _(n.error),1;let r=Xd(n.raw);if(!r.ok)return _(`Could not read that export: ${r.message??"unrecognized format"}`),k(S("Expected the conversations.json from a Claude data export (claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data).")),1;if(r.conversations.length===0)return _("That export contains no conversations with readable messages."),1;let o;try{o=await eu(r.conversations)}catch(a){let s=a?.code;return _(`Could not create the history archive (${s??"write failed"}).`),k(S("Check that ~/.anyray is a writable directory, then try again.")),1}return F(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&k(S(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&D(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),k(""),k(j("Your history is now searchable from any Anyray-connected client.")),k(S(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),k(S(" and the assistant can search this archive and pull it up.")),k(S(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),k(S(" for them, they do not reappear as a clickable list in the app.")),0},bG=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return _("Usage: anyray-connect history restore <export.zip>"),k(S("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await Xl(t);return n.ok?(F(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&k(S(` ${n.skipped} already present, left untouched.`)),n.failed>0&&D(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),k(""),k(j("Open Claude Desktop \u2014 they are in the sidebar again.")),k(S(" Anyray stays configured; this changed nothing about your routing.")),k(S(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),k(S(" undocumented. A future Desktop release could stop reading it \u2014 your export")),k(S(" file still works, and `history import` remains a second copy.")),0):(_(`Could not restore into Claude Desktop: ${n.reason}`),k(S(` ${n.remedy}`)),1)},kG=async()=>{let e=await Pr(),t=await Ba();return t===0?(k(`No conversations imported yet. Archive would live at ${e}`),k(S(" Import one with: anyray-connect history import <conversations.json>")),0):(F(`${t} conversation${t===1?"":"s"} in ${e}`),0)},KI=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(HI),0):t==="import"?wG(e.slice(1)):t==="restore"?bG(e.slice(1)):t==="status"?kG():(_(`Unknown history command: ${t}`),console.log(HI),1)};import{promises as CG}from"node:fs";var AG=`anyray-connect migrate [options]
657
+ `,AG=async e=>{try{return{raw:await CG.readFile(e,"utf8")}}catch(t){let n=t?.code;return n==="ENOENT"?{error:`no such file: ${e}`}:n==="EACCES"?{error:`not readable: ${e}`}:n==="EISDIR"?{error:`${e} is a directory \u2014 point at the conversations.json inside it`}:{error:`could not read ${e} (${n??"read failed"})`}}},vG=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return _("Usage: anyray-connect history import <conversations.json>"),k(S("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await AG(t);if("error"in n)return _(n.error),1;let r=zd(n.raw);if(!r.ok)return _(`Could not read that export: ${r.message??"unrecognized format"}`),k(S("Expected the conversations.json from a Claude data export (claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data).")),1;if(r.conversations.length===0)return _("That export contains no conversations with readable messages."),1;let o;try{o=await nu(r.conversations)}catch(a){let s=a?.code;return _(`Could not create the history archive (${s??"write failed"}).`),k(S("Check that ~/.anyray is a writable directory, then try again.")),1}return F(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&k(S(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&L(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),k(""),k(j("Your history is now searchable from any Anyray-connected client.")),k(S(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),k(S(" and the assistant can search this archive and pull it up.")),k(S(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),k(S(" for them, they do not reappear as a clickable list in the app.")),0},SG=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return _("Usage: anyray-connect history restore <export.zip>"),k(S("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await zl(t);return n.ok?(F(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&k(S(` ${n.skipped} already present, left untouched.`)),n.failed>0&&L(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),k(""),k(j("Open Claude Desktop \u2014 they are in the sidebar again.")),k(S(" Anyray stays configured; this changed nothing about your routing.")),k(S(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),k(S(" undocumented. A future Desktop release could stop reading it \u2014 your export")),k(S(" file still works, and `history import` remains a second copy.")),0):(_(`Could not restore into Claude Desktop: ${n.reason}`),k(S(` ${n.remedy}`)),1)},EG=async()=>{let e=await Lr(),t=await Wa();return t===0?(k(`No conversations imported yet. Archive would live at ${e}`),k(S(" Import one with: anyray-connect history import <conversations.json>")),0):(F(`${t} conversation${t===1?"":"s"} in ${e}`),0)},Gx=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(Kx),0):t==="import"?vG(e.slice(1)):t==="restore"?SG(e.slice(1)):t==="status"?EG():(_(`Unknown history command: ${t}`),console.log(Kx),1)};import{promises as xG}from"node:fs";var IG=`anyray-connect migrate [options]
658
658
 
659
659
  Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
660
660
 
@@ -683,50 +683,50 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
683
683
  Open claude.ai -> Settings -> Privacy -> Export data. Anthropic emails a link.
684
684
  Pass the .zip to --export, and the conversations.json inside it to
685
685
  --conversations. Both are safe to re-run; they skip what is already there.
686
- `,vG=e=>{let t={allAccounts:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--export")t.exportZip=e[++n];else if(r==="--conversations")t.conversations=e[++n];else if(r==="--account")t.account=e[++n];else if(r==="--all-accounts")t.allAccounts=!0;else if(r==="--help"||r==="-h")t.help=!0;else if(!(r==="--yes"||r==="-y"))if(!r.startsWith("-")&&!t.exportZip)r.endsWith(".json")?t.conversations=r:t.exportZip=r;else throw new Error(`unexpected argument: ${r}`)}return t},GI={code:"Claude Code sessions",cowork:"Cowork tasks"},SG=e=>{let t=[e.alreadyPresent>0?`${e.alreadyPresent} already there`:"",e.skippedNoTranscript>0?`${e.skippedNoTranscript} skipped, transcript no longer on disk`:"",e.failed>0?`${e.failed} failed`:""].filter(Boolean);return`${GI[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},EG=async(e,t)=>{k(j("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??fo)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){_(` ${n.reason}`);for(let s of n.remedy.split(`
687
- `).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${SG(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";k(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&D(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&D(` Claude Desktop has more than one target ${r.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run this again.`);let o=n.retryableAssets??[];o.length>0&&D(` ${o.length} portable configuration ${o.length===1?"type needs":"types need"} another local-copy attempt; no existing target entry was replaced.`);for(let s of n.blocked??[])D(` ${GI[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${Lh(s.reason,s.lane,"anyray-connect migrate")}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&k(S(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},IG=async(e,t)=>{if(k(""),k(j("2. Your claude.ai chats")),t){k(S(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){k(" These live on your Claude account, not this machine, so they need"),k(" an export. Anyray cannot fetch them: the only credential that could"),k(" is your claude.ai session, which Connect never holds."),k(S(" claude.ai -> Settings -> Privacy -> Export data, then:")),k(S(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await Xl(e.exportZip);if(!n.ok){_(` ${n.reason}`),k(` ${n.remedy}`);return}F(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),k(S(" They are listed under Cowork \u2014 the Chat tab has no local store."));let r=n.projects;if(r.imported+r.alreadyPresent+r.skippedCollision+r.failed>0){let a=[r.alreadyPresent>0?`${r.alreadyPresent} already there`:"",r.skippedCollision>0?`${r.skippedCollision} skipped, a folder of that name already exists`:"",r.failed>0?`${r.failed} failed`:""].filter(Boolean);F(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&k(S(` Instructions and docs are in ${r.root}, listed under Projects.`))}},xG=async e=>{if(k(""),k(j("3. Searchable from every Anyray client")),!e.conversations){let o=await Ba();o>0?k(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(k(S(" Optional. Pass the conversations.json inside the export:")),k(S(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await CG.readFile(e.conversations,"utf8")}catch{_(` could not read ${e.conversations}`);return}let n=Xd(t);if(!n.ok){_(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await eu(n.conversations);F(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),k(S(` Ask any Anyray-connected client about a past chat. ${await Pr()}`))},RG=e=>{k(""),k(j("Next")),k(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||D(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),k(S(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},jI=async(e,t={})=>{let n;try{n=vG(e)}catch(o){return _(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(AG),0;k(j("Migrating Claude Desktop onto Anyray")),k(S("Claude Desktop must be fully quit.")),k("");let r=await EG(n,t);return await IG(n,!r),await xG(n),r?(RG(n),0):(k(""),D("Fix the item above and re-run to finish the migration."),1)};var OG=3e3,tu=async(e,t={})=>{let n=t.timeoutMs??OG,r=`${e}/`,o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await fetch(r,{method:"GET",signal:o.signal});return s.ok?{reachable:!0,detail:`responded ${s.status}`}:{reachable:!1,detail:`responded ${s.status} at ${r} \u2014 a healthy gateway answers 200 there`}}catch(s){return{reachable:!1,detail:s instanceof Error&&s.name==="AbortError"?`no response within ${n}ms`:gt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};var _G="enl_",TG="enp_",VI=e=>e.startsWith(_G)||e.startsWith(TG),PG=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],ay=e=>PG.find(t=>e.startsWith(t.prefix)),YI=/^\/enroll\/([^/]+)\/?$/,ZI=/^\/i\/([^/]+)\/?$/,JI=e=>{let t=e.match(YI);if(t)return ay(t[1])?void 0:t[1];let n=e.match(ZI);return n&&VI(n[1])?n[1]:void 0},LG=1e4,nu=e=>{let t=e.trim();if(!t)return;let n;try{n=new URL(t)}catch{n=void 0}if(n){if(n.protocol!=="http:"&&n.protocol!=="https:")return;let r=JI(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!ay(t))return{cpOrigin:Yn(),token:t}},XI=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(YI)??o.pathname.match(ZI);if(!a)return;n=a[1]}catch{}let r=ay(n);return r?{flag:r.flag,what:r.what}:void 0},Wi=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:JI(n.pathname)!==void 0}catch{return VI(t)}},Bi=e=>typeof e=="string"&&e.trim()?e.trim():void 0,zI=async(e,t={})=>{let n=t.timeoutMs??LG,r=`${e.cpOrigin}/enroll-info/${e.token}`,o=new AbortController,a=setTimeout(()=>o.abort(),n),s;try{s=await fetch(r,{method:"GET",signal:o.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${n}ms.`:gt(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${f}`)}finally{clearTimeout(a)}if(!s.ok)throw new Error(`enrollment link lookup failed: ${e.cpOrigin} responded ${s.status} \u2014 the link may be expired or revoked; ask your admin for a fresh one.`);let i;try{i=await s.json()}catch{throw new Error(`enrollment link lookup failed: ${e.cpOrigin} returned a malformed response`)}let l=(Array.isArray(i?.gateways)?i.gateways:[]).find(u=>u!==null&&typeof u=="object"&&Bi(u.url)!==void 0),d=Bi(l?.url);if(!d)throw new Error(i.connected===!0?"this enrollment link's gateway is running but hasn't advertised its public URL yet \u2014 ask your admin to set ANYRAY_GATEWAY_PUBLIC_URL (Helm: gateway.publicUrl), then re-run.":"this enrollment link has no gateway configured yet \u2014 ask your admin to confirm the gateway is deployed, then re-run.");return{gatewayUrl:d,deploymentId:Bi(l?.deploymentId),org:Bi(i.org),email:Bi(i.email),seatMode:i.seatMode===!0}};var qI=()=>Wm(),QI=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??qI)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},DG=e=>{let t=String(e),n=[];for(let r=0;r<t.length;r++)t[r]==="\x1B"&&t[r+1]==="["&&t[r+2]?(n.push(t.slice(r,r+3)),r+=2):n.push(t[r]);return n},ex=async(e,t={})=>{let n=(t.openInput??qI)(),r=n.stream,o=t.output??process.stderr;if(typeof r.setRawMode!="function")throw n.close(),new Error("raw terminal input is unavailable");let a=e.items.map(h=>h.selected===!0&&h.requiresExplicitChoice!==!0),s=0,i=0,c=Da(o,t.env??process.env),l=(h,m)=>c?`\x1B[${h}m${m}\x1B[0m`:m,d=()=>{let h=[l("1",e.title)];for(let m=0;m<e.items.length;m++){let w=e.items[m],g=m===s?l("36","\u276F"):" ",y=e.single?a[m]?"(\u25CF)":"(\u25CB)":a[m]?"[x]":"[ ]",b=w.hint?` ${l("2",w.hint)}`:"";h.push(`${g} ${y} ${w.label}${b}`)}h.push(l("2",e.single?"\u2191/\u2193 move \xB7 space choose \xB7 enter accept \xB7 q cancel":"\u2191/\u2193 move \xB7 space toggle \xB7 a toggle all \xB7 enter accept \xB7 q cancel")),i>0&&o.write(`\x1B[${i}A`),o.write(h.map(m=>`\r\x1B[2K${m}`).join(`
686
+ `,OG=e=>{let t={allAccounts:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--export")t.exportZip=e[++n];else if(r==="--conversations")t.conversations=e[++n];else if(r==="--account")t.account=e[++n];else if(r==="--all-accounts")t.allAccounts=!0;else if(r==="--help"||r==="-h")t.help=!0;else if(!(r==="--yes"||r==="-y"))if(!r.startsWith("-")&&!t.exportZip)r.endsWith(".json")?t.conversations=r:t.exportZip=r;else throw new Error(`unexpected argument: ${r}`)}return t},jx={code:"Claude Code sessions",cowork:"Cowork tasks"},RG=e=>{let t=[e.alreadyPresent>0?`${e.alreadyPresent} already there`:"",e.skippedNoTranscript>0?`${e.skippedNoTranscript} skipped, transcript no longer on disk`:"",e.failed>0?`${e.failed} failed`:""].filter(Boolean);return`${jx[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},_G=async(e,t)=>{k(j("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??po)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){_(` ${n.reason}`);for(let s of n.remedy.split(`
687
+ `).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${RG(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";k(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&L(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&L(` Claude Desktop has more than one target ${r.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run this again.`);let o=n.retryableAssets??[];o.length>0&&L(` ${o.length} portable configuration ${o.length===1?"type needs":"types need"} another local-copy attempt; no existing target entry was replaced.`);for(let s of n.blocked??[])L(` ${jx[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${Nh(s.reason,s.lane,"anyray-connect migrate")}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&k(S(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},PG=async(e,t)=>{if(k(""),k(j("2. Your claude.ai chats")),t){k(S(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){k(" These live on your Claude account, not this machine, so they need"),k(" an export. Anyray cannot fetch them: the only credential that could"),k(" is your claude.ai session, which Connect never holds."),k(S(" claude.ai -> Settings -> Privacy -> Export data, then:")),k(S(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await zl(e.exportZip);if(!n.ok){_(` ${n.reason}`),k(` ${n.remedy}`);return}F(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),k(S(" They are listed under Cowork \u2014 the Chat tab has no local store."));let r=n.projects;if(r.imported+r.alreadyPresent+r.skippedCollision+r.failed>0){let a=[r.alreadyPresent>0?`${r.alreadyPresent} already there`:"",r.skippedCollision>0?`${r.skippedCollision} skipped, a folder of that name already exists`:"",r.failed>0?`${r.failed} failed`:""].filter(Boolean);F(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&k(S(` Instructions and docs are in ${r.root}, listed under Projects.`))}},TG=async e=>{if(k(""),k(j("3. Searchable from every Anyray client")),!e.conversations){let o=await Wa();o>0?k(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(k(S(" Optional. Pass the conversations.json inside the export:")),k(S(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await xG.readFile(e.conversations,"utf8")}catch{_(` could not read ${e.conversations}`);return}let n=zd(t);if(!n.ok){_(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await nu(n.conversations);F(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),k(S(` Ask any Anyray-connected client about a past chat. ${await Lr()}`))},LG=e=>{k(""),k(j("Next")),k(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||L(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),k(S(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},Vx=async(e,t={})=>{let n;try{n=OG(e)}catch(o){return _(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(IG),0;k(j("Migrating Claude Desktop onto Anyray")),k(S("Claude Desktop must be fully quit.")),k("");let r=await _G(n,t);return await PG(n,!r),await TG(n),r?(LG(n),0):(k(""),L("Fix the item above and re-run to finish the migration."),1)};var DG=3e3,ru=async(e,t={})=>{let n=t.timeoutMs??DG,r=`${e}/`,o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await fetch(r,{method:"GET",signal:o.signal});return s.ok?{reachable:!0,detail:`responded ${s.status}`}:{reachable:!1,detail:`responded ${s.status} at ${r} \u2014 a healthy gateway answers 200 there`}}catch(s){return{reachable:!1,detail:s instanceof Error&&s.name==="AbortError"?`no response within ${n}ms`:wt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};var NG="enl_",$G="enp_",Yx=e=>e.startsWith(NG)||e.startsWith($G),MG=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],iy=e=>MG.find(t=>e.startsWith(t.prefix)),Zx=/^\/enroll\/([^/]+)\/?$/,Xx=/^\/i\/([^/]+)\/?$/,Jx=e=>{let t=e.match(Zx);if(t)return iy(t[1])?void 0:t[1];let n=e.match(Xx);return n&&Yx(n[1])?n[1]:void 0},FG=1e4,ou=e=>{let t=e.trim();if(!t)return;let n;try{n=new URL(t)}catch{n=void 0}if(n){if(n.protocol!=="http:"&&n.protocol!=="https:")return;let r=Jx(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!iy(t))return{cpOrigin:Xn(),token:t}},qx=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(Zx)??o.pathname.match(Xx);if(!a)return;n=a[1]}catch{}let r=iy(n);return r?{flag:r.flag,what:r.what}:void 0},Ki=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:Jx(n.pathname)!==void 0}catch{return Yx(t)}},Hi=e=>typeof e=="string"&&e.trim()?e.trim():void 0,zx=async(e,t={})=>{let n=t.timeoutMs??FG,r=`${e.cpOrigin}/enroll-info/${e.token}`,o=new AbortController,a=setTimeout(()=>o.abort(),n),s;try{s=await fetch(r,{method:"GET",signal:o.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${n}ms.`:wt(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${f}`)}finally{clearTimeout(a)}if(!s.ok)throw new Error(`enrollment link lookup failed: ${e.cpOrigin} responded ${s.status} \u2014 the link may be expired or revoked; ask your admin for a fresh one.`);let i;try{i=await s.json()}catch{throw new Error(`enrollment link lookup failed: ${e.cpOrigin} returned a malformed response`)}let l=(Array.isArray(i?.gateways)?i.gateways:[]).find(u=>u!==null&&typeof u=="object"&&Hi(u.url)!==void 0),d=Hi(l?.url);if(!d)throw new Error(i.connected===!0?"this enrollment link's gateway is running but hasn't advertised its public URL yet \u2014 ask your admin to set ANYRAY_GATEWAY_PUBLIC_URL (Helm: gateway.publicUrl), then re-run.":"this enrollment link has no gateway configured yet \u2014 ask your admin to confirm the gateway is deployed, then re-run.");return{gatewayUrl:d,deploymentId:Hi(l?.deploymentId),org:Hi(i.org),email:Hi(i.email),seatMode:i.seatMode===!0}};var Qx=()=>Km(),eI=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??Qx)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},UG=e=>{let t=String(e),n=[];for(let r=0;r<t.length;r++)t[r]==="\x1B"&&t[r+1]==="["&&t[r+2]?(n.push(t.slice(r,r+3)),r+=2):n.push(t[r]);return n},tI=async(e,t={})=>{let n=(t.openInput??Qx)(),r=n.stream,o=t.output??process.stderr;if(typeof r.setRawMode!="function")throw n.close(),new Error("raw terminal input is unavailable");let a=e.items.map(h=>h.selected===!0&&h.requiresExplicitChoice!==!0),s=0,i=0,c=Na(o,t.env??process.env),l=(h,m)=>c?`\x1B[${h}m${m}\x1B[0m`:m,d=()=>{let h=[l("1",e.title)];for(let m=0;m<e.items.length;m++){let w=e.items[m],g=m===s?l("36","\u276F"):" ",y=e.single?a[m]?"(\u25CF)":"(\u25CB)":a[m]?"[x]":"[ ]",b=w.hint?` ${l("2",w.hint)}`:"";h.push(`${g} ${y} ${w.label}${b}`)}h.push(l("2",e.single?"\u2191/\u2193 move \xB7 space choose \xB7 enter accept \xB7 q cancel":"\u2191/\u2193 move \xB7 space toggle \xB7 a toggle all \xB7 enter accept \xB7 q cancel")),i>0&&o.write(`\x1B[${i}A`),o.write(h.map(m=>`\r\x1B[2K${m}`).join(`
688
688
  `)),o.write(`
689
689
  `),i=h.length},u=()=>{i!==0&&(o.write(`\x1B[${i}A`),o.write(Array.from({length:i},()=>`\r\x1B[2K
690
- `).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,p=!1;try{return p=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((h,m)=>{let w=()=>{r.off("data",v),r.off("end",b),r.off("close",b),r.off("error",A)},g=E=>{w(),h(E)},y=E=>{w(),m(E)},b=()=>g({kind:"cancelled"}),A=E=>y(E),v=E=>{try{for(let I of DG(E)){if(I===""||I==="\x1B"||I==="q"){g({kind:"cancelled"});return}if(e.items.length===0){(I==="\r"||I===`
691
- `)&&g({kind:"ok",values:[]});continue}if(I==="\x1B[A"||I==="k")s=(s-1+e.items.length)%e.items.length,d();else if(I==="\x1B[B"||I==="j")s=(s+1)%e.items.length,d();else if(I===" "){if(e.single){let C=!a[s];a.fill(!1),a[s]=C}else a[s]=!a[s];d()}else if(I==="a"&&!e.single){let C=e.items.map((T,$)=>({item:T,index:$})).filter(({item:T})=>T.requiresExplicitChoice!==!0),x=!C.every(({index:T})=>a[T]);for(let{index:T}of C)a[T]=x;d()}else if(I==="\r"||I===`
692
- `){g({kind:"ok",values:e.items.filter((C,x)=>a[x]).map(C=>C.value)});return}}}catch(I){y(I)}};r.on("data",v),r.on("end",b),r.on("close",b),r.on("error",A)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),p&&r.setRawMode(f)}catch{}n.close()}};var tx=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],NG=80,Hi=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&Da(r,n.env??process.env)))return r.write(`${e}
693
- `),t();let a=0,s=()=>{r.write(`\r${tx[a++%tx.length]} ${e}`)};s();let i=setInterval(s,NG);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as $G}from"node:fs";import{spawnSync as MG}from"node:child_process";import{chmod as FG,copyFile as cy,lstat as ly,mkdir as Wa,readdir as dy,realpath as ou,rename as ru,rm as _t,stat as UG,symlink as BG,writeFile as WG}from"node:fs/promises";import{createHash as HG}from"node:crypto";import{basename as sy,dirname as Lr,join as pt}from"node:path";import{Readable as KG}from"node:stream";import{pipeline as GG}from"node:stream/promises";var nx="https://github.com/anyrayHQ/install/releases",rx="connect-v",jG=new RegExp(`/releases/tag/${rx}([0-9][0-9A-Za-z.-]*)$`),VG=300*1024*1024,au=1e4,YG=5*6e4,ZG=360*6e4,JG=30*6e4,Ha=(e,t)=>{let n=s=>s.split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),r=n(e),o=n(t);for(let s=0;s<Math.max(r.length,o.length);s++){let i=(r[s]??0)-(o[s]??0);if(i!==0)return i<0?-1:1}let a=s=>s.includes("-")?0:1;return a(e)-a(t)},ox=(e,t)=>{let n=t==="arm64"?"arm64":t==="x64"?"x64":void 0;if(n){if(e==="darwin")return`anyray-connect-darwin-${n}`;if(e==="linux")return`anyray-connect-linux-${n}`;if(e==="win32")return"anyray-connect-windows-x64.exe"}},XG=e=>{if(e)return jG.exec(e.trim())?.[1]},uy=(e,t)=>{for(let n of e.split(`
694
- `)){let[r,o]=n.trim().split(/\s+/);if(!r||!o)continue;if((o.startsWith("*")?o.slice(1):o)===t&&/^[0-9a-f]{64}$/i.test(r))return r.toLowerCase()}},ax=e=>{if(e.latest===e.current)return{apply:!1,mandatory:!1};if(e.autoUpdate||e.forced)return{apply:!0,mandatory:!1};let t=!!e.minVersion&&Ha(e.current,e.minVersion)<0&&Ha(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},zG=e=>Ha(e.latest,e.current)<0?{apply:!1,mandatory:!1,downgradeBlocked:!0}:e.latest===e.current?{apply:e.autoUpdate||e.forced===!0,mandatory:!1,downgradeBlocked:!1}:{...ax(e),downgradeBlocked:!1},Ka=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",qG=(e=process.execPath)=>{let t=Bu(e);return t?Lr(t):Lr(Lr(e))},QG=async(e=ht())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=pt(qG(e.execPath),"bin",Ka());try{if(await ou(t)!==await ou(e.execPath))return}catch{return}return t},py=async(e=ht(),t=Q())=>{let n=await QG(e);if(n)return{kind:"managed",root:Lr(Lr(n)),link:n,entryPath:er(e)};let r=er(e);return Hu(r,t)?{kind:"durable",root:t,entryPath:r}:Fu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},su=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(o)}},fy=async(e=au)=>{let t=await su(`${nx}/latest`,e,{redirect:"manual"});return XG(t.headers.get("location"))},ej=async e=>{try{let t=await su(`${e}/connect-update.json`,au);if(!t.ok)return;let n=await t.json();if(!n||typeof n!="object")return;let r=n.minVersion;return typeof r=="string"&&/^\d+\.\d+\.\d+/.test(r)?r:void 0}catch{return}},Ki=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},hy=async(e,t,n)=>{let r=await su(e,YG);if(!r.ok||!r.body)throw new Ki(r.status);let o=HG("sha256"),a=0;if(await GG(KG.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>VG)throw new Error("asset exceeds size cap");o.update(c),yield c}},$G(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},tj=e=>sy(e)===Ka()?sy(Lr(e)):sy(e),nj=async e=>{let t=await dy(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await _t(pt(e,n),{force:!0}).catch(()=>{})},sx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await _t(r,{force:!0}).catch(()=>{});let o=!1;try{await ru(e,r),o=!0}catch{}try{await cy(t,e),await WG(as(e),tj(t))}catch(a){throw o&&await ru(r,e).catch(()=>{}),a}await _t(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await _t(n,{force:!0}),await BG(t,n),await ru(n,e)},rj=async(e,t={})=>{let n=pt(e.root,"bin"),r=pt(e.root,"versions"),o=pt(n,Ka());await Wa(n,{recursive:!0,mode:448}),await Wa(r,{recursive:!0,mode:448});let a=pt(r,e.version),i=(await ly(a).catch(()=>{}))?.isFile()?a:pt(a,Ka());if(!(await ly(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??su)(`${e.tagUrl}/SHA256SUMS`,au),d=l.ok?uy(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await Wa(Lr(i),{recursive:!0,mode:448}),await nj(Lr(i));let u=`${i}.part-${process.pid}`;try{await(t.download??hy)(`${e.tagUrl}/${e.asset}`,u,d),await FG(u,493),await ru(u,i)}catch(f){throw await _t(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??sx)(o,i),{link:o,target:i,versionsDir:r}},oj=async e=>{let t=MG(e,["--version"],{stdio:"ignore",timeout:au});return!t.error&&t.status===0},aj=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??bo)(n);if(r.length>0){let o=await(t.resolveTarget??_e)(async()=>e);if(!o||!(await(t.repair??yt)(r,o.target)).every(wo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??dr)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Nt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},sj=async e=>{let t=await e.install();if(!await(e.smoke??oj)(t.target))throw await e.rollback?.(t),new Error("managed binary smoke test failed");if(!await e.repoint(t.link))throw new Error("persistent config repoint failed");return await e.prune(),t},ij=async(e,t)=>{let n=await dy(e).catch(()=>[]);for(let r of n)t.includes(r)||await _t(pt(e,r),{force:!0,recursive:!0}).catch(()=>{})},cj=async e=>{let t=await dy(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await _t(pt(e,n),{force:!0}).catch(()=>{})},lj=async(e,t)=>{let n=async()=>{await _t(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Wa(e,{recursive:!1}),n}catch{}let r=await UG(e).catch(()=>{});if(!(!r||t-r.mtimeMs<JG)){await n();try{return await Wa(e,{recursive:!1}),n}catch{return}}},iy=e=>pt(e,"update-state.json"),dj=async e=>{let t=await U(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},uj=1e3,pj=16*6e4,fj=e=>e.inFlight===0,hj=async(e,t,n={})=>{let r=n.probe??be,o=n.sleep??(i=>new Promise(c=>setTimeout(c,i))),a=n.now??Date.now,s=a()+(n.timeoutMs??pj);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&fj(i))return!0;if(a()>=s)return!1;await o(uj)}},Gi=async(e={})=>{let t=e.now??Date.now,n=we;if(Ct(mt(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ht(),o=e.root??Q(),a;try{let s=await py(r,o);if(o=s.root,s.kind==="unmanaged")return{outcome:"unmanaged",current:n};if(s.kind==="npm"&&!e.allowNpmMigration)return{outcome:"unmanaged",current:n};let i=s.kind!=="managed",c=ox(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??fy)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&Ha(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await dj(iy(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<ZG)return{outcome:"failed",current:n,latest:l};let f=`${nx}/download/${rx}${l}`,p=await(e.load??L)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??ej)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?zG(w):{...ax(w),downgradeBlocked:!1};if(g.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:l};if(!g.apply)return{outcome:"disabled",current:n,latest:l};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:l,mandatory:g.mandatory};o===Q()?await kt():await Wa(o,{recursive:!0,mode:448});let y=await lj(pt(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,A;try{await cj(pt(o,"bin"));let I=await ou(pt(o,"versions")).catch(()=>{}),C=await ou(pt(o,"bin",Ka())).catch(()=>{}),x=C&&mc(C,I)?C:void 0,T=pt(o,"bin",Ka());i&&process.platform==="win32"&&(await ly(T).catch(()=>{}))?.isFile()&&(A=`${T}.rollback-${process.pid}`,await cy(T,A));let $=()=>(e.installBinary??rj)({root:o,version:l,asset:c,tagUrl:f});i?b=await sj({install:$,smoke:e.smoke,rollback:async({link:Y,target:Z})=>{A?(await cy(A,Y),await _t(as(Y),{force:!0}).catch(()=>{})):x&&x!==Z?await sx(Y,x):(await _t(Y,{force:!0}),await _t(as(Y),{force:!0}).catch(()=>{}))},repoint:async Y=>e.repoint?e.repoint(p,Y):aj(p),prune:async()=>{await(e.pruneDurable??(Y=>yc(Y)))(r)}}):b=await $(),await ij(b.versionsDir,[l,n]),await _t(iy(o),{force:!0}).catch(()=>{})}finally{A&&await _t(A,{force:!0}).catch(()=>{}),await y()}let v=e.bounceDaemon??np,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let I=p.fallbackPort??ke,C=E?!0:await gw().catch(()=>!0),x=await v(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!C&&p.gateway&&((x?await(e.waitForDaemon??hj)(I,l):!0)?await Nt({port:I,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??bw)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await J(iy(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},ix=async(e={})=>{let t=e.context??ht(),n=await py(t,e.root??Q()),r=Fo(e.root??Q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:we,managedPath:n.link??r}:Gi({...e,context:t,allowNpmMigration:!0})},Ro=async(e={})=>{let t=e.context??ht(),n=e.root??Q(),r=await py(t,n),o=r.kind==="npm"||r.kind==="durable"?Fo(n):void 0,a=await(e.load??L)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!ox(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=Ct(mt(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:we,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};var mj=async(e,t)=>{if(!e.gateway||!e.clientKey)return;let n=await t().catch(()=>{});return ge({origin:e.gateway,clientKey:e.clientKey,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:n,user:e.name,team:e.team})},cx=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,yj=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},my=async(e={})=>{let t=e.load??L,n=e.save??re,r=e.mutate??(e.load||e.save?yj(t,n):xg),o=e.loadDevKey??We,a=e.heartbeat??Id,s=e.detectSeat??$t,i=e.rewriteTools??vi,c=e.uninstallProxy??Qt;try{let l=await t();if(l.credentialProtocol==="stable-heartbeat-v1"&&l.directMigration==="complete")return"already-direct";if(!l.keyRefreshEnabled&&!l.refreshSchedulerEnabled||!l.gateway||!l.clientKey||!l.enrolledCert)return"not-eligible";let d=l.enrolledCert.sig,u=await o();if(!u)return"not-eligible";let f;try{f=await a(l.gateway,l.clientKey,l.enrolledCert,u)}catch(y){return y instanceof Ir&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!cx(y,l))return{result:void 0};let b={...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"pending"};return{next:b,result:b}});if(!p)return"pending";let h=await mj(p,s);if(!h)return"pending";let m=l.keyRefreshEnabled===!0,w=Number.isInteger(l.fallbackPort)&&l.fallbackPort>0&&l.fallbackPort<=65535?l.fallbackPort:ke;if(m){let y=`http://${ft}:${w}`;if(await i(h,y)===!1)return"pending"}return await r(y=>y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||y.credentialProtocol!=="stable-heartbeat-v1"||y.directMigration!=="pending"||!cx(y,p)?{result:!1}:{next:{...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"complete",keyRefreshEnabled:!1,fallbackPort:void 0},result:!0})?((m||l.fallbackPort!==void 0)&&await c(w).catch(()=>{}),"migrated"):"pending"}catch{return"pending"}};import{z as lx}from"zod";var gj=5e3,wj=lx.object({lane:lx.enum(["subscription","org"]).optional().catch(void 0)}),dx=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??gj);try{let a=await(n.fetchResponse??fetch)(`${e.replace(/\/$/,"")}/connect/policy`,{headers:{"x-anyray-api-key":t.trim()},signal:r.signal});if(!a.ok)return;let s=wj.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},ux=(e,t)=>{if(!e||t.byoUpstream)return{overrodeFlag:!1};let n=t.subscription?"subscription":t.org?"org":void 0;return{lane:e,overrodeFlag:n!=null&&n!==e}};var bj=12e3,kj="anyray-wiring-probe-not-a-real-token",Cj={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},gy={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},Oo=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},fx=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},wy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},px=e=>["Note: OpenCode\u2019s Claude provider can ONLY use a server-side key \u2014 unlike","Claude Code, it has no personal-subscription path. For Claude, either:",...e," \u2022 use Claude Code with your own Claude subscription instead of OpenCode.","OpenCode ChatGPT OAuth uses a non-configurable endpoint. Use Codex for"," config-native ChatGPT subscription pass-through, or use an OpenCode"," API-key/Copilot provider that Connect can route."],Aj=e=>e.includes("no provider key configured for"),by=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},ky=e=>({kind:"enrollment-required",detail:`gateway requires per-developer enrollment (HTTP ${e}).`,remedy:["This gateway only serves enrolled developers. Re-run with your enrollment","link from your admin so connect can mint your personal key automatically:"," anyray-connect --enroll <link>"]}),ji=e=>({kind:"key-rejected",detail:`gateway rejected the client key (HTTP ${e}).`,remedy:["The gateway did not receive a usable personal key (missing, unknown, expired,","or revoked). Re-run `anyray-connect` to refresh an existing enrollment, or","use `--enroll` / `--sso` to enroll first."]}),vj=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:e===401||e===403?by(t)?ky(e):wy(t)?ji(e):fx(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Oo(t)}`,remedy:["The org provider rejected the request \u2014 check the gateway\u2019s provider","key/config (e.g. the model is enabled for that account)."]}:Aj(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Oo(t)}`,remedy:["Your enrollment key is fine \u2014 the gateway has NO server-side provider","key configured (org-key mode), so it refused to forward the request.","Fix: add a provider key in the console \u2192 Providers.",...n.includes("opencode")?px([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${Oo(t)}`,remedy:n.includes("opencode")?["Your enrollment key is fine \u2014 the gateway forwarded the request and the","upstream model provider refused the credential it was given: this","gateway has no WORKING provider key for it (either none is configured,","or the configured one is wrong or revoked).",...px([" \u2022 open the console \u2192 Providers and add a key for that provider, or"," replace the one already listed (fixes it for everyone), or"])]:["Your enrollment key is fine \u2014 the gateway forwarded the request and the","upstream model provider refused it.","Open the console \u2192 Providers: if no key is listed for that provider,","add one; if a key IS listed, it is wrong, revoked, or not entitled to","the model \u2014 replace it.","Either way this is gateway config, not your enrollment. Alternatively,","sign in with your own provider subscription instead of the org key.","If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]}:{kind:"unknown",detail:`gateway responded HTTP ${e}: ${Oo(t)}`,remedy:[]},Sj=(e,t)=>{if(wy(t))return ji(e);if(by(t))return ky(e);if(fx(t))return{kind:"routed-elsewhere",detail:"gateway sent the request to the org provider, not your subscription.",remedy:["Pass-through isn\u2019t being honored for this gateway \u2014 your seat token would","not be used. Check the gateway is current (subscription pass-through support)."]};let n=t.toLowerCase();return e===401||n.includes("authentication_error")||n.includes("invalid bearer")||n.includes('"provider":"anthropic"')?{kind:"ok",detail:"gateway passes your sign-in through to Anthropic \u2014 your Claude seat will be used.",remedy:[]}:e>=200&&e<300?{kind:"ok",detail:"gateway pass-through reached the provider \u2014 your seat will be used.",remedy:[]}:{kind:"unknown",detail:`seat-wiring probe got HTTP ${e}: ${Oo(t)}`,remedy:[]}},Ej=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),Ij=(e,t)=>{if(wy(t))return ji(e);if(by(t))return ky(e);let n=t.toLowerCase();if(n.includes("bedrock"))return{kind:"routed-elsewhere",detail:"gateway routed to the org provider instead of the configured BYO upstream.",remedy:["Re-run anyray-connect with your --upstream URL and --upstream-key so","the custom-host pass-through pins are restored."]};if(n.includes("invalid custom host")||n.includes("custom_host_blocked")||n.includes("hostname is not authorized"))return{kind:"routed-elsewhere",detail:"gateway rejected the configured BYO upstream before routing to it.",remedy:["Ask the gateway admin to authorize this LiteLLM/upstream hostname in","ANYRAY_CUSTOM_HOST_ALLOWLIST (or TRUSTED_CUSTOM_HOSTS for an internal host)."]};if(e===401||e===403)return{kind:"provider-rejected",detail:`gateway accepted your personal key but the BYO upstream rejected its credential (HTTP ${e}).`,remedy:["Your Anyray enrollment key is fine. The configured personal upstream key","was rejected by the BYO upstream (for example, LiteLLM). Re-run","anyray-connect with a current --upstream-key."]};let r=e>=400&&e<500&&(n.includes("litellm")||Ej(n));return e>=200&&e<300||r?{kind:"ok",detail:e>=200&&e<300?"gateway served a completion through the configured BYO upstream.":`gateway authenticated and reached the configured BYO upstream, which rejected this probe's fixed model (HTTP ${e}).`,remedy:[]}:{kind:"unknown",detail:`BYO-upstream probe got HTTP ${e}: ${Oo(t)}`,remedy:[`The probe asks for a fixed model (${gy.model}) your upstream`,"is not required to serve, so a model rejection here does not mean your","tools are broken. Check that the upstream serves it before chasing this."]}},yy=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),r);try{let s=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...t},body:JSON.stringify(n),signal:o.signal});return{status:s.status,bodyText:await s.text()}}finally{clearTimeout(a)}},xj=async(e,t)=>{if(!e.clientKey)return ji(401);let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`${e.origin}/connect/savings`,{method:"GET",headers:{"x-anyray-api-key":e.clientKey},signal:n.signal}),a=await o.text();return o.ok?{kind:"ok",detail:"gateway accepted your personal key \u2014 Cursor hooks/MCP can report and retrieve.",remedy:[]}:o.status===401||o.status===403?ji(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Oo(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},Rj=(e,t)=>{let n=typeof t?.code=="string"?` ${t.code}`:"";return{kind:"unreachable",detail:`could not reach the gateway to verify (${t instanceof Error&&t.name==="AbortError"?`no response within ${e}ms`:t instanceof Error?`${t.name}${n}`:"unknown error"}).`,remedy:["Your config was still written \u2014 re-run the curl below once the gateway is reachable."]}},Vi=async(e,t={})=>{let n=t.timeoutMs??bj,r=de(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await xj(e,n);if(e.byoUpstream){let l={Authorization:`Bearer ${e.byoUpstream.key}`,"anthropic-version":"2023-06-01","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic","x-anyray-custom-host":e.byoUpstream.url};e.clientKey&&(l["x-anyray-api-key"]=e.clientKey),r&&(l["x-anyray-metadata"]=r);let{status:d,bodyText:u}=await yy(`${e.anthropicBaseUrl}/v1/messages`,l,gy,n);return Ij(d,u)}if(X(e,"anthropic")){let l={Authorization:`Bearer ${kj}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"};r&&(l["x-anyray-metadata"]=r),e.clientKey&&(l["x-anyray-api-key"]=e.clientKey);let{status:d,bodyText:u}=await yy(`${e.anthropicBaseUrl}/v1/messages`,l,gy,n);return Sj(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await yy(`${e.openaiBaseUrl}/chat/completions`,s,Cj,n);return vj(i,c,t.tools??[])}catch(o){return Rj(n,o)}};var hx=async e=>{let t=await L(),n;try{n=_r(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),M(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${tt(n)}`),t.gateway?M(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?M(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||M(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??S("(not set)")}`),k(` Team: ${t.team??S("(not set)")}`);let r=mt();r&&(K("Environment"),k(` Remote dev context: ${cr(r)}`),Ct(r)&&M(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),M(" VS Code tools configure the remote server variant backing this window.")),t.credentialProtocol==="stable-heartbeat-v1"&&(K("Credential renewal"),t.directMigration==="pending"?(k(" Stable-key heartbeat active; direct-routing migration is still completing."),M(" The local proxy remains available until every managed tool moves.")):(F(" Direct gateway routing with a proof-backed stable-key heartbeat."),M(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(nt(t)&&t.fallbackPort),a=o?`http://${ft}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await be(t.fallbackPort)?F(` Running on 127.0.0.1:${t.fallbackPort} \u2192 ${n} `+S("(auto-refreshes your key so long sessions never 401)")):(D(` Enabled on 127.0.0.1:${t.fallbackPort} but NOT responding \u2014 your tools cannot reach any gateway until it's back.`),k(S(" Re-run `anyray-connect`, or check the service logs.")))),K("Tools");for(let s of se){if(!(await s.detect()).installed){M(` ${s.title}: not installed`);continue}if(!s.pointsAt){M(` ${s.title}: installed ${S("(status not introspectable)")}`);continue}let c=await s.pointsAt(Di(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){F(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(S(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}F(` ${s.title}: pointed at Anyray${o&&Li(s.id)?S(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===Fa&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await jd();l=Vd({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:f.authoritative}),d={...f.authoritative?{}:{reason:f.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=Yd(l,d);D(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(S(` ${f}`))}else M(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as Dj}from"node:fs";import{isAbsolute as Nj}from"node:path";import{access as Oj}from"node:fs/promises";import{constants as _j}from"node:fs";import{platform as Tj}from"node:os";var Pj=async e=>{try{return await Oj(e,_j.F_OK),!0}catch{return!1}},Lj=e=>e==="darwin"?["/Library/LaunchDaemons/com.fleetdm.orbit.plist","/opt/orbit/bin/orbit"]:e==="linux"?["/etc/systemd/system/orbit.service","/usr/lib/systemd/system/orbit.service","/opt/orbit/bin/orbit"]:e==="win32"?["C:\\Program Files\\Orbit\\bin\\orbit\\orbit.exe"]:[],_o=async(e={})=>{let t=e.os??Tj(),n=e.exists??Pj;for(let r of Lj(t))if(await n(r))return!0;return!1};var Zt="connect",Cy=e=>e.replace(/-/g,"_"),mx=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Zt,checkId:"gateway_reachable",status:e.gateway.reachable?"ok":"unreachable"});let n=Date.parse(e.report.generatedAt),r=Date.parse(e.enrollment.expiresAt??""),o=e.enrollment.enrolled&&e.enrollment.expired===!1&&Number.isFinite(n)&&Number.isFinite(r)&&r-n<=336*60*60*1e3;if(t.push({tool:Zt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Zt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:Zt,checkId:"fallback_proxy",status:e.fallbackProxy.healthy===!1?"fail":e.fallbackProxy.healthy===!0?"ok":"unknown"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:Zt,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:Zt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Zt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=Cy(e.retrieval.kind);t.push({tool:Zt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":Cy(e.verify.kind);t.push({tool:Zt,checkId:"auth_verify",status:c,...i?{errorClass:"verify_not_applicable_subscription"}:c==="ok"?{}:{errorClass:`verify_${c}`}})}for(let i of e.tools)!i.installed||i.claudeCodeHookPolicy===void 0||t.push({tool:i.id,checkId:"hook_policy",status:i.claudeCodeHookPolicy==="fine"?"ok":i.claudeCodeHookPolicy});if(e.hookLane&&e.hookLane.verdict!=="indeterminate"){let i=e.hookLane.verdict==="dark";t.push({tool:Zt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:Cy(e.hookLane.reason)}:{}})}t.push({tool:Zt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:Zt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function $j(){return we}var Mj="ctx_doctor-probe-synthetic",Fj=(e,t={mode:"unknown",ssoLink:null})=>{if(e.ok||e.kind==="not-found")return{kind:"ok",detail:"Retrieval loop healthy: gateway answered, key authorized, optimizer retrieval wired.",remedy:[]};switch(e.kind){case"auth":return{kind:"auth",detail:"The gateway rejected the retrieval call (no valid personal key).",remedy:[`Fix: ${Sy(t.mode,t.ssoLink)}, or set ANYRAY_CLIENT_KEY.`,"Retrieval needs a personal key \u2014 the MCP server hits the same wall, so externalized output is unretrievable until this is fixed."]};case"unsupported":return{kind:"unsupported",detail:"The gateway has no /connect/retrieve route.",remedy:["Fix: update the gateway image \u2014 this one predates the retrieval loop."]};case"timeout":case"network":return{kind:"unreachable",detail:`Could not reach the gateway for the retrieval probe (${e.kind}).`,remedy:["Fix: check the gateway origin and network (see the Gateway section above)."]};default:return{kind:"unavailable",detail:e.message,remedy:["Fix: the gateway answered but retrieval is unavailable \u2014 usually the optimizer is down or ANYRAY_OPTIMIZER_URL is unset on the gateway. Check the optimizer service."]}}};function Uj(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function Bj(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Sy(e,t){let n=`\`anyray-connect --sso ${t??"<link>"}\``,r="`anyray-connect --enroll <link>`";switch(e){case"sso":return`enroll via SSO with ${n}`;case"passwordless":return`enroll with the link from your admin (${r})`;default:return`enroll \u2014 SSO org: use ${n}; passwordless org: use ${r} (link from your admin)`}}var yx=e=>Vd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),Ay=e=>e.pointedAt===!1&&e.tombstoned!==!0&&yx(e)!=="unverifiable",gx=e=>e.registered&&e.command&&Nj(e.command)?Dj(e.command):null,vy=e=>(Ay(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),Wj=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,Hj=async(e,t)=>{if(e.length===0)return!1;for(let n of e){let r=t.find(a=>a.id===n);if(!r?.inferenceAuthLanes)return!1;let o=await r.inferenceAuthLanes().catch(()=>["unknown"]);if(o.length===0||o.some(a=>a!=="subscription"&&a!=="native"))return!1}return!0},wx=async e=>{for(let t of e)if(t.integrationStatus)try{if(!(await t.detect()).installed)continue;if((await t.integrationStatus()).hook_registration==="owned")return!0}catch{}return!1},Kj=(e,t)=>{let n=c=>typeof c=="object"&&c!==null&&!Array.isArray(c),r=c=>typeof c=="number"&&Number.isSafeInteger(c)&&c>=0&&Number.isFinite(new Date(c).getTime()),o=new Set(t.map(c=>c.id)),a=new Set(Ao),s=[],i=n(e.selfcheck?.adapters)?e.selfcheck.adapters:{};for(let[c,l]of Object.entries(i)){if(!o.has(c)||!n(l))continue;let d=n(l.lastRepaired)?l.lastRepaired:{},u=Object.entries(d).filter(w=>a.has(w[0])&&r(w[1])).map(([w,g])=>({checkId:w,at:g})),f=n(l.flapping)?l.flapping:void 0,p=Array.isArray(f?.checks)?f.checks.filter(w=>typeof w=="string"&&a.has(w)):[],h=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,m=f&&r(f.since)&&h&&p.length>0?{since:f.since,reason:h,checks:p}:void 0;(u.length>0||m)&&s.push({tool:c,repaired:u,...m?{flapping:m}:{}})}return s},Gj=async(e,t,n,r,o,a,s=n,i=Vi,c=!0,l=Eo,d=Ro,u=Gt,f=Ra)=>{let p=c?await tu(e):null,h=!!(nt(t)&&t.fallbackPort),m=h?await be(t.fallbackPort):null,w=h?`http://${ft}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=V=>V&&Um(V)?"machine_default":null,b=t.enrolledCert?.payload,A=b?.expiresAt??t.enrolledCertExpiry??null,E=(await a())?.sso??null,I=Bj({ssoLink:E,enrolledViaToken:!!t.enrolledTokenHash}),C=At(),x=await Zw(C),T=x?[]:Qw(ge({origin:w})),$=[];for(let V of r){let Ee=await V.detect(),bt=null;if(Ee.installed&&V.mcpStatus)try{let qa=await V.mcpStatus();bt={...qa,commandOk:gx(qa)}}catch{}let qn=Ee.installed&&V.id===Fa?await o():void 0,Tt=Ee.installed&&V.pointsAt?await V.pointsAt(Di(V.id,e,w)):null,$r=await Wj(Tt,V,t.managedTools??[]),Mr=Tt===!1&&$r===null,Za=$r===!1&&V.routingPendingReload?await V.routingPendingReload().catch(()=>!1):!1,oc=Ee.installed?V.runtimeDiagnostics?await V.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:V.routingOverrides?await V.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Po,claudeCodeHookPolicy:Ja}=oc,Xa=t.fleetToolPolicy,za=Xa?.enabled.includes(V.id)?Xa.tiers?.[V.id]??Ea:void 0;$.push({id:V.id,title:V.title,installed:Ee.installed,...Ee.detail?{detail:Ee.detail}:{},pointedAt:$r,...Mr?{routingHeld:!0}:{},...Za?{routingPendingReload:!0}:{},...Po.length?{routingOverrides:Po}:{},...Ja===void 0?{}:{claudeCodeHookPolicy:Ja},mcp:bt,...za?{policyTier:za}:{},...t.revertedTools?.includes(V.id)?{tombstoned:!0}:{},...V.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...qn===void 0?{}:{inferenceIntrospectable:qn.authoritative,...qn.authoritative?{}:{inferenceUnverifiableReason:qn.reason}}})}let Y=s?await(async()=>{let{kind:V,detail:Ee,remedy:bt}=await i(ge({origin:e,clientKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey,subscription:t.authMode==="subscription",placeholder:t.authMode==="placeholder",byoUpstream:t.byoUpstream,...t.authMode==="auto"?{seat:{anthropic:!1,openai:!1,copilot:!1}}:{},user:t.name,team:t.team}),{tools:t.managedTools??[]});return{kind:V,detail:Ee,remedy:bt}})():null,Z=Y?.kind==="provider-rejected"&&await Hj(t.managedTools??[],r),W=Y?{...Y,...Z?{notApplicableSubscription:!0}:{}}:null,z=n?Fj(await xa({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:de({user:t.name,team:t.team})},Mj,{probe:!0}),{mode:I,ssoLink:E}):null,me=await u().catch(()=>({})),Le=Sn(me.hookLane),ne=s?await wx(r):!1,Ke=ne?await(async()=>{let V=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...lm(V,{hookRegistered:ne,neverInvoked:im(Le,Date.now())}),lastInvokedAt:Rd(Le)}})():null,De=(await pr()).map(V=>({adapter:V.adapter,op:V.op,requestedAt:V.requestedAt,watcherAlive:hr(V.watcherPid)})),O=De.find(V=>V.adapter==="cursor"),P=O?{op:O.op,requestedAt:O.requestedAt,watcherAlive:O.watcherAlive}:null,H=!!t.refreshSchedulerEnabled,fe=await Yo(),q=await d(),Ye=t.persistenceOwner==="tray",Ue=Ye?await l(t)==="healthy":null,ee=await EE({daemonEnabled:h&&!Ye,daemonHealthy:h?!!m:null,schedulerEnabled:H&&!Ye,schedulerInstalled:fe,binaryDurable:!je(ir())}),Be=await Du(),Ne=0;p&&!p.reachable&&(Ne+=1),h&&!m&&(Ne+=1),Ye?H&&!Ue&&(Ne+=1):H&&!fe&&(Ne+=1);for(let V of $)Ne+=vy(V);return W&&W.kind!=="ok"&&!W.notApplicableSubscription&&(Ne+=1),z&&z.kind!=="ok"&&(Ne+=1),Ke?.verdict==="dark"&&(Ne+=1),T.length>0&&(Ne+=1),Ne+=De.filter(V=>!V.watcherAlive).length,Be.length>0&&(Ne+=1),{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:$j(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:mt(),selfUpdate:{managed:q.managed,available:q.available,autoUpdate:q.autoUpdate,state:q.state}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},toolOrigin:w,fallbackProxy:{enabled:h,port:h?t.fallbackPort:null,healthy:h?!!m:null},refreshScheduler:{enabled:H,installed:fe,owner:Ye?"tray":"os",...Ye?{trayHealthy:!!Ue}:{}},serviceRemoval:ee,retiredFallbackState:Be,fleetdPresent:await _o(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:y(t.name)},enrollment:{enrolled:!!b,deploymentId:b?.deploymentId??null,issuedAt:b?.issuedAt??null,expiresAt:A,expired:A?Date.parse(A)<Date.now():null,orgMode:I,ssoLink:E},shell:{profilePath:C,blockPresent:x,staleExports:T},tools:$,...t.fleetToolPolicy?{fleetPlan:Cd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:P,pendingOps:De,ambientRepairs:Kj(me,r),verify:W,retrieval:z,hookLane:Ke,problems:Ne}},jj=e=>{if(e.serviceRemoval.suspected){K("Endpoint security"),D(" Anyray installed these background services, but their files are gone from disk \u2014"),D(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),D(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)k(S(` missing: ${t}`));k(S(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(S(" tools straight at the gateway (your key then needs a periodic re-run).")),k(S(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(S(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},Vj=e=>{if(e.retiredFallbackState.length!==0){K("Retired fallback lane"),_(" A cached organization provider key from the removed --fallback lane is still on this machine.");for(let t of e.retiredFallbackState)k(S(` ${t}`));k(S(" Fix: `anyray-connect doctor --repair` deletes it (a normal `anyray-connect` run does too)."))}},Yj=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${cr(e.connect.remoteContext)}`),Ct(e.connect.remoteContext)&&k(S(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),K("CLI updates"),e.connect.selfUpdate.state){case"managed":F(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||D(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":D(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),k(S(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":D(" Self-update is unavailable on this platform because no standalone binary is published."),k(S(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(S(" This copy is externally managed; update it with the method that installed it."));break;case"container":k(S(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(K("Gateway"),e.gateway.reachable===null?k(S(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?F(` Reachable: ${e.gateway.origin} ${S(`(${e.gateway.detail})`)}`):(_(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),k(S(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.fallbackProxy.enabled&&(K("Local key-refresh proxy"),e.fallbackProxy.healthy?F(` Running on 127.0.0.1:${e.fallbackProxy.port} \u2192 ${e.gateway.origin} `+S("(auto-refreshes your key so long sessions never 401)")):(_(` Enabled on 127.0.0.1:${e.fallbackProxy.port} but NOT responding \u2014 your tools point at it and cannot reach any gateway until it's back.`),e.serviceRemoval.kinds.includes("daemon")||k(S(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to point tools straight at the gateway.")))),e.refreshScheduler.enabled&&(K("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?F(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh and supervises the daemon."):(_(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),k(S(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?F(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(_(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||k(S(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),jj(e),Vj(e),K("Personal key"),Uj(e)){case"env":F(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":F(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":D(" Enrolled, but no personal key is cached locally right now."),k(S(" Fix: re-run `anyray-connect` to re-mint it from your enrollment \u2014 no need to re-enroll. Claude Code and Codex are still attributed to you by name."));break;default:D(" Enrollment required \u2014 no personal gateway key is available."),k(S(` Fix: ${Sy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?D(` Enrollment cert expired ${S(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):F(` Enrollment cert valid until ${e.enrollment.expiresAt} ${S(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(K("Shell"),_(" This terminal still exports Anyray, but the config is gone."),k(S(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(S(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(S(" Anything you start from this terminal keeps reaching the gateway with")),k(S(" no credential, and fails with 401.")),k(S(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(S(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(S(" reuses the environment it captured at launch, so a new terminal")),k(S(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};K("Claude Code hook policy"),_(` ${Ac(c)}.`),k(S(` ${vc(c)}`))}K("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])_(` ${c.title}: ${l.problem}.`),k(S(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(_(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),k(S(" Fix: re-run `anyray-connect` to re-register the current binary."))):F(` ${c.title}: retrieval MCP server registered ${S("(anyray_retrieve / anyray_recall)")}`):(D(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),k(S(" Fix: re-run `anyray-connect` from a durable install (registration is skipped for one-off npx runs)."))))};for(let c of e.tools){if(!c.installed){k(S(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){k(S(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){F(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),k(S(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}F(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&Li(c.id)?S(" (via key-refresh proxy)"):""}`),o(c),c.id==="claude-code"&&k(S(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===Fa&&k(S(` ${PC}`)),c.id==="codex"&&k(S(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=yx(c);if(l==="not-routed"||l==="unverifiable"){let d=Yd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});D(` ${c.title}: ${d.headline}`);for(let u of d.detail)k(S(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(D(` ${c.title}: reverted locally against admin policy (out of compliance)`),k(S(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?D(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):k(S(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(_(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),k(S(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(_(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),k(S(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(D(" No tools are pointed at this gateway yet."),k(S(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){K("Queued operations");for(let c of e.pendingOps){let l=Kt(c.adapter)?.title??c.adapter;c.watcherAlive?D(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(_(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),k(S(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){K("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=Kt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:p,at:h})=>`${c(p)} ${new Date(h).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?D(f):k(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){K("Fleet policy");let c=l=>l.map(d=>Kt(d)?.title??d).join(", ");i.freshIds.length>0&&k(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&D(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(K("Auth probe"),e.verify.notApplicableSubscription)F(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")F(` ${e.verify.detail}`);else{_(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(S(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")F(` ${e.retrieval.detail}`);else{_(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(S(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")F(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(S(` ${c}`))}else{D(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(S(` ${c}`))}e.hookLane.lastInvokedAt!==null&&k(S(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}K("Summary"),e.problems===0?(e.verify?F(" No problems found."):F(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(S(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):_(` ${e.problems} problem(s) found \u2014 see fixes above.`)},Zj=e=>({...e,verify:e.verify?{kind:e.verify.kind,detail:"",remedy:e.verify.remedy,...e.verify.notApplicableSubscription?{notApplicableSubscription:!0}:{}}:null,retrieval:e.retrieval?{kind:e.retrieval.kind,detail:"",remedy:e.retrieval.remedy}:null}),Jj=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!om(n.code))return{hookLane:n,note:`Hook lane: the gateway rejected this machine\u2019s key as '${n.code??"unclassified"}', which an automatic re-mint must never answer \u2014 no key was minted. Re-enroll (see the Hook lane fixes above).`};let r=t.probeHookLane??Ra,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??et)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=Sn((await(t.readRefreshState??Gt)().catch(()=>({}))).hookLane),l=lm(i,{hookRegistered:await wx(t.adapters??se).catch(()=>!1),neverInvoked:im(c,Date.now())}),d=s==="disabled"?"Hook lane: key refresh is disabled here (ANYRAY_REFRESH_DISABLE), so no key was minted and the finding stands.":l.verdict==="live"?"Hook lane: re-minted the personal key and rewrote the configured tools \u2014 the lane answers again.":l.verdict==="indeterminate"?`Hook lane: re-mint reported '${s}', but the confirming probe could not establish the lane's state \u2014 nothing is proven fixed and the finding stands.`:`Hook lane: re-mint reported '${s}' and the lane is still not live \u2014 re-enroll (see the Hook lane fixes above).`;return{hookLane:{...l,lastInvokedAt:Rd(c)},note:d}},Xj=async(e,t,n={})=>{let r=n.adapters??se,o=n.resolveTarget??_e,a=n.applyTools??yt,s=await Jj(e,n).catch(()=>null),i=s&&e.hookLane?.verdict==="dark"&&s.hookLane?.verdict==="live"?1:0,c=s?{hookLane:s.hookLane,notes:[s.note]}:{notes:[]},l=e.tools.filter(y=>y.installed&&(Ay(y)||y.mcp?.commandOk===!1||y.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t,void 0,be);if(!d)return{entries:l.map(y=>({id:y.id,title:y.title,status:"skipped-not-enrolled"})),remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,`Repair needs an enrolled personal key \u2014 ${Sy(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],p=[...c.notes],h=[];for(let y of l){let b=r.find(A=>A.id===y.id);if(!u.has(y.id)||!b){f.push({id:y.id,title:y.title,status:"skipped-unmanaged"});continue}h.push(b)}f.length>0&&p.push("Drifted tools outside the managed record are never auto-repaired \u2014 run `anyray-connect` once to (re)configure and record them.");let m=await a(h,d.target),w=new Map,g=0;for(let y of m){if(f.push(y),!wo(y))continue;let b=e.tools.find(T=>T.id===y.id);if(!b)continue;let A=r.find(T=>T.id===y.id),v=b.mcp;if(A?.mcpStatus)try{let T=await A.mcpStatus();v={...T,commandOk:gx(T)}}catch{}let E=Ay(b)?!0:b.pointedAt;if(A?.pointsAt&&b.pointedAt!==null)try{E=await A.pointsAt(Di(A.id,e.gateway.origin,e.toolOrigin))}catch{}let I=b.routingOverrides,C=b.claudeCodeHookPolicy;if(A?.runtimeDiagnostics)try{let T=await A.runtimeDiagnostics();I=T.routingOverrides.length?T.routingOverrides:void 0,C=T.claudeCodeHookPolicy}catch{}else if(A?.routingOverrides)try{let T=await A.routingOverrides();I=T.length?T:void 0}catch{}let x={...b,pointedAt:E,mcp:v,...I?{routingOverrides:I}:{},...C===void 0?{}:{claudeCodeHookPolicy:C}};I||delete x.routingOverrides,C===void 0&&delete x.claudeCodeHookPolicy,w.set(y.id,x),g+=vy(b)-vy(x)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},zj=e=>{K("Repair"),e.entries.length===0&&F(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?F(` ${t.title}: re-applied`):t.status==="queued"?F(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(S(` ${t.title}: ${t.status}`)):_(` ${t.title}: ${t.status}`);for(let t of e.notes)k(S(` ${t}`))},bx=async(e,t={})=>{let n=await L();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of IE(n.fallbackPort??ke))k(c?` ${c}`:"");return 0}let r;try{r=_r(e.gateway,n)}catch(c){return e.json?(console.log(JSON.stringify({error:c.message})),1):(k(j("Anyray connect \u2014 doctor")),_(` Gateway URL: ${c.message}`),k(S(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(k(j("Anyray connect \u2014 doctor")),_(" --quick skips the network probes; it cannot be combined with --verify.")),1;let o=!e.noVerify&&!e.quick,a=await Gj(r,n,!!e.verify&&!e.quick,t.adapters??se,t.inferenceIntrospection??jd,t.fleetBootstrap??Vt,o,t.verifyAuth??Vi,!e.quick,t.checkTray??Eo,t.updateStatus??Ro,t.readRefreshState??Gt,t.probeHookLane??Ra);e.repair&&a.retiredFallbackState.length>0&&(await pc(),a.retiredFallbackState=await Du(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await Xj(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;e.json?console.log(JSON.stringify(Zj(i),null,2)):(Yj(i),s&&zj(s));try{e.quick||await(t.reportHealth??yS)(mx(i),i.connect.version)}catch{}return i.problems===0?0:1};var qj=()=>{let e=[];for(let t of se){let n=t.skillsDir?.();n&&e.push(n)}return e},kx=async e=>{let t=await L();k(j("Anyray connect \u2014 sync"));let n;try{n=_r(e.gateway,t)}catch(s){return _(s.message),1}M(`Gateway: ${n}`);let r=nI(t.clientKey,"anyray-placeholder"),o;try{o=await vd(n,r)}catch(s){return _(`Team policy sync failed: ${Ad(s)}`),1}let a=qj();if(a.length===0)Qj();else if(o.skills.length===0)M("No team skills published yet \u2014 nothing to sync.");else{let s=await zv(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?F(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):M(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await re({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){M(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${tt(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Sd(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(k(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&M(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){M(`Fleet policy reconcile skipped: ${Ad(s)}`)}return 0},Qj=()=>{M("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as r2}from"node:zlib";import{promisify as o2}from"node:util";var Dr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Ey=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),Cx=e=>`
690
+ `).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,p=!1;try{return p=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((h,m)=>{let w=()=>{r.off("data",v),r.off("end",b),r.off("close",b),r.off("error",A)},g=E=>{w(),h(E)},y=E=>{w(),m(E)},b=()=>g({kind:"cancelled"}),A=E=>y(E),v=E=>{try{for(let x of UG(E)){if(x===""||x==="\x1B"||x==="q"){g({kind:"cancelled"});return}if(e.items.length===0){(x==="\r"||x===`
691
+ `)&&g({kind:"ok",values:[]});continue}if(x==="\x1B[A"||x==="k")s=(s-1+e.items.length)%e.items.length,d();else if(x==="\x1B[B"||x==="j")s=(s+1)%e.items.length,d();else if(x===" "){if(e.single){let C=!a[s];a.fill(!1),a[s]=C}else a[s]=!a[s];d()}else if(x==="a"&&!e.single){let C=e.items.map((P,$)=>({item:P,index:$})).filter(({item:P})=>P.requiresExplicitChoice!==!0),I=!C.every(({index:P})=>a[P]);for(let{index:P}of C)a[P]=I;d()}else if(x==="\r"||x===`
692
+ `){g({kind:"ok",values:e.items.filter((C,I)=>a[I]).map(C=>C.value)});return}}}catch(x){y(x)}};r.on("data",v),r.on("end",b),r.on("close",b),r.on("error",A)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),p&&r.setRawMode(f)}catch{}n.close()}};var nI=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],BG=80,Gi=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&Na(r,n.env??process.env)))return r.write(`${e}
693
+ `),t();let a=0,s=()=>{r.write(`\r${nI[a++%nI.length]} ${e}`)};s();let i=setInterval(s,BG);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as WG}from"node:fs";import{spawnSync as HG}from"node:child_process";import{chmod as KG,copyFile as dy,lstat as uy,mkdir as Ha,readdir as py,realpath as su,rename as au,rm as _t,stat as GG,symlink as jG,writeFile as VG}from"node:fs/promises";import{createHash as YG}from"node:crypto";import{basename as cy,dirname as Dr,join as pt}from"node:path";import{Readable as ZG}from"node:stream";import{pipeline as XG}from"node:stream/promises";var rI="https://github.com/anyrayHQ/install/releases",oI="connect-v",JG=new RegExp(`/releases/tag/${oI}([0-9][0-9A-Za-z.-]*)$`),qG=300*1024*1024,iu=1e4,zG=5*6e4,QG=360*6e4,ej=30*6e4,Ka=(e,t)=>{let n=s=>s.split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),r=n(e),o=n(t);for(let s=0;s<Math.max(r.length,o.length);s++){let i=(r[s]??0)-(o[s]??0);if(i!==0)return i<0?-1:1}let a=s=>s.includes("-")?0:1;return a(e)-a(t)},aI=(e,t)=>{let n=t==="arm64"?"arm64":t==="x64"?"x64":void 0;if(n){if(e==="darwin")return`anyray-connect-darwin-${n}`;if(e==="linux")return`anyray-connect-linux-${n}`;if(e==="win32")return"anyray-connect-windows-x64.exe"}},tj=e=>{if(e)return JG.exec(e.trim())?.[1]},fy=(e,t)=>{for(let n of e.split(`
694
+ `)){let[r,o]=n.trim().split(/\s+/);if(!r||!o)continue;if((o.startsWith("*")?o.slice(1):o)===t&&/^[0-9a-f]{64}$/i.test(r))return r.toLowerCase()}},sI=e=>{if(e.latest===e.current)return{apply:!1,mandatory:!1};if(e.autoUpdate||e.forced)return{apply:!0,mandatory:!1};let t=!!e.minVersion&&Ka(e.current,e.minVersion)<0&&Ka(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},nj=e=>Ka(e.latest,e.current)<0?{apply:!1,mandatory:!1,downgradeBlocked:!0}:e.latest===e.current?{apply:e.autoUpdate||e.forced===!0,mandatory:!1,downgradeBlocked:!1}:{...sI(e),downgradeBlocked:!1},Ga=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",rj=(e=process.execPath)=>{let t=Hu(e);return t?Dr(t):Dr(Dr(e))},oj=async(e=mt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=pt(rj(e.execPath),"bin",Ga());try{if(await su(t)!==await su(e.execPath))return}catch{return}return t},hy=async(e=mt(),t=Q())=>{let n=await oj(e);if(n)return{kind:"managed",root:Dr(Dr(n)),link:n,entryPath:nr(e)};let r=nr(e);return Gu(r,t)?{kind:"durable",root:t,entryPath:r}:Bu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},cu=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(o)}},my=async(e=iu)=>{let t=await cu(`${rI}/latest`,e,{redirect:"manual"});return tj(t.headers.get("location"))},aj=async e=>{try{let t=await cu(`${e}/connect-update.json`,iu);if(!t.ok)return;let n=await t.json();if(!n||typeof n!="object")return;let r=n.minVersion;return typeof r=="string"&&/^\d+\.\d+\.\d+/.test(r)?r:void 0}catch{return}},ji=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},yy=async(e,t,n)=>{let r=await cu(e,zG);if(!r.ok||!r.body)throw new ji(r.status);let o=YG("sha256"),a=0;if(await XG(ZG.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>qG)throw new Error("asset exceeds size cap");o.update(c),yield c}},WG(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},sj=e=>cy(e)===Ga()?cy(Dr(e)):cy(e),ij=async e=>{let t=await py(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await _t(pt(e,n),{force:!0}).catch(()=>{})},iI=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await _t(r,{force:!0}).catch(()=>{});let o=!1;try{await au(e,r),o=!0}catch{}try{await dy(t,e),await VG(is(e),sj(t))}catch(a){throw o&&await au(r,e).catch(()=>{}),a}await _t(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await _t(n,{force:!0}),await jG(t,n),await au(n,e)},cj=async(e,t={})=>{let n=pt(e.root,"bin"),r=pt(e.root,"versions"),o=pt(n,Ga());await Ha(n,{recursive:!0,mode:448}),await Ha(r,{recursive:!0,mode:448});let a=pt(r,e.version),i=(await uy(a).catch(()=>{}))?.isFile()?a:pt(a,Ga());if(!(await uy(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??cu)(`${e.tagUrl}/SHA256SUMS`,iu),d=l.ok?fy(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await Ha(Dr(i),{recursive:!0,mode:448}),await ij(Dr(i));let u=`${i}.part-${process.pid}`;try{await(t.download??yy)(`${e.tagUrl}/${e.asset}`,u,d),await KG(u,493),await au(u,i)}catch(f){throw await _t(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??iI)(o,i),{link:o,target:i,versionsDir:r}},lj=async e=>{let t=HG(e,["--version"],{stdio:"ignore",timeout:iu});return!t.error&&t.status===0},dj=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??wo)(n);if(r.length>0){let o=await(t.resolveTarget??Re)(async()=>e);if(!o||!(await(t.repair??gt)(r,o.target)).every(go))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??pr)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Dt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},uj=async e=>{let t=await e.install();if(!await(e.smoke??lj)(t.target))throw await e.rollback?.(t),new Error("managed binary smoke test failed");if(!await e.repoint(t.link))throw new Error("persistent config repoint failed");return await e.prune(),t},pj=async(e,t)=>{let n=await py(e).catch(()=>[]);for(let r of n)t.includes(r)||await _t(pt(e,r),{force:!0,recursive:!0}).catch(()=>{})},fj=async e=>{let t=await py(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await _t(pt(e,n),{force:!0}).catch(()=>{})},hj=async(e,t)=>{let n=async()=>{await _t(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Ha(e,{recursive:!1}),n}catch{}let r=await GG(e).catch(()=>{});if(!(!r||t-r.mtimeMs<ej)){await n();try{return await Ha(e,{recursive:!1}),n}catch{return}}},ly=e=>pt(e,"update-state.json"),mj=async e=>{let t=await U(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},yj=1e3,gj=16*6e4,wj=e=>e.inFlight===0,bj=async(e,t,n={})=>{let r=n.probe??be,o=n.sleep??(i=>new Promise(c=>setTimeout(c,i))),a=n.now??Date.now,s=a()+(n.timeoutMs??gj);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&wj(i))return!0;if(a()>=s)return!1;await o(yj)}},Vi=async(e={})=>{let t=e.now??Date.now,n=we;if(Ct(yt(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??mt(),o=e.root??Q(),a;try{let s=await hy(r,o);if(o=s.root,s.kind==="unmanaged")return{outcome:"unmanaged",current:n};if(s.kind==="npm"&&!e.allowNpmMigration)return{outcome:"unmanaged",current:n};let i=s.kind!=="managed",c=aI(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??my)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&Ka(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await mj(ly(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<QG)return{outcome:"failed",current:n,latest:l};let f=`${rI}/download/${oI}${l}`,p=await(e.load??D)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??aj)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?nj(w):{...sI(w),downgradeBlocked:!1};if(g.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:l};if(!g.apply)return{outcome:"disabled",current:n,latest:l};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:l,mandatory:g.mandatory};o===Q()?await kt():await Ha(o,{recursive:!0,mode:448});let y=await hj(pt(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,A;try{await fj(pt(o,"bin"));let x=await su(pt(o,"versions")).catch(()=>{}),C=await su(pt(o,"bin",Ga())).catch(()=>{}),I=C&&gc(C,x)?C:void 0,P=pt(o,"bin",Ga());i&&process.platform==="win32"&&(await uy(P).catch(()=>{}))?.isFile()&&(A=`${P}.rollback-${process.pid}`,await dy(P,A));let $=()=>(e.installBinary??cj)({root:o,version:l,asset:c,tagUrl:f});i?b=await uj({install:$,smoke:e.smoke,rollback:async({link:Y,target:Z})=>{A?(await dy(A,Y),await _t(is(Y),{force:!0}).catch(()=>{})):I&&I!==Z?await iI(Y,I):(await _t(Y,{force:!0}),await _t(is(Y),{force:!0}).catch(()=>{}))},repoint:async Y=>e.repoint?e.repoint(p,Y):dj(p),prune:async()=>{await(e.pruneDurable??(Y=>wc(Y)))(r)}}):b=await $(),await pj(b.versionsDir,[l,n]),await _t(ly(o),{force:!0}).catch(()=>{})}finally{A&&await _t(A,{force:!0}).catch(()=>{}),await y()}let v=e.bounceDaemon??op,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let x=p.fallbackPort??ke,C=E?!0:await bw().catch(()=>!0),I=await v(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!C&&p.gateway&&((I?await(e.waitForDaemon??bj)(x,l):!0)?await Dt({port:x,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??Cw)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await X(ly(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},cI=async(e={})=>{let t=e.context??mt(),n=await hy(t,e.root??Q()),r=Fo(e.root??Q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:we,managedPath:n.link??r}:Vi({...e,context:t,allowNpmMigration:!0})},Io=async(e={})=>{let t=e.context??mt(),n=e.root??Q(),r=await hy(t,n),o=r.kind==="npm"||r.kind==="durable"?Fo(n):void 0,a=await(e.load??D)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!aI(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=Ct(yt(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:we,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};var kj=async(e,t)=>{if(!e.gateway||!e.clientKey)return;let n=await t().catch(()=>{});return ge({origin:e.gateway,clientKey:e.clientKey,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:n,user:e.name,team:e.team})},lI=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,Cj=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},gy=async(e={})=>{let t=e.load??D,n=e.save??re,r=e.mutate??(e.load||e.save?Cj(t,n):Rg),o=e.loadDevKey??We,a=e.heartbeat??Od,s=e.detectSeat??Nt,i=e.rewriteTools??Ei,c=e.uninstallProxy??Qt;try{let l=await t();if(l.credentialProtocol==="stable-heartbeat-v1"&&l.directMigration==="complete")return"already-direct";if(!l.keyRefreshEnabled&&!l.refreshSchedulerEnabled||!l.gateway||!l.clientKey||!l.enrolledCert)return"not-eligible";let d=l.enrolledCert.sig,u=await o();if(!u)return"not-eligible";let f;try{f=await a(l.gateway,l.clientKey,l.enrolledCert,u)}catch(y){return y instanceof Ir&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!lI(y,l))return{result:void 0};let b={...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"pending"};return{next:b,result:b}});if(!p)return"pending";let h=await kj(p,s);if(!h)return"pending";let m=l.keyRefreshEnabled===!0,w=Number.isInteger(l.fallbackPort)&&l.fallbackPort>0&&l.fallbackPort<=65535?l.fallbackPort:ke;if(m){let y=`http://${ht}:${w}`;if(await i(h,y)===!1)return"pending"}return await r(y=>y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||y.credentialProtocol!=="stable-heartbeat-v1"||y.directMigration!=="pending"||!lI(y,p)?{result:!1}:{next:{...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"complete",keyRefreshEnabled:!1,fallbackPort:void 0},result:!0})?((m||l.fallbackPort!==void 0)&&await c(w).catch(()=>{}),"migrated"):"pending"}catch{return"pending"}};import{z as dI}from"zod";var Aj=5e3,vj=dI.object({lane:dI.enum(["subscription","org"]).optional().catch(void 0)}),uI=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??Aj);try{let a=await(n.fetchResponse??fetch)(`${e.replace(/\/$/,"")}/connect/policy`,{headers:{"x-anyray-api-key":t.trim()},signal:r.signal});if(!a.ok)return;let s=vj.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},pI=(e,t)=>{if(!e||t.byoUpstream)return{overrodeFlag:!1};let n=t.subscription?"subscription":t.org?"org":void 0;return{lane:e,overrodeFlag:n!=null&&n!==e}};var Sj=12e3,Ej="anyray-wiring-probe-not-a-real-token",xj={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},by={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},Oo=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},hI=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},ky=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},fI=e=>["Note: OpenCode\u2019s Claude provider can ONLY use a server-side key \u2014 unlike","Claude Code, it has no personal-subscription path. For Claude, either:",...e," \u2022 use Claude Code with your own Claude subscription instead of OpenCode.","OpenCode ChatGPT OAuth uses a non-configurable endpoint. Use Codex for"," config-native ChatGPT subscription pass-through, or use an OpenCode"," API-key/Copilot provider that Connect can route."],Ij=e=>e.includes("no provider key configured for"),Cy=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},Ay=e=>({kind:"enrollment-required",detail:`gateway requires per-developer enrollment (HTTP ${e}).`,remedy:["This gateway only serves enrolled developers. Re-run with your enrollment","link from your admin so connect can mint your personal key automatically:"," anyray-connect --enroll <link>"]}),Yi=e=>({kind:"key-rejected",detail:`gateway rejected the client key (HTTP ${e}).`,remedy:["The gateway did not receive a usable personal key (missing, unknown, expired,","or revoked). Re-run `anyray-connect` to refresh an existing enrollment, or","use `--enroll` / `--sso` to enroll first."]}),Oj=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:e===401||e===403?Cy(t)?Ay(e):ky(t)?Yi(e):hI(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Oo(t)}`,remedy:["The org provider rejected the request \u2014 check the gateway\u2019s provider","key/config (e.g. the model is enabled for that account)."]}:Ij(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Oo(t)}`,remedy:["Your enrollment key is fine \u2014 the gateway has NO server-side provider","key configured (org-key mode), so it refused to forward the request.","Fix: add a provider key in the console \u2192 Providers.",...n.includes("opencode")?fI([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${Oo(t)}`,remedy:n.includes("opencode")?["Your enrollment key is fine \u2014 the gateway forwarded the request and the","upstream model provider refused the credential it was given: this","gateway has no WORKING provider key for it (either none is configured,","or the configured one is wrong or revoked).",...fI([" \u2022 open the console \u2192 Providers and add a key for that provider, or"," replace the one already listed (fixes it for everyone), or"])]:["Your enrollment key is fine \u2014 the gateway forwarded the request and the","upstream model provider refused it.","Open the console \u2192 Providers: if no key is listed for that provider,","add one; if a key IS listed, it is wrong, revoked, or not entitled to","the model \u2014 replace it.","Either way this is gateway config, not your enrollment. Alternatively,","sign in with your own provider subscription instead of the org key.","If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]}:{kind:"unknown",detail:`gateway responded HTTP ${e}: ${Oo(t)}`,remedy:[]},Rj=(e,t)=>{if(ky(t))return Yi(e);if(Cy(t))return Ay(e);if(hI(t))return{kind:"routed-elsewhere",detail:"gateway sent the request to the org provider, not your subscription.",remedy:["Pass-through isn\u2019t being honored for this gateway \u2014 your seat token would","not be used. Check the gateway is current (subscription pass-through support)."]};let n=t.toLowerCase();return e===401||n.includes("authentication_error")||n.includes("invalid bearer")||n.includes('"provider":"anthropic"')?{kind:"ok",detail:"gateway passes your sign-in through to Anthropic \u2014 your Claude seat will be used.",remedy:[]}:e>=200&&e<300?{kind:"ok",detail:"gateway pass-through reached the provider \u2014 your seat will be used.",remedy:[]}:{kind:"unknown",detail:`seat-wiring probe got HTTP ${e}: ${Oo(t)}`,remedy:[]}},_j=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),Pj=(e,t)=>{if(ky(t))return Yi(e);if(Cy(t))return Ay(e);let n=t.toLowerCase();if(n.includes("bedrock"))return{kind:"routed-elsewhere",detail:"gateway routed to the org provider instead of the configured BYO upstream.",remedy:["Re-run anyray-connect with your --upstream URL and --upstream-key so","the custom-host pass-through pins are restored."]};if(n.includes("invalid custom host")||n.includes("custom_host_blocked")||n.includes("hostname is not authorized"))return{kind:"routed-elsewhere",detail:"gateway rejected the configured BYO upstream before routing to it.",remedy:["Ask the gateway admin to authorize this LiteLLM/upstream hostname in","ANYRAY_CUSTOM_HOST_ALLOWLIST (or TRUSTED_CUSTOM_HOSTS for an internal host)."]};if(e===401||e===403)return{kind:"provider-rejected",detail:`gateway accepted your personal key but the BYO upstream rejected its credential (HTTP ${e}).`,remedy:["Your Anyray enrollment key is fine. The configured personal upstream key","was rejected by the BYO upstream (for example, LiteLLM). Re-run","anyray-connect with a current --upstream-key."]};let r=e>=400&&e<500&&(n.includes("litellm")||_j(n));return e>=200&&e<300||r?{kind:"ok",detail:e>=200&&e<300?"gateway served a completion through the configured BYO upstream.":`gateway authenticated and reached the configured BYO upstream, which rejected this probe's fixed model (HTTP ${e}).`,remedy:[]}:{kind:"unknown",detail:`BYO-upstream probe got HTTP ${e}: ${Oo(t)}`,remedy:[`The probe asks for a fixed model (${by.model}) your upstream`,"is not required to serve, so a model rejection here does not mean your","tools are broken. Check that the upstream serves it before chasing this."]}},wy=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),r);try{let s=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...t},body:JSON.stringify(n),signal:o.signal});return{status:s.status,bodyText:await s.text()}}finally{clearTimeout(a)}},Tj=async(e,t)=>{if(!e.clientKey)return Yi(401);let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`${e.origin}/connect/savings`,{method:"GET",headers:{"x-anyray-api-key":e.clientKey},signal:n.signal}),a=await o.text();return o.ok?{kind:"ok",detail:"gateway accepted your personal key \u2014 Cursor hooks/MCP can report and retrieve.",remedy:[]}:o.status===401||o.status===403?Yi(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Oo(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},Lj=(e,t)=>{let n=typeof t?.code=="string"?` ${t.code}`:"";return{kind:"unreachable",detail:`could not reach the gateway to verify (${t instanceof Error&&t.name==="AbortError"?`no response within ${e}ms`:t instanceof Error?`${t.name}${n}`:"unknown error"}).`,remedy:["Your config was still written \u2014 re-run the curl below once the gateway is reachable."]}},Zi=async(e,t={})=>{let n=t.timeoutMs??Sj,r=de(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await Tj(e,n);if(e.byoUpstream){let l={Authorization:`Bearer ${e.byoUpstream.key}`,"anthropic-version":"2023-06-01","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic","x-anyray-custom-host":e.byoUpstream.url};e.clientKey&&(l["x-anyray-api-key"]=e.clientKey),r&&(l["x-anyray-metadata"]=r);let{status:d,bodyText:u}=await wy(`${e.anthropicBaseUrl}/v1/messages`,l,by,n);return Pj(d,u)}if(J(e,"anthropic")){let l={Authorization:`Bearer ${Ej}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"};r&&(l["x-anyray-metadata"]=r),e.clientKey&&(l["x-anyray-api-key"]=e.clientKey);let{status:d,bodyText:u}=await wy(`${e.anthropicBaseUrl}/v1/messages`,l,by,n);return Rj(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await wy(`${e.openaiBaseUrl}/chat/completions`,s,xj,n);return Oj(i,c,t.tools??[])}catch(o){return Lj(n,o)}};var mI=async e=>{let t=await D(),n;try{n=Pr(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),M(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${nt(n)}`),t.gateway?M(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?M(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||M(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??S("(not set)")}`),k(` Team: ${t.team??S("(not set)")}`);let r=yt();r&&(K("Environment"),k(` Remote dev context: ${dr(r)}`),Ct(r)&&M(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),M(" VS Code tools configure the remote server variant backing this window.")),t.credentialProtocol==="stable-heartbeat-v1"&&(K("Credential renewal"),t.directMigration==="pending"?(k(" Stable-key heartbeat active; direct-routing migration is still completing."),M(" The local proxy remains available until every managed tool moves.")):(F(" Direct gateway routing with a proof-backed stable-key heartbeat."),M(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(rt(t)&&t.fallbackPort),a=o?`http://${ht}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await be(t.fallbackPort)?F(` Running on 127.0.0.1:${t.fallbackPort} \u2192 ${n} `+S("(auto-refreshes your key so long sessions never 401)")):(L(` Enabled on 127.0.0.1:${t.fallbackPort} but NOT responding \u2014 your tools cannot reach any gateway until it's back.`),k(S(" Re-run `anyray-connect`, or check the service logs.")))),K("Tools");for(let s of ie){if(!(await s.detect()).installed){M(` ${s.title}: not installed`);continue}if(!s.pointsAt){M(` ${s.title}: installed ${S("(status not introspectable)")}`);continue}let c=await s.pointsAt($i(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){F(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(S(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}F(` ${s.title}: pointed at Anyray${o&&Ni(s.id)?S(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===Ua&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await Yd();l=Zd({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:f.authoritative}),d={...f.authoritative?{}:{reason:f.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=Xd(l,d);L(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(S(` ${f}`))}else M(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as qj}from"node:fs";import{isAbsolute as zj}from"node:path";import{access as Dj}from"node:fs/promises";import{constants as Nj}from"node:fs";import{platform as $j}from"node:os";var Mj=async e=>{try{return await Dj(e,Nj.F_OK),!0}catch{return!1}},Fj=e=>e==="darwin"?["/Library/LaunchDaemons/com.fleetdm.orbit.plist","/opt/orbit/bin/orbit"]:e==="linux"?["/etc/systemd/system/orbit.service","/usr/lib/systemd/system/orbit.service","/opt/orbit/bin/orbit"]:e==="win32"?["C:\\Program Files\\Orbit\\bin\\orbit\\orbit.exe"]:[],Ro=async(e={})=>{let t=e.os??$j(),n=e.exists??Mj;for(let r of Fj(t))if(await n(r))return!0;return!1};import{execFile as Uj}from"node:child_process";import{readFile as Bj}from"node:fs/promises";import{homedir as Wj,platform as Hj}from"node:os";import{join as Kj}from"node:path";import{promisify as Gj}from"node:util";var jj=Gj(Uj),gI="extensions.supportAgentsWindow",wI="chat.agentHost.byokModels.enabled",Vj="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",yI=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yj=async e=>{try{let t=yn(await Bj(e,"utf-8"));if(!yI(t))return{};let n=t[gI],r=t[wI];return{supportsAnyray:yI(n)?n[ae]===!0:void 0,bridgeEnabled:typeof r=="boolean"?r:void 0}}catch{return{}}},Zj=e=>Kj(Ye(e),"User","settings.json"),Xj=async(e=async()=>(await jj("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(Hj()==="win32")return"unknown";try{let t=(await e()).match(new RegExp(`${Vj}=(\\w*)`,"g"))??[];return t.length===0?"unknown":t.some(n=>n.endsWith("=true"))?"on":"off"}catch{return"unknown"}},Jj=e=>e.mode!=="copilot-seat"?"not-applicable":e.settings.supportsAnyray!==!0||e.settings.bridgeEnabled!==!0?"not-configured":e.bridge==="off"?"awaiting-relaunch":"ready",lu=(e,t)=>{switch(e){case"ready":return t==="on"?"Agents window: Anyray models available (agent host is running with the model bridge on).":"Agents window: configured. VS Code is not running one yet, so the next launch picks it up.";case"awaiting-relaunch":return"Agents window: configured, but the agent host running right now started before it. Quit and relaunch VS Code once; a window reload will not do it, because that process outlives every window.";case"not-configured":return`Agents window: not enabled. Re-run anyray-connect --tools copilot, then quit and relaunch VS Code (it sets ${gI} and ${wI}; if you switched either off yourself, that choice is left alone).`;case"not-applicable":return"Agents window: not applicable on this machine."}},bI=async(e={})=>{let{installedVariant:t=Jo,receiptMode:n=yl,readSettings:r=Yj,probeBridge:o=Xj,home:a=Wj()}=e;try{let s=await t();if(!s)return{state:"not-applicable",bridge:"unknown",detail:lu("not-applicable","unknown")};let i=await n(s,a);if(i!=="copilot-seat")return{state:"not-applicable",bridge:"unknown",detail:lu("not-applicable","unknown")};let c=await r(Zj(s)),l=await o(),d=Jj({mode:i,settings:c,bridge:l});return{state:d,bridge:l,detail:lu(d,l)}}catch{return{state:"not-applicable",bridge:"unknown",detail:lu("not-applicable","unknown")}}};var Yt="connect",vy=e=>e.replace(/-/g,"_"),kI=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Yt,checkId:"gateway_reachable",status:e.gateway.reachable?"ok":"unreachable"});let n=Date.parse(e.report.generatedAt),r=Date.parse(e.enrollment.expiresAt??""),o=e.enrollment.enrolled&&e.enrollment.expired===!1&&Number.isFinite(n)&&Number.isFinite(r)&&r-n<=336*60*60*1e3;if(t.push({tool:Yt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Yt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:Yt,checkId:"fallback_proxy",status:e.fallbackProxy.healthy===!1?"fail":e.fallbackProxy.healthy===!0?"ok":"unknown"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:Yt,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:Yt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Yt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=vy(e.retrieval.kind);t.push({tool:Yt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":vy(e.verify.kind);t.push({tool:Yt,checkId:"auth_verify",status:c,...i?{errorClass:"verify_not_applicable_subscription"}:c==="ok"?{}:{errorClass:`verify_${c}`}})}for(let i of e.tools)!i.installed||i.claudeCodeHookPolicy===void 0||t.push({tool:i.id,checkId:"hook_policy",status:i.claudeCodeHookPolicy==="fine"?"ok":i.claudeCodeHookPolicy});if(e.hookLane&&e.hookLane.verdict!=="indeterminate"){let i=e.hookLane.verdict==="dark";t.push({tool:Yt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:vy(e.hookLane.reason)}:{}})}t.push({tool:Yt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:Yt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function Qj(){return we}var eV="ctx_doctor-probe-synthetic",tV=(e,t={mode:"unknown",ssoLink:null})=>{if(e.ok||e.kind==="not-found")return{kind:"ok",detail:"Retrieval loop healthy: gateway answered, key authorized, optimizer retrieval wired.",remedy:[]};switch(e.kind){case"auth":return{kind:"auth",detail:"The gateway rejected the retrieval call (no valid personal key).",remedy:[`Fix: ${xy(t.mode,t.ssoLink)}, or set ANYRAY_CLIENT_KEY.`,"Retrieval needs a personal key \u2014 the MCP server hits the same wall, so externalized output is unretrievable until this is fixed."]};case"unsupported":return{kind:"unsupported",detail:"The gateway has no /connect/retrieve route.",remedy:["Fix: update the gateway image \u2014 this one predates the retrieval loop."]};case"timeout":case"network":return{kind:"unreachable",detail:`Could not reach the gateway for the retrieval probe (${e.kind}).`,remedy:["Fix: check the gateway origin and network (see the Gateway section above)."]};default:return{kind:"unavailable",detail:e.message,remedy:["Fix: the gateway answered but retrieval is unavailable \u2014 usually the optimizer is down or ANYRAY_OPTIMIZER_URL is unset on the gateway. Check the optimizer service."]}}};function nV(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function rV(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function xy(e,t){let n=`\`anyray-connect --sso ${t??"<link>"}\``,r="`anyray-connect --enroll <link>`";switch(e){case"sso":return`enroll via SSO with ${n}`;case"passwordless":return`enroll with the link from your admin (${r})`;default:return`enroll \u2014 SSO org: use ${n}; passwordless org: use ${r} (link from your admin)`}}var CI=e=>Zd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),Sy=e=>e.pointedAt===!1&&e.tombstoned!==!0&&CI(e)!=="unverifiable",AI=e=>e.registered&&e.command&&zj(e.command)?qj(e.command):null,Ey=e=>(Sy(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),oV=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,aV=async(e,t)=>{if(e.length===0)return!1;for(let n of e){let r=t.find(a=>a.id===n);if(!r?.inferenceAuthLanes)return!1;let o=await r.inferenceAuthLanes().catch(()=>["unknown"]);if(o.length===0||o.some(a=>a!=="subscription"&&a!=="native"))return!1}return!0},vI=async e=>{for(let t of e)if(t.integrationStatus)try{if(!(await t.detect()).installed)continue;if((await t.integrationStatus()).hook_registration==="owned")return!0}catch{}return!1},sV=(e,t)=>{let n=c=>typeof c=="object"&&c!==null&&!Array.isArray(c),r=c=>typeof c=="number"&&Number.isSafeInteger(c)&&c>=0&&Number.isFinite(new Date(c).getTime()),o=new Set(t.map(c=>c.id)),a=new Set(Co),s=[],i=n(e.selfcheck?.adapters)?e.selfcheck.adapters:{};for(let[c,l]of Object.entries(i)){if(!o.has(c)||!n(l))continue;let d=n(l.lastRepaired)?l.lastRepaired:{},u=Object.entries(d).filter(w=>a.has(w[0])&&r(w[1])).map(([w,g])=>({checkId:w,at:g})),f=n(l.flapping)?l.flapping:void 0,p=Array.isArray(f?.checks)?f.checks.filter(w=>typeof w=="string"&&a.has(w)):[],h=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,m=f&&r(f.since)&&h&&p.length>0?{since:f.since,reason:h,checks:p}:void 0;(u.length>0||m)&&s.push({tool:c,repaired:u,...m?{flapping:m}:{}})}return s},iV=async(e,t,n,r,o,a,s=n,i=Zi,c=!0,l=So,d=Io,u=Kt,f=Ra)=>{let p=c?await ru(e):null,h=!!(rt(t)&&t.fallbackPort),m=h?await be(t.fallbackPort):null,w=h?`http://${ht}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=V=>V&&Wm(V)?"machine_default":null,b=t.enrolledCert?.payload,A=b?.expiresAt??t.enrolledCertExpiry??null,E=(await a())?.sso??null,x=rV({ssoLink:E,enrolledViaToken:!!t.enrolledTokenHash}),C=At(),I=await Jw(C),P=I?[]:tb(ge({origin:w})),$=[];for(let V of r){let Ne=await V.detect(),er=null;if(Ne.installed&&V.mcpStatus)try{let To=await V.mcpStatus();er={...To,commandOk:AI(To)}}catch{}let ft=Ne.installed&&V.id===Ua?await o():void 0,Po=Ne.installed&&V.pointsAt?await V.pointsAt($i(V.id,e,w)):null,In=await oV(Po,V,t.managedTools??[]),Xa=Po===!1&&In===null,sc=In===!1&&V.routingPendingReload?await V.routingPendingReload().catch(()=>!1):!1,Ja=Ne.installed?V.runtimeDiagnostics?await V.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:V.routingOverrides?await V.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:qa,claudeCodeHookPolicy:za}=Ja,Qa=t.fleetToolPolicy,es=Qa?.enabled.includes(V.id)?Qa.tiers?.[V.id]??xa:void 0;$.push({id:V.id,title:V.title,installed:Ne.installed,...Ne.detail?{detail:Ne.detail}:{},pointedAt:In,...Xa?{routingHeld:!0}:{},...sc?{routingPendingReload:!0}:{},...qa.length?{routingOverrides:qa}:{},...za===void 0?{}:{claudeCodeHookPolicy:za},mcp:er,...es?{policyTier:es}:{},...t.revertedTools?.includes(V.id)?{tombstoned:!0}:{},...V.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...ft===void 0?{}:{inferenceIntrospectable:ft.authoritative,...ft.authoritative?{}:{inferenceUnverifiableReason:ft.reason}}})}let Y=s?await(async()=>{let{kind:V,detail:Ne,remedy:er}=await i(ge({origin:e,clientKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey,subscription:t.authMode==="subscription",placeholder:t.authMode==="placeholder",byoUpstream:t.byoUpstream,...t.authMode==="auto"?{seat:{anthropic:!1,openai:!1,copilot:!1}}:{},user:t.name,team:t.team}),{tools:t.managedTools??[]});return{kind:V,detail:Ne,remedy:er}})():null,Z=Y?.kind==="provider-rejected"&&await aV(t.managedTools??[],r),W=Y?{...Y,...Z?{notApplicableSubscription:!0}:{}}:null,q=n?tV(await Oa({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:de({user:t.name,team:t.team})},eV,{probe:!0}),{mode:x,ssoLink:E}):null,me=await u().catch(()=>({})),Te=En(me.hookLane),ne=s?await vI(r):!1,Ke=ne?await(async()=>{let V=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...um(V,{hookRegistered:ne,neverInvoked:lm(Te,Date.now())}),lastInvokedAt:_d(Te)}})():null,Le=(await hr()).map(V=>({adapter:V.adapter,op:V.op,requestedAt:V.requestedAt,watcherAlive:yr(V.watcherPid)})),R=Le.find(V=>V.adapter==="cursor"),T=R?{op:R.op,requestedAt:R.requestedAt,watcherAlive:R.watcherAlive}:null,H=!!t.refreshSchedulerEnabled,fe=await Yo(),z=await d(),Ze=t.persistenceOwner==="tray",Ue=Ze?await l(t)==="healthy":null,ee=await xE({daemonEnabled:h&&!Ze,daemonHealthy:h?!!m:null,schedulerEnabled:H&&!Ze,schedulerInstalled:fe,binaryDurable:!je(lr())}),Be=await $u(),De=0;p&&!p.reachable&&(De+=1),h&&!m&&(De+=1),Ze?H&&!Ue&&(De+=1):H&&!fe&&(De+=1);for(let V of $)De+=Ey(V);W&&W.kind!=="ok"&&!W.notApplicableSubscription&&(De+=1),q&&q.kind!=="ok"&&(De+=1),Ke?.verdict==="dark"&&(De+=1),P.length>0&&(De+=1),De+=Le.filter(V=>!V.watcherAlive).length,Be.length>0&&(De+=1);let Xt=await bI();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:Qj(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:yt(),selfUpdate:{managed:z.managed,available:z.available,autoUpdate:z.autoUpdate,state:z.state}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},toolOrigin:w,fallbackProxy:{enabled:h,port:h?t.fallbackPort:null,healthy:h?!!m:null},refreshScheduler:{enabled:H,installed:fe,owner:Ze?"tray":"os",...Ze?{trayHealthy:!!Ue}:{}},serviceRemoval:ee,retiredFallbackState:Be,fleetdPresent:await Ro(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:y(t.name)},enrollment:{enrolled:!!b,deploymentId:b?.deploymentId??null,issuedAt:b?.issuedAt??null,expiresAt:A,expired:A?Date.parse(A)<Date.now():null,orgMode:x,ssoLink:E},shell:{profilePath:C,blockPresent:I,staleExports:P},tools:$,...t.fleetToolPolicy?{fleetPlan:vd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:T,pendingOps:Le,ambientRepairs:sV(me,r),verify:W,retrieval:q,hookLane:Ke,agentsWindow:Xt,problems:De}},cV=e=>{if(e.serviceRemoval.suspected){K("Endpoint security"),L(" Anyray installed these background services, but their files are gone from disk \u2014"),L(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),L(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)k(S(` missing: ${t}`));k(S(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(S(" tools straight at the gateway (your key then needs a periodic re-run).")),k(S(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(S(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},lV=e=>{if(e.retiredFallbackState.length!==0){K("Retired fallback lane"),_(" A cached organization provider key from the removed --fallback lane is still on this machine.");for(let t of e.retiredFallbackState)k(S(` ${t}`));k(S(" Fix: `anyray-connect doctor --repair` deletes it (a normal `anyray-connect` run does too)."))}},dV=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${dr(e.connect.remoteContext)}`),Ct(e.connect.remoteContext)&&k(S(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),K("CLI updates"),e.connect.selfUpdate.state){case"managed":F(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||L(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":L(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),k(S(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":L(" Self-update is unavailable on this platform because no standalone binary is published."),k(S(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(S(" This copy is externally managed; update it with the method that installed it."));break;case"container":k(S(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(K("Gateway"),e.gateway.reachable===null?k(S(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?F(` Reachable: ${e.gateway.origin} ${S(`(${e.gateway.detail})`)}`):(_(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),k(S(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.fallbackProxy.enabled&&(K("Local key-refresh proxy"),e.fallbackProxy.healthy?F(` Running on 127.0.0.1:${e.fallbackProxy.port} \u2192 ${e.gateway.origin} `+S("(auto-refreshes your key so long sessions never 401)")):(_(` Enabled on 127.0.0.1:${e.fallbackProxy.port} but NOT responding \u2014 your tools point at it and cannot reach any gateway until it's back.`),e.serviceRemoval.kinds.includes("daemon")||k(S(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to point tools straight at the gateway.")))),e.refreshScheduler.enabled&&(K("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?F(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh and supervises the daemon."):(_(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),k(S(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?F(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(_(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||k(S(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),cV(e),lV(e),K("Personal key"),nV(e)){case"env":F(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":F(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":L(" Enrolled, but no personal key is cached locally right now."),k(S(" Fix: re-run `anyray-connect` to re-mint it from your enrollment \u2014 no need to re-enroll. Claude Code and Codex are still attributed to you by name."));break;default:L(" Enrollment required \u2014 no personal gateway key is available."),k(S(` Fix: ${xy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?L(` Enrollment cert expired ${S(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):F(` Enrollment cert valid until ${e.enrollment.expiresAt} ${S(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(K("Shell"),_(" This terminal still exports Anyray, but the config is gone."),k(S(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(S(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(S(" Anything you start from this terminal keeps reaching the gateway with")),k(S(" no credential, and fails with 401.")),k(S(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(S(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(S(" reuses the environment it captured at launch, so a new terminal")),k(S(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};K("Claude Code hook policy"),_(` ${Sc(c)}.`),k(S(` ${Ec(c)}`))}K("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])_(` ${c.title}: ${l.problem}.`),k(S(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(_(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),k(S(" Fix: re-run `anyray-connect` to re-register the current binary."))):F(` ${c.title}: retrieval MCP server registered ${S("(anyray_retrieve / anyray_recall)")}`):(L(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),k(S(" Fix: re-run `anyray-connect` from a durable install (registration is skipped for one-off npx runs)."))))};for(let c of e.tools){if(!c.installed){k(S(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){k(S(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){F(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),k(S(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}F(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&Ni(c.id)?S(" (via key-refresh proxy)"):""}`),o(c),c.id==="claude-code"&&k(S(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===Ua&&k(S(` ${LC}`)),c.id==="codex"&&k(S(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=CI(c);if(l==="not-routed"||l==="unverifiable"){let d=Xd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});L(` ${c.title}: ${d.headline}`);for(let u of d.detail)k(S(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(L(` ${c.title}: reverted locally against admin policy (out of compliance)`),k(S(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?L(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):k(S(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(_(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),k(S(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(_(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),k(S(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(L(" No tools are pointed at this gateway yet."),k(S(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){K("Queued operations");for(let c of e.pendingOps){let l=Ht(c.adapter)?.title??c.adapter;c.watcherAlive?L(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(_(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),k(S(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){K("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=Ht(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:p,at:h})=>`${c(p)} ${new Date(h).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?L(f):k(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){K("Fleet policy");let c=l=>l.map(d=>Ht(d)?.title??d).join(", ");i.freshIds.length>0&&k(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&L(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(K("Auth probe"),e.verify.notApplicableSubscription)F(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")F(` ${e.verify.detail}`);else{_(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(S(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")F(` ${e.retrieval.detail}`);else{_(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(S(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")F(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(S(` ${c}`))}else{L(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(S(` ${c}`))}e.hookLane.lastInvokedAt!==null&&k(S(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(K("VS Code Agents window"),L(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(K("VS Code Agents window"),F(` ${e.agentsWindow.detail}`)),K("Summary"),e.problems===0?(e.verify?F(" No problems found."):F(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(S(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):_(` ${e.problems} problem(s) found \u2014 see fixes above.`)},uV=e=>({...e,verify:e.verify?{kind:e.verify.kind,detail:"",remedy:e.verify.remedy,...e.verify.notApplicableSubscription?{notApplicableSubscription:!0}:{}}:null,retrieval:e.retrieval?{kind:e.retrieval.kind,detail:"",remedy:e.retrieval.remedy}:null}),pV=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!sm(n.code))return{hookLane:n,note:`Hook lane: the gateway rejected this machine\u2019s key as '${n.code??"unclassified"}', which an automatic re-mint must never answer \u2014 no key was minted. Re-enroll (see the Hook lane fixes above).`};let r=t.probeHookLane??Ra,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??tt)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=En((await(t.readRefreshState??Kt)().catch(()=>({}))).hookLane),l=um(i,{hookRegistered:await vI(t.adapters??ie).catch(()=>!1),neverInvoked:lm(c,Date.now())}),d=s==="disabled"?"Hook lane: key refresh is disabled here (ANYRAY_REFRESH_DISABLE), so no key was minted and the finding stands.":l.verdict==="live"?"Hook lane: re-minted the personal key and rewrote the configured tools \u2014 the lane answers again.":l.verdict==="indeterminate"?`Hook lane: re-mint reported '${s}', but the confirming probe could not establish the lane's state \u2014 nothing is proven fixed and the finding stands.`:`Hook lane: re-mint reported '${s}' and the lane is still not live \u2014 re-enroll (see the Hook lane fixes above).`;return{hookLane:{...l,lastInvokedAt:_d(c)},note:d}},fV=async(e,t,n={})=>{let r=n.adapters??ie,o=n.resolveTarget??Re,a=n.applyTools??gt,s=await pV(e,n).catch(()=>null),i=s&&e.hookLane?.verdict==="dark"&&s.hookLane?.verdict==="live"?1:0,c=s?{hookLane:s.hookLane,notes:[s.note]}:{notes:[]},l=e.tools.filter(y=>y.installed&&(Sy(y)||y.mcp?.commandOk===!1||y.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t,void 0,be);if(!d)return{entries:l.map(y=>({id:y.id,title:y.title,status:"skipped-not-enrolled"})),remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,`Repair needs an enrolled personal key \u2014 ${xy(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],p=[...c.notes],h=[];for(let y of l){let b=r.find(A=>A.id===y.id);if(!u.has(y.id)||!b){f.push({id:y.id,title:y.title,status:"skipped-unmanaged"});continue}h.push(b)}f.length>0&&p.push("Drifted tools outside the managed record are never auto-repaired \u2014 run `anyray-connect` once to (re)configure and record them.");let m=await a(h,d.target),w=new Map,g=0;for(let y of m){if(f.push(y),!go(y))continue;let b=e.tools.find(P=>P.id===y.id);if(!b)continue;let A=r.find(P=>P.id===y.id),v=b.mcp;if(A?.mcpStatus)try{let P=await A.mcpStatus();v={...P,commandOk:AI(P)}}catch{}let E=Sy(b)?!0:b.pointedAt;if(A?.pointsAt&&b.pointedAt!==null)try{E=await A.pointsAt($i(A.id,e.gateway.origin,e.toolOrigin))}catch{}let x=b.routingOverrides,C=b.claudeCodeHookPolicy;if(A?.runtimeDiagnostics)try{let P=await A.runtimeDiagnostics();x=P.routingOverrides.length?P.routingOverrides:void 0,C=P.claudeCodeHookPolicy}catch{}else if(A?.routingOverrides)try{let P=await A.routingOverrides();x=P.length?P:void 0}catch{}let I={...b,pointedAt:E,mcp:v,...x?{routingOverrides:x}:{},...C===void 0?{}:{claudeCodeHookPolicy:C}};x||delete I.routingOverrides,C===void 0&&delete I.claudeCodeHookPolicy,w.set(y.id,I),g+=Ey(b)-Ey(I)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},hV=e=>{K("Repair"),e.entries.length===0&&F(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?F(` ${t.title}: re-applied`):t.status==="queued"?F(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(S(` ${t.title}: ${t.status}`)):_(` ${t.title}: ${t.status}`);for(let t of e.notes)k(S(` ${t}`))},SI=async(e,t={})=>{let n=await D();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of IE(n.fallbackPort??ke))k(c?` ${c}`:"");return 0}let r;try{r=Pr(e.gateway,n)}catch(c){return e.json?(console.log(JSON.stringify({error:c.message})),1):(k(j("Anyray connect \u2014 doctor")),_(` Gateway URL: ${c.message}`),k(S(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(k(j("Anyray connect \u2014 doctor")),_(" --quick skips the network probes; it cannot be combined with --verify.")),1;let o=!e.noVerify&&!e.quick,a=await iV(r,n,!!e.verify&&!e.quick,t.adapters??ie,t.inferenceIntrospection??Yd,t.fleetBootstrap??jt,o,t.verifyAuth??Zi,!e.quick,t.checkTray??So,t.updateStatus??Io,t.readRefreshState??Kt,t.probeHookLane??Ra);e.repair&&a.retiredFallbackState.length>0&&(await hc(),a.retiredFallbackState=await $u(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await fV(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;e.json?console.log(JSON.stringify(uV(i),null,2)):(dV(i),s&&hV(s));try{e.quick||await(t.reportHealth??gS)(kI(i),i.connect.version)}catch{}return i.problems===0?0:1};var mV=()=>{let e=[];for(let t of ie){let n=t.skillsDir?.();n&&e.push(n)}return e},EI=async e=>{let t=await D();k(j("Anyray connect \u2014 sync"));let n;try{n=Pr(e.gateway,t)}catch(s){return _(s.message),1}M(`Gateway: ${n}`);let r=rx(t.clientKey,"anyray-placeholder"),o;try{o=await Ed(n,r)}catch(s){return _(`Team policy sync failed: ${Sd(s)}`),1}let a=mV();if(a.length===0)yV();else if(o.skills.length===0)M("No team skills published yet \u2014 nothing to sync.");else{let s=await zv(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?F(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):M(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await re({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){M(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${nt(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await xd(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(k(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&M(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){M(`Fleet policy reconcile skipped: ${Sd(s)}`)}return 0},yV=()=>{M("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as k2}from"node:zlib";import{promisify as C2}from"node:util";var Nr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Iy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),xI=e=>`
695
695
 
696
696
  \u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
697
697
 
698
- `,iu=(e,t={})=>{if(typeof e!="string")return Ey(String(e??""));let n=Math.max(1,t.maxChars??Dr.maxChars);if(e.length<=n)return Ey(e);let r=e.length,o=Math.max(0,t.headChars??Dr.headChars),a=Math.max(0,t.tailChars??Dr.tailChars),s=Math.max(0,t.middleWindows??Dr.middleWindows),i=100*(s+2),c=Math.max(1,n-1-i);o+a>c&&(a=Math.min(a,c),o=Math.max(0,c-a));let l=o,d=r-a,u=[];o>0&&u.push([0,o]);let f=c-o-a;if(s>0&&f>0&&d>l){let g=d-l,y=Math.max(1,Math.floor(f/s));for(let b=0;b<s;b++){let A=l+Math.round((b+.5)/s*g),v=Math.min(d,Math.max(l,A)+Math.ceil(y/2)),E=Math.max(l,v-y),I=e.lastIndexOf(`
699
- `,E);I>=l&&(E=I+1);let C=e.indexOf(`
700
- `,v);C!==-1&&C<d&&(v=C),v>E&&u.push([E,v])}}a>0&&u.push([d,r]),u.sort((g,y)=>g[0]-y[0]);let p=[];for(let[g,y]of u){let b=p[p.length-1];b&&g<=b[1]?b[1]=Math.max(b[1],y):p.push([g,y])}let h="",m=0;for(let[g,y]of p)g>m&&(h+=Cx(g-m)),h+=e.slice(g,y),m=y;if(r>m&&(h+=Cx(r-m)),h.length>=r)return Ey(e);let w=r-h.length;return{text:h,trimmed:!0,originalChars:r,trimmedChars:h.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},eV=["stdout","content","output","text","result"],Ax=e=>{if(typeof e=="string")return{body:e,rebuild:o=>o};if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(Array.isArray(t.content)){let o=t.content,a=[];for(let[i,c]of o.entries())c&&typeof c=="object"&&!Array.isArray(c)&&typeof c.text=="string"&&a.push({index:i,part:c,text:c.text});let s=Object.prototype.hasOwnProperty.call(t,"structuredContent")&&t.structuredContent!==void 0;if(a.length===1&&!s){let i=a[0];return{body:i.text,rebuild:c=>({...t,content:o.map((l,d)=>d===i.index?{...i.part,text:c}:l)})}}if(a.length>0||s){let i=a.map(({text:d},u)=>`--- MCP text part ${u+1} ---
698
+ `,du=(e,t={})=>{if(typeof e!="string")return Iy(String(e??""));let n=Math.max(1,t.maxChars??Nr.maxChars);if(e.length<=n)return Iy(e);let r=e.length,o=Math.max(0,t.headChars??Nr.headChars),a=Math.max(0,t.tailChars??Nr.tailChars),s=Math.max(0,t.middleWindows??Nr.middleWindows),i=100*(s+2),c=Math.max(1,n-1-i);o+a>c&&(a=Math.min(a,c),o=Math.max(0,c-a));let l=o,d=r-a,u=[];o>0&&u.push([0,o]);let f=c-o-a;if(s>0&&f>0&&d>l){let g=d-l,y=Math.max(1,Math.floor(f/s));for(let b=0;b<s;b++){let A=l+Math.round((b+.5)/s*g),v=Math.min(d,Math.max(l,A)+Math.ceil(y/2)),E=Math.max(l,v-y),x=e.lastIndexOf(`
699
+ `,E);x>=l&&(E=x+1);let C=e.indexOf(`
700
+ `,v);C!==-1&&C<d&&(v=C),v>E&&u.push([E,v])}}a>0&&u.push([d,r]),u.sort((g,y)=>g[0]-y[0]);let p=[];for(let[g,y]of u){let b=p[p.length-1];b&&g<=b[1]?b[1]=Math.max(b[1],y):p.push([g,y])}let h="",m=0;for(let[g,y]of p)g>m&&(h+=xI(g-m)),h+=e.slice(g,y),m=y;if(r>m&&(h+=xI(r-m)),h.length>=r)return Iy(e);let w=r-h.length;return{text:h,trimmed:!0,originalChars:r,trimmedChars:h.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},gV=["stdout","content","output","text","result"],II=e=>{if(typeof e=="string")return{body:e,rebuild:o=>o};if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(Array.isArray(t.content)){let o=t.content,a=[];for(let[i,c]of o.entries())c&&typeof c=="object"&&!Array.isArray(c)&&typeof c.text=="string"&&a.push({index:i,part:c,text:c.text});let s=Object.prototype.hasOwnProperty.call(t,"structuredContent")&&t.structuredContent!==void 0;if(a.length===1&&!s){let i=a[0];return{body:i.text,rebuild:c=>({...t,content:o.map((l,d)=>d===i.index?{...i.part,text:c}:l)})}}if(a.length>0||s){let i=a.map(({text:d},u)=>`--- MCP text part ${u+1} ---
701
701
  ${d}`);s&&i.push(`--- MCP structuredContent ---
702
702
  ${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
703
703
 
704
- `),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((f,p)=>l.has(p)?p!==c?.index?[]:[{...c.part,text:d}]:[f]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=eV.find(o=>typeof t[o]=="string");if(!n){let o=-1;for(let[a,s]of Object.entries(t))typeof s=="string"&&s.length>o&&(n=a,o=s.length)}if(!n)return null;let r=n;return{body:t[r],rebuild:o=>({...t,[r]:o})}};var tV=e=>{let t=e.trim();return t?t.length>=200&&!/\s/.test(t.slice(0,200).replace(/[{}[\],":]/g,""))?!0:/^\[?\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/.test(t)||/^\[?\d{2}:\d{2}:\d{2}/.test(t)||/^(ERROR|WARN|WARNING|INFO|DEBUG|TRACE|FATAL)\b/i.test(t)||/^\s*at\s+\S+\s+\(/.test(e)||/^\s*File ".+", line \d+/.test(e)||/^Traceback \(most recent call last\)/.test(t)||/^[{}[\]]/.test(t)||/[}\]],?$/.test(t)||/^"?[\w.-]+"?\s*[:=]\s+\S/.test(t):!1},Yi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},cu=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Yi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Yi.minDataLineRatio,o=t.minDataLines??Yi.minDataLines,a=e.split(`
705
- `),s=0,i=0;for(let c of a)c.trim()&&(s++,tV(c)&&i++);return s===0||i<o?!1:i/s>=r};var Zi=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,lu={pytest:"test-run",jest:"test-run",vitest:"test-run",mocha:"test-run",cargo:"test-run",go:"test-run",rg:"grep",grep:"grep",egrep:"grep",fgrep:"grep",ag:"grep",ack:"grep"},Ex=new Set(["npm","pnpm","yarn","bun"]),du=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},nV=e=>{let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return null;let o=du(r[0]);if(o in lu)return lu[o];if((o==="npx"||o==="bunx")&&r[1]){let a=du(r[1]);if(a in lu)return lu[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||Ex.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},xy=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=nV(t);if(n)return n}return null},rV={git:new Set(["log","diff","show","blame","shortlog","whatchanged"]),docker:new Set(["logs","ps","images","inspect","history","diff"]),podman:new Set(["logs","ps","images","inspect","history","diff"]),kubectl:new Set(["logs","get","describe"]),journalctl:null,dmesg:null,tsc:null,make:null,gradle:null,mvn:null,bazel:null},oV=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,aV=(e,t,n)=>{let r=(...o)=>n.some(a=>o.includes(a));return(e==="docker"||e==="podman"||e==="kubectl")&&t==="logs"||e==="journalctl"?r("-f","--follow"):e==="kubectl"&&t==="get"||e==="tsc"?r("-w","--watch"):!1},Ix=e=>{if(typeof e!="string"||!e.trim())return!1;let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return!1;let o=du(r[0]);if(Ex.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&oV.test(i)}let a=r[1]?du(r[1]):void 0;if(aV(o,a,r))return!1;let s=rV[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},sV=e=>{let t=e.trim();if(t.length<2)return!1;let n=t[0],r=t[t.length-1];return n==="{"&&r==="}"||n==="["&&r==="]"},iV=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},cV=e=>{let t=e.trim();if(t==="")return!1;let n=!0;for(let o=0;o<t.length;o++){let a=t[o];if(a!=="{"&&a!=="}"&&a!=="["&&a!=="]"&&a!==","){n=!1;break}}if(n)return!0;if(t[0]!=='"')return!1;let r=iV(t);return r>0&&t[r+1]===":"},lV=80,dV=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/lV),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,cV(e[o])&&r++;return n>0&&r/n>.3},uV=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,pV=e=>{let t=e.slice(0,80);if(t.length===0)return!1;let n=0;for(let r of t){let o=r.trim();(uV.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},fV=[/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b.*\bin\s+[\d.]+\s*s/i,/^=+ FAILURES =+/m,/^=+ short test summary/im,/test session starts/i,/^Test Suites:\s+\d+/m,/^Tests:\s+\d+\s+(failed|passed|total)/m,/^test result:\s+(ok|FAILED)\b/m,/^running \d+ tests?$/m,/^--- (FAIL|PASS): /m,/^(ok|FAIL)\s+\S+\s+[\d.]+s/m],Iy=8192,hV=e=>{let t=e.length>2*Iy?`${e.slice(0,Iy)}
706
- ${e.slice(-Iy)}`:e;return fV.some(n=>n.test(t))},mV=e=>/^[=~_—-]{4,}$/.test(e)||/^=+ .* =+$/.test(e)||/test session starts/i.test(e)||/^platform /i.test(e)||/^(rootdir|cachedir|configfile|plugins):/i.test(e)||/^collected \d+ items?/i.test(e)||/^Ran all test suites/.test(e)||/^(Snapshots|Time):/.test(e)||/^running \d+ tests?$/.test(e)||/^=== RUN /.test(e),yV=e=>/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b/i.test(e)&&/\bin\s+[\d.]+\s*s/i.test(e)||/^Test Suites:\s+\d+/.test(e)||/^Tests:\s+\d+/.test(e)||/^test result:\s+(ok|FAILED)\b/.test(e)||/^FAIL\s+\S+\s+[\d.]+s$/.test(e),gV=e=>{let t=/^_{2,}\s*(.+?)\s*_{2,}$/.exec(e);return t?`FAIL: ${t[1]}`:/^FAIL\s+\S+/.test(e)&&!/\s[\d.]+s$/.test(e)||/^--- FAIL: /.test(e)||/^---- .+ (stdout|stderr) ----$/.test(e)?e:null},wV=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),vx=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(yV(i)){t.push(Zi(i));continue}let c=gV(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Zi(c)),o=12;continue}mV(i)||wV(i)||o>0&&(t.push(Zi(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
707
- `),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},bV=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,xx=e=>{let t=bV.exec(e);return t&&/[/.]/.test(t[1])?t:null},kV=/^([^\s:]+)-(\d+)-/,CV=e=>{if(e==="--")return!0;let t=kV.exec(e);return t!=null&&/[/.]/.test(t[1])},AV=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>xx(r)!=null).length;return n>=3&&n/t.length>=.7},Sx=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=xx(c);if(!l){if(CV(c))return null;r++;continue}o++;let d=n.get(l[1])??[];d.push({line:l[2],content:l[3]}),n.set(l[1],d)}if(o===0||o/(o+r)<t)return null;let a=[`${o} matches in ${n.size} files:`],s=0,i=!1;for(let[c,l]of n){if(s>=200){i=!0;break}a.push("",`${c}:`);let d=Math.min(l.length,25,200-s);for(let u of l.slice(0,d))a.push(Zi(` ${u.line}: ${u.content.trim()}`)),s++;l.length>d&&a.push(` \u2026+${l.length-d} more in this file`)}return i&&a.push("",`\u2026+${o-s} more matches elided`),{text:a.join(`
708
- `),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},vV=e=>e.replace(/\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d(?:\.\d+)?Z?/g,"<TS>").replace(/\b\d\d:\d\d:\d\d\b/g,"<TS>").replace(/\b[0-9a-f]{2,}(?:-[0-9a-f]{2,}){2,}\b/gi,"<ID>").replace(/\b0x[0-9a-f]+\b/gi,"<HEX>").replace(/\b\d{8,}\b/g,"<NUM>").trim(),SV=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=vV(o),s=t.get(a);s?s.n++:(t.set(a,{first:o,n:1}),n.push(a))}return n.length/e.length>.6?null:{text:n.map(o=>{let{first:a,n:s}=t.get(o),i=Zi(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
709
- `),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},Rx=(e,t)=>{if(typeof t!="string"||t.length===0||sV(t))return null;let n=t.split(`
710
- `).filter(s=>s.trim()!==""),r=xy(e),o=hV(t),a=null;return r==="test-run"&&o?a=vx(n):r==="grep"&&(a=Sx(n,.5)),a||(o?a=vx(n):AV(n)?a=Sx(n,.7):!pV(n)&&!dV(n)&&(a=SV(n))),!a||a.text.length>=t.length?null:a},Ry=(e,t)=>t?`
704
+ `),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((f,p)=>l.has(p)?p!==c?.index?[]:[{...c.part,text:d}]:[f]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=gV.find(o=>typeof t[o]=="string");if(!n){let o=-1;for(let[a,s]of Object.entries(t))typeof s=="string"&&s.length>o&&(n=a,o=s.length)}if(!n)return null;let r=n;return{body:t[r],rebuild:o=>({...t,[r]:o})}};var wV=e=>{let t=e.trim();return t?t.length>=200&&!/\s/.test(t.slice(0,200).replace(/[{}[\],":]/g,""))?!0:/^\[?\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/.test(t)||/^\[?\d{2}:\d{2}:\d{2}/.test(t)||/^(ERROR|WARN|WARNING|INFO|DEBUG|TRACE|FATAL)\b/i.test(t)||/^\s*at\s+\S+\s+\(/.test(e)||/^\s*File ".+", line \d+/.test(e)||/^Traceback \(most recent call last\)/.test(t)||/^[{}[\]]/.test(t)||/[}\]],?$/.test(t)||/^"?[\w.-]+"?\s*[:=]\s+\S/.test(t):!1},Xi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},uu=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Xi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Xi.minDataLineRatio,o=t.minDataLines??Xi.minDataLines,a=e.split(`
705
+ `),s=0,i=0;for(let c of a)c.trim()&&(s++,wV(c)&&i++);return s===0||i<o?!1:i/s>=r};var Ji=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,pu={pytest:"test-run",jest:"test-run",vitest:"test-run",mocha:"test-run",cargo:"test-run",go:"test-run",rg:"grep",grep:"grep",egrep:"grep",fgrep:"grep",ag:"grep",ack:"grep"},_I=new Set(["npm","pnpm","yarn","bun"]),fu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},bV=e=>{let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return null;let o=fu(r[0]);if(o in pu)return pu[o];if((o==="npx"||o==="bunx")&&r[1]){let a=fu(r[1]);if(a in pu)return pu[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||_I.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},Ry=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=bV(t);if(n)return n}return null},kV={git:new Set(["log","diff","show","blame","shortlog","whatchanged"]),docker:new Set(["logs","ps","images","inspect","history","diff"]),podman:new Set(["logs","ps","images","inspect","history","diff"]),kubectl:new Set(["logs","get","describe"]),journalctl:null,dmesg:null,tsc:null,make:null,gradle:null,mvn:null,bazel:null},CV=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,AV=(e,t,n)=>{let r=(...o)=>n.some(a=>o.includes(a));return(e==="docker"||e==="podman"||e==="kubectl")&&t==="logs"||e==="journalctl"?r("-f","--follow"):e==="kubectl"&&t==="get"||e==="tsc"?r("-w","--watch"):!1},PI=e=>{if(typeof e!="string"||!e.trim())return!1;let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return!1;let o=fu(r[0]);if(_I.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&CV.test(i)}let a=r[1]?fu(r[1]):void 0;if(AV(o,a,r))return!1;let s=kV[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},vV=e=>{let t=e.trim();if(t.length<2)return!1;let n=t[0],r=t[t.length-1];return n==="{"&&r==="}"||n==="["&&r==="]"},SV=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},EV=e=>{let t=e.trim();if(t==="")return!1;let n=!0;for(let o=0;o<t.length;o++){let a=t[o];if(a!=="{"&&a!=="}"&&a!=="["&&a!=="]"&&a!==","){n=!1;break}}if(n)return!0;if(t[0]!=='"')return!1;let r=SV(t);return r>0&&t[r+1]===":"},xV=80,IV=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/xV),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,EV(e[o])&&r++;return n>0&&r/n>.3},OV=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,RV=e=>{let t=e.slice(0,80);if(t.length===0)return!1;let n=0;for(let r of t){let o=r.trim();(OV.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},_V=[/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b.*\bin\s+[\d.]+\s*s/i,/^=+ FAILURES =+/m,/^=+ short test summary/im,/test session starts/i,/^Test Suites:\s+\d+/m,/^Tests:\s+\d+\s+(failed|passed|total)/m,/^test result:\s+(ok|FAILED)\b/m,/^running \d+ tests?$/m,/^--- (FAIL|PASS): /m,/^(ok|FAIL)\s+\S+\s+[\d.]+s/m],Oy=8192,PV=e=>{let t=e.length>2*Oy?`${e.slice(0,Oy)}
706
+ ${e.slice(-Oy)}`:e;return _V.some(n=>n.test(t))},TV=e=>/^[=~_—-]{4,}$/.test(e)||/^=+ .* =+$/.test(e)||/test session starts/i.test(e)||/^platform /i.test(e)||/^(rootdir|cachedir|configfile|plugins):/i.test(e)||/^collected \d+ items?/i.test(e)||/^Ran all test suites/.test(e)||/^(Snapshots|Time):/.test(e)||/^running \d+ tests?$/.test(e)||/^=== RUN /.test(e),LV=e=>/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b/i.test(e)&&/\bin\s+[\d.]+\s*s/i.test(e)||/^Test Suites:\s+\d+/.test(e)||/^Tests:\s+\d+/.test(e)||/^test result:\s+(ok|FAILED)\b/.test(e)||/^FAIL\s+\S+\s+[\d.]+s$/.test(e),DV=e=>{let t=/^_{2,}\s*(.+?)\s*_{2,}$/.exec(e);return t?`FAIL: ${t[1]}`:/^FAIL\s+\S+/.test(e)&&!/\s[\d.]+s$/.test(e)||/^--- FAIL: /.test(e)||/^---- .+ (stdout|stderr) ----$/.test(e)?e:null},NV=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),OI=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(LV(i)){t.push(Ji(i));continue}let c=DV(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Ji(c)),o=12;continue}TV(i)||NV(i)||o>0&&(t.push(Ji(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
707
+ `),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},$V=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,TI=e=>{let t=$V.exec(e);return t&&/[/.]/.test(t[1])?t:null},MV=/^([^\s:]+)-(\d+)-/,FV=e=>{if(e==="--")return!0;let t=MV.exec(e);return t!=null&&/[/.]/.test(t[1])},UV=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>TI(r)!=null).length;return n>=3&&n/t.length>=.7},RI=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=TI(c);if(!l){if(FV(c))return null;r++;continue}o++;let d=n.get(l[1])??[];d.push({line:l[2],content:l[3]}),n.set(l[1],d)}if(o===0||o/(o+r)<t)return null;let a=[`${o} matches in ${n.size} files:`],s=0,i=!1;for(let[c,l]of n){if(s>=200){i=!0;break}a.push("",`${c}:`);let d=Math.min(l.length,25,200-s);for(let u of l.slice(0,d))a.push(Ji(` ${u.line}: ${u.content.trim()}`)),s++;l.length>d&&a.push(` \u2026+${l.length-d} more in this file`)}return i&&a.push("",`\u2026+${o-s} more matches elided`),{text:a.join(`
708
+ `),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},BV=e=>e.replace(/\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d(?:\.\d+)?Z?/g,"<TS>").replace(/\b\d\d:\d\d:\d\d\b/g,"<TS>").replace(/\b[0-9a-f]{2,}(?:-[0-9a-f]{2,}){2,}\b/gi,"<ID>").replace(/\b0x[0-9a-f]+\b/gi,"<HEX>").replace(/\b\d{8,}\b/g,"<NUM>").trim(),WV=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=BV(o),s=t.get(a);s?s.n++:(t.set(a,{first:o,n:1}),n.push(a))}return n.length/e.length>.6?null:{text:n.map(o=>{let{first:a,n:s}=t.get(o),i=Ji(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
709
+ `),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},LI=(e,t)=>{if(typeof t!="string"||t.length===0||vV(t))return null;let n=t.split(`
710
+ `).filter(s=>s.trim()!==""),r=Ry(e),o=PV(t),a=null;return r==="test-run"&&o?a=OI(n):r==="grep"&&(a=RI(n,.5)),a||(o?a=OI(n):UV(n)?a=RI(n,.7):!RV(n)&&!IV(n)&&(a=WV(n))),!a||a.text.length>=t.length?null:a},_y=(e,t)=>t?`
711
711
 
712
712
  \u2026[anyray-hook digest \u2014 ${e}; full output: ${t}]\u2026`:`
713
713
 
714
- \u2026[anyray-hook digest \u2014 ${e}]\u2026`,Ox=e=>`
714
+ \u2026[anyray-hook digest \u2014 ${e}]\u2026`,DI=e=>`
715
715
 
716
- \u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as EV}from"node:crypto";import{homedir as IV}from"node:os";import{join as To}from"node:path";import{chmod as xV,mkdir as RV,readdir as Lx,stat as Xi,unlink as Ji,utimes as OV,writeFile as _y}from"node:fs/promises";var uu={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},Dx=".swept",_V=".sweeping",_x=64,Tx=448,Ty=384,TV=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",Nx=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,$x=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=Q();try{if((await Xi(t)).isDirectory())return To(t,"hook-tee")}catch{}return To(IV(),".anyray-hook-tee")},PV=async(e,t={})=>{let n=t.limits??uu;try{let r=Date.now(),o=(await Lx(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=_x)await Promise.all(o.slice(c,c+_x).map(async l=>{let d=To(e,l);try{let u=await Xi(d);if(!u.isFile())return;let f=r-u.mtimeMs>n.ttlMs||r-Nx(u)>n.maxAgeMs;if(d!==t.protect&&f){await Ji(d);return}a.push({path:d,mtimeMs:u.mtimeMs,size:u.size})}catch{}}));a.sort((c,l)=>l.mtimeMs-c.mtimeMs);let s=0,i=0;for(let c of a){let l=s<n.maxFiles&&i+c.size<=n.maxTotalBytes,d=r-c.mtimeMs<n.writeGraceMs;if(l||s===0||c.path===t.protect||d){s+=1,i+=c.size;continue}await Ji(c.path).catch(()=>{})}}catch{}},Mx=async e=>{try{return Date.now()-(await Xi(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},Px=async e=>{try{return await _y(e,"",{mode:Ty,flag:"wx"}),!0}catch{return!1}},LV=async(e,t)=>{let n=uu,r=To(e,_V),o=To(e,Dx);if(!await Px(r)){let a=0;try{a=Date.now()-(await Xi(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await Ji(r).catch(()=>{}),!await Px(r)))return!1}try{return await Mx(o)<n.sweepIntervalMs?!1:(await _y(o,"",{mode:Ty}).catch(()=>{}),await PV(e,{protect:t}),!0)}finally{await Ji(r).catch(()=>{})}},Oy=async(e,t)=>await Mx(To(e,Dx))<uu.sweepIntervalMs?!1:LV(e,t),DV=async()=>{try{let e=await $x();if(!(await Lx(e)).some(t=>t.endsWith(".txt")))return;await Oy(e)}catch{}},Fx=async e=>{if(TV())return await DV(),null;try{let t=await $x();await RV(t,{recursive:!0,mode:Tx}),await xV(t,Tx).catch(()=>{});let n=`${EV("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=To(t,n),o=Date.now();try{let a=await Xi(r);if(a.isFile()){if(o-Nx(a)<=uu.maxAgeMs){let s=new Date(o);return await OV(r,s,s).catch(()=>{}),await Oy(t,r),r}await Ji(r).catch(()=>{})}}catch{}return await _y(r,e,{mode:Ty}),await Oy(t,r),r}catch{return null}};import{createHash as NV}from"node:crypto";import{homedir as Ux}from"node:os";import{join as Py}from"node:path";import{readFile as $V,writeFile as MV,chmod as FV,stat as UV,unlink as BV}from"node:fs/promises";var WV=200,HV=1440*60*1e3,KV=4e6,Bx=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",Wx=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},GV=()=>Wx("ANYRAY_HOOK_CACHE_MAX_ENTRIES",WV),Hx=()=>Wx("ANYRAY_HOOK_CACHE_TTL_MS",HV),Kx=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Py(Ux(),".anyray");try{if((await UV(t)).isDirectory())return Py(t,"hook-cache.json")}catch{}return Py(Ux(),".anyray-hook-cache.json")},Gx=(e,t,n)=>NV("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),jx=async e=>{try{let t=JSON.parse(await $V(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},Vx=async e=>{if(Bx())return null;try{let n=(await jx(await Kx())).entries[e];return!n||Date.now()-n.at>Hx()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},jV=e=>{let t=Date.now(),n=Hx(),r=Object.entries(e).filter(([,i])=>t-i.at<=n);r.sort((i,c)=>c[1].at-i[1].at);let o=[],a=0,s=GV();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>KV&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},Yx=async(e,t)=>{if(Bx())return;let n;try{let r=await Kx(),o=await jx(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=jV(o.entries),n=`${r}.${process.pid}.tmp`,await MV(n,JSON.stringify(o),{mode:384}),await FV(n,384),await he(n,r)}catch{if(n)try{await BV(n)}catch{}}};import{open as VV,stat as YV}from"node:fs/promises";var Zx=600,ZV=3,JV=256e3,XV=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
717
- `):"",zV=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),qV=e=>{let t=[];for(let n of e)if(!(!n||!n.trim()))try{let r=JSON.parse(n);r&&typeof r=="object"&&!Array.isArray(r)&&t.push(r)}catch{}return t},QV=e=>{let t=[],n=0;for(let r=e.length-1;r>=0;r--){let o=e[r];if(!o||o.type!=="user"||o.isMeta||o.isSidechain)continue;let a=XV(o.message?.content).trim();if(!(!a||zV(a))&&(t.unshift(a),n+=a.length,t.length>=ZV||n>=Zx))break}return t.join(`
718
- `).slice(0,Zx)};var e2=e=>/(^|[\\/])subagents[\\/]/i.test(e),t2=e=>/\.jsonl$/i.test(e),n2=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),Jx=async e=>{let t={intent:"",kind:"unknown"};if(!e||!t2(e))return t;let n;try{let{size:r}=await YV(e),o=Math.max(0,r-JV),a=r-o;if(a<=0)return t;n=await VV(e,"r");let s=new Uint8Array(a);await n.read(s,0,a,o);let i=new TextDecoder().decode(s);if(o>0){let l=i.indexOf(`
719
- `);i=l>=0?i.slice(l+1):""}let c=qV(i.split(`
720
- `));return n2(c)?{intent:QV(c),kind:e2(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var a2=3e3,s2=1500,i2=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:a2},c2={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},l2=new Set(["claude","opencode"]),d2=(e,t)=>{let n={};if(e)try{let r=JSON.parse(e);r&&typeof r=="object"&&!Array.isArray(r)&&(n=r)}catch{}return JSON.stringify({...n,tool:c2[t]})},u2={cacheGet:async()=>null,cachePut:async()=>{}},p2=(e,t={cacheGet:Vx,cachePut:Yx,tee:Fx})=>e==="claude"?t:u2,f2=1e3,h2=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),pu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),m2=e=>{try{let t=JSON.parse(e);if(!pu(t)||typeof t.tool_name!="string"||!t.tool_name.startsWith("MCP:")||typeof t.tool_output!="string")return;let n=JSON.parse(t.tool_output);return pu(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},y2=e=>{try{let t=JSON.parse(e);return pu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},g2=e=>pu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
721
- `:"",Ly=e=>Math.round(Math.max(0,e)/4),Xx=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",w2=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),b2=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),k2=["tool_output","tool_response","tool_result"],C2=e=>{for(let t of k2)if(t in e)return e[t]},A2=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},v2=120,S2=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??f2))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=Ry(r.stat,null).length+v2;if(r.text.length+o>=n.length)return null;let a=null;if(e.tee)try{a=await e.tee(n)}catch{a=null}let s=Ry(r.stat,a);return r.text.length+s.length>=n.length?null:{body:r.text,marker:s,teePath:a,decision:{router:r.router,kept:r.kept,total:r.total,teed:a!=null}}},E2=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let E=JSON.parse(e);if(!E||typeof E!="object")return n;r=E}catch{return n}let o=typeof r.tool_name=="string"?r.tool_name:"unknown";if(w2.has(o)||b2(o))return n;let a=Ax(C2(r));if(!a)return n;let s=async E=>{try{await t.beacon(o,E)}catch{}},i=a.body,c=typeof r.transcript_path=="string"?r.transcript_path:"",l={intent:"",retrievalContext:t.defaultRetrievalContext??"unknown"};if(t.readContext&&c)try{l=await t.readContext(c)}catch{l={intent:"",retrievalContext:"unknown"}}if(zx(o)&&l.retrievalContext!=="available")return n;let d=await S2(t,A2(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!cu(i,{minChars:s2})))return n;let p=i.length-u.length-f.length,h=async(E,I,C=E.length+f.length)=>{let x=d?.teePath??null;if(!x&&t.tee)try{x=await t.tee(i)}catch{x=null}let T=x?E.replaceAll("; not retrievable in this context]","]"):E,$=x&&!f?Ox(x):"",Y=T+f+$,Z=$.length,W=Y;if(t.finalizeOutput)try{let ne=t.finalizeOutput(Y);ne.length<=Y.length&&(W=ne)}catch{W=Y}let z=Y.length-W.length,me=Ly(Math.max(0,p-Z))+I+Ly(z);me>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,C+Z-z),estTokensSaved:me,...d&&{digest:d.decision}});let Le=a.rebuild(W);return{stdout:h2(Le),replacement:Le}},m=async()=>d?h(u,0):n;if(d&&u.length<=t.sizeGate)return h(u,0);let w=l.intent?`${l.intent}
722
- ${Xx(r.tool_input)}`:Xx(r.tool_input),g=Gx(o,w,u),y=async E=>{try{await t.cachePut(g,E)}catch{}},b=null;try{b=await t.cacheGet(g)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?h(b.output,b.tokensSaved):m();let A=null;try{A=T2(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{A=null}if(A&&!A.handled&&(A=null),A)return A.optimized&&A.output.length<u.length?(await y({optimized:!0,output:A.output,tokensSaved:Ly(u.length-A.output.length)}),h(A.output,0,u.length+f.length)):(await y({optimized:!1}),m());let v;try{v=t.localTrim(u)}catch{return m()}return v.trimmed?h(v.text,v.estTokensSaved):m()},zi=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},I2=()=>{let e=n=>{let r=process.env[n];if(!r)return;let o=Number(r);return Number.isFinite(o)&&o>0?o:void 0},t=n=>{let r=process.env[n];if(!r)return;let o=Number(r);return Number.isFinite(o)&&o>=0?Math.floor(o):void 0};return{maxChars:e("ANYRAY_HOOK_MAX_CHARS"),headChars:e("ANYRAY_HOOK_HEAD_CHARS"),tailChars:e("ANYRAY_HOOK_TAIL_CHARS"),middleWindows:t("ANYRAY_HOOK_MIDDLE_WINDOWS")}},x2=o2(r2),R2=async e=>{try{let t=await x2(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},zx=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),O2=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},_2=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),T2=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),P2=2048,L2=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,P2),n=xd(t);if(!n)return;await WS({at:Date.now(),status:e.status,code:n})}catch{}},D2=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),i2());try{let c=await R2(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...zx(t)||O2(t)&&a==="available"?{reversible:!0}:{},..._2(t)?{semanticRerank:!0}:{},output:r})),l=qt(e);c.encoding&&(l["content-encoding"]=c.encoding);let d=await fetch(`${e.origin}/connect/optimize-output`,{method:"POST",headers:l,body:c.body,signal:s.signal});if(!d.ok)return(d.status===401||d.status===403)&&await L2(d),null;let u=await d.json();return{optimized:u?.optimized===!0&&typeof u?.output=="string",output:typeof u?.output=="string"?u.output:r,handled:u?.handled===!0}}catch{return null}finally{clearTimeout(i)}},qx=async(e="claude")=>{let t=await zi();if(e!=="cursor"&&y2(t))return 0;let n=e==="cursor"?m2(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Dy(n,e);if(e==="cursor"){let a=g2(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Dy=async(e,t="claude",n)=>{await Rr(),await BS(t);let r=I2(),o=await rt(),a=o&&{...o,metadata:d2(o.metadata,t)},s=p2(t);return E2(e,{optimize:(i,c,l,d,u)=>D2(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await Jx(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>iu(i,r),beacon:(i,c)=>Ec(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Dr.maxChars,digestCommand:Rx,tee:s.tee,mediumBand:l2.has(t),finalizeOutput:n})};var Qx=async()=>0;var N2=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let a=JSON.parse(e);if(!a||typeof a!="object")return n;let s=a.prompt;if(typeof s!="string"||!s)return n;r=s}catch{return n}if(!t.isPaste(r))return n;let o=null;try{o=t.measure(r)}catch{o=null}if(!o||o.estTokensSaved<=0)return n;try{await t.beacon(o)}catch{}return n},$2=async(e,t={})=>{try{if(!e.trim())return;let n;try{n=JSON.parse(e)?.hook_event_name}catch{return}if(n!=="beforeSubmitPrompt")return;let r=await(t.readBootstrap??Vt)();if(!r)return;let o=await(t.ssoGate??Jn)({sso:r.sso,gateway:r.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(o.exitCode!==2||!o.stderr)return;let a=o.stderr.trim().replace(/Your prompt was not sent — complete sign-in, then resubmit it\.?/,"This request will fail until sign-in completes \u2014 then just continue chatting.");return`${JSON.stringify({continue:!0,user_message:a})}
723
- `}catch{return}},M2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},F2=()=>{let e=t=>{let n=process.env[t];if(!n)return;let r=Number(n);return Number.isFinite(r)&&r>0?r:void 0};return{minChars:e("ANYRAY_PROMPT_PASTE_MIN_CHARS"),minDataLines:e("ANYRAY_PROMPT_PASTE_MIN_LINES")}},U2=(e,t)=>{let n=t.minChars??Yi.minChars,r={maxChars:Math.min(Dr.maxChars,n)},o=iu(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},e0=async()=>{let e=await M2(),t=await $2(e);t&&process.stdout.write(t);let n=F2(),r=await rt();return await N2(e,{isPaste:o=>cu(o,n),measure:o=>U2(o,n),beacon:o=>Ec(r,"prompt",o)}),0};import{spawn as B2}from"node:child_process";var t0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),W2=/[|&;<>`$()\n]/,n0=e=>{if(W2.test(e))return null;let t=[],n="",r=!1,o=null;for(let a of e){if(o){if(a===o)o=null;else{if(o==='"'&&a==="\\")return null;n+=a,r=!0}continue}if(a==='"'||a==="'"){o=a,r=!0;continue}if(a===" "||a===" "){r&&(t.push(n),n="",r=!1);continue}if("*?[]{}~#\\".includes(a))return null;n+=a,r=!0}return o||(r&&t.push(n),!t.length)||/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0])?null:t},H2=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!t0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!t0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(ju)||!t.isRecognized(o)||n0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},K2=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?n0(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
716
+ \u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as HV}from"node:crypto";import{homedir as KV}from"node:os";import{join as _o}from"node:path";import{chmod as GV,mkdir as jV,readdir as FI,stat as zi,unlink as qi,utimes as VV,writeFile as Ty}from"node:fs/promises";var hu={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},UI=".swept",YV=".sweeping",NI=64,$I=448,Ly=384,ZV=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",BI=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,WI=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=Q();try{if((await zi(t)).isDirectory())return _o(t,"hook-tee")}catch{}return _o(KV(),".anyray-hook-tee")},XV=async(e,t={})=>{let n=t.limits??hu;try{let r=Date.now(),o=(await FI(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=NI)await Promise.all(o.slice(c,c+NI).map(async l=>{let d=_o(e,l);try{let u=await zi(d);if(!u.isFile())return;let f=r-u.mtimeMs>n.ttlMs||r-BI(u)>n.maxAgeMs;if(d!==t.protect&&f){await qi(d);return}a.push({path:d,mtimeMs:u.mtimeMs,size:u.size})}catch{}}));a.sort((c,l)=>l.mtimeMs-c.mtimeMs);let s=0,i=0;for(let c of a){let l=s<n.maxFiles&&i+c.size<=n.maxTotalBytes,d=r-c.mtimeMs<n.writeGraceMs;if(l||s===0||c.path===t.protect||d){s+=1,i+=c.size;continue}await qi(c.path).catch(()=>{})}}catch{}},HI=async e=>{try{return Date.now()-(await zi(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},MI=async e=>{try{return await Ty(e,"",{mode:Ly,flag:"wx"}),!0}catch{return!1}},JV=async(e,t)=>{let n=hu,r=_o(e,YV),o=_o(e,UI);if(!await MI(r)){let a=0;try{a=Date.now()-(await zi(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await qi(r).catch(()=>{}),!await MI(r)))return!1}try{return await HI(o)<n.sweepIntervalMs?!1:(await Ty(o,"",{mode:Ly}).catch(()=>{}),await XV(e,{protect:t}),!0)}finally{await qi(r).catch(()=>{})}},Py=async(e,t)=>await HI(_o(e,UI))<hu.sweepIntervalMs?!1:JV(e,t),qV=async()=>{try{let e=await WI();if(!(await FI(e)).some(t=>t.endsWith(".txt")))return;await Py(e)}catch{}},KI=async e=>{if(ZV())return await qV(),null;try{let t=await WI();await jV(t,{recursive:!0,mode:$I}),await GV(t,$I).catch(()=>{});let n=`${HV("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=_o(t,n),o=Date.now();try{let a=await zi(r);if(a.isFile()){if(o-BI(a)<=hu.maxAgeMs){let s=new Date(o);return await VV(r,s,s).catch(()=>{}),await Py(t,r),r}await qi(r).catch(()=>{})}}catch{}return await Ty(r,e,{mode:Ly}),await Py(t,r),r}catch{return null}};import{createHash as zV}from"node:crypto";import{homedir as GI}from"node:os";import{join as Dy}from"node:path";import{readFile as QV,writeFile as e2,chmod as t2,stat as n2,unlink as r2}from"node:fs/promises";var o2=200,a2=1440*60*1e3,s2=4e6,jI=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",VI=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},i2=()=>VI("ANYRAY_HOOK_CACHE_MAX_ENTRIES",o2),YI=()=>VI("ANYRAY_HOOK_CACHE_TTL_MS",a2),ZI=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Dy(GI(),".anyray");try{if((await n2(t)).isDirectory())return Dy(t,"hook-cache.json")}catch{}return Dy(GI(),".anyray-hook-cache.json")},XI=(e,t,n)=>zV("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),JI=async e=>{try{let t=JSON.parse(await QV(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},qI=async e=>{if(jI())return null;try{let n=(await JI(await ZI())).entries[e];return!n||Date.now()-n.at>YI()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},c2=e=>{let t=Date.now(),n=YI(),r=Object.entries(e).filter(([,i])=>t-i.at<=n);r.sort((i,c)=>c[1].at-i[1].at);let o=[],a=0,s=i2();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>s2&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},zI=async(e,t)=>{if(jI())return;let n;try{let r=await ZI(),o=await JI(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=c2(o.entries),n=`${r}.${process.pid}.tmp`,await e2(n,JSON.stringify(o),{mode:384}),await t2(n,384),await he(n,r)}catch{if(n)try{await r2(n)}catch{}}};import{open as l2,stat as d2}from"node:fs/promises";var QI=600,u2=3,p2=256e3,f2=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
717
+ `):"",h2=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),m2=e=>{let t=[];for(let n of e)if(!(!n||!n.trim()))try{let r=JSON.parse(n);r&&typeof r=="object"&&!Array.isArray(r)&&t.push(r)}catch{}return t},y2=e=>{let t=[],n=0;for(let r=e.length-1;r>=0;r--){let o=e[r];if(!o||o.type!=="user"||o.isMeta||o.isSidechain)continue;let a=f2(o.message?.content).trim();if(!(!a||h2(a))&&(t.unshift(a),n+=a.length,t.length>=u2||n>=QI))break}return t.join(`
718
+ `).slice(0,QI)};var g2=e=>/(^|[\\/])subagents[\\/]/i.test(e),w2=e=>/\.jsonl$/i.test(e),b2=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),e0=async e=>{let t={intent:"",kind:"unknown"};if(!e||!w2(e))return t;let n;try{let{size:r}=await d2(e),o=Math.max(0,r-p2),a=r-o;if(a<=0)return t;n=await l2(e,"r");let s=new Uint8Array(a);await n.read(s,0,a,o);let i=new TextDecoder().decode(s);if(o>0){let l=i.indexOf(`
719
+ `);i=l>=0?i.slice(l+1):""}let c=m2(i.split(`
720
+ `));return b2(c)?{intent:y2(c),kind:g2(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var A2=3e3,v2=1500,S2=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:A2},E2={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},x2=new Set(["claude","opencode"]),I2=(e,t)=>{let n={};if(e)try{let r=JSON.parse(e);r&&typeof r=="object"&&!Array.isArray(r)&&(n=r)}catch{}return JSON.stringify({...n,tool:E2[t]})},O2={cacheGet:async()=>null,cachePut:async()=>{}},R2=(e,t={cacheGet:qI,cachePut:zI,tee:KI})=>e==="claude"?t:O2,_2=1e3,P2=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),mu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),T2=e=>{try{let t=JSON.parse(e);if(!mu(t)||typeof t.tool_name!="string"||!t.tool_name.startsWith("MCP:")||typeof t.tool_output!="string")return;let n=JSON.parse(t.tool_output);return mu(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},L2=e=>{try{let t=JSON.parse(e);return mu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},D2=e=>mu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
721
+ `:"",Ny=e=>Math.round(Math.max(0,e)/4),t0=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",N2=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),$2=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),M2=["tool_output","tool_response","tool_result"],F2=e=>{for(let t of M2)if(t in e)return e[t]},U2=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},B2=120,W2=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??_2))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=_y(r.stat,null).length+B2;if(r.text.length+o>=n.length)return null;let a=null;if(e.tee)try{a=await e.tee(n)}catch{a=null}let s=_y(r.stat,a);return r.text.length+s.length>=n.length?null:{body:r.text,marker:s,teePath:a,decision:{router:r.router,kept:r.kept,total:r.total,teed:a!=null}}},H2=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let E=JSON.parse(e);if(!E||typeof E!="object")return n;r=E}catch{return n}let o=typeof r.tool_name=="string"?r.tool_name:"unknown";if(N2.has(o)||$2(o))return n;let a=II(F2(r));if(!a)return n;let s=async E=>{try{await t.beacon(o,E)}catch{}},i=a.body,c=typeof r.transcript_path=="string"?r.transcript_path:"",l={intent:"",retrievalContext:t.defaultRetrievalContext??"unknown"};if(t.readContext&&c)try{l=await t.readContext(c)}catch{l={intent:"",retrievalContext:"unknown"}}if(n0(o)&&l.retrievalContext!=="available")return n;let d=await W2(t,U2(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!uu(i,{minChars:v2})))return n;let p=i.length-u.length-f.length,h=async(E,x,C=E.length+f.length)=>{let I=d?.teePath??null;if(!I&&t.tee)try{I=await t.tee(i)}catch{I=null}let P=I?E.replaceAll("; not retrievable in this context]","]"):E,$=I&&!f?DI(I):"",Y=P+f+$,Z=$.length,W=Y;if(t.finalizeOutput)try{let ne=t.finalizeOutput(Y);ne.length<=Y.length&&(W=ne)}catch{W=Y}let q=Y.length-W.length,me=Ny(Math.max(0,p-Z))+x+Ny(q);me>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,C+Z-q),estTokensSaved:me,...d&&{digest:d.decision}});let Te=a.rebuild(W);return{stdout:P2(Te),replacement:Te}},m=async()=>d?h(u,0):n;if(d&&u.length<=t.sizeGate)return h(u,0);let w=l.intent?`${l.intent}
722
+ ${t0(r.tool_input)}`:t0(r.tool_input),g=XI(o,w,u),y=async E=>{try{await t.cachePut(g,E)}catch{}},b=null;try{b=await t.cacheGet(g)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?h(b.output,b.tokensSaved):m();let A=null;try{A=Z2(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{A=null}if(A&&!A.handled&&(A=null),A)return A.optimized&&A.output.length<u.length?(await y({optimized:!0,output:A.output,tokensSaved:Ny(u.length-A.output.length)}),h(A.output,0,u.length+f.length)):(await y({optimized:!1}),m());let v;try{v=t.localTrim(u)}catch{return m()}return v.trimmed?h(v.text,v.estTokensSaved):m()},Qi=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},K2=()=>{let e=n=>{let r=process.env[n];if(!r)return;let o=Number(r);return Number.isFinite(o)&&o>0?o:void 0},t=n=>{let r=process.env[n];if(!r)return;let o=Number(r);return Number.isFinite(o)&&o>=0?Math.floor(o):void 0};return{maxChars:e("ANYRAY_HOOK_MAX_CHARS"),headChars:e("ANYRAY_HOOK_HEAD_CHARS"),tailChars:e("ANYRAY_HOOK_TAIL_CHARS"),middleWindows:t("ANYRAY_HOOK_MIDDLE_WINDOWS")}},G2=C2(k2),j2=async e=>{try{let t=await G2(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},n0=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),V2=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},Y2=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),Z2=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),X2=2048,J2=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,X2),n=Rd(t);if(!n)return;await HS({at:Date.now(),status:e.status,code:n})}catch{}},q2=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),S2());try{let c=await j2(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...n0(t)||V2(t)&&a==="available"?{reversible:!0}:{},...Y2(t)?{semanticRerank:!0}:{},output:r})),l=zt(e);c.encoding&&(l["content-encoding"]=c.encoding);let d=await fetch(`${e.origin}/connect/optimize-output`,{method:"POST",headers:l,body:c.body,signal:s.signal});if(!d.ok)return(d.status===401||d.status===403)&&await J2(d),null;let u=await d.json();return{optimized:u?.optimized===!0&&typeof u?.output=="string",output:typeof u?.output=="string"?u.output:r,handled:u?.handled===!0}}catch{return null}finally{clearTimeout(i)}},r0=async(e="claude")=>{let t=await Qi();if(e!=="cursor"&&L2(t))return 0;let n=e==="cursor"?T2(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await $y(n,e);if(e==="cursor"){let a=D2(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},$y=async(e,t="claude",n)=>{await Rr(),await WS(t);let r=K2(),o=await ot(),a=o&&{...o,metadata:I2(o.metadata,t)},s=R2(t);return H2(e,{optimize:(i,c,l,d,u)=>q2(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await e0(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>du(i,r),beacon:(i,c)=>Ic(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Nr.maxChars,digestCommand:LI,tee:s.tee,mediumBand:x2.has(t),finalizeOutput:n})};var o0=async()=>0;var z2=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let a=JSON.parse(e);if(!a||typeof a!="object")return n;let s=a.prompt;if(typeof s!="string"||!s)return n;r=s}catch{return n}if(!t.isPaste(r))return n;let o=null;try{o=t.measure(r)}catch{o=null}if(!o||o.estTokensSaved<=0)return n;try{await t.beacon(o)}catch{}return n},Q2=async(e,t={})=>{try{if(!e.trim())return;let n;try{n=JSON.parse(e)?.hook_event_name}catch{return}if(n!=="beforeSubmitPrompt")return;let r=await(t.readBootstrap??jt)();if(!r)return;let o=await(t.ssoGate??qn)({sso:r.sso,gateway:r.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(o.exitCode!==2||!o.stderr)return;let a=o.stderr.trim().replace(/Your prompt was not sent — complete sign-in, then resubmit it\.?/,"This request will fail until sign-in completes \u2014 then just continue chatting.");return`${JSON.stringify({continue:!0,user_message:a})}
723
+ `}catch{return}},eY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},tY=()=>{let e=t=>{let n=process.env[t];if(!n)return;let r=Number(n);return Number.isFinite(r)&&r>0?r:void 0};return{minChars:e("ANYRAY_PROMPT_PASTE_MIN_CHARS"),minDataLines:e("ANYRAY_PROMPT_PASTE_MIN_LINES")}},nY=(e,t)=>{let n=t.minChars??Xi.minChars,r={maxChars:Math.min(Nr.maxChars,n)},o=du(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},a0=async()=>{let e=await eY(),t=await Q2(e);t&&process.stdout.write(t);let n=tY(),r=await ot();return await z2(e,{isPaste:o=>uu(o,n),measure:o=>nY(o,n),beacon:o=>Ic(r,"prompt",o)}),0};import{spawn as rY}from"node:child_process";var s0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),oY=/[|&;<>`$()\n]/,i0=e=>{if(oY.test(e))return null;let t=[],n="",r=!1,o=null;for(let a of e){if(o){if(a===o)o=null;else{if(o==='"'&&a==="\\")return null;n+=a,r=!0}continue}if(a==='"'||a==="'"){o=a,r=!0;continue}if(a===" "||a===" "){r&&(t.push(n),n="",r=!1);continue}if("*?[]{}~#\\".includes(a))return null;n+=a,r=!0}return o||(r&&t.push(n),!t.length)||/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0])?null:t},aY=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!s0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!s0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(Yu)||!t.isRecognized(o)||i0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},sY=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?i0(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
724
724
  `),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
725
- `),1}if(o.alreadyWritten)return o.code;let a=o.output;try{a=await t.trim(n,o.output)}catch{a=o.output}return t.write(a),o.code},G2=16*1024*1024,j2=e=>new Promise(t=>{let n=[],r=0,o=!1,a=!1,s=new Map,i=c=>{if(!a){a=!0;for(let[l,d]of s)process.off(l,d);t({output:o?"":Buffer.concat(n).toString("utf8"),code:c,...o?{alreadyWritten:!0}:{}})}};try{let c=B2(e[0],e.slice(1),{stdio:["inherit","pipe","pipe"]});for(let d of["SIGINT","SIGTERM","SIGHUP"]){let u=()=>{if(c.exitCode===null&&c.signalCode===null)try{c.kill(d)}catch{}};s.set(d,u),process.on(d,u)}let l=d=>{if(o){process.stdout.write(d);return}if(r+d.byteLength>G2){for(let u of n)process.stdout.write(u);n.length=0,process.stdout.write(d),o=!0;return}n.push(d),r+=d.byteLength};c.stdout?.on("data",l),c.stderr?.on("data",l),c.on("error",()=>i(1)),c.on("close",(d,u)=>i(typeof d=="number"?d:u?1:0))}catch{i(1)}}),V2=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Dy(n,"cursor");return typeof r=="string"?r:t},r0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return K2(t,{exec:j2,trim:V2,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},o0=async()=>{let e=await zi();if(process.platform==="win32")return 0;let t=H2(e,{isRecognized:n=>xy(n)!==null||Ix(n),wrap:n=>Lt(ju,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as Y2}from"node:crypto";import{homedir as a0}from"node:os";import{extname as Z2,isAbsolute as J2,join as Ny,resolve as qi,sep as s0}from"node:path";import{chmod as X2,readFile as z2,stat as u0,unlink as q2,writeFile as Q2}from"node:fs/promises";var My=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),eY=16*1024,i0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],tY=["pattern","query","regex","search"],nY=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".pdf",".zip",".gz",".tar",".tgz",".woff",".woff2",".ttf",".otf",".mp3",".mp4",".mov",".wasm",".so",".dylib",".dll",".exe",".bin",".parquet",".sqlite",".db"]),rY=720*60*1e3,oY=512,$y=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},aY=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],c0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(s0)?n:n+s0)),sY=(e,t,n)=>J2(e)?[qi(e)]:[...new Set([qi(t,e),...n.map(r=>qi(r,e))])],l0=(e,t,n)=>Y2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),d0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),iY=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!My(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!My(o))return"";let a=aY(n.workspace_roots).map(d=>qi(d));if(!a.length)return"";let s=typeof n.cwd=="string"&&n.cwd?n.cwd:a[0],i=typeof n.conversation_id=="string"&&n.conversation_id||typeof n.session_id=="string"&&n.session_id||"";if(r==="Grep"){let d=$y(o,tY);if(!d)return"";let u=$y(o,i0);return u&&!c0(qi(s,u),a)||!await t.remember(l0(i,"Grep",d))?"":d0(`Anyray: run this search with the anyray_search MCP tool instead of the built-in search. anyray_search ranks the matches by relevance and drops the noise, so the hits that answer the task reach you without the rest. Call anyray_search with query ${JSON.stringify(d)} now; do not retry the built-in search.`)}let c=$y(o,i0);if(!c||nY.has(Z2(c).toLowerCase()))return"";let l=await t.resolveFile(sY(c,s,a));return!l||l.bytes<eY||!c0(l.path,a)||!await t.remember(l0(i,"Read",l.path))?"":d0(`Anyray: ${JSON.stringify(l.path)} is ${Math.round(l.bytes/1024)} KB \u2014 read it with the anyray_read MCP tool instead of the built-in read. anyray_read returns the part of the file that answers the task plus a retrieve handle (ctx_\u2026) you can pass to anyray_retrieve for any detail it elided, so the whole file never enters the context. Call anyray_read now; do not retry the built-in read.`)},cY=async e=>{for(let t of e)try{let n=await u0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},lY=async()=>{let e=Ny(a0(),".anyray");try{if((await u0(e)).isDirectory())return Ny(e,"cursor-redirects.json")}catch{}return Ny(a0(),".anyray-cursor-redirects.json")},dY=async e=>{let t;try{let n=await lY(),r=Date.now(),o={};try{let s=JSON.parse(await z2(n,"utf-8"));if(s?.v===1&&My(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=rY&&(o[i]=c)}catch{}if(o[e]!==void 0)return!1;o[e]=r;let a=Object.entries(o).sort((s,i)=>i[1]-s[1]).slice(0,oY);return t=`${n}.${process.pid}.tmp`,await Q2(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await X2(t,384),await he(t,n),!0}catch{if(t)try{await q2(t)}catch{}return!1}},p0=async()=>{let e=await zi(),t="";try{t=await iY(e,{resolveFile:cY,remember:dY})}catch{t=""}return t&&process.stdout.write(t),0};var Qi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Fy=e=>typeof e=="string"&&e.trim()?e.trim():void 0,uY=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Qi(n,"deviceCode"),o=Qi(n,"privateKeyPem"),a=Qi(n,"publicKeyPem"),s=Qi(n,"cpOrigin"),i=Qi(n,"tenantId"),c=n.intervalMs,l=n.grantExpiresAt,d=n.startedAt;if(!r||!o||!a||!s||!i||typeof c!="number"||!Number.isFinite(c)||typeof l!="number"||!Number.isFinite(l)||typeof d!="number"||!Number.isFinite(d))return null;let u=Fy(n.gatewayUrl),f=Fy(n.gatewayOverride),p=Fy(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...f?{gatewayOverride:f}:{},...p?{team:p}:{}}}catch{return null}},pY=e=>new Promise(t=>setTimeout(t,e)),fY=async(e,t)=>{let n=await t.readGateState()??{v:1};await t.writeGateState({v:1,lastAttemptAt:t.now(),failureCount:(n.failureCount??0)+1,lastFailure:e})},hY=async(e,t={})=>{let n=t.poll??Fd,r=t.verify??ln,o=t.loadProfile??L,a=t.saveProfile??re,s=t.saveDevKey??dc,i=t.readGateState??Or,c=t.writeGateState??Ud,l=t.clearGateState??qS,d=t.sleep??pY,u=t.now??Date.now,f=t.recordMint??Oa,p=t.reserveMint??vo,h=t.applyClaudeCode??(async I=>{await sr.apply(I,{dryRun:!1})}),m=I=>fY(I,{readGateState:i,writeGateState:c,now:u}),w={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g;try{g=await n(w,{gatewayUrl:e.gatewayOverride})}catch(I){let C=I instanceof jt?I.kind:"cp-unreachable";return await m(C),C}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),A={...b,gateway:y??b.gateway,name:g.cert.payload.user||b.name,team:e.team??g.cert.payload.team??b.team,enrolledCert:g.cert,enrolledCertExpiry:g.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(g.privateKeyPem),await a(A)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let v;await p();for(let I=0;I<3;I++)try{v=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(C){if(C instanceof Rt||I===2)break;await d(1e3)}if(!v)return await m("gateway-unreachable"),"gateway-unreachable";let E={...A,gateway:y,name:v.user,team:e.team??v.team??A.team,clientKey:v.key,clientKeyExpiresAt:v.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:v.expiresAt});let I=ge({origin:y,clientKey:v.key,subscription:!0,user:E.name,team:E.team});return await h(I),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},mY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},f0=async()=>{let e=uY(await mY());if(e)try{await hY(e)}catch{}return 0};var yY=1e4,Uy=/^[\w.:-]{1,64}$/,Jt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},By=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,h0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),yY);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new Jt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},gY=e=>{let t=By(e);if(!t)return;let n=t.browser_url;try{if(typeof n!="string")return;let r=new URL(n);if(r.protocol!=="http:"&&r.protocol!=="https:")return}catch{return}if(!(typeof t.id!="string"||!t.id||typeof t.user_code!="string"||!t.user_code||typeof t.poll_secret!="string"||!t.poll_secret||typeof t.interval!="number"||!Number.isFinite(t.interval)||t.interval<=0||typeof t.expires_in!="number"||!Number.isFinite(t.expires_in)||t.expires_in<=0))return{id:t.id,browser_url:n,user_code:t.user_code,poll_secret:t.poll_secret,interval:t.interval,expires_in:t.expires_in}},wY=e=>{let t=By(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Uy.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Uy.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},bY=e=>{let t=By(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!xe(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Uy.test(t.team)))return{status:"complete",key:t.key,user:t.user,team:t.team,...typeof t.expires_at=="string"&&{expires_at:t.expires_at}}},kY=e=>new Promise(t=>setTimeout(t,e)),CY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Jt("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}k("Available teams:"),e.forEach((i,c)=>k(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Ma("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Jt("invalid-team","Choose one of the teams shown above.");return s},AY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??kY,a=t.loadProfile??L,s=t.saveProfile??re,i=t.clearDevKey??rs,c=t.chooseTeam??CY,l=t.apply??(async g=>{await sr.apply(g,{dryRun:!1})}),d=t.log??M,u=await a(),f=_r(e.gateway,u),p=await h0(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=gY(p.body);if(p.status!==200||!h)throw new Jt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${h.browser_url}`),d(`Enter this code in the browser: ${h.user_code}`),(t.openBrowser??_a)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await h0(`${f}/sso/cli/poll/${encodeURIComponent(h.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":h.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(g.status===202){await o(h.interval*1e3);continue}if(g.status===401)throw new Jt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new Jt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=wY(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new Jt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??Yt());continue}let b=bY(g.body);if(g.status!==200||!b)throw new Jt("login-failed","SSO login could not be completed.");let A={...u,gateway:f,name:b.user,team:b.team,clientKey:b.key,clientKeyExpiresAt:b.expires_at,enrolledCert:void 0,enrolledCertExpiry:void 0,enrolledTokenHash:void 0,ssoLink:void 0,authMode:"subscription"};return await i(),await s(A),await l(ge({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Jt("expired","SSO login expired before it completed. Run anyray-connect login again.")},vY=`anyray-connect login [--gateway <url>] [--team <name>]
725
+ `),1}if(o.alreadyWritten)return o.code;let a=o.output;try{a=await t.trim(n,o.output)}catch{a=o.output}return t.write(a),o.code},iY=16*1024*1024,cY=e=>new Promise(t=>{let n=[],r=0,o=!1,a=!1,s=new Map,i=c=>{if(!a){a=!0;for(let[l,d]of s)process.off(l,d);t({output:o?"":Buffer.concat(n).toString("utf8"),code:c,...o?{alreadyWritten:!0}:{}})}};try{let c=rY(e[0],e.slice(1),{stdio:["inherit","pipe","pipe"]});for(let d of["SIGINT","SIGTERM","SIGHUP"]){let u=()=>{if(c.exitCode===null&&c.signalCode===null)try{c.kill(d)}catch{}};s.set(d,u),process.on(d,u)}let l=d=>{if(o){process.stdout.write(d);return}if(r+d.byteLength>iY){for(let u of n)process.stdout.write(u);n.length=0,process.stdout.write(d),o=!0;return}n.push(d),r+=d.byteLength};c.stdout?.on("data",l),c.stderr?.on("data",l),c.on("error",()=>i(1)),c.on("close",(d,u)=>i(typeof d=="number"?d:u?1:0))}catch{i(1)}}),lY=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await $y(n,"cursor");return typeof r=="string"?r:t},c0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return sY(t,{exec:cY,trim:lY,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},l0=async()=>{let e=await Qi();if(process.platform==="win32")return 0;let t=aY(e,{isRecognized:n=>Ry(n)!==null||PI(n),wrap:n=>Tt(Yu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as dY}from"node:crypto";import{homedir as d0}from"node:os";import{extname as uY,isAbsolute as pY,join as My,resolve as ec,sep as u0}from"node:path";import{chmod as fY,readFile as hY,stat as y0,unlink as mY,writeFile as yY}from"node:fs/promises";var Uy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),gY=16*1024,p0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],wY=["pattern","query","regex","search"],bY=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".pdf",".zip",".gz",".tar",".tgz",".woff",".woff2",".ttf",".otf",".mp3",".mp4",".mov",".wasm",".so",".dylib",".dll",".exe",".bin",".parquet",".sqlite",".db"]),kY=720*60*1e3,CY=512,Fy=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},AY=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],f0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(u0)?n:n+u0)),vY=(e,t,n)=>pY(e)?[ec(e)]:[...new Set([ec(t,e),...n.map(r=>ec(r,e))])],h0=(e,t,n)=>dY("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),m0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),SY=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!Uy(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!Uy(o))return"";let a=AY(n.workspace_roots).map(d=>ec(d));if(!a.length)return"";let s=typeof n.cwd=="string"&&n.cwd?n.cwd:a[0],i=typeof n.conversation_id=="string"&&n.conversation_id||typeof n.session_id=="string"&&n.session_id||"";if(r==="Grep"){let d=Fy(o,wY);if(!d)return"";let u=Fy(o,p0);return u&&!f0(ec(s,u),a)||!await t.remember(h0(i,"Grep",d))?"":m0(`Anyray: run this search with the anyray_search MCP tool instead of the built-in search. anyray_search ranks the matches by relevance and drops the noise, so the hits that answer the task reach you without the rest. Call anyray_search with query ${JSON.stringify(d)} now; do not retry the built-in search.`)}let c=Fy(o,p0);if(!c||bY.has(uY(c).toLowerCase()))return"";let l=await t.resolveFile(vY(c,s,a));return!l||l.bytes<gY||!f0(l.path,a)||!await t.remember(h0(i,"Read",l.path))?"":m0(`Anyray: ${JSON.stringify(l.path)} is ${Math.round(l.bytes/1024)} KB \u2014 read it with the anyray_read MCP tool instead of the built-in read. anyray_read returns the part of the file that answers the task plus a retrieve handle (ctx_\u2026) you can pass to anyray_retrieve for any detail it elided, so the whole file never enters the context. Call anyray_read now; do not retry the built-in read.`)},EY=async e=>{for(let t of e)try{let n=await y0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},xY=async()=>{let e=My(d0(),".anyray");try{if((await y0(e)).isDirectory())return My(e,"cursor-redirects.json")}catch{}return My(d0(),".anyray-cursor-redirects.json")},IY=async e=>{let t;try{let n=await xY(),r=Date.now(),o={};try{let s=JSON.parse(await hY(n,"utf-8"));if(s?.v===1&&Uy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=kY&&(o[i]=c)}catch{}if(o[e]!==void 0)return!1;o[e]=r;let a=Object.entries(o).sort((s,i)=>i[1]-s[1]).slice(0,CY);return t=`${n}.${process.pid}.tmp`,await yY(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await fY(t,384),await he(t,n),!0}catch{if(t)try{await mY(t)}catch{}return!1}},g0=async()=>{let e=await Qi(),t="";try{t=await SY(e,{resolveFile:EY,remember:IY})}catch{t=""}return t&&process.stdout.write(t),0};var tc=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},By=e=>typeof e=="string"&&e.trim()?e.trim():void 0,OY=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=tc(n,"deviceCode"),o=tc(n,"privateKeyPem"),a=tc(n,"publicKeyPem"),s=tc(n,"cpOrigin"),i=tc(n,"tenantId"),c=n.intervalMs,l=n.grantExpiresAt,d=n.startedAt;if(!r||!o||!a||!s||!i||typeof c!="number"||!Number.isFinite(c)||typeof l!="number"||!Number.isFinite(l)||typeof d!="number"||!Number.isFinite(d))return null;let u=By(n.gatewayUrl),f=By(n.gatewayOverride),p=By(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...f?{gatewayOverride:f}:{},...p?{team:p}:{}}}catch{return null}},RY=e=>new Promise(t=>setTimeout(t,e)),_Y=async(e,t)=>{let n=await t.readGateState()??{v:1};await t.writeGateState({v:1,lastAttemptAt:t.now(),failureCount:(n.failureCount??0)+1,lastFailure:e})},PY=async(e,t={})=>{let n=t.poll??Bd,r=t.verify??ln,o=t.loadProfile??D,a=t.saveProfile??re,s=t.saveDevKey??pc,i=t.readGateState??_r,c=t.writeGateState??Wd,l=t.clearGateState??QS,d=t.sleep??RY,u=t.now??Date.now,f=t.recordMint??_a,p=t.reserveMint??Ao,h=t.applyClaudeCode??(async x=>{await cr.apply(x,{dryRun:!1})}),m=x=>_Y(x,{readGateState:i,writeGateState:c,now:u}),w={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g;try{g=await n(w,{gatewayUrl:e.gatewayOverride})}catch(x){let C=x instanceof Gt?x.kind:"cp-unreachable";return await m(C),C}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),A={...b,gateway:y??b.gateway,name:g.cert.payload.user||b.name,team:e.team??g.cert.payload.team??b.team,enrolledCert:g.cert,enrolledCertExpiry:g.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(g.privateKeyPem),await a(A)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let v;await p();for(let x=0;x<3;x++)try{v=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(C){if(C instanceof Ot||x===2)break;await d(1e3)}if(!v)return await m("gateway-unreachable"),"gateway-unreachable";let E={...A,gateway:y,name:v.user,team:e.team??v.team??A.team,clientKey:v.key,clientKeyExpiresAt:v.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:v.expiresAt});let x=ge({origin:y,clientKey:v.key,subscription:!0,user:E.name,team:E.team});return await h(x),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},TY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},w0=async()=>{let e=OY(await TY());if(e)try{await PY(e)}catch{}return 0};var LY=1e4,Wy=/^[\w.:-]{1,64}$/,Zt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Hy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,b0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),LY);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new Zt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},DY=e=>{let t=Hy(e);if(!t)return;let n=t.browser_url;try{if(typeof n!="string")return;let r=new URL(n);if(r.protocol!=="http:"&&r.protocol!=="https:")return}catch{return}if(!(typeof t.id!="string"||!t.id||typeof t.user_code!="string"||!t.user_code||typeof t.poll_secret!="string"||!t.poll_secret||typeof t.interval!="number"||!Number.isFinite(t.interval)||t.interval<=0||typeof t.expires_in!="number"||!Number.isFinite(t.expires_in)||t.expires_in<=0))return{id:t.id,browser_url:n,user_code:t.user_code,poll_secret:t.poll_secret,interval:t.interval,expires_in:t.expires_in}},NY=e=>{let t=Hy(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Wy.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Wy.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},$Y=e=>{let t=Hy(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!xe(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Wy.test(t.team)))return{status:"complete",key:t.key,user:t.user,team:t.team,...typeof t.expires_at=="string"&&{expires_at:t.expires_at}}},MY=e=>new Promise(t=>setTimeout(t,e)),FY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Zt("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}k("Available teams:"),e.forEach((i,c)=>k(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Fa("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Zt("invalid-team","Choose one of the teams shown above.");return s},UY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??MY,a=t.loadProfile??D,s=t.saveProfile??re,i=t.clearDevKey??as,c=t.chooseTeam??FY,l=t.apply??(async g=>{await cr.apply(g,{dryRun:!1})}),d=t.log??M,u=await a(),f=Pr(e.gateway,u),p=await b0(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=DY(p.body);if(p.status!==200||!h)throw new Zt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${h.browser_url}`),d(`Enter this code in the browser: ${h.user_code}`),(t.openBrowser??Pa)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await b0(`${f}/sso/cli/poll/${encodeURIComponent(h.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":h.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(g.status===202){await o(h.interval*1e3);continue}if(g.status===401)throw new Zt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new Zt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=NY(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new Zt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??Vt());continue}let b=$Y(g.body);if(g.status!==200||!b)throw new Zt("login-failed","SSO login could not be completed.");let A={...u,gateway:f,name:b.user,team:b.team,clientKey:b.key,clientKeyExpiresAt:b.expires_at,enrolledCert:void 0,enrolledCertExpiry:void 0,enrolledTokenHash:void 0,ssoLink:void 0,authMode:"subscription"};return await i(),await s(A),await l(ge({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Zt("expired","SSO login expired before it completed. Run anyray-connect login again.")},BY=`anyray-connect login [--gateway <url>] [--team <name>]
726
726
 
727
727
  Start browser SSO, choose a team, mint a personal gateway key, and configure
728
728
  the subscription-backed Connect lane. In a non-interactive shell, --team may be
729
- omitted only when the identity authority supplies a default or sole team.`,m0=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return k(vY),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return _(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return _(`unknown login option: ${a}`),1}try{let o=await AY({gateway:n,team:r},t);return F(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof wt)throw o;return _(o instanceof Jt?o.message:"SSO login failed."),1}};var y0=`anyray-connect update [--check] [--auto on|off] [--json]
729
+ omitted only when the identity authority supplies a default or sole team.`,k0=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return k(BY),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return _(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return _(`unknown login option: ${a}`),1}try{let o=await UY({gateway:n,team:r},t);return F(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof bt)throw o;return _(o instanceof Zt?o.message:"SSO login failed."),1}};var C0=`anyray-connect update [--check] [--auto on|off] [--json]
730
730
 
731
731
  Keep this machine's anyray-connect binary on the published release. Runs
732
732
  automatically about every 30 minutes; this command forces it now.
@@ -737,32 +737,32 @@ Options:
737
737
  Off still accepts a release the Anyray team marks mandatory.
738
738
  --json Emit the result as JSON.
739
739
  --help Show this help.
740
- `,SY=e=>{let t={check:!1,json:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--check")t.check=!0;else if(r==="--json")t.json=!0;else if(r==="--help"||r==="-h")t.help=!0;else if(r==="--auto"){let o=e[++n];if(o!=="on"&&o!=="off")throw new Error("--auto takes `on` or `off`.");t.auto=o==="on"}else throw new Error(`Unknown option: ${r}`)}return t},EY=e=>{switch(e.outcome){case"current":return`Already on the published version (${e.current}).`;case"available":return`Version ${e.latest} is published; this machine is on ${e.current}.`;case"updated":return`Updated ${e.current} \u2192 ${e.latest}. New commands run it immediately.`;case"migrated":return`Installed the managed ${e.latest} binary at ${e.managedPath}.`;case"migration-available":return`Version ${e.latest} will migrate this npm runtime to the managed standalone binary.`;case"migration-deferred":return`The published standalone binary (${e.latest}) is older than this npm runtime (${e.current}); migration was deferred.`;case"disabled":return`Automatic updates are off. Version ${e.latest} is published; this machine is on ${e.current}.`;case"unmanaged":return"This copy is not an Anyray-managed or npm runtime, so it updates elsewhere.";case"container":return"Self-update is skipped inside a container \u2014 it updates by rebuild, not by download-and-swap.";case"platform-unsupported":return"Self-update is unavailable because this platform has no published standalone binary.";case"unavailable":return"Could not reach the release feed to check for a newer version.";case"failed":return`Could not install ${e.latest??"the published version"} \u2014 staying on ${e.current}.`}},g0=async e=>{let t;try{t=SY(e)}catch(o){return _(o.message),process.stderr.write(y0),1}if(t.help)return process.stdout.write(y0),0;if(t.auto!==void 0){let o=await L();if(o.autoUpdate!==!1!==t.auto&&await re({...o,autoUpdate:t.auto}),t.json||(F(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||k("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!t.auto)return t.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
741
- `),0}let n=await Gi({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await Ro();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state},null,2)}
742
- `),n.outcome==="failed"?1:0}let r=EY(n);switch(n.outcome){case"updated":case"migrated":F(r);break;case"current":F(r);break;case"available":case"migration-available":k(r),t.check&&k(`Run ${j("anyray-connect update")} to install it.`);break;case"migration-deferred":D(r),k(S("Use the newer npm runtime until that standalone release is published."));break;case"disabled":D(r),k(`Run ${j("anyray-connect update")} to install it now, or ${j("--auto on")} to resume.`);break;case"unmanaged":k(r),k(S("A copy your IT team placed is theirs to roll."));break;case"container":k(r);break;case"platform-unsupported":D(r),k(S("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":D(r);break;case"failed":return _(r),1}return 0};var IY=3e3,w0=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>fy(IY)),o=e.updateStatus??Ro;t(`anyray-connect ${we}
743
- `);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&Ha(a,we)>0){let i="Run `anyray-connect update` to install the latest version.";s?.state==="will-migrate"?i="Run `anyray-connect update` to install the managed standalone binary.":s?.state==="container"?i="Self-update is off in this container; updates arrive when it is rebuilt.":s?.state==="platform-unsupported"?i="Self-update is unavailable on this platform; run `npx anyray-connect@latest`.":s?.state==="unmanaged"&&(i="Update this copy with the method that installed it."),n(`Update available: ${we} \u2192 ${a}
740
+ `,WY=e=>{let t={check:!1,json:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--check")t.check=!0;else if(r==="--json")t.json=!0;else if(r==="--help"||r==="-h")t.help=!0;else if(r==="--auto"){let o=e[++n];if(o!=="on"&&o!=="off")throw new Error("--auto takes `on` or `off`.");t.auto=o==="on"}else throw new Error(`Unknown option: ${r}`)}return t},HY=e=>{switch(e.outcome){case"current":return`Already on the published version (${e.current}).`;case"available":return`Version ${e.latest} is published; this machine is on ${e.current}.`;case"updated":return`Updated ${e.current} \u2192 ${e.latest}. New commands run it immediately.`;case"migrated":return`Installed the managed ${e.latest} binary at ${e.managedPath}.`;case"migration-available":return`Version ${e.latest} will migrate this npm runtime to the managed standalone binary.`;case"migration-deferred":return`The published standalone binary (${e.latest}) is older than this npm runtime (${e.current}); migration was deferred.`;case"disabled":return`Automatic updates are off. Version ${e.latest} is published; this machine is on ${e.current}.`;case"unmanaged":return"This copy is not an Anyray-managed or npm runtime, so it updates elsewhere.";case"container":return"Self-update is skipped inside a container \u2014 it updates by rebuild, not by download-and-swap.";case"platform-unsupported":return"Self-update is unavailable because this platform has no published standalone binary.";case"unavailable":return"Could not reach the release feed to check for a newer version.";case"failed":return`Could not install ${e.latest??"the published version"} \u2014 staying on ${e.current}.`}},A0=async e=>{let t;try{t=WY(e)}catch(o){return _(o.message),process.stderr.write(C0),1}if(t.help)return process.stdout.write(C0),0;if(t.auto!==void 0){let o=await D();if(o.autoUpdate!==!1!==t.auto&&await re({...o,autoUpdate:t.auto}),t.json||(F(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||k("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!t.auto)return t.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
741
+ `),0}let n=await Vi({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await Io();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state},null,2)}
742
+ `),n.outcome==="failed"?1:0}let r=HY(n);switch(n.outcome){case"updated":case"migrated":F(r);break;case"current":F(r);break;case"available":case"migration-available":k(r),t.check&&k(`Run ${j("anyray-connect update")} to install it.`);break;case"migration-deferred":L(r),k(S("Use the newer npm runtime until that standalone release is published."));break;case"disabled":L(r),k(`Run ${j("anyray-connect update")} to install it now, or ${j("--auto on")} to resume.`);break;case"unmanaged":k(r),k(S("A copy your IT team placed is theirs to roll."));break;case"container":k(r);break;case"platform-unsupported":L(r),k(S("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":L(r);break;case"failed":return _(r),1}return 0};var KY=3e3,v0=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>my(KY)),o=e.updateStatus??Io;t(`anyray-connect ${we}
743
+ `);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&Ka(a,we)>0){let i="Run `anyray-connect update` to install the latest version.";s?.state==="will-migrate"?i="Run `anyray-connect update` to install the managed standalone binary.":s?.state==="container"?i="Self-update is off in this container; updates arrive when it is rebuilt.":s?.state==="platform-unsupported"?i="Self-update is unavailable on this platform; run `npx anyray-connect@latest`.":s?.state==="unmanaged"&&(i="Update this copy with the method that installed it."),n(`Update available: ${we} \u2192 ${a}
744
744
  ${i}
745
- `)}else s?.state==="will-migrate"?n("This npm runtime will migrate to the managed standalone binary on the next persistent setup change.\nRun `anyray-connect update` to migrate now.\n"):s?.state==="container"?n("Self-update and the npm-to-managed-binary migration are off in this container.\nUpdates arrive when the container is rebuilt, not via `anyray-connect update`.\n"):s?.state==="platform-unsupported"&&n("Self-update is unavailable on this platform; use `npx anyray-connect@latest` to stay current.\n");return 0};var xY=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},RY=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),OY=async(e={})=>{try{let t=await(e.readBootstrap??Vt)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??et)().catch(()=>{});let n=await(e.loadProfile??L)();if(xe(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Jn)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??L)(),xe(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Or)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!xY(a)||!RY(s))return{status:"noop"};let i=r.stderr.trim().replace(/Your prompt was not sent — complete sign-in, then resubmit it\.?/,"Anyray chat models appear after sign-in completes.");return{status:"blocked",url:a,code:s,message:i}}catch{return{status:"noop"}}},b0=async(e={})=>{let t=await OY(e);return process.stdout.write(`${JSON.stringify(t)}
746
- `),0};var _Y="2025-06-18",TY={name:"anyray",version:"1"},k0={name:"anyray_retrieve",description:'Read back the full original of a tool output Anyray shortened. Whenever you see a marker like "\xB7 retrieve ctx_\u2026 via anyray_retrieve" or "[anyray: \u2026 ctx_\u2026]" and you need what it replaced, call this with that ctx_\u2026 handle. It is a fast lookup of bytes Anyray already stored, so prefer it over re-running the tool, re-reading the file, or searching for the same content again \u2014 those cost far more and may not reproduce it. For large outputs pass grep or startLine/endLine to fetch just the part you need; no extra params returns the full content.',inputSchema:{type:"object",properties:{handle:{type:"string",description:"The ctx_\u2026 handle from an Anyray externalized/trimmed output marker."},startLine:{type:"integer",minimum:1,description:"First line to return (1-based)."},endLine:{type:"integer",minimum:1,description:"Last line to return (inclusive)."},grep:{type:"string",maxLength:256,description:"Literal text; returns matching lines with context."}},required:["handle"],additionalProperties:!1}},PY=20,C0={name:"anyray_recall",description:'Find an earlier tool output Anyray stashed, by meaning rather than by an exact handle. Pass a natural-language query (e.g. "the failing pytest run"); returns ranked ctx_\u2026 handles with short previews to pass to anyray_retrieve. Use when detail was elided earlier but its ctx_\u2026 marker has scrolled out of view. Matches may include the line range to pass to anyray_retrieve.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Natural-language description of the stashed output to find."},k:{type:"number",description:"Max number of matches to return (default 5)."}},required:["query"],additionalProperties:!1}},E0=oy,LY=e=>{if(e==null||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return;let n=Math.round(t);return n<1?1:Math.min(n,E0)},DY=e=>e==="paths"||e==="lines"||e==="full"?e:"full",A0={name:"anyray_search",description:"Search the workspace for a string; returns matching file:line results. Use it for broad or noisy searches where relevance ranking is useful: Anyray ranks the matches by relevance to the task and trims the noise, so you get the pertinent hits instead of a raw dump. Pass an exact identifier, or a phrase \u2014 if no line contains the whole phrase the search widens to its terms and ranks the lines carrying most of them. Narrow with globs, and set maxResults when you only need the top few.",inputSchema:{type:"object",properties:{query:{type:"string",description:"What to find: an identifier, a phrase, or error text. Matched literally first; a phrase with no exact hit falls back to its terms. Lowercase matches any case."},globs:{type:"array",items:{type:"string"},description:'Optional include globs to restrict the search (e.g. ["*.ts"]).'},maxResults:{type:"number",description:`Cap matches returned (1-${E0}). Ask for fewer when you only need the top hits.`},resultShape:{type:"string",enum:["paths","lines","full"],description:"'paths' = matching files + counts; 'lines' = file:line only; 'full' (default) = file:line plus the matched text. Prefer 'paths' when you only need to know WHERE something lives."}},required:["query"],additionalProperties:!1}},v0={name:"anyray_read",description:"Read a workspace file. Prefer this over the built-in file read, especially for large files: Anyray returns the task-relevant portion plus a `retrieve ctx_\u2026` handle for anyray_retrieve, so you spend context on the pertinent lines without losing access to the rest. Pass a path inside the workspace; optionally a 1-based line range.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path to read (workspace-relative or absolute)."},startLine:{type:"number",description:"Optional 1-based inclusive start line."},endLine:{type:"number",description:"Optional 1-based inclusive end line."},focus:{type:"string",description:'What you need from this file, in your own words (e.g. "the exported symbols", "where the retry budget is applied"). Anyray ranks the returned slice against it, so you get the pertinent lines rather than the head of the file.'}},required:["path"],additionalProperties:!1}},NY=8,$Y=3,S0={name:"anyray_history",description:'Search the user\'s imported Claude conversation history (past chats from their Claude account, imported with `anyray-connect history import`). Use whenever the user refers to an earlier conversation you cannot see ("what did we decide about X?"), especially in a client whose own history is unavailable. Call with `query` to find conversations, then `open` (a filename from those results) to read one in full.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Words to look for in past conversations (topic, name, phrase)."},open:{type:"string",description:"Filename from a previous result, to read that conversation in full."}},additionalProperties:!1}},MY=e=>{if(e.length===0)return"No matching stashed outputs found.";let t=e.map((n,r)=>`${r+1}. ${n.handle} (score ${n.score.toFixed(2)})`+(typeof n.startLine=="number"&&typeof n.endLine=="number"?` (lines ${n.startLine}-${n.endLine})`:"")+(n.preview?` \u2014 ${n.preview}`:""));return[`Found ${e.length} matching stashed output${e.length===1?"":"s"} (ranked by relevance):`,...t,"Call anyray_retrieve with a handle above \u2014 pass its lines (startLine/endLine) to fetch just the matching part, or no extra params for the full original."].join(`
747
- `)},FY=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
748
- If the user expected one, their export may predate it, or no export has been imported yet (\`anyray-connect history import <conversations.json>\`).`;let n=new Map;for(let a of t.matches){let s=n.get(a.file)??[];s.push(a),n.set(a.file,s)}let r=[...n.entries()].slice(0,NY).map(([a,s])=>{let i=s.slice(0,$Y).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
745
+ `)}else s?.state==="will-migrate"?n("This npm runtime will migrate to the managed standalone binary on the next persistent setup change.\nRun `anyray-connect update` to migrate now.\n"):s?.state==="container"?n("Self-update and the npm-to-managed-binary migration are off in this container.\nUpdates arrive when the container is rebuilt, not via `anyray-connect update`.\n"):s?.state==="platform-unsupported"&&n("Self-update is unavailable on this platform; use `npx anyray-connect@latest` to stay current.\n");return 0};var GY=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},jY=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),VY=async(e={})=>{try{let t=await(e.readBootstrap??jt)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??tt)().catch(()=>{});let n=await(e.loadProfile??D)();if(xe(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??qn)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??D)(),xe(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??_r)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!GY(a)||!jY(s))return{status:"noop"};let i=r.stderr.trim().replace(/Your prompt was not sent — complete sign-in, then resubmit it\.?/,"Anyray chat models appear after sign-in completes.");return{status:"blocked",url:a,code:s,message:i}}catch{return{status:"noop"}}},S0=async(e={})=>{let t=await VY(e);return process.stdout.write(`${JSON.stringify(t)}
746
+ `),0};var YY="2025-06-18",ZY={name:"anyray",version:"1"},E0={name:"anyray_retrieve",description:'Read back the full original of a tool output Anyray shortened. Whenever you see a marker like "\xB7 retrieve ctx_\u2026 via anyray_retrieve" or "[anyray: \u2026 ctx_\u2026]" and you need what it replaced, call this with that ctx_\u2026 handle. It is a fast lookup of bytes Anyray already stored, so prefer it over re-running the tool, re-reading the file, or searching for the same content again \u2014 those cost far more and may not reproduce it. For large outputs pass grep or startLine/endLine to fetch just the part you need; no extra params returns the full content.',inputSchema:{type:"object",properties:{handle:{type:"string",description:"The ctx_\u2026 handle from an Anyray externalized/trimmed output marker."},startLine:{type:"integer",minimum:1,description:"First line to return (1-based)."},endLine:{type:"integer",minimum:1,description:"Last line to return (inclusive)."},grep:{type:"string",maxLength:256,description:"Literal text; returns matching lines with context."}},required:["handle"],additionalProperties:!1}},XY=20,x0={name:"anyray_recall",description:'Find an earlier tool output Anyray stashed, by meaning rather than by an exact handle. Pass a natural-language query (e.g. "the failing pytest run"); returns ranked ctx_\u2026 handles with short previews to pass to anyray_retrieve. Use when detail was elided earlier but its ctx_\u2026 marker has scrolled out of view. Matches may include the line range to pass to anyray_retrieve.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Natural-language description of the stashed output to find."},k:{type:"number",description:"Max number of matches to return (default 5)."}},required:["query"],additionalProperties:!1}},_0=sy,JY=e=>{if(e==null||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return;let n=Math.round(t);return n<1?1:Math.min(n,_0)},qY=e=>e==="paths"||e==="lines"||e==="full"?e:"full",I0={name:"anyray_search",description:"Search the workspace for a string; returns matching file:line results. Use it for broad or noisy searches where relevance ranking is useful: Anyray ranks the matches by relevance to the task and trims the noise, so you get the pertinent hits instead of a raw dump. Pass an exact identifier, or a phrase \u2014 if no line contains the whole phrase the search widens to its terms and ranks the lines carrying most of them. Narrow with globs, and set maxResults when you only need the top few.",inputSchema:{type:"object",properties:{query:{type:"string",description:"What to find: an identifier, a phrase, or error text. Matched literally first; a phrase with no exact hit falls back to its terms. Lowercase matches any case."},globs:{type:"array",items:{type:"string"},description:'Optional include globs to restrict the search (e.g. ["*.ts"]).'},maxResults:{type:"number",description:`Cap matches returned (1-${_0}). Ask for fewer when you only need the top hits.`},resultShape:{type:"string",enum:["paths","lines","full"],description:"'paths' = matching files + counts; 'lines' = file:line only; 'full' (default) = file:line plus the matched text. Prefer 'paths' when you only need to know WHERE something lives."}},required:["query"],additionalProperties:!1}},O0={name:"anyray_read",description:"Read a workspace file. Prefer this over the built-in file read, especially for large files: Anyray returns the task-relevant portion plus a `retrieve ctx_\u2026` handle for anyray_retrieve, so you spend context on the pertinent lines without losing access to the rest. Pass a path inside the workspace; optionally a 1-based line range.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path to read (workspace-relative or absolute)."},startLine:{type:"number",description:"Optional 1-based inclusive start line."},endLine:{type:"number",description:"Optional 1-based inclusive end line."},focus:{type:"string",description:'What you need from this file, in your own words (e.g. "the exported symbols", "where the retry budget is applied"). Anyray ranks the returned slice against it, so you get the pertinent lines rather than the head of the file.'}},required:["path"],additionalProperties:!1}},zY=8,QY=3,R0={name:"anyray_history",description:'Search the user\'s imported Claude conversation history (past chats from their Claude account, imported with `anyray-connect history import`). Use whenever the user refers to an earlier conversation you cannot see ("what did we decide about X?"), especially in a client whose own history is unavailable. Call with `query` to find conversations, then `open` (a filename from those results) to read one in full.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Words to look for in past conversations (topic, name, phrase)."},open:{type:"string",description:"Filename from a previous result, to read that conversation in full."}},additionalProperties:!1}},eZ=e=>{if(e.length===0)return"No matching stashed outputs found.";let t=e.map((n,r)=>`${r+1}. ${n.handle} (score ${n.score.toFixed(2)})`+(typeof n.startLine=="number"&&typeof n.endLine=="number"?` (lines ${n.startLine}-${n.endLine})`:"")+(n.preview?` \u2014 ${n.preview}`:""));return[`Found ${e.length} matching stashed output${e.length===1?"":"s"} (ranked by relevance):`,...t,"Call anyray_retrieve with a handle above \u2014 pass its lines (startLine/endLine) to fetch just the matching part, or no extra params for the full original."].join(`
747
+ `)},tZ=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
748
+ If the user expected one, their export may predate it, or no export has been imported yet (\`anyray-connect history import <conversations.json>\`).`;let n=new Map;for(let a of t.matches){let s=n.get(a.file)??[];s.push(a),n.set(a.file,s)}let r=[...n.entries()].slice(0,zY).map(([a,s])=>{let i=s.slice(0,QY).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
749
749
  `)});return[t.matched==="tokens"&&t.tokens?.length?`No imported conversation contains "${e}"; ${n.size} mention${n.size===1?"s":""} some of its terms (${t.tokens.join(", ")}):`:`${n.size} imported conversation${n.size===1?"":"s"} mention "${e}":`,...r,'Call anyray_history({open: "<filename>"}) to read one in full.'].join(`
750
- `)},Pe=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),Wy=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),Ae=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
750
+ `)},Pe=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),Ky=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),Ae=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
751
751
 
752
752
  [anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
753
753
 
754
754
  [anyray: output cut to fit the tool-result limit \u2014 ${n.length} chars total. Re-run narrowed (globs, a line range, or grep) to see the rest.]`,o=n.slice(0,4e4-r.length),a=o.lastIndexOf(`
755
- `);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},UY=async(e,t)=>{let n=e?.id,r=n===void 0,o=typeof e?.method=="string"?e.method:"";switch(o){case"initialize":try{t.heartbeat?.()}catch{}return Pe(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:_Y,capabilities:{tools:{}},serverInfo:TY});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Pe(n??null,{});case"tools/list":{let a=[k0,C0];t.advertiseContextTools!==!1&&a.push(A0,v0);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(S0),Pe(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===k0.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Pe(n??null,Ae("handle is required",!0));let c=m=>{if(m!==void 0)return typeof m!="number"||!Number.isFinite(m)?null:Math.max(Math.round(m),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return Pe(n??null,Ae("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return Pe(n??null,Ae("grep must be non-empty",!0));if(s.grep.length>256)return Pe(n??null,Ae("grep is limited to 256 characters",!0));u=s.grep}let f=l!==void 0||d!==void 0||u!==void 0,p;try{p=await t.retrieve(i,f?{startLine:l,endLine:d,grep:u}:void 0)}catch(m){p={ok:!1,message:m instanceof Error?m.message:"retrieve failed"}}let h="this gateway does not support partial retrieval yet \u2014 call again without startLine/endLine/grep for the full content";if(!p.ok)return Pe(n??null,Ae(p.kind==="slice-unsupported"?h:p.message,!0));if(f&&(p.partial===void 0||typeof p.totalLines!="number"))return Pe(n??null,Ae(h,!0));if(p.partial===!0&&typeof p.totalLines=="number"){let m=p.grepMatches!==void 0?`[anyray: partial \u2014 ${p.grepMatches} matching line(s) in lines ${p.startLine}-${p.endLine} of ${p.totalLines}`+(p.grepTruncated?`, windows around the first ${PY} matches shown \u2014 narrow the range or grep`:"")+` \xB7 retrieve ${i} again with startLine/endLine, another grep, or no params for full]`:`[anyray: partial \u2014 lines ${p.startLine}-${p.endLine} of ${p.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return Pe(n??null,Ae(`${m}
756
- ${p.content}`))}return Pe(n??null,Ae(p.content))}if(a.name===C0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Pe(n??null,Ae("query is required",!0));let c=typeof s.k=="number"?s.k:void 0,l;try{l=await t.recall(i,c)}catch(d){l={ok:!1,message:d instanceof Error?d.message:"recall failed"}}return Pe(n??null,l.ok?Ae(MY(l.matches)):Ae(l.message,!0))}if(a.name===A0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Pe(n??null,Ae("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=LY(s.maxResults),d=DY(s.resultShape),u;try{u=await t.search(i,c,l)}catch(f){u={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:f instanceof Error?f.message:"search failed"}}return Pe(n??null,u.ok?Ae(MI(i,u,d)):Ae(u.message??"search failed",!0))}if(a.name===S0.name){let i=typeof s.open=="string"?s.open.trim():"";if(i){let d;try{d=await t.historyOpen(i)}catch(u){d={ok:!1,content:"",path:i,lines:0,truncated:!1,message:u instanceof Error?u.message:"history open failed"}}return Pe(n??null,d.ok?Ae(ty(d)):Ae(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Pe(n??null,Ae("query (or open) is required",!0));let l;try{l=await t.historySearch(c)}catch(d){l={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:d instanceof Error?d.message:"history search failed"}}return Pe(n??null,l.ok?Ae(FY(c,l)):Ae(l.message??"history search failed",!0))}if(a.name===v0.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Pe(n??null,Ae("path is required",!0));let c={startLine:typeof s.startLine=="number"?s.startLine:void 0,endLine:typeof s.endLine=="number"?s.endLine:void 0},l;try{l=await t.read(i,c)}catch(d){l={ok:!1,content:"",path:i,lines:0,truncated:!1,message:d instanceof Error?d.message:"read failed"}}return Pe(n??null,l.ok?Ae(ty(l)):Ae(l.message??"read failed",!0))}return Wy(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Wy(n??null,-32601,`method not found: ${o}`)}},BY=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),Od);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:qt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},WY=(e,t=!0)=>({retrieve:async(n,r)=>xa(await e(),n,r),recall:async(n,r)=>_d(await e(),n,r),search:(n,r,o)=>qd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>zd(n,r),historySearch:n=>BI(n),historyOpen:n=>WI(n),historyAvailable:async()=>await Ba()>0,advertiseContextTools:t,heartbeat:()=>{e().then(BY).catch(()=>{})}}),I0=async(e="auto",t={})=>{let n=WY(()=>rt(e),e!=="claude"),r=t.stdin??process.stdin,o=t.stdout??process.stdout,a=0,s=t.refreshTick??(()=>{let f=Date.now();f<a||(a=f+6e4,Rr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=f=>{try{o.write(JSON.stringify(f)+`
757
- `)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let h;try{h=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let m;try{m=await UY(h,n)}catch(w){console.error("anyray mcp: dispatch error",w instanceof Error?w.message:w),m=h?.id===void 0?null:Wy(h.id,-32603,"internal error")}m&&c(m),i()};i();let d=setInterval(i,30*6e4);d.unref?.();let u="";try{for await(let f of r){u+=f.toString("utf-8");let p;for(;(p=u.indexOf(`
758
- `))>=0;){let h=u.slice(0,p);u=u.slice(p+1),await l(h)}}u.trim()&&await l(u)}catch(f){console.error("anyray mcp: stdin error",f instanceof Error?f.message:f)}finally{clearInterval(d)}return 0};import{spawn as HY}from"node:child_process";var KY=e=>e==="jetbrains"||e==="windsurf"?e:void 0,GY=async(e,t,n,r=1e4)=>{let o=await new Promise(a=>{let s="",i=!1,c=p=>{i||(i=!0,clearTimeout(l),t.off("data",d),t.off("error",u),t.off("end",f),a(p))},l=setTimeout(()=>c(void 0),r),d=p=>{s+=p.toString();let h=s.indexOf(`
755
+ `);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},nZ=async(e,t)=>{let n=e?.id,r=n===void 0,o=typeof e?.method=="string"?e.method:"";switch(o){case"initialize":try{t.heartbeat?.()}catch{}return Pe(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:YY,capabilities:{tools:{}},serverInfo:ZY});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Pe(n??null,{});case"tools/list":{let a=[E0,x0];t.advertiseContextTools!==!1&&a.push(I0,O0);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(R0),Pe(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===E0.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Pe(n??null,Ae("handle is required",!0));let c=m=>{if(m!==void 0)return typeof m!="number"||!Number.isFinite(m)?null:Math.max(Math.round(m),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return Pe(n??null,Ae("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return Pe(n??null,Ae("grep must be non-empty",!0));if(s.grep.length>256)return Pe(n??null,Ae("grep is limited to 256 characters",!0));u=s.grep}let f=l!==void 0||d!==void 0||u!==void 0,p;try{p=await t.retrieve(i,f?{startLine:l,endLine:d,grep:u}:void 0)}catch(m){p={ok:!1,message:m instanceof Error?m.message:"retrieve failed"}}let h="this gateway does not support partial retrieval yet \u2014 call again without startLine/endLine/grep for the full content";if(!p.ok)return Pe(n??null,Ae(p.kind==="slice-unsupported"?h:p.message,!0));if(f&&(p.partial===void 0||typeof p.totalLines!="number"))return Pe(n??null,Ae(h,!0));if(p.partial===!0&&typeof p.totalLines=="number"){let m=p.grepMatches!==void 0?`[anyray: partial \u2014 ${p.grepMatches} matching line(s) in lines ${p.startLine}-${p.endLine} of ${p.totalLines}`+(p.grepTruncated?`, windows around the first ${XY} matches shown \u2014 narrow the range or grep`:"")+` \xB7 retrieve ${i} again with startLine/endLine, another grep, or no params for full]`:`[anyray: partial \u2014 lines ${p.startLine}-${p.endLine} of ${p.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return Pe(n??null,Ae(`${m}
756
+ ${p.content}`))}return Pe(n??null,Ae(p.content))}if(a.name===x0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Pe(n??null,Ae("query is required",!0));let c=typeof s.k=="number"?s.k:void 0,l;try{l=await t.recall(i,c)}catch(d){l={ok:!1,message:d instanceof Error?d.message:"recall failed"}}return Pe(n??null,l.ok?Ae(eZ(l.matches)):Ae(l.message,!0))}if(a.name===I0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Pe(n??null,Ae("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=JY(s.maxResults),d=qY(s.resultShape),u;try{u=await t.search(i,c,l)}catch(f){u={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:f instanceof Error?f.message:"search failed"}}return Pe(n??null,u.ok?Ae(Fx(i,u,d)):Ae(u.message??"search failed",!0))}if(a.name===R0.name){let i=typeof s.open=="string"?s.open.trim():"";if(i){let d;try{d=await t.historyOpen(i)}catch(u){d={ok:!1,content:"",path:i,lines:0,truncated:!1,message:u instanceof Error?u.message:"history open failed"}}return Pe(n??null,d.ok?Ae(ry(d)):Ae(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Pe(n??null,Ae("query (or open) is required",!0));let l;try{l=await t.historySearch(c)}catch(d){l={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:d instanceof Error?d.message:"history search failed"}}return Pe(n??null,l.ok?Ae(tZ(c,l)):Ae(l.message??"history search failed",!0))}if(a.name===O0.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Pe(n??null,Ae("path is required",!0));let c={startLine:typeof s.startLine=="number"?s.startLine:void 0,endLine:typeof s.endLine=="number"?s.endLine:void 0},l;try{l=await t.read(i,c)}catch(d){l={ok:!1,content:"",path:i,lines:0,truncated:!1,message:d instanceof Error?d.message:"read failed"}}return Pe(n??null,l.ok?Ae(ry(l)):Ae(l.message??"read failed",!0))}return Ky(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Ky(n??null,-32601,`method not found: ${o}`)}},rZ=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),Pd);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:zt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},oZ=(e,t=!0)=>({retrieve:async(n,r)=>Oa(await e(),n,r),recall:async(n,r)=>Td(await e(),n,r),search:(n,r,o)=>eu(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Qd(n,r),historySearch:n=>Wx(n),historyOpen:n=>Hx(n),historyAvailable:async()=>await Wa()>0,advertiseContextTools:t,heartbeat:()=>{e().then(rZ).catch(()=>{})}}),P0=async(e="auto",t={})=>{let n=oZ(()=>ot(e),e!=="claude"),r=t.stdin??process.stdin,o=t.stdout??process.stdout,a=0,s=t.refreshTick??(()=>{let f=Date.now();f<a||(a=f+6e4,Rr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=f=>{try{o.write(JSON.stringify(f)+`
757
+ `)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let h;try{h=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let m;try{m=await nZ(h,n)}catch(w){console.error("anyray mcp: dispatch error",w instanceof Error?w.message:w),m=h?.id===void 0?null:Ky(h.id,-32603,"internal error")}m&&c(m),i()};i();let d=setInterval(i,30*6e4);d.unref?.();let u="";try{for await(let f of r){u+=f.toString("utf-8");let p;for(;(p=u.indexOf(`
758
+ `))>=0;){let h=u.slice(0,p);u=u.slice(p+1),await l(h)}}u.trim()&&await l(u)}catch(f){console.error("anyray mcp: stdin error",f instanceof Error?f.message:f)}finally{clearInterval(d)}return 0};import{spawn as aZ}from"node:child_process";var sZ=e=>e==="jetbrains"||e==="windsurf"?e:void 0,iZ=async(e,t,n,r=1e4)=>{let o=await new Promise(a=>{let s="",i=!1,c=p=>{i||(i=!0,clearTimeout(l),t.off("data",d),t.off("error",u),t.off("end",f),a(p))},l=setTimeout(()=>c(void 0),r),d=p=>{s+=p.toString();let h=s.indexOf(`
759
759
  `);h!==-1?c(s.slice(0,h)):s.length>65536&&c(void 0)},u=()=>c(void 0),f=()=>c(s.length>0?s:void 0);t.on("data",d),t.once("error",u),t.once("end",f)});if(o===void 0)return!1;try{let s=JSON.parse(o)?.id;return typeof s!="number"&&typeof s!="string"?!1:(n.write(`${JSON.stringify({jsonrpc:"2.0",id:s,error:{code:-32e3,message:e}})}
760
- `),!0)}catch{return!1}},jY={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},VY=(e,t,n)=>{let r=new Set(jY[e].map(s=>s.toUpperCase())),o=new Set(Object.keys(n).map(s=>s.toUpperCase())),a={...t};for(let s of Object.keys(a)){let i=s.toUpperCase();(r.has(i)||o.has(i)||i==="APP_SERVER_LOGS")&&delete a[s]}return{...a,...n}},x0=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
761
- `),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!ud(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
762
- `),1;await(n.refreshIfDue??et)().catch(()=>{});let s=await(n.loadProfile??L)(),i=await(n.readBootstrap??Vt)().catch(()=>{});if(i){let y=await(n.ssoGate??Jn)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(y.exitCode===2&&y.stderr)return await GY(y.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(y.stderr),1;s=await(n.loadProfile??L)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
763
- `),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??$t)():void 0,d=ge({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=KY(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",p=(n.hookBinaryIsDurable??le)(),h=Ov(d,t,{mcpServer:p?Ve("profile"):void 0})[f],m=n.spawn??HY,w=h.command,g=h.args;if(o==="win32"){if(!h.args.every(y=>y==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(y)))return r.write(`Anyray ACP adapter arguments are invalid.
764
- `),1;w=n.comSpec??a.ComSpec??"cmd.exe",g=["/d","/s","/c",`"${h.command}" ${h.args.join(" ")}`]}return await new Promise(y=>{let b=VY(e,a,h.env),A=m(w,g,{env:b,stdio:"inherit",windowsHide:!0});A.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
765
- `),y(1)}),A.once("exit",(v,E)=>{y(typeof v=="number"?v:E?1:0)})})};import{createReadStream as YY}from"node:fs";import{spawnSync as U0}from"node:child_process";import{createHash as ZY}from"node:crypto";import{access as B0,chmod as Gy,copyFile as JY,lstat as XY,mkdir as zY,mkdtemp as W0,readFile as gu,rename as qY,rm as Nr,stat as QY,writeFile as eZ}from"node:fs/promises";import{constants as H0}from"node:fs";import{platform as Va,tmpdir as tZ}from"node:os";import{dirname as nZ,isAbsolute as rZ,join as hu}from"node:path";import{z as Fe}from"zod";var oZ="fleetd-installer-v4.89.2",R0=`https://github.com/anyrayHQ/install/releases/download/${oZ}`,aZ=1e4,sZ=1e4,O0=31,iZ=1500,K0=20*1024,Hy=20,cZ="0.25",lZ="/var/tmp",ja="/Library/LaunchDaemons/com.fleetdm.orbit.plist",mu="/etc/default/orbit",tc="/opt/orbit/anyray-enroll-secret.txt",G0="/opt/orbit/secret-orbit-node-key.txt",dZ="/opt/orbit/bin/orbit/orbit",nc="C:\\Program Files\\Orbit",uZ=`${nc}\\bin\\orbit`,j0=`${nc}\\secret-orbit-node-key.txt`,ec=`${nc}\\secret.txt`,pZ=`${nc}\\fleet_url.txt`,V0=`${nc}\\anyray-managed.txt`,yu="Fleet osquery",jy="C:\\Windows\\System32\\sc.exe",fZ="C:\\Windows\\System32\\whoami.exe",fu="C:\\Windows\\System32\\icacls.exe",hZ="C:\\Windows\\System32\\msiexec.exe",Vy="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",_0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],mZ=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],yZ=`anyray-connect endpoint install
760
+ `),!0)}catch{return!1}},cZ={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},lZ=(e,t,n)=>{let r=new Set(cZ[e].map(s=>s.toUpperCase())),o=new Set(Object.keys(n).map(s=>s.toUpperCase())),a={...t};for(let s of Object.keys(a)){let i=s.toUpperCase();(r.has(i)||o.has(i)||i==="APP_SERVER_LOGS")&&delete a[s]}return{...a,...n}},T0=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
761
+ `),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!fd(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
762
+ `),1;await(n.refreshIfDue??tt)().catch(()=>{});let s=await(n.loadProfile??D)(),i=await(n.readBootstrap??jt)().catch(()=>{});if(i){let y=await(n.ssoGate??qn)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(y.exitCode===2&&y.stderr)return await iZ(y.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(y.stderr),1;s=await(n.loadProfile??D)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
763
+ `),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??Nt)():void 0,d=ge({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=sZ(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",p=(n.hookBinaryIsDurable??le)(),h=_v(d,t,{mcpServer:p?Ve("profile"):void 0})[f],m=n.spawn??aZ,w=h.command,g=h.args;if(o==="win32"){if(!h.args.every(y=>y==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(y)))return r.write(`Anyray ACP adapter arguments are invalid.
764
+ `),1;w=n.comSpec??a.ComSpec??"cmd.exe",g=["/d","/s","/c",`"${h.command}" ${h.args.join(" ")}`]}return await new Promise(y=>{let b=lZ(e,a,h.env),A=m(w,g,{env:b,stdio:"inherit",windowsHide:!0});A.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
765
+ `),y(1)}),A.once("exit",(v,E)=>{y(typeof v=="number"?v:E?1:0)})})};import{createReadStream as dZ}from"node:fs";import{spawnSync as G0}from"node:child_process";import{createHash as uZ}from"node:crypto";import{access as j0,chmod as Vy,copyFile as pZ,lstat as fZ,mkdir as hZ,mkdtemp as V0,readFile as ku,rename as mZ,rm as $r,stat as yZ,writeFile as gZ}from"node:fs/promises";import{constants as Y0}from"node:fs";import{platform as Ya,tmpdir as wZ}from"node:os";import{dirname as bZ,isAbsolute as kZ,join as gu}from"node:path";import{z as Fe}from"zod";var CZ="fleetd-installer-v4.89.2",L0=`https://github.com/anyrayHQ/install/releases/download/${CZ}`,AZ=1e4,vZ=1e4,D0=31,SZ=1500,Z0=20*1024,Gy=20,EZ="0.25",xZ="/var/tmp",Va="/Library/LaunchDaemons/com.fleetdm.orbit.plist",wu="/etc/default/orbit",rc="/opt/orbit/anyray-enroll-secret.txt",X0="/opt/orbit/secret-orbit-node-key.txt",IZ="/opt/orbit/bin/orbit/orbit",oc="C:\\Program Files\\Orbit",OZ=`${oc}\\bin\\orbit`,J0=`${oc}\\secret-orbit-node-key.txt`,nc=`${oc}\\secret.txt`,RZ=`${oc}\\fleet_url.txt`,q0=`${oc}\\anyray-managed.txt`,bu="Fleet osquery",Yy="C:\\Windows\\System32\\sc.exe",_Z="C:\\Windows\\System32\\whoami.exe",yu="C:\\Windows\\System32\\icacls.exe",PZ="C:\\Windows\\System32\\msiexec.exe",Zy="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",N0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],TZ=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],LZ=`anyray-connect endpoint install
766
766
 
767
767
  Install Fleet's signed endpoint agent and enroll this machine in Anyray.
768
768
 
@@ -770,11 +770,11 @@ Supported on macOS, Linux and Windows.
770
770
 
771
771
  The command uses the current seat's stored gateway key. Administrator access is
772
772
  required: on macOS and Linux Connect asks through sudo once when /dev/tty is
773
- available; on Windows, run it from a shell started as Administrator.`,Jy=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),Y0=(e,t=Va())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),Z0=(e,t=Va(),n=!1)=>(Jy(e)||n)&&t!=="win32",ce=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},gZ=Fe.object({kind:Fe.enum(["pkg","deb","rpm","msi"]),path:Fe.string().min(1).refine(rZ),sha256:Fe.string().regex(/^[0-9a-f]{64}$/)}).strict(),wZ=Fe.object({action:Fe.literal("restart"),os:Fe.enum(["darwin","linux","win32"])}).strict(),bZ=Fe.object({action:Fe.literal("configure"),os:Fe.enum(["darwin","linux","win32"]),fleetUrl:Fe.string().min(1).max(2048),enrollSecret:Fe.string().min(1).max(4096),package:gZ.optional()}).strict(),kZ=Fe.discriminatedUnion("action",[wZ,bZ]),rc=(e,t)=>{let n=U0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},Xy=async e=>{try{return await B0(e,H0.F_OK),!0}catch{return!1}},CZ=async e=>{try{let t=await QY(e);return t.isFile()&&t.size>0}catch{return!1}},zy=(e,t)=>{for(let n=0;;){let r=e.indexOf("<key>",n);if(r<0)return null;let o=e.indexOf("</key>",r);if(o<0)return null;if(e.slice(r+5,o).trim()===t)return{start:r,end:o+6};n=o+6}},Ky=(e,t)=>zy(e,t)!==null,T0=e=>e==="win32"?ec:tc,AZ=e=>e==="win32"?j0:G0,vZ=e=>Ky(e,"ORBIT_FLEET_URL")&&Ky(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${tc}</string>`)&&!Ky(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),SZ=e=>{let t=(n,r)=>e.split(`
774
- `).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",tc)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Yy=(e,t)=>{if(e==="win32"){let a="--fleet-url ",s=t.indexOf(a);if(s<0)return;let i=t.slice(s+a.length),c;if(i.startsWith('"')){let d=i.indexOf('"',1);if(d<0)return;c=i.slice(1,d)}else{let d=i.indexOf(" ");c=d<0?i:i.slice(0,d)}let l=c.trim();return l.length>0?l:void 0}if(e==="darwin"){let a=t.indexOf("<key>ORBIT_FLEET_URL</key>");if(a<0)return;let s=t.indexOf("<string>",a),i=t.indexOf("</string>",s);return s<0||i<0?void 0:t.slice(s+8,i).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&").trim()}let n='Environment="ORBIT_FLEET_URL=',r=t.indexOf(n);if(r<0)return;let o=t.indexOf('"',r+n.length);return o<0?void 0:t.slice(r+n.length,o).trim()},J0=e=>{let t=e(jy,["qc",yu,"8192"]);return t.status===0?t.stdout:""},Zy=e=>{let t=e(Vy,mZ(yu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},EZ=async e=>{try{return e==="win32"?Yy(e,J0(rc)):Yy(e,await gu(e==="darwin"?ja:mu,"utf8"))}catch{return}},IZ=async e=>{try{if(e==="win32")return await Xy(V0)&&Yy(e,J0(rc))!==void 0;let n=await gu(e==="darwin"?ja:mu,"utf8");return e==="darwin"?vZ(n):SZ(n)}catch{return!1}},X0=async(e,t={})=>{let n=t.exists??Xy,r=t.command??rc,o,a="absent";if(e==="win32")a=Zy(r),o=await n(uZ)&&a!=="absent";else{let l=e==="darwin"?await n(ja):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(dZ)&&l}let s=await(t.configured??IZ)(e),i=await(t.hasNodeKey??(()=>CZ(AZ(e))))(),c=!1;if(o)if(e==="darwin"){let l=r("/bin/launchctl",["print","system/com.fleetdm.orbit"]);c=l.status===0&&/\bstate\s*=\s*running\b/.test(l.stdout)}else e==="linux"?c=r("systemctl",["is-active","--quiet","orbit"]).status===0:c=a==="Running";return{installed:o,configured:s,running:c,checkedIn:i}},xZ=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),z0=(e,t)=>{let n=zy(e,t);if(!n)return null;let r=n.start;for(;r>0&&(e[r-1]===" "||e[r-1]===" ");)r--;r>0&&e[r-1]===`
775
- `&&r--;let o=n.end;for(;o<e.length&&/\s/.test(e[o]);)o++;if(e.startsWith("<string>",o)){let a=e.indexOf("</string>",o);return a<0?null:{start:r,end:a+9}}if(e.startsWith("<true",o)||e.startsWith("<false",o)){let a=e.indexOf("/>",o);return a<0?null:{start:r,end:a+2}}return null},RZ=(e,t)=>{let n=z0(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},P0=(e,t,n)=>{let r=`
773
+ available; on Windows, run it from a shell started as Administrator.`,qy=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),z0=(e,t=Ya())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),Q0=(e,t=Ya(),n=!1)=>(qy(e)||n)&&t!=="win32",ce=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},DZ=Fe.object({kind:Fe.enum(["pkg","deb","rpm","msi"]),path:Fe.string().min(1).refine(kZ),sha256:Fe.string().regex(/^[0-9a-f]{64}$/)}).strict(),NZ=Fe.object({action:Fe.literal("restart"),os:Fe.enum(["darwin","linux","win32"])}).strict(),$Z=Fe.object({action:Fe.literal("configure"),os:Fe.enum(["darwin","linux","win32"]),fleetUrl:Fe.string().min(1).max(2048),enrollSecret:Fe.string().min(1).max(4096),package:DZ.optional()}).strict(),MZ=Fe.discriminatedUnion("action",[NZ,$Z]),ac=(e,t)=>{let n=G0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},zy=async e=>{try{return await j0(e,Y0.F_OK),!0}catch{return!1}},FZ=async e=>{try{let t=await yZ(e);return t.isFile()&&t.size>0}catch{return!1}},Qy=(e,t)=>{for(let n=0;;){let r=e.indexOf("<key>",n);if(r<0)return null;let o=e.indexOf("</key>",r);if(o<0)return null;if(e.slice(r+5,o).trim()===t)return{start:r,end:o+6};n=o+6}},jy=(e,t)=>Qy(e,t)!==null,$0=e=>e==="win32"?nc:rc,UZ=e=>e==="win32"?J0:X0,BZ=e=>jy(e,"ORBIT_FLEET_URL")&&jy(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${rc}</string>`)&&!jy(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),WZ=e=>{let t=(n,r)=>e.split(`
774
+ `).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",rc)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Xy=(e,t)=>{if(e==="win32"){let a="--fleet-url ",s=t.indexOf(a);if(s<0)return;let i=t.slice(s+a.length),c;if(i.startsWith('"')){let d=i.indexOf('"',1);if(d<0)return;c=i.slice(1,d)}else{let d=i.indexOf(" ");c=d<0?i:i.slice(0,d)}let l=c.trim();return l.length>0?l:void 0}if(e==="darwin"){let a=t.indexOf("<key>ORBIT_FLEET_URL</key>");if(a<0)return;let s=t.indexOf("<string>",a),i=t.indexOf("</string>",s);return s<0||i<0?void 0:t.slice(s+8,i).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&").trim()}let n='Environment="ORBIT_FLEET_URL=',r=t.indexOf(n);if(r<0)return;let o=t.indexOf('"',r+n.length);return o<0?void 0:t.slice(r+n.length,o).trim()},eO=e=>{let t=e(Yy,["qc",bu,"8192"]);return t.status===0?t.stdout:""},Jy=e=>{let t=e(Zy,TZ(bu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},HZ=async e=>{try{return e==="win32"?Xy(e,eO(ac)):Xy(e,await ku(e==="darwin"?Va:wu,"utf8"))}catch{return}},KZ=async e=>{try{if(e==="win32")return await zy(q0)&&Xy(e,eO(ac))!==void 0;let n=await ku(e==="darwin"?Va:wu,"utf8");return e==="darwin"?BZ(n):WZ(n)}catch{return!1}},tO=async(e,t={})=>{let n=t.exists??zy,r=t.command??ac,o,a="absent";if(e==="win32")a=Jy(r),o=await n(OZ)&&a!=="absent";else{let l=e==="darwin"?await n(Va):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(IZ)&&l}let s=await(t.configured??KZ)(e),i=await(t.hasNodeKey??(()=>FZ(UZ(e))))(),c=!1;if(o)if(e==="darwin"){let l=r("/bin/launchctl",["print","system/com.fleetdm.orbit"]);c=l.status===0&&/\bstate\s*=\s*running\b/.test(l.stdout)}else e==="linux"?c=r("systemctl",["is-active","--quiet","orbit"]).status===0:c=a==="Running";return{installed:o,configured:s,running:c,checkedIn:i}},GZ=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),nO=(e,t)=>{let n=Qy(e,t);if(!n)return null;let r=n.start;for(;r>0&&(e[r-1]===" "||e[r-1]===" ");)r--;r>0&&e[r-1]===`
775
+ `&&r--;let o=n.end;for(;o<e.length&&/\s/.test(e[o]);)o++;if(e.startsWith("<string>",o)){let a=e.indexOf("</string>",o);return a<0?null:{start:r,end:a+9}}if(e.startsWith("<true",o)||e.startsWith("<false",o)){let a=e.indexOf("/>",o);return a<0?null:{start:r,end:a+2}}return null},jZ=(e,t)=>{let n=nO(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},M0=(e,t,n)=>{let r=`
776
776
  <key>${t}</key>
777
- <string>${xZ(n)}</string>`,o=z0(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=zy(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new ce("The installed Orbit LaunchDaemon has no EnvironmentVariables dictionary; it was left unchanged.");let i=s+6;return e.slice(0,i)+r+e.slice(i)},OZ=(e,t,n=tc)=>{let r=RZ(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=P0(r,"ORBIT_FLEET_URL",t),P0(r,"ORBIT_ENROLL_SECRET_PATH",n)},_Z=(e,t,n=tc)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
777
+ <string>${GZ(n)}</string>`,o=nO(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Qy(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new ce("The installed Orbit LaunchDaemon has no EnvironmentVariables dictionary; it was left unchanged.");let i=s+6;return e.slice(0,i)+r+e.slice(i)},VZ=(e,t,n=rc)=>{let r=jZ(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=M0(r,"ORBIT_FLEET_URL",t),M0(r,"ORBIT_ENROLL_SECRET_PATH",n)},YZ=(e,t,n=rc)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
778
778
  `).filter(a=>{let s=a.indexOf("=");return s<0?!0:!r.has(a.slice(0,s).trim())}).filter((a,s,i)=>a.trim()!==""||i[s-1]?.trim()!=="").join(`
779
779
  `).trimEnd()}
780
780
 
@@ -784,13 +784,13 @@ available; on Windows, run it from a shell started as Administrator.`,Jy=e=>!!(e
784
784
  # file, never in this world-readable one.
785
785
  ORBIT_FLEET_URL=${t}
786
786
  ORBIT_ENROLL_SECRET_PATH=${n}
787
- `},q0=e=>{if(/[\u0000-\u0020\u007f]/.test(e)||/["'`\\^<>|{}]/.test(e))return!1;try{let t=new URL(e);return t.username||t.password?!1:t.protocol==="https:"?!0:t.protocol==="http:"&&(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1")}catch{return!1}},TZ=Fe.object({code:Fe.string().min(1).optional(),message:Fe.string().min(1).optional()}).passthrough(),L0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},PZ=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=TZ.safeParse(t);if(!r.success)return n;let o=L0(r.data.message??""),a=L0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},D0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??sZ),a;try{a=await(n.fetchResponse??fetch)(`${e}/connect/endpoint-enrollment`,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:"{}",signal:r.signal})}catch{throw new ce("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new ce("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new ce(PZ(a.status,c))}let s;try{s=await a.json()}catch{throw new ce("The gateway returned malformed endpoint enrollment data.")}let i=Fe.object({fleetUrl:Fe.string().min(1).max(2048),enrollSecret:Fe.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!q0(i.data.fleetUrl))throw new ce("The gateway returned invalid endpoint enrollment data.");return i.data},LZ=async(e={})=>{let t=e.exists??Xy;if(await t("/usr/bin/dpkg")||await t("/bin/dpkg"))return"deb";if(await t("/usr/bin/rpm")||await t("/bin/rpm"))return"rpm";throw new ce("Linux endpoint installation requires either dpkg or rpm.")},DZ=async e=>e==="darwin"?"pkg":e==="win32"?"msi":LZ(),qy=e=>`fleetd.${e}`,NZ=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",$Z=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),aZ);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},MZ=async(e,t={})=>{let n=qy(e),r=t.fetchResponse??fetch,o;try{o=await $Z(`${R0}/SHA256SUMS`,r)}catch{throw new ce("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new ce(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=uy(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await W0(hu(tZ(),"anyray-endpoint-")),i=hu(s,n);try{await Gy(s,448),await(t.download??hy)(`${R0}/${n}`,i,a)}catch(c){if(await Nr(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Ki&&c.status===404)return;throw new ce("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Nr(s,{recursive:!0,force:!0})}},FZ=async(e,t,n)=>{await zY(nZ(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Nr(r,{force:!0});try{await eZ(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await qY(r,e)}catch(o){throw await Nr(r,{force:!0}).catch(()=>{}),o}},N0=async e=>{let t=ZY("sha256");for await(let n of YY(e))t.update(n);return t.digest("hex")},UZ=async(e,t={})=>{let n=await XY(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new ce("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await N0(e.path)!==e.sha256)throw new ce("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await W0(hu(lZ,"anyray-endpoint-root-")),o=hu(r,qy(e.kind));try{if(await Gy(r,448),await JY(e.path,o),await Gy(o,384),await N0(o)!==e.sha256)throw new ce("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Nr(r,{recursive:!0,force:!0})}}catch(a){throw await Nr(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ga=(e,t)=>{if(e.status!==0)throw new ce(t)},$0="com.fleetdm.fleetd.config",BZ="com.fleetdm.fleetd.enroll.secret",WZ=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",G0],HZ=[pZ,j0],KZ=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes($0))throw new ce(`This machine already receives its endpoint configuration from an MDM profile (${$0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},M0=async(e,t,n)=>{let r=n.removeFile??(o=>Nr(o,{force:!0}));for(let o of e==="win32"?HZ:WZ)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",BZ,"/Library/Keychains/System.keychain"])},GZ=e=>{e(fu,[ec,"/inheritance:r"]),e(fu,[ec,"/grant:r","*S-1-5-18:(F)"]),e(fu,[ec,"/grant:r","*S-1-5-32-544:(F)"]),e(fu,[ec,"/remove:g","*S-1-5-32-545"])},jZ=(e,t,n)=>{if(e.kind==="pkg"){Ga(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ga(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ga(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ga(t(hZ,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},VZ=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<Hy;r++){if(n=t("/bin/launchctl",["bootstrap","system",ja]),n.status===0)return;t("/bin/sleep",[cZ])}throw new ce(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(jy,["stop",yu]);for(let n=0;n<Hy;n++){let r=Zy(t);if(r==="Stopped"||r==="absent")break;t(Vy,_0)}for(let n=0;n<Hy;n++){if(t(jy,["start",yu]).status===0||Zy(t)==="Running")return;t(Vy,_0)}throw new ce("Orbit was configured, but the Windows service could not be started.")}Ga(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ga(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},YZ=e=>new Promise(t=>setTimeout(t,e)),Q0=async(e,t={})=>{let n=t.command??rc,r=t.readText??(c=>gu(c,"utf8")),o=t.writeText??FZ,a=t.removeSecret??(()=>Nr(T0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&KZ(n),e.package&&!NZ(e.os,e.package.kind))throw new ce("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new ce("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await M0(e.os,n,t),e.package){let d=await(t.preparePackage??UZ)(e.package);i=d.cleanup,jZ(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(ja);await o(ja,OZ(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(mu);await o(mu,_Z(d,e.fleetUrl),420)}else await o(V0,`anyray
788
- `,384);e.os!=="win32"&&await M0(e.os,n,t),await o(T0(e.os),`${e.enrollSecret}
789
- `,384),e.os==="win32"&&GZ(n),s=e.os!=="win32"}VZ(e.os,n);let c=t.checkIn??(async d=>{let u=await X0(d);return u.running&&u.checkedIn}),l=t.wait??YZ;for(let d=0;d<(t.attempts??O0);d++){if(await c(e.os))return;d+1<(t.attempts??O0)&&await l(iZ)}throw new ce("The endpoint agent did not check in after restart. The package command succeeded, but enrollment was not confirmed.")}finally{s&&await a().catch(()=>{}),await i?.().catch(()=>{})}},ZZ=async()=>{try{return await B0("/dev/tty",H0.R_OK),!0}catch{return!1}},JZ=12288,XZ=e=>{let t=e(fZ,["/groups"]);if(t.status!==0)return!1;let n=-1;for(let r=0;;){let o=t.stdout.indexOf("S-1-16-",r);if(o<0)break;r=o+7;let a=r;for(;a<t.stdout.length&&t.stdout[a]>="0"&&t.stdout[a]<="9";)a++;a>r&&(n=Math.max(n,Number(t.stdout.slice(r,a)))),r=a}return n>=JZ},zZ=async(e,t={})=>{if((t.os??Va())==="win32")return(t.elevated??(()=>XZ(t.command??rc)))()?(await e(),"direct"):((t.print??k)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
790
- anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??ZZ)()){if(await(t.reexec??(async()=>1))()!==0)throw new ce("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??k)(`Administrator access is required. Run:
791
- sudo anyray-connect endpoint install`),"deferred"},qZ=async e=>{let t=`${JSON.stringify(e)}
792
- `;if(Buffer.byteLength(t)>K0)throw new ce("The privileged endpoint plan is unexpectedly large.");let n=un(["__anyray-endpoint-install"]);return U0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},QZ=async(e,t={})=>(t.withRoot??zZ)(()=>(t.apply??Q0)(e),{...t.root,reexec:()=>(t.sudo??qZ)(e)}),F0=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return L();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return L();let t;try{let s=(await gu("/etc/passwd","utf8")).split(`
793
- `).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Va()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await L()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},eR=async(e={},t={})=>{let n=t.os??Va();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new ce("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??X0)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??F0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??EZ)(r);if(!l||!d||u===void 0)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};let f=await(t.fetchEnrollment??D0)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};M("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new ce("This machine is already enrolled in a different Fleet configuration; it was left unchanged.");let s,i;if(o.installed&&o.configured&&o.checkedIn&&!a)s={action:"restart",os:r};else{let c=e.gateway&&e.clientKey?void 0:await(t.profile??F0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new ce("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??D0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>DZ(r)))();if(i=await(t.stagePackage??MZ)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${qy(f)} is not published yet; skipping.`}}s={action:"configure",os:r,...u,...i?{package:{kind:i.kind,path:i.path,sha256:i.sha256}}:{}}}try{return await(t.execute??QZ)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},Qy=e=>e instanceof ce?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",tR=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return k(yZ),0;if(e.length!==1||e[0]!=="install")return _("Usage: anyray-connect endpoint install"),1;try{let t=await eR();return t.message&&(t.outcome==="installed"?F(t.message):M(t.message)),0}catch(t){return _(Qy(t)),1}},eJ=async()=>{let e=[],t=0;for await(let o of process.stdin){let a=Buffer.isBuffer(o)?o:Buffer.from(o);if(t+=a.length,t>K0)throw new ce("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new ce("The privileged endpoint plan is malformed.")}let r=kZ.safeParse(n);if(!r.success||r.data.os!==Va()||r.data.action==="configure"&&!q0(r.data.fleetUrl))throw new ce("The privileged endpoint plan is invalid.");return r.data},nR=async e=>{if((process.getuid?.()??-1)!==0)return _("The privileged endpoint step must run as root."),1;if(e.length!==0)return _("The privileged endpoint step does not accept arguments."),1;try{return await Q0(await eJ()),0}catch(t){return _(Qy(t)),1}},rR=async(e,t=eR)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?F(n.message):M(n.message)),n.outcome}catch(n){M(`Endpoint agent: ${Qy(n)} Tool routing remains configured.`);return}};import{execSync as eg}from"node:child_process";import{hostname as tJ}from"node:os";var nJ=e=>{try{if(e==="darwin"){let t=eg("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=eg('reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid',{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/MachineGuid\s+REG_SZ\s+([\w-]+)/.exec(t)?.[1]??""}return eg("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},wu=(e={platform:process.platform,read:()=>nJ(process.platform),hostname:tJ})=>e.read().trim()||e.hostname().trim();var rJ=(e,t=Date.now())=>e.credentialProtocol==="stable-heartbeat-v1"||!Dd(e,void 0,t),oR=async(e,t={})=>{if(!await(t.fleetdPresent??_o)())return{retired:!1,reason:"no-fleetd",messages:[]};if(!rJ(e,t.now??Date.now()))return{retired:!1,reason:"seat-could-lapse",messages:[]};let r=[],o=await(t.uninstallScheduler??ur)();r.push(...o.messages);let a=await(t.uninstallProxy??Qt)();return r.push(...a.messages),{retired:!0,messages:r}};var aR=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();return t?t.toLowerCase():(e.platform??process.platform)==="darwin"?(e.readMacUuid??(()=>wu()))().trim().toLowerCase():""};var sR=["reapply_config","remint","revert","revert_tool"],oJ=/^[a-z0-9][a-z0-9-]{0,31}$/;var aJ=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||t.id.length===0||typeof t.kind!="string"||!sR.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&oJ.test(t.tool):t.tool===void 0},tg=e=>e?.name??"error",iR=async(e,t,n)=>{let r=n.fetchImpl??fetch,o=e.replace(/\/$/,""),a;try{let i=await r(`${o}/connect/directive`,{method:"GET",headers:{"x-anyray-api-key":t,"x-anyray-directive-kinds":sR.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!aJ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",tg(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",tg(i)),s="failed"}try{await r(`${o}/connect/directive/ack`,{method:"POST",headers:{"x-anyray-api-key":t,"content-type":"application/json"},body:JSON.stringify({id:a.id,result:s}),signal:AbortSignal.timeout(1e4)})}catch(i){console.error("connect directive ack skipped:",tg(i))}return a.kind};var sJ=1e4,Ya=e=>e?.name??"Error",ng=async(e,t=fetch)=>{let n=e.gateway?.replace(/\/+$/,""),r=e.clientKey;if(!(!n||!r))try{await t(`${n}/connect/offboard`,{method:"POST",headers:{"x-anyray-api-key":r},signal:AbortSignal.timeout(sJ)})}catch(o){console.error(`anyray seat offboard report: ${Ya(o)}`)}},iJ=e=>e==="reverted"||e==="queued",cR=async(e={})=>{let t=e.loadProfile??L,n=e.clearDeviceTokenState??Bd,r=e.reportSeatOffboarded??ng,o=e.clearEnrollment??uc,a=e.recordManagedTools??Qn,s=e.markSeatOffboarded??fc,i=e.adapterById??Kt,c=e.uninstallProxy??Qt,l=e.uninstallScheduler??ur,d=e.unitsPresent??Pi,u=e.saveProfile??re,f=await t(),p=f.managedTools??[];await r(f).catch(()=>{}),await n().catch(()=>{});let h=!1,m=!1;try{h=await o()}catch(E){m=!0,console.error(`anyray offboard: clearing enrollment: ${Ya(E)}`)}let w=[],g=[],y=[];for(let E of p){let I=i(E);if(!I){y.push(E);continue}try{let C=await I.revert({dryRun:!1,fullRevert:!0});w.push({id:E,status:C.status}),iJ(C.status)?g.push(E):y.push(E)}catch(C){console.error(`anyray offboard: reverting ${E}: ${Ya(C)}`),y.push(E)}}let b=!0;try{await a(w,!0,!0)}catch(E){b=!1,console.error(`anyray offboard: recording managed tools: ${Ya(E)}`)}let A=y.length===0&&b,v=!1;if(A)try{await s(),v=!0}catch(E){console.error(`anyray offboard: stamping offboard: ${Ya(E)}`)}try{let E=await t();(E.fallbackPort||await d("daemon"))&&await c(E.fallbackPort),(E.refreshSchedulerEnabled||await d("scheduler"))&&await l(),await u({...await t(),keyRefreshEnabled:!1,fallbackPort:void 0,refreshSchedulerEnabled:!1})}catch(E){console.error(`anyray offboard: unit teardown: ${Ya(E)}`)}return{reverted:g,unresolved:y,enrollmentCleared:h,credentialHeld:m,recordPersisted:b,offboardMarked:v,ok:y.length===0&&!m&&b&&v}};var lR=e=>e?.name??"Error",dR=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??L,r=t.recordManagedTools??Qn,o=t.adapterById??Kt,a=t.isLocked??Ci,s=await n().catch(()=>{});if(!s)return"failed";if(!(s.managedTools??[]).includes(e))return"ok";if(a(s,e))return console.error(`anyray revert-tool: ${e} is locked by fleet policy`),"failed";let i=o(e);if(!i)return"failed";let c;try{c=(await i.revert({dryRun:!1,fullRevert:!1})).status}catch(l){return console.error(`anyray revert-tool: reverting ${e}: ${lR(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${lR(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as fR}from"node:os";var hR=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
787
+ `},rO=e=>{if(/[\u0000-\u0020\u007f]/.test(e)||/["'`\\^<>|{}]/.test(e))return!1;try{let t=new URL(e);return t.username||t.password?!1:t.protocol==="https:"?!0:t.protocol==="http:"&&(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1")}catch{return!1}},ZZ=Fe.object({code:Fe.string().min(1).optional(),message:Fe.string().min(1).optional()}).passthrough(),F0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},XZ=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=ZZ.safeParse(t);if(!r.success)return n;let o=F0(r.data.message??""),a=F0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},U0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??vZ),a;try{a=await(n.fetchResponse??fetch)(`${e}/connect/endpoint-enrollment`,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:"{}",signal:r.signal})}catch{throw new ce("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new ce("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new ce(XZ(a.status,c))}let s;try{s=await a.json()}catch{throw new ce("The gateway returned malformed endpoint enrollment data.")}let i=Fe.object({fleetUrl:Fe.string().min(1).max(2048),enrollSecret:Fe.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!rO(i.data.fleetUrl))throw new ce("The gateway returned invalid endpoint enrollment data.");return i.data},JZ=async(e={})=>{let t=e.exists??zy;if(await t("/usr/bin/dpkg")||await t("/bin/dpkg"))return"deb";if(await t("/usr/bin/rpm")||await t("/bin/rpm"))return"rpm";throw new ce("Linux endpoint installation requires either dpkg or rpm.")},qZ=async e=>e==="darwin"?"pkg":e==="win32"?"msi":JZ(),eg=e=>`fleetd.${e}`,zZ=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",QZ=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),AZ);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},e5=async(e,t={})=>{let n=eg(e),r=t.fetchResponse??fetch,o;try{o=await QZ(`${L0}/SHA256SUMS`,r)}catch{throw new ce("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new ce(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=fy(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await V0(gu(wZ(),"anyray-endpoint-")),i=gu(s,n);try{await Vy(s,448),await(t.download??yy)(`${L0}/${n}`,i,a)}catch(c){if(await $r(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof ji&&c.status===404)return;throw new ce("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>$r(s,{recursive:!0,force:!0})}},t5=async(e,t,n)=>{await hZ(bZ(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await $r(r,{force:!0});try{await gZ(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await mZ(r,e)}catch(o){throw await $r(r,{force:!0}).catch(()=>{}),o}},B0=async e=>{let t=uZ("sha256");for await(let n of dZ(e))t.update(n);return t.digest("hex")},n5=async(e,t={})=>{let n=await fZ(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new ce("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await B0(e.path)!==e.sha256)throw new ce("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await V0(gu(xZ,"anyray-endpoint-root-")),o=gu(r,eg(e.kind));try{if(await Vy(r,448),await pZ(e.path,o),await Vy(o,384),await B0(o)!==e.sha256)throw new ce("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>$r(r,{recursive:!0,force:!0})}}catch(a){throw await $r(r,{recursive:!0,force:!0}).catch(()=>{}),a}},ja=(e,t)=>{if(e.status!==0)throw new ce(t)},W0="com.fleetdm.fleetd.config",r5="com.fleetdm.fleetd.enroll.secret",o5=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",X0],a5=[RZ,J0],s5=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(W0))throw new ce(`This machine already receives its endpoint configuration from an MDM profile (${W0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},H0=async(e,t,n)=>{let r=n.removeFile??(o=>$r(o,{force:!0}));for(let o of e==="win32"?a5:o5)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",r5,"/Library/Keychains/System.keychain"])},i5=e=>{e(yu,[nc,"/inheritance:r"]),e(yu,[nc,"/grant:r","*S-1-5-18:(F)"]),e(yu,[nc,"/grant:r","*S-1-5-32-544:(F)"]),e(yu,[nc,"/remove:g","*S-1-5-32-545"])},c5=(e,t,n)=>{if(e.kind==="pkg"){ja(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){ja(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){ja(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}ja(t(PZ,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},l5=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<Gy;r++){if(n=t("/bin/launchctl",["bootstrap","system",Va]),n.status===0)return;t("/bin/sleep",[EZ])}throw new ce(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(Yy,["stop",bu]);for(let n=0;n<Gy;n++){let r=Jy(t);if(r==="Stopped"||r==="absent")break;t(Zy,N0)}for(let n=0;n<Gy;n++){if(t(Yy,["start",bu]).status===0||Jy(t)==="Running")return;t(Zy,N0)}throw new ce("Orbit was configured, but the Windows service could not be started.")}ja(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),ja(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},d5=e=>new Promise(t=>setTimeout(t,e)),oO=async(e,t={})=>{let n=t.command??ac,r=t.readText??(c=>ku(c,"utf8")),o=t.writeText??t5,a=t.removeSecret??(()=>$r($0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&s5(n),e.package&&!zZ(e.os,e.package.kind))throw new ce("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new ce("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await H0(e.os,n,t),e.package){let d=await(t.preparePackage??n5)(e.package);i=d.cleanup,c5(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Va);await o(Va,VZ(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(wu);await o(wu,YZ(d,e.fleetUrl),420)}else await o(q0,`anyray
788
+ `,384);e.os!=="win32"&&await H0(e.os,n,t),await o($0(e.os),`${e.enrollSecret}
789
+ `,384),e.os==="win32"&&i5(n),s=e.os!=="win32"}l5(e.os,n);let c=t.checkIn??(async d=>{let u=await tO(d);return u.running&&u.checkedIn}),l=t.wait??d5;for(let d=0;d<(t.attempts??D0);d++){if(await c(e.os))return;d+1<(t.attempts??D0)&&await l(SZ)}throw new ce("The endpoint agent did not check in after restart. The package command succeeded, but enrollment was not confirmed.")}finally{s&&await a().catch(()=>{}),await i?.().catch(()=>{})}},u5=async()=>{try{return await j0("/dev/tty",Y0.R_OK),!0}catch{return!1}},p5=12288,f5=e=>{let t=e(_Z,["/groups"]);if(t.status!==0)return!1;let n=-1;for(let r=0;;){let o=t.stdout.indexOf("S-1-16-",r);if(o<0)break;r=o+7;let a=r;for(;a<t.stdout.length&&t.stdout[a]>="0"&&t.stdout[a]<="9";)a++;a>r&&(n=Math.max(n,Number(t.stdout.slice(r,a)))),r=a}return n>=p5},h5=async(e,t={})=>{if((t.os??Ya())==="win32")return(t.elevated??(()=>f5(t.command??ac)))()?(await e(),"direct"):((t.print??k)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
790
+ anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??u5)()){if(await(t.reexec??(async()=>1))()!==0)throw new ce("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??k)(`Administrator access is required. Run:
791
+ sudo anyray-connect endpoint install`),"deferred"},m5=async e=>{let t=`${JSON.stringify(e)}
792
+ `;if(Buffer.byteLength(t)>Z0)throw new ce("The privileged endpoint plan is unexpectedly large.");let n=un(["__anyray-endpoint-install"]);return G0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},y5=async(e,t={})=>(t.withRoot??h5)(()=>(t.apply??oO)(e),{...t.root,reexec:()=>(t.sudo??m5)(e)}),K0=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return D();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return D();let t;try{let s=(await ku("/etc/passwd","utf8")).split(`
793
+ `).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Ya()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await D()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},aO=async(e={},t={})=>{let n=t.os??Ya();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new ce("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??tO)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??K0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??HZ)(r);if(!l||!d||u===void 0)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};let f=await(t.fetchEnrollment??U0)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};M("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new ce("This machine is already enrolled in a different Fleet configuration; it was left unchanged.");let s,i;if(o.installed&&o.configured&&o.checkedIn&&!a)s={action:"restart",os:r};else{let c=e.gateway&&e.clientKey?void 0:await(t.profile??K0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new ce("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??U0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>qZ(r)))();if(i=await(t.stagePackage??e5)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${eg(f)} is not published yet; skipping.`}}s={action:"configure",os:r,...u,...i?{package:{kind:i.kind,path:i.path,sha256:i.sha256}}:{}}}try{return await(t.execute??y5)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},tg=e=>e instanceof ce?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",sO=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return k(LZ),0;if(e.length!==1||e[0]!=="install")return _("Usage: anyray-connect endpoint install"),1;try{let t=await aO();return t.message&&(t.outcome==="installed"?F(t.message):M(t.message)),0}catch(t){return _(tg(t)),1}},g5=async()=>{let e=[],t=0;for await(let o of process.stdin){let a=Buffer.isBuffer(o)?o:Buffer.from(o);if(t+=a.length,t>Z0)throw new ce("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new ce("The privileged endpoint plan is malformed.")}let r=MZ.safeParse(n);if(!r.success||r.data.os!==Ya()||r.data.action==="configure"&&!rO(r.data.fleetUrl))throw new ce("The privileged endpoint plan is invalid.");return r.data},iO=async e=>{if((process.getuid?.()??-1)!==0)return _("The privileged endpoint step must run as root."),1;if(e.length!==0)return _("The privileged endpoint step does not accept arguments."),1;try{return await oO(await g5()),0}catch(t){return _(tg(t)),1}},cO=async(e,t=aO)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?F(n.message):M(n.message)),n.outcome}catch(n){M(`Endpoint agent: ${tg(n)} Tool routing remains configured.`);return}};import{execSync as ng}from"node:child_process";import{hostname as w5}from"node:os";var b5=e=>{try{if(e==="darwin"){let t=ng("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=ng('reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid',{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/MachineGuid\s+REG_SZ\s+([\w-]+)/.exec(t)?.[1]??""}return ng("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Cu=(e={platform:process.platform,read:()=>b5(process.platform),hostname:w5})=>e.read().trim()||e.hostname().trim();var k5=(e,t=Date.now())=>e.credentialProtocol==="stable-heartbeat-v1"||!$d(e,void 0,t),lO=async(e,t={})=>{if(!await(t.fleetdPresent??Ro)())return{retired:!1,reason:"no-fleetd",messages:[]};if(!k5(e,t.now??Date.now()))return{retired:!1,reason:"seat-could-lapse",messages:[]};let r=[],o=await(t.uninstallScheduler??fr)();r.push(...o.messages);let a=await(t.uninstallProxy??Qt)();return r.push(...a.messages),{retired:!0,messages:r}};var dO=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();return t?t.toLowerCase():(e.platform??process.platform)==="darwin"?(e.readMacUuid??(()=>Cu()))().trim().toLowerCase():""};var uO=["reapply_config","remint","revert","revert_tool"],C5=/^[a-z0-9][a-z0-9-]{0,31}$/;var A5=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||t.id.length===0||typeof t.kind!="string"||!uO.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&C5.test(t.tool):t.tool===void 0},rg=e=>e?.name??"error",pO=async(e,t,n)=>{let r=n.fetchImpl??fetch,o=e.replace(/\/$/,""),a;try{let i=await r(`${o}/connect/directive`,{method:"GET",headers:{"x-anyray-api-key":t,"x-anyray-directive-kinds":uO.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!A5(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",rg(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",rg(i)),s="failed"}try{await r(`${o}/connect/directive/ack`,{method:"POST",headers:{"x-anyray-api-key":t,"content-type":"application/json"},body:JSON.stringify({id:a.id,result:s}),signal:AbortSignal.timeout(1e4)})}catch(i){console.error("connect directive ack skipped:",rg(i))}return a.kind};var v5=1e4,Za=e=>e?.name??"Error",og=async(e,t=fetch)=>{let n=e.gateway?.replace(/\/+$/,""),r=e.clientKey;if(!(!n||!r))try{await t(`${n}/connect/offboard`,{method:"POST",headers:{"x-anyray-api-key":r},signal:AbortSignal.timeout(v5)})}catch(o){console.error(`anyray seat offboard report: ${Za(o)}`)}},S5=e=>e==="reverted"||e==="queued",fO=async(e={})=>{let t=e.loadProfile??D,n=e.clearDeviceTokenState??Hd,r=e.reportSeatOffboarded??og,o=e.clearEnrollment??fc,a=e.recordManagedTools??tr,s=e.markSeatOffboarded??mc,i=e.adapterById??Ht,c=e.uninstallProxy??Qt,l=e.uninstallScheduler??fr,d=e.unitsPresent??Di,u=e.saveProfile??re,f=await t(),p=f.managedTools??[];await r(f).catch(()=>{}),await n().catch(()=>{});let h=!1,m=!1;try{h=await o()}catch(E){m=!0,console.error(`anyray offboard: clearing enrollment: ${Za(E)}`)}let w=[],g=[],y=[];for(let E of p){let x=i(E);if(!x){y.push(E);continue}try{let C=await x.revert({dryRun:!1,fullRevert:!0});w.push({id:E,status:C.status}),S5(C.status)?g.push(E):y.push(E)}catch(C){console.error(`anyray offboard: reverting ${E}: ${Za(C)}`),y.push(E)}}let b=!0;try{await a(w,!0,!0)}catch(E){b=!1,console.error(`anyray offboard: recording managed tools: ${Za(E)}`)}let A=y.length===0&&b,v=!1;if(A)try{await s(),v=!0}catch(E){console.error(`anyray offboard: stamping offboard: ${Za(E)}`)}try{let E=await t();(E.fallbackPort||await d("daemon"))&&await c(E.fallbackPort),(E.refreshSchedulerEnabled||await d("scheduler"))&&await l(),await u({...await t(),keyRefreshEnabled:!1,fallbackPort:void 0,refreshSchedulerEnabled:!1})}catch(E){console.error(`anyray offboard: unit teardown: ${Za(E)}`)}return{reverted:g,unresolved:y,enrollmentCleared:h,credentialHeld:m,recordPersisted:b,offboardMarked:v,ok:y.length===0&&!m&&b&&v}};var hO=e=>e?.name??"Error",mO=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??D,r=t.recordManagedTools??tr,o=t.adapterById??Ht,a=t.isLocked??vi,s=await n().catch(()=>{});if(!s)return"failed";if(!(s.managedTools??[]).includes(e))return"ok";if(a(s,e))return console.error(`anyray revert-tool: ${e} is locked by fleet policy`),"failed";let i=o(e);if(!i)return"failed";let c;try{c=(await i.revert({dryRun:!1,fullRevert:!1})).status}catch(l){return console.error(`anyray revert-tool: reverting ${e}: ${hO(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${hO(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as wO}from"node:os";var bO=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
794
794
 
795
795
  ${j("Usage")}
796
796
  npx anyray-connect [options]
@@ -810,7 +810,7 @@ ${j("Options")}
810
810
  --enroll <link> Connect with a passwordless enrollment link or token
811
811
  --sso <link> Connect with an enterprise SSO link or tenant id
812
812
  --claim <code> Redeem the one-time code from your org's Anyray sign-in page
813
- --tools <ids> Comma-separated subset: ${se.map(e=>e.id).join(", ")}
813
+ --tools <ids> Comma-separated subset: ${ie.map(e=>e.id).join(", ")}
814
814
  --user <id> Attribute spend to this user
815
815
  --team <id> Attribute spend to this team
816
816
  --dry-run Show what would change without writing anything
@@ -827,7 +827,7 @@ ${j("What it does")}
827
827
  key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
828
828
  metadata (user/team) is attached \u2014 never prompt content.
829
829
  ~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
830
- per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,mR=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
830
+ per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,kO=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
831
831
 
832
832
  ${j("Usage")}
833
833
  npx anyray-connect <gateway-url> [options]
@@ -974,7 +974,7 @@ ${j("Options")}
974
974
  Your personal key for the --upstream endpoint (e.g. your
975
975
  LiteLLM virtual key). Stored locally (mode 600) and in the
976
976
  tool config, never sent to Anyray's control plane.
977
- --tools <ids> Comma-separated subset: ${se.map(e=>e.id).join(", ")}
977
+ --tools <ids> Comma-separated subset: ${ie.map(e=>e.id).join(", ")}
978
978
  --project Write committable, credential-free routing config into the
979
979
  CURRENT repo (.claude/settings.json + .codex/config.toml)
980
980
  instead of this machine's user config \u2014 so devcontainers,
@@ -1023,22 +1023,22 @@ ${j("What it does")}
1023
1023
  key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
1024
1024
  metadata (user/team) is attached \u2014 never prompt content.
1025
1025
  ~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
1026
- per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,lJ=e=>{let t=e?.trim();return t||Bm()},bu=(e,t)=>t||e,yR=e=>{let t={subscription:!1,placeholder:!1,dryRun:!1,yes:!1,revert:!1,force:!1,skipVerify:!1,verbose:!1,help:!1,helpAll:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>e[++n];switch(r){case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":t.key=o();break;case"--enroll":t.enroll=o();break;case"--sso":t.sso=o();break;case"--claim":t.claim=o();break;case"--machine":t.machine=!0;break;case"--subscription":t.subscription=!0;break;case"--placeholder":case"--org":t.placeholder=!0;break;case"--upstream":t.upstream=o();break;case"--upstream-key":t.upstreamKey=o();break;case"--tools":t.tools=(o()??"").split(",").map(a=>a.trim()).filter(Boolean);break;case"--project":t.project=!0;break;case"--dry-run":t.dryRun=!0;break;case"--yes":case"-y":t.yes=!0;break;case"--force":t.force=!0;break;case"--skip-verify":t.skipVerify=!0;break;case"--fallback":case"--no-fallback":t.retiredFallbackFlag=!0;break;case"--no-key-refresh":t.noKeyRefresh=!0;break;case"--quit-apps":t.quitApps=!0;break;case"--no-quit-apps":t.noQuitApps=!0;break;case"--endpoint":t.endpoint=!0;break;case"--no-endpoint":t.noEndpoint=!0;break;case"--revert":t.revert=!0;break;case"--json":t.json=!0;break;case"--verify":t.verify=!0;break;case"--no-verify":t.noVerify=!0;break;case"--quick":t.quick=!0;break;case"--repair":t.repair=!0;break;case"--security-review":t.securityReview=!0;break;case"--verbose":t.verbose=!0;break;case"--help":case"-h":t.help=!0;break;case"--help-all":t.help=!0,t.helpAll=!0;break;case"--all":if(!e.includes("--help")&&!e.includes("-h"))throw new Error(`unknown option: ${r}`);t.helpAll=!0;break;default:if(!r.startsWith("-")&&t.gateway===void 0)t.gateway=r;else throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r} (gateway already set to ${t.gateway})`)}}return t},dJ=e=>!e||e.length===0?se:e.map(t=>{let n=Kt(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${se.map(r=>r.id).join(", ")}`);return n}),uJ=(e,t)=>{if(K("Gateway target"),k(` Origin: ${tt(e.origin)}`),e.byoUpstream)k(` Auth: BYO upstream key ${S(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&k(` Client key: personal gateway key (${Mt(e.clientKey)}) ${S("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=X(e,"anthropic")?tt("your subscription"):"org key",r=X(e,"openai")?tt("your subscription"):"org key";k(` Auth: auto ${S("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&k(` Client key: personal gateway key (${Mt(e.clientKey)})`)}else e.authMode==="subscription"?(k(` Auth: subscription pass-through ${S("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&k(` Client key: personal gateway key (${Mt(e.clientKey)}) ${S("rides x-anyray-api-key")}`)):e.clientKey?k(` Auth: personal gateway key (${Mt(e.clientKey)}) ${S("(replaces the placeholder)")}`):k(` Enrollment: ${S("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&k(` Cursor: ${tt("native Team subscription")} ${S("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(X(e,"anthropic")?(k(` Claude Desktop: ${tt("subscription-backed Gateway lane")} ${S("(verified macOS builds; Windows fails closed)")}`),k(` ${S("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(k(` Claude Desktop: ${tt("third-party API lane")} ${S("(API-billed; switches the active local inference profile)")}`),k(` ${S("The first-party Claude subscription remains untouched.")}`))),k(` Attribution: ${de(e.metadata)??S("(none \u2014 pass --user)")}`)},uR=async(e,t)=>{K("Selected tools");for(let n of e){let r=await n.detect();r.installed?k(` ${n.title} ${S(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):M(` ${n.title} ${S(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},pJ=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!xe(n))return;let r=e.clientKeyExpiresAt?.trim();if(!r)return n;let o=Date.parse(r);return Number.isFinite(o)&&o>t?n:void 0},fJ={loadDevKey:We,saveDevKey:dc,clearDevKey:rs,saveProfile:re},hJ=async(e,t,n,r=fJ,o=!1)=>{let a=!!n||o,s=a?await r.loadDevKey():void 0,i=!1,c=!1;try{a&&(i=!0,n?await r.saveDevKey(n):await r.clearDevKey()),c=!0,await r.saveProfile(t)}catch(l){throw i&&(s!==void 0?await r.saveDevKey(s).catch(()=>{}):await r.clearDevKey().catch(()=>{})),c&&await r.saveProfile(e).catch(()=>{}),l}},mJ=async(e,t,n,r,o)=>{n.dryRun||await pc();let a=0,s=[],i=[],c=[],l=[],d=[];for(let u of e){if(!(await u.detect()).installed&&!r){d.push(u.title);continue}K(`${u.title} ${S(`(${u.id})`)}`);try{let p=r?await u.revert(n):await u.apply(t,{...n,explicit:o?.has(u.id)===!0,reportsToUser:!0});for(let h of p.messages)k(` ${h}`);a+=p.changedFiles?.length??0,l.push({id:u.id,status:p.status}),p.status==="configured"||p.status==="reverted"?F(` ${p.status}`):p.status==="manual"?(s.push(u.title),p.manualAudience==="admin"?(i.push(u.title),c.push(u.id),D(" blocked by machine policy \u2014 your IT team owns this one")):D(" manual step required (see above)")):p.status==="held"?M(" left on its own plan (no change)"):M(` ${p.status}`)}catch(p){l.push({id:u.id,status:"failed"}),_(` failed: ${p instanceof Error?p.message:String(p)}`)}}if(d.length>0&&M(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await yc().catch(()=>[]);u.length&&M(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},yJ=(e,t=[],n)=>{if(e.length===0)return[];if(t.length===e.length)return[`${e.length===1?`${e[0]} is`:`${e.join(", ")} are`} controlled by a machine policy your organization manages, so local setup cannot change it.`,...n==="darwin"?["Admin next step: on an unmanaged admin Mac, open Claude Desktop \u2192 Developer \u2192 Configure Third-Party Inference, complete and test the Anyray connection, connectors, and plugin marketplaces, then Export \u2192 .mobileconfig and deploy that complete profile through MDM.","The configuration window is read-only on managed endpoints; Connect will not create an incomplete replacement profile or supplement the managed source locally."]:n?["Your administrator must create and test the complete Claude Desktop third-party policy through Anthropic's enterprise configuration flow, then deploy it through your organization's device-management system.","Connect will not create an incomplete replacement policy or supplement the managed source locally."]:["Your Anyray administrator can see this state in the console's Connect coverage view."],"Everything else on this machine is configured and routing normally."];let o=[`${e.length===1?`${e[0]} needs`:`${e.length} tools need`} a remaining app action \u2014 Connect may already have written its automatic config.`,`Review and complete the steps shown above for: ${e.join(", ")}.`,"Then restart or reload the app as instructed; use `npx anyray-connect status` for the available route checks."];return t.length>0&&o.push(`Not yours to fix: ${t.join(", ")} \u2014 a machine policy your organization manages. Flagged for your Anyray administrator.`),o},gJ=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>gR(o)&&!r.has(o.id))},wJ=async e=>{let t=II(e,process.platform,Q());if(t){await pe(t.path,t.content);for(let n of xI(t,process.platform))k(` ${n}`)}},bJ=async(e,t,n=fR())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!Ab(i,n)||!Cb(i,n))continue;let c=bb(i,n);if(!o.has(c)){try{if(!(await a.detect()).installed||!s.isRunning()||await a.pointsAt?.(t)===!0)continue}catch{continue}o.add(c),r.push({id:a.id,title:kb(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},kJ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,CJ=e=>`
1027
- ${e.length===1?`${e[0]} is open and won't pick this up until it restarts. Quit it now?`:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]} are open and won't pick this up until they restart. Quit them now?`}`,AJ=async(e,t={})=>{let n=t.requestQuit??(a=>Sb(a)),r=t.waitFor??(a=>Eb(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),F(` Closed ${a.title}.`);continue}D(` ${a.title} is still open \u2014 leaving it alone.`),M(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},vJ=(e,t={})=>{let n=t.relaunch??(o=>Ib(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),F(` Reopened ${o.title}.`)):D(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},gR=e=>e.changesBilling===!0||e.changesOrgManagement===!0,wR=e=>e.changesBilling===!0?"moves inference spend from your subscription to the org API bill":e.changesOrgManagement===!0?"switches the app to third-party mode; claude.ai Enterprise org settings stop applying":void 0,rg=e=>!gR(e),SJ=async(e,t,n={})=>{let r=n.hasEnrollment??Lu,o=n.canMultiSelect??QI,a=n.multiSelect??ex,s=n.prompt??Ma,i=n.registry??se;if(k(j("Anyray connect \u2014 guided setup")),k(S("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())k("Stored enrollment will be reused. Run with --revert to clear it.");else if(!e.enroll&&!e.sso&&!e.gateway){K("How do you want to connect?");let c;for(let l=0;l<3&&!c;l++){if(o()){let d=await a({title:"Choose a connection method",single:!0,items:[{value:"enroll",label:"Paste an enrollment link",selected:!0},{value:"sso",label:"Sign in with SSO"},{value:"gateway",label:"I already have a gateway URL"}]});if(d.kind==="cancelled")throw new wt;c=d.values[0]}else{k(" 1. Paste an enrollment link"),k(" 2. Sign in with SSO"),k(" 3. I already have a gateway URL");let d=await s("? Connection method (1-3)","1");c=d==="1"?"enroll":d==="2"?"sso":d==="3"?"gateway":void 0}c||D("Choose one of the three connection methods.")}if(!c)throw new wt;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&Wi(d)&&nu(d)){e.enroll=d;break}D("That is not a valid enrollment link or token. Try again.")}else if(c==="sso"){let d=await s("? SSO link or tenant id");if(d&&Ot(d)){e.sso=d;break}D("That is not a valid SSO link or tenant id. Try again.")}else{let d=await s("? Gateway URL",t.gateway||process.env.ANYRAY_GATEWAY_URL);if(d&&Wi(d)){e.enroll=d,k("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=dn(d);break}catch{D("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new wt}if(!e.tools||e.tools.length===0){K("Tools detected");let c=[],l=[];for(let u of i){if(!(await u.detect()).installed){l.push(u);continue}c.push(u)}let d=c.filter(u=>rg(u)).map(u=>u.id);if(c.length>0){for(let u=0;u<3&&!e.tools;u++){let f;if(o()){let p=await a({title:"Tools to configure",items:c.map(h=>({value:h.id,label:`${h.title} (${h.id})`,hint:wR(h),selected:rg(h),requiresExplicitChoice:!rg(h)}))});if(p.kind==="cancelled")throw new wt;f=p.values}else{f=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(w=>w.trim()).filter(Boolean);let h=new Set(c.map(w=>w.id)),m=f.filter(w=>!h.has(w));if(m.length>0){D(`Unknown or unavailable tool id${m.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(f.length===0){D("Choose at least one installed tool.");continue}e.tools=f}if(!e.tools)throw new wt}l.length>0&&M(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},EJ=async(e,t)=>{K("Verifying the connection");let n=await Hi("Checking the gateway\u2026",()=>Vi(e,{tools:t}));n.kind==="ok"?F(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?D(` ${n.detail}`):_(` ${n.detail}`);for(let r of n.remedy)k(S(` ${r}`))},IJ=5e3,xJ=500,pR=3,RJ=600*1e3,OJ=async()=>{try{let e=await cJ(await No());return Date.now()-e.mtimeMs}catch{return Number.POSITIVE_INFINITY}},_J=async(e={})=>{try{let t=await(e.load??L)();if(t.keyRefreshEnabled!==!0){if((e.draining??ap)()||!await(e.unitExists??yw)()||await(e.profileAgeMs??OJ)()<RJ)return;await(e.uninstall??Qt)(t.fallbackPort??ke);return}if(!t.gateway||t.persistenceOwner==="tray"&&await(e.checkTray??Eo)(t)==="healthy")return;let n=t.fallbackPort??ke,r=e.probe??be,o=e.probeGapMs??xJ;for(let s=0;s<pR;s++){if(await r(n,s===0?void 0:IJ)!==null)return;s<pR-1&&o>0&&await new Promise(c=>setTimeout(c,o))}if((e.draining??ap)())return;let a=await(e.install??Nt)({port:n,remoteOrigin:new URL(t.gateway).origin});if(!a.ok)for(let s of a.messages)console.error(s)}catch{}},TJ=async(e,t,n={})=>{let r=n.install??Nt,o=n.probe??be,a=n.pollDelayMs??300;K("Seamless key refresh");let s=n.trayManaged?{ok:!0,messages:["Launch-at-login is managed by the Anyray Connect app \u2014 not re-registering the login service."]}:await r({port:t,remoteOrigin:e.origin});for(let l of s.messages)k(` ${l}`);let i=s.ok?10:1,c=null;for(let l=0;l<i&&!c;l++)c=await o(t),!c&&l<i-1&&await new Promise(d=>setTimeout(d,a));return c?(F(` Running on 127.0.0.1:${t} \u2192 ${e.origin} \u2014 your key refreshes automatically, no restart needed.`),In(e,t)):(D(" Key-refresh proxy did not come up \u2014 pointing tools directly at the gateway for now."),k(S(s.ok?" It will retry on the next run; check the service logs if it persists.":Ct(mt())?" In a container the key refreshes via Claude Code's helper and on each `anyray-connect` run instead.":" Your key still refreshes on a schedule \u2014 no daemon needed here.")),e)},PJ=async(e,t={})=>{if(e.dryRun)return;let n=t.install??dr,r=t.uninstall??ur;if(e.want&&e.trayManaged){e.announcePrimary&&(K("Automatic key refresh"),F(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."));return}if(e.want){let o=await n();if(e.announcePrimary){K("Automatic key refresh");for(let a of o.messages)k(` ${a}`);o.ok&&F(" Your gateway key now re-mints every ~30 min \u2014 no tool will 401 on a stale key mid-session.")}o.ok||await re({...await L(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){K("Automatic key refresh");let o=await r();for(let a of o.messages)k(` ${a}`);await re({...await L(),refreshSchedulerEnabled:!1}),F(" Removed the automatic key-refresh schedule.")}},LJ=new Set(["login","wizard","status","doctor","sync","device-url"]),DJ=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),NJ=e=>{if(e.outcome==="migrated"&&e.managedPath)return{level:"info",message:`Installed managed anyray-connect at ${e.managedPath}.`};if(e.outcome==="platform-unsupported")return{level:"warn",message:"Self-update is unavailable on this platform; keeping the durable npm runtime for persistent integrations."};if(e.outcome==="migration-deferred")return{level:"warn",message:`Managed install deferred because the published binary (${e.latest}) is older than this npm runtime (${e.current}).`};if(!(e.outcome==="current"||e.outcome==="unmanaged"||e.outcome==="updated"||e.outcome==="disabled"||e.outcome==="container"))return{level:"warn",message:"Could not install the managed anyray-connect binary; continuing with the current runtime \u2014 it migrates automatically on a later refresh."}},$J=e=>{if(e.includes("--help")||e.includes("--help-all")||e.includes("-h"))return!1;if(e[0]==="managed")return e.includes("--write")&&!e.includes("--revert");if(e[0]==="desktop"){let t=qm(e.slice(1));return!!(t&&!t.includes("--dry-run")&&!t.includes("--revert"))}return e.includes("--dry-run")||e.includes("--revert")||e.includes("--project")?!1:e[0]==="doctor"?e.includes("--repair"):e[0]==="models"?e.slice(1).some(t=>!t.startsWith("-")):!e[0]||!DJ.has(e[0])},og=async(e,t)=>{try{return await UJ(e,t)}catch(n){if(n instanceof wt)return console.error(S("Cancelled \u2014 nothing was written.")),130;throw n}},MJ=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??Yt)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
1028
- ${o} ${n} tool target(s)?`;return await(r.confirm??$a)(a)?"proceed":"declined"},FJ=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return qx(n)}if(e[0]==="__anyray-codex-hook")return Qx();if(e[0]==="__anyray-prompt-hook")return e0();if(e[0]==="__anyray-shell-pretool")return o0();if(e[0]==="__anyray-shell-run")return r0(e.slice(1));if(e[0]==="__anyray-read-pretool")return p0();if(e[0]==="__anyray-sso-gate")return nE(e.slice(1));if(e[0]==="__anyray-sso-poll")return f0();if(e[0]==="__anyray-vscode-gate")return b0();if(e[0]==="__anyray-spawn-refresh")return await Rr(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return I0(n)}if(e[0]==="__anyray-acp-agent")return x0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return nR(e.slice(1));if(e[0]==="__anyray-refresh"){await my(),await et({runAmbientSelfcheck:!0}),await Im(),await _J(),await HS(),await KS();let n=await L().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await re(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await _o().catch(()=>!1);if(await oR(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=aR(),i=n.enrolledCert;if(s&&i){let l=await We().catch(()=>{});l&&await eS(o,a,i,l,s).catch(()=>{})}await iR(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await et({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?dR(d):(await cR()).ok?"ok":"failed"}).catch(()=>{})}}return await Gi(),0}if(e[0]==="__anyray-fallback-proxy")return kE();if(e[0]==="__anyray-persistence")return AE(e.slice(1));if(e[0]==="__anyray-quit-watch")return RE(e.slice(1));if(e[0]===oi)return dI(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return w0();try{let n=await $g(e);if(n!==void 0)return n}catch(n){return _(`Could not persist anyray-connect for long-lived integrations: ${n instanceof Error?n.message:String(n)}`),1}if($J(e)){let n=NJ(await ix());n?.level==="warn"?D(n.message):n&&console.error(n.message)}if(e[0]==="managed")return UE(e.slice(1));if(e[0]==="endpoint")return tR(e.slice(1));if(e[0]==="print-key")return KE(e.slice(1));if(e[0]==="models")return jE(e.slice(1));if(e[0]==="copilot-login")return VE(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=qm(n);return r?og(r,!1):RI(n)}if(e[0]==="retrieve")return _I(e.slice(1));if(e[0]==="recall")return TI(e.slice(1));if(e[0]==="history")return KI(e.slice(1));if(e[0]==="migrate")return jI(e.slice(1));if(e[0]==="login")return m0(e.slice(1));if(e[0]==="update")return g0(e.slice(1));let t=e[0];if(t&&LJ.has(t)){let n=e.slice(1),r;try{r=yR(n)}catch(o){return _(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?mR:hR),0):t==="status"?hx({gateway:r.gateway}):t==="doctor"?bx({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?kx({gateway:r.gateway}):t==="device-url"?YE():og(n,!0)}return og(e,!1)},bR=async e=>{try{return await FJ(e)}catch(t){if(t instanceof wt)return console.error(S("Cancelled.")),130;throw t}},UJ=async(e,t,n={})=>{let r=n.isInteractive??Yt,o;try{o=yR(e)}catch(O){return _(O.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?mR:hR),0;if(o.revert&&(o.sso||o.enroll||o.claim))return _("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(_("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):iI({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return _("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return _("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let O;try{O=new URL(o.upstream.trim())}catch{return _(`invalid --upstream URL: "${o.upstream}"`),1}if(O.protocol!=="http:"&&O.protocol!=="https:")return _(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let P=o.upstreamKey.trim();if(!P)return _("--upstream-key must not be empty."),1;a={url:Ze(o.upstream),key:P}}let s=await L();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let O=await my();(O==="migrated"||O==="already-direct")&&(s=await L())}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream),o.retiredFallbackFlag&&D("--fallback/--no-fallback are retired and ignored: the local daemon no longer routes around the gateway to the provider. Seamless key refresh is on by default (--no-key-refresh opts out).");let i=!t&&Yt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??SJ)(o,s),c=!0);let l;try{l=dJ(o.tools)}catch(O){return _(O.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&Wi(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,k("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,f=!1;if(o.enroll&&(!o.gateway||s.enrolledCert)){let O=nu(o.enroll);if(O)try{let P=await Hi("Resolving enrollment link\u2026",()=>zI(O)),H=!o.gateway;H&&(o.gateway=P.gatewayUrl),d=P.deploymentId,u=P.email,f=!0,H&&M(`Enrollment link${P.org?` for ${P.org}`:""}: gateway ${P.gatewayUrl}`),P.seatMode&&!o.subscription&&(o.subscription=!0,M("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(P){let H=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(H)M(`Could not resolve the gateway from the enrollment link \u2014 using ${H}.`);else return _(P instanceof Error?P.message:String(P)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)M("dry run: not enrolled (skipped redeeming the enrollment link).");else{let O=VS(o.claim);if(!O)return _("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let P=await Hi("Connecting this machine\u2026",()=>YS({cpOrigin:O.cpOrigin,claim:O.claim,gatewayUrl:o.gateway}));p={cert:P.cert,privateKeyPem:P.privateKeyPem},P.deploymentId&&(d=P.deploymentId),!o.gateway&&P.gatewayUrl&&(o.gateway=P.gatewayUrl),h=P.ssoLink}catch(P){return _(P instanceof Error?P.message:String(P)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)M("dry run: not enrolled via SSO (skipped minting a personal key).");else{let O=Ot(o.sso);if(!O)return _(Wi(o.sso)?"that is an enrollment link, not an SSO link \u2014 re-run with --enroll instead of --sso.":"invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let P=await Md({cpOrigin:O.cpOrigin,tenantId:O.tenantId,gatewayUrl:o.gateway,log:fe=>M(fe),open:r()?_a:void 0}),H=await Hi("Waiting for SSO sign-in\u2026",()=>Fd(P,{gatewayUrl:o.gateway}));p={cert:H.cert,privateKeyPem:H.privateKeyPem},H.deploymentId&&(d=H.deploymentId),!o.gateway&&H.gatewayUrl&&(o.gateway=H.gatewayUrl)}catch(P){return _(P instanceof Error?P.message:String(P)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=dn(o.gateway)}catch(O){return _(O.message),1}let g,y;m&&!o.revert&&M(`Gateway: ${w} ${S("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&ig(w)&&D(`${w} is plaintext http over a network \u2014 connections can be reset by firewalls/VPNs and traffic is unencrypted. Prefer an https:// gateway URL (front it with the TLS edge).`);let b=process.env.ANYRAY_CLIENT_KEY?.trim(),A=b||pJ(s),v,E,I,C,x,T,$=s.credentialProtocol==="stable-heartbeat-v1",Y=async O=>{await vo();let P=Qv(O.token),H=tS(s.enrolledCert,s.enrolledCertExpiry,O.deploymentId,Date.now(),P,s.enrolledTokenHash,O.expectedUser),fe=H?await We():void 0,q=H&&fe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:fe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,Ye=Be=>nS({cpOrigin:O.cpOrigin,token:O.token,gatewayOrigin:w,email:O.email,team:O.team,machineId:O.machineId,deploymentId:O.deploymentId,reuse:Be?q:void 0}),Ue=!!q,ee=await(async()=>{try{return await Ye(Ue)}catch(Be){if(q&&Be instanceof Rt)return M("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),Ue=!1,await Ye(!1);throw Be}})();A=ee.clientKey,o.user=bu(o.user,ee.user),o.team=bu(o.team,ee.team),v=ee.cert,E=ee.cert.payload.expiresAt,T=ee.expiresAt,$=ee.capabilities?.includes(Ai)===!0,x=void 0,Ue||(I=ee.privateKeyPem),Ue||(C=P),F(`Enrolled${ee.user?` as ${ee.user}`:""}${Ue?" (reused your saved cert)":""} \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)};if(o.enroll&&!o.revert)if(o.dryRun)M("dry run: not enrolled (skipped minting a personal key).");else{let O=nu(o.enroll);if(!O){let P=XI(o.enroll);return _(P?`that is ${P.what}, not an enrollment link \u2014 re-run with ${P.flag} instead of --enroll.`:Ot(o.enroll)?"that is an SSO link, not an enrollment link \u2014 re-run with --sso instead of --enroll.":"invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1}try{let P=o.machine?wu():void 0,H=u??lJ(o.user);if(!o.machine&&!o.user&&!u){let q=qE();q.distinct||(D(` Enrolling as "${q.identity}" \u2014 this may not be unique to you.`),D(q.reason==="machine_default"?" That looks like a machine or container default, so every developer on":" No personal git email is set, so machines sharing this image can"),D(q.reason==="machine_default"?" this image would enroll as the same person and their spend would merge.":" enroll under the same name and their spend would merge."),D(" Re-run with `--user you@company.com` (or set `git config --global"),D(" user.email`) so your usage is attributed to you."))}let fe=o.machine?`machine:${P}`:f?H:void 0;await Y({cpOrigin:O.cpOrigin,token:O.token,email:H,team:o.team,machineId:P,deploymentId:d,expectedUser:fe})}catch(P){return _(P instanceof Error?P.message:String(P)),P instanceof Rt&&M("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),1}}if(p){await vo();try{let O=await ln(w,p.cert,p.privateKeyPem);A=O.key,o.user=bu(o.user,O.user),o.team=bu(o.team,O.team),v=p.cert,E=p.cert.payload.expiresAt,I=p.privateKeyPem,T=O.expiresAt,$=O.capabilities?.includes(Ai)===!0;let P=o.sso?Ot(o.sso):void 0;x=P?`${P.cpOrigin}/sso/${P.tenantId}`:h,F(`Enrolled${O.user?` as ${O.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(O){return _(O instanceof Error?O.message:String(O)),O instanceof Rt&&M("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}if(!o.revert){let O=o.yes;g=await eI(o.user,s.name,O),y=await tI(o.team,s.team,O)}if(!o.revert&&!o.dryRun){let O=ux(await dx(w,A),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(O.lane){let P=O.lane==="subscription";o.subscription=P,o.placeholder=!P;let H=P?"your own subscription seat":"the organization's provider account";O.overrodeFlag?M(`Your administrator assigns this machine to ${H}, so that is what was applied (it overrides the lane flag you passed).`):M(`Billing lane set by your administrator: ${H}.`)}}let Z;!o.revert&&!o.subscription&&!o.placeholder&&(Z=await $t(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?tt("BYO upstream key (passthrough)"):Z.anthropic?tt("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${Z.openai?tt("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),!Z.anthropic&&!Z.openai&&!Z.copilot&&jr()&&(D(" No subscription sign-ins found on this host. Sign-ins do not cross the"),D(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),D(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),D(" and re-run, or everything below routes on the org key instead.")));let W=ge({origin:w,placeholderKey:o.key,clientKey:A,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:Z,user:g,team:y,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),z=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:z};if(!o.revert&&W.clientKey&&!xe(W.clientKey))return _("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!W.clientKey){K("Enrollment required");let O="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(D(` ${O}`),M(" Dry run only \u2014 no placeholder configuration will be written."),await uR(l,"after-enrollment"),M(`
1029
- Dry run complete \u2014 no files were written.`),0):(_(` ${O}`),1)}o.revert||uJ(W,l),c&&!o.revert&&await uR(l,"plan"),o.dryRun&&M(`
1030
- Dry run \u2014 no files will be written.`);let Le=await MJ(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(Le==="non-interactive")return _(`
1031
- Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(Le==="declined")return M(c?"Nothing was written. Re-run `npx anyray-connect wizard` when you're ready.":"Aborted. Nothing changed."),0;if(!o.dryRun&&!o.revert&&!o.force){let O=await tu(W.origin);if(!O.reachable)return _(`
1032
- Gateway ${W.origin} is not reachable (${O.detail}).`),k(S(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
1026
+ per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,x5=e=>{let t=e?.trim();return t||Hm()},Au=(e,t)=>t||e,CO=e=>{let t={subscription:!1,placeholder:!1,dryRun:!1,yes:!1,revert:!1,force:!1,skipVerify:!1,verbose:!1,help:!1,helpAll:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>e[++n];switch(r){case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":t.key=o();break;case"--enroll":t.enroll=o();break;case"--sso":t.sso=o();break;case"--claim":t.claim=o();break;case"--machine":t.machine=!0;break;case"--subscription":t.subscription=!0;break;case"--placeholder":case"--org":t.placeholder=!0;break;case"--upstream":t.upstream=o();break;case"--upstream-key":t.upstreamKey=o();break;case"--tools":t.tools=(o()??"").split(",").map(a=>a.trim()).filter(Boolean);break;case"--project":t.project=!0;break;case"--dry-run":t.dryRun=!0;break;case"--yes":case"-y":t.yes=!0;break;case"--force":t.force=!0;break;case"--skip-verify":t.skipVerify=!0;break;case"--fallback":case"--no-fallback":t.retiredFallbackFlag=!0;break;case"--no-key-refresh":t.noKeyRefresh=!0;break;case"--quit-apps":t.quitApps=!0;break;case"--no-quit-apps":t.noQuitApps=!0;break;case"--endpoint":t.endpoint=!0;break;case"--no-endpoint":t.noEndpoint=!0;break;case"--revert":t.revert=!0;break;case"--json":t.json=!0;break;case"--verify":t.verify=!0;break;case"--no-verify":t.noVerify=!0;break;case"--quick":t.quick=!0;break;case"--repair":t.repair=!0;break;case"--security-review":t.securityReview=!0;break;case"--verbose":t.verbose=!0;break;case"--help":case"-h":t.help=!0;break;case"--help-all":t.help=!0,t.helpAll=!0;break;case"--all":if(!e.includes("--help")&&!e.includes("-h"))throw new Error(`unknown option: ${r}`);t.helpAll=!0;break;default:if(!r.startsWith("-")&&t.gateway===void 0)t.gateway=r;else throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r} (gateway already set to ${t.gateway})`)}}return t},I5=e=>!e||e.length===0?ie:e.map(t=>{let n=Ht(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${ie.map(r=>r.id).join(", ")}`);return n}),O5=(e,t)=>{if(K("Gateway target"),k(` Origin: ${nt(e.origin)}`),e.byoUpstream)k(` Auth: BYO upstream key ${S(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&k(` Client key: personal gateway key (${$t(e.clientKey)}) ${S("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=J(e,"anthropic")?nt("your subscription"):"org key",r=J(e,"openai")?nt("your subscription"):"org key";k(` Auth: auto ${S("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&k(` Client key: personal gateway key (${$t(e.clientKey)})`)}else e.authMode==="subscription"?(k(` Auth: subscription pass-through ${S("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&k(` Client key: personal gateway key (${$t(e.clientKey)}) ${S("rides x-anyray-api-key")}`)):e.clientKey?k(` Auth: personal gateway key (${$t(e.clientKey)}) ${S("(replaces the placeholder)")}`):k(` Enrollment: ${S("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&k(` Cursor: ${nt("native Team subscription")} ${S("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(J(e,"anthropic")?(k(` Claude Desktop: ${nt("subscription-backed Gateway lane")} ${S("(verified macOS builds; Windows fails closed)")}`),k(` ${S("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(k(` Claude Desktop: ${nt("third-party API lane")} ${S("(API-billed; switches the active local inference profile)")}`),k(` ${S("The first-party Claude subscription remains untouched.")}`))),k(` Attribution: ${de(e.metadata)??S("(none \u2014 pass --user)")}`)},yO=async(e,t)=>{K("Selected tools");for(let n of e){let r=await n.detect();r.installed?k(` ${n.title} ${S(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):M(` ${n.title} ${S(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},R5=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!xe(n))return;let r=e.clientKeyExpiresAt?.trim();if(!r)return n;let o=Date.parse(r);return Number.isFinite(o)&&o>t?n:void 0},_5={loadDevKey:We,saveDevKey:pc,clearDevKey:as,saveProfile:re},P5=async(e,t,n,r=_5,o=!1)=>{let a=!!n||o,s=a?await r.loadDevKey():void 0,i=!1,c=!1;try{a&&(i=!0,n?await r.saveDevKey(n):await r.clearDevKey()),c=!0,await r.saveProfile(t)}catch(l){throw i&&(s!==void 0?await r.saveDevKey(s).catch(()=>{}):await r.clearDevKey().catch(()=>{})),c&&await r.saveProfile(e).catch(()=>{}),l}},T5=async(e,t,n,r,o)=>{n.dryRun||await hc();let a=0,s=[],i=[],c=[],l=[],d=[];for(let u of e){if(!(await u.detect()).installed&&!r){d.push(u.title);continue}K(`${u.title} ${S(`(${u.id})`)}`);try{let p=r?await u.revert(n):await u.apply(t,{...n,explicit:o?.has(u.id)===!0,reportsToUser:!0});for(let h of p.messages)k(` ${h}`);a+=p.changedFiles?.length??0,l.push({id:u.id,status:p.status}),p.status==="configured"||p.status==="reverted"?F(` ${p.status}`):p.status==="manual"?(s.push(u.title),p.manualAudience==="admin"?(i.push(u.title),c.push(u.id),L(" blocked by machine policy \u2014 your IT team owns this one")):L(" manual step required (see above)")):p.status==="held"?M(" left on its own plan (no change)"):M(` ${p.status}`)}catch(p){l.push({id:u.id,status:"failed"}),_(` failed: ${p instanceof Error?p.message:String(p)}`)}}if(d.length>0&&M(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await wc().catch(()=>[]);u.length&&M(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},L5=(e,t=[],n)=>{if(e.length===0)return[];if(t.length===e.length)return[`${e.length===1?`${e[0]} is`:`${e.join(", ")} are`} controlled by a machine policy your organization manages, so local setup cannot change it.`,...n==="darwin"?["Admin next step: on an unmanaged admin Mac, open Claude Desktop \u2192 Developer \u2192 Configure Third-Party Inference, complete and test the Anyray connection, connectors, and plugin marketplaces, then Export \u2192 .mobileconfig and deploy that complete profile through MDM.","The configuration window is read-only on managed endpoints; Connect will not create an incomplete replacement profile or supplement the managed source locally."]:n?["Your administrator must create and test the complete Claude Desktop third-party policy through Anthropic's enterprise configuration flow, then deploy it through your organization's device-management system.","Connect will not create an incomplete replacement policy or supplement the managed source locally."]:["Your Anyray administrator can see this state in the console's Connect coverage view."],"Everything else on this machine is configured and routing normally."];let o=[`${e.length===1?`${e[0]} needs`:`${e.length} tools need`} a remaining app action \u2014 Connect may already have written its automatic config.`,`Review and complete the steps shown above for: ${e.join(", ")}.`,"Then restart or reload the app as instructed; use `npx anyray-connect status` for the available route checks."];return t.length>0&&o.push(`Not yours to fix: ${t.join(", ")} \u2014 a machine policy your organization manages. Flagged for your Anyray administrator.`),o},D5=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>AO(o)&&!r.has(o.id))},N5=async e=>{let t=Ix(e,process.platform,Q());if(t){await pe(t.path,t.content);for(let n of Ox(t,process.platform))k(` ${n}`)}},$5=async(e,t,n=wO())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!Sb(i,n)||!vb(i,n))continue;let c=Cb(i,n);if(!o.has(c)){try{if(!(await a.detect()).installed||!s.isRunning()||await a.pointsAt?.(t)===!0)continue}catch{continue}o.add(c),r.push({id:a.id,title:Ab(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},M5=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,F5=e=>`
1027
+ ${e.length===1?`${e[0]} is open and won't pick this up until it restarts. Quit it now?`:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]} are open and won't pick this up until they restart. Quit them now?`}`,U5=async(e,t={})=>{let n=t.requestQuit??(a=>xb(a)),r=t.waitFor??(a=>Ib(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),F(` Closed ${a.title}.`);continue}L(` ${a.title} is still open \u2014 leaving it alone.`),M(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},B5=(e,t={})=>{let n=t.relaunch??(o=>Ob(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),F(` Reopened ${o.title}.`)):L(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},AO=e=>e.changesBilling===!0||e.changesOrgManagement===!0,vO=e=>e.changesBilling===!0?"moves inference spend from your subscription to the org API bill":e.changesOrgManagement===!0?"switches the app to third-party mode; claude.ai Enterprise org settings stop applying":void 0,ag=e=>!AO(e),W5=async(e,t,n={})=>{let r=n.hasEnrollment??Nu,o=n.canMultiSelect??eI,a=n.multiSelect??tI,s=n.prompt??Fa,i=n.registry??ie;if(k(j("Anyray connect \u2014 guided setup")),k(S("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())k("Stored enrollment will be reused. Run with --revert to clear it.");else if(!e.enroll&&!e.sso&&!e.gateway){K("How do you want to connect?");let c;for(let l=0;l<3&&!c;l++){if(o()){let d=await a({title:"Choose a connection method",single:!0,items:[{value:"enroll",label:"Paste an enrollment link",selected:!0},{value:"sso",label:"Sign in with SSO"},{value:"gateway",label:"I already have a gateway URL"}]});if(d.kind==="cancelled")throw new bt;c=d.values[0]}else{k(" 1. Paste an enrollment link"),k(" 2. Sign in with SSO"),k(" 3. I already have a gateway URL");let d=await s("? Connection method (1-3)","1");c=d==="1"?"enroll":d==="2"?"sso":d==="3"?"gateway":void 0}c||L("Choose one of the three connection methods.")}if(!c)throw new bt;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&Ki(d)&&ou(d)){e.enroll=d;break}L("That is not a valid enrollment link or token. Try again.")}else if(c==="sso"){let d=await s("? SSO link or tenant id");if(d&&Rt(d)){e.sso=d;break}L("That is not a valid SSO link or tenant id. Try again.")}else{let d=await s("? Gateway URL",t.gateway||process.env.ANYRAY_GATEWAY_URL);if(d&&Ki(d)){e.enroll=d,k("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=dn(d);break}catch{L("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new bt}if(!e.tools||e.tools.length===0){K("Tools detected");let c=[],l=[];for(let u of i){if(!(await u.detect()).installed){l.push(u);continue}c.push(u)}let d=c.filter(u=>ag(u)).map(u=>u.id);if(c.length>0){for(let u=0;u<3&&!e.tools;u++){let f;if(o()){let p=await a({title:"Tools to configure",items:c.map(h=>({value:h.id,label:`${h.title} (${h.id})`,hint:vO(h),selected:ag(h),requiresExplicitChoice:!ag(h)}))});if(p.kind==="cancelled")throw new bt;f=p.values}else{f=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(w=>w.trim()).filter(Boolean);let h=new Set(c.map(w=>w.id)),m=f.filter(w=>!h.has(w));if(m.length>0){L(`Unknown or unavailable tool id${m.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(f.length===0){L("Choose at least one installed tool.");continue}e.tools=f}if(!e.tools)throw new bt}l.length>0&&M(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},H5=async(e,t)=>{K("Verifying the connection");let n=await Gi("Checking the gateway\u2026",()=>Zi(e,{tools:t}));n.kind==="ok"?F(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?L(` ${n.detail}`):_(` ${n.detail}`);for(let r of n.remedy)k(S(` ${r}`))},K5=5e3,G5=500,gO=3,j5=600*1e3,V5=async()=>{try{let e=await E5(await No());return Date.now()-e.mtimeMs}catch{return Number.POSITIVE_INFINITY}},Y5=async(e={})=>{try{let t=await(e.load??D)();if(t.keyRefreshEnabled!==!0){if((e.draining??ip)()||!await(e.unitExists??ww)()||await(e.profileAgeMs??V5)()<j5)return;await(e.uninstall??Qt)(t.fallbackPort??ke);return}if(!t.gateway||t.persistenceOwner==="tray"&&await(e.checkTray??So)(t)==="healthy")return;let n=t.fallbackPort??ke,r=e.probe??be,o=e.probeGapMs??G5;for(let s=0;s<gO;s++){if(await r(n,s===0?void 0:K5)!==null)return;s<gO-1&&o>0&&await new Promise(c=>setTimeout(c,o))}if((e.draining??ip)())return;let a=await(e.install??Dt)({port:n,remoteOrigin:new URL(t.gateway).origin});if(!a.ok)for(let s of a.messages)console.error(s)}catch{}},Z5=async(e,t,n={})=>{let r=n.install??Dt,o=n.probe??be,a=n.pollDelayMs??300;K("Seamless key refresh");let s=n.trayManaged?{ok:!0,messages:["Launch-at-login is managed by the Anyray Connect app \u2014 not re-registering the login service."]}:await r({port:t,remoteOrigin:e.origin});for(let l of s.messages)k(` ${l}`);let i=s.ok?10:1,c=null;for(let l=0;l<i&&!c;l++)c=await o(t),!c&&l<i-1&&await new Promise(d=>setTimeout(d,a));return c?(F(` Running on 127.0.0.1:${t} \u2192 ${e.origin} \u2014 your key refreshes automatically, no restart needed.`),On(e,t)):(L(" Key-refresh proxy did not come up \u2014 pointing tools directly at the gateway for now."),k(S(s.ok?" It will retry on the next run; check the service logs if it persists.":Ct(yt())?" In a container the key refreshes via Claude Code's helper and on each `anyray-connect` run instead.":" Your key still refreshes on a schedule \u2014 no daemon needed here.")),e)},X5=async(e,t={})=>{if(e.dryRun)return;let n=t.install??pr,r=t.uninstall??fr;if(e.want&&e.trayManaged){e.announcePrimary&&(K("Automatic key refresh"),F(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."));return}if(e.want){let o=await n();if(e.announcePrimary){K("Automatic key refresh");for(let a of o.messages)k(` ${a}`);o.ok&&F(" Your gateway key now re-mints every ~30 min \u2014 no tool will 401 on a stale key mid-session.")}o.ok||await re({...await D(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){K("Automatic key refresh");let o=await r();for(let a of o.messages)k(` ${a}`);await re({...await D(),refreshSchedulerEnabled:!1}),F(" Removed the automatic key-refresh schedule.")}},J5=new Set(["login","wizard","status","doctor","sync","device-url"]),q5=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),z5=e=>{if(e.outcome==="migrated"&&e.managedPath)return{level:"info",message:`Installed managed anyray-connect at ${e.managedPath}.`};if(e.outcome==="platform-unsupported")return{level:"warn",message:"Self-update is unavailable on this platform; keeping the durable npm runtime for persistent integrations."};if(e.outcome==="migration-deferred")return{level:"warn",message:`Managed install deferred because the published binary (${e.latest}) is older than this npm runtime (${e.current}).`};if(!(e.outcome==="current"||e.outcome==="unmanaged"||e.outcome==="updated"||e.outcome==="disabled"||e.outcome==="container"))return{level:"warn",message:"Could not install the managed anyray-connect binary; continuing with the current runtime \u2014 it migrates automatically on a later refresh."}},Q5=e=>{if(e.includes("--help")||e.includes("--help-all")||e.includes("-h"))return!1;if(e[0]==="managed")return e.includes("--write")&&!e.includes("--revert");if(e[0]==="desktop"){let t=ey(e.slice(1));return!!(t&&!t.includes("--dry-run")&&!t.includes("--revert"))}return e.includes("--dry-run")||e.includes("--revert")||e.includes("--project")?!1:e[0]==="doctor"?e.includes("--repair"):e[0]==="models"?e.slice(1).some(t=>!t.startsWith("-")):!e[0]||!q5.has(e[0])},sg=async(e,t)=>{try{return await nX(e,t)}catch(n){if(n instanceof bt)return console.error(S("Cancelled \u2014 nothing was written.")),130;throw n}},eX=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??Vt)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
1028
+ ${o} ${n} tool target(s)?`;return await(r.confirm??Ma)(a)?"proceed":"declined"},tX=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return r0(n)}if(e[0]==="__anyray-codex-hook")return o0();if(e[0]==="__anyray-prompt-hook")return a0();if(e[0]==="__anyray-shell-pretool")return l0();if(e[0]==="__anyray-shell-run")return c0(e.slice(1));if(e[0]==="__anyray-read-pretool")return g0();if(e[0]==="__anyray-sso-gate")return rE(e.slice(1));if(e[0]==="__anyray-sso-poll")return w0();if(e[0]==="__anyray-vscode-gate")return S0();if(e[0]==="__anyray-spawn-refresh")return await Rr(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return P0(n)}if(e[0]==="__anyray-acp-agent")return T0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return iO(e.slice(1));if(e[0]==="__anyray-refresh"){await gy(),await tt({runAmbientSelfcheck:!0}),await Om(),await Y5(),await KS(),await GS();let n=await D().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await re(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await Ro().catch(()=>!1);if(await lO(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=dO(),i=n.enrolledCert;if(s&&i){let l=await We().catch(()=>{});l&&await tS(o,a,i,l,s).catch(()=>{})}await pO(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await tt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?mO(d):(await fO()).ok?"ok":"failed"}).catch(()=>{})}}return await Vi(),0}if(e[0]==="__anyray-fallback-proxy")return CE();if(e[0]==="__anyray-persistence")return vE(e.slice(1));if(e[0]==="__anyray-quit-watch")return RE(e.slice(1));if(e[0]===si)return ux(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return v0();try{let n=await Fg(e);if(n!==void 0)return n}catch(n){return _(`Could not persist anyray-connect for long-lived integrations: ${n instanceof Error?n.message:String(n)}`),1}if(Q5(e)){let n=z5(await cI());n?.level==="warn"?L(n.message):n&&console.error(n.message)}if(e[0]==="managed")return BE(e.slice(1));if(e[0]==="endpoint")return sO(e.slice(1));if(e[0]==="print-key")return GE(e.slice(1));if(e[0]==="models")return VE(e.slice(1));if(e[0]==="copilot-login")return YE(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=ey(n);return r?sg(r,!1):Rx(n)}if(e[0]==="retrieve")return Px(e.slice(1));if(e[0]==="recall")return Tx(e.slice(1));if(e[0]==="history")return Gx(e.slice(1));if(e[0]==="migrate")return Vx(e.slice(1));if(e[0]==="login")return k0(e.slice(1));if(e[0]==="update")return A0(e.slice(1));let t=e[0];if(t&&J5.has(t)){let n=e.slice(1),r;try{r=CO(n)}catch(o){return _(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?kO:bO),0):t==="status"?mI({gateway:r.gateway}):t==="doctor"?SI({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?EI({gateway:r.gateway}):t==="device-url"?ZE():sg(n,!0)}return sg(e,!1)},SO=async e=>{try{return await tX(e)}catch(t){if(t instanceof bt)return console.error(S("Cancelled.")),130;throw t}},nX=async(e,t,n={})=>{let r=n.isInteractive??Vt,o;try{o=CO(e)}catch(R){return _(R.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?kO:bO),0;if(o.revert&&(o.sso||o.enroll||o.claim))return _("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(_("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):cx({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return _("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return _("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let R;try{R=new URL(o.upstream.trim())}catch{return _(`invalid --upstream URL: "${o.upstream}"`),1}if(R.protocol!=="http:"&&R.protocol!=="https:")return _(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let T=o.upstreamKey.trim();if(!T)return _("--upstream-key must not be empty."),1;a={url:Xe(o.upstream),key:T}}let s=await D();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let R=await gy();(R==="migrated"||R==="already-direct")&&(s=await D())}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream),o.retiredFallbackFlag&&L("--fallback/--no-fallback are retired and ignored: the local daemon no longer routes around the gateway to the provider. Seamless key refresh is on by default (--no-key-refresh opts out).");let i=!t&&Vt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??W5)(o,s),c=!0);let l;try{l=I5(o.tools)}catch(R){return _(R.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&Ki(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,k("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,f=!1;if(o.enroll&&(!o.gateway||s.enrolledCert)){let R=ou(o.enroll);if(R)try{let T=await Gi("Resolving enrollment link\u2026",()=>zx(R)),H=!o.gateway;H&&(o.gateway=T.gatewayUrl),d=T.deploymentId,u=T.email,f=!0,H&&M(`Enrollment link${T.org?` for ${T.org}`:""}: gateway ${T.gatewayUrl}`),T.seatMode&&!o.subscription&&(o.subscription=!0,M("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(T){let H=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(H)M(`Could not resolve the gateway from the enrollment link \u2014 using ${H}.`);else return _(T instanceof Error?T.message:String(T)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)M("dry run: not enrolled (skipped redeeming the enrollment link).");else{let R=YS(o.claim);if(!R)return _("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let T=await Gi("Connecting this machine\u2026",()=>ZS({cpOrigin:R.cpOrigin,claim:R.claim,gatewayUrl:o.gateway}));p={cert:T.cert,privateKeyPem:T.privateKeyPem},T.deploymentId&&(d=T.deploymentId),!o.gateway&&T.gatewayUrl&&(o.gateway=T.gatewayUrl),h=T.ssoLink}catch(T){return _(T instanceof Error?T.message:String(T)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)M("dry run: not enrolled via SSO (skipped minting a personal key).");else{let R=Rt(o.sso);if(!R)return _(Ki(o.sso)?"that is an enrollment link, not an SSO link \u2014 re-run with --enroll instead of --sso.":"invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let T=await Ud({cpOrigin:R.cpOrigin,tenantId:R.tenantId,gatewayUrl:o.gateway,log:fe=>M(fe),open:r()?Pa:void 0}),H=await Gi("Waiting for SSO sign-in\u2026",()=>Bd(T,{gatewayUrl:o.gateway}));p={cert:H.cert,privateKeyPem:H.privateKeyPem},H.deploymentId&&(d=H.deploymentId),!o.gateway&&H.gatewayUrl&&(o.gateway=H.gatewayUrl)}catch(T){return _(T instanceof Error?T.message:String(T)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=dn(o.gateway)}catch(R){return _(R.message),1}let g,y;m&&!o.revert&&M(`Gateway: ${w} ${S("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&lg(w)&&L(`${w} is plaintext http over a network \u2014 connections can be reset by firewalls/VPNs and traffic is unencrypted. Prefer an https:// gateway URL (front it with the TLS edge).`);let b=process.env.ANYRAY_CLIENT_KEY?.trim(),A=b||R5(s),v,E,x,C,I,P,$=s.credentialProtocol==="stable-heartbeat-v1",Y=async R=>{await Ao();let T=eS(R.token),H=nS(s.enrolledCert,s.enrolledCertExpiry,R.deploymentId,Date.now(),T,s.enrolledTokenHash,R.expectedUser),fe=H?await We():void 0,z=H&&fe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:fe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,Ze=Be=>rS({cpOrigin:R.cpOrigin,token:R.token,gatewayOrigin:w,email:R.email,team:R.team,machineId:R.machineId,deploymentId:R.deploymentId,reuse:Be?z:void 0}),Ue=!!z,ee=await(async()=>{try{return await Ze(Ue)}catch(Be){if(z&&Be instanceof Ot)return M("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),Ue=!1,await Ze(!1);throw Be}})();A=ee.clientKey,o.user=Au(o.user,ee.user),o.team=Au(o.team,ee.team),v=ee.cert,E=ee.cert.payload.expiresAt,P=ee.expiresAt,$=ee.capabilities?.includes(Si)===!0,I=void 0,Ue||(x=ee.privateKeyPem),Ue||(C=T),F(`Enrolled${ee.user?` as ${ee.user}`:""}${Ue?" (reused your saved cert)":""} \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)};if(o.enroll&&!o.revert)if(o.dryRun)M("dry run: not enrolled (skipped minting a personal key).");else{let R=ou(o.enroll);if(!R){let T=qx(o.enroll);return _(T?`that is ${T.what}, not an enrollment link \u2014 re-run with ${T.flag} instead of --enroll.`:Rt(o.enroll)?"that is an SSO link, not an enrollment link \u2014 re-run with --sso instead of --enroll.":"invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1}try{let T=o.machine?Cu():void 0,H=u??x5(o.user);if(!o.machine&&!o.user&&!u){let z=QE();z.distinct||(L(` Enrolling as "${z.identity}" \u2014 this may not be unique to you.`),L(z.reason==="machine_default"?" That looks like a machine or container default, so every developer on":" No personal git email is set, so machines sharing this image can"),L(z.reason==="machine_default"?" this image would enroll as the same person and their spend would merge.":" enroll under the same name and their spend would merge."),L(" Re-run with `--user you@company.com` (or set `git config --global"),L(" user.email`) so your usage is attributed to you."))}let fe=o.machine?`machine:${T}`:f?H:void 0;await Y({cpOrigin:R.cpOrigin,token:R.token,email:H,team:o.team,machineId:T,deploymentId:d,expectedUser:fe})}catch(T){return _(T instanceof Error?T.message:String(T)),T instanceof Ot&&M("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),1}}if(p){await Ao();try{let R=await ln(w,p.cert,p.privateKeyPem);A=R.key,o.user=Au(o.user,R.user),o.team=Au(o.team,R.team),v=p.cert,E=p.cert.payload.expiresAt,x=p.privateKeyPem,P=R.expiresAt,$=R.capabilities?.includes(Si)===!0;let T=o.sso?Rt(o.sso):void 0;I=T?`${T.cpOrigin}/sso/${T.tenantId}`:h,F(`Enrolled${R.user?` as ${R.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(R){return _(R instanceof Error?R.message:String(R)),R instanceof Ot&&M("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}if(!o.revert){let R=o.yes;g=await tx(o.user,s.name,R),y=await nx(o.team,s.team,R)}if(!o.revert&&!o.dryRun){let R=pI(await uI(w,A),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(R.lane){let T=R.lane==="subscription";o.subscription=T,o.placeholder=!T;let H=T?"your own subscription seat":"the organization's provider account";R.overrodeFlag?M(`Your administrator assigns this machine to ${H}, so that is what was applied (it overrides the lane flag you passed).`):M(`Billing lane set by your administrator: ${H}.`)}}let Z;!o.revert&&!o.subscription&&!o.placeholder&&(Z=await Nt(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?nt("BYO upstream key (passthrough)"):Z.anthropic?nt("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${Z.openai?nt("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),!Z.anthropic&&!Z.openai&&!Z.copilot&&Gr()&&(L(" No subscription sign-ins found on this host. Sign-ins do not cross the"),L(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),L(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),L(" and re-run, or everything below routes on the org key instead.")));let W=ge({origin:w,placeholderKey:o.key,clientKey:A,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:Z,user:g,team:y,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),q=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:q};if(!o.revert&&W.clientKey&&!xe(W.clientKey))return _("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!W.clientKey){K("Enrollment required");let R="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(L(` ${R}`),M(" Dry run only \u2014 no placeholder configuration will be written."),await yO(l,"after-enrollment"),M(`
1029
+ Dry run complete \u2014 no files were written.`),0):(_(` ${R}`),1)}o.revert||O5(W,l),c&&!o.revert&&await yO(l,"plan"),o.dryRun&&M(`
1030
+ Dry run \u2014 no files will be written.`);let Te=await eX(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(Te==="non-interactive")return _(`
1031
+ Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(Te==="declined")return M(c?"Nothing was written. Re-run `npx anyray-connect wizard` when you're ready.":"Aborted. Nothing changed."),0;if(!o.dryRun&&!o.revert&&!o.force){let R=await ru(W.origin);if(!R.reachable)return _(`
1032
+ Gateway ${W.origin} is not reachable (${R.detail}).`),k(S(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
1033
1033
  that would break them until you re-run with --revert.`)),k(`
1034
- Start the gateway and try again, or pass --force to configure anyway.`),1;F(`Gateway reachable (${O.detail}).`)}let ne=o.revert?[]:await bJ(l,W.origin),Ke=[],De=()=>{Ke.length!==0&&(K("Reopening"),vJ(Ke),Ke=[])};if(ne.length>0){let O=ne.map(H=>H.title),P=O.length===1?"it":"them";if(K("Open apps"),kJ(o,Yt()))o.quitApps===!0||await $a(CJ(O))?Ke=await AJ(ne):M(` Leaving ${P} open \u2014 restart when convenient.`);else{let H=o.noQuitApps===!0?"":" (or pass --quit-apps)";M(o.dryRun?` Would offer to quit ${O.join(", ")} \u2014 dry run, nothing was closed.`:` ${O.join(", ")} ${O.length===1?"is":"are"} open; restart ${P} to pick this up${H}.`)}}try{if(!o.dryRun)try{await kt()}catch{return _("Could not prepare the owner-only Anyray state directory."),1}let O=l.some(ye=>ye.id==="claude-code")&&X(W,"anthropic")||l.some(ye=>ye.id==="codex")&&X(W,"openai"),P=Dd(s,T),H=s.anyrayFleetManaged===!0&&await _o().catch(()=>!1),fe=Z0(o,fR(),H),q=!o.revert&&o.noKeyRefresh!==!0&&O&&P&&!$&&!fe,Ue=!o.revert&&(o.tools?.length??0)>0&&o.noKeyRefresh!==!0&&!!s.keyRefreshEnabled,ee=!!(b&&W.clientKey===b&&!v),Be=!ee&&!!(v??s.enrolledCert),Ne=l.some(ye=>US.has(ye.id)),V=!o.revert&&o.noKeyRefresh!==!0&&Be&&(P||!Ne),Ee=o.dryRun?await Eo(s):await Im(),bt=Ee==="healthy";Ee==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath);let qn=W,Tt=q||Ue,$r=Tt?s.fallbackPort:void 0;if(q&&!o.dryRun&&($r=s.fallbackPort??await Oc()),!o.revert&&!o.dryRun){let ye={...s,gateway:W.origin,name:g,team:y,clientKey:W.clientKey??s.clientKey,enrolledCert:ee?void 0:v??s.enrolledCert,enrolledCertExpiry:ee?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:ee?void 0:C??s.enrolledTokenHash,ssoLink:ee?void 0:p?x:v?void 0:s.ssoLink,clientKeyExpiresAt:ee?void 0:T??(W.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:W.authMode,byoUpstream:W.byoUpstream,credentialProtocol:ee?void 0:Tt?"rotating-proxy-v1":$?"stable-heartbeat-v1":s.credentialProtocol,directMigration:ee?void 0:Tt?"pending":$?"complete":s.directMigration,keyRefreshEnabled:Tt,refreshSchedulerEnabled:V,fallbackPort:$r};try{await hJ(s,ye,I,void 0,ee)}catch{return _("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}T&&!ee&&await Oa({expiresAt:T})}if(q&&!o.dryRun&&(qn=await TJ(W,$r,{trayManaged:bt})),z)if(o.dryRun)await Lu()&&(K("Enrollment"),k(" would remove the stored gateway credential"));else{await ng(s),await Bd().catch(()=>{});try{await uc()&&(K("Enrollment"),F(" Removed the stored gateway credential."),M(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(ye){K("Enrollment"),D(" Could not remove the stored gateway credential."),D(` Delete ${Q()} by hand, or the key-refresh hook may restore your tool config.`)}}else o.revert&&!o.dryRun&&(k(`
1035
- Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let Mr=l,Za=gJ(Mr,o,s.managedTools);if(Za.length>0){K("Not configured \u2014 needs your say-so");for(let Ie of Za)D(` ${Ie.id}: ${wR(Ie)??"changes where inference is billed"}.`),k(` Configure it deliberately with \`npx anyray-connect --tools ${Ie.id}\`.`);let ye=new Set(Za.map(Ie=>Ie.id));Mr=Mr.filter(Ie=>!ye.has(Ie.id))}if(o.revert&&!z){let ye=l.filter(Ie=>Ci(s,Ie.id));if(ye.length>0){K("Fleet policy");for(let Ie of ye)D(` ${Ie.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);Mr=l.filter(Ie=>!Ci(s,Ie.id))}}let{changes:oc,manual:Po,manualAdminOnly:Ja,manualAdminOnlyIds:Xa,results:za}=await mJ(Mr,qn,me,o.revert,new Set(o.tools??[])),qa;if(Jy(o)){K("Endpoint agent");try{qa=await(n.installEndpointAfterEnrollment??rR)({gateway:w,clientKey:W.clientKey})}catch{M("Endpoint agent setup did not complete. Tool routing remains configured.")}}let ku=fe&&Y0(qa),ag=V&&!ku;if(fe&&!ku&&V&&!o.dryRun&&M(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),ku&&!o.dryRun&&await re({...await L(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await Qn(za,o.revert,z).catch(()=>{}),z&&await fc().catch(()=>{})),!Tt&&!o.dryRun&&(nt(s)||s.fallbackPort||await Pi("daemon"))){K("Local loopback proxy");let ye=await Qt(s.fallbackPort);for(let Ie of ye.messages)k(` ${Ie}`);await re({...await L(),keyRefreshEnabled:!1,fallbackPort:void 0}),F(" Removed the local loopback proxy.")}if(await PJ({want:ag,announcePrimary:!q,scopedRevert:!!o.revert&&!z,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!ag&&await Pi("scheduler"),trayManaged:bt}),!o.revert&&!o.dryRun&&!ee){let ye=I??await We();ye&&await ym(await L(),ye).catch(()=>{})}if(De(),K("Summary"),o.dryRun)M("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){F(`Reverted (${oc} file(s) touched).`),M("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let ye=await sI();ye.length>0&&(K("This repo carries its own Anyray routing"),D(` Committed here: ${ye.join(", ")}`),D(" Those are tracked files, so they route every checkout of this"),D(" repo \u2014 this machine included, and your teammates' too. This"),D(" revert only removed THIS machine's own configuration."),k(`
1036
- Remove them from the repo (then commit):`),k(S(" anyray-connect --project --revert")));let Ie=[W,...s.fallbackPort?[In(W,s.fallbackPort)]:[]],ac=Pp(Ie);ac.length>0&&(K("This terminal still points at the gateway"),D(` Still exported here: ${ac.join(", ")}`),D(" Removing the block from your shell profile cannot reach a shell"),D(" that already ran it. Until these are gone, your tools keep"),D(" reaching the gateway and now fail with 401."),k(`
1037
- Fix this terminal:`),k(S(` unset ${ac.join(" ")}`)),k(`
1038
- Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(F(`Done (${oc} file(s) written).`),Po.length>0){let Pt=Ja.length===Po.length;K(Pt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let sg of yJ(Po,Ja,Xa.includes("claude-desktop")?process.platform:void 0))D(sg);if(Xa.includes("claude-desktop")&&!o.dryRun)try{await wJ(W)}catch{D(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}Yt()&&!o.yes&&!Pt&&(await $a("Have you applied the manual settings shown above?")?F("Acknowledged."):D("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?M(`
1039
- Skipped the connection smoke test (--skip-verify).`):await EJ(W,l.map(Pt=>Pt.id)),K("What's next");let ye=new Set(za.filter(Pt=>Pt.status==="configured").map(Pt=>Pt.id)),Ie=l.filter(Pt=>ye.has(Pt.id)).map(Pt=>Pt.title);if(k(Ie.length>0?` Connected: ${Ie.join(", ")}`:" Connected: no tools completed automatic configuration."),k(" Restart any editor that was already running \u2014 it loaded our config at startup."),k(" If something looks wrong: npx anyray-connect doctor"),!o.verbose)return 0;k(`
1034
+ Start the gateway and try again, or pass --force to configure anyway.`),1;F(`Gateway reachable (${R.detail}).`)}let ne=o.revert?[]:await $5(l,W.origin),Ke=[],Le=()=>{Ke.length!==0&&(K("Reopening"),B5(Ke),Ke=[])};if(ne.length>0){let R=ne.map(H=>H.title),T=R.length===1?"it":"them";if(K("Open apps"),M5(o,Vt()))o.quitApps===!0||await Ma(F5(R))?Ke=await U5(ne):M(` Leaving ${T} open \u2014 restart when convenient.`);else{let H=o.noQuitApps===!0?"":" (or pass --quit-apps)";M(o.dryRun?` Would offer to quit ${R.join(", ")} \u2014 dry run, nothing was closed.`:` ${R.join(", ")} ${R.length===1?"is":"are"} open; restart ${T} to pick this up${H}.`)}}try{if(!o.dryRun)try{await kt()}catch{return _("Could not prepare the owner-only Anyray state directory."),1}let R=l.some(ye=>ye.id==="claude-code")&&J(W,"anthropic")||l.some(ye=>ye.id==="codex")&&J(W,"openai"),T=$d(s,P),H=s.anyrayFleetManaged===!0&&await Ro().catch(()=>!1),fe=Q0(o,wO(),H),z=!o.revert&&o.noKeyRefresh!==!0&&R&&T&&!$&&!fe,Ue=!o.revert&&(o.tools?.length??0)>0&&o.noKeyRefresh!==!0&&!!s.keyRefreshEnabled,ee=!!(b&&W.clientKey===b&&!v),Be=!ee&&!!(v??s.enrolledCert),De=l.some(ye=>BS.has(ye.id)),Xt=!o.revert&&o.noKeyRefresh!==!0&&Be&&(T||!De),V=o.dryRun?await So(s):await Om(),Ne=V==="healthy";V==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath);let er=W,ft=z||Ue,Po=ft?s.fallbackPort:void 0;if(z&&!o.dryRun&&(Po=s.fallbackPort??await Pc()),!o.revert&&!o.dryRun){let ye={...s,gateway:W.origin,name:g,team:y,clientKey:W.clientKey??s.clientKey,enrolledCert:ee?void 0:v??s.enrolledCert,enrolledCertExpiry:ee?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:ee?void 0:C??s.enrolledTokenHash,ssoLink:ee?void 0:p?I:v?void 0:s.ssoLink,clientKeyExpiresAt:ee?void 0:P??(W.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:W.authMode,byoUpstream:W.byoUpstream,credentialProtocol:ee?void 0:ft?"rotating-proxy-v1":$?"stable-heartbeat-v1":s.credentialProtocol,directMigration:ee?void 0:ft?"pending":$?"complete":s.directMigration,keyRefreshEnabled:ft,refreshSchedulerEnabled:Xt,fallbackPort:Po};try{await P5(s,ye,x,void 0,ee)}catch{return _("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}P&&!ee&&await _a({expiresAt:P})}if(z&&!o.dryRun&&(er=await Z5(W,Po,{trayManaged:Ne})),q)if(o.dryRun)await Nu()&&(K("Enrollment"),k(" would remove the stored gateway credential"));else{await og(s),await Hd().catch(()=>{});try{await fc()&&(K("Enrollment"),F(" Removed the stored gateway credential."),M(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(ye){K("Enrollment"),L(" Could not remove the stored gateway credential."),L(` Delete ${Q()} by hand, or the key-refresh hook may restore your tool config.`)}}else o.revert&&!o.dryRun&&(k(`
1035
+ Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let In=l,Xa=D5(In,o,s.managedTools);if(Xa.length>0){K("Not configured \u2014 needs your say-so");for(let Ee of Xa)L(` ${Ee.id}: ${vO(Ee)??"changes where inference is billed"}.`),k(` Configure it deliberately with \`npx anyray-connect --tools ${Ee.id}\`.`);let ye=new Set(Xa.map(Ee=>Ee.id));In=In.filter(Ee=>!ye.has(Ee.id))}if(o.revert&&!q){let ye=l.filter(Ee=>vi(s,Ee.id));if(ye.length>0){K("Fleet policy");for(let Ee of ye)L(` ${Ee.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);In=l.filter(Ee=>!vi(s,Ee.id))}}let{changes:sc,manual:Ja,manualAdminOnly:qa,manualAdminOnlyIds:za,results:Qa}=await T5(In,er,me,o.revert,new Set(o.tools??[])),es;if(qy(o)){K("Endpoint agent");try{es=await(n.installEndpointAfterEnrollment??cO)({gateway:w,clientKey:W.clientKey})}catch{M("Endpoint agent setup did not complete. Tool routing remains configured.")}}let To=fe&&z0(es),ig=Xt&&!To;if(fe&&!To&&Xt&&!o.dryRun&&M(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),To&&!o.dryRun&&await re({...await D(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await tr(Qa,o.revert,q).catch(()=>{}),q&&await mc().catch(()=>{})),!ft&&!o.dryRun&&(rt(s)||s.fallbackPort||await Di("daemon"))){K("Local loopback proxy");let ye=await Qt(s.fallbackPort);for(let Ee of ye.messages)k(` ${Ee}`);await re({...await D(),keyRefreshEnabled:!1,fallbackPort:void 0}),F(" Removed the local loopback proxy.")}if(await X5({want:ig,announcePrimary:!z,scopedRevert:!!o.revert&&!q,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!ig&&await Di("scheduler"),trayManaged:Ne}),!o.revert&&!o.dryRun&&!ee){let ye=x??await We();ye&&await wm(await D(),ye).catch(()=>{})}if(Le(),K("Summary"),o.dryRun)M("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){F(`Reverted (${sc} file(s) touched).`),M("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let ye=await ix();ye.length>0&&(K("This repo carries its own Anyray routing"),L(` Committed here: ${ye.join(", ")}`),L(" Those are tracked files, so they route every checkout of this"),L(" repo \u2014 this machine included, and your teammates' too. This"),L(" revert only removed THIS machine's own configuration."),k(`
1036
+ Remove them from the repo (then commit):`),k(S(" anyray-connect --project --revert")));let Ee=[W,...s.fallbackPort?[On(W,s.fallbackPort)]:[]],ic=Dp(Ee);ic.length>0&&(K("This terminal still points at the gateway"),L(` Still exported here: ${ic.join(", ")}`),L(" Removing the block from your shell profile cannot reach a shell"),L(" that already ran it. Until these are gone, your tools keep"),L(" reaching the gateway and now fail with 401."),k(`
1037
+ Fix this terminal:`),k(S(` unset ${ic.join(" ")}`)),k(`
1038
+ Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(F(`Done (${sc} file(s) written).`),Ja.length>0){let Pt=qa.length===Ja.length;K(Pt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let cg of L5(Ja,qa,za.includes("claude-desktop")?process.platform:void 0))L(cg);if(za.includes("claude-desktop")&&!o.dryRun)try{await N5(W)}catch{L(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}Vt()&&!o.yes&&!Pt&&(await Ma("Have you applied the manual settings shown above?")?F("Acknowledged."):L("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?M(`
1039
+ Skipped the connection smoke test (--skip-verify).`):await H5(W,l.map(Pt=>Pt.id)),K("What's next");let ye=new Set(Qa.filter(Pt=>Pt.status==="configured").map(Pt=>Pt.id)),Ee=l.filter(Pt=>ye.has(Pt.id)).map(Pt=>Pt.title);if(k(Ee.length>0?` Connected: ${Ee.join(", ")}`:" Connected: no tools completed automatic configuration."),k(" Restart any editor that was already running \u2014 it loaded our config at startup."),k(" If something looks wrong: npx anyray-connect doctor"),!o.verbose)return 0;k(`
1040
1040
  Re-test by hand any time:`),W.authMode!=="placeholder"&&l.length===1&&l[0]?.id==="cursor"?(k(S(` curl -sS ${W.origin}/connect/savings \\
1041
1041
  -H "x-anyray-api-key: $(anyray-connect print-key)"`)),k(S(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):k(S(` curl -sS ${W.openaiBaseUrl}/chat/completions \\
1042
1042
  -H "Content-Type: application/json" \\
1043
- -H "Authorization: Bearer ${W.clientKey?`<your personal key (${Mt(W.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
1044
- -d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(S(" Revert: npx anyray-connect --revert"))}return 0}finally{De()}};bR(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
1043
+ -H "Authorization: Bearer ${W.clientKey?`<your personal key (${$t(W.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
1044
+ -d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(S(" Revert: npx anyray-connect --revert"))}return 0}finally{Le()}};SO(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});