anyray-connect 0.11.133 → 0.11.136

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 +216 -216
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- var OI="http://localhost:8787",Wa="anyray-placeholder",Ie=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Ye=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},uu=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,_I=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),By=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!_I.has(n)}catch{return!1}},ln=e=>{let t=Ye(e||process.env.ANYRAY_GATEWAY_URL||OI),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",vn=(e,t)=>{let n=`http://${ht}:${t}`;return{...e,anthropicBaseUrl:n,openaiBaseUrl:`${n}/v1`,viaLocalProxy:!0}},ge=(e={})=>{let t=ln(e.origin),n=e.placeholderKey?.trim()||Wa,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:uu(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:uu(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:uu(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 rs,platform as Do}from"node:os";import{join as No}from"node:path";import{mkdir as Hu,readFile as Kg,rename as ZR,stat as Gg,truncate as XR,writeFile as jg,rm as Lo}from"node:fs/promises";import{spawnSync as fn}from"node:child_process";import{createServer as JR}from"node:net";import{homedir as fc}from"node:os";import{join as hc}from"node:path";import{access as NI,chmod as $I,mkdir as pu,open as gu,readFile as Vy,rm as Yt,stat as Hy,utimes as MI}from"node:fs/promises";import{createHash as FI,randomUUID as Yy}from"node:crypto";import{dirname as wu,join as BI}from"node:path";import{isDeepStrictEqual as Eo}from"node:util";import{randomUUID as TI}from"node:crypto";import{lstat as PI,rename as Yi,rm as LI}from"node:fs/promises";import{platform as Uy}from"node:os";var DI=e=>e?.code==="ENOENT",Ka=async(e,t=Uy())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},fe=async(e,t,n=Uy())=>{if(n!=="win32"){await Yi(e,t);return}let r=`${t}.anyray-old-${process.pid}-${TI()}`,o=!1;try{let a=await PI(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await Yi(t,r),o=!0}catch(a){if(!DI(a))throw a}try{await Yi(e,t)}catch(a){if(o)try{await Yi(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await LI(r,{force:!0})};var Ga=e=>`${e}.anyray-bak`,Zy=async e=>{let t;try{t=await gu(wu(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},Wy=async(e,t)=>{let n,r;try{n=await gu(e,"wx",384),await n.writeFile(t,"utf-8"),await Ka(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Yt(e,{force:!0}).catch(()=>{}),r;await Zy(e)},UI=async e=>{let t;try{t=await gu(e,"r"),await Ka(t)}finally{await t?.close().catch(()=>{})}await Zy(e)},R=async e=>{try{return await NI(e),!0}catch{return!1}},M=async e=>{if(!await R(e))return{};let t=await Vy(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},Z=async(e,t,n={})=>{await pu(wu(e),{recursive:!0,mode:448});let r=Ga(e);if(n.backup!==!1&&await R(e)&&!await R(r))try{await Wy(r,await Vy(e,"utf-8"))}catch(a){if(a.code!=="EEXIST")throw a}let o=`${e}.anyray-tmp-${process.pid}-${Yy()}`;try{await Wy(o,`${JSON.stringify(t,null,2)}
3
- `),await fe(o,e),await $I(e,384),await UI(e)}finally{await Yt(o,{force:!0}).catch(()=>{})}},Xy=1,Ky=3e4,HI=5e3,WI=/^[a-f0-9]{64}$/,Jy=e=>`${e}.pending`,KI=e=>`${e}.lock`,fu=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=>fu(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${fu(t[n])}`).join(",")}}`},hu=(e,t)=>({exists:e,sha256:FI("sha256").update(fu(t)).digest("hex")}),mu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gy=e=>mu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&WI.test(e.sha256),GI=e=>mu(e)&&e.transactionVersion===Xy&&Gy(e.before)&&Gy(e.after)&&mu(e.journal),yu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,xo=async(e,t)=>{try{return await M(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},jI=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},zy=async e=>{let t=KI(e),n=BI(t,"owner.json");await pu(wu(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=Yy();try{await pu(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await xo(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 Hy(n)).mtimeMs;i=!jI(c.pid)||l>Ky}catch{try{i=Date.now()-(await Hy(t)).mtimeMs>Ky}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Yt(t,{recursive:!0,force:!0});continue}try{await Z(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Yt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await xo(n,"ownership journal")).nonce!==o)return;let i=new Date;await MI(n,i,i)}catch{}})()},HI);return a.unref(),async()=>{clearInterval(a);try{(await xo(n,"ownership journal")).nonce===o&&await Yt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},qy=async e=>{let t=await R(e),n={};if(t)try{n=await M(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:hu(t,n)}},Qy=async(e,t)=>{let n=Jy(t);if(!await R(n))return;let r=await xo(n,"prepared ownership transaction");if(!GI(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await qy(e),a=await R(t),s=await R(Ga(e)),i=yu(o.fingerprint,r.before),c=yu(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await Z(t,r.journal,{backup:!1}),await Yt(n,{force:!0});return}if(i){await Yt(n,{force:!0}),a||await re(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},Zi=async(e,t,n)=>{let r=await zy(t);try{return await Qy(e,t),await n()}finally{await r()}},jy=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 xo(e,"ownership journal");if(!(n&&Eo(a,t))){if(!Eo(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await Z(e,t,{backup:!1}):await Yt(e,{force:!0})}},Xi=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await zy(a);try{await Qy(n,a);let l=await qy(n),d=hu(i,r),u=await R(a),f=u?await xo(a,"ownership journal"):void 0,p=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!yu(l.fingerprint,d)){if(Eo(l.value,o)&&f&&Eo(f,p))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&Eo(l.value,o)&&f&&Eo(f,p))return;let h=await R(Ga(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=Jy(a),w={transactionVersion:Xy,before:l.fingerprint,after:hu(!0,o),journal:p};await Z(m,w,{backup:!1});try{await Z(n,o,f?{backup:!1}:{}),await(t.writeJournal??Z)(a,p,{backup:!1}),await Yt(m,{force:!0})}catch(g){try{await jy(n,l.value,l.exists,o)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed and config rollback was incomplete")}try{await jy(a,f??{},u,p),await Yt(m,{force:!0}),!h&&!f&&await re(n)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed after config rollback")}throw g}}finally{await c()}},Dr=async e=>{try{return await M(Ga(e))}catch{return{}}},re=async e=>{await Yt(Ga(e),{force:!0}).catch(()=>{})};import{access as gR}from"node:fs/promises";import{spawnSync as nR}from"node:child_process";import{readFileSync as rR,realpathSync as Ya,statSync as lg}from"node:fs";import{access as oR,cp as dg,mkdir as ig,readdir as aR,readFile as Iu,realpath as sR,rename as iR,rm as Eu,writeFile as cR}from"node:fs/promises";import{tmpdir as lR}from"node:os";import{basename as Ro,dirname as Ke,join as Re,resolve as dR}from"node:path";import{writeFile as Ji,readFile as ja,chmod as ku,stat as Au,mkdir as tg,rm as Nr,access as VI}from"node:fs/promises";import{randomUUID as YI}from"node:crypto";import{homedir as ng}from"node:os";import{join as Sn}from"node:path";var q=()=>Sn(ng(),".anyray"),Io=async()=>{let e=q();try{if((await Au(e)).isDirectory())return Sn(e,"connect.json")}catch{}return e},Cu=()=>Sn(q(),"dev-key.pem"),kt=async()=>{let e=q(),t;try{if(!(await Au(e)).isDirectory())t=await ja(e,"utf-8").catch(()=>{}),await Nr(e,{force:!0});else return}catch{}if(await tg(e,{recursive:!0,mode:448}),t!==void 0){let n=Sn(e,"connect.json");await Ji(n,t,{mode:384}),await ku(n,384)}},zi=async e=>{await kt();let t=Cu();await Ji(t,e,{mode:384}),await ku(t,384)},Be=async()=>{try{let e=await ja(Cu(),"utf-8");return e.trim()?e:void 0}catch{return}},Va=async()=>{await Nr(Cu(),{force:!0}).catch(()=>{})},ZI=e=>{let{fallbackEnabled:t,fallbackGatewayTimeoutMs:n,fallbackBreaker:r,...o}=e,a=o;return t===!0&&(a.keyRefreshEnabled=!0),a},P=async()=>{try{let e=await ja(await Io(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:ZI(t)}catch{return{}}},XI=0,JI=3e4,zI=5e3,qI=25,QI=()=>Sn(ng(),".anyray-connect-profile.lock"),eR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},tR=async e=>{try{let t=JSON.parse(await ja(Sn(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!eR(t.pid)}catch{}return Date.now()-(await Au(e)).mtimeMs>JI},rg=async()=>{let e=QI(),t=Sn(e,"owner.json"),n=Date.now()+zI;for(;;){let r=YI();try{await tg(e,{mode:448});try{await Ji(t,`${JSON.stringify({pid:process.pid,nonce:r})}
4
- `,{mode:384})}catch(a){throw await Nr(e,{recursive:!0,force:!0}).catch(()=>{}),a}return async()=>{try{JSON.parse(await ja(t,"utf-8")).nonce===r&&await Nr(e,{recursive:!0,force:!0})}catch{}}}catch(a){if(a.code!=="EEXIST")throw a}if(!(await tR(e).catch(()=>!1)&&await Nr(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,qI))}}},og=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Io(),r=`${n}.${process.pid}.${XI++}.tmp`;await Ji(r,`${JSON.stringify(t,null,2)}
5
- `,{mode:384}),await ku(r,384);try{await fe(r,n)}catch(o){throw await Nr(r,{force:!0}).catch(()=>{}),o}},te=async e=>{let t=await rg();try{await og(e)}finally{await t()}},ag=async e=>{let t=await rg();try{let n=await P(),{next:r,result:o}=e(n);return r&&await og(r),o}finally{await t()}},bu=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],eg="ssoLink",vu=async()=>{let e=await P();return bu.some(t=>e[t]!==void 0)?!0:await Be()!==void 0},qi=async()=>{let e=await P(),t=bu.some(a=>e[a]!==void 0),n=e[eg]!==void 0,r=e.byoUpstream!==void 0,o=await Be()!==void 0;if(!t&&!n&&!r&&!o)return!1;if(t||n||r){let a={...e};for(let s of bu)delete a[s];delete a[eg],delete a.byoUpstream,delete a.anyrayFleetManaged,await te(a)}if(await Va(),await Be())throw new Error(`could not remove the dev key from ${q()}`);return!0},sg=["fallback-bundle.enc","fallback-key","fallback-usage-queue.jsonl"],Qi=async()=>{let e=q();for(let t of sg)await Nr(Sn(e,t),{force:!0}).catch(()=>{})},Su=async()=>{let e=q(),t=[];for(let n of sg){let r=Sn(e,n);try{await VI(r),t.push(r)}catch{}}return t},Xn=async(e,t,n=!1)=>{let r=await P(),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 te({...p,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},ec=async(e=new Date().toISOString())=>{await te({...await P(),offboardedAt:e})};var Oo=e=>dR(e).replace(/\\/g,"/").toLowerCase(),xu=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",Za=e=>`${e}.source`,ug=e=>/(^|\/)_npx(\/|$)/.test(Oo(e)),Ru=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Oo(e)),Ou=e=>{let t=Oo(e),n=[lR(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Oo);return ug(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},mt=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),Xa=e=>/[\\/](node|node\.exe)$/i.test(e),Jn=(e=mt())=>Xa(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,cg=e=>{try{let t=lg(e);return t.isFile()?t.size:void 0}catch{return}},_u=e=>{let t=Ke(e);if(Ro(t)==="versions")return t;let n=Ke(t);return Ro(n)==="versions"?n:void 0},nc=(e,t)=>t!==void 0&&(Ke(e)===t||Ke(Ke(e))===t),uR=e=>{let t=_u(e);if(!t)return;let n=Re(Ke(t),"bin",xu());try{let r=Ya(n);return r===Ya(e)||nc(r,Ya(t))?n:void 0}catch{return}},_o=(e=q(),t=process.platform)=>{let n=Re(e,"bin",xu(t));try{let r=Ya(n),o=Ya(Re(e,"versions"));if(nc(r,o))return n;if(t==="win32"){let a=rR(Za(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=cg(Re(o,a,xu(t)))??cg(Re(o,a));if(s!==void 0&&s===lg(n).size)return n}}catch{return}},$r=(e=mt())=>{let t=Jn(e),n=Ru(t)||Pu(t)?_o():void 0;return uR(e.execPath)??n??t},pg=(e=mt())=>$r(e)!==Jn(e),dn=(e,t=mt())=>{let n=$r(t);return Xa(t.execPath)&&t.scriptPath!==void 0&&n===Jn(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},fg=(e=mt())=>{let t=$r(e);return!Xa(e.execPath)&&!Ou(t)?Ke(t):Re(q(),"bin")},tc=async e=>{try{return await oR(e),!0}catch{return!1}},pR=async e=>{let t=await sR(e),n=Ke(t),r=Ke(n),o=Re(r,"package.json"),a=await Iu(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 tc(Re(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},fR=async(e,t)=>{let n=t;for(;;){let r=Re(n,"node_modules",e);if(await tc(Re(r,"package.json")))return r;let o=Ke(n);if(o===n)return;n=o}},hR=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Iu(Re(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await fR(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await dg(i,Re(t,s),{recursive:!0}),r.push(i)}}},mR=async(e=mt())=>{let t=_o();if(t)return{command:t,args:[],entryPath:t};if(!Xa(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await pR(e.scriptPath);await kt();let r=Re(q(),"bin",`connect-runtime-${n.version}`),o=Re(r,"dist","index.js");if(!await tc(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Eu(a,{recursive:!0,force:!0}),await ig(a,{recursive:!0,mode:448});try{await dg(n.dist,Re(a,"dist"),{recursive:!0}),await cR(Re(a,"package.json"),await Iu(n.packageJson),{mode:384}),await hR(n.root,Re(a,"node_modules")),await ig(Ke(r),{recursive:!0,mode:448});try{await iR(a,r)}catch(s){if(!await tc(o))throw s}}finally{await Eu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Tu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,yR=e=>{let t=Ro(Ke(Ke(e)));return Tu.test(t)?t:void 0},Pu=(e,t=q())=>{let n=Ke(Ke(e));return Oo(Ke(n))===Oo(Re(t,"bin"))&&Tu.test(Ro(n))&&Ro(Ke(e))==="dist"&&Ro(e)==="index.js"},rc=async(e=mt())=>{let t=Re(q(),"bin"),n=yR(Jn(e)),r=[];for(let o of await aR(t).catch(()=>[])){if(!Tu.test(o)||o===n)continue;let a=Re(t,o);await Eu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},hg=async(e,t=mt())=>{let n=Jn(t);if(!Xa(t.execPath)||!ug(n)||_o())return;let r=await mR(t),o=nR(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Lu=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,Ja=(e,t)=>[e,...t].map(Lu).join(" "),En=(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}:{}}]}),zn=(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))},oc=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!zn(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},To=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!zn(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)},Du=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=>!zn(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 Ze="__anyray-hook",mg="__anyray-codex-hook",qn="__anyray-prompt-hook",yg="__anyray-shell-pretool",Nu="__anyray-shell-run",gg="__anyray-read-pretool",Qn="__anyray-refresh",za=(e,t=[])=>{let{command:n,args:r}=dn([e,...t]);return{command:n,args:r}},Tt=(e,t=[])=>{let n=za(e,t);return[n.command,...n.args].map(Lu).join(" ")},ac=(e,t,n=[])=>typeof e=="string"&&e.trim()===Tt(t,n),wg=()=>Tt("print-key"),Oe=()=>$r(),Ge=Ou,ce=()=>!Ge(Oe()),Mr=async()=>{if(!ce())return!1;try{return await gR(Oe()),!0}catch{return!1}},er="__anyray-mcp-server",je=e=>za(er,[e]),wR=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),sc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=je(t);return n.command===r.command&&wR(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)===er&&r.at(-1)===t};var J=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,le=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Fr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],bg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],ic=[...Fr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],bR=(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
- `)},un=(e,t={})=>{let n=e.byoUpstream,r=!n&&J(e,"anthropic"),o=le({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1&&!((r||n)&&e.viaLocalProxy),s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=bR(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 $u}from"zod";var kR=5e3,AR=1e3,CR=1e8,vR=$u.object({modelContext:$u.object({contextTokens:$u.number().int().min(AR).max(CR)}).optional()}),kg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},Ag=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??kR,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=vR.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var SR=1e6,qa="[1m]",ER=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Cg=(e,t)=>!e||t===void 0?{}:ER(e)?{envTokens:t}:t<SR?{}:e.toLowerCase().endsWith(qa)?{}:{model:`${e}${qa}`},vg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(qa))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(qa))return e.slice(0,-qa.length)};import{platform as xR}from"node:os";var Pt=(e=xR())=>{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 xn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],cc=e=>typeof e=="string"&&e.trim()!=="",IR=(e,t)=>typeof e[t]=="string"&&!cc(e[t]),Sg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},RR=()=>M(Pt()).catch(()=>({})),Eg=async(e={})=>{let t=e.env??process.env,n=Sg(e.userSettings??{}),r=Sg(await(e.readManaged??RR)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of xn)cc(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Pt()})`,repairable:!1}):cc(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!IR(n,a)&&cc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Mu=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`,Fu=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.",xg=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 OR=xn.map(e=>e.name),_R=ic.filter(e=>!OR.includes(e)),Ig=e=>typeof e=="string"&&e.trim()!=="",Rg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},TR=(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)},PR=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Bu=()=>M(Pt()).catch(()=>({})),Og=Bu,LR=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=>zn(r,Ze))},_g=async(e={})=>{let t=await(e.readManaged??Og)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!LR(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},lc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Pt()}) \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 (${Pt()}), 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",dc=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.",Tg=async(e={})=>{let t=Rg(e.userSettings??{}),n=Rg(await(e.readManaged??Og)().catch(()=>({}))),r=[];for(let o of _R){if(!Ig(n[o])||!Ig(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(TR(n[o],t[o],a))continue;let s=a?PR(n[o]):void 0;r.push({name:o,source:`managed settings (${Pt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},Pg=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`,Lg=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 DR}from"node:os";import{join as NR}from"node:path";import{readFile as $R}from"node:fs/promises";var nt=e=>!!e.keyRefreshEnabled;var MR=400,Dg=async()=>{try{let e=NR(DR(),".claude","settings.json"),n=JSON.parse(await $R(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}},Ng=async()=>{try{let e=await P();return e.gateway?{origin:new URL(e.gateway).origin,metadata:le({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},rt=async(e="auto")=>e==="profile"?Ng():e==="claude"?Dg():await Dg()??await Ng(),uc=async(e={})=>{let t=e.readTarget??rt,n=e.loadProfile??P,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://${ht}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},Xt=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},pc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),MR);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Xt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var In=()=>hc(fc(),".claude","settings.json"),Qa=()=>hc(fc(),".claude.json"),FR=ic,tr="anyray",BR=()=>({type:"stdio",...je("claude"),alwaysLoad:!0}),Br=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),UR=e=>{if("mcpServers"in e&&!Br(e.mcpServers))return"conflict";let t=Br(e.mcpServers)?{...e.mcpServers}:{},n=t[tr];return n!==void 0&&!Zt(n,"claude")?"conflict":(t[tr]=BR(),e.mcpServers=t,"installed")},$g=e=>{let t=e.mcpServers;return!t||!(tr in t)||!Zt(t[tr],"claude")?!1:(delete t[tr],Object.keys(t).length===0&&delete e.mcpServers,!0)},HR=e=>{oc(e,"PostToolUse",Ze,En(Tt(Ze),{matcher:"*"})),oc(e,"UserPromptSubmit",qn,En(Tt(qn)))},WR=e=>{oc(e,"SessionStart",Qn,En(Tt(Qn),{async:!0}))},Bg=e=>To(e,"SessionStart",Qn),Mg=e=>{let t=To(e,"PostToolUse",Ze),n=To(e,"UserPromptSubmit",qn),r=Bg(e);return t||n||r},KR="print-key",GR=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Ur=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===KR&&GR(t)},jR=async(e,t)=>{let n=(await Dr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of FR){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},VR=e=>typeof e.apiKeyHelper=="string"&&!Ur(e),Ug=async e=>{let t=await Bu(),n=async()=>t,[r,o,a]=await Promise.all([Eg({userSettings:e,readManaged:n}),Tg({userSettings:e,readManaged:n}).catch(()=>[]),_g({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},Fg=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await Ug(e),o=Fu(t),a=Lg(n);return{routingOverrides:[...t.map(i=>({problem:Mu(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:Pg(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},nr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=hc(fc(),".claude"),t=await R(e);return{installed:t,detail:t?In():"no ~/.claude directory"}},async apply(e,t){let n=In(),r=await M(n),o=kg(r),a=await Ag(e.origin,e.clientKey,o),s=Cg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=un(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await Ug(r),h=f.filter(I=>!I.repairable),m=f.filter(I=>I.repairable),w=[...h.map(I=>`WARNING: ${Mu(I)}.`),...h.length?[Fu(h)]:[],...p.state==="fine"?[]:[`WARNING: ${lc(p)}.`,dc(p)],...m.map(I=>xg(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 xn)m.some(T=>T.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 bg)delete y[I];let b=!!e.clientKey,v=ce(),S=VR(r);!c&&!l&&b&&v&&!S?(r.apiKeyHelper=wg(),delete 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).")):Ur(r)&&delete r.apiKeyHelper,S&&!c&&!l&&b&&v&&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&&v?(WR(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Bg(r),ce()?(HR(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.")):(Mg(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 Z(n,r);let x=[n],A=Qa();try{let I=await M(A),T=!1;ce()?UR(I)==="conflict"?w.push(`MCP name conflict in ${A}: mcpServers.${tr} 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=$g(I),T&&(await Z(A,I),x.push(A))}catch(I){w.push(`Could not register the Anyray MCP server in ${A} (${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 hc(fc(),".claude","skills")},async watchPaths(){return[In(),Qa()]},async pointsAt(e){let t=In();if(!await R(t))return!1;try{let o=(await M(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await M(In()).catch(()=>({}));return Fg(e)},async routingOverrides(){let e=await M(In()).catch(()=>({}));return(await Fg(e)).routingOverrides},async mcpStatus(){let e=Qa();if(!await R(e))return{registered:!1,command:null};try{let r=(await M(e)).mcpServers?.[tr];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=In();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!Br(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>zn(c,Ze))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>zn(c,Ze)&&Br(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Br(l)&&ac(l.command,Ze))))}}catch{e="unreadable"}let r,o=!0,a=Qa();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!Br(s.mcpServers))r="unreadable";else{let i=s.mcpServers[tr];r=i===void 0?"missing":Zt(i,"claude")?"owned":"foreign",r==="owned"&&(o=sc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Mr()?"owned":"missing",beacon_target:await uc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(In()),t=Br(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=In();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 M(t),r=n.env,o=Mg(n),a=Ur(n);a&&delete n.apiKeyHelper;let s=r?await jR(t,r):[],i=vg(typeof n.model=="string"?n.model:void 0,(await Dr(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await Z(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=Qa();try{let d=await M(l);$g(d)&&(await Z(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await re(t),{status:"reverted",messages:c,changedFiles:[t]}}};var be="0.11.133";var pn=e=>{let{command:t,args:n}=dn([e]);return{command:t,args:n}},rr=()=>$r();import{homedir as Hg,userInfo as YR}from"node:os";var es=()=>{try{return Hg()!==YR().homedir}catch{return!1}},Po=e=>[`Skipped ${e} \u2014 HOME (${Hg()}) 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,ts=(e=process.env)=>yt(e)!==null,At=e=>e==="codespaces"||e==="devcontainer",or=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var Ku="__anyray-fallback-proxy",os="ai.anyray.connect.fallback",ar="anyray-fallback",Vg=os,Ae=8785,as=60,Gu="x-anyray-local",ju=()=>pn(Ku),Wg=rr,yc=async(e=Ae)=>{let t=n=>new Promise(r=>{let o=JR();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},ke=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)}},$o=()=>No(rs(),"Library","LaunchAgents",`${Vg}.plist`),ss=()=>No(rs(),".anyray","logs"),ns=()=>No(ss(),"connect-daemon.log"),Yg=async(e,t=1048576)=>{await Gg(e).then(r=>r.size,()=>0)>t&&await XR(e).catch(()=>{})},Mo=()=>No(rs(),".config","systemd","user",`${ar}.service`),Uu=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),is=(e=ju())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${Uu(o)}</string>`).join(`
2
+ var NI="http://localhost:8787",ja="anyray-placeholder",Re=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},je=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},hu=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,$I=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Gy=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!$I.has(n)}catch{return!1}},ln=e=>{let t=je(e||process.env.ANYRAY_GATEWAY_URL||NI),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},ut="127.0.0.1",vn=(e,t)=>{let n=`http://${ut}:${t}`;return{...e,anthropicBaseUrl:n,openaiBaseUrl:`${n}/v1`,viaLocalProxy:!0}},ge=(e={})=>{let t=ln(e.origin),n=e.placeholderKey?.trim()||ja,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:hu(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:hu(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:hu(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 ss,platform as Do}from"node:os";import{join as No}from"node:path";import{mkdir as Gu,readFile as Zg,rename as eO,stat as Xg,truncate as tO,writeFile as Jg,rm as Lo}from"node:fs/promises";import{spawnSync as fn}from"node:child_process";import{createServer as nO}from"node:net";import{homedir as gc}from"node:os";import{join as wc}from"node:path";import{access as HI,chmod as WI,mkdir as mu,open as ku,readFile as zy,rm as Zt,stat as Vy,utimes as KI}from"node:fs/promises";import{createHash as GI,randomUUID as qy}from"node:crypto";import{dirname as Au,join as jI}from"node:path";import{isDeepStrictEqual as Eo}from"node:util";import{randomUUID as MI}from"node:crypto";import{lstat as FI,rename as zi,rm as BI}from"node:fs/promises";import{platform as jy}from"node:os";var UI=e=>e?.code==="ENOENT",Va=async(e,t=jy())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},he=async(e,t,n=jy())=>{if(n!=="win32"){await zi(e,t);return}let r=`${t}.anyray-old-${process.pid}-${MI()}`,o=!1;try{let a=await FI(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await zi(t,r),o=!0}catch(a){if(!UI(a))throw a}try{await zi(e,t)}catch(a){if(o)try{await zi(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await BI(r,{force:!0})};var Ya=e=>`${e}.anyray-bak`,Qy=async e=>{let t;try{t=await ku(Au(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},Yy=async(e,t)=>{let n,r;try{n=await ku(e,"wx",384),await n.writeFile(t,"utf-8"),await Va(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Zt(e,{force:!0}).catch(()=>{}),r;await Qy(e)},VI=async e=>{let t;try{t=await ku(e,"r"),await Va(t)}finally{await t?.close().catch(()=>{})}await Qy(e)},R=async e=>{try{return await HI(e),!0}catch{return!1}},M=async e=>{if(!await R(e))return{};let t=await zy(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},Z=async(e,t,n={})=>{await mu(Au(e),{recursive:!0,mode:448});let r=Ya(e);if(n.backup!==!1&&await R(e)&&!await R(r))try{await Yy(r,await zy(e,"utf-8"))}catch(a){if(a.code!=="EEXIST")throw a}let o=`${e}.anyray-tmp-${process.pid}-${qy()}`;try{await Yy(o,`${JSON.stringify(t,null,2)}
3
+ `),await he(o,e),await WI(e,384),await VI(e)}finally{await Zt(o,{force:!0}).catch(()=>{})}},eg=1,Zy=3e4,YI=5e3,ZI=/^[a-f0-9]{64}$/,tg=e=>`${e}.pending`,XI=e=>`${e}.lock`,yu=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=>yu(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${yu(t[n])}`).join(",")}}`},gu=(e,t)=>({exists:e,sha256:GI("sha256").update(yu(t)).digest("hex")}),wu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Xy=e=>wu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&ZI.test(e.sha256),JI=e=>wu(e)&&e.transactionVersion===eg&&Xy(e.before)&&Xy(e.after)&&wu(e.journal),bu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,xo=async(e,t)=>{try{return await M(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},zI=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},ng=async e=>{let t=XI(e),n=jI(t,"owner.json");await mu(Au(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=qy();try{await mu(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await xo(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 Vy(n)).mtimeMs;i=!zI(c.pid)||l>Zy}catch{try{i=Date.now()-(await Vy(t)).mtimeMs>Zy}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Zt(t,{recursive:!0,force:!0});continue}try{await Z(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Zt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await xo(n,"ownership journal")).nonce!==o)return;let i=new Date;await KI(n,i,i)}catch{}})()},YI);return a.unref(),async()=>{clearInterval(a);try{(await xo(n,"ownership journal")).nonce===o&&await Zt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},rg=async e=>{let t=await R(e),n={};if(t)try{n=await M(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:gu(t,n)}},og=async(e,t)=>{let n=tg(t);if(!await R(n))return;let r=await xo(n,"prepared ownership transaction");if(!JI(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await rg(e),a=await R(t),s=await R(Ya(e)),i=bu(o.fingerprint,r.before),c=bu(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await Z(t,r.journal,{backup:!1}),await Zt(n,{force:!0});return}if(i){await Zt(n,{force:!0}),a||await re(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},qi=async(e,t,n)=>{let r=await ng(t);try{return await og(e,t),await n()}finally{await r()}},Jy=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 xo(e,"ownership journal");if(!(n&&Eo(a,t))){if(!Eo(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await Z(e,t,{backup:!1}):await Zt(e,{force:!0})}},Qi=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await ng(a);try{await og(n,a);let l=await rg(n),d=gu(i,r),u=await R(a),f=u?await xo(a,"ownership journal"):void 0,p=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!bu(l.fingerprint,d)){if(Eo(l.value,o)&&f&&Eo(f,p))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&Eo(l.value,o)&&f&&Eo(f,p))return;let h=await R(Ya(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=tg(a),w={transactionVersion:eg,before:l.fingerprint,after:gu(!0,o),journal:p};await Z(m,w,{backup:!1});try{await Z(n,o,f?{backup:!1}:{}),await(t.writeJournal??Z)(a,p,{backup:!1}),await Zt(m,{force:!0})}catch(g){try{await Jy(n,l.value,l.exists,o)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed and config rollback was incomplete")}try{await Jy(a,f??{},u,p),await Zt(m,{force:!0}),!h&&!f&&await re(n)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed after config rollback")}throw g}}finally{await c()}},Pr=async e=>{try{return await M(Ya(e))}catch{return{}}},re=async e=>{await Zt(Ya(e),{force:!0}).catch(()=>{})};import{access as vR}from"node:fs/promises";import{spawnSync as cR}from"node:child_process";import{readFileSync as lR,realpathSync as Ja,statSync as hg}from"node:fs";import{access as dR,cp as mg,mkdir as pg,readdir as uR,readFile as _u,realpath as pR,rename as fR,rm as Ru,writeFile as hR}from"node:fs/promises";import{tmpdir as mR}from"node:os";import{basename as Ro,dirname as We,join as Oe,resolve as yR}from"node:path";import{writeFile as ec,readFile as Za,chmod as vu,stat as Su,mkdir as sg,rm as Lr,access as qI}from"node:fs/promises";import{randomUUID as QI}from"node:crypto";import{homedir as ig}from"node:os";import{join as Sn}from"node:path";var q=()=>Sn(ig(),".anyray"),Io=async()=>{let e=q();try{if((await Su(e)).isDirectory())return Sn(e,"connect.json")}catch{}return e},Eu=()=>Sn(q(),"dev-key.pem"),kt=async()=>{let e=q(),t;try{if(!(await Su(e)).isDirectory())t=await Za(e,"utf-8").catch(()=>{}),await Lr(e,{force:!0});else return}catch{}if(await sg(e,{recursive:!0,mode:448}),t!==void 0){let n=Sn(e,"connect.json");await ec(n,t,{mode:384}),await vu(n,384)}},tc=async e=>{await kt();let t=Eu();await ec(t,e,{mode:384}),await vu(t,384)},Be=async()=>{try{let e=await Za(Eu(),"utf-8");return e.trim()?e:void 0}catch{return}},Xa=async()=>{await Lr(Eu(),{force:!0}).catch(()=>{})},eR=e=>{let{fallbackEnabled:t,fallbackGatewayTimeoutMs:n,fallbackBreaker:r,...o}=e,a=o;return t===!0&&(a.keyRefreshEnabled=!0),a},P=async()=>{try{let e=await Za(await Io(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:eR(t)}catch{return{}}},tR=0,nR=3e4,rR=5e3,oR=25,aR=()=>Sn(ig(),".anyray-connect-profile.lock"),sR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},iR=async e=>{try{let t=JSON.parse(await Za(Sn(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!sR(t.pid)}catch{}return Date.now()-(await Su(e)).mtimeMs>nR},cg=async()=>{let e=aR(),t=Sn(e,"owner.json"),n=Date.now()+rR;for(;;){let r=QI();try{await sg(e,{mode:448});try{await ec(t,`${JSON.stringify({pid:process.pid,nonce:r})}
4
+ `,{mode:384})}catch(a){throw await Lr(e,{recursive:!0,force:!0}).catch(()=>{}),a}return async()=>{try{JSON.parse(await Za(t,"utf-8")).nonce===r&&await Lr(e,{recursive:!0,force:!0})}catch{}}}catch(a){if(a.code!=="EEXIST")throw a}if(!(await iR(e).catch(()=>!1)&&await Lr(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,oR))}}},lg=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Io(),r=`${n}.${process.pid}.${tR++}.tmp`;await ec(r,`${JSON.stringify(t,null,2)}
5
+ `,{mode:384}),await vu(r,384);try{await he(r,n)}catch(o){throw await Lr(r,{force:!0}).catch(()=>{}),o}},te=async e=>{let t=await cg();try{await lg(e)}finally{await t()}},dg=async e=>{let t=await cg();try{let n=await P(),{next:r,result:o}=e(n);return r&&await lg(r),o}finally{await t()}},Cu=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],ag="ssoLink",xu=async()=>{let e=await P();return Cu.some(t=>e[t]!==void 0)?!0:await Be()!==void 0},nc=async()=>{let e=await P(),t=Cu.some(a=>e[a]!==void 0),n=e[ag]!==void 0,r=e.byoUpstream!==void 0,o=await Be()!==void 0;if(!t&&!n&&!r&&!o)return!1;if(t||n||r){let a={...e};for(let s of Cu)delete a[s];delete a[ag],delete a.byoUpstream,delete a.anyrayFleetManaged,await te(a)}if(await Xa(),await Be())throw new Error(`could not remove the dev key from ${q()}`);return!0},ug=["fallback-bundle.enc","fallback-key","fallback-usage-queue.jsonl"],rc=async()=>{let e=q();for(let t of ug)await Lr(Sn(e,t),{force:!0}).catch(()=>{})},Iu=async()=>{let e=q(),t=[];for(let n of ug){let r=Sn(e,n);try{await qI(r),t.push(r)}catch{}}return t},Xn=async(e,t,n=!1)=>{let r=await P(),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 te({...p,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},oc=async(e=new Date().toISOString())=>{await te({...await P(),offboardedAt:e})};var Oo=e=>yR(e).replace(/\\/g,"/").toLowerCase(),Ou=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",za=e=>`${e}.source`,yg=e=>/(^|\/)_npx(\/|$)/.test(Oo(e)),Tu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Oo(e)),Pu=e=>{let t=Oo(e),n=[mR(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Oo);return yg(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},pt=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),qa=e=>/[\\/](node|node\.exe)$/i.test(e),Jn=(e=pt())=>qa(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,fg=e=>{try{let t=hg(e);return t.isFile()?t.size:void 0}catch{return}},Lu=e=>{let t=We(e);if(Ro(t)==="versions")return t;let n=We(t);return Ro(n)==="versions"?n:void 0},sc=(e,t)=>t!==void 0&&(We(e)===t||We(We(e))===t),gR=e=>{let t=Lu(e);if(!t)return;let n=Oe(We(t),"bin",Ou());try{let r=Ja(n);return r===Ja(e)||sc(r,Ja(t))?n:void 0}catch{return}},_o=(e=q(),t=process.platform)=>{let n=Oe(e,"bin",Ou(t));try{let r=Ja(n),o=Ja(Oe(e,"versions"));if(sc(r,o))return n;if(t==="win32"){let a=lR(za(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=fg(Oe(o,a,Ou(t)))??fg(Oe(o,a));if(s!==void 0&&s===hg(n).size)return n}}catch{return}},Dr=(e=pt())=>{let t=Jn(e),n=Tu(t)||Nu(t)?_o():void 0;return gR(e.execPath)??n??t},gg=(e=pt())=>Dr(e)!==Jn(e),dn=(e,t=pt())=>{let n=Dr(t);return qa(t.execPath)&&t.scriptPath!==void 0&&n===Jn(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},wg=(e=pt())=>{let t=Dr(e);return!qa(e.execPath)&&!Pu(t)?We(t):Oe(q(),"bin")},ac=async e=>{try{return await dR(e),!0}catch{return!1}},wR=async e=>{let t=await pR(e),n=We(t),r=We(n),o=Oe(r,"package.json"),a=await _u(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 ac(Oe(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},bR=async(e,t)=>{let n=t;for(;;){let r=Oe(n,"node_modules",e);if(await ac(Oe(r,"package.json")))return r;let o=We(n);if(o===n)return;n=o}},kR=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await _u(Oe(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await bR(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await mg(i,Oe(t,s),{recursive:!0}),r.push(i)}}},AR=async(e=pt())=>{let t=_o();if(t)return{command:t,args:[],entryPath:t};if(!qa(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await wR(e.scriptPath);await kt();let r=Oe(q(),"bin",`connect-runtime-${n.version}`),o=Oe(r,"dist","index.js");if(!await ac(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Ru(a,{recursive:!0,force:!0}),await pg(a,{recursive:!0,mode:448});try{await mg(n.dist,Oe(a,"dist"),{recursive:!0}),await hR(Oe(a,"package.json"),await _u(n.packageJson),{mode:384}),await kR(n.root,Oe(a,"node_modules")),await pg(We(r),{recursive:!0,mode:448});try{await fR(a,r)}catch(s){if(!await ac(o))throw s}}finally{await Ru(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Du=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,CR=e=>{let t=Ro(We(We(e)));return Du.test(t)?t:void 0},Nu=(e,t=q())=>{let n=We(We(e));return Oo(We(n))===Oo(Oe(t,"bin"))&&Du.test(Ro(n))&&Ro(We(e))==="dist"&&Ro(e)==="index.js"},ic=async(e=pt())=>{let t=Oe(q(),"bin"),n=CR(Jn(e)),r=[];for(let o of await uR(t).catch(()=>[])){if(!Du.test(o)||o===n)continue;let a=Oe(t,o);await Ru(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},bg=async(e,t=pt())=>{let n=Jn(t);if(!qa(t.execPath)||!yg(n)||_o())return;let r=await AR(t),o=cR(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var $u=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,Qa=(e,t)=>[e,...t].map($u).join(" "),En=(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}:{}}]}),zn=(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))},cc=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!zn(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},To=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!zn(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)},Mu=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=>!zn(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 Ve="__anyray-hook",kg="__anyray-codex-hook",qn="__anyray-prompt-hook",Ag="__anyray-shell-pretool",Fu="__anyray-shell-run",Cg="__anyray-read-pretool",Qn="__anyray-refresh",es=(e,t=[])=>{let{command:n,args:r}=dn([e,...t]);return{command:n,args:r}},Pt=(e,t=[])=>{let n=es(e,t);return[n.command,...n.args].map($u).join(" ")},lc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Pt(t,n),vg=()=>Pt("print-key"),_e=()=>Dr(),Ke=Pu,se=()=>!Ke(_e()),Nr=async()=>{if(!se())return!1;try{return await vR(_e()),!0}catch{return!1}},er="__anyray-mcp-server",Ge=e=>es(er,[e]),SR=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),dc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ge(t);return n.command===r.command&&SR(n.args,r.args)},Xt=(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)===er&&r.at(-1)===t};var J=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,ce=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var $r=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Sg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],uc=[...$r,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],ER=(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
+ `)},un=(e,t={})=>{let n=e.byoUpstream,r=!n&&J(e,"anthropic"),o=ce({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1&&!((r||n)&&e.viaLocalProxy),s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=ER(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 Bu}from"zod";var xR=5e3,IR=1e3,RR=1e8,OR=Bu.object({modelContext:Bu.object({contextTokens:Bu.number().int().min(IR).max(RR)}).optional()}),Eg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},xg=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??xR,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=OR.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var _R=1e6,ts="[1m]",TR=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Ig=(e,t)=>!e||t===void 0?{}:TR(e)?{envTokens:t}:t<_R?{}:e.toLowerCase().endsWith(ts)?{}:{model:`${e}${ts}`},Rg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(ts))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(ts))return e.slice(0,-ts.length)};import{platform as PR}from"node:os";var Lt=(e=PR())=>{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 xn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],pc=e=>typeof e=="string"&&e.trim()!=="",LR=(e,t)=>typeof e[t]=="string"&&!pc(e[t]),Og=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},DR=()=>M(Lt()).catch(()=>({})),_g=async(e={})=>{let t=e.env??process.env,n=Og(e.userSettings??{}),r=Og(await(e.readManaged??DR)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of xn)pc(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Lt()})`,repairable:!1}):pc(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!LR(n,a)&&pc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Uu=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`,Hu=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.",Tg=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 NR=xn.map(e=>e.name),$R=uc.filter(e=>!NR.includes(e)),Pg=e=>typeof e=="string"&&e.trim()!=="",Lg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},MR=(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)},FR=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Wu=()=>M(Lt()).catch(()=>({})),Dg=Wu,BR=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=>zn(r,Ve))},Ng=async(e={})=>{let t=await(e.readManaged??Dg)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!BR(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},fc=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",hc=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.",$g=async(e={})=>{let t=Lg(e.userSettings??{}),n=Lg(await(e.readManaged??Dg)().catch(()=>({}))),r=[];for(let o of $R){if(!Pg(n[o])||!Pg(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(MR(n[o],t[o],a))continue;let s=a?FR(n[o]):void 0;r.push({name:o,source:`managed settings (${Lt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},Mg=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`,Fg=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 UR}from"node:os";import{join as HR}from"node:path";import{readFile as WR}from"node:fs/promises";var Qe=e=>!!e.keyRefreshEnabled;var KR=400,Bg=async()=>{try{let e=HR(UR(),".claude","settings.json"),n=JSON.parse(await WR(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}},Ug=async()=>{try{let e=await P();return e.gateway?{origin:new URL(e.gateway).origin,metadata:ce({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},et=async(e="auto")=>e==="profile"?Ug():e==="claude"?Bg():await Bg()??await Ug(),mc=async(e={})=>{let t=e.readTarget??et,n=e.loadProfile??P,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 Qe(r)&&r.fallbackPort&&a.add(`http://${ut}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},Jt=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},yc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),KR);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Jt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var In=()=>wc(gc(),".claude","settings.json"),ns=()=>wc(gc(),".claude.json"),GR=uc,tr="anyray",jR=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),Mr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),VR=e=>{if("mcpServers"in e&&!Mr(e.mcpServers))return"conflict";let t=Mr(e.mcpServers)?{...e.mcpServers}:{},n=t[tr];return n!==void 0&&!Xt(n,"claude")?"conflict":(t[tr]=jR(),e.mcpServers=t,"installed")},Hg=e=>{let t=e.mcpServers;return!t||!(tr in t)||!Xt(t[tr],"claude")?!1:(delete t[tr],Object.keys(t).length===0&&delete e.mcpServers,!0)},YR=e=>{cc(e,"PostToolUse",Ve,En(Pt(Ve),{matcher:"*"})),cc(e,"UserPromptSubmit",qn,En(Pt(qn)))},ZR=e=>{cc(e,"SessionStart",Qn,En(Pt(Qn),{async:!0}))},Gg=e=>To(e,"SessionStart",Qn),Wg=e=>{let t=To(e,"PostToolUse",Ve),n=To(e,"UserPromptSubmit",qn),r=Gg(e);return t||n||r},XR="print-key",JR=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(_e()),Fr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===XR&&JR(t)},zR=async(e,t)=>{let n=(await Pr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of GR){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},qR=e=>typeof e.apiKeyHelper=="string"&&!Fr(e),jg=async e=>{let t=await Wu(),n=async()=>t,[r,o,a]=await Promise.all([_g({userSettings:e,readManaged:n}),$g({userSettings:e,readManaged:n}).catch(()=>[]),Ng({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},Kg=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await jg(e),o=Hu(t),a=Fg(n);return{routingOverrides:[...t.map(i=>({problem:Uu(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:Mg(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},nr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=wc(gc(),".claude"),t=await R(e);return{installed:t,detail:t?In():"no ~/.claude directory"}},async apply(e,t){let n=In(),r=await M(n),o=Eg(r),a=await xg(e.origin,e.clientKey,o),s=Ig(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=un(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await jg(r),h=f.filter(I=>!I.repairable),m=f.filter(I=>I.repairable),w=[...h.map(I=>`WARNING: ${Uu(I)}.`),...h.length?[Hu(h)]:[],...p.state==="fine"?[]:[`WARNING: ${fc(p)}.`,hc(p)],...m.map(I=>Tg(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 xn)m.some(T=>T.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 Sg)delete y[I];let b=!!e.clientKey,v=se(),S=qR(r);!c&&!l&&b&&v&&!S?(r.apiKeyHelper=vg(),delete 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).")):Fr(r)&&delete r.apiKeyHelper,S&&!c&&!l&&b&&v&&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&&v?(ZR(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Gg(r),se()?(YR(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.")):(Wg(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${_e()}). 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 Z(n,r);let x=[n],A=ns();try{let I=await M(A),T=!1;se()?VR(I)==="conflict"?w.push(`MCP name conflict in ${A}: mcpServers.${tr} 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=Hg(I),T&&(await Z(A,I),x.push(A))}catch(I){w.push(`Could not register the Anyray MCP server in ${A} (${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 wc(gc(),".claude","skills")},async watchPaths(){return[In(),ns()]},async pointsAt(e){let t=In();if(!await R(t))return!1;try{let o=(await M(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await M(In()).catch(()=>({}));return Kg(e)},async routingOverrides(){let e=await M(In()).catch(()=>({}));return(await Kg(e)).routingOverrides},async mcpStatus(){let e=ns();if(!await R(e))return{registered:!1,command:null};try{let r=(await M(e)).mcpServers?.[tr];return!r||!Xt(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=In();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!Mr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>zn(c,Ve))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>zn(c,Ve)&&Mr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Mr(l)&&lc(l.command,Ve))))}}catch{e="unreadable"}let r,o=!0,a=ns();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!Mr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[tr];r=i===void 0?"missing":Xt(i,"claude")?"owned":"foreign",r==="owned"&&(o=dc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Nr()?"owned":"missing",beacon_target:await mc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(In()),t=Mr(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=In();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 M(t),r=n.env,o=Wg(n),a=Fr(n);a&&delete n.apiKeyHelper;let s=r?await zR(t,r):[],i=Rg(typeof n.model=="string"?n.model:void 0,(await Pr(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await Z(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=ns();try{let d=await M(l);Hg(d)&&(await Z(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await re(t),{status:"reverted",messages:c,changedFiles:[t]}}};var be="0.11.136";var pn=e=>{let{command:t,args:n}=dn([e]);return{command:t,args:n}},rr=()=>Dr();import{homedir as Vg,userInfo as QR}from"node:os";var rs=()=>{try{return Vg()!==QR().homedir}catch{return!1}},Po=e=>[`Skipped ${e} \u2014 HOME (${Vg()}) 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 ft=(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,os=(e=process.env)=>ft(e)!==null,At=e=>e==="codespaces"||e==="devcontainer",or=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var Vu="__anyray-fallback-proxy",is="ai.anyray.connect.fallback",ar="anyray-fallback",zg=is,Ae=8785,cs=60,Yu="x-anyray-local",Zu=()=>pn(Vu),Yg=rr,kc=async(e=Ae)=>{let t=n=>new Promise(r=>{let o=nO();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},ke=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)}},$o=()=>No(ss(),"Library","LaunchAgents",`${zg}.plist`),ls=()=>No(ss(),".anyray","logs"),as=()=>No(ls(),"connect-daemon.log"),qg=async(e,t=1048576)=>{await Xg(e).then(r=>r.size,()=>0)>t&&await tO(e).catch(()=>{})},Mo=()=>No(ss(),".config","systemd","user",`${ar}.service`),Ku=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ds=(e=Zu())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${Ku(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>${Vg}</string>
12
+ <key>Label</key><string>${zg}</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>${as}</integer>
21
- <key>StandardOutPath</key><string>${Uu(ns())}</string>
22
- <key>StandardErrorPath</key><string>${Uu(ns())}</string>
20
+ <key>ExitTimeOut</key><integer>${cs}</integer>
21
+ <key>StandardOutPath</key><string>${Ku(as())}</string>
22
+ <key>StandardErrorPath</key><string>${Ku(as())}</string>
23
23
  </dict>
24
24
  </plist>
25
- `},cs=(e=ju())=>{let{command:t,args:n}=e;return`[Unit]
25
+ `},us=(e=Zu())=>{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=${as}
33
+ TimeoutStopSec=${cs}
34
34
 
35
35
  [Install]
36
36
  WantedBy=default.target
37
- `},mc=()=>{let{command:e,args:t}=ju();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)."]},Zg=async()=>{let e=Do();if(e!=="darwin"&&e!=="linux")return!1;let t=e==="darwin"?$o():Mo();try{return await Gg(t),!0}catch{return!1}},Xg=async()=>{let e=Do();if(e!=="darwin"&&e!=="linux")return!0;let t=e==="darwin"?$o():Mo(),n=e==="darwin"?is():cs();return await Kg(t,"utf-8").catch(()=>null)===n},Wu=async e=>{await Hu(No(rs(),"Library","LaunchAgents"),{recursive:!0}),await Hu(ss(),{recursive:!0,mode:448}),await jg(e,is())},Jg=async()=>{let e=Do();return e==="darwin"?(await Wu($o()),!0):e==="linux"?(await Hu(No(rs(),".config","systemd","user"),{recursive:!0}),await jg(Mo(),cs()),!0):!1},zg=async()=>Jg().catch(()=>!1),zR=async(e,t)=>{let n=Do();if(n!=="darwin"&&n!=="linux")return!1;let r=n==="darwin"?$o():Mo(),o=n==="darwin"?is():cs();if(await Kg(r,"utf-8").catch(()=>null)!==o)return!1;let s=await ke(e);return s?.version!==be?!1:typeof s.remoteOrigin=="string"&&Ye(s.remoteOrigin)===Ye(t)},Lt=async e=>{if(Ge(Wg()))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 anyray-connect is running from a temporary path (${Wg()}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(es())return{ok:!1,messages:Po("key-refresh auto-start")};{let n=yt();if(At(n))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 ${or(n)} has no per-user service manager to supervise the daemon.`]}}if(await zR(e.port,e.remoteOrigin))return{ok:!0,messages:["Key-refresh service already current \u2014 left running."]};let t=Do();try{if(t==="darwin"){let n=$o(),r=String(process.getuid?.()??""),o=`${n}.new-${process.pid}`;await Lo(o,{force:!0}).catch(()=>{}),await Wu(o),fn("launchctl",["bootout",`gui/${r}`,n]),await Lo(n,{force:!0}).catch(()=>{});try{await ZR(o,n)}catch{await Wu(n),await Lo(o,{force:!0}).catch(()=>{})}return fn("launchctl",["bootstrap",`gui/${r}`,n]).status===0||fn("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.`,...mc()]}}if(t==="linux"){let n=Mo();return await Jg(),fn("systemctl",["--user","daemon-reload"]),fn("systemctl",["--user","enable",`${ar}.service`]),fn("systemctl",["--user","restart",`${ar}.service`]).status!==0?{ok:!1,messages:[`Wrote ${n} but \`systemctl --user restart\` failed.`,...mc()]}:{ok:!0,messages:[`Installed systemd user unit ${n}.`]}}return{ok:!1,messages:mc()}}catch(n){return{ok:!1,messages:[`Could not install the key-refresh service: ${n instanceof Error?n.message:String(n)}`,...mc()]}}},Vu=async(e=Ae,t={})=>{if(await ke(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:{[Gu]:"1"},signal:r.signal})}finally{clearTimeout(o)}}catch{}for(let r=0;r<10&&await ke(e,300)!==null;r++)await new Promise(o=>setTimeout(o,100));return!0},Jt=async(e=Ae)=>{let t=Do();await Lo(ns(),{force:!0}).catch(()=>{});let n=[],r=es();try{if(r)n.push(...Po("key-refresh service teardown"));else if(t==="darwin"){let o=$o(),a=String(process.getuid?.()??"");fn("launchctl",["bootout",`gui/${a}`,o]),fn("launchctl",["unload",o]),await Lo(o,{force:!0}),n.push("Removed the launchd key-refresh agent.")}else t==="linux"&&(fn("systemctl",["--user","disable","--now",`${ar}.service`]),await Lo(Mo(),{force:!0}),fn("systemctl",["--user","daemon-reload"]),n.push("Removed the systemd key-refresh unit."))}catch{}try{await Vu(e)&&n.push("Stopped the running key-refresh proxy daemon.")}catch{}return{ok:!0,messages:n}};import{stat as sZ}from"node:fs/promises";import{readFileSync as qR,rmSync as QR,writeFileSync as eO,mkdirSync as tO}from"node:fs";import{join as nO}from"node:path";var Yu=()=>nO(q(),"draining"),qg=e=>{try{tO(q(),{recursive:!0}),eO(Yu(),`${Math.floor(e)}
38
- `,"utf-8")}catch{}},Zu=()=>{try{QR(Yu(),{force:!0})}catch{}},rO=16*6e4,Xu=(e=Date.now())=>{let t;try{t=qR(Yu(),"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+rO};import{homedir as Qu,platform as ep}from"node:os";import{join as Fo}from"node:path";import{mkdir as Ju,readFile as oO,rename as aO,writeFile as gc,rm as Hr}from"node:fs/promises";import{spawnSync as sO}from"node:child_process";var qu=()=>Fo(ss(),"connect-refresh.log"),bc=1800,us="ai.anyray.connect.refresh",Wr="anyray-refresh",kc="\\AnyrayConnectKeyRefresh",Ac=us,ps=Wr,ds=kc,iO=String(bc/60),tp=(e,t)=>{let n=sO(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},np=()=>Fo(Qu(),"Library","LaunchAgents",`${Ac}.plist`),rp=()=>Fo(Qu(),".config","systemd","user"),Qg=()=>Fo(rp(),`${ps}.service`),wc=()=>Fo(rp(),`${ps}.timer`),zu=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Cc=()=>pn(Qn),cO=(e=Cc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${zu(o)}</string>`).join(`
37
+ `},bc=()=>{let{command:e,args:t}=Zu();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)."]},Qg=async()=>{let e=Do();if(e!=="darwin"&&e!=="linux")return!1;let t=e==="darwin"?$o():Mo();try{return await Xg(t),!0}catch{return!1}},ew=async()=>{let e=Do();if(e!=="darwin"&&e!=="linux")return!0;let t=e==="darwin"?$o():Mo(),n=e==="darwin"?ds():us();return await Zg(t,"utf-8").catch(()=>null)===n},ju=async e=>{await Gu(No(ss(),"Library","LaunchAgents"),{recursive:!0}),await Gu(ls(),{recursive:!0,mode:448}),await Jg(e,ds())},tw=async()=>{let e=Do();return e==="darwin"?(await ju($o()),!0):e==="linux"?(await Gu(No(ss(),".config","systemd","user"),{recursive:!0}),await Jg(Mo(),us()),!0):!1},nw=async()=>tw().catch(()=>!1),rO=async(e,t)=>{let n=Do();if(n!=="darwin"&&n!=="linux")return!1;let r=n==="darwin"?$o():Mo(),o=n==="darwin"?ds():us();if(await Zg(r,"utf-8").catch(()=>null)!==o)return!1;let s=await ke(e);return s?.version!==be?!1:typeof s.remoteOrigin=="string"&&je(s.remoteOrigin)===je(t)},Dt=async e=>{if(Ke(Yg()))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 anyray-connect is running from a temporary path (${Yg()}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(rs())return{ok:!1,messages:Po("key-refresh auto-start")};{let n=ft();if(At(n))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 ${or(n)} has no per-user service manager to supervise the daemon.`]}}if(await rO(e.port,e.remoteOrigin))return{ok:!0,messages:["Key-refresh service already current \u2014 left running."]};let t=Do();try{if(t==="darwin"){let n=$o(),r=String(process.getuid?.()??""),o=`${n}.new-${process.pid}`;await Lo(o,{force:!0}).catch(()=>{}),await ju(o),fn("launchctl",["bootout",`gui/${r}`,n]),await Lo(n,{force:!0}).catch(()=>{});try{await eO(o,n)}catch{await ju(n),await Lo(o,{force:!0}).catch(()=>{})}return fn("launchctl",["bootstrap",`gui/${r}`,n]).status===0||fn("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.`,...bc()]}}if(t==="linux"){let n=Mo();return await tw(),fn("systemctl",["--user","daemon-reload"]),fn("systemctl",["--user","enable",`${ar}.service`]),fn("systemctl",["--user","restart",`${ar}.service`]).status!==0?{ok:!1,messages:[`Wrote ${n} but \`systemctl --user restart\` failed.`,...bc()]}:{ok:!0,messages:[`Installed systemd user unit ${n}.`]}}return{ok:!1,messages:bc()}}catch(n){return{ok:!1,messages:[`Could not install the key-refresh service: ${n instanceof Error?n.message:String(n)}`,...bc()]}}},Xu=async(e=Ae,t={})=>{if(await ke(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:{[Yu]:"1"},signal:r.signal})}finally{clearTimeout(o)}}catch{}for(let r=0;r<10&&await ke(e,300)!==null;r++)await new Promise(o=>setTimeout(o,100));return!0},zt=async(e=Ae)=>{let t=Do();await Lo(as(),{force:!0}).catch(()=>{});let n=[],r=rs();try{if(r)n.push(...Po("key-refresh service teardown"));else if(t==="darwin"){let o=$o(),a=String(process.getuid?.()??"");fn("launchctl",["bootout",`gui/${a}`,o]),fn("launchctl",["unload",o]),await Lo(o,{force:!0}),n.push("Removed the launchd key-refresh agent.")}else t==="linux"&&(fn("systemctl",["--user","disable","--now",`${ar}.service`]),await Lo(Mo(),{force:!0}),fn("systemctl",["--user","daemon-reload"]),n.push("Removed the systemd key-refresh unit."))}catch{}try{await Xu(e)&&n.push("Stopped the running key-refresh proxy daemon.")}catch{}return{ok:!0,messages:n}};import{stat as pZ}from"node:fs/promises";import{readFileSync as oO,rmSync as aO,writeFileSync as sO,mkdirSync as iO}from"node:fs";import{join as cO}from"node:path";var Ju=()=>cO(q(),"draining"),rw=e=>{try{iO(q(),{recursive:!0}),sO(Ju(),`${Math.floor(e)}
38
+ `,"utf-8")}catch{}},zu=()=>{try{aO(Ju(),{force:!0})}catch{}},lO=16*6e4,qu=(e=Date.now())=>{let t;try{t=oO(Ju(),"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+lO};import{homedir as np,platform as rp}from"node:os";import{join as Fo}from"node:path";import{mkdir as Qu,readFile as dO,rename as uO,writeFile as Ac,rm as Br}from"node:fs/promises";import{spawnSync as pO}from"node:child_process";var tp=()=>Fo(ls(),"connect-refresh.log"),vc=1800,hs="ai.anyray.connect.refresh",Ur="anyray-refresh",Sc="\\AnyrayConnectKeyRefresh",Ec=hs,ms=Ur,fs=Sc,fO=String(vc/60),op=(e,t)=>{let n=pO(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},ap=()=>Fo(np(),"Library","LaunchAgents",`${Ec}.plist`),sp=()=>Fo(np(),".config","systemd","user"),ow=()=>Fo(sp(),`${ms}.service`),Cc=()=>Fo(sp(),`${ms}.timer`),ep=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),xc=()=>pn(Qn),hO=(e=xc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${ep(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>${Ac}</string>
43
+ <key>Label</key><string>${Ec}</string>
44
44
  <key>ProgramArguments</key>
45
45
  <array>
46
46
  ${r}
47
47
  </array>
48
- <key>StartInterval</key><integer>${bc}</integer>
48
+ <key>StartInterval</key><integer>${vc}</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>${zu(qu())}</string>
53
- <key>StandardErrorPath</key><string>${zu(qu())}</string>
52
+ <key>StandardOutPath</key><string>${ep(tp())}</string>
53
+ <key>StandardErrorPath</key><string>${ep(tp())}</string>
54
54
  </dict>
55
55
  </plist>
56
- `},lO=(e=Cc())=>{let{command:t,args:n}=e;return`[Unit]
56
+ `},mO=(e=xc())=>{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
- `},dO=()=>`[Unit]
64
- Description=Anyray connect gateway key refresh (every ${bc/60}m)
63
+ `},yO=()=>`[Unit]
64
+ Description=Anyray connect gateway key refresh (every ${vc/60}m)
65
65
 
66
66
  [Timer]
67
67
  OnBootSec=5min
68
- OnUnitActiveSec=${bc/60}min
68
+ OnUnitActiveSec=${vc/60}min
69
69
  Persistent=true
70
70
 
71
71
  [Install]
72
72
  WantedBy=timers.target
73
- `,uO=(e=Cc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),ls=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(" ")}`],ew=e=>!e.run&&es(),pO=async(e,t)=>await oO(np(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Ac]).ok,sr=async(e={})=>{let t=e.os??ep(),n=e.invocation??Cc(),r=e.run??tp,o=e.binaryPath??rr();if(Ge(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(ew(e))return{ok:!1,messages:Po("auto-refresh scheduling")};let a=yt(e.env??(e.run?{}:process.env));if(At(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${or(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=np(),i=cO(n);if(await pO(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await Ju(ss(),{recursive:!0,mode:448}),await Ju(Fo(Qu(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await Hr(l,{force:!0}).catch(()=>{}),await gc(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await Hr(s,{force:!0}).catch(()=>{});try{await aO(l,s)}catch{await gc(s,i),await Hr(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.`,...ls(n)]}}if(t==="linux")return await Ju(rp(),{recursive:!0}),await gc(Qg(),lO(n)),await gc(wc(),dO()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${ps}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${wc()}).`]}:{ok:!1,messages:[`Wrote ${wc()} but \`systemctl --user enable --now\` failed.`,...ls(n)]};if(t==="win32"){let s=uO(n);return r("schtasks",["/Create","/TN",ds,"/TR",s,"/SC","MINUTE","/MO",iO,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",ds]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${ds}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...ls(n)]}}return{ok:!1,messages:ls(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...ls(n)]}}},ir=async(e={})=>{await Hr(qu(),{force:!0}).catch(()=>{});let t=e.os??ep(),n=e.run??tp,r=[];if(ew(e))return{ok:!0,messages:Po("scheduler teardown")};try{if(t==="darwin"){let o=np(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Hr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${ps}.timer`]),await Hr(wc(),{force:!0}),await Hr(Qg(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",ds,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},vc=async(e=ep(),t=tp)=>e==="win32"?t("schtasks",["/Query","/TN",ds]).ok:e==="darwin"?t("launchctl",["list",Ac]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${ps}.timer`]).ok:!1;import n1 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 uS}from"node:path";import{readFile as mB,writeFile as pS,chmod as yB,stat as gB,unlink as tS}from"node:fs/promises";import{homedir as Rc,platform as fw}from"node:os";import{join as at}from"node:path";import{execFile as AO}from"node:child_process";import{readFile as CO,readdir as vO}from"node:fs/promises";import{homedir as fO,platform as hO}from"node:os";import{join as Sc}from"node:path";var ot=e=>{let t=fO();switch(hO()){case"darwin":return Sc(t,"Library","Application Support",e);case"win32":return Sc(process.env.APPDATA??Sc(t,"AppData","Roaming"),e);default:return Sc(t,".config",e)}};import{readFile as rw}from"node:fs/promises";import{homedir as Kr,platform as Bo}from"node:os";import{join as Rn,posix as mO,win32 as yO}from"node:path";var fs=["Code","Code - Insiders","VSCodium"],Ec="1.121.0",tw=1,gO=121,ow="1.102.0",nw=1,wO=102,bO={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},xc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},op=e=>{let t=xc(e);return t?t.major!==tw?t.major>tw:t.minor>=gO:!1},aw=e=>{let t=xc(e);return t?t.major!==nw?t.major>nw:t.minor>=wO:!1},kO=async e=>{if(Bo()!=="darwin")return;let t=Rn("/Applications",`${bO[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await rw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},sw=(e,t=Bo(),n=Kr(),r=process.env)=>{switch(t){case"darwin":return Rn(n,"Library","Application Support",e);case"win32":return Rn(r.APPDATA??Rn(n,"AppData","Roaming"),e);default:return Rn(n,".config",e)}},ap=(e,t)=>e?t==="win32"?yO.join:mO.join:Rn,Uo=(e,t=!1,n=Bo(),r=Kr(),o=process.env)=>t?ap(t,n)(r,sp[e],"data","User"):Rn(sw(e,n,r,o),"User"),iw=async(e,t=!1,n=Bo(),r=Kr(),o=process.env)=>{try{let a=ap(t,n)(Uo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await rw(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[]}},cw=async(e,t=Bo(),n=Kr(),r=process.env)=>{let a=(await iw(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},lw=async(e,t=!1,n=Bo(),r=Kr(),o=process.env)=>{let a=ap(t,n),s=Uo(e,t,n,r,o),i=await iw(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Ic=async()=>{for(let e of fs)if(await R(sw(e)))return e},sp={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},dw=(e,t=Kr())=>Rn(t,sp[e],"extensions"),ip=async(e=Kr())=>{for(let t of fs)if(await R(Rn(e,sp[t])))return t},uw=async e=>{let t=e??await Ic();if(!t)return{status:"unknown"};let n=await kO(t);return n?{variant:t,version:n,status:op(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var SO=3e3,EO="Claude Code-credentials",xO=["copilot-cli","CopilotCLI"],hw=e=>new Promise(t=>{try{AO("security",["find-generic-password","-s",e],{timeout:SO},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),IO=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=at(Rc(),".claude");return!!(await R(at(e,".oauth_token"))||await R(at(e,".credentials.json"))||fw()==="darwin"&&await hw(EO))},RO=async()=>{let e=at(process.env.CODEX_HOME?.trim()||at(Rc(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await CO(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},pw=async e=>{try{return(await vO(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},cp=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of fs){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(Rc(),".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 pw(at(Rc(),t,"extensions")))return!0;for(let t of fs){if(await pw(dw(t)))return!0;let n=at(Uo(t,!0),"globalStorage");if(await R(at(n,"github.copilot-chat"))||await R(at(n,"github.copilot")))return!0}if(fw()==="darwin"){for(let t of xO)if(await hw(t))return!0}return!1},Dt=async()=>{let[e,t,n]=await Promise.all([IO(),RO(),cp()]);return{anthropic:e,openai:t,copilot:n}};var _e=async(e=P,t=Dt,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:vn(a,r.fallbackPort),toolOrigin:`http://${ht}:${r.fallbackPort}`}};import{homedir as $O}from"node:os";import{join as $c}from"node:path";import{chmod as MO,readFile as hs,rm as kw,copyFile as FO}from"node:fs/promises";var Gr="# >>> anyray connect >>>",Tc="# <<< anyray connect <<<",lp="# restore: ",mw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Pc=e=>{let t=new RegExp(`\\n*${mw(Gr)}[\\s\\S]*?${mw(Tc)}\\n?`,"g");return e.replace(t,"")},dp=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},Oc=(e,t)=>e.split(t).length-1,yw=e=>Oc(e,"[")-Oc(e,"]"),OO=e=>e.replace(/^['"]|['"]$/g,""),_c=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Oc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+yw(dp(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?OO(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=dp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Oc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+yw(l)))}return t},up=e=>e.findIndex(t=>t.kind==="table"),pp=e=>e.includes(Gr),gw=(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("#")})},fp=(e,t)=>gw(Pc(e),t),hp=e=>{let t=e.indexOf(Gr);if(t<0)return;let n=e.indexOf(Tc,t+Gr.length);if(!(n<0))return e.slice(t,n)},ww=(e,t)=>{let n=e.indexOf(Gr);if(n<0)return!1;let r=e.indexOf(Tc,n+Gr.length);return r<0?!1:gw(e.slice(n,r),t)},mp=(e,t)=>{let r=Pc(e).split(`
75
- `),o=_c(r),a=up(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=dp(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}},Lc=(e,t,n)=>{let r=bw(e),a=Pc(e).split(`
76
- `),s=_c(a),i=up(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 v=s[b];if(b<l&&v.kind==="key"&&c.has(v.key)){u.has(v.key)||u.set(v.key,a[b].trim());continue}d.push(a[b])}let f=_c(d),p=up(f),h=(p===-1?d:d.slice(0,p)).join(`
73
+ `,gO=(e=xc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),ps=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&&rs(),wO=async(e,t)=>await dO(ap(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Ec]).ok,sr=async(e={})=>{let t=e.os??rp(),n=e.invocation??xc(),r=e.run??op,o=e.binaryPath??rr();if(Ke(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:Po("auto-refresh scheduling")};let a=ft(e.env??(e.run?{}:process.env));if(At(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${or(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=ap(),i=hO(n);if(await wO(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await Qu(ls(),{recursive:!0,mode:448}),await Qu(Fo(np(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await Br(l,{force:!0}).catch(()=>{}),await Ac(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await Br(s,{force:!0}).catch(()=>{});try{await uO(l,s)}catch{await Ac(s,i),await Br(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.`,...ps(n)]}}if(t==="linux")return await Qu(sp(),{recursive:!0}),await Ac(ow(),mO(n)),await Ac(Cc(),yO()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${ms}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${Cc()}).`]}:{ok:!1,messages:[`Wrote ${Cc()} but \`systemctl --user enable --now\` failed.`,...ps(n)]};if(t==="win32"){let s=gO(n);return r("schtasks",["/Create","/TN",fs,"/TR",s,"/SC","MINUTE","/MO",fO,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",fs]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${fs}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...ps(n)]}}return{ok:!1,messages:ps(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...ps(n)]}}},ir=async(e={})=>{await Br(tp(),{force:!0}).catch(()=>{});let t=e.os??rp(),n=e.run??op,r=[];if(aw(e))return{ok:!0,messages:Po("scheduler teardown")};try{if(t==="darwin"){let o=ap(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Br(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${ms}.timer`]),await Br(Cc(),{force:!0}),await Br(ow(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",fs,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Ic=async(e=rp(),t=op)=>e==="win32"?t("schtasks",["/Query","/TN",fs]).ok:e==="darwin"?t("launchctl",["list",Ec]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${ms}.timer`]).ok:!1;import c1 from"node:http";import{spawn as wB}from"node:child_process";import{createHash as bB}from"node:crypto";import{homedir as kB}from"node:os";import{join as yS}from"node:path";import{readFile as AB,writeFile as gS,chmod as CB,stat as vB,unlink as sS}from"node:fs/promises";import{homedir as Pc,platform as ww}from"node:os";import{join as nt}from"node:path";import{execFile as IO}from"node:child_process";import{readFile as RO,readdir as OO}from"node:fs/promises";import{homedir as bO,platform as kO}from"node:os";import{join as Rc}from"node:path";var tt=e=>{let t=bO();switch(kO()){case"darwin":return Rc(t,"Library","Application Support",e);case"win32":return Rc(process.env.APPDATA??Rc(t,"AppData","Roaming"),e);default:return Rc(t,".config",e)}};import{readFile as cw}from"node:fs/promises";import{homedir as Hr,platform as Bo}from"node:os";import{join as Rn,posix as AO,win32 as CO}from"node:path";var ys=["Code","Code - Insiders","VSCodium"],Oc="1.121.0",sw=1,vO=121,lw="1.102.0",iw=1,SO=102,EO={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},_c=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},ip=e=>{let t=_c(e);return t?t.major!==sw?t.major>sw:t.minor>=vO:!1},dw=e=>{let t=_c(e);return t?t.major!==iw?t.major>iw:t.minor>=SO:!1},xO=async e=>{if(Bo()!=="darwin")return;let t=Rn("/Applications",`${EO[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await cw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},uw=(e,t=Bo(),n=Hr(),r=process.env)=>{switch(t){case"darwin":return Rn(n,"Library","Application Support",e);case"win32":return Rn(r.APPDATA??Rn(n,"AppData","Roaming"),e);default:return Rn(n,".config",e)}},cp=(e,t)=>e?t==="win32"?CO.join:AO.join:Rn,Uo=(e,t=!1,n=Bo(),r=Hr(),o=process.env)=>t?cp(t,n)(r,lp[e],"data","User"):Rn(uw(e,n,r,o),"User"),pw=async(e,t=!1,n=Bo(),r=Hr(),o=process.env)=>{try{let a=cp(t,n)(Uo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await cw(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[]}},fw=async(e,t=Bo(),n=Hr(),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)},hw=async(e,t=!1,n=Bo(),r=Hr(),o=process.env)=>{let a=cp(t,n),s=Uo(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"))]},Tc=async()=>{for(let e of ys)if(await R(uw(e)))return e},lp={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},mw=(e,t=Hr())=>Rn(t,lp[e],"extensions"),dp=async(e=Hr())=>{for(let t of ys)if(await R(Rn(e,lp[t])))return t},yw=async e=>{let t=e??await Tc();if(!t)return{status:"unknown"};let n=await xO(t);return n?{variant:t,version:n,status:ip(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var _O=3e3,TO="Claude Code-credentials",PO=["copilot-cli","CopilotCLI"],bw=e=>new Promise(t=>{try{IO("security",["find-generic-password","-s",e],{timeout:_O},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),LO=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=nt(Pc(),".claude");return!!(await R(nt(e,".oauth_token"))||await R(nt(e,".credentials.json"))||ww()==="darwin"&&await bw(TO))},DO=async()=>{let e=nt(process.env.CODEX_HOME?.trim()||nt(Pc(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await RO(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},gw=async e=>{try{return(await OO(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},up=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of ys){let n=nt(tt(t),"User","globalStorage");if(await R(nt(n,"github.copilot-chat"))||await R(nt(n,"github.copilot")))return!0}let e=nt(Pc(),".config","github-copilot");if(await R(nt(e,"apps.json"))||await R(nt(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await gw(nt(Pc(),t,"extensions")))return!0;for(let t of ys){if(await gw(mw(t)))return!0;let n=nt(Uo(t,!0),"globalStorage");if(await R(nt(n,"github.copilot-chat"))||await R(nt(n,"github.copilot")))return!0}if(ww()==="darwin"){for(let t of PO)if(await bw(t))return!0}return!1},Nt=async()=>{let[e,t,n]=await Promise.all([LO(),DO(),up()]);return{anthropic:e,openai:t,copilot:n}};var Te=async(e=P,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(!Qe(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:vn(a,r.fallbackPort),toolOrigin:`http://${ut}:${r.fallbackPort}`}};import{homedir as WO}from"node:os";import{join as Uc}from"node:path";import{chmod as KO,readFile as gs,rm as Ew,copyFile as GO}from"node:fs/promises";var Wr="# >>> anyray connect >>>",Nc="# <<< anyray connect <<<",pp="# restore: ",kw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$c=e=>{let t=new RegExp(`\\n*${kw(Wr)}[\\s\\S]*?${kw(Nc)}\\n?`,"g");return e.replace(t,"")},fp=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},Lc=(e,t)=>e.split(t).length-1,Aw=e=>Lc(e,"[")-Lc(e,"]"),NO=e=>e.replace(/^['"]|['"]$/g,""),Dc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Lc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+Aw(fp(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?NO(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=fp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Lc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+Aw(l)))}return t},hp=e=>e.findIndex(t=>t.kind==="table"),mp=e=>e.includes(Wr),Cw=(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("#")})},yp=(e,t)=>Cw($c(e),t),gp=e=>{let t=e.indexOf(Wr);if(t<0)return;let n=e.indexOf(Nc,t+Wr.length);if(!(n<0))return e.slice(t,n)},vw=(e,t)=>{let n=e.indexOf(Wr);if(n<0)return!1;let r=e.indexOf(Nc,n+Wr.length);return r<0?!1:Cw(e.slice(n,r),t)},wp=(e,t)=>{let r=$c(e).split(`
75
+ `),o=Dc(r),a=hp(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=fp(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}},Mc=(e,t,n)=>{let r=Sw(e),a=$c(e).split(`
76
+ `),s=Dc(a),i=hp(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 v=s[b];if(b<l&&v.kind==="key"&&c.has(v.key)){u.has(v.key)||u.set(v.key,a[b].trim());continue}d.push(a[b])}let f=Dc(d),p=hp(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],[v])=>b.localeCompare(v)).map(([,b])=>`${lp}${b}`),g=[Gr,...w,...t,Tc].join(`
78
+ `),w=[...u.entries()].sort(([b],[v])=>b.localeCompare(v)).map(([,b])=>`${pp}${b}`),g=[Wr,...w,...t,Nc].join(`
79
79
  `);return[h.replace(/\s*$/,""),g,m.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
80
80
 
81
81
  `).replace(/\s*$/,"")+`
82
- `},bw=e=>{let t=new Map,n=hp(e);if(n===void 0)return t;for(let r of n.split(`
83
- `)){let o=r.trim();if(!o.startsWith(lp))continue;let a=o.slice(lp.length).trim(),[s]=_c([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Dc=e=>{if(!pp(e))return null;let t=[...bw(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Pc(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
82
+ `},Sw=e=>{let t=new Map,n=gp(e);if(n===void 0)return t;for(let r of n.split(`
83
+ `)){let o=r.trim();if(!o.startsWith(pp))continue;let a=o.slice(pp.length).trim(),[s]=Dc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Fc=e=>{if(!mp(e))return null;let t=[...Sw(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=$c(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 _O}from"node:crypto";import{chmod as TO,mkdir as PO,rm as LO,writeFile as DO}from"node:fs/promises";import{dirname as NO}from"node:path";var he=async(e,t)=>{await PO(NO(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${_O()}`;try{await DO(n,t,{flag:"wx",mode:384}),await fe(n,e),await TO(e,384)}finally{await LO(n,{force:!0}).catch(()=>{})}};var BO="codex",UO="Codex app / CLI / IDE",HO="https://chatgpt.com/backend-api/codex",WO="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",KO="x-anyray-client-context-window",GO="x-anyray-client-auto-compact-limit",Mc=()=>process.env.CODEX_HOME?.trim()||$c($O(),".codex"),jr=()=>$c(Mc(),"config.toml"),Nc=()=>`${jr()}.anyray-bak`,yp=()=>$c(Mc(),"hooks.json"),On=()=>$c(Mc(),"anyray.config.toml"),Aw=e=>To(e,"PostToolUse",mg),Cw=(e,t=!1)=>le({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||BO,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||UO}),st=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,gp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,ms=(e,t={})=>{let n=Cw(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:gp(),i=e.clientKey&&!e.viaLocalProxy,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${st(HO)}`,`"x-anyray-forward-headers" = ${st(WO)}`,...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(`"${KO}" = ${st(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${GO}" = ${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(", ")}]`]:[]]},jO=()=>gp()?["model_provider","model"]:["model_provider"],vw={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=Mc(),t=await R(e);return{installed:t,detail:t?jr():`no ${e} directory`}},async apply(e,t){let n=jr(),r=yp(),o=Cw(e),a=J(e,"openai"),s=gp(),i=ce(),c={},l=await R(r);try{l&&(c=await M(r))}catch(v){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${v instanceof Error?v.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=Aw(c),u=await R(n),f=u?await hs(n,"utf-8"):"";if(fp(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=fp(f,"mcp_servers.anyray"),h=mp(f,"model_context_window"),m=mp(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 Z(r,c,{backup:!1}),await re(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(Nc())&&(await FO(n,Nc()),await MO(Nc(),384),w.push(`Backed up your original config to ${Nc()}.`));let y=i&&!p?je("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=Lc(f,ms(e,{mcpServer:y,modelContextWindow:h,modelAutoCompactTokenLimit:m}),jO());return await he(n,b),g.push(n),await R(On())&&(await kw(On(),{force:!0}),g.push(On()),w.push(`Removed the old opt-in profile ${On()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:g}},async pointsAt(e){let t=jr();if(!await R(t))return!1;try{let n=await hs(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=jr();if(!await R(e))return{registered:!1,command:null};try{let t=await hs(e,"utf-8");if(!ww(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 hs(jr(),"utf-8"),t=hp(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=jr(),n=await R(t),r=await R(On()),o=await R(yp());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=yp(),c;try{c=await M(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.`]}}Aw(c)&&(e.dryRun||(await Z(i,c,{backup:!1}),await re(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=Dc(await hs(t,"utf-8"));i!==null&&(e.dryRun||await he(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 kw(On(),{force:!0}),s.push(On()),a.push(e.dryRun?`would remove the old opt-in profile ${On()}`:`removed the old opt-in profile ${On()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await re(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as zO}from"node:os";import{join as qO}from"node:path";import{readFile as Iw,rm as bp}from"node:fs/promises";import{readFile as VO,writeFile as Sw,access as YO}from"node:fs/promises";import{homedir as ZO}from"node:os";import{join as wp}from"node:path";var XO="# >>> anyray connect >>>",JO="# <<< anyray connect <<<",ys=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:XO,end:JO},Ct=()=>{let e=ZO(),t=process.env.SHELL||"";return t.includes("zsh")?wp(e,".zshrc"):t.includes("bash")?wp(e,".bashrc"):wp(e,".profile")},Fc=async e=>{try{return await YO(e),await VO(e,"utf-8")}catch{return""}},Ew=(e,t)=>{let{begin:n,end:r}=ys(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 $O}from"node:crypto";import{chmod as MO,mkdir as FO,rm as BO,writeFile as UO}from"node:fs/promises";import{dirname as HO}from"node:path";var me=async(e,t)=>{await FO(HO(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${$O()}`;try{await UO(n,t,{flag:"wx",mode:384}),await he(n,e),await MO(e,384)}finally{await BO(n,{force:!0}).catch(()=>{})}};var jO="codex",VO="Codex app / CLI / IDE",YO="https://chatgpt.com/backend-api/codex",ZO="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",XO="x-anyray-client-context-window",JO="x-anyray-client-auto-compact-limit",Hc=()=>process.env.CODEX_HOME?.trim()||Uc(WO(),".codex"),Kr=()=>Uc(Hc(),"config.toml"),Bc=()=>`${Kr()}.anyray-bak`,bp=()=>Uc(Hc(),"hooks.json"),On=()=>Uc(Hc(),"anyray.config.toml"),xw=e=>To(e,"PostToolUse",kg),Iw=(e,t=!1)=>ce({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||jO,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||VO}),rt=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,kp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,ws=(e,t={})=>{let n=Iw(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:kp(),i=e.clientKey&&!e.viaLocalProxy,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${rt(YO)}`,`"x-anyray-forward-headers" = ${rt(ZO)}`,...i?[`"x-anyray-api-key" = ${rt(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${rt(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${rt(n)}`),a&&c.push(`"x-anyray-provider" = ${rt(a)}`),t.modelContextWindow&&c.push(`"${XO}" = ${rt(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${JO}" = ${rt(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 = ${rt(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${rt(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${rt(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>rt(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${rt(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(rt).join(", ")}]`]:[]]},zO=()=>kp()?["model_provider","model"]:["model_provider"],Rw={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=Hc(),t=await R(e);return{installed:t,detail:t?Kr():`no ${e} directory`}},async apply(e,t){let n=Kr(),r=bp(),o=Iw(e),a=J(e,"openai"),s=kp(),i=se(),c={},l=await R(r);try{l&&(c=await M(r))}catch(v){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${v instanceof Error?v.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=xw(c),u=await R(n),f=u?await gs(n,"utf-8"):"";if(yp(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=yp(f,"mcp_servers.anyray"),h=wp(f,"model_context_window"),m=wp(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 Z(r,c,{backup:!1}),await re(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(Bc())&&(await GO(n,Bc()),await KO(Bc(),384),w.push(`Backed up your original config to ${Bc()}.`));let y=i&&!p?Ge("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 (${_e()}). Re-run via the installer or a global install to enable retrieval.`);let b=Mc(f,ws(e,{mcpServer:y,modelContextWindow:h,modelAutoCompactTokenLimit:m}),zO());return await me(n,b),g.push(n),await R(On())&&(await Ew(On(),{force:!0}),g.push(On()),w.push(`Removed the old opt-in profile ${On()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:g}},async pointsAt(e){let t=Kr();if(!await R(t))return!1;try{let n=await gs(t,"utf-8"),r=`base_url = ${rt(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){let e=Kr();if(!await R(e))return{registered:!1,command:null};try{let t=await gs(e,"utf-8");if(!vw(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 gs(Kr(),"utf-8"),t=gp(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=Kr(),n=await R(t),r=await R(On()),o=await R(bp());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=bp(),c;try{c=await M(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.`]}}xw(c)&&(e.dryRun||(await Z(i,c,{backup:!1}),await re(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=Fc(await gs(t,"utf-8"));i!==null&&(e.dryRun||await me(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 Ew(On(),{force:!0}),s.push(On()),a.push(e.dryRun?`would remove the old opt-in profile ${On()}`:`removed the old opt-in profile ${On()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await re(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as r_}from"node:os";import{join as o_}from"node:path";import{readFile as Pw,rm as Cp}from"node:fs/promises";import{readFile as qO,writeFile as Ow,access as QO}from"node:fs/promises";import{homedir as e_}from"node:os";import{join as Ap}from"node:path";var t_="# >>> anyray connect >>>",n_="# <<< anyray connect <<<",bs=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:t_,end:n_},Ct=()=>{let e=e_(),t=process.env.SHELL||"";return t.includes("zsh")?Ap(e,".zshrc"):t.includes("bash")?Ap(e,".bashrc"):Ap(e,".profile")},Wc=async e=>{try{return await QO(e),await qO(e,"utf-8")}catch{return""}},_w=(e,t)=>{let{begin:n,end:r}=bs(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)},Bc=async(e,t,n)=>{let r=await Fc(e),{begin:o,end:a}=ys(n),s=Ew(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
89
+ `&&(i+=1),e.slice(0,s)+e.slice(i)},Kc=async(e,t,n)=>{let r=await Wc(e),{begin:o,end:a}=bs(n),s=_w(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 Sw(e,c),e},Uc=async(e,t)=>{let n=await Fc(e),{begin:r,end:o}=ys(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)},xw=async(e,t)=>(await Fc(e)).includes(ys(t).begin),gs=async(e,t)=>{let n=await Fc(e);return n.includes(ys(t).begin)?(await Sw(e,Ew(n,t).replace(/\s*$/,"")+`
96
- `),!0):!1};var Nt=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 Se=e=>`'${e.replace(/'/g,"'\\''")}'`,QO=e=>{let t=Se(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},Rw=(e,t,n,r)=>{let a=e.viaLocalProxy===!0?e.placeholderKey:t;return[`export OPENAI_BASE_URL=${Se(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${Se(a)}`],`export ANTHROPIC_BASE_URL=${Se(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${Se(a)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]]},e_=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],t_=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],kp=()=>qO(zO(),".anyray","shell-env.sh"),_w="# Managed by anyray-connect. Do not source this file anywhere else.",Ow=e=>e.split(/\r?\n/,1)[0]===_w,Ap=e=>t_.some(t=>e.startsWith(`export ${t}=`)),Tw=(e,t=process.env)=>Cp([e],t),Cp=(e,t=process.env)=>e.some(r=>t.ANTHROPIC_BASE_URL===r.anthropicBaseUrl||t.OPENAI_BASE_URL===r.openaiBaseUrl)?e_.filter(r=>(t[r]??"")!==""):[],Pw={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=Ct();return{installed:!0,detail:await R(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await Uc(Ct());return e?e.some(n=>Ap(n)||n.includes(kp()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=Ct(),r=J(e,"openai"),o=J(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=Rw(e,s,r,o),c=i.filter(Ap),l=i.filter(b=>!Ap(b)),d=kp(),u=fg(),f=[QO(u),...l,...c.length>0?[`[ -r ${Se(d)} ] && . ${Se(d)}`]:[]],p=e.clientKey?Rw(e,Nt(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 Iw(d,"utf8"):void 0,y=g===void 0||Ow(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 he(d,[_w,...c,""].join(`
97
- `)):w&&y&&await bp(d,{force:!0}),await Bc(n,f)}catch(b){try{g!==void 0&&y?await he(d,g):y&&await bp(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=Ct(),n=kp(),r=await R(n),o=r?Ow(await Iw(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 gs(t);o&&await bp(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 $_}from"node:child_process";import{closeSync as M_,copyFileSync as F_,existsSync as Ee,mkdirSync as B_,openSync as U_,readFileSync as db,readSync as H_,renameSync as W_,rmSync as hn,writeFileSync as Mp}from"node:fs";import{homedir as ub,platform as K_}from"node:os";import{dirname as pb,join as Go,resolve as G_}from"node:path";import{isIP as _p}from"node:net";import{execFileSync as Kc}from"node:child_process";import{mkdtempSync as n_,rmSync as r_,writeFileSync as o_}from"node:fs";import{createRequire as a_}from"node:module";import{tmpdir as s_}from"node:os";import{join as Lw}from"node:path";var ws=class extends Error{},bs=e=>e instanceof ws?`: ${e.message}`:"",Dw=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new ws("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new ws(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},Nw=()=>{try{return Kc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Sp=64*1024*1024,i_=Sp*2+64,Wc=e=>`'${e.replace(/'/g,"''")}'`,c_=(e,t)=>Kc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:i_,stdio:["ignore","pipe","pipe"]}),l_=(e,t)=>Kc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Sp,stdio:["pipe","pipe","pipe"]}),$w=(e,t,n=c_)=>{let r=Wc(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 Ow(e,c),e},Gc=async(e,t)=>{let n=await Wc(e),{begin:r,end:o}=bs(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)},Tw=async(e,t)=>(await Wc(e)).includes(bs(t).begin),ks=async(e,t)=>{let n=await Wc(e);return n.includes(bs(t).begin)?(await Ow(e,_w(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 Se=e=>`'${e.replace(/'/g,"'\\''")}'`,a_=e=>{let t=Se(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},Lw=(e,t,n,r)=>{let a=e.viaLocalProxy===!0?e.placeholderKey:t;return[`export OPENAI_BASE_URL=${Se(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${Se(a)}`],`export ANTHROPIC_BASE_URL=${Se(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${Se(a)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]]},s_=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],i_=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],vp=()=>o_(r_(),".anyray","shell-env.sh"),Nw="# Managed by anyray-connect. Do not source this file anywhere else.",Dw=e=>e.split(/\r?\n/,1)[0]===Nw,Sp=e=>i_.some(t=>e.startsWith(`export ${t}=`)),$w=(e,t=process.env)=>Ep([e],t),Ep=(e,t=process.env)=>e.some(r=>t.ANTHROPIC_BASE_URL===r.anthropicBaseUrl||t.OPENAI_BASE_URL===r.openaiBaseUrl)?s_.filter(r=>(t[r]??"")!==""):[],Mw={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=Ct();return{installed:!0,detail:await R(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await Gc(Ct());return e?e.some(n=>Sp(n)||n.includes(vp()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=Ct(),r=J(e,"openai"),o=J(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=Lw(e,s,r,o),c=i.filter(Sp),l=i.filter(b=>!Sp(b)),d=vp(),u=wg(),f=[a_(u),...l,...c.length>0?[`[ -r ${Se(d)} ] && . ${Se(d)}`]:[]],p=e.clientKey?Lw(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 R(d),g=w?await Pw(d,"utf8"):void 0,y=g===void 0||Dw(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 me(d,[Nw,...c,""].join(`
97
+ `)):w&&y&&await Cp(d,{force:!0}),await Kc(n,f)}catch(b){try{g!==void 0&&y?await me(d,g):y&&await Cp(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=Ct(),n=vp(),r=await R(n),o=r?Dw(await Pw(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 ks(t);o&&await Cp(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 W_}from"node:child_process";import{closeSync as K_,copyFileSync as G_,existsSync as Ee,mkdirSync as j_,openSync as V_,readFileSync as mb,readSync as Y_,renameSync as Z_,rmSync as hn,writeFileSync as Up}from"node:fs";import{homedir as yb,platform as X_}from"node:os";import{dirname as gb,join as Go,resolve as J_}from"node:path";import{isIP as Lp}from"node:net";import{execFileSync as Yc}from"node:child_process";import{mkdtempSync as c_,rmSync as l_,writeFileSync as d_}from"node:fs";import{createRequire as u_}from"node:module";import{tmpdir as p_}from"node:os";import{join as Fw}from"node:path";var As=class extends Error{},Cs=e=>e instanceof As?`: ${e.message}`:"",Bw=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new As("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new As(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},Uw=()=>{try{return Yc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Ip=64*1024*1024,f_=Ip*2+64,Vc=e=>`'${e.replace(/'/g,"''")}'`,h_=(e,t)=>Yc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:f_,stdio:["ignore","pipe","pipe"]}),m_=(e,t)=>Yc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Ip,stdio:["pipe","pipe","pipe"]}),Hw=(e,t,n=h_)=>{let r=Vc(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")},Mw=(e,t=l_)=>{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")},Ww=(e,t=m_)=>{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??"");Dw(o?.slice(1).map(Number))},d_=(e,t)=>{let n=n_(Lw(s_(),"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=${Wc(a.key)};`;let i=Lw(n,`value-${s}`);return o_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${Wc(a.key)}, CAST(readfile(${Wc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
103
- `);Kc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Sp,stdio:["pipe","ignore","pipe"]})}finally{try{r_(n,{recursive:!0,force:!0})}catch{}}},u_={kind:"sqlite3-cli",readItem:(e,t)=>$w(e,t),checkpointWal:e=>Mw(e),mutateRows:d_},p_=()=>{try{let t=a_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},vp=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},f_=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),h_=e=>({kind:"node-sqlite",readItem:(t,n)=>vp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:f_(o.value)}),checkpointWal:t=>vp(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);Dw(o)}),mutateRows:(t,n)=>vp(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}})}),Hc,ks=()=>{if(Hc!==void 0)return Hc;let e=p_();return Hc=e?h_(e):Nw()?u_:null,Hc};import{spawn as m_}from"node:child_process";import{randomUUID as Fw}from"node:crypto";import{constants as Bw}from"node:fs";import{chmod as y_,copyFile as Uw,mkdir as g_,readdir as w_,readFile as b_,rename as k_,rm as As,writeFile as A_}from"node:fs/promises";import{join as Ep}from"node:path";var xp=/^[a-z0-9][a-z0-9-]{0,31}$/,C_=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,Hw=/^[a-z0-9][a-z0-9-]{0,31}$/,v_=/^[0-9TZ:.+-]{1,40}$/,Ip=()=>Ep(q(),"pending"),jc=e=>{if(!xp.test(e)||C_.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Ep(Ip(),`${e}.json`)},Ww=()=>Ep(q(),"cursor-pending.json"),S_=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),E_=(e,t)=>{if(!S_(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!xp.test(n)||typeof e.op!="string"||!Hw.test(e.op)||typeof e.requestedAt!="string"||!v_.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}:{}}},Rp=async(e,t)=>{try{return E_(JSON.parse(await b_(e,"utf-8")),t)}catch{return}},Kw=async()=>{let e=Ww(),t=await Rp(e,"cursor");if(!t)return;let n=!1;try{await Gw(),await Uw(e,jc("cursor"),Bw.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await As(e,{force:!0})}catch{}return t},Vc=async e=>{let t=await Rp(jc(e),e);return t||(e==="cursor"?Kw():void 0)},cr=async()=>{let e;try{e=await w_(Ip())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!xp.test(r))continue;let o=await Vc(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await Kw();n&&t.push(n)}return t},Gw=async()=>{await kt();let e=Ip();await g_(e,{recursive:!0,mode:448});try{await y_(e,448)}catch{}},Gc=async e=>{await Gw();let t=jc(e.adapter),n=`${t}.${process.pid}.tmp`;await A_(n,`${JSON.stringify(e)}
104
- `,{mode:384}),await fe(n,t)},x_=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,lr=async(e,t)=>await Op(e,t)==="claimed",Op=async(e,t)=>{let n=jc(e);if(t){let o=`${n}.${process.pid}.${Fw()}.claimed`;try{await k_(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Rp(o,e);if(a&&x_(a,t))return await As(o,{force:!0}),"claimed";let s=!1;try{await Uw(o,n,Bw.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await As(o,{force:!0})}return"superseded"}let r=!1;try{await As(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await As(Ww(),{force:!0})}catch{}return r?"claimed":"absent"},dr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},I_=e=>{let{command:t,args:n}=pn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},R_=e=>{let{exe:t,args:n}=I_(e),r=m_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},jw=R_;var Vw=async()=>{let e=[],t;try{t=await cr()}catch{return e}for(let n of t)if(!dr(n.watcherPid))try{let r=jw(n.adapter);if(!r)continue;await Gc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},Cs=async(e,t)=>{if(!Hw.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await Vc(e),r=new Date().toISOString(),o=Fw();if(n&&dr(n.watcherPid))return await Gc({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await Gc({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=jw(e)}catch{a=void 0}return a&&await Gc({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as O_,spawnSync as Zw}from"node:child_process";import{existsSync as Yc}from"node:fs";import{homedir as __,platform as ur}from"node:os";import{join as Xw,win32 as Yw}from"node:path";var Jw=(e,t={})=>{let n=t.env??process.env,r=t.exists??Yc,o=(t.home??__)(),a={localAppData:n.LOCALAPPDATA??Yw.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=Yw.join(i,s.path);if(r(c))return c}},Vr=/^[A-Za-z0-9 ._-]{1,64}$/,T_=/^[A-Za-z0-9.-]{1,128}$/,Zc=e=>e.darwinBundleId&&T_.test(e.darwinBundleId)?e.darwinBundleId:void 0,zw=(e,t=ur())=>t==="darwin"?Zc(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",qw=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",Qw=(e,t=ur(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return Jw(e,r)!==void 0;let o=e.linuxProcess;return!o||!Vr.test(o)?!1:n.split(":").filter(Boolean).some(a=>Yc(Xw(a,o)))},eb=(e,t=ur())=>{if(t==="darwin"&&Zc(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Vr.test(n))},tb=1e4,vs=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=Xw(t,"System32",e);return Yc(n)?n:e},P_=e=>{let t=`/usr/bin/${e}`;return Yc(t)?t:e},L_=(e,t)=>{try{let n=Zw(e,t,{encoding:"utf-8",timeout:tb,windowsHide:!0,...ur()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:ur()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},D_=e=>new Promise(t=>setTimeout(t,e)),nb=(e,t={})=>{let n=t.runtimePlatform??ur(),r=t.run??L_;if(n==="darwin"){let a=Zc(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||!Vr.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||!Vr.test(a)?!1:r(vs("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(P_("pkill"),["-TERM","-o","-x",o])},rb=async(e,t=2e4,n={})=>{let r=n.sleep??D_,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},N_=(e,t,n={})=>{let r=ur();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=Zw(e,t,{stdio:"ignore",timeout:tb,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=O_(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??ur(),r=t.launch??N_;if(n==="darwin"){let a=Zc(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Vr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=Jw(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(o,[])};var j_={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"}]},V_=e=>e==="apply"||e==="native"||e==="revert",fb=()=>ot("Cursor"),Yr=()=>Go(fb(),"User","globalStorage","state.vscdb"),Es=()=>`${Yr()}.anyray-bak.json`,Ko=()=>`${Yr()}.anyray-bak`,Xe="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",ct="cursorAuth/openAIKey";var Pp="/seat/cursor",Fp="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.",Ss=Go(".cursor","rules","anyray.mdc"),hb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",Y_=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",hb,"",Fp,""].join(`
105
- `),Z_=e=>{let t=G_(e);for(;;){if(Ee(Go(t,".git")))return t;let n=pb(t);if(n===t)return null;t=n}},X_=e=>e.authMode!=="placeholder",zt=()=>Go(ub(),".cursor","hooks.json"),qt=()=>Go(ub(),".cursor","mcp.json"),$t="anyray",mb="--anyray-owner=cursor-v1",J_="postToolUse",z_="beforeSubmitPrompt",ab="preToolUse",q_="^MCP:",Q_="UserPromptSubmit",eT="Shell",tT="^(Read|Grep)$",Qc="--anyray-owner=cursor-hook-v1",Zr=[{event:J_,flag:Ze,trailingArgs:["cursor"],matcher:q_},{event:z_,flag:qn,trailingArgs:[],matcher:Q_},{event:ab,flag:yg,trailingArgs:[],matcher:eT},{event:ab,flag:gg,trailingArgs:[],matcher:tT}];var sb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},nT=(e,t,n)=>$_(e,t,n),ib=nT,rT,oT=()=>{let e=rT??K_();if(e==="win32"){let t=ib(vs("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],sb);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=ib("pgrep",["-x",t],sb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},aT=oT,zc=()=>aT();var sT=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Xe)??null,openAIKey:e.readItem(n,ct)??null,lastWritten:r};Mp(t,`${JSON.stringify(o,null,2)}
106
- `,{encoding:"utf-8",flag:"wx",mode:384})},yb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Mp(n,`${JSON.stringify(t,null,2)}
107
- `,{encoding:"utf-8",flag:"wx",mode:384});try{W_(n,e)}catch(r){throw hn(n,{force:!0}),r}},iT=(e,t)=>{let n=Ho(e);yb(e,{...n,lastWritten:t})},ne=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),cb=e=>ne(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Ho=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(ne(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||ne(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(!ne(n)||n.version!==1||!ne(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Xe],o=n.rows[ct];if(!cb(r)||!cb(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=U_(e,"r");try{return H_(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{M_(n)}},cT=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return ne(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var gb=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(".")&&_p(t)===0||t==="0.0.0.0")return!0;if(_p(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(_p(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 gb(`${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},Lp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!gb(t.hostname)}catch{return!1}},lT=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},dT=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Ye(e.origin)}/v1${Pp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Pp}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),Wo=(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."],wb=()=>{let e=Yr();if(!Ee(e))return"clear";let t=ks();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 ne(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},uT=(e,t)=>{if(!Lp(e))return{routed:!1,problem:"gateway-not-public-https"};let n=Yr();if(!Ee(n))return{routed:!1,problem:"state-db-missing"};let r=ks();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(!ne(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ye(e)}/v1${Pp}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ie(a)||!Ie(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},pT=(e,t=[])=>({command:Tt(e,[...t,Qc])}),Bp=(e,t,n)=>{if(!ne(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Tt(t,[...n,Qc])||r===Tt(t,n)||r.endsWith(` ${Qc}`)&&r.includes(` ${t} `)},fT=(e,t)=>ne(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),bb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Bp(a,t,n)){r=!0;continue}if(!ne(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!fT(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}},Up=(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},kb=(e,t,n,r,o)=>ne(e.hooks)&&Up(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Bp(a,n,r)),hT=(e,t,n,r,o)=>ne(e.hooks)&&Up(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Bp(a,n,r)&&ac(a.command,n,[...r,Qc])),Ab=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!ne(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=ne(e.hooks)?{...e.hooks}:{},{entries:s}=bb(Up(a,t),n,r);return s.push({...pT(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},mT=(e,t,n,r=[])=>{if(!ne(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=bb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},yT=async()=>{let e=zt();if(!ce()){let t=await vb();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 M(e);for(let n of Zr)t=Ab(t,n.event,n.flag,n.trailingArgs,n.matcher);return await Z(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}}},qc=()=>{let e=je("profile");return{command:e.command,args:[...e.args,mb]}},Dp=e=>ne(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===qc().command&&e.args.length===qc().args.length&&e.args.every((t,n)=>t===qc().args[n]),gT=e=>{if(!ne(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")||Ge(e.command))return!1;let t=e.args;if(t.at(-2)!==er||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!Ge(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},el=e=>ne(e)&&Array.isArray(e.args)&&e.args.at(-1)===mb||gT(e),wT=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,bT=async()=>{if(!ce())return Cb();let e=qt();try{let t=await M(e);if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?{...t.mcpServers}:{},r=n[$t];return r!==void 0&&!el(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${$t} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[$t]=qc(),await Z(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}}},Cb=async()=>{let e=qt();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!ne(t.mcpServers)||!($t in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!el(t.mcpServers[$t]))return{changedFiles:[],messages:[`Preserved the foreign ${$t} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[$t];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await Z(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}}},vb=async()=>{let e=zt();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e),n=t;for(let r of Zr)n=mT(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await Z(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}}},kT=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=Z_(e);if(!n)return t;let r=Go(n,Ss),o=Y_();try{if(Ee(r)){let a=db(r,"utf8");if(a===o)return t;if(!a.includes(hb))return{...t,messages:[`Left ${Ss} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Fp}"`]}}return B_(pb(r),{recursive:!0}),Mp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Ss} 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 ${Ss} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Sb=async()=>{let e=await yT(),t=await bT(),n=await kT();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Np=async()=>{let e=await vb(),t=await Cb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Eb=async()=>{if(!ce()){let e=await Np();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 M(zt());for(let r of Zr)e=Ab(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(qt());if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?t.mcpServers[$t]:void 0;return n!==void 0&&!el(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${qt()} already contains a foreign ${$t} 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 ${zt()} and ${qt()}, then re-run Connect.`],complete:!1}}},AT=async()=>{if(!ce())return!1;try{let e=await M(zt());if(!ne(e.hooks)||!Zr.every(r=>kb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(qt()),n=ne(t.mcpServers)?t.mcpServers[$t]:void 0;return Dp(n)}catch{return!1}},xb=["openAIBaseUrl","useOpenAIKey"],xs=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!ne(t))throw new Error("Cursor application-user settings are not an object");return t},CT=(e,t,n)=>{let r=xs(e),o=xs(t??void 0),a=n===void 0?void 0:xs(n),s={...r},i=[];for(let c of xb){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}},Tp=(e,t)=>{let n=xs(e),r=xs(t??void 0),o={...n};for(let a of xb)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)}},Xc=e=>typeof e=="string"&&e.startsWith("ark_"),Jc=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ne(o)&&(n=o)}catch{}let r=Xc(t)||n!==null&&(Xc(n.useOpenAIKey)||Xc(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,Xc(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.",...Wo(e)];let n=le(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.",...Wo(e)]},$p=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ce())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 Cs("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]}},vT=async(e,t)=>{if(!Ie(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 lr("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 Eb();if(!n.complete)return{status:"manual",messages:n.messages};let r=Ee(Es())||Ee(Ko());if(r&&zc())return $p("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=wb();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 ${Ee(Ko())?Ko():Es()}, 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 ${zt()}, and register the Anyray retrieval MCP server in ${qt()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Is.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 Sb(),s=[];if(!t.preservePendingOp)try{await lr("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 -- "${Fp}" (connect already writes ${Ss} 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."]}},Is={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>zc(),quitTarget:j_,needsTarget:e=>e!=="revert",async complete(e,t,n){return V_(e)?e!=="revert"&&t?Is.apply(t,n):Is.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=fb(),t=Ee(e);return{installed:t,detail:t?Yr():"Cursor user dir not found"}},async watchPaths(){return[zt(),qt()]},async mcpStatus(){let e=qt();if(!await R(e))return{registered:!1,command:null};try{let t=await M(e),n=ne(t.mcpServers)?t.mcpServers[$t]:void 0;return Dp(n)?{registered:!0,command:wT(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=zt();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!ne(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=>kb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Zr.every(c=>hT(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=qt();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!ne(s.mcpServers))r="unreadable";else{let i=s.mcpServers[$t];r=i===void 0?"missing":el(i)?"owned":"foreign",r==="owned"&&(o=Dp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Mr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await P();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(X_(e))return vT(e,t);let n=dT(e),r=lT(e.openaiBaseUrl),o=Yr(),a=Es(),s=Ko();if(!Ie(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(!Lp(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.",...Wo(n)]});let l=await Eb();if(!l.complete)return{status:"manual",messages:l.messages};let d=ks();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(!Ee(o))return c({status:"manual",messages:it(n,`No Cursor state DB at ${o} (open Cursor once first).`)});let u=null,f;if(Ee(s)){if(Ee(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":(Ho(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(Ee(a))try{p=Ho(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(zc())return c(await $p("apply",t,{status:"manual",messages:it(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Wo(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}, ${Ee(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 ${zt()}, and register the Anyray retrieval MCP server in ${qt()}.`,...Wo(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}${bs(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=Jc(d.readItem(s,Xe)??null,d.readItem(s,ct)??null);else{let b=Ho(s);y=Jc(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,[Tp(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{hn(s,{force:!0}),hn(`${s}-wal`,{force:!0}),hn(`${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}${bs(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=cT(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(Ee(a))try{iT(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{sT(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{yb(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 Sb();let g=[];if(!t.preservePendingOp)try{await lr("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,...Wo(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await P().catch(()=>{}),n=e;if(!Lp(n)){let o=t&&nt(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&Ye(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Ee(Es())||Ee(Ko())||wb()!=="clear"?!1:AT():uT(n,r).routed},async revert(e){let t=Yr(),n=Es(),r=Ko(),o=Ee(n),a=Ee(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 ${zt()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${zt()} and unregister its owned retrieval MCP server.`]};if((o||a)&&zc()){if(e.fullRevert){let h=await Np(),m=!0;try{await lr("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 $p("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=ks(),i=!1,c=!1,l,d=[];if(a)try{if(lb(r))if(Ee(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=Jc(s.readItem(r,Xe)??null,s.readItem(r,ct)??null);s.mutateRows(t,[Tp(s.readItem(t,Xe),h.applicationUser),h.openAIKey===null?{key:ct}:{key:ct,value:h.openAIKey}]),c=!0}else i=!0,F_(r,t),hn(`${t}-wal`,{force:!0}),hn(`${t}-shm`,{force:!0});else{let h=Ho(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ee(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=Jc(h.applicationUser,h.openAIKey);s.mutateRows(t,[Tp(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}${bs(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Ho(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(!Ee(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=CT(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}${bs(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{hn(r,{force:!0}),hn(`${r}-wal`,{force:!0}),hn(`${r}-shm`,{force:!0}),hn(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 lr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await Np();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 tP,mkdir as nP,readFile as zb,rm as rP,writeFile as oP}from"node:fs/promises";import{randomUUID as aP}from"node:crypto";import{dirname as sP,join as qb}from"node:path";var ST=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},ET=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},pr=e=>JSON.parse(ET(ST(e)));import{spawnSync as xT}from"node:child_process";import{platform as IT}from"node:os";var Ib={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},RT=(e,t,n)=>xT(e,t,n),Rb=RT,OT,_T=()=>{let e=OT??IT();if(e==="win32"){let n=Rb(vs("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],Ib);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=Rb("pgrep",[n,r],Ib);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},TT=_T,Rs=()=>TT();var tl={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 PT}from"node:child_process";import{readdirSync as LT}from"node:fs";import{createHash as Pb,randomBytes as DT,randomUUID as Lb}from"node:crypto";import{chmod as NT,lstat as $T,mkdir as Wp,readFile as Jr,rm as Db,unlink as Nb,writeFile as Kp}from"node:fs/promises";import{homedir as Vo,platform as Gp}from"node:os";import{dirname as $b,join as Os,posix as _b,win32 as MT}from"node:path";import{promisify as FT}from"node:util";var _n="0.1.21";var Xr="8c2875844439f1b8a906d1b16e85cfc04f559096f7af88f6b9a26d877eee1c82",nl="22be5f6ea9b3bf833982e1be741254dba1c37395e5b133caa071fbc3d91efdcc",Ob="UEsDBBQAAAgIAHwuCl3s2NkrBwMAALQJAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGcoqXlU+GsNhAUOxEqBQrk+hhgRI5WE1MkweHKUn99sbv6spKmlV3ktsuZeY/zwUfm79dLK1YYmbzryW52JQU67Q25sierNO/8Lt8Xlxf5BPQjlDgGR3PkJB52IdfZVR20XlrHPblIKdwoxXqBS+BsSTp69vOUab9UBldofcCoVrzutD7q+qrb3YbfmBcAdAwyla7FKS4vLvIxJjCQoP65yIcGXaK0ESNwZQUl9iS6zp9TKYamJ8FtImw6K9beoDxkdZV1s+uuFJNqZokXGHeuUqgW9wNxsLD5DEss+o1JzH0UD1Mx8AZzdWxvA5B1pJDIuzrdGw6gsSdDRMa4Qln0jRG4DpY0JbGFLCHhE2zE0hu0LHzcGjpPEUJAIwY+kPVJcDU7wG+90yL6qlzs9vQGgud3LPx8TprACrutSKfxFyH6FRmMoj8ZZrk62m+bwD2UXDyP4Vw1q419AAlLHwm56A/fjkEvyKEYIURHrszVkb3x/wjWYtzc2RqhKbTO1bPF2q1xncS662kXul/YNE0c74fkgbgCO02VIZ/VOWe3riRXdxZshT35tZt1r5spV2cjrRO6ejo+YEBn0GlC3gO/BrA+W/8L0B/kzB7oycfHZsbeVvQC0JHXYOkvNLtz87pcHcwsmn6gOsQz2B/AnZ026iohD9qj24KlWOELAKcYV6SRsxG5R86mvor6AFqLEt8oVVJaVLNGilo1+PRFLb3zEYPPSkrnFeaE8yMmThATml/MS+lTNfu1nNMqBB/TWaSKmKt6Cl/B24jRWay/RQSzPBmpF/C3Vb6zsPIRzRjio/FP7sdjex7ywLuELmWTSJpcuYe8i4hSFZfPt52rEy3NR6TRMRa4UxE1Gg5uP09vs7ROudqZt1qcq+PrNR86TmAtHG6J45V7iCWmfzvIskk7V6dY+bHQtj59ZkzbfTff4n4T8OcysXuySDGBtOjJQ56hfdNk39g7KfrGRGSudep5P/4L03fd2Jbte9Kj4v4zZ672mebq5OlV/A1QSwMEFAAACAgAfC4KXd+jDd+8AAAAZQEAABMAAABbQ29udGVudF9UeXBlc10ueG1sfdAxbsMwDAXQPacQuMd0OxRBYTtD2hv0AoRCO0olSjAZQ7194WQL6s7873+A3bGm6BaeNWTp4aVpwbH4fA4y9XCzcX+A47Drvn4Kq6spivZwMSvviOovnEibXFhqimOeE5k2eZ6wkP+mifG1bd/QZzEW29vaAUP3wSPdornPaiyP3eaq4E6P3DrVA5USgycLWfBKC6mfQzHALZ7lv4L1vEGt2pM0roYlUtg0i4aaSMLI+ieuKa4U718bdr9QSwMEFAAICAgAWy0KXQAAAAAAAAAAAAAAABYAAABleHRlbnNpb24vcGFja2FnZS5qc29udVTbbtQwEH3frxjlBQmIs7vluk9UpYgKiorK5YEWyWtPk6FZ27Ine1HVf0d2vMkWlackc87MnLnlbgJQGLnCYgGFNDsvd+U6KKuxeB4hTcG1cvclM44TA26shx+XcDLSMChPjsmaRNMacOtaUsSQfWrJuJE7WFmNbQDrM1BuvHQONZxYR61lCN1yCLZnc+NtVzf7pE8C2JsbUiRbaKWpO1ljmajgvF2TRg/HF2eiF7dGH7KwqZiJ+aw3O09rybEs9h32pm7ZUmjQj93ouS0pNCG14PzsW2/z6Gwgtn5XLOBuAgBQ8M4lUk2cSABF59tsedYwu7Coqpq46ZZC2VXVJ/n4tVpZY2NEceCqyaPKCYp+KiVuGU0qZwJwn4SgqclgGFXkAS6g+D0Ts/lMTEeykoy19ZT4v3r+8dk+47lUDRmEzyi9IVNHv+vkt5KUOigqTYGrQYb4E/p2DJZPZPQYe2P9bXBS4dAPGoMq6eSSWmI6lN8Z9l1g1D/3viMIUITOOesZdZ5cst8PBUrFca5kzekaDR+Uac0lS8+d+0AmTlnvJVnz3R+qsoY9LTs+FLVfs/O4ZSeN5Iu8aGMCGDSmpTPa/rtHGXv0qIqM36fn9VBPfwsHSpYdtbH2wliNgCF9i1WeQ9xiqW5ljYt1oG3eHIRshLI0ttTo0Gg0ijBAWdqO4cHti+Saw20kq+axfFCWPfZ8XH7VoLqNZA4q5TpdjfvMGHgIVJa0inMEDlsoy4jBVRG8quJr9VTEh+BwVezde20L5zHf6X9EOW91p/jBjWhcvz8oeuzmu6g6VCYfzPxV/EPsM2ZwvKd4TlMxHfAeiYQEH4m3o3MW1f925m/EbGhDSGN5IeZH4uVh8/pRR+y1mIp5Uj+5n/wFUEsHCOw4L8eaAgAApAUAAFBLAwQUAAgICABbLQpdAAAAAAAAAAAAAAAAFQAAAGV4dGVuc2lvbi9MSUNFTlNFLnR4dF1RQW7bMBC88xWDnFJASIsceuiNkWiLqEwaFB3XR1qiIxYyaYh0A/++oOwkTU8Ed3dmdmZXXKNxnfXRElKG02VyL0PCffcFj98ev4P6y2QuhKztdHQxuuDhIgY72f0FL5PxyfYFDpO1CAd0g5lebIEUYPwFJzvF4BH2yTjv/AsMunC6kHBAGlxEDIf0aiYL43uYGEPnTLI9+tCdj9Ynk7LewY024j4NFnftDXH3ZRbprRmJ88i9txZeXRrCOWGyMU2uyxwFnO/Gc593eGuP7uhuChk++44kBZyjLeY9CxxD7w75tbOt03k/ujgU6F2m3p+TLRBzcQ6wyD6+hgnRjiPpwsnZiNnrx3bzTF79lANNt4hirrwO4fjZiYvkcJ68i4OdMX1ADLPib9ulXMnjhzCO4TVb64LvXXYUfxCiBwuzD3/s7OV6Vh+S665xzwc4fVz11oqDGUfs7S0w28N5mH/sTFk+JuOTMyNOYZr1/rf5QIiuGVq50FuqGHiLtZLPvGIV7mgL3t4V2HJdy43GlipFhd5BLkDFDj+5qAqwX2vF2hZSEb5aN5xVBbgom03FxRJPGw0hNRq+4ppV0BJZ8EbFWZvJVkyVNRWaPvGG611BFlyLzLmQChRrqjQvNw1VWG/UWrYMVFQQUnCxUFws2YoJ/QAuICTYMxMabU2bJksRutG1VHk/lHK9U3xZa9SyqZhq8cTQcPrUsKuU2KFsKF8VqOiKLtmMkrpmiuSx63bY1iyXsh4VoKXmUmQbpRRa0VIX0FLpd+iWt6wAVbzNgSyUXBUkxykXeYSLjBPsypKjxqeLSDX/Ny17J0TFaMPFss3gbPFt+IH8BVBLBwiyhnqNeQIAACcEAABQSwMEFAAICAgAfC4KXQAAAAAAAAAAAAAAABsAAABleHRlbnNpb24vZGlzdC9leHRlbnNpb24uanPlfe1227ay6P/9FBKvlw5xAtN2kma3VGFe13GbtPlq7PTL0bZpEpJQU4BKQrZVmc9y/t3zXudJ7hp8EaQkJ937rHN/3NXVmAJBYDAYzAwGM4NgUdFeJUuWyWB4k5a9nyR5e/U7zWSUlTSVVBX+astyOmacvivFnJZyqd597z6YUPn2ltuXz2mVlWwuRamqfbOl2pt0RivdiV/jXSmkkMs5fTvGP7gXc1saTdPKa0R9/4skIcUSkcPVWJQhFPEe4z2Jfg0p5ng1oTKW53yEKV/MaJleFTTu79eoxm+o+hRzLOBzNg7lYAD9iHFPEhII1X1wf++VjRc8k0zwAEFvBZW9sifGvW9kKBHq/yCjLC2KkOISDQZlnxA+GAAcpYYjRORQnpdtWEJBvpehxCVC9/cial7VaFhSuSh5j9ZqrC8twIgchpzQPuGLokh+kuGvMqQIxSsYVCjv7/sU/o8uLmj1WuSLgia/hhwHOR2ni0IGeHWTFgsa0y5SYo4pQvg3SSg5fEPDX8NVjYOmGfclVMYUKbCkIKt6+IsMpcCrNJPsJpVUjfVHjnPaKqGiRsOZaiuid3NRyor8Bl/qpl6TlzQs6R8LVtIwuKkykdMAIfydJK6Ui5zGWbmcSxEg/Ef3zbjam5dixipaBbrR30mQ8mWZLqNJKultujwWfMwm0c1BgH/ovvuBLvWS+FkSTm97p1SG58GiomWAA0nTWYADxiXl0j28Sq9oEeCgolUFpDFC+EeFQEoICQqRpcVUVEBIquA8jg9Gwf393j8OHv89TOKP0cd8dYCf1Gj1pN7ZiyStYDbxL9CEokpNfrRPAlizfBIgTRdBMJTlcgVUqIH98P5VSCNZslmIHPGYBZSJok9IMJVyHgeDwXppFQOpu2LiVe7/KEMZwSB4OqMIqgFG4If6JK2qW1Hm+llOoRxa3VMNVjQtsyk8TdNqmgRBLCNRsgnjdZbKbLqyg6lr/BuMGYjXG7NbhkclzBOr1N+QomRVx4ZFjEsxO+GyZLQKTRE1PymKxqyQtAzDc4n5CJHDnxUooURuuXPicDsY8KigfCKnh/vN89fk8RfPBoP+3vnHxf7+/v4u/DkYw79/H4/MpHGEolk6bzrSfxHeoTAuOya/r71/pOX1xfnR7m/p7p/7u19d7I5Wj/fxFwePPVJIaHwjWN7bx6+2NkQ9oGkD9P7+p4D2m//Jkly/i2tDceejoaa28xHmdn0MLSsUwAppVBUso+E+fvYUIdWYcPMpts+nQCgTXDK+oKqPkgjMyCsalhHLEa70o6K/YZ/d3/er+3uu5pGh+/uQR2mehwxhGc0X1TRcsTxmGKrHVY1QbRdDjZ83bB+X5BzmSS0hRn6BZVeRHRpKNATATTcCiDkTc1YIuVvRVAaDgSozPGM3nbMAyWkpbnuAk5OyFGUYMH6TFizvmVq9TLGdRZlqAaJGWZCfwlJ1JkinwcGgMPNICNn/dPMzkdNirRMz7u9P376JNLGw8TJc3dASeFV8gM3nH8oiZrhhgnGFZ1SmeSrT+LeQIwzNx8LWeA2dVXEBcvSDIkrDhla140k5Ub3O07KiIU2SIEDD3C25vJGwg0GH3nI0GOSRgZEQcjAYhJLkyDCMGlrn5JdQRg30CAs1cx4jR7gkv4UysgNBmBEZwUC6uAbuZMtbE53ocrtAKsKSpF0DwxS6XjVeLNpXHnK5j1zRILfUmK26mMWsOjZzSfPY50lAehqewYB5z2G1Bv79feE+RLXWIn4mWZFW1SoTvJLlIpOiDCVaySmropKmOZE1/BnOKc8ZnwwnVIZqHasaphTZ9eSVGdbgGgpRpOYr5ORwpcnXr04IkTCvfpEeCsK80X1a7yWWtaH7VNLQQN3+2gzzw0N6Af6TdhWKKSvyi3kpMlpBhVed9yDXAoTn1KqbilbytLxlPEiCvVfsqkzL5d7RfF6wTK2+3uliDhrO3pHSMPauhJCVLNN59HsleBCrFm4Zf/I4SF5F6iH6XTAeyuhdKSZlOnueyjRJguP440evJMCBbjHAQadNFIf7+JVqBYXBHpVZgI2Cs6EypvyviZMvDh4PBudRFNFRRG9ouQylWficyCibpuWxyOmRDPfd9PFD8uTxYMD7hBw8/nuNBoNQgciqo6tKFAtJUQgahUVAUw5SB0tO9v5hxOOoQUPvW1bQKux9DO++fPYRoeTjxz2GJ25ypIdaya2gi/v7eEZJWi15pkUA+RBVMpVW/W++MvTd33fcTJD0NmWyx0PqBieiBcuBOw8GoVCMYnDwJYKClmrTP6hrvPQ6Jh/UAoFBQNe2C266kCHFwUKOvwyUZLA6SqP/geQz8/N0/6tnBtjVvKQV5TLuH9RDDbLHgLmTMrBp+DyJDPuRG5i5pnpUVWJNEV3ruSQiumJ82H29j68YjykPS5SUsV2vPq78puoaT92UKrJLzukoPh/hKIr8KT4fxeeGzHczwTmMZjTCnPsfT6n6oTQ0Tg7D1ZgVNOY4LSfVu5KO2R20LNmMioV8XcUZrxHa1JP+MODzu6D1cbC7u6SVW3AWkv9dpEB/gd/2d7QejbDgzX4OBPs7zZ9CQQ5X4T7+E7ZINFNUouqtTAMxx7P07pvFeEzL+NnTfz/Yf/wU3zKei9vqBcvV7gyHJWZWtalIaeY92Y/NTJZRpgRewBezK1oGiS5IkoMYKg5FuKJ3TB5r4VTJHDpmSSTFqZr7EIFErxH8h0vuqQB2BxJV84LJ8PJvlyiai7n+YNgQu0ecWt/iXeLkDXEaSjN0zdWyXVSKpEET40LMrVZGeSmKgub291Uhsmuat5ooCXO44eds5KSN7rhqeGFSWTq11Ky7jgVelEVchsGiLAKEAXnwS29Z8YxWVTpRJeYxQG1Kr2tccadw0/t7x3O/OHhs+c+BwpflpXaLh9Z2aVUcrLOcdCt7dzx1f/er3dHqKT545m89c06e0ae44ORg/9/hKdMF31Fy8CV9ihecPKZP8ZiTg8fq/R+wTMmqRh4RzItUjkU5SxIjVV0J5oRGlN80byi/wYJQxxWTpOGQuCRUTTcUwl/MoOaCJ4nguCI04kKy8TJJQs1gETnsHyBcEBqJOeUndxK2qoX/flUjnKsvb5PkeSrVE06ho4LSeZKEs/aSvCKHFZVnev2FV3iGEMIZeaPWTvTm5Lujs5c/nVy8fPPtyzcvz37FSzzd/vKG9A/whRYHvZmxXAHarmADxXk4wxIhhcgzIxJYeAXbWIqBk11FDdsB64zhN9pcsgt6ZDDCV5FjN1YPMyNXW5uz+/uzyC7wPmwwWruvE1Ly8CzSy159cWJ5fSZms5Tn8RW+oWXOMhmfAKdeeOOxMM8amGctmHd3pRAF8EqjrgbYcM8R/o524K3x2GsbgL9BqxviyeYrkofo0ZirnegwD9HXV0PExqGGIw0XHOHwk0DNS8bl7jVdBiN88AV90gEDJQ5fakNmRrkIZ1YfqOsx42lRLAE6EF+WY2jox6BNIiXt2TjMQ7SbfZ1zy5UyGIPC/YzMaQhSAV+Z2V/ScIaFnriryEhIn52dkSuQt95mYEJDVYTByqFbmUErYGfEJ6bdi/AsUbUMi9M9nHgtu9l+4Wb7riYnUO/O8GDis9wGKy8cVry6PjuGvTUP76JFWaD7+34Kz0DA1tagYDFlfUKWsCcM0e7064Kj1dhrf0l0JTwFFGJ4hTUUVXipNeW4V7GJtguLHuVg72y25dNU6s1z1fu4eLx/8LS3FIuyB032WNXbWenm60scvJ1TrpraZTxwiC3MKOz2tDZbENrdZAjYWfy4eWfx9sH9yk9r+xVjAFUdfbvtLX7zYKsvNgI4V2KDJkZBIMHJm7cnb84C/Htbdw738YuGzaMQGTUayNCq0Zocwn38JiqpMt4oJcxOnZbmlzsrWUeGi4ki391ZOZHB8np3B7Shb2lUpjwXsw8fXj5HIaovcUmMfNTmm6arQin1zooTsQoESYgGA/XjdDm7EgXLXjF+HaJ1y0pJx4uK8QkQS0nnRZrRXtrjgu8C5+jltJKMWwPL+gAlFmB56JtNQMi0FWzOQ2Y7YzWAvRk3ra9KtLmicBVXXfAvxykraA7AzxdXBaumPQV2yvNeSSspStqTU9qbl/SGiUXlj2fYK2kmYGfXy8R82SvpLGW86qWyt7MS9SWqLfylIX4N1QwgAjGWmcMVRZYTTowNf3cKUzceVwGeNYUlzSibyyrA31PyGC+9vZ4xhR48wwePv6x39vCUe+Z4pWNh9WeX8YrltARZopplixlY4L+h0Nj+7ldm79g8Ro92R6t9/AyM7fhXVS3dHe/vfjVaPXsKZbdu22A1s8+xRm830LVMcj2DCWP/44Qqzdcau/qEfE9he8cFz4DtyUYZjm7SkqVc+vvA/lTbQN3LfwIONg5DDqcxNJM0B3WJAyg/OYi0cACo1io9Z5U8naaPv3jm6sEW34G8vVVvDN9QYz/fWh15WHgQBq/VX7e32nyB/jl88ShVx4DAHUEau/1Jz24vfgl5yzjJCN9sYQS0bjJJJrxjefypadFaGT1ItIna2Ath+OX9Pdiv2bpZufLMyh5es4JRLn+gyxYWP+OAwvv0n8CmUZGiKOK+LdqYRVnHLFrVNf6hJYawAEFEaTQVM5qzspFD/aWz/HwuWGrV6Sn2qPLGEaFHVLlHQ1tbp5bielcLVuQ9llMumVya1V8C6D8ac53AQWRNdROOL3dWtFaGukuEmRNzqRNzb62Y0+cH6ZpgA6XKib77+zSq2J/08ODZky+frkO84FU6pg/yCIVlT9w3Yh6Meqm2fz17AuUNXVlBPqFS2cqaE/TBIAXzWZ+Qdp1w05r8FHjkloeePaHBkbOzhaW1qcHBtdPUm5oLXjB+DejsbD+0lWDLTM14owK8jWbXigIrvCpptigrdkOV0RFI+enTL2t76OM1VsFMM8u+3YznZsuTmh11BlpSUUdKF/qpqwtFcja/HPqqwtvotmSS6qFn0Me2I6DvKVZkH1OsWUmcYtrhv7FbBM2rhonG/moAi1lKWtxoMGAev/TL/QMS5vFLs/gVSdU1qv92iVeq6MmXT2ur3f9OwwwXm6YSyDPz9ZHOjNqNWW8bXOzT4nAwCB+s5TB2f7+hXktutphJYjaqOeihhUjzXaOi5wHC60VxuHkMiTElR64obCGYNUwb/xYy/4xMYR3/1NQ34gbFtk0l8kI7D7kDAT42T1oDnG/251Dv/lQ+JtpGAlyKM2XzHwzo4X7yOpXTqBQLnoPdfh9LuunUiljTjTkI4uKWyKF6rGRaSpofmfMoLm5DVHNxO3QvhmIu2Yz9SU/XSp4LTo/kEACnlTylXB7J4ZiVlXyXlvBcpO5xnoIPy/6wpNqbZb/drj2jWuvMh8u+POH51vo+4bVqaGC95uCw2wEeupM9byx+33MPSDWWR+TAP8lTtTROPQyQLjT+O4mwKmuwpM4UAT8NOApbj8gBLF9WTeEIUivEKwVF3ACETeXY/xJnYsHlcVoUVfxnqP2uKmRLsyl9waR9Y34hLIVMi9eq2A1tt00uqG4dPD40DRtmwZ8k7t69rsifm+Zsd3MXyKCvNWXdfj18tzt1L5pevbq76y3b7ja32JnIdl+VLGk6azpq6u12m0RwqFvjXygJ7nbbBkvl/YNv2ru/6GIvhg2g3f/95g6CDJmcX6rZJDsrGpl5rS8bO74H6I1RA8ESxrV3yKWy9xCwO1wiTH2keR/ayu6t6syrqz+2WNjwpX6lPrO19DcNaWz4yr5U3zU14UtbRXMdeK+e/FeWEcFL8+y/btaNqtH8XKsEa8avY5aRrqcOqgMcoBr/7Pt/nLsp2DJI+YlBzqoHZkR+ckbM5xvmRD4wJ+oruR238mHcSh9ta3jd24BDxZRy79N1YlYwXYJ1Mu4phO6spEF7L0D1pZawP1IS7N0c7Dm1rNrTy2rP4jTAR1zXgbb2MjGbFxRkdBVgLjuryk2F0rATe8zmptRwDqIME74ypDagKTg/0Dyo8WtODr7Y38dnnDylz/AxJ1/SZ/iKa2uLM+9gbXG54GSLjxq+VR6Bfer8hugDfkMUYaE8L1eNX6Tvg+QO7m9DiRJpD/Y6p3I7Cifg8If+inOEHAz6F27Hie+as72wf6t8HGgErfX9TdD9PbyL7G8EJsqwvxNScHq7v1dP9mVknS8NSM2LtJwsZpTLqrV1FzLcVAdZAzu4yEE/GBqMG5iwfYpXyn+uAwF2LcWbmoezoJNm7HrkfedCm1YVq2Sq3GfhDCgYRYxnxSKnVWgOlmlUioI6MIf2QBFKh9ZNo2mnoQzQdcEht9+aK1doz5b7n/05TJlxZrV0rmbETgQAogZhyuH5AjSRCzV7qifzvv3SM6qtgePVbNiXjwtzMrKx3mCw5rvpVdM06H5aMn78xTPwoCStd+Amcced8+w3QhQ05cD69Vd9Qja0hRrqgumKJTZIjR16lUuFRTlg0l9aluLgTw01+WCwanqJed363Mdpqxn/RdyuBwR6+i8uzu6S9EpyEwHR3iuur9lWPZ/gXI15WqYzKmnpT28LIq9Kg/e/uJp9dG4CroVWrzzeXF3NzzYYB4NV8yveWAcOz/B12wJvJ0gpbWAT10/392ukblwtNKHbHy1z51rx4QF92lpdxKsCi+BkfRFow6u3DjptdpxV6G3vdTrHpT3BwAzUJHvov4BDf9mA7rwBxvBi4a2xJDkfqVMhoWz+Y5ARtisRwZYcirCe5/FWrj3exLVh626UmLQo4p0VNAUHPmwcLhTr9Zjdos3p1EGVAqnzwgJXKufszkvXYUmrRSHjnVW7AnRubG8Wb4V7ytcwyD+JOH22LsDMqHEH01g1qLy/nyWW3Xewd38/84Us2YRCO9hKDVa1iPPPxamGbkzaKFCMXmN2DFK0co+FeXKUpjttenRIHTs8pmsIA7NxoszC6lnD5ISWsh/ntKCSbptYbVM2HpCplVVD60qyaaDmy6bYl32tSTOLSbVsz/4WXRE1Jod6HWg7bUb226PMNVkMs6+Za4+dZ6M+IYshysDYwcZhRghhncWbKeOE31aFGkIHWVCYR3+5L6E5LXA86b0ppkLXcSLZ40dP7u/DJbHFMMrTDYJ42RXEjQz24Fk41IVS11KLQbU6I4ezjihDeOzCOtg4XEaVmNEwXDkhMgMfr/5CjXxmxd/Y/5n09+NwrOjRlOD+gRNPapamRFlzi9hwcustV8UcxMfSCPAqXmpxbzZqnhhc6ZLYvqprfEMoviDnq2u6jANJZ3NaphJMoXjGeLwPLpPx4xqb92J+MfffHNg3s/TuQoprCtsj70P6FYZorwktlXdlU7fZT332Z9qBJ6MXc8rTQi71F7uP2yCO1V6LZ8st1Rz/U9UX6uVYvZu5Pq9qMe5dWFeym/PFCJ8Qeb4YweSekYY+jQpw0viDDgbh9HwxIift5WwqnvVdxfv7fteKe4bu78++Ht/fnx3O7u+vBoOmxksNmaoSLmD9ewi/v3cl62j1zpVP/N7PDk8cxSuIz2ywz7TGpdoOhqvAKJ+70EIQ652qdtPfU87wOF3IqSjNxje+/IamJS17sCFv4jbABchZr6zFPIi7JyvgqewM6hgoOXZ+bspdlsnmBNPfe09pCq4MSkI5iPWiNufOZhcDHpwf80fuBBYNBhrDIUeH0hyfaes8ja5EvkyiLOUZLcLOUQj2zti0q5Tzi9JIpHkv5T2hzjL+pLkKJAI3krnglT0p1V3YE/DuMRyo6fROQkSi1od0dRjkezXeEBnV6IzeyecUjBclZgTOvAMIrzFOPoqND5EJLdJNCxNoAmDkUS44RavqESmjXDUTghdof394VdL0GqiXPSJ5pCJYo6ulpK8UajFzKPtXseH3bTrCllUpv5h1HFXNAVZxf2+HtWW2YLwFTSv6SmTXIapr/F3Hxdet3rUVp49WiDlbmTEeUvyYfoWsh8HbljPyZ7m8tDfomJN2DYgcz5gySqHE+2FFWQmWndJtjsoHLDtlE6tZRteMt3Z7V8bqot8g5EcgKkFXAguAd7GuAkLlu7CMwPFplkqanykWc5re0Bz5UmZThXjrl3WNHDaF565kzWI4qK7ZfK6eclaBFyI8Gj/dAAcUSC8Y+U4RNva8ZZd7mW9z5r7wbObG6t35EjZh7ZK4W8XfY0vn5dl0qLcf9g1S0li5xNuiWiNYRhD6wLPl66qFVVcat+u4Db+jFLPfh2r/7Fxt+RK2mZVs+TOOqcymEBTqB06sjMUzlrXhdX5cnuV5ZRLdpiUPA2t07ZmZjh0D4UI69wV1llsZXwCgk6MrUcpjwaVyoy1xTmDFF1F6pc7MhiLRjzRPXGEMhXl+cgMh6KySlNMyDNTLAOd4pc70gekMtd+I57/eahy/5si5l2QuyunSE30fyqLeWf0ILrCrGZVTkcfBu7enZwE2EisGUi2V3TOKIjYYrM5/oaOY1TUGXr8mIRukIgzutGkRF5F+wCV48dBMxmY5aIf1MokYH4vm3KAHAPQUVL3dw97OKrPEd4lwP4vEtZ0cjeil9aSXYYbP9B6+fxsuUbvalFzzcGnt3I2ram+aOKin2F8v8Vv4wC9BdVwZL84MrTok0gzANNfT/poxDKHHOGyFMqXkwOiTTKnQDheXCFdOXmQFTUs7pynCIolKOhM3dAtNgLzglDx7ilNl3sa3VP25UX/oE/yekwP6DFNJHtNn+I8mOgmkAtWqR5N7YGNqAi+MZV2oXn6WUAWFqbez4vWllwAD57INjrTd3NBd2uzCTSkE9Jr37/lus0vXEv/zpX0HKtdNgIZep4+IxN0+HhELQY2L9WMWvYMFRc/EPjUOhGoDqd8rjy3C6ecDLIXozVK+1PCqVgKreIHBPwh0UHwQeBahIKibIx7TM0AGjsyixu/86C44VdCL5y8oTdYfbg2JTVj+G96eX3ty0N01Z1PBMlqhto3NlUdjxnMQ+LdKZ4DsATynd0myr+IyNeTQOEQ3wh+wcMgUebsLU2Tt1W3J13o1GPDQ2FtBxQ2wTo7SqVUj3O8Mw9bwTPPIWPa6LywZ/+tEsKHtsShPUtAvjczTeC83OOA9sHJbkwvtGoKriEM+85hFtXnraNVUsIhUX+/f31d/jfA3AdJT3btUCwWQdAW+dbdh2Zj1k+YZMuik5A+VcwKnEgeqlZfP9UYnVVNURCyH3AzqFCf9CwAq8V+wTOrQAgujah2aI6kxYf0R5tpme0txAA+6+8ySwi3dLVQFa/D55zYvCgTTvG7vEclwLsMCAwRumeIbigNv0ULoAYgS2eVqnXwg51iMxNiEi1ega4SQ++icQcqNcpeZ7CA7odDWV+3Jrn78i9NuJ0wnBVEtYtWPtnH9040bZEm36IUodhXFY/j3ZR5DX5rB6s4w4/OFjN/xUHiWYoW+l/+vGJ4xtrVZninczPQ6L7eyvU69jYzP1tnA+tZf/Xcyvw2tb2N/ClEeh/hvYoeK/zA0rGCxb2IyuNIHon94nXc5ASzQCrdqfHKlZrLtMY9LvdlxIS6tTY09avt0hpsOFo7evVSBdBA1193uDL0YrV65YXdxxLfvLvTOYtNOQrr9g9iycegz2Ap8WhP1dfFeCC7ZZjuBLu38rcwZtDnPa+t78X5tuttoxVN2R5Q0zg5q6exR0NR3tYUoQGj1kodum8LwMUe4gkBQKcNKK2aY+3GVfaZNb59Nn1w4c1UPvnSyka0b5fI1o1wKBrkMopeXZGrY/g2ZmkD/vY9l8pHvuZOKC3J4oR0rq5+ZnIaByncTmCRZ+q0y1HyBVMYA4y+LtJMTpA0AhN4o5nCjMqc9f/vmZBSgVQZGPYOFNy3H/xuNsLpuTIb9zBgNp4b6Cs9oONVGusFgumYWPKT/rFVQT2dPza3RHMDuaOyC065dcKoMl+DWbtndf1fPan50UPQN0dOj50gllghTZDBzQVJnM7vR8kOD7cpN6aOb8/2R1TrwMrxAOEPOuqoHYn73Mwjw0JkgBoNlmHYc9XvFNiNn0TFytohfe72V1ObtiwP8ipPzA/oEP6FP8AF9ip/QpyO8MIZ/lseXO6uS1sBw4PRVS2e7/j/effN3ZeRXDieXeJzOWLEE1wT1gG2QBHXxD7P07iXIdG1MimnULoD3bxeyqXAAG2uQBZLN4+BXiCw+1mcBJmPXLZPTngHHtyIEOKcyZUUcfMfki8WV+6xaXDl3Cz0Aa1LIe4L3VGKennaqzdJ5esUKJhmtYnWmBi6JjE8gKoXN0glVoKtkKwjv8I5C55mMvKhdmKeW6YGjGouNDvrG2zun84rIGv4MtecjHN+nEk7pJNkfakJ4T7Mpza6HOvBFr1Gz6TSBB7atqGAVmMVchsPGwyPRnsgVdLKAwCcdOFIY73HdO65kajNehsYjWkc0eJXAzSSdhwv5YBMHNaqzRVlqV3vfdVzXq03LK+NmDnlQdC9u+HDIPKGea/w6KOejOmfVXFS03VKt/6xMXQ+LSdQ04RXbHFkNflxmr1a9tmn/FT/3QR4N16MRzKtH5GBTr2EzdYamyiTZ4Uiv+a1gWj94VRaiGtJi1JY8TOHDFOIZinTShg51WCnSnpEtZNC0LvjRTcoKsOCHNq/afGuO0uecfEGf4LH0zCjhPp7bbLsv0mqKwqBSAUABwpwIrZgpnVnn+YlY9ROjoMWjlYwWc5X/TCWEYVx+aZXrK1UXCyXG3o7HFZXmhzF8+crDWv7FpuHgPEDDVoZbgSBpE25qYNgIuV+jwG9ZuMMa0Zzp+M2vXAAkJHns5pGsIFFDiZjavVXIKxfjnknveU2XFRgqNlaCPScze06EXLfrQXAVqmNwZw/L82rkj27YGl3djM5vzI6xjtcaFpDsaMF15uQc7LbOwgYJxLCMcjaB45lgCgaKGk/cZvrSSKqP+8q3Xckh88PIIPXLS0psMxVdVjurMRgU68v4cuae60vMtoRPcbMgZukdkfUsvRuatKnWaW04hYwnCw5cesaqyj5rw6VN/QZNmA99k6bvX6B6sQ2A143Bp88xbV+Oidg2jROSXYK2WNsowSe1Bl29cgx4NWU2XMi2iaFzagodIHVt2zC+oGvmKIj65V/vI5Xv+a8ANWyXgiHXotpoXaKNOEXRKOLqrHyobYFOnRpu6lpoTRLySoE4tnLA1jKF9QRWBfuTduSTD5rNmagNvdZQR+XLGcRUp5L6brGJ/wLC81pqwj6qcfVpZWBokXE8TctKMVn9mCTPnoLG5PNpIt1jknzgWpGwWR+DYGhf5uArYBtypUPlESf1FDc8nFWwtYG83RqucQHVfC5vQtakz9r8hJOPSFMXdnNvx44aTA2r0JPWaNsdtkSQG8n9fVuRyUl/v40UT3b648d+25D51jx2M3j6UrEl7FspPVv5NYNgA3JcwSy9phajhp6Ot4lEnbWm47rgzv6p8XLBM8cUv1V5itWhNCHkcdJ4gNM7z2E/6R/EIY0Kxuk3sGy+oWNRwhd9FQDUhG3YsJu/NSE4ui2E+/sodj0dJDQC6u2rJLTu+fFGOx0r8pJyBEA0P02iTE4OZzKEdEwo7h/E/QN8RJ2/xbfa8vcthBZ4GZB6KhFfN65qJk01DDEsJiIoQCprX42XkgTnC15Snuu87j1jgRgFeCp9t2roVFFFg1bPTx1w0YgWtPrXkOotoAa1g0GoEUpUhkn3/BgNBluR23j5cp1t2r2ZavS6XFwGgqVENb6Vn8T1Uq5heuphGjeY1rT9JyeP8XecHOA/OHmCj9VsUqUrSnIorXvrHzzRkRDfcb3zlNqgZ8MipDOWxhLhKwWnNbuccGV2CVFE1RMk/vPclr5tpfdLtDBoxylpq7STw/hGtj+x75tvmnft0Ax89MlPO3OW2JEh/KID6YzN6JmKtmhlGgFS+bi3x0wMlauGEqDteIM2TCMVs550DFUhssYWU0EtDvz7FjDaOIMP+sbLrt8A4Vnu9gKEL2QrXHXUPPb/187gHxdNlqGPe59VbWcP/+Q8sDaGu9mtjlujm+C/kOvYu+zBswoutIX1ZRwEhs4vd1ZrqfWDFJ6C2PZdq1BZp60ZCGr8XAt6negkr7SxalXj73k7JrS9aJF3rQFfI1zYKKily41+03JAtfWb3P3u+xaeBDmiTQte6tsWczU9Ca8P77Ubb7P28evWOuiskqQVvwSniVeU7P3Xf/yfj3tJWsbzGNJQpbtjyGxV/9d//OfeBH/DVQX1NvRfo//6j/8Mzz9WH09H/54g1Yaq9PFAf/grb28nj///3k62mvc3iQJ9xkawtBtBcV7+xY2giVpc2wAif8tnL1wxxIvtOow9NoSVfZwmigPZA0XHaeu1TaMz2R48QzW+k59mbhuZw3kqZZpN4SSj12IRo8sYVIlKZzGnuadJvPZuojGr7Vc/MTbXodNqMyQwRfjy4+Lx30+eKQKGTHLq598hotkk2AuvKIb1pevtdSpe1jhtknsntPNVTPEPrZCxrULRLv4URIOeCr1ZpV22QjezFQ5shVq2YodrFNYkpUoHiV9Drulb6SrCQZypq17dqQMt0ExypTes8d/LczUV6TzMKfKC7UeX8UbZkFyudlY+1VNL9VYjWad5icBwAULyXI5Qfen3U1/Gm+kaQkROugf/HoMXhsFr6875CGLdoigSVhkYwR0K9oToyGRolE1SMtAjqyayha27ODwPgxm7M/4LuzrOqWcDSHppSdXZI2TqPHq5a8p7EE6QSnZVUI9V5DqoR+fVUqZClJLcQqoQl5HDH3iYgdruZMCQFhU13pLf89B9gGwkkZIyLYD1JhhOQvWxsIa60rZ/SCwJqo9dX24Mskx5VaQy1WCnJKtLc7uJUil1RBVuxbrmhl04BTM1GayKBu05OewfyTBHCmLvhgjjW+9NZwYoKvQRnAwz744W2EFwKFmZkLOUhplbUp481c6XL6CuCikya8X/btn+Akjid922mhRb8zUkfLoDMNr1fVRf+gyrmX2NWGBKcLb7EzQOB7smMI7kzeQqw4tR3v/kyMxzYXF3AzuM1iR4Ee0O5+AF+1qGQrnDZh5p+7HMmaKwpTmlWtqJ+0T87rIbztlZoMtIuZwkiUp0BVtxVAPB9tpQ63D8dYBrFZ0odaSbW4YHSF2ZdArnvK/NUoMzWLcScpLTsDzfHyGcEpUgCvKMKmNgjoZpklo9K25egnDI8bkYodrkHQEnYscoeY0vFHM8Uczy1LeemxxBLrJWt+h+d0GFYxrMyYk5xrL+SQKXI+Xibr5HpYvBg82shdNa25xbvhetBrlHs7SMJUQtO7bYQYC6yiKJqikbw8HO23X2iQUYV0qyj5ny/F4JIjoyDguXIGYF3CIWEA9CwHWzZR8HqSGz6VFRhN/Adlk8IvZKphJX5nAXl8Q8PqqaE13jCiCN8AbYq/ODkeYSnjFXPCLV+eORt2BDlzpmBYlkb6i6GcjekuFBgLCqW+P3srVfDj8Vti6baHU/3LwTky7XQtGlXg6n2ZTOUj9cwAtEb9WpYdHgM/kX846cOfVkTZZ3gmLAjqVuCdP3Dp4plQFWAYpp3D+T2j5xJlXNz7vgTF86xrFQl45xrHLBeZgIWgp0d68PtyN6Wxj4GZ9RSDF8zkcI7i97J9sZce1tYIDf0bBx/nudzkM9OEEOz0XHhwmG2BzZjotUvtY1jbLAFcUZJz1bsUzOIbZAeCEp5V/LU7C5uiIOsY04vGKFCr8eLjfmNqhruJkEstX/wh9MQbPtnsk1qpLONiVtZvGtiUYbD4Cui3WN37SXmnaet9HX1bKSdLbBt+un0x6kuu8VKZ8sQIiaFOm5ULqJEbI9/b3Tv1xaYxc+tOZQmLgycEIXTc2NW2npttLDFtyN1G3lG/GlseKSKqBYU8/G2HLnFAFsoBNbrsLGzD6sdI6dXdc87eH5C9/okacs8B3QTcC/UnzbYfVrk9CZVqPssqoHJ1jgRsxkZTyd8yaXbks51EiAH+91SgA7onbfpmJd161GtJrgYbKutfH+pSTN3Q13zh1n1/gnxQH+rdmReXeYXMAaMMEx+tSN+0Evzx3J23gfLU96cMfkLuBnMZlCqAy3/pwqHZky5Wjk1TV+Dx3DjCPvbg1leZLWNkST6JyPPK90sTF20sQzC7cSRV3j7+39gYAPm/OebMrUoxLUWwCYtntYck+iczZqhVtTKOAqczwalvf3IT0X5/ujEQH/mmLjkRpk4VdeU8qn0zhQ6TOhCZXapdOetQn+gTcemYTr0kJMiBiadIhwjQopa/fpsP3NsBCToa41zKYpn9CTGZOS6ujdeaTCjkzREHKc5seq1ivDQlQe0eNpKl9ySCGsvJz0cVOrtUi5rw0hO7bOPKqaFzRcgVOHvkRXfaTJT9cJEfacMrxKrZb1FRw1GkIoFs3fiGO/DZitkqaFhhO8P9wxuIpBP9bp3aCMUXv+eLYo+Qvt8amPDsYlraYWKHetnteoPZjVh2ley+0Xzfg7LkGbRtT1Dmq+dW82fe1eGq+aDkr9hasdbOZRMYsqWtBMwkSaiqsbynNRxi9lbde2bB82F2Ji499yVukrBmLbXa8Q4nox95xvpT5+SJLgxLjyXiJ8PqpraKIza3bMG6fUHqNumW9zpKppOpzDPUQqhE5SuKE6sV6CFaXg0dzrOOIZicj0GHs7q24DdU/fyhW5TwBpvXLBzVcQBAiVvUThcMuuvYdEMcaiUBUNKE1F4TeA4ZlDy7327WM90Bw1fBqWf6t6kpYzcMWMLuPgc0YY9Y7B16onAfhODTUgVllQaY7N/So5VjdOgHe2CgCLApWY1iyExnkE/Gisu4v03V2kc3e5xIJsWkegLppr7Rx/NnzXEB2Q1XuvzwiwFDJyGLL7+01Nmr0eZDKGnP2teyu3V+3cVtmpCGuXw7U7pVll63C5OxRZ7ntMlxROeKFM755cwA9sWdTWmXzessQsj7l1bpVd59YG083NhgbUeSluWP4gB9fuM4V3RWJb/mhnlr7YGDi9QTJt4H/WQRKfj7R9ZtOFCY4E2mmrlSZXNa7Ad+AKXHmuwDrmwiIH3jjE2PaDrtfvweMv6ZNPuPp2HLbVUmp8eo/evYSrpsDGNx6zTPvxlmIhlUu3r9BfLXu+szLoYruCF/riogddfA/WXHxNVBSrjpW3ZaEm8L2OfehMiod+59+qboQyvrCl8YBltT/rLaGlnOxtpnXrKKokgVbtPEnAhRMGhqvesArMtb1QMziyzl2TJOCC06BGuFfR8gb04Z2VteHUPS/HasUKyqVZ8htlSLM6t5H8exM3EZoQGsyQyRHwANVXbarX3GQetRpXIi56I94BW1ZXyFfO3X8tkibqvV/n8ekkVQzWGHCqjevDxHNICha6ruZh/OdwhpdajYSWJtvrnZI8Mom7TVTMBFztqkeTSDva7YapLkhNAcIuEbepu6tr1Nog1yGOn2l4itrOVJ6mpW1Nv9HwFGcIDbfVMta8L4doWw1jk6vxlBSJVuBjbzp9eaXmE3wCpg9Po/xWpa0Pzqa0p0xxQJeb5Kqe3F4h+ISWvdTqrnYeb0gBVsi2RLhrS4S7RiJo4JWpDpKA3qh0cW1OaHJ5sTyeQBYvuIH5ZtNlGy+NUWETB+tpKaPvvmrmLKdXi0loshW75NrAZdUvAixXXebgLAUE9nBmqZoIqwu8UPAjQ32/cTCNmT40/iefDIxxZgr+b3BxXmOpULywJ8rmvGXLqQxMwAWZ1M64PSGnStG4IBOXphEvyCQy1t9a5+4TTX41PLMZzorkJp6CTHFG4wvYN467ZwJV/F6GY50C5b2RcMVbZaqqcCudWSvpifci/sRn25rWmdDg77tO2/BmU6utL7Y066dRgx9nJomX30FTZ0Mv2xp4oL8Nqdig/NgVbwNi7cMt8Hx2B1uAXE/85oremZIWbN36G8D6nCa3QLMhwVxTthGetS82APR5rRrzK1D+ay2rOtwUJO6ZeRu9N9eduPMzFfocB+4aFMjlY5Ns6VNYt+4cN9mUZ+eUsEjwjcqQcq+d2CQ5aMi2aU2DgauF86h19UZzI08vg6jdGT4mh3Cambra+lIMXNrHY+seqUOrE21ZaaEGHN0g2314bLwL4k2VjCJoKpqzxWOt6x5rezaCuAOTdqeJzjv1TAbL0J7i1PqeVR1GPMGnSA2kPVqocmy0oWlUUZ4bJMEHsKG6VpNQ0XClna/jI3J45Jv/towUa+9qVd060BhvYyh7CEdHyFwfAhVXmzB+BEekNlxUmzmUve4I7HXHJr8kcpN2rXWPowZh1851fKlSsp0pDeoqPFabQ31t6yJZOz81ZotG5Qm09Nxo8ASZlUoxY5k71J4yOGJcBvYanrOwda3myUaCf/EJgj/5LIJ3tXBXpddDgH2M1sYvnDZuwA4r1DOjUuYLK7btfqc0usDdMG/fjGLo6z0ln9Dl1FTeGTKs9LLTqb1ObIopCzV+790E1vSnruHBLzzrmPWdXxupA7tnc5YRuC920yUKbrvSY/mGSu0UbEkS7KpsT1tnwbsll8vwDm6kXm0khHedrHx3dtU2KafdcZT3TulwzWmMexPP8DtK3snwnVZ3sKf2GO+Jv8zVfW3oHW3F620c0reSvAEA3ADwmJKJOZ1c2G3sRBHMKXkL/GfhdqKnWg8+JoeBXmoB471jlJwqSwEUK84LhZ/gvsq1PQaeCs2geFMLulYcBMjzIX0hybfav8iyUs06F8m1P6zz0xFe+Jr9cfc+gN4xDc+PR+h8XxlGJpuOx1Tb1+Tc1FBAq7IjMqa2YGgI4Mib8qPBwDC7hxksiq+d+wawRXPeofjnJHLna00S7t8lOdISyBGe+e05tJkSOPh7AApfyh1ZKXekpdzvEjkfhA10aPhwdGRRFV47Mkyu4Wxyoo+i6xZmTQp0PTB9pGZRrNHpiluhDw9B8KGiZXi+ZXi6LTXAVuOet5AY9669edvYkp2uazSKr9HocxCjwGpIxKED4ZdEncm3ND9wOKqH34cvcUcjfBd525DOngRvrg8bjO4+Y3PVZpeQJPrXmo6+dSvxF3X6zQB09e/P08g3t7WmOn+uNm00gKvwhcRmN/mOYsuG44Yjg9bte4m+RP4+1AcnfgmOYy2L2JmzA2kTmHXyfMD8Vf7Pmr+U09pG27C5O9WGDHirhXcd6C5oCH4vbuFeQW7F2k9fs9k0xP5nzEIVmZio12LdPKdctrS/1pqo0JFkNnMy0zdSaeJWrkjO9L9N4zDm05Y5EPrDcNGBifjLujfKty+cf7UWEAjRWxfmAlgTF/hzNw1FuI9fyaiap7dcXZGOV2BFB+MupLGoZM5EHLAJFyUYg4c8Ejw0OYCwy3MdQVDcGEx9Oy4bElnVqOWp09xvmyTuCnpTgiFtI+U3zRvKbzBk4rJ3zCZJ1vzAJXi9yVSqUnjADEpgFEnyM8cVmVM7kXpOljSsIOViToroivnXx0xoqIow3GGnK8+gsoRjpZRMaQiJYa8Yt+mHpVUJ+qlTFMMUnwcXF2bxKEB2zXF1MLK3yZt5PKFEbUeiq6W4/iDhfEFbEZ/TcbooZIBPnc/HtjrRLOXpBFIcP9ceSGtXXAdwu/zRBJLVNBnS8Z9NbVt2f091YnhbHX/TzqDebLTVedtr3TO4uNth4Q+dJFjtz6T/GUetO8H6B/XaQbjq5rtCXKUF7PL67VvETKVvdApNOHrB161bq5u4CXA+rOB2WJ0GHZawBQNOIP+UYYmS0lMCS48umHcPp+2SY7PuMfNqimiigP1JBzUQd3jxXHpxGxW8gfjVD5rHV5g5TaFpzV5R6/fVP0Bxqw/viisR3YryupqnGX3g1beiyGnZruCBouC03dX4Ld2UQl+20ScAfRwl3EOfIE3vtMF9B3R3oOyvwmZSm1EPH6QMW2/Dl/tdEtMLb0HJygAVu4MYSl43eGqErLkHO0RuGCduKlfeeCCIyPuJ27MBb9sleNOctKp55ZBH24431voCeD/qEX8CbBNBdUIxxa+j1tuzFI58I90uuNDppq2HXe9HCDda7VizgCSrZuYV4qgZ8qmEO4JBMJ5ShJtFHjf3a9t58z+wwV0UpyptMvB+63oRzdPsOp1QpTiYs2LPlcy7z2vraUXjxmHa6k1TJfZNc03OXnsWzXFzSXQc7uPvtoT7Wcjtbdh/SO8OdBql1dFVJYqFpO9SlZONVbK5PDL6vQoQQt3kJNrB6+dQrzhEDj80dztUNCupUT1+RwgZD/ZSFUCWZD9dVWWjwu1XnpdYCFMRpqCYEkJ+hwvr9eMPaDCArJbqUAqGBk6VRhf6g4Yr7b2j5zNMcYbIoaM+7X5TTcWt57FgNji6LiEZFnPK4WrukjsaTj0ahmNnv0r4OvpQMnvHBSQMABMiLojrUM+Mdg6A0XFa2KkP8KoQE52YfSNyCmQUNcB5QUOmdZjKunrhAgNwrcH9nJac8YkbGLi4sdC4u6ihtBTx5JqGqb7mW0XrxKFtHb+loQ7gqdU1quvg5VvKX4MLSkknkHW8XNtTvtNbCEhGbrCQo4ca8ujCc2gBRIAJt+Vit70dgyAL1IeSvUh5XtAyXE3Vw4eSedMNCe+ieaoCXoK95ip136MzU7Py4f2rU5qW2fQd+H9XYRr9saDlEumUjxwy7weQAChwefVt9vkfIIRp5do2RDvFN/gCL/AYedzILhEVSBL+jp9Tr54VKU014470A1i2/bViKl7TcKEnu8bKnTB2i3mtR9PU73+5E0s8dW3M3rB81++sf5B23dbPOpT1UuCftPR45tWCFbAVVA33jKf6dhc4tz80JsQ1EsKf4hRLrYxaikgskOaw2dufBs7xJ/PFWU+5dsJ7q1q2ulTCoYuBTCyKXO1/b2jJxktlLxec7sKFIXbUnW6ArsV4/OA2WUW41E6SUhGiVQ2J3GYCkshE9E5fcrxKM8luUklxTu1jjYZ/+79QSwcIdRWLOUc3AAA+pAAAUEsBAj8DFAAACAgAfC4KXezY2SsHAwAAtAkAABYAAAAAAAAAAAAAALSBAAAAAGV4dGVuc2lvbi52c2l4bWFuaWZlc3RQSwECPwMUAAAICAB8Lgpd36MN37wAAABlAQAAEwAAAAAAAAAAAAAAtIE7AwAAW0NvbnRlbnRfVHlwZXNdLnhtbFBLAQI/AxQACAgIAFstCl3sOC/HmgIAAKQFAAAWAAAAAAAAAAAAAACkgSgEAABleHRlbnNpb24vcGFja2FnZS5qc29uUEsBAj8DFAAICAgAWy0KXbKGeo15AgAAJwQAABUAAAAAAAAAAAAAAKSBBgcAAGV4dGVuc2lvbi9MSUNFTlNFLnR4dFBLAQI/AxQACAgIAHwuCl11FYs5RzcAAD6kAAAbAAAAAAAAAAAAAACkgcIJAABleHRlbnNpb24vZGlzdC9leHRlbnNpb24uanNQSwUGAAAAAAUABQBVAQAAUkEAAAAA";var Te="anyray.anyray-vscode",BT="vscode-handoffs",Mb="vscode-receipts",_s=2,UT=FT(PT),fr={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"]}},HT={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"}},WT=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),Fb=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&WT(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ts=e=>{if(Fb(e))try{return new URL(e.trim()).origin}catch{return}},KT=(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)},GT=e=>{try{return LT(e)}catch{return[]}},jT=(e,t,n)=>{let{macAppName:r,commands:o}=fr[e],a=o[0],s=[];for(let i of["/Applications",_b.join(t,"Applications")])for(let c of n(i))KT(c,r)&&s.push(_b.join(i,c,"Contents/Resources/app/bin",a));return s},VT=(e,t=Gp(),n=Vo(),r=process.env,o=GT)=>{if(t==="darwin")return[...new Set([...fr[e].commands,...jT(e,n,o)])];if(t!=="win32"){let l=fr[e].commands[0];return[...new Set([l,`/usr/bin/${l}`,`/usr/local/bin/${l}`])]}let a=HT[e],s=MT.join,i=r.LOCALAPPDATA??s(n,"AppData","Local"),c=[s(i,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(l=>!!l);return[...new Set([...c.map(l=>s(l,a.directory,a.executable)),fr[e].commands[0]])]},Bb={run:async(e,t)=>({stdout:(await UT(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>DT(24).toString("base64url"),home:"",commandCandidates:e=>VT(e)},jo=(e,t)=>Os(e,".anyray",Mb,`${t}.json`),jp=(e,t)=>Os(e,".anyray",Mb,`${t}.applied.json`),Ub=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&xc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},Hb=async(e,t)=>{let n=await Ub(e,t);if(n)try{let r=await t.run(n.command,["--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()===Te.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===_n}catch{return}},Wb=250,YT=9e4,ZT=YT/Wb,XT=async(e,t,n,r)=>{for(let o=0;o<ZT;o++){try{let a=JSON.parse(await Jr(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===_s&&a.action===n?"confirmed":a.extensionVersion!==_n||a.extensionDistSha256!==Xr?"reload-required":a.version===_s&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(Wb)}return"timeout"},JT=async e=>{try{let t=await $T(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},Tb=e=>Pb("sha256").update(e).digest("hex"),zT=async(e=Vo())=>{let t=Buffer.from(Ob,"base64");if(t.length<4||t[0]!==80||t[1]!==75||Tb(t)!==nl)throw new Error("bundled VS Code extension failed integrity validation");let n=Os(e,".anyray","vscode-extension"),r=Os(n,`anyray-vscode-${_n}-${nl.slice(0,12)}.vsix`);try{if(Tb(await Jr(r))===nl)return r}catch{}await Wp(n,{recursive:!0,mode:448});let o=`${r}.${Lb()}.tmp`;try{await Kp(o,t,{mode:384}),await fe(o,r),Gp()!=="win32"&&await NT(r,384)}finally{await Db(o,{force:!0})}return r},Hp=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=>Hp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Hp(t[n])}`).join(",")}}`},Kb=(e,t,n)=>Pb("sha256").update(Hp({gatewayUrl:Ts(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:_n,extensionDistSha256:Xr,profiles:[...n].sort()})).digest("hex"),qT=async(e,t,n,r,o,a)=>{let s=JSON.parse(await Jr(jp(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==Kb(t,n,r))return!1;let i=JSON.parse(await Jr(jo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===_n&&i.extensionDistSha256===Xr&&i.gatewayUrl===Ts(t.origin)?await Hb(e,a)===!0:!1},QT=async(e,t,n,r)=>{let o=jp(e,t),a=`${o}.${Lb()}.tmp`;try{await Wp($b(o),{recursive:!0,mode:448}),await Kp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
109
- `,{mode:384}),await fe(a,o)}catch{}finally{await Db(a,{force:!0})}},eP=async(e,t)=>{await Nb(jp(e,t)).catch(()=>{})},Gb=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...Bb,...r,home:r.home??Vo()},s=fr[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!Fb(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((g,y,b)=>typeof g.id=="string"&&g.id.length>0&&g.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(g.id)&&typeof g.name=="string"&&g.name.length>0&&g.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(g.name)&&b.findIndex(v=>v.id===g.id)===y);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await Ub(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!op(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,d=a.listProfiles??(g=>cw(g,Gp(),a.home)),u=n==="configure"?await d(e).catch(()=>[]):[];if(n==="configure"&&await qT(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:jo(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 JT(f))return{ok:!1,reason:"extension-missing"}}let p=a.nonce(),h=Os(a.home,".anyray",BT,`${p}.json`),m=jo(a.home,s.slug);await Wp($b(h),{recursive:!0,mode:448}),await Kp(h,`${JSON.stringify({version:_s,action:n,nonce:p,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:_n,expectedExtensionDistSha256:Xr})}
110
- `,{mode:384});let w={installed:[],failed:[]};try{if(n==="configure"){await a.run(l,["--install-extension",f,"--force"]);for(let y of u)try{await a.run(l,["--profile",y,"--install-extension",f,"--force"]),w.installed.push(y)}catch{w.failed.push(y)}}await a.run(l,["--open-url",`${s.scheme}://${Te}/configure?nonce=${encodeURIComponent(p)}`]);let g=await XT(m,p,n,a);return g!=="confirmed"?{ok:!1,reason:g==="reload-required"?"reload-required":"activation-timeout"}:(n==="configure"?w.failed.length===0&&await QT(a.home,s.slug,Kb(t,o,u),p):await eP(a.home,s.slug),{ok:!0,receipt:m,profiles:w})}catch{return{ok:!1,reason:"failed"}}finally{await Nb(h).catch(()=>{})}},jb=async(e,t=Vo())=>{try{let n=JSON.parse(await Jr(jo(t,fr[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==_n||n.extensionDistSha256!==Xr)}catch{return!1}},Vb=async(e,t=Vo())=>{try{let n=JSON.parse(await Jr(jo(t,fr[e].slug),"utf8"));return n.version!==_s||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},Yb=async(e,t,n=Vo(),r={})=>{try{let o=Ts(t);if(!o)return!1;let a=JSON.parse(await Jr(jo(n,fr[e].slug),"utf8"));if(!(a.version===_s&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===_n&&a.extensionDistSha256===Xr))return!1;let i={...Bb,...r,home:n};return await Hb(e,i)===!0}catch{return!1}};var hr="Anyray",mn="anyray",Qb="--anyray-owner=vscode-profile-v1",Ps=e=>qb(ot(e),"User","chatLanguageModels.json"),iP=e=>qb(ot(e),"User","settings.json"),Ls="github.copilot.advanced",ol="debug.overrideCapiUrl",vt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cP=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}},ek=e=>{let t=e[Ls];if(!vt(t)||!cP(t[ol]))return{next:e,removed:!1};let n={...t};delete n[ol];let r={...e};return Object.keys(n).length>0?r[Ls]=n:delete r[Ls],{next:r,removed:!0}},Ds="anyray-default",Ns=()=>{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:[Ds]},tk=e=>e===Ds?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),rl=async e=>{if(!await R(e))return{kind:"missing"};try{let t=await zb(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"}}},nk=async(e,t)=>{await nP(sP(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${aP()}`;try{await oP(n,`${JSON.stringify(t,null,2)}
111
- `,{flag:"wx",mode:384}),await fe(n,e),await tP(e,384)}finally{await rP(n,{force:!0}).catch(()=>{})}},Vp=e=>{if(!vt(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!==hr||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(!vt(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!==tk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!vt(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}})},Yp=e=>{let t=e.filter(n=>!Vp(n));return{next:t,removed:t.length!==e.length}},lP=async(e,t)=>{let n=Ps(e),r=await rl(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 "${hr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=Yp(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${hr}" Custom Endpoint from ${n}.`]};try{return await nk(n,o),await re(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${hr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${hr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},dP=async e=>{try{let t=pr(await zb(e,"utf-8"));if(vt(t))return ek(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Ls}.${ol} 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 ${Ls}.${ol} value manually if present.`]}},rk=async(e,t)=>{let n=iP(e),r;try{r=await M(n)}catch{return dP(n)}let{next:o,removed:a}=ek(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 Z(n,o,{backup:!1}),await re(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.`]}}},uP=async(e,t)=>{let n=await lP(e,t),r=await rk(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},ok=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,Qb]}},ak=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},sk=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),pP=e=>Array.isArray(e.args)&&e.args.at(-1)===Qb,ik=(e,t)=>{if(!t.hookBinaryIsDurable()||!vt(e)||!ak(e,["type","command","args"]))return!1;let n=ok(t);return e.type==="stdio"&&e.command===n.command&&sk(e.args,n.args)},fP=(e,t)=>{if(!vt(e)||!ak(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&&sk(e.args,n.args))return!0;if(Ge(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===er&&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!Ge(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},Zp=(e,t)=>ik(e,t)?"exact":vt(e)&&pP(e)||fP(e,t)?"stale-owned":"foreign",Zb=e=>`MCP name conflict in ${e}: servers.${mn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,hP=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 M(p);if(i){if("servers"in h&&!vt(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=vt(h.servers)?{...h.servers}:{},b=ok(o),v=y[mn],S=v===void 0?void 0:Zp(v,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(Zb(p));continue}if(t){d+=1;continue}y[mn]=b,f.push({path:p,next:{...h,servers:y},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!vt(h.servers)||!(mn in h.servers))continue;if(Zp(h.servers[mn],o)==="foreign"){u=!0,l.push(Zb(p));continue}if(t)continue;let w={...h.servers};delete w[mn];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 Z(p.path,p.next,p.backup?{}:{backup:!1}),p.clearBackupAfter&&await re(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}},mP=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 M(c);if(!vt(l.servers)||!(mn in l.servers)||Zp(l.servers[mn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[mn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await Z(c,u,{backup:!1}),await re(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}},ck=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.`]:[]],lk=()=>`${Te} 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.)`,Xb=e=>[`${Te} 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."],dk=(e,t,n,r)=>({runMcp:o=>hP(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):uP(e,o)}),yP=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=dk(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 ${Te} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...Xb(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${Te}; 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:[d.reason==="reload-required"?`A newer ${Te} build was installed, but ${e} is still running the previous build. Reload VS Code completely, then re-run anyray-connect.`:d.reason==="cli-not-found"?`The ${e} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`:d.reason==="unsupported-version"?`The Anyray language-model provider requires VS Code ${Ec} or newer. Upgrade ${e}, then re-run anyray-connect; no extension configuration was written.`:d.reason==="unsafe-gateway"?"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.":d.reason==="extension-missing"?`This anyray-connect installation is missing its bundled ${Te} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`:`VS Code did not confirm the one-time ${Te} configuration. Open VS Code and re-run anyray-connect.`]};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?[lk()]:[],...Xb(t),...d.alreadyCurrent?[]:ck(d.profiles),...f.messages,...u.messages]}},Jb=e=>[`${Te} 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: ${Ns().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."],gP=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=dk(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 ${Te} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...Jb(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${Te}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Ns().map(p=>({id:p,name:tk(p)}))});if(!d.ok)return{status:"manual",messages:[d.reason==="reload-required"?`A newer ${Te} build was installed, but ${e} is still running the previous build. Reload VS Code completely, then re-run anyray-connect.`:d.reason==="cli-not-found"?`The ${e} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`:d.reason==="unsupported-version"?`The Anyray language-model provider requires VS Code ${Ec} or newer. Upgrade ${e}, then re-run anyray-connect; no extension configuration was written.`:d.reason==="unsafe-gateway"?"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.":d.reason==="extension-missing"?`This anyray-connect installation is missing its bundled ${Te} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`:`VS Code did not confirm the one-time ${Te} gateway API configuration. Open VS Code and re-run anyray-connect.`]};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?[lk()]:[],...Jb(t),...d.alreadyCurrent?[]:ck(d.profiles),...f.messages,...u.messages]}},wP=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 M(s),c=vt(i.servers)?i.servers[mn]:void 0;if(!ik(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 bP=async(e={installedVariant:Ic,remoteServerVariant:ip,isRemoteDevContext:ts})=>{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}},kP={installedVariant:Ic,remoteServerVariant:ip,detectVscodeLmProviderEligibility:uw,configureVscodeExtension:Gb,vscodeExtensionPointsAt:Yb,vscodeExtensionAwaitingReload:jb,vscodeExtensionReceiptMode:Vb,hookBinaryIsDurable:ce,hookBinaryPath:Oe,mcpServerCommand:je,vscodeUserMcpConfigPaths:lw,isRemoteDevContext:ts},AP=(e={})=>{let t={...kP,...e},n=()=>bP(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Rs,quitTarget:tl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Uo(r,!0)}`:Ps(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ie(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 ${Ec} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||aw(i.version);return J(r,"copilot")?yP(a,r,o,t.configureVscodeExtension,c,s,t):gP(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?wP(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ts(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await rl(Ps(o));if(s.kind==="array"){let c=s.entries.find(Vp)?.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 rl(Ps(r));if(o.kind==="array"&&o.entries.some(Vp))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 mP(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await rk(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${Te} 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 ${Te} gateway configuration and secret.`)):(l=!0,u.push(y.reason==="cli-not-found"?`The ${o} command-line launcher was not found, so Anyray could not ask ${Te} to clear its SecretStorage configuration. Install the launcher and re-run revert.`:`VS Code did not confirm the ${Te} reset. Open VS Code and re-run revert.`))}let f=Ps(o),p=await rl(f),h=p.kind==="missing"||p.kind==="array"&&!Yp(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 "${hr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=Yp(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${hr} Custom Endpoint from ${f}`]};await nk(f,w);let g=[...u,`Removed the ${hr} Custom Endpoint from ${f}.`];return await re(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},uk=AP();import{accessSync as KP,constants as Ck,statSync as GP}from"node:fs";import{readFile as vk,rm as Ms}from"node:fs/promises";import{homedir as of,platform as _k}from"node:os";import{delimiter as jP,join as af,resolve as VP}from"node:path";import{execFile as xP}from"node:child_process";import{readFile as IP}from"node:fs/promises";import{homedir as zp,platform as RP}from"node:os";import{join as $s}from"node:path";import{join as CP}from"node:path";var Xp="Iv1.b507a08c87ecfe98",vP="https://github.com/login/device/code",SP="https://github.com/login/oauth/access_token",EP="read:user",pk=1e4,Yo=()=>CP(q(),"copilot-seat-login.json"),fk={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},Jp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hk=async(e={})=>{let t={...fk,...e};try{let n=await t.fetch(vP,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Xp,scope:EP}),signal:AbortSignal.timeout(pk)});if(!n.ok)return;let r=await n.json();if(!Jp(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}},mk=async(e,t={})=>{let n={...fk,...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(SP,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Xp,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(pk)})).json();if(!Jp(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"}},yk=async(e,t)=>{let n=Yo();return await he(n,`${JSON.stringify({token:e,clientId:Xp,mintedAtIso:t},null,2)}
112
- `),n},al=async()=>{try{let e=await M(Yo());if(!Jp(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var OP=5e3,qp=5e3,_P=["copilot-cli","CopilotCLI"],TP="https://api.github.com/copilot_internal/user",wk="~/.copilot/config.json",bk="macOS Keychain (Copilot CLI)",kk=e=>e===wk||e===bk,Zo=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),Qt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),PP=()=>process.env.XDG_CONFIG_HOME?.trim()||$s(zp(),".config"),LP=()=>process.env.XDG_DATA_HOME?.trim()||$s(zp(),".local","share"),DP=async()=>{try{let e=await IP($s(zp(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return Zo(t)?t:void 0}catch{}},NP=async e=>{try{let t=await M($s(PP(),"github-copilot",e));if(!Qt(t))return;for(let n of Object.values(t))if(Qt(n)&&Zo(n.oauth_token))return n.oauth_token}catch{}},$P=async()=>{try{let e=await M($s(LP(),"opencode","auth.json")),t=Qt(e)?e["github-copilot"]:void 0;if(!Qt(t)||t.type!=="oauth")return;if(Zo(t.access))return t.access;if(Zo(t.refresh))return t.refresh}catch{}},MP=(e,t)=>new Promise((n,r)=>{try{xP(e,[...t],{timeout:OP},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),FP=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return Zo(r)?r:void 0}catch{return}},BP=async(e=MP)=>{for(let t of _P){let n=await FP(t,e);if(n)return n}};var sl={env:process.env,platform:RP,tokenFromDeviceLogin:al,tokenFromCopilotCliConfig:DP,tokenFromSharedConfig:NP,tokenFromOpenCode:$P,tokenFromKeychain:BP,fetch:(...e)=>fetch(...e)},UP=new Set([401,403,404]),Ak=/^[a-z][a-z0-9-]{0,30}$/,HP=e=>e!=="default"&&Ak.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",WP=e=>typeof e!="string"?"default":/^https:\/\/api\.([a-z][a-z0-9-]{0,30})\.githubcopilot\.com\/?$/.exec(e.trim())?.[1]??"default",Qp=async(e,t={})=>{let n={...sl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),qp);try{let a=await n.fetch(TP,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=Qt(i)&&Qt(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:WP(s)}}return{verdict:UP.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var Xo=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${Ak.test(n)?n:"default"}/header/models`,a=await gk(o,e,r.clientKey,t);if(a.length>0)return a}return gk(`${HP(n)}/models`,e,void 0,t)},gk=async(e,t,n,r={})=>{let o={...sl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),qp);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=Qt(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!Qt(u))continue;let f=u.id;if(typeof f!="string"||f.length===0||u.model_picker_enabled!==!0)continue;let p=u.policy;if(Qt(p)&&p.state!=="enabled")continue;let h=u.supported_endpoints,m=Array.isArray(h)?h.filter(E=>typeof E=="string"):[],w=u.capabilities,g=Qt(w)?w.limits:void 0,y=E=>{let x=Qt(g)?g[E]:void 0;return typeof x=="number"&&Number.isFinite(x)&&x>0?Math.floor(x):void 0},b={id:f,endpoints:m},v=y("max_prompt_tokens"),S=y("max_output_tokens");v!==void 0&&(b.maxPromptTokens=v),S!==void 0&&(b.maxOutputTokens=S),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},il=async(e,t,n,r={})=>{let o={...sl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),qp);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)}},cl=async(e={},t={})=>{let n={...sl,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return Zo(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:bk,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 Qp(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 Qr="copilot-cli",yn="copilot-cli",YP=Rs,ZP=()=>YP()?["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."]:[],Tk=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],sf=()=>Object.fromEntries(Tk.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),ef=()=>af(of(),".anyray","copilot-cli.sh"),Pk="# Managed by anyray-connect. Do not source this file anywhere else.",Sk=e=>e.split(/\r?\n/,1)[0]===Pk,XP=["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"],ll="COPILOT_PROVIDER_API_KEY",Ek=e=>e.startsWith(`export ${ll}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Pn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",JP=()=>Ns()[0],Fs=(e="default")=>`/copilot/${e}/header`,yz=Fs(),zr=e=>e.replace(/\/+$/,""),zP=(e,t="default")=>`${zr(e.openaiBaseUrl)}${Fs(t)}`,tf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),rf="claude-sonnet-5",qP=()=>{let e=Ns()[0];return e===Ds?rf:e},Lk=e=>e.endpoints.includes(Pn(e.id)==="responses"?"/responses":"/chat/completions"),cf=e=>{let t=e.filter(Lk),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)=>xk(a.version,s.version)?-1:xk(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var xk=(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},Ik=(e,t,n,r,o,a="default")=>{let s=le({...e.metadata,tool:Qr}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...Tk];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Se(zP(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Pn(t)}'`,`export COPILOT_MODEL=${Se(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=${Se(i.join(`
113
- `))}`]:[],`export ${ll}=${Se(n)}`]},nf=(e,t,n)=>{let r=le({...e.metadata,tool:Qr});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Se(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Pn(t)}'`,`export COPILOT_MODEL=${Se(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${Se(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${ll}=${Se(n)}`]:[]]},QP=(e,t)=>t||!J(e,"copilot"),Rk=()=>{let e=XP.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).`]},Ok=(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 ${Qr}\`), 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`."],eL=(e=process.env.PATH,t=_k())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(jP)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=VP(o,n);try{if(!GP(a).isFile())continue;return KP(a,t==="win32"?Ck.F_OK:Ck.X_OK),a}catch{}}},tL=()=>af(of(),".copilot","config.json"),Tn=()=>af(of(),".copilot","mcp-config.json"),qr="anyray",nL=()=>({type:"local",...je("profile"),tools:["*"]}),mr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rL=async()=>{let e=Tn(),t;try{t=await M(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&&!mr(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=(mr(t.mcpServers)?t.mcpServers:{})[qr];return r!==void 0&&!Zt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${qr} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},oL=async e=>{let t=Tn(),n=e.json,r=mr(n.mcpServers)?n.mcpServers:{};r[qr]=nL(),n.mcpServers=r,await Z(t,n)},aL=async()=>{let e=Tn(),t;try{let r=await M(e);if(!mr(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!mr(n)||!(qr in n)||!Zt(n[qr],"profile")?!1:(delete n[qr],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Ms(e,{force:!0}):await Z(e,t,{backup:!1}),await re(e),!0)},sL={resolveCopilotCommand:eL,platform:_k,detectCopilotSeat:cp,discoverSeatToken:cl,readDeviceLoginToken:al,fetchSeatModelCatalog:Xo,probeSeatChatModel:il},iL=e=>`'${e.replace(/'/g,"''")}'`,cL=e=>e.split(`
114
- `).map(iL).join(" + [Environment]::NewLine + "),lL=(e={})=>{let t={...sL,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Uc(Ct(),yn))?.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&&zr(s)===`${zr(i)}/v1`,a=(s,i)=>s!==void 0&&tf(s)&&zr(s).startsWith(`${zr(i)}/v1/copilot/`);return{id:Qr,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Rs,quitTarget:tl},async usesDynamicCredential(s){let i=await r();return a(i,s)||!o(i,s)?!1:!await R(ef())},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=tL();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=Ct(),l=async(E,x,A)=>{let I=E.filter(Ek),T=E.filter(xe=>!Ek(xe)),B=ef(),X=[...T,...I.length>0?[`[ -r ${Se(B)} ] && . ${Se(B)}`]:[]],V=await R(B),W=V?await vk(B,"utf8"):void 0,z=W===void 0||Sk(W);if(I.length>0&&!z)return{status:"manual",messages:[`Refused to overwrite user-managed ${B}; move or rename that file, then run Connect again.`]};let me=ce(),De=me?await rL():void 0,ee=[`${c} \u2190 managed Anyray block (${yn})`,...x.map(xe=>` ${xe}`),...I.length>0?[`${B} \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."],...A,De?.status==="skipped"?De.message:me?`${Tn()} \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.`,...ZP()];if(i.dryRun)return{status:"configured",messages:ee};let Fe=!1;De?.status==="installable"&&(await oL(De),Fe=!0);try{I.length>0?await he(B,[Pk,...I,""].join(`
115
- `)):V&&z&&await Ms(B,{force:!0}),await Bc(c,X,yn)}catch(xe){try{W!==void 0&&z?await he(B,W):z&&await Ms(B,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw xe}return{status:"configured",messages:ee,changedFiles:[c,...I.length>0||V&&z?[B]:[],...Fe?[Tn()]:[]]}},d=await r(),u=d!==void 0&&!tf(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=qP(),A=x!==rf||!!process.env.ANYRAY_COPILOT_MODEL,I=await t.fetchSeatModelCatalog(g.token,{},E,{laneOrigin:zr(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),T=I.find(ee=>ee.id===x);if(!A){let ee=cf(I);if(T=ee[0],!i.dryRun&&ee.length>0){let Fe=H=>`${zr(s.origin)}/v1${Fs(E)}/${Pn(H)==="responses"?"responses":"chat/completions"}`,xe={...sf(),authorization:`Bearer ${g.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},_=new Set,L;for(let H of ee.slice(0,4)){let ye=await t.probeSeatChatModel(Fe(H.id),xe,H.id);if(ye==="ok"){L=H;break}if(ye==="unreachable")break;_.add(H.id)}T=L??ee.find(H=>!_.has(H.id))??ee[0]}x=T?.id??rf}let B=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,X=B&&s.clientKey?Nt(B):B,V=Ik(s,x,g.token,B,T,E),W=Ik(s,x,Nt(g.token),X,T,E),z=Pn(x),me=I.filter(ee=>Lk(ee)&&Pn(ee.id)===z).map(ee=>ee.id).filter(ee=>ee!==x),De=[`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}${A?" (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&&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(ee=>{let Fe=ee.indexOf("="),xe=ee.slice(7,Fe),_=ee.slice(Fe+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${xe}', ${cL(_)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${g.source}, and the gateway key from \`anyray-connect print-key\`.)`,...De]}:l(V,W,De)}if(!QP(s,h)){if(p&&!i.dryRun){let E=Ct();if(await gs(E,yn))return{status:"reverted",changedFiles:[E],messages:[`removed a stale Anyray ${yn} 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:",...Ok(t.platform(),y),...Rk()]}}return{status:"held",messages:[...p&&i.dryRun?[`would remove a stale Anyray ${yn} block from ${Ct()} (org lane, not chosen)`]:[],...Ok(t.platform(),y)]}}let b=JP(),v=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,S=v&&s.clientKey?Nt(v):v;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...nf(s,b,S).map(E=>{let[x,...A]=E.replace(/^export /,"").split("=");return` setx ${x} "${A.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${ll} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(nf(s,b,v),nf(s,b,S),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===Ds?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=Ct(),c=ef(),l=await R(c),d=l?Sk(await vk(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${yn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Tn()} if registered`,...await R(Yo())?[`would remove the Copilot sign-in Connect minted (${Yo()})`]:[]]};let u=await gs(i,yn);d&&await Ms(c,{force:!0});let f=await aL(),p=Yo(),h=await R(p);h&&await Ms(p,{force:!0});let m=[...u?[i]:[],...d?[c]:[],...f?[Tn()]:[],...h?[p]:[]];return{status:m.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${yn} block from ${i}`:`no Anyray ${yn} 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 ${Tn()}`]:[],...Rk()],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 M(Tn()),i=mr(s)?s.mcpServers:void 0,c=mr(i)?i[qr]:void 0;return!mr(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"]:tf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(Qr)?!0:!await t.detectCopilotSeat()}}},Dk=lL();import{homedir as Wk}from"node:os";import{join as gr}from"node:path";import{constants as pL,chmod as fL,copyFile as hL,readFile as pl}from"node:fs/promises";import{applyEdits as mL,modify as yL}from"jsonc-parser";import{readFile as Nk,rm as dL}from"node:fs/promises";var $k="// Managed by anyray-connect: OpenCode trim carrier v1",uL=5e3,lf=e=>`${$k}
102
+ `).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");Bw(o?.slice(1).map(Number))},y_=(e,t)=>{let n=c_(Fw(p_(),"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=${Vc(a.key)};`;let i=Fw(n,`value-${s}`);return d_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${Vc(a.key)}, CAST(readfile(${Vc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
103
+ `);Yc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Ip,stdio:["pipe","ignore","pipe"]})}finally{try{l_(n,{recursive:!0,force:!0})}catch{}}},g_={kind:"sqlite3-cli",readItem:(e,t)=>Hw(e,t),checkpointWal:e=>Ww(e),mutateRows:y_},w_=()=>{try{let t=u_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},xp=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},b_=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),k_=e=>({kind:"node-sqlite",readItem:(t,n)=>xp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:b_(o.value)}),checkpointWal:t=>xp(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);Bw(o)}),mutateRows:(t,n)=>xp(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}})}),jc,vs=()=>{if(jc!==void 0)return jc;let e=w_();return jc=e?k_(e):Uw()?g_:null,jc};import{spawn as A_}from"node:child_process";import{randomUUID as Kw}from"node:crypto";import{constants as Gw}from"node:fs";import{chmod as C_,copyFile as jw,mkdir as v_,readdir as S_,readFile as E_,rename as x_,rm as Ss,writeFile as I_}from"node:fs/promises";import{join as Rp}from"node:path";var Op=/^[a-z0-9][a-z0-9-]{0,31}$/,R_=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,Vw=/^[a-z0-9][a-z0-9-]{0,31}$/,O_=/^[0-9TZ:.+-]{1,40}$/,_p=()=>Rp(q(),"pending"),Xc=e=>{if(!Op.test(e)||R_.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Rp(_p(),`${e}.json`)},Yw=()=>Rp(q(),"cursor-pending.json"),__=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),T_=(e,t)=>{if(!__(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Op.test(n)||typeof e.op!="string"||!Vw.test(e.op)||typeof e.requestedAt!="string"||!O_.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}:{}}},Tp=async(e,t)=>{try{return T_(JSON.parse(await E_(e,"utf-8")),t)}catch{return}},Zw=async()=>{let e=Yw(),t=await Tp(e,"cursor");if(!t)return;let n=!1;try{await Xw(),await jw(e,Xc("cursor"),Gw.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await Ss(e,{force:!0})}catch{}return t},Jc=async e=>{let t=await Tp(Xc(e),e);return t||(e==="cursor"?Zw():void 0)},cr=async()=>{let e;try{e=await S_(_p())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Op.test(r))continue;let o=await Jc(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await Zw();n&&t.push(n)}return t},Xw=async()=>{await kt();let e=_p();await v_(e,{recursive:!0,mode:448});try{await C_(e,448)}catch{}},Zc=async e=>{await Xw();let t=Xc(e.adapter),n=`${t}.${process.pid}.tmp`;await I_(n,`${JSON.stringify(e)}
104
+ `,{mode:384}),await he(n,t)},P_=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,lr=async(e,t)=>await Pp(e,t)==="claimed",Pp=async(e,t)=>{let n=Xc(e);if(t){let o=`${n}.${process.pid}.${Kw()}.claimed`;try{await x_(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Tp(o,e);if(a&&P_(a,t))return await Ss(o,{force:!0}),"claimed";let s=!1;try{await jw(o,n,Gw.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await Ss(o,{force:!0})}return"superseded"}let r=!1;try{await Ss(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await Ss(Yw(),{force:!0})}catch{}return r?"claimed":"absent"},dr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},L_=e=>{let{command:t,args:n}=pn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},D_=e=>{let{exe:t,args:n}=L_(e),r=A_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},Jw=D_;var zw=async()=>{let e=[],t;try{t=await cr()}catch{return e}for(let n of t)if(!dr(n.watcherPid))try{let r=Jw(n.adapter);if(!r)continue;await Zc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},Es=async(e,t)=>{if(!Vw.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await Jc(e),r=new Date().toISOString(),o=Kw();if(n&&dr(n.watcherPid))return await Zc({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await Zc({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=Jw(e)}catch{a=void 0}return a&&await Zc({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as N_,spawnSync as Qw}from"node:child_process";import{existsSync as zc}from"node:fs";import{homedir as $_,platform as ur}from"node:os";import{join as eb,win32 as qw}from"node:path";var tb=(e,t={})=>{let n=t.env??process.env,r=t.exists??zc,o=(t.home??$_)(),a={localAppData:n.LOCALAPPDATA??qw.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=qw.join(i,s.path);if(r(c))return c}},Gr=/^[A-Za-z0-9 ._-]{1,64}$/,M_=/^[A-Za-z0-9.-]{1,128}$/,qc=e=>e.darwinBundleId&&M_.test(e.darwinBundleId)?e.darwinBundleId:void 0,nb=(e,t=ur())=>t==="darwin"?qc(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",rb=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",ob=(e,t=ur(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return tb(e,r)!==void 0;let o=e.linuxProcess;return!o||!Gr.test(o)?!1:n.split(":").filter(Boolean).some(a=>zc(eb(a,o)))},ab=(e,t=ur())=>{if(t==="darwin"&&qc(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Gr.test(n))},sb=1e4,xs=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=eb(t,"System32",e);return zc(n)?n:e},F_=e=>{let t=`/usr/bin/${e}`;return zc(t)?t:e},B_=(e,t)=>{try{let n=Qw(e,t,{encoding:"utf-8",timeout:sb,windowsHide:!0,...ur()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:ur()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},U_=e=>new Promise(t=>setTimeout(t,e)),ib=(e,t={})=>{let n=t.runtimePlatform??ur(),r=t.run??B_;if(n==="darwin"){let a=qc(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||!Gr.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||!Gr.test(a)?!1:r(xs("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Gr.test(o)?!1:r(F_("pkill"),["-TERM","-o","-x",o])},cb=async(e,t=2e4,n={})=>{let r=n.sleep??U_,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},H_=(e,t,n={})=>{let r=ur();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=Qw(e,t,{stdio:"ignore",timeout:sb,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=N_(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},lb=(e,t={})=>{let n=t.runtimePlatform??ur(),r=t.launch??H_;if(n==="darwin"){let a=qc(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Gr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=tb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Gr.test(o)?!1:r(o,[])};var z_={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"}]},q_=e=>e==="apply"||e==="native"||e==="revert",wb=()=>tt("Cursor"),jr=()=>Go(wb(),"User","globalStorage","state.vscdb"),Rs=()=>`${jr()}.anyray-bak.json`,Ko=()=>`${jr()}.anyray-bak`,Ye="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",at="cursorAuth/openAIKey";var Np="/seat/cursor",Hp="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.",Is=Go(".cursor","rules","anyray.mdc"),bb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",Q_=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",bb,"",Hp,""].join(`
105
+ `),eT=e=>{let t=J_(e);for(;;){if(Ee(Go(t,".git")))return t;let n=gb(t);if(n===t)return null;t=n}},tT=e=>e.authMode!=="placeholder",qt=()=>Go(yb(),".cursor","hooks.json"),Qt=()=>Go(yb(),".cursor","mcp.json"),Mt="anyray",kb="--anyray-owner=cursor-v1",nT="postToolUse",rT="beforeSubmitPrompt",db="preToolUse",oT="^MCP:",aT="UserPromptSubmit",sT="Shell",iT="^(Read|Grep)$",rl="--anyray-owner=cursor-hook-v1",Vr=[{event:nT,flag:Ve,trailingArgs:["cursor"],matcher:oT},{event:rT,flag:qn,trailingArgs:[],matcher:aT},{event:db,flag:Ag,trailingArgs:[],matcher:sT},{event:db,flag:Cg,trailingArgs:[],matcher:iT}];var ub={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},cT=(e,t,n)=>W_(e,t,n),pb=cT,lT,dT=()=>{let e=lT??X_();if(e==="win32"){let t=pb(xs("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],ub);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],ub);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},uT=dT,tl=()=>uT();var pT=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Ye)??null,openAIKey:e.readItem(n,at)??null,lastWritten:r};Up(t,`${JSON.stringify(o,null,2)}
106
+ `,{encoding:"utf-8",flag:"wx",mode:384})},Ab=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Up(n,`${JSON.stringify(t,null,2)}
107
+ `,{encoding:"utf-8",flag:"wx",mode:384});try{Z_(n,e)}catch(r){throw hn(n,{force:!0}),r}},fT=(e,t)=>{let n=Ho(e);Ab(e,{...n,lastWritten:t})},ne=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),fb=e=>ne(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Ho=e=>{let t=mb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(ne(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||ne(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(!ne(n)||n.version!==1||!ne(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Ye],o=n.rows[at];if(!fb(r)||!fb(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}},hb=e=>{let t=Buffer.alloc(16),n=V_(e,"r");try{return Y_(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{K_(n)}},hT=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return ne(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Cb=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(".")&&Lp(t)===0||t==="0.0.0.0")return!0;if(Lp(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(Lp(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 Cb(`${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},$p=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Cb(t.hostname)}catch{return!1}},mT=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},yT=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${je(e.origin)}/v1${Np}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Np}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),Wo=(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."],vb=()=>{let e=jr();if(!Ee(e))return"clear";let t=vs();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ye)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ne(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},gT=(e,t)=>{if(!$p(e))return{routed:!1,problem:"gateway-not-public-https"};let n=jr();if(!Ee(n))return{routed:!1,problem:"state-db-missing"};let r=vs();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Ye),a=r.readItem(n,at)}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(!ne(s))return{routed:!1,problem:"settings-malformed"};let i=`${je(e)}/v1${Np}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Re(a)||!Re(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},wT=(e,t=[])=>({command:Pt(e,[...t,rl])}),Wp=(e,t,n)=>{if(!ne(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Pt(t,[...n,rl])||r===Pt(t,n)||r.endsWith(` ${rl}`)&&r.includes(` ${t} `)},bT=(e,t)=>ne(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Sb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Wp(a,t,n)){r=!0;continue}if(!ne(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!bT(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}},Kp=(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},Eb=(e,t,n,r,o)=>ne(e.hooks)&&Kp(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Wp(a,n,r)),kT=(e,t,n,r,o)=>ne(e.hooks)&&Kp(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Wp(a,n,r)&&lc(a.command,n,[...r,rl])),xb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!ne(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=ne(e.hooks)?{...e.hooks}:{},{entries:s}=Sb(Kp(a,t),n,r);return s.push({...wT(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},AT=(e,t,n,r=[])=>{if(!ne(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Sb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},CT=async()=>{let e=qt();if(!se()){let t=await Rb();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${_e()}). 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 M(e);for(let n of Vr)t=xb(t,n.event,n.flag,n.trailingArgs,n.matcher);return await Z(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}}},nl=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,kb]}},Mp=e=>ne(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===nl().command&&e.args.length===nl().args.length&&e.args.every((t,n)=>t===nl().args[n]),vT=e=>{if(!ne(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")||Ke(e.command))return!1;let t=e.args;if(t.at(-2)!==er||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!Ke(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},ol=e=>ne(e)&&Array.isArray(e.args)&&e.args.at(-1)===kb||vT(e),ST=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,ET=async()=>{if(!se())return Ib();let e=Qt();try{let t=await M(e);if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?{...t.mcpServers}:{},r=n[Mt];return r!==void 0&&!ol(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]=nl(),await Z(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}}},Ib=async()=>{let e=Qt();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!ne(t.mcpServers)||!(Mt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!ol(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 Z(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}}},Rb=async()=>{let e=qt();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e),n=t;for(let r of Vr)n=AT(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await Z(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}}},xT=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=eT(e);if(!n)return t;let r=Go(n,Is),o=Q_();try{if(Ee(r)){let a=mb(r,"utf8");if(a===o)return t;if(!a.includes(bb))return{...t,messages:[`Left ${Is} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Hp}"`]}}return j_(gb(r),{recursive:!0}),Up(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Is} 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 ${Is} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Ob=async()=>{let e=await CT(),t=await ET(),n=await xT();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Fp=async()=>{let e=await Rb(),t=await Ib();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},_b=async()=>{if(!se()){let e=await Fp();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${_e()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await M(qt());for(let r of Vr)e=xb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(Qt());if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?t.mcpServers[Mt]:void 0;return n!==void 0&&!ol(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${Qt()} 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 ${qt()} and ${Qt()}, then re-run Connect.`],complete:!1}}},IT=async()=>{if(!se())return!1;try{let e=await M(qt());if(!ne(e.hooks)||!Vr.every(r=>Eb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(Qt()),n=ne(t.mcpServers)?t.mcpServers[Mt]:void 0;return Mp(n)}catch{return!1}},Tb=["openAIBaseUrl","useOpenAIKey"],Os=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!ne(t))throw new Error("Cursor application-user settings are not an object");return t},RT=(e,t,n)=>{let r=Os(e),o=Os(t??void 0),a=n===void 0?void 0:Os(n),s={...r},i=[];for(let c of Tb){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:Ye}:{key:Ye,value:JSON.stringify(s)},conflicts:i}},Dp=(e,t)=>{let n=Os(e),r=Os(t??void 0),o={...n};for(let a of Tb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Ye}:{key:Ye,value:JSON.stringify(o)}},Qc=e=>typeof e=="string"&&e.startsWith("ark_"),el=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ne(o)&&(n=o)}catch{}let r=Qc(t)||n!==null&&(Qc(n.useOpenAIKey)||Qc(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,Qc(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}},ot=(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.",...Wo(e)];let n=ce(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.",...Wo(e)]},Bp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!se())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 Es("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]}},OT=async(e,t)=>{if(!Re(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 lr("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 _b();if(!n.complete)return{status:"manual",messages:n.messages};let r=Ee(Rs())||Ee(Ko());if(r&&tl())return Bp("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=vb();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 ${Ee(Ko())?Ko():Rs()}, 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 ${qt()}, and register the Anyray retrieval MCP server in ${Qt()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await _s.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 Ob(),s=[];if(!t.preservePendingOp)try{await lr("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 -- "${Hp}" (connect already writes ${Is} 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."]}},_s={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>tl(),quitTarget:z_,needsTarget:e=>e!=="revert",async complete(e,t,n){return q_(e)?e!=="revert"&&t?_s.apply(t,n):_s.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=wb(),t=Ee(e);return{installed:t,detail:t?jr():"Cursor user dir not found"}},async watchPaths(){return[qt(),Qt()]},async mcpStatus(){let e=Qt();if(!await R(e))return{registered:!1,command:null};try{let t=await M(e),n=ne(t.mcpServers)?t.mcpServers[Mt]:void 0;return Mp(n)?{registered:!0,command:ST(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=qt();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!ne(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Vr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Vr.every(c=>Eb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Vr.every(c=>kT(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=Qt();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!ne(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Mt];r=i===void 0?"missing":ol(i)?"owned":"foreign",r==="owned"&&(o=Mp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Nr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await P();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(tT(e))return OT(e,t);let n=yT(e),r=mT(e.openaiBaseUrl),o=jr(),a=Rs(),s=Ko();if(!Re(e.clientKey))return{status:"manual",messages:ot(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(!$p(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.",...Wo(n)]});let l=await _b();if(!l.complete)return{status:"manual",messages:l.messages};let d=vs();if(!d)return c({status:"manual",messages:ot(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Ee(o))return c({status:"manual",messages:ot(n,`No Cursor state DB at ${o} (open Cursor once first).`)});let u=null,f;if(Ee(s)){if(Ee(a))return c({status:"manual",messages:ot(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{hb(s)?u="sqlite":(Ho(s),u="value")}catch{u=null}if(!u)return c({status:"manual",messages:ot(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(Ee(a))try{p=Ho(a)}catch{return c({status:"manual",messages:ot(n,`Existing Cursor backup at ${a} is invalid \u2014 refusing to write or replace recovery data.`)})}if(tl())return c(await Bp("apply",t,{status:"manual",messages:ot(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Wo(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}, ${Ee(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 ${qt()}, and register the Anyray retrieval MCP server in ${Qt()}.`,...Wo(n,r)]};if(u){try{d.checkpointWal(o)}catch(b){return c({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${o} while migrating the legacy Anyray backup at ${s}${Cs(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=el(d.readItem(s,Ye)??null,d.readItem(s,at)??null);else{let b=Ho(s);y=el(b.applicationUser,b.openAIKey)}}catch{return c({status:"manual",messages:ot(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,[Dp(d.readItem(o,Ye),y.applicationUser),y.openAIKey===null?{key:at}:{key:at,value:y.openAIKey}])}catch{return c({status:"manual",messages:ot(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{hn(s,{force:!0}),hn(`${s}-wal`,{force:!0}),hn(`${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:ot(n,`Couldn't checkpoint Cursor's state DB at ${o}${Cs(y)} \u2014 refusing to write; set it by hand:`)})}let h;try{h=d.readItem(o,Ye)}catch{return c({status:"manual",messages:ot(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=hT(h,n);if(!m)return c({status:"manual",messages:ot(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(Ee(a))try{fT(a,w)}catch{return c({status:"manual",messages:ot(n,`Couldn't update three-way ownership in the protected Cursor backup at ${a} \u2014 refusing to write; set it by hand:`)})}else try{pT(d,a,o,w)}catch{return c({status:"manual",messages:ot(n,`Couldn't create the protected Cursor value backup at ${a} \u2014 refusing to write; set it by hand:`)})}try{d.mutateRows(o,[{key:Ye,value:m.value},{key:at,value:e.clientKey}])}catch{let y=!0;if(p)try{Ab(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 Ob();let g=[];if(!t.preservePendingOp)try{await lr("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,...Wo(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await P().catch(()=>{}),n=e;if(!$p(n)){let o=t&&Qe(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&je(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Ee(Rs())||Ee(Ko())||vb()!=="clear"?!1:IT():gT(n,r).routed},async revert(e){let t=jr(),n=Rs(),r=Ko(),o=Ee(n),a=Ee(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 ${qt()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${qt()} and unregister its owned retrieval MCP server.`]};if((o||a)&&tl()){if(e.fullRevert){let h=await Fp(),m=!0;try{await lr("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 Bp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=vs(),i=!1,c=!1,l,d=[];if(a)try{if(hb(r))if(Ee(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=el(s.readItem(r,Ye)??null,s.readItem(r,at)??null);s.mutateRows(t,[Dp(s.readItem(t,Ye),h.applicationUser),h.openAIKey===null?{key:at}:{key:at,value:h.openAIKey}]),c=!0}else i=!0,G_(r,t),hn(`${t}-wal`,{force:!0}),hn(`${t}-shm`,{force:!0});else{let h=Ho(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ee(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=el(h.applicationUser,h.openAIKey);s.mutateRows(t,[Dp(s.readItem(t,Ye),m.applicationUser),m.openAIKey===null?{key:at}:{key:at,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${Cs(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Ho(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(!Ee(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=RT(s.readItem(t,Ye),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,at);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:at}:{key:at,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${Cs(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{hn(r,{force:!0}),hn(`${r}-wal`,{force:!0}),hn(`${r}-shm`,{force:!0}),hn(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 lr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await Fp();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 iP,mkdir as cP,readFile as nk,rm as lP,writeFile as dP}from"node:fs/promises";import{randomUUID as uP}from"node:crypto";import{dirname as pP,join as rk}from"node:path";var _T=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},TT=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},pr=e=>JSON.parse(TT(_T(e)));import{spawnSync as PT}from"node:child_process";import{platform as LT}from"node:os";var Pb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},DT=(e,t,n)=>PT(e,t,n),Lb=DT,NT,$T=()=>{let e=NT??LT();if(e==="win32"){let n=Lb(xs("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],Pb);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=Lb("pgrep",[n,r],Pb);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},MT=$T,Ts=()=>MT();var al={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 FT}from"node:child_process";import{readdirSync as BT}from"node:fs";import{createHash as Mb,randomBytes as UT,randomUUID as Fb}from"node:crypto";import{chmod as HT,lstat as WT,mkdir as jp,readFile as Zr,rm as Bb,unlink as Ub,writeFile as Vp}from"node:fs/promises";import{homedir as Vo,platform as Yp}from"node:os";import{dirname as Hb,join as Ps,posix as Nb,win32 as KT}from"node:path";import{promisify as GT}from"node:util";var _n="0.1.21";var Yr="8c2875844439f1b8a906d1b16e85cfc04f559096f7af88f6b9a26d877eee1c82",sl="22be5f6ea9b3bf833982e1be741254dba1c37395e5b133caa071fbc3d91efdcc",Db="UEsDBBQAAAgIAHwuCl3s2NkrBwMAALQJAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGcoqXlU+GsNhAUOxEqBQrk+hhgRI5WE1MkweHKUn99sbv6spKmlV3ktsuZeY/zwUfm79dLK1YYmbzryW52JQU67Q25sierNO/8Lt8Xlxf5BPQjlDgGR3PkJB52IdfZVR20XlrHPblIKdwoxXqBS+BsSTp69vOUab9UBldofcCoVrzutD7q+qrb3YbfmBcAdAwyla7FKS4vLvIxJjCQoP65yIcGXaK0ESNwZQUl9iS6zp9TKYamJ8FtImw6K9beoDxkdZV1s+uuFJNqZokXGHeuUqgW9wNxsLD5DEss+o1JzH0UD1Mx8AZzdWxvA5B1pJDIuzrdGw6gsSdDRMa4Qln0jRG4DpY0JbGFLCHhE2zE0hu0LHzcGjpPEUJAIwY+kPVJcDU7wG+90yL6qlzs9vQGgud3LPx8TprACrutSKfxFyH6FRmMoj8ZZrk62m+bwD2UXDyP4Vw1q419AAlLHwm56A/fjkEvyKEYIURHrszVkb3x/wjWYtzc2RqhKbTO1bPF2q1xncS662kXul/YNE0c74fkgbgCO02VIZ/VOWe3riRXdxZshT35tZt1r5spV2cjrRO6ejo+YEBn0GlC3gO/BrA+W/8L0B/kzB7oycfHZsbeVvQC0JHXYOkvNLtz87pcHcwsmn6gOsQz2B/AnZ026iohD9qj24KlWOELAKcYV6SRsxG5R86mvor6AFqLEt8oVVJaVLNGilo1+PRFLb3zEYPPSkrnFeaE8yMmThATml/MS+lTNfu1nNMqBB/TWaSKmKt6Cl/B24jRWay/RQSzPBmpF/C3Vb6zsPIRzRjio/FP7sdjex7ywLuELmWTSJpcuYe8i4hSFZfPt52rEy3NR6TRMRa4UxE1Gg5uP09vs7ROudqZt1qcq+PrNR86TmAtHG6J45V7iCWmfzvIskk7V6dY+bHQtj59ZkzbfTff4n4T8OcysXuySDGBtOjJQ56hfdNk39g7KfrGRGSudep5P/4L03fd2Jbte9Kj4v4zZ672mebq5OlV/A1QSwMEFAAACAgAfC4KXd+jDd+8AAAAZQEAABMAAABbQ29udGVudF9UeXBlc10ueG1sfdAxbsMwDAXQPacQuMd0OxRBYTtD2hv0AoRCO0olSjAZQ7194WQL6s7873+A3bGm6BaeNWTp4aVpwbH4fA4y9XCzcX+A47Drvn4Kq6spivZwMSvviOovnEibXFhqimOeE5k2eZ6wkP+mifG1bd/QZzEW29vaAUP3wSPdornPaiyP3eaq4E6P3DrVA5USgycLWfBKC6mfQzHALZ7lv4L1vEGt2pM0roYlUtg0i4aaSMLI+ieuKa4U718bdr9QSwMEFAAICAgAWy0KXQAAAAAAAAAAAAAAABYAAABleHRlbnNpb24vcGFja2FnZS5qc29udVTbbtQwEH3frxjlBQmIs7vluk9UpYgKiorK5YEWyWtPk6FZ27Ine1HVf0d2vMkWlackc87MnLnlbgJQGLnCYgGFNDsvd+U6KKuxeB4hTcG1cvclM44TA26shx+XcDLSMChPjsmaRNMacOtaUsSQfWrJuJE7WFmNbQDrM1BuvHQONZxYR61lCN1yCLZnc+NtVzf7pE8C2JsbUiRbaKWpO1ljmajgvF2TRg/HF2eiF7dGH7KwqZiJ+aw3O09rybEs9h32pm7ZUmjQj93ouS0pNCG14PzsW2/z6Gwgtn5XLOBuAgBQ8M4lUk2cSABF59tsedYwu7Coqpq46ZZC2VXVJ/n4tVpZY2NEceCqyaPKCYp+KiVuGU0qZwJwn4SgqclgGFXkAS6g+D0Ts/lMTEeykoy19ZT4v3r+8dk+47lUDRmEzyi9IVNHv+vkt5KUOigqTYGrQYb4E/p2DJZPZPQYe2P9bXBS4dAPGoMq6eSSWmI6lN8Z9l1g1D/3viMIUITOOesZdZ5cst8PBUrFca5kzekaDR+Uac0lS8+d+0AmTlnvJVnz3R+qsoY9LTs+FLVfs/O4ZSeN5Iu8aGMCGDSmpTPa/rtHGXv0qIqM36fn9VBPfwsHSpYdtbH2wliNgCF9i1WeQ9xiqW5ljYt1oG3eHIRshLI0ttTo0Gg0ijBAWdqO4cHti+Saw20kq+axfFCWPfZ8XH7VoLqNZA4q5TpdjfvMGHgIVJa0inMEDlsoy4jBVRG8quJr9VTEh+BwVezde20L5zHf6X9EOW91p/jBjWhcvz8oeuzmu6g6VCYfzPxV/EPsM2ZwvKd4TlMxHfAeiYQEH4m3o3MW1f925m/EbGhDSGN5IeZH4uVh8/pRR+y1mIp5Uj+5n/wFUEsHCOw4L8eaAgAApAUAAFBLAwQUAAgICABbLQpdAAAAAAAAAAAAAAAAFQAAAGV4dGVuc2lvbi9MSUNFTlNFLnR4dF1RQW7bMBC88xWDnFJASIsceuiNkWiLqEwaFB3XR1qiIxYyaYh0A/++oOwkTU8Ed3dmdmZXXKNxnfXRElKG02VyL0PCffcFj98ev4P6y2QuhKztdHQxuuDhIgY72f0FL5PxyfYFDpO1CAd0g5lebIEUYPwFJzvF4BH2yTjv/AsMunC6kHBAGlxEDIf0aiYL43uYGEPnTLI9+tCdj9Ynk7LewY024j4NFnftDXH3ZRbprRmJ88i9txZeXRrCOWGyMU2uyxwFnO/Gc593eGuP7uhuChk++44kBZyjLeY9CxxD7w75tbOt03k/ujgU6F2m3p+TLRBzcQ6wyD6+hgnRjiPpwsnZiNnrx3bzTF79lANNt4hirrwO4fjZiYvkcJ68i4OdMX1ADLPib9ulXMnjhzCO4TVb64LvXXYUfxCiBwuzD3/s7OV6Vh+S665xzwc4fVz11oqDGUfs7S0w28N5mH/sTFk+JuOTMyNOYZr1/rf5QIiuGVq50FuqGHiLtZLPvGIV7mgL3t4V2HJdy43GlipFhd5BLkDFDj+5qAqwX2vF2hZSEb5aN5xVBbgom03FxRJPGw0hNRq+4ppV0BJZ8EbFWZvJVkyVNRWaPvGG611BFlyLzLmQChRrqjQvNw1VWG/UWrYMVFQQUnCxUFws2YoJ/QAuICTYMxMabU2bJksRutG1VHk/lHK9U3xZa9SyqZhq8cTQcPrUsKuU2KFsKF8VqOiKLtmMkrpmiuSx63bY1iyXsh4VoKXmUmQbpRRa0VIX0FLpd+iWt6wAVbzNgSyUXBUkxykXeYSLjBPsypKjxqeLSDX/Ny17J0TFaMPFss3gbPFt+IH8BVBLBwiyhnqNeQIAACcEAABQSwMEFAAICAgAfC4KXQAAAAAAAAAAAAAAABsAAABleHRlbnNpb24vZGlzdC9leHRlbnNpb24uanPlfe1227ay6P/9FBKvlw5xAtN2kma3VGFe13GbtPlq7PTL0bZpEpJQU4BKQrZVmc9y/t3zXudJ7hp8EaQkJ937rHN/3NXVmAJBYDAYzAwGM4NgUdFeJUuWyWB4k5a9nyR5e/U7zWSUlTSVVBX+astyOmacvivFnJZyqd597z6YUPn2ltuXz2mVlWwuRamqfbOl2pt0RivdiV/jXSmkkMs5fTvGP7gXc1saTdPKa0R9/4skIcUSkcPVWJQhFPEe4z2Jfg0p5ng1oTKW53yEKV/MaJleFTTu79eoxm+o+hRzLOBzNg7lYAD9iHFPEhII1X1wf++VjRc8k0zwAEFvBZW9sifGvW9kKBHq/yCjLC2KkOISDQZlnxA+GAAcpYYjRORQnpdtWEJBvpehxCVC9/cial7VaFhSuSh5j9ZqrC8twIgchpzQPuGLokh+kuGvMqQIxSsYVCjv7/sU/o8uLmj1WuSLgia/hhwHOR2ni0IGeHWTFgsa0y5SYo4pQvg3SSg5fEPDX8NVjYOmGfclVMYUKbCkIKt6+IsMpcCrNJPsJpVUjfVHjnPaKqGiRsOZaiuid3NRyor8Bl/qpl6TlzQs6R8LVtIwuKkykdMAIfydJK6Ui5zGWbmcSxEg/Ef3zbjam5dixipaBbrR30mQ8mWZLqNJKultujwWfMwm0c1BgH/ovvuBLvWS+FkSTm97p1SG58GiomWAA0nTWYADxiXl0j28Sq9oEeCgolUFpDFC+EeFQEoICQqRpcVUVEBIquA8jg9Gwf393j8OHv89TOKP0cd8dYCf1Gj1pN7ZiyStYDbxL9CEokpNfrRPAlizfBIgTRdBMJTlcgVUqIH98P5VSCNZslmIHPGYBZSJok9IMJVyHgeDwXppFQOpu2LiVe7/KEMZwSB4OqMIqgFG4If6JK2qW1Hm+llOoRxa3VMNVjQtsyk8TdNqmgRBLCNRsgnjdZbKbLqyg6lr/BuMGYjXG7NbhkclzBOr1N+QomRVx4ZFjEsxO+GyZLQKTRE1PymKxqyQtAzDc4n5CJHDnxUooURuuXPicDsY8KigfCKnh/vN89fk8RfPBoP+3vnHxf7+/v4u/DkYw79/H4/MpHGEolk6bzrSfxHeoTAuOya/r71/pOX1xfnR7m/p7p/7u19d7I5Wj/fxFwePPVJIaHwjWN7bx6+2NkQ9oGkD9P7+p4D2m//Jkly/i2tDceejoaa28xHmdn0MLSsUwAppVBUso+E+fvYUIdWYcPMpts+nQCgTXDK+oKqPkgjMyCsalhHLEa70o6K/YZ/d3/er+3uu5pGh+/uQR2mehwxhGc0X1TRcsTxmGKrHVY1QbRdDjZ83bB+X5BzmSS0hRn6BZVeRHRpKNATATTcCiDkTc1YIuVvRVAaDgSozPGM3nbMAyWkpbnuAk5OyFGUYMH6TFizvmVq9TLGdRZlqAaJGWZCfwlJ1JkinwcGgMPNICNn/dPMzkdNirRMz7u9P376JNLGw8TJc3dASeFV8gM3nH8oiZrhhgnGFZ1SmeSrT+LeQIwzNx8LWeA2dVXEBcvSDIkrDhla140k5Ub3O07KiIU2SIEDD3C25vJGwg0GH3nI0GOSRgZEQcjAYhJLkyDCMGlrn5JdQRg30CAs1cx4jR7gkv4UysgNBmBEZwUC6uAbuZMtbE53ocrtAKsKSpF0DwxS6XjVeLNpXHnK5j1zRILfUmK26mMWsOjZzSfPY50lAehqewYB5z2G1Bv79feE+RLXWIn4mWZFW1SoTvJLlIpOiDCVaySmropKmOZE1/BnOKc8ZnwwnVIZqHasaphTZ9eSVGdbgGgpRpOYr5ORwpcnXr04IkTCvfpEeCsK80X1a7yWWtaH7VNLQQN3+2gzzw0N6Af6TdhWKKSvyi3kpMlpBhVed9yDXAoTn1KqbilbytLxlPEiCvVfsqkzL5d7RfF6wTK2+3uliDhrO3pHSMPauhJCVLNN59HsleBCrFm4Zf/I4SF5F6iH6XTAeyuhdKSZlOnueyjRJguP440evJMCBbjHAQadNFIf7+JVqBYXBHpVZgI2Cs6EypvyviZMvDh4PBudRFNFRRG9ouQylWficyCibpuWxyOmRDPfd9PFD8uTxYMD7hBw8/nuNBoNQgciqo6tKFAtJUQgahUVAUw5SB0tO9v5hxOOoQUPvW1bQKux9DO++fPYRoeTjxz2GJ25ypIdaya2gi/v7eEZJWi15pkUA+RBVMpVW/W++MvTd33fcTJD0NmWyx0PqBieiBcuBOw8GoVCMYnDwJYKClmrTP6hrvPQ6Jh/UAoFBQNe2C266kCHFwUKOvwyUZLA6SqP/geQz8/N0/6tnBtjVvKQV5TLuH9RDDbLHgLmTMrBp+DyJDPuRG5i5pnpUVWJNEV3ruSQiumJ82H29j68YjykPS5SUsV2vPq78puoaT92UKrJLzukoPh/hKIr8KT4fxeeGzHczwTmMZjTCnPsfT6n6oTQ0Tg7D1ZgVNOY4LSfVu5KO2R20LNmMioV8XcUZrxHa1JP+MODzu6D1cbC7u6SVW3AWkv9dpEB/gd/2d7QejbDgzX4OBPs7zZ9CQQ5X4T7+E7ZINFNUouqtTAMxx7P07pvFeEzL+NnTfz/Yf/wU3zKei9vqBcvV7gyHJWZWtalIaeY92Y/NTJZRpgRewBezK1oGiS5IkoMYKg5FuKJ3TB5r4VTJHDpmSSTFqZr7EIFErxH8h0vuqQB2BxJV84LJ8PJvlyiai7n+YNgQu0ecWt/iXeLkDXEaSjN0zdWyXVSKpEET40LMrVZGeSmKgub291Uhsmuat5ooCXO44eds5KSN7rhqeGFSWTq11Ky7jgVelEVchsGiLAKEAXnwS29Z8YxWVTpRJeYxQG1Kr2tccadw0/t7x3O/OHhs+c+BwpflpXaLh9Z2aVUcrLOcdCt7dzx1f/er3dHqKT545m89c06e0ae44ORg/9/hKdMF31Fy8CV9ihecPKZP8ZiTg8fq/R+wTMmqRh4RzItUjkU5SxIjVV0J5oRGlN80byi/wYJQxxWTpOGQuCRUTTcUwl/MoOaCJ4nguCI04kKy8TJJQs1gETnsHyBcEBqJOeUndxK2qoX/flUjnKsvb5PkeSrVE06ho4LSeZKEs/aSvCKHFZVnev2FV3iGEMIZeaPWTvTm5Lujs5c/nVy8fPPtyzcvz37FSzzd/vKG9A/whRYHvZmxXAHarmADxXk4wxIhhcgzIxJYeAXbWIqBk11FDdsB64zhN9pcsgt6ZDDCV5FjN1YPMyNXW5uz+/uzyC7wPmwwWruvE1Ly8CzSy159cWJ5fSZms5Tn8RW+oWXOMhmfAKdeeOOxMM8amGctmHd3pRAF8EqjrgbYcM8R/o524K3x2GsbgL9BqxviyeYrkofo0ZirnegwD9HXV0PExqGGIw0XHOHwk0DNS8bl7jVdBiN88AV90gEDJQ5fakNmRrkIZ1YfqOsx42lRLAE6EF+WY2jox6BNIiXt2TjMQ7SbfZ1zy5UyGIPC/YzMaQhSAV+Z2V/ScIaFnriryEhIn52dkSuQt95mYEJDVYTByqFbmUErYGfEJ6bdi/AsUbUMi9M9nHgtu9l+4Wb7riYnUO/O8GDis9wGKy8cVry6PjuGvTUP76JFWaD7+34Kz0DA1tagYDFlfUKWsCcM0e7064Kj1dhrf0l0JTwFFGJ4hTUUVXipNeW4V7GJtguLHuVg72y25dNU6s1z1fu4eLx/8LS3FIuyB032WNXbWenm60scvJ1TrpraZTxwiC3MKOz2tDZbENrdZAjYWfy4eWfx9sH9yk9r+xVjAFUdfbvtLX7zYKsvNgI4V2KDJkZBIMHJm7cnb84C/Htbdw738YuGzaMQGTUayNCq0Zocwn38JiqpMt4oJcxOnZbmlzsrWUeGi4ki391ZOZHB8np3B7Shb2lUpjwXsw8fXj5HIaovcUmMfNTmm6arQin1zooTsQoESYgGA/XjdDm7EgXLXjF+HaJ1y0pJx4uK8QkQS0nnRZrRXtrjgu8C5+jltJKMWwPL+gAlFmB56JtNQMi0FWzOQ2Y7YzWAvRk3ra9KtLmicBVXXfAvxykraA7AzxdXBaumPQV2yvNeSSspStqTU9qbl/SGiUXlj2fYK2kmYGfXy8R82SvpLGW86qWyt7MS9SWqLfylIX4N1QwgAjGWmcMVRZYTTowNf3cKUzceVwGeNYUlzSibyyrA31PyGC+9vZ4xhR48wwePv6x39vCUe+Z4pWNh9WeX8YrltARZopplixlY4L+h0Nj+7ldm79g8Ro92R6t9/AyM7fhXVS3dHe/vfjVaPXsKZbdu22A1s8+xRm830LVMcj2DCWP/44Qqzdcau/qEfE9he8cFz4DtyUYZjm7SkqVc+vvA/lTbQN3LfwIONg5DDqcxNJM0B3WJAyg/OYi0cACo1io9Z5U8naaPv3jm6sEW34G8vVVvDN9QYz/fWh15WHgQBq/VX7e32nyB/jl88ShVx4DAHUEau/1Jz24vfgl5yzjJCN9sYQS0bjJJJrxjefypadFaGT1ItIna2Ath+OX9Pdiv2bpZufLMyh5es4JRLn+gyxYWP+OAwvv0n8CmUZGiKOK+LdqYRVnHLFrVNf6hJYawAEFEaTQVM5qzspFD/aWz/HwuWGrV6Sn2qPLGEaFHVLlHQ1tbp5bielcLVuQ9llMumVya1V8C6D8ac53AQWRNdROOL3dWtFaGukuEmRNzqRNzb62Y0+cH6ZpgA6XKib77+zSq2J/08ODZky+frkO84FU6pg/yCIVlT9w3Yh6Meqm2fz17AuUNXVlBPqFS2cqaE/TBIAXzWZ+Qdp1w05r8FHjkloeePaHBkbOzhaW1qcHBtdPUm5oLXjB+DejsbD+0lWDLTM14owK8jWbXigIrvCpptigrdkOV0RFI+enTL2t76OM1VsFMM8u+3YznZsuTmh11BlpSUUdKF/qpqwtFcja/HPqqwtvotmSS6qFn0Me2I6DvKVZkH1OsWUmcYtrhv7FbBM2rhonG/moAi1lKWtxoMGAev/TL/QMS5vFLs/gVSdU1qv92iVeq6MmXT2ur3f9OwwwXm6YSyDPz9ZHOjNqNWW8bXOzT4nAwCB+s5TB2f7+hXktutphJYjaqOeihhUjzXaOi5wHC60VxuHkMiTElR64obCGYNUwb/xYy/4xMYR3/1NQ34gbFtk0l8kI7D7kDAT42T1oDnG/251Dv/lQ+JtpGAlyKM2XzHwzo4X7yOpXTqBQLnoPdfh9LuunUiljTjTkI4uKWyKF6rGRaSpofmfMoLm5DVHNxO3QvhmIu2Yz9SU/XSp4LTo/kEACnlTylXB7J4ZiVlXyXlvBcpO5xnoIPy/6wpNqbZb/drj2jWuvMh8u+POH51vo+4bVqaGC95uCw2wEeupM9byx+33MPSDWWR+TAP8lTtTROPQyQLjT+O4mwKmuwpM4UAT8NOApbj8gBLF9WTeEIUivEKwVF3ACETeXY/xJnYsHlcVoUVfxnqP2uKmRLsyl9waR9Y34hLIVMi9eq2A1tt00uqG4dPD40DRtmwZ8k7t69rsifm+Zsd3MXyKCvNWXdfj18tzt1L5pevbq76y3b7ja32JnIdl+VLGk6azpq6u12m0RwqFvjXygJ7nbbBkvl/YNv2ru/6GIvhg2g3f/95g6CDJmcX6rZJDsrGpl5rS8bO74H6I1RA8ESxrV3yKWy9xCwO1wiTH2keR/ayu6t6syrqz+2WNjwpX6lPrO19DcNaWz4yr5U3zU14UtbRXMdeK+e/FeWEcFL8+y/btaNqtH8XKsEa8avY5aRrqcOqgMcoBr/7Pt/nLsp2DJI+YlBzqoHZkR+ckbM5xvmRD4wJ+oruR238mHcSh9ta3jd24BDxZRy79N1YlYwXYJ1Mu4phO6spEF7L0D1pZawP1IS7N0c7Dm1rNrTy2rP4jTAR1zXgbb2MjGbFxRkdBVgLjuryk2F0rATe8zmptRwDqIME74ypDagKTg/0Dyo8WtODr7Y38dnnDylz/AxJ1/SZ/iKa2uLM+9gbXG54GSLjxq+VR6Bfer8hugDfkMUYaE8L1eNX6Tvg+QO7m9DiRJpD/Y6p3I7Cifg8If+inOEHAz6F27Hie+as72wf6t8HGgErfX9TdD9PbyL7G8EJsqwvxNScHq7v1dP9mVknS8NSM2LtJwsZpTLqrV1FzLcVAdZAzu4yEE/GBqMG5iwfYpXyn+uAwF2LcWbmoezoJNm7HrkfedCm1YVq2Sq3GfhDCgYRYxnxSKnVWgOlmlUioI6MIf2QBFKh9ZNo2mnoQzQdcEht9+aK1doz5b7n/05TJlxZrV0rmbETgQAogZhyuH5AjSRCzV7qifzvv3SM6qtgePVbNiXjwtzMrKx3mCw5rvpVdM06H5aMn78xTPwoCStd+Amcced8+w3QhQ05cD69Vd9Qja0hRrqgumKJTZIjR16lUuFRTlg0l9aluLgTw01+WCwanqJed363Mdpqxn/RdyuBwR6+i8uzu6S9EpyEwHR3iuur9lWPZ/gXI15WqYzKmnpT28LIq9Kg/e/uJp9dG4CroVWrzzeXF3NzzYYB4NV8yveWAcOz/B12wJvJ0gpbWAT10/392ukblwtNKHbHy1z51rx4QF92lpdxKsCi+BkfRFow6u3DjptdpxV6G3vdTrHpT3BwAzUJHvov4BDf9mA7rwBxvBi4a2xJDkfqVMhoWz+Y5ARtisRwZYcirCe5/FWrj3exLVh626UmLQo4p0VNAUHPmwcLhTr9Zjdos3p1EGVAqnzwgJXKufszkvXYUmrRSHjnVW7AnRubG8Wb4V7ytcwyD+JOH22LsDMqHEH01g1qLy/nyWW3Xewd38/84Us2YRCO9hKDVa1iPPPxamGbkzaKFCMXmN2DFK0co+FeXKUpjttenRIHTs8pmsIA7NxoszC6lnD5ISWsh/ntKCSbptYbVM2HpCplVVD60qyaaDmy6bYl32tSTOLSbVsz/4WXRE1Jod6HWg7bUb226PMNVkMs6+Za4+dZ6M+IYshysDYwcZhRghhncWbKeOE31aFGkIHWVCYR3+5L6E5LXA86b0ppkLXcSLZ40dP7u/DJbHFMMrTDYJ42RXEjQz24Fk41IVS11KLQbU6I4ezjihDeOzCOtg4XEaVmNEwXDkhMgMfr/5CjXxmxd/Y/5n09+NwrOjRlOD+gRNPapamRFlzi9hwcustV8UcxMfSCPAqXmpxbzZqnhhc6ZLYvqprfEMoviDnq2u6jANJZ3NaphJMoXjGeLwPLpPx4xqb92J+MfffHNg3s/TuQoprCtsj70P6FYZorwktlXdlU7fZT332Z9qBJ6MXc8rTQi71F7uP2yCO1V6LZ8st1Rz/U9UX6uVYvZu5Pq9qMe5dWFeym/PFCJ8Qeb4YweSekYY+jQpw0viDDgbh9HwxIift5WwqnvVdxfv7fteKe4bu78++Ht/fnx3O7u+vBoOmxksNmaoSLmD9ewi/v3cl62j1zpVP/N7PDk8cxSuIz2ywz7TGpdoOhqvAKJ+70EIQ652qdtPfU87wOF3IqSjNxje+/IamJS17sCFv4jbABchZr6zFPIi7JyvgqewM6hgoOXZ+bspdlsnmBNPfe09pCq4MSkI5iPWiNufOZhcDHpwf80fuBBYNBhrDIUeH0hyfaes8ja5EvkyiLOUZLcLOUQj2zti0q5Tzi9JIpHkv5T2hzjL+pLkKJAI3krnglT0p1V3YE/DuMRyo6fROQkSi1od0dRjkezXeEBnV6IzeyecUjBclZgTOvAMIrzFOPoqND5EJLdJNCxNoAmDkUS44RavqESmjXDUTghdof394VdL0GqiXPSJ5pCJYo6ulpK8UajFzKPtXseH3bTrCllUpv5h1HFXNAVZxf2+HtWW2YLwFTSv6SmTXIapr/F3Hxdet3rUVp49WiDlbmTEeUvyYfoWsh8HbljPyZ7m8tDfomJN2DYgcz5gySqHE+2FFWQmWndJtjsoHLDtlE6tZRteMt3Z7V8bqot8g5EcgKkFXAguAd7GuAkLlu7CMwPFplkqanykWc5re0Bz5UmZThXjrl3WNHDaF565kzWI4qK7ZfK6eclaBFyI8Gj/dAAcUSC8Y+U4RNva8ZZd7mW9z5r7wbObG6t35EjZh7ZK4W8XfY0vn5dl0qLcf9g1S0li5xNuiWiNYRhD6wLPl66qFVVcat+u4Db+jFLPfh2r/7Fxt+RK2mZVs+TOOqcymEBTqB06sjMUzlrXhdX5cnuV5ZRLdpiUPA2t07ZmZjh0D4UI69wV1llsZXwCgk6MrUcpjwaVyoy1xTmDFF1F6pc7MhiLRjzRPXGEMhXl+cgMh6KySlNMyDNTLAOd4pc70gekMtd+I57/eahy/5si5l2QuyunSE30fyqLeWf0ILrCrGZVTkcfBu7enZwE2EisGUi2V3TOKIjYYrM5/oaOY1TUGXr8mIRukIgzutGkRF5F+wCV48dBMxmY5aIf1MokYH4vm3KAHAPQUVL3dw97OKrPEd4lwP4vEtZ0cjeil9aSXYYbP9B6+fxsuUbvalFzzcGnt3I2ram+aOKin2F8v8Vv4wC9BdVwZL84MrTok0gzANNfT/poxDKHHOGyFMqXkwOiTTKnQDheXCFdOXmQFTUs7pynCIolKOhM3dAtNgLzglDx7ilNl3sa3VP25UX/oE/yekwP6DFNJHtNn+I8mOgmkAtWqR5N7YGNqAi+MZV2oXn6WUAWFqbez4vWllwAD57INjrTd3NBd2uzCTSkE9Jr37/lus0vXEv/zpX0HKtdNgIZep4+IxN0+HhELQY2L9WMWvYMFRc/EPjUOhGoDqd8rjy3C6ecDLIXozVK+1PCqVgKreIHBPwh0UHwQeBahIKibIx7TM0AGjsyixu/86C44VdCL5y8oTdYfbg2JTVj+G96eX3ty0N01Z1PBMlqhto3NlUdjxnMQ+LdKZ4DsATynd0myr+IyNeTQOEQ3wh+wcMgUebsLU2Tt1W3J13o1GPDQ2FtBxQ2wTo7SqVUj3O8Mw9bwTPPIWPa6LywZ/+tEsKHtsShPUtAvjczTeC83OOA9sHJbkwvtGoKriEM+85hFtXnraNVUsIhUX+/f31d/jfA3AdJT3btUCwWQdAW+dbdh2Zj1k+YZMuik5A+VcwKnEgeqlZfP9UYnVVNURCyH3AzqFCf9CwAq8V+wTOrQAgujah2aI6kxYf0R5tpme0txAA+6+8ySwi3dLVQFa/D55zYvCgTTvG7vEclwLsMCAwRumeIbigNv0ULoAYgS2eVqnXwg51iMxNiEi1ega4SQ++icQcqNcpeZ7CA7odDWV+3Jrn78i9NuJ0wnBVEtYtWPtnH9040bZEm36IUodhXFY/j3ZR5DX5rB6s4w4/OFjN/xUHiWYoW+l/+vGJ4xtrVZninczPQ6L7eyvU69jYzP1tnA+tZf/Xcyvw2tb2N/ClEeh/hvYoeK/zA0rGCxb2IyuNIHon94nXc5ASzQCrdqfHKlZrLtMY9LvdlxIS6tTY09avt0hpsOFo7evVSBdBA1193uDL0YrV65YXdxxLfvLvTOYtNOQrr9g9iycegz2Ap8WhP1dfFeCC7ZZjuBLu38rcwZtDnPa+t78X5tuttoxVN2R5Q0zg5q6exR0NR3tYUoQGj1kodum8LwMUe4gkBQKcNKK2aY+3GVfaZNb59Nn1w4c1UPvnSyka0b5fI1o1wKBrkMopeXZGrY/g2ZmkD/vY9l8pHvuZOKC3J4oR0rq5+ZnIaByncTmCRZ+q0y1HyBVMYA4y+LtJMTpA0AhN4o5nCjMqc9f/vmZBSgVQZGPYOFNy3H/xuNsLpuTIb9zBgNp4b6Cs9oONVGusFgumYWPKT/rFVQT2dPza3RHMDuaOyC065dcKoMl+DWbtndf1fPan50UPQN0dOj50gllghTZDBzQVJnM7vR8kOD7cpN6aOb8/2R1TrwMrxAOEPOuqoHYn73Mwjw0JkgBoNlmHYc9XvFNiNn0TFytohfe72V1ObtiwP8ipPzA/oEP6FP8AF9ip/QpyO8MIZ/lseXO6uS1sBw4PRVS2e7/j/effN3ZeRXDieXeJzOWLEE1wT1gG2QBHXxD7P07iXIdG1MimnULoD3bxeyqXAAG2uQBZLN4+BXiCw+1mcBJmPXLZPTngHHtyIEOKcyZUUcfMfki8WV+6xaXDl3Cz0Aa1LIe4L3VGKennaqzdJ5esUKJhmtYnWmBi6JjE8gKoXN0glVoKtkKwjv8I5C55mMvKhdmKeW6YGjGouNDvrG2zun84rIGv4MtecjHN+nEk7pJNkfakJ4T7Mpza6HOvBFr1Gz6TSBB7atqGAVmMVchsPGwyPRnsgVdLKAwCcdOFIY73HdO65kajNehsYjWkc0eJXAzSSdhwv5YBMHNaqzRVlqV3vfdVzXq03LK+NmDnlQdC9u+HDIPKGea/w6KOejOmfVXFS03VKt/6xMXQ+LSdQ04RXbHFkNflxmr1a9tmn/FT/3QR4N16MRzKtH5GBTr2EzdYamyiTZ4Uiv+a1gWj94VRaiGtJi1JY8TOHDFOIZinTShg51WCnSnpEtZNC0LvjRTcoKsOCHNq/afGuO0uecfEGf4LH0zCjhPp7bbLsv0mqKwqBSAUABwpwIrZgpnVnn+YlY9ROjoMWjlYwWc5X/TCWEYVx+aZXrK1UXCyXG3o7HFZXmhzF8+crDWv7FpuHgPEDDVoZbgSBpE25qYNgIuV+jwG9ZuMMa0Zzp+M2vXAAkJHns5pGsIFFDiZjavVXIKxfjnknveU2XFRgqNlaCPScze06EXLfrQXAVqmNwZw/L82rkj27YGl3djM5vzI6xjtcaFpDsaMF15uQc7LbOwgYJxLCMcjaB45lgCgaKGk/cZvrSSKqP+8q3Xckh88PIIPXLS0psMxVdVjurMRgU68v4cuae60vMtoRPcbMgZukdkfUsvRuatKnWaW04hYwnCw5cesaqyj5rw6VN/QZNmA99k6bvX6B6sQ2A143Bp88xbV+Oidg2jROSXYK2WNsowSe1Bl29cgx4NWU2XMi2iaFzagodIHVt2zC+oGvmKIj65V/vI5Xv+a8ANWyXgiHXotpoXaKNOEXRKOLqrHyobYFOnRpu6lpoTRLySoE4tnLA1jKF9QRWBfuTduSTD5rNmagNvdZQR+XLGcRUp5L6brGJ/wLC81pqwj6qcfVpZWBokXE8TctKMVn9mCTPnoLG5PNpIt1jknzgWpGwWR+DYGhf5uArYBtypUPlESf1FDc8nFWwtYG83RqucQHVfC5vQtakz9r8hJOPSFMXdnNvx44aTA2r0JPWaNsdtkSQG8n9fVuRyUl/v40UT3b648d+25D51jx2M3j6UrEl7FspPVv5NYNgA3JcwSy9phajhp6Ot4lEnbWm47rgzv6p8XLBM8cUv1V5itWhNCHkcdJ4gNM7z2E/6R/EIY0Kxuk3sGy+oWNRwhd9FQDUhG3YsJu/NSE4ui2E+/sodj0dJDQC6u2rJLTu+fFGOx0r8pJyBEA0P02iTE4OZzKEdEwo7h/E/QN8RJ2/xbfa8vcthBZ4GZB6KhFfN65qJk01DDEsJiIoQCprX42XkgTnC15Snuu87j1jgRgFeCp9t2roVFFFg1bPTx1w0YgWtPrXkOotoAa1g0GoEUpUhkn3/BgNBluR23j5cp1t2r2ZavS6XFwGgqVENb6Vn8T1Uq5heuphGjeY1rT9JyeP8XecHOA/OHmCj9VsUqUrSnIorXvrHzzRkRDfcb3zlNqgZ8MipDOWxhLhKwWnNbuccGV2CVFE1RMk/vPclr5tpfdLtDBoxylpq7STw/hGtj+x75tvmnft0Ax89MlPO3OW2JEh/KID6YzN6JmKtmhlGgFS+bi3x0wMlauGEqDteIM2TCMVs550DFUhssYWU0EtDvz7FjDaOIMP+sbLrt8A4Vnu9gKEL2QrXHXUPPb/187gHxdNlqGPe59VbWcP/+Q8sDaGu9mtjlujm+C/kOvYu+zBswoutIX1ZRwEhs4vd1ZrqfWDFJ6C2PZdq1BZp60ZCGr8XAt6negkr7SxalXj73k7JrS9aJF3rQFfI1zYKKily41+03JAtfWb3P3u+xaeBDmiTQte6tsWczU9Ca8P77Ubb7P28evWOuiskqQVvwSniVeU7P3Xf/yfj3tJWsbzGNJQpbtjyGxV/9d//OfeBH/DVQX1NvRfo//6j/8Mzz9WH09H/54g1Yaq9PFAf/grb28nj///3k62mvc3iQJ9xkawtBtBcV7+xY2giVpc2wAif8tnL1wxxIvtOow9NoSVfZwmigPZA0XHaeu1TaMz2R48QzW+k59mbhuZw3kqZZpN4SSj12IRo8sYVIlKZzGnuadJvPZuojGr7Vc/MTbXodNqMyQwRfjy4+Lx30+eKQKGTHLq598hotkk2AuvKIb1pevtdSpe1jhtknsntPNVTPEPrZCxrULRLv4URIOeCr1ZpV22QjezFQ5shVq2YodrFNYkpUoHiV9Drulb6SrCQZypq17dqQMt0ExypTes8d/LczUV6TzMKfKC7UeX8UbZkFyudlY+1VNL9VYjWad5icBwAULyXI5Qfen3U1/Gm+kaQkROugf/HoMXhsFr6875CGLdoigSVhkYwR0K9oToyGRolE1SMtAjqyayha27ODwPgxm7M/4LuzrOqWcDSHppSdXZI2TqPHq5a8p7EE6QSnZVUI9V5DqoR+fVUqZClJLcQqoQl5HDH3iYgdruZMCQFhU13pLf89B9gGwkkZIyLYD1JhhOQvWxsIa60rZ/SCwJqo9dX24Mskx5VaQy1WCnJKtLc7uJUil1RBVuxbrmhl04BTM1GayKBu05OewfyTBHCmLvhgjjW+9NZwYoKvQRnAwz744W2EFwKFmZkLOUhplbUp481c6XL6CuCikya8X/btn+Akjid922mhRb8zUkfLoDMNr1fVRf+gyrmX2NWGBKcLb7EzQOB7smMI7kzeQqw4tR3v/kyMxzYXF3AzuM1iR4Ee0O5+AF+1qGQrnDZh5p+7HMmaKwpTmlWtqJ+0T87rIbztlZoMtIuZwkiUp0BVtxVAPB9tpQ63D8dYBrFZ0odaSbW4YHSF2ZdArnvK/NUoMzWLcScpLTsDzfHyGcEpUgCvKMKmNgjoZpklo9K25egnDI8bkYodrkHQEnYscoeY0vFHM8Uczy1LeemxxBLrJWt+h+d0GFYxrMyYk5xrL+SQKXI+Xibr5HpYvBg82shdNa25xbvhetBrlHs7SMJUQtO7bYQYC6yiKJqikbw8HO23X2iQUYV0qyj5ny/F4JIjoyDguXIGYF3CIWEA9CwHWzZR8HqSGz6VFRhN/Adlk8IvZKphJX5nAXl8Q8PqqaE13jCiCN8AbYq/ODkeYSnjFXPCLV+eORt2BDlzpmBYlkb6i6GcjekuFBgLCqW+P3srVfDj8Vti6baHU/3LwTky7XQtGlXg6n2ZTOUj9cwAtEb9WpYdHgM/kX846cOfVkTZZ3gmLAjqVuCdP3Dp4plQFWAYpp3D+T2j5xJlXNz7vgTF86xrFQl45xrHLBeZgIWgp0d68PtyN6Wxj4GZ9RSDF8zkcI7i97J9sZce1tYIDf0bBx/nudzkM9OEEOz0XHhwmG2BzZjotUvtY1jbLAFcUZJz1bsUzOIbZAeCEp5V/LU7C5uiIOsY04vGKFCr8eLjfmNqhruJkEstX/wh9MQbPtnsk1qpLONiVtZvGtiUYbD4Cui3WN37SXmnaet9HX1bKSdLbBt+un0x6kuu8VKZ8sQIiaFOm5ULqJEbI9/b3Tv1xaYxc+tOZQmLgycEIXTc2NW2npttLDFtyN1G3lG/GlseKSKqBYU8/G2HLnFAFsoBNbrsLGzD6sdI6dXdc87eH5C9/okacs8B3QTcC/UnzbYfVrk9CZVqPssqoHJ1jgRsxkZTyd8yaXbks51EiAH+91SgA7onbfpmJd161GtJrgYbKutfH+pSTN3Q13zh1n1/gnxQH+rdmReXeYXMAaMMEx+tSN+0Evzx3J23gfLU96cMfkLuBnMZlCqAy3/pwqHZky5Wjk1TV+Dx3DjCPvbg1leZLWNkST6JyPPK90sTF20sQzC7cSRV3j7+39gYAPm/OebMrUoxLUWwCYtntYck+iczZqhVtTKOAqczwalvf3IT0X5/ujEQH/mmLjkRpk4VdeU8qn0zhQ6TOhCZXapdOetQn+gTcemYTr0kJMiBiadIhwjQopa/fpsP3NsBCToa41zKYpn9CTGZOS6ujdeaTCjkzREHKc5seq1ivDQlQe0eNpKl9ySCGsvJz0cVOrtUi5rw0hO7bOPKqaFzRcgVOHvkRXfaTJT9cJEfacMrxKrZb1FRw1GkIoFs3fiGO/DZitkqaFhhO8P9wxuIpBP9bp3aCMUXv+eLYo+Qvt8amPDsYlraYWKHetnteoPZjVh2ley+0Xzfg7LkGbRtT1Dmq+dW82fe1eGq+aDkr9hasdbOZRMYsqWtBMwkSaiqsbynNRxi9lbde2bB82F2Ji499yVukrBmLbXa8Q4nox95xvpT5+SJLgxLjyXiJ8PqpraKIza3bMG6fUHqNumW9zpKppOpzDPUQqhE5SuKE6sV6CFaXg0dzrOOIZicj0GHs7q24DdU/fyhW5TwBpvXLBzVcQBAiVvUThcMuuvYdEMcaiUBUNKE1F4TeA4ZlDy7327WM90Bw1fBqWf6t6kpYzcMWMLuPgc0YY9Y7B16onAfhODTUgVllQaY7N/So5VjdOgHe2CgCLApWY1iyExnkE/Gisu4v03V2kc3e5xIJsWkegLppr7Rx/NnzXEB2Q1XuvzwiwFDJyGLL7+01Nmr0eZDKGnP2teyu3V+3cVtmpCGuXw7U7pVll63C5OxRZ7ntMlxROeKFM755cwA9sWdTWmXzessQsj7l1bpVd59YG083NhgbUeSluWP4gB9fuM4V3RWJb/mhnlr7YGDi9QTJt4H/WQRKfj7R9ZtOFCY4E2mmrlSZXNa7Ad+AKXHmuwDrmwiIH3jjE2PaDrtfvweMv6ZNPuPp2HLbVUmp8eo/evYSrpsDGNx6zTPvxlmIhlUu3r9BfLXu+szLoYruCF/riogddfA/WXHxNVBSrjpW3ZaEm8L2OfehMiod+59+qboQyvrCl8YBltT/rLaGlnOxtpnXrKKokgVbtPEnAhRMGhqvesArMtb1QMziyzl2TJOCC06BGuFfR8gb04Z2VteHUPS/HasUKyqVZ8htlSLM6t5H8exM3EZoQGsyQyRHwANVXbarX3GQetRpXIi56I94BW1ZXyFfO3X8tkibqvV/n8ekkVQzWGHCqjevDxHNICha6ruZh/OdwhpdajYSWJtvrnZI8Mom7TVTMBFztqkeTSDva7YapLkhNAcIuEbepu6tr1Nog1yGOn2l4itrOVJ6mpW1Nv9HwFGcIDbfVMta8L4doWw1jk6vxlBSJVuBjbzp9eaXmE3wCpg9Po/xWpa0Pzqa0p0xxQJeb5Kqe3F4h+ISWvdTqrnYeb0gBVsi2RLhrS4S7RiJo4JWpDpKA3qh0cW1OaHJ5sTyeQBYvuIH5ZtNlGy+NUWETB+tpKaPvvmrmLKdXi0loshW75NrAZdUvAixXXebgLAUE9nBmqZoIqwu8UPAjQ32/cTCNmT40/iefDIxxZgr+b3BxXmOpULywJ8rmvGXLqQxMwAWZ1M64PSGnStG4IBOXphEvyCQy1t9a5+4TTX41PLMZzorkJp6CTHFG4wvYN467ZwJV/F6GY50C5b2RcMVbZaqqcCudWSvpifci/sRn25rWmdDg77tO2/BmU6utL7Y066dRgx9nJomX30FTZ0Mv2xp4oL8Nqdig/NgVbwNi7cMt8Hx2B1uAXE/85oremZIWbN36G8D6nCa3QLMhwVxTthGetS82APR5rRrzK1D+ay2rOtwUJO6ZeRu9N9eduPMzFfocB+4aFMjlY5Ns6VNYt+4cN9mUZ+eUsEjwjcqQcq+d2CQ5aMi2aU2DgauF86h19UZzI08vg6jdGT4mh3Cambra+lIMXNrHY+seqUOrE21ZaaEGHN0g2314bLwL4k2VjCJoKpqzxWOt6x5rezaCuAOTdqeJzjv1TAbL0J7i1PqeVR1GPMGnSA2kPVqocmy0oWlUUZ4bJMEHsKG6VpNQ0XClna/jI3J45Jv/towUa+9qVd060BhvYyh7CEdHyFwfAhVXmzB+BEekNlxUmzmUve4I7HXHJr8kcpN2rXWPowZh1851fKlSsp0pDeoqPFabQ31t6yJZOz81ZotG5Qm09Nxo8ASZlUoxY5k71J4yOGJcBvYanrOwda3myUaCf/EJgj/5LIJ3tXBXpddDgH2M1sYvnDZuwA4r1DOjUuYLK7btfqc0usDdMG/fjGLo6z0ln9Dl1FTeGTKs9LLTqb1ObIopCzV+790E1vSnruHBLzzrmPWdXxupA7tnc5YRuC920yUKbrvSY/mGSu0UbEkS7KpsT1tnwbsll8vwDm6kXm0khHedrHx3dtU2KafdcZT3TulwzWmMexPP8DtK3snwnVZ3sKf2GO+Jv8zVfW3oHW3F620c0reSvAEA3ADwmJKJOZ1c2G3sRBHMKXkL/GfhdqKnWg8+JoeBXmoB471jlJwqSwEUK84LhZ/gvsq1PQaeCs2geFMLulYcBMjzIX0hybfav8iyUs06F8m1P6zz0xFe+Jr9cfc+gN4xDc+PR+h8XxlGJpuOx1Tb1+Tc1FBAq7IjMqa2YGgI4Mib8qPBwDC7hxksiq+d+wawRXPeofjnJHLna00S7t8lOdISyBGe+e05tJkSOPh7AApfyh1ZKXekpdzvEjkfhA10aPhwdGRRFV47Mkyu4Wxyoo+i6xZmTQp0PTB9pGZRrNHpiluhDw9B8KGiZXi+ZXi6LTXAVuOet5AY9669edvYkp2uazSKr9HocxCjwGpIxKED4ZdEncm3ND9wOKqH34cvcUcjfBd525DOngRvrg8bjO4+Y3PVZpeQJPrXmo6+dSvxF3X6zQB09e/P08g3t7WmOn+uNm00gKvwhcRmN/mOYsuG44Yjg9bte4m+RP4+1AcnfgmOYy2L2JmzA2kTmHXyfMD8Vf7Pmr+U09pG27C5O9WGDHirhXcd6C5oCH4vbuFeQW7F2k9fs9k0xP5nzEIVmZio12LdPKdctrS/1pqo0JFkNnMy0zdSaeJWrkjO9L9N4zDm05Y5EPrDcNGBifjLujfKty+cf7UWEAjRWxfmAlgTF/hzNw1FuI9fyaiap7dcXZGOV2BFB+MupLGoZM5EHLAJFyUYg4c8Ejw0OYCwy3MdQVDcGEx9Oy4bElnVqOWp09xvmyTuCnpTgiFtI+U3zRvKbzBk4rJ3zCZJ1vzAJXi9yVSqUnjADEpgFEnyM8cVmVM7kXpOljSsIOViToroivnXx0xoqIow3GGnK8+gsoRjpZRMaQiJYa8Yt+mHpVUJ+qlTFMMUnwcXF2bxKEB2zXF1MLK3yZt5PKFEbUeiq6W4/iDhfEFbEZ/TcbooZIBPnc/HtjrRLOXpBFIcP9ceSGtXXAdwu/zRBJLVNBnS8Z9NbVt2f091YnhbHX/TzqDebLTVedtr3TO4uNth4Q+dJFjtz6T/GUetO8H6B/XaQbjq5rtCXKUF7PL67VvETKVvdApNOHrB161bq5u4CXA+rOB2WJ0GHZawBQNOIP+UYYmS0lMCS48umHcPp+2SY7PuMfNqimiigP1JBzUQd3jxXHpxGxW8gfjVD5rHV5g5TaFpzV5R6/fVP0Bxqw/viisR3YryupqnGX3g1beiyGnZruCBouC03dX4Ld2UQl+20ScAfRwl3EOfIE3vtMF9B3R3oOyvwmZSm1EPH6QMW2/Dl/tdEtMLb0HJygAVu4MYSl43eGqErLkHO0RuGCduKlfeeCCIyPuJ27MBb9sleNOctKp55ZBH24431voCeD/qEX8CbBNBdUIxxa+j1tuzFI58I90uuNDppq2HXe9HCDda7VizgCSrZuYV4qgZ8qmEO4JBMJ5ShJtFHjf3a9t58z+wwV0UpyptMvB+63oRzdPsOp1QpTiYs2LPlcy7z2vraUXjxmHa6k1TJfZNc03OXnsWzXFzSXQc7uPvtoT7Wcjtbdh/SO8OdBql1dFVJYqFpO9SlZONVbK5PDL6vQoQQt3kJNrB6+dQrzhEDj80dztUNCupUT1+RwgZD/ZSFUCWZD9dVWWjwu1XnpdYCFMRpqCYEkJ+hwvr9eMPaDCArJbqUAqGBk6VRhf6g4Yr7b2j5zNMcYbIoaM+7X5TTcWt57FgNji6LiEZFnPK4WrukjsaTj0ahmNnv0r4OvpQMnvHBSQMABMiLojrUM+Mdg6A0XFa2KkP8KoQE52YfSNyCmQUNcB5QUOmdZjKunrhAgNwrcH9nJac8YkbGLi4sdC4u6ihtBTx5JqGqb7mW0XrxKFtHb+loQ7gqdU1quvg5VvKX4MLSkknkHW8XNtTvtNbCEhGbrCQo4ca8ujCc2gBRIAJt+Vit70dgyAL1IeSvUh5XtAyXE3Vw4eSedMNCe+ieaoCXoK95ip136MzU7Py4f2rU5qW2fQd+H9XYRr9saDlEumUjxwy7weQAChwefVt9vkfIIRp5do2RDvFN/gCL/AYedzILhEVSBL+jp9Tr54VKU014470A1i2/bViKl7TcKEnu8bKnTB2i3mtR9PU73+5E0s8dW3M3rB81++sf5B23dbPOpT1UuCftPR45tWCFbAVVA33jKf6dhc4tz80JsQ1EsKf4hRLrYxaikgskOaw2dufBs7xJ/PFWU+5dsJ7q1q2ulTCoYuBTCyKXO1/b2jJxktlLxec7sKFIXbUnW6ArsV4/OA2WUW41E6SUhGiVQ2J3GYCkshE9E5fcrxKM8luUklxTu1jjYZ/+79QSwcIdRWLOUc3AAA+pAAAUEsBAj8DFAAACAgAfC4KXezY2SsHAwAAtAkAABYAAAAAAAAAAAAAALSBAAAAAGV4dGVuc2lvbi52c2l4bWFuaWZlc3RQSwECPwMUAAAICAB8Lgpd36MN37wAAABlAQAAEwAAAAAAAAAAAAAAtIE7AwAAW0NvbnRlbnRfVHlwZXNdLnhtbFBLAQI/AxQACAgIAFstCl3sOC/HmgIAAKQFAAAWAAAAAAAAAAAAAACkgSgEAABleHRlbnNpb24vcGFja2FnZS5qc29uUEsBAj8DFAAICAgAWy0KXbKGeo15AgAAJwQAABUAAAAAAAAAAAAAAKSBBgcAAGV4dGVuc2lvbi9MSUNFTlNFLnR4dFBLAQI/AxQACAgIAHwuCl11FYs5RzcAAD6kAAAbAAAAAAAAAAAAAACkgcIJAABleHRlbnNpb24vZGlzdC9leHRlbnNpb24uanNQSwUGAAAAAAUABQBVAQAAUkEAAAAA";var Pe="anyray.anyray-vscode",jT="vscode-handoffs",Wb="vscode-receipts",Ls=2,VT=GT(FT),fr={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"]}},YT={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"}},ZT=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),Kb=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&ZT(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ds=e=>{if(Kb(e))try{return new URL(e.trim()).origin}catch{return}},XT=(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)},JT=e=>{try{return BT(e)}catch{return[]}},zT=(e,t,n)=>{let{macAppName:r,commands:o}=fr[e],a=o[0],s=[];for(let i of["/Applications",Nb.join(t,"Applications")])for(let c of n(i))XT(c,r)&&s.push(Nb.join(i,c,"Contents/Resources/app/bin",a));return s},qT=(e,t=Yp(),n=Vo(),r=process.env,o=JT)=>{if(t==="darwin")return[...new Set([...fr[e].commands,...zT(e,n,o)])];if(t!=="win32"){let l=fr[e].commands[0];return[...new Set([l,`/usr/bin/${l}`,`/usr/local/bin/${l}`])]}let a=YT[e],s=KT.join,i=r.LOCALAPPDATA??s(n,"AppData","Local"),c=[s(i,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(l=>!!l);return[...new Set([...c.map(l=>s(l,a.directory,a.executable)),fr[e].commands[0]])]},Gb={run:async(e,t)=>({stdout:(await VT(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>UT(24).toString("base64url"),home:"",commandCandidates:e=>qT(e)},jo=(e,t)=>Ps(e,".anyray",Wb,`${t}.json`),Zp=(e,t)=>Ps(e,".anyray",Wb,`${t}.applied.json`),jb=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&_c(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},Vb=async(e,t)=>{let n=await jb(e,t);if(n)try{let r=await t.run(n.command,["--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()===Pe.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===_n}catch{return}},Yb=250,QT=9e4,eP=QT/Yb,tP=async(e,t,n,r)=>{for(let o=0;o<eP;o++){try{let a=JSON.parse(await Zr(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Ls&&a.action===n?"confirmed":a.extensionVersion!==_n||a.extensionDistSha256!==Yr?"reload-required":a.version===Ls&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(Yb)}return"timeout"},nP=async e=>{try{let t=await WT(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},$b=e=>Mb("sha256").update(e).digest("hex"),rP=async(e=Vo())=>{let t=Buffer.from(Db,"base64");if(t.length<4||t[0]!==80||t[1]!==75||$b(t)!==sl)throw new Error("bundled VS Code extension failed integrity validation");let n=Ps(e,".anyray","vscode-extension"),r=Ps(n,`anyray-vscode-${_n}-${sl.slice(0,12)}.vsix`);try{if($b(await Zr(r))===sl)return r}catch{}await jp(n,{recursive:!0,mode:448});let o=`${r}.${Fb()}.tmp`;try{await Vp(o,t,{mode:384}),await he(o,r),Yp()!=="win32"&&await HT(r,384)}finally{await Bb(o,{force:!0})}return r},Gp=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=>Gp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Gp(t[n])}`).join(",")}}`},Zb=(e,t,n)=>Mb("sha256").update(Gp({gatewayUrl:Ds(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:_n,extensionDistSha256:Yr,profiles:[...n].sort()})).digest("hex"),oP=async(e,t,n,r,o,a)=>{let s=JSON.parse(await Zr(Zp(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==Zb(t,n,r))return!1;let i=JSON.parse(await Zr(jo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===_n&&i.extensionDistSha256===Yr&&i.gatewayUrl===Ds(t.origin)?await Vb(e,a)===!0:!1},aP=async(e,t,n,r)=>{let o=Zp(e,t),a=`${o}.${Fb()}.tmp`;try{await jp(Hb(o),{recursive:!0,mode:448}),await Vp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
109
+ `,{mode:384}),await he(a,o)}catch{}finally{await Bb(a,{force:!0})}},sP=async(e,t)=>{await Ub(Zp(e,t)).catch(()=>{})},Xb=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...Gb,...r,home:r.home??Vo()},s=fr[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!Kb(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((g,y,b)=>typeof g.id=="string"&&g.id.length>0&&g.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(g.id)&&typeof g.name=="string"&&g.name.length>0&&g.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(g.name)&&b.findIndex(v=>v.id===g.id)===y);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await jb(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!ip(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,d=a.listProfiles??(g=>fw(g,Yp(),a.home)),u=n==="configure"?await d(e).catch(()=>[]):[];if(n==="configure"&&await oP(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:jo(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let f=a.extensionPath;if(n==="configure"){try{f??=await rP(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await nP(f))return{ok:!1,reason:"extension-missing"}}let p=a.nonce(),h=Ps(a.home,".anyray",jT,`${p}.json`),m=jo(a.home,s.slug);await jp(Hb(h),{recursive:!0,mode:448}),await Vp(h,`${JSON.stringify({version:Ls,action:n,nonce:p,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:_n,expectedExtensionDistSha256:Yr})}
110
+ `,{mode:384});let w={installed:[],failed:[]};try{if(n==="configure"){await a.run(l,["--install-extension",f,"--force"]);for(let y of u)try{await a.run(l,["--profile",y,"--install-extension",f,"--force"]),w.installed.push(y)}catch{w.failed.push(y)}}await a.run(l,["--open-url",`${s.scheme}://${Pe}/configure?nonce=${encodeURIComponent(p)}`]);let g=await tP(m,p,n,a);return g!=="confirmed"?{ok:!1,reason:g==="reload-required"?"reload-required":"activation-timeout"}:(n==="configure"?w.failed.length===0&&await aP(a.home,s.slug,Zb(t,o,u),p):await sP(a.home,s.slug),{ok:!0,receipt:m,profiles:w})}catch{return{ok:!1,reason:"failed"}}finally{await Ub(h).catch(()=>{})}},Jb=async(e,t=Vo())=>{try{let n=JSON.parse(await Zr(jo(t,fr[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==_n||n.extensionDistSha256!==Yr)}catch{return!1}},zb=async(e,t=Vo())=>{try{let n=JSON.parse(await Zr(jo(t,fr[e].slug),"utf8"));return n.version!==Ls||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},qb=async(e,t,n=Vo(),r={})=>{try{let o=Ds(t);if(!o)return!1;let a=JSON.parse(await Zr(jo(n,fr[e].slug),"utf8"));if(!(a.version===Ls&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===_n&&a.extensionDistSha256===Yr))return!1;let i={...Gb,...r,home:n};return await Vb(e,i)===!0}catch{return!1}};var hr="Anyray",mn="anyray",ok="--anyray-owner=vscode-profile-v1",Ns=e=>rk(tt(e),"User","chatLanguageModels.json"),fP=e=>rk(tt(e),"User","settings.json"),$s="github.copilot.advanced",cl="debug.overrideCapiUrl",vt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hP=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[$s];if(!vt(t)||!hP(t[cl]))return{next:e,removed:!1};let n={...t};delete n[cl];let r={...e};return Object.keys(n).length>0?r[$s]=n:delete r[$s],{next:r,removed:!0}},Ms="anyray-default",Fs=()=>{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:[Ms]},sk=e=>e===Ms?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),il=async e=>{if(!await R(e))return{kind:"missing"};try{let t=await nk(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"}}},ik=async(e,t)=>{await cP(pP(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${uP()}`;try{await dP(n,`${JSON.stringify(t,null,2)}
111
+ `,{flag:"wx",mode:384}),await he(n,e),await iP(e,384)}finally{await lP(n,{force:!0}).catch(()=>{})}},Xp=e=>{if(!vt(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!==hr||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(!vt(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&&(!vt(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}})},Jp=e=>{let t=e.filter(n=>!Xp(n));return{next:t,removed:t.length!==e.length}},mP=async(e,t)=>{let n=Ns(e),r=await il(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 "${hr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=Jp(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${hr}" Custom Endpoint from ${n}.`]};try{return await ik(n,o),await re(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${hr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${hr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},yP=async e=>{try{let t=pr(await nk(e,"utf-8"));if(vt(t))return ak(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${$s}.${cl} 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 ${$s}.${cl} value manually if present.`]}},ck=async(e,t)=>{let n=fP(e),r;try{r=await M(n)}catch{return yP(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 Z(n,o,{backup:!1}),await re(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.`]}}},gP=async(e,t)=>{let n=await mP(e,t),r=await ck(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},lk=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,ok]}},dk=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},uk=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),wP=e=>Array.isArray(e.args)&&e.args.at(-1)===ok,pk=(e,t)=>{if(!t.hookBinaryIsDurable()||!vt(e)||!dk(e,["type","command","args"]))return!1;let n=lk(t);return e.type==="stdio"&&e.command===n.command&&uk(e.args,n.args)},bP=(e,t)=>{if(!vt(e)||!dk(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&&uk(e.args,n.args))return!0;if(Ke(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===er&&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!Ke(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},zp=(e,t)=>pk(e,t)?"exact":vt(e)&&wP(e)||bP(e,t)?"stale-owned":"foreign",Qb=e=>`MCP name conflict in ${e}: servers.${mn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,kP=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 M(p);if(i){if("servers"in h&&!vt(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=vt(h.servers)?{...h.servers}:{},b=lk(o),v=y[mn],S=v===void 0?void 0:zp(v,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(Qb(p));continue}if(t){d+=1;continue}y[mn]=b,f.push({path:p,next:{...h,servers:y},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!vt(h.servers)||!(mn in h.servers))continue;if(zp(h.servers[mn],o)==="foreign"){u=!0,l.push(Qb(p));continue}if(t)continue;let w={...h.servers};delete w[mn];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 Z(p.path,p.next,p.backup?{}:{backup:!1}),p.clearBackupAfter&&await re(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 (${lw}+).`),{changedFiles:c,messages:l,manual:u}},AP=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 M(c);if(!vt(l.servers)||!(mn in l.servers)||zp(l.servers[mn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[mn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await Z(c,u,{backup:!1}),await re(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}},fk=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.`]:[]],hk=()=>`${Pe} 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.)`,ek=e=>[`${Pe} 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."],mk=(e,t,n,r)=>({runMcp:o=>kP(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):gP(e,o)}),CP=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=mk(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 ${Pe} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...ek(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${Pe}; 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:[d.reason==="reload-required"?`A newer ${Pe} build was installed, but ${e} is still running the previous build. Reload VS Code completely, then re-run anyray-connect.`:d.reason==="cli-not-found"?`The ${e} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`:d.reason==="unsupported-version"?`The Anyray language-model provider requires VS Code ${Oc} or newer. Upgrade ${e}, then re-run anyray-connect; no extension configuration was written.`:d.reason==="unsafe-gateway"?"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.":d.reason==="extension-missing"?`This anyray-connect installation is missing its bundled ${Pe} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`:`VS Code did not confirm the one-time ${Pe} configuration. Open VS Code and re-run anyray-connect.`]};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?[hk()]:[],...ek(t),...d.alreadyCurrent?[]:fk(d.profiles),...f.messages,...u.messages]}},tk=e=>[`${Pe} 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: ${Fs().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."],vP=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=mk(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 ${Pe} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...tk(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${Pe}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Fs().map(p=>({id:p,name:sk(p)}))});if(!d.ok)return{status:"manual",messages:[d.reason==="reload-required"?`A newer ${Pe} build was installed, but ${e} is still running the previous build. Reload VS Code completely, then re-run anyray-connect.`:d.reason==="cli-not-found"?`The ${e} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`:d.reason==="unsupported-version"?`The Anyray language-model provider requires VS Code ${Oc} or newer. Upgrade ${e}, then re-run anyray-connect; no extension configuration was written.`:d.reason==="unsafe-gateway"?"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.":d.reason==="extension-missing"?`This anyray-connect installation is missing its bundled ${Pe} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`:`VS Code did not confirm the one-time ${Pe} gateway API configuration. Open VS Code and re-run anyray-connect.`]};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?[hk()]:[],...tk(t),...d.alreadyCurrent?[]:fk(d.profiles),...f.messages,...u.messages]}},SP=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 M(s),c=vt(i.servers)?i.servers[mn]:void 0;if(!pk(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 EP=async(e={installedVariant:Tc,remoteServerVariant:dp,isRemoteDevContext:os})=>{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}},xP={installedVariant:Tc,remoteServerVariant:dp,detectVscodeLmProviderEligibility:yw,configureVscodeExtension:Xb,vscodeExtensionPointsAt:qb,vscodeExtensionAwaitingReload:Jb,vscodeExtensionReceiptMode:zb,hookBinaryIsDurable:se,hookBinaryPath:_e,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:hw,isRemoteDevContext:os},IP=(e={})=>{let t={...xP,...e},n=()=>EP(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Ts,quitTarget:al},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Uo(r,!0)}`:Ns(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Re(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 ${Oc} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||dw(i.version);return J(r,"copilot")?CP(a,r,o,t.configureVscodeExtension,c,s,t):vP(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?SP(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ds(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await il(Ns(o));if(s.kind==="array"){let c=s.entries.find(Xp)?.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 il(Ns(r));if(o.kind==="array"&&o.entries.some(Xp))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 AP(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await ck(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${Pe} 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 ${Pe} gateway configuration and secret.`)):(l=!0,u.push(y.reason==="cli-not-found"?`The ${o} command-line launcher was not found, so Anyray could not ask ${Pe} to clear its SecretStorage configuration. Install the launcher and re-run revert.`:`VS Code did not confirm the ${Pe} reset. Open VS Code and re-run revert.`))}let f=Ns(o),p=await il(f),h=p.kind==="missing"||p.kind==="array"&&!Jp(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 "${hr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=Jp(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${hr} Custom Endpoint from ${f}`]};await ik(f,w);let g=[...u,`Removed the ${hr} Custom Endpoint from ${f}.`];return await re(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},yk=IP();import{accessSync as XP,constants as Ik,statSync as JP}from"node:fs";import{readFile as Rk,rm as Us}from"node:fs/promises";import{homedir as cf,platform as Nk}from"node:os";import{delimiter as zP,join as lf,resolve as qP}from"node:path";import{execFile as PP}from"node:child_process";import{readFile as LP}from"node:fs/promises";import{homedir as ef,platform as DP}from"node:os";import{join as Bs}from"node:path";import{join as RP}from"node:path";var qp="Iv1.b507a08c87ecfe98",OP="https://github.com/login/device/code",_P="https://github.com/login/oauth/access_token",TP="read:user",gk=1e4,Yo=()=>RP(q(),"copilot-seat-login.json"),wk={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},Qp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bk=async(e={})=>{let t={...wk,...e};try{let n=await t.fetch(OP,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:qp,scope:TP}),signal:AbortSignal.timeout(gk)});if(!n.ok)return;let r=await n.json();if(!Qp(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}},kk=async(e,t={})=>{let n={...wk,...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(_P,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:qp,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(gk)})).json();if(!Qp(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"}},Ak=async(e,t)=>{let n=Yo();return await me(n,`${JSON.stringify({token:e,clientId:qp,mintedAtIso:t},null,2)}
112
+ `),n},ll=async()=>{try{let e=await M(Yo());if(!Qp(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var NP=5e3,tf=5e3,$P=["copilot-cli","CopilotCLI"],MP="https://api.github.com/copilot_internal/user",vk="~/.copilot/config.json",Sk="macOS Keychain (Copilot CLI)",Ek=e=>e===vk||e===Sk,Zo=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),en=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),FP=()=>process.env.XDG_CONFIG_HOME?.trim()||Bs(ef(),".config"),BP=()=>process.env.XDG_DATA_HOME?.trim()||Bs(ef(),".local","share"),UP=async()=>{try{let e=await LP(Bs(ef(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return Zo(t)?t:void 0}catch{}},HP=async e=>{try{let t=await M(Bs(FP(),"github-copilot",e));if(!en(t))return;for(let n of Object.values(t))if(en(n)&&Zo(n.oauth_token))return n.oauth_token}catch{}},WP=async()=>{try{let e=await M(Bs(BP(),"opencode","auth.json")),t=en(e)?e["github-copilot"]:void 0;if(!en(t)||t.type!=="oauth")return;if(Zo(t.access))return t.access;if(Zo(t.refresh))return t.refresh}catch{}},KP=(e,t)=>new Promise((n,r)=>{try{PP(e,[...t],{timeout:NP},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),GP=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return Zo(r)?r:void 0}catch{return}},jP=async(e=KP)=>{for(let t of $P){let n=await GP(t,e);if(n)return n}};var dl={env:process.env,platform:DP,tokenFromDeviceLogin:ll,tokenFromCopilotCliConfig:UP,tokenFromSharedConfig:HP,tokenFromOpenCode:WP,tokenFromKeychain:jP,fetch:(...e)=>fetch(...e)},VP=new Set([401,403,404]),xk=/^[a-z][a-z0-9-]{0,30}$/,YP=e=>e!=="default"&&xk.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",ZP=e=>typeof e!="string"?"default":/^https:\/\/api\.([a-z][a-z0-9-]{0,30})\.githubcopilot\.com\/?$/.exec(e.trim())?.[1]??"default",nf=async(e,t={})=>{let n={...dl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),tf);try{let a=await n.fetch(MP,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=en(i)&&en(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:ZP(s)}}return{verdict:VP.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var Xo=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${xk.test(n)?n:"default"}/header/models`,a=await Ck(o,e,r.clientKey,t);if(a.length>0)return a}return Ck(`${YP(n)}/models`,e,void 0,t)},Ck=async(e,t,n,r={})=>{let o={...dl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),tf);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=en(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!en(u))continue;let f=u.id;if(typeof f!="string"||f.length===0||u.model_picker_enabled!==!0)continue;let p=u.policy;if(en(p)&&p.state!=="enabled")continue;let h=u.supported_endpoints,m=Array.isArray(h)?h.filter(E=>typeof E=="string"):[],w=u.capabilities,g=en(w)?w.limits:void 0,y=E=>{let x=en(g)?g[E]:void 0;return typeof x=="number"&&Number.isFinite(x)&&x>0?Math.floor(x):void 0},b={id:f,endpoints:m},v=y("max_prompt_tokens"),S=y("max_output_tokens");v!==void 0&&(b.maxPromptTokens=v),S!==void 0&&(b.maxOutputTokens=S),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},ul=async(e,t,n,r={})=>{let o={...dl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),tf);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)}},pl=async(e={},t={})=>{let n={...dl,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return Zo(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:Sk,read:()=>n.tokenFromKeychain()}]:[],{source:vk,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await nf(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 zr="copilot-cli",yn="copilot-cli",QP=Ts,eL=()=>QP()?["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."]:[],$k=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],df=()=>Object.fromEntries($k.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),rf=()=>lf(cf(),".anyray","copilot-cli.sh"),Mk="# Managed by anyray-connect. Do not source this file anywhere else.",Ok=e=>e.split(/\r?\n/,1)[0]===Mk,tL=["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"],fl="COPILOT_PROVIDER_API_KEY",_k=e=>e.startsWith(`export ${fl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Pn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",nL=()=>Fs()[0],Hs=(e="default")=>`/copilot/${e}/header`,Cz=Hs(),Xr=e=>e.replace(/\/+$/,""),rL=(e,t="default")=>`${Xr(e.openaiBaseUrl)}${Hs(t)}`,of=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),sf="claude-sonnet-5",oL=()=>{let e=Fs()[0];return e===Ms?sf:e},Fk=e=>e.endpoints.includes(Pn(e.id)==="responses"?"/responses":"/chat/completions"),uf=e=>{let t=e.filter(Fk),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)=>Tk(a.version,s.version)?-1:Tk(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var Tk=(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},Pk=(e,t,n,r,o,a="default")=>{let s=ce({...e.metadata,tool:zr}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...$k];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Se(rL(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Pn(t)}'`,`export COPILOT_MODEL=${Se(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=${Se(i.join(`
113
+ `))}`]:[],`export ${fl}=${Se(n)}`]},af=(e,t,n)=>{let r=ce({...e.metadata,tool:zr});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Se(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Pn(t)}'`,`export COPILOT_MODEL=${Se(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${Se(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${fl}=${Se(n)}`]:[]]},aL=(e,t)=>t||!J(e,"copilot"),Lk=()=>{let e=tL.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).`]},Dk=(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 ${zr}\`), 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`."],sL=(e=process.env.PATH,t=Nk())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(zP)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=qP(o,n);try{if(!JP(a).isFile())continue;return XP(a,t==="win32"?Ik.F_OK:Ik.X_OK),a}catch{}}},iL=()=>lf(cf(),".copilot","config.json"),Tn=()=>lf(cf(),".copilot","mcp-config.json"),Jr="anyray",cL=()=>({type:"local",...Ge("profile"),tools:["*"]}),mr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lL=async()=>{let e=Tn(),t;try{t=await M(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&&!mr(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=(mr(t.mcpServers)?t.mcpServers:{})[Jr];return r!==void 0&&!Xt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${Jr} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},dL=async e=>{let t=Tn(),n=e.json,r=mr(n.mcpServers)?n.mcpServers:{};r[Jr]=cL(),n.mcpServers=r,await Z(t,n)},uL=async()=>{let e=Tn(),t;try{let r=await M(e);if(!mr(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!mr(n)||!(Jr in n)||!Xt(n[Jr],"profile")?!1:(delete n[Jr],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Us(e,{force:!0}):await Z(e,t,{backup:!1}),await re(e),!0)},pL={resolveCopilotCommand:sL,platform:Nk,detectCopilotSeat:up,discoverSeatToken:pl,readDeviceLoginToken:ll,fetchSeatModelCatalog:Xo,probeSeatChatModel:ul},fL=e=>`'${e.replace(/'/g,"''")}'`,hL=e=>e.split(`
114
+ `).map(fL).join(" + [Environment]::NewLine + "),mL=(e={})=>{let t={...pL,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Gc(Ct(),yn))?.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&&Xr(s)===`${Xr(i)}/v1`,a=(s,i)=>s!==void 0&&of(s)&&Xr(s).startsWith(`${Xr(i)}/v1/copilot/`);return{id:zr,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Ts,quitTarget:al},async usesDynamicCredential(s){let i=await r();return a(i,s)||!o(i,s)?!1:!await R(rf())},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=iL();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=Ct(),l=async(E,x,A)=>{let I=E.filter(_k),T=E.filter(xe=>!_k(xe)),B=rf(),X=[...T,...I.length>0?[`[ -r ${Se(B)} ] && . ${Se(B)}`]:[]],V=await R(B),H=V?await Rk(B,"utf8"):void 0,z=H===void 0||Ok(H);if(I.length>0&&!z)return{status:"manual",messages:[`Refused to overwrite user-managed ${B}; move or rename that file, then run Connect again.`]};let ye=se(),Ne=ye?await lL():void 0,ee=[`${c} \u2190 managed Anyray block (${yn})`,...x.map(xe=>` ${xe}`),...I.length>0?[`${B} \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."],...A,Ne?.status==="skipped"?Ne.message:ye?`${Tn()} \u2190 Anyray retrieval MCP server (anyray_retrieve / anyray_recall)`:`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${_e()}). 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.`,...eL()];if(i.dryRun)return{status:"configured",messages:ee};let Fe=!1;Ne?.status==="installable"&&(await dL(Ne),Fe=!0);try{I.length>0?await me(B,[Mk,...I,""].join(`
115
+ `)):V&&z&&await Us(B,{force:!0}),await Kc(c,X,yn)}catch(xe){try{H!==void 0&&z?await me(B,H):z&&await Us(B,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw xe}return{status:"configured",messages:ee,changedFiles:[c,...I.length>0||V&&z?[B]:[],...Fe?[Tn()]:[]]}},d=await r(),u=d!==void 0&&!of(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=oL(),A=x!==sf||!!process.env.ANYRAY_COPILOT_MODEL,I=await t.fetchSeatModelCatalog(g.token,{},E,{laneOrigin:Xr(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),T=I.find(ee=>ee.id===x);if(!A){let ee=uf(I);if(T=ee[0],!i.dryRun&&ee.length>0){let Fe=W=>`${Xr(s.origin)}/v1${Hs(E)}/${Pn(W)==="responses"?"responses":"chat/completions"}`,xe={...df(),authorization:`Bearer ${g.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},_=new Set,L;for(let W of ee.slice(0,4)){let le=await t.probeSeatChatModel(Fe(W.id),xe,W.id);if(le==="ok"){L=W;break}if(le==="unreachable")break;_.add(W.id)}T=L??ee.find(W=>!_.has(W.id))??ee[0]}x=T?.id??sf}let B=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,X=B&&s.clientKey?$t(B):B,V=Pk(s,x,g.token,B,T,E),H=Pk(s,x,$t(g.token),X,T,E),z=Pn(x),ye=I.filter(ee=>Fk(ee)&&Pn(ee.id)===z).map(ee=>ee.id).filter(ee=>ee!==x),Ne=[`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}${A?" (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&&Ek(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."]:[],...ye.length>0?[`Your plan also serves: ${ye.slice(0,8).join(", ")}${ye.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",...H.map(ee=>{let Fe=ee.indexOf("="),xe=ee.slice(7,Fe),_=ee.slice(Fe+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${xe}', ${hL(_)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${g.source}, and the gateway key from \`anyray-connect print-key\`.)`,...Ne]}:l(V,H,Ne)}if(!aL(s,h)){if(p&&!i.dryRun){let E=Ct();if(await ks(E,yn))return{status:"reverted",changedFiles:[E],messages:[`removed a stale Anyray ${yn} 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:",...Dk(t.platform(),y),...Lk()]}}return{status:"held",messages:[...p&&i.dryRun?[`would remove a stale Anyray ${yn} block from ${Ct()} (org lane, not chosen)`]:[],...Dk(t.platform(),y)]}}let b=nL(),v=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,S=v&&s.clientKey?$t(v):v;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...af(s,b,S).map(E=>{let[x,...A]=E.replace(/^export /,"").split("=");return` setx ${x} "${A.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${fl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(af(s,b,v),af(s,b,S),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===Ms?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=Ct(),c=rf(),l=await R(c),d=l?Ok(await Rk(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${yn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Tn()} if registered`,...await R(Yo())?[`would remove the Copilot sign-in Connect minted (${Yo()})`]:[]]};let u=await ks(i,yn);d&&await Us(c,{force:!0});let f=await uL(),p=Yo(),h=await R(p);h&&await Us(p,{force:!0});let m=[...u?[i]:[],...d?[c]:[],...f?[Tn()]:[],...h?[p]:[]];return{status:m.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${yn} block from ${i}`:`no Anyray ${yn} 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 ${Tn()}`]:[],...Lk()],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 M(Tn()),i=mr(s)?s.mcpServers:void 0,c=mr(i)?i[Jr]:void 0;return!mr(c)||!Xt(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"]:of(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(zr)?!0:!await t.detectCopilotSeat()}}},Bk=mL();import{homedir as Yk}from"node:os";import{join as gr}from"node:path";import{constants as wL,chmod as bL,copyFile as kL,readFile as yl}from"node:fs/promises";import{applyEdits as AL,modify as CL}from"jsonc-parser";import{readFile as Uk,rm as yL}from"node:fs/promises";var Hk="// Managed by anyray-connect: OpenCode trim carrier v1",gL=5e3,pf=e=>`${Hk}
116
116
  import { spawn } from "node:child_process"
117
117
 
118
118
  const hookCommand = ${JSON.stringify([e.command,...e.args])}
119
- const hookTimeoutMs = ${uL}
119
+ const hookTimeoutMs = ${gL}
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
- `,Bs=async e=>await R(e)?(await Nk(e,"utf-8")).startsWith(`${$k}
187
- `)?"owned":"foreign":"absent",Mk=async(e,t)=>{let n=lf(t),r=await Bs(e);return r==="foreign"?"foreign":r==="owned"&&await Nk(e,"utf-8")===n?"unchanged":(await he(e,n),"installed")},df=async e=>{let t=await Bs(e);return t!=="owned"?t:(await dL(e,{force:!0}),"removed")};var uf="https://opencode.ai/config.json",Nn="x-anyray-metadata",Mt="x-anyray-api-key",pf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Ln="Authorization",yr=["anthropic","openai"],$n="github-copilot",gL="header",Dn="anyray",wL=()=>process.env.XDG_CONFIG_HOME?.trim()||gr(Wk(),".config"),bL=()=>process.env.XDG_DATA_HOME?.trim()||gr(Wk(),".local","share"),fl=()=>gr(wL(),"opencode"),dl=()=>gr(fl(),"plugins","anyrayTrim.js"),Kk=()=>gr(bL(),"opencode"),Gk=async()=>{try{let e=await pl(gr(Kk(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return U(t)?{chatGptOAuth:U(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}}},Fk=async()=>(await Gk()).chatGptOAuth,kL=["opencode.jsonc","opencode.json","config.json"],zo=async()=>{let e=fl(),t=[];for(let n of kL){let r=gr(e,n);await R(r)&&t.push(r)}return t},Bk=async()=>(await zo())[0]??gr(fl(),"opencode.json"),Jo=async e=>{let t=await R(e),n=t?await pl(e,"utf8"):`{}
188
- `,r=n.trim()?pr(n):{};if(!U(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},jk=(e,t,n=[])=>{if(U(e)&&U(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...jk(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}]},Uk=async(e,t,n,r)=>{let o=jk(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await hL(e,`${e}.anyray-bak`,pL.COPYFILE_EXCL),await fL(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await he(`${e}.anyray-bak`,`{}
186
+ `,Ws=async e=>await R(e)?(await Uk(e,"utf-8")).startsWith(`${Hk}
187
+ `)?"owned":"foreign":"absent",Wk=async(e,t)=>{let n=pf(t),r=await Ws(e);return r==="foreign"?"foreign":r==="owned"&&await Uk(e,"utf-8")===n?"unchanged":(await me(e,n),"installed")},ff=async e=>{let t=await Ws(e);return t!=="owned"?t:(await yL(e,{force:!0}),"removed")};var hf="https://opencode.ai/config.json",Nn="x-anyray-metadata",Ft="x-anyray-api-key",mf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Ln="Authorization",yr=["anthropic","openai"],$n="github-copilot",vL="header",Dn="anyray",SL=()=>process.env.XDG_CONFIG_HOME?.trim()||gr(Yk(),".config"),EL=()=>process.env.XDG_DATA_HOME?.trim()||gr(Yk(),".local","share"),gl=()=>gr(SL(),"opencode"),hl=()=>gr(gl(),"plugins","anyrayTrim.js"),Zk=()=>gr(EL(),"opencode"),Xk=async()=>{try{let e=await yl(gr(Zk(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return U(t)?{chatGptOAuth:U(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}}},Kk=async()=>(await Xk()).chatGptOAuth,xL=["opencode.jsonc","opencode.json","config.json"],zo=async()=>{let e=gl(),t=[];for(let n of xL){let r=gr(e,n);await R(r)&&t.push(r)}return t},Gk=async()=>(await zo())[0]??gr(gl(),"opencode.json"),Jo=async e=>{let t=await R(e),n=t?await yl(e,"utf8"):`{}
188
+ `,r=n.trim()?pr(n):{};if(!U(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},Jk=(e,t,n=[])=>{if(U(e)&&U(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...Jk(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}]},jk=async(e,t,n,r)=>{let o=Jk(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await kL(e,`${e}.anyray-bak`,wL.COPYFILE_EXCL),await bL(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await me(`${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=mL(s,yL(s,i.path,i.value,{formattingOptions:a}));return await he(e,s.endsWith(`
192
+ `},s=t.raw;for(let i of o)s=AL(s,CL(s,i.path,i.value,{formattingOptions:a}));return await me(e,s.endsWith(`
193
193
  `)?s:`${s}
194
- `),!0},AL=async e=>{try{let t=pr(await pl(`${e}.anyray-bak`,"utf8"));return U(t)?t:void 0}catch{return}},ff=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",hf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${ff()}/${gL}`,U=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},CL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===yr[0]||n===yr[1]||n===$n?[]:U(r)&&U(r.options)&&bf(r.options.baseURL,t)?[n]:[]),mf=/claude/i,kf=["model","small_model"],Vk=(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)||!mf.test(o)))return`${yr[0]}/${o}`},yf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)yf(n,t);return t}if(!U(e))return t;for(let[n,r]of Object.entries(e))kf.includes(n)&&typeof r=="string"?t.push(r):yf(r,t);return t},vL=(e,t,n)=>{if(!U(e)||!U(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>mf.test(a)))return!1;let o=`${n}/`;return yf(t).filter(a=>a.startsWith(o)).every(a=>mf.test(a.slice(o.length)))},gf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>gf(o,t,n));if(!U(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=kf.includes(o)?Vk(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=gf(a,t,n)}return r},wf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>wf(o,t[a],n));if(!U(e)||!U(t))return e;let r={};for(let[o,a]of Object.entries(e))kf.includes(o)&&typeof a=="string"&&Vk(t[o],n)===a?r[o]=t[o]:r[o]=wf(a,t[o],n);return r},SL=e=>{if(U(e))for(let t of yr){let n=e[t];if(U(n)&&U(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Us=e=>{if(!U(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Zt({command:t,args:n},"profile")},ul=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),EL=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return U(t)&&t.tool==="opencode"}catch{return!1}},Af=e=>J(e,"copilot")&&!!e.clientKey,xL=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".`]:[],IL=(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.`]:[],RL=e=>Af(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."]:[],OL=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=uf);let o=!1;if(n)if("mcp"in r&&!U(r.mcp))o=!0;else{let y=U(r.mcp)?{...r.mcp}:{},b=y[Dn];b!==void 0&&!Us(b)?o=!0:(y[Dn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(U(r.mcp)&&Us(r.mcp[Dn])){let y={...r.mcp};delete y[Dn],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=U(r.provider)?{...r.provider}:{},s=CL(a,t.origin),i=s.every(y=>vL(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=gf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,h=le({...t.metadata,tool:"opencode"});for(let y of c){let b={...a[y]},v={...b.options};if("headers"in v&&!U(v.headers)){u.push(y);continue}let S=U(v.headers)?{...v.headers}:{},E=!1;for(let[x,A]of[[Mt,p],...h?[[Nn,h]]:[]])x in S?(typeof S[x]!="string"||S[x].trim()==="")&&u.push(`${y}.${x}`):(S[x]=A,d.push(`${y}.${x}`),E=!0);E&&(v.headers=S,b.options=v,a[y]=b)}let m=c.length>0?[]:yr.filter(y=>y!=="openai"||!J(t,"openai")),w=t.byoUpstream;for(let y of m){let b=U(a[y])?{...a[y]}:{},v=U(b.options)?{...b.options}:{};v.baseURL=f;let S=U(v.headers)?{...v.headers}:{};if(y==="anthropic"&&w)v.apiKey=w.key,S[Ln]=`Bearer ${w.key}`,S["x-anyray-provider"]="anthropic",S["x-anyray-auth-mode"]="passthrough",S["x-anyray-custom-host"]=w.url;else{v.apiKey=p,"x-anyray-custom-host"in S&&delete S[Ln];for(let E of pf)delete S[E]}S[Mt]=p,h&&(S[Nn]=h),v.headers=S,b.options=v,a[y]=b}let g=c.length===0&&Af(t);if(g){let y=U(a[$n])?{...a[$n]}:{},b=U(y.options)?{...y.options}:{};b.baseURL=hf(t);let v=U(b.headers)?{...b.headers}:{};v[Mt]=t.clientKey,h&&(v[Nn]=h),b.headers=v,y.options=b,a[$n]=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}},_L=["baseURL","apiKey"],Hk=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!U(s)||!U(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=U(c.headers)?{...c.headers}:void 0,f=u?.[Mt],p=ul(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let h=u,m=U(r)?r.options:void 0,w=U(m)&&U(m.headers)?m.headers:void 0;for(let g of[Mt,Nn])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=U(r)?r.options:void 0,u=U(d)?d:{},f=U(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Mt]=="string"||typeof f[Nn]=="string"||pf.some(h=>h in f);if(!o&&!p)return!1;for(let h of _L)h in u?c[h]!==u[h]&&(c[h]=u[h],l=!0):h in c&&(delete c[h],l=!0);if(U(c.headers)){let h={...c.headers},m=U(u.headers)?u.headers:{};"x-anyray-custom-host"in h&&Ln in h&&(Ln in m?h[Ln]!==m[Ln]&&(h[Ln]=m[Ln],l=!0):(delete h[Ln],l=!0));for(let w of[Mt,Nn,...pf])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},TL=(e,t,n)=>{let r=e[t];if(!U(r)||!U(r.options)||!U(n)||!U(n.options))return!1;let o={...r.options};if(!U(o.headers)||"headers"in n.options&&!U(n.options.headers))return!1;let a={...o.headers},s=U(n.options.headers)?n.options.headers:{},i=!1;return!(Mt in s)&&ul(a[Mt])&&(delete a[Mt],i=!0),!(Nn in s)&&EL(a[Nn])&&(delete a[Nn],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},PL=(e,t)=>{let n={...e},r=!1,o=SL(e.provider);if(U(n.mcp)&&Us(n.mcp[Dn])){let c={...n.mcp};delete c[Dn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!U(n.provider))return{next:n,removed:r};let a={...n.provider},s=U(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===uf&&yr.every(c=>{let l=a[c];return U(l)&&U(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of yr)Hk(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...yr,$n]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;TL(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&U(u)&&U(u.options)&&bf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=wf(n,t,l))}return Hk(a,$n,!0,s[$n])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===uf&&(delete n.$schema,r=!0),{next:n,removed:r}},Yk={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=fl(),t=Kk(),n=await R(e)||await R(t),r=n&&await Fk();return{installed:n,detail:n?`${await Bk()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await Bk(),r=e.openaiBaseUrl,o=le({...e.metadata,tool:"opencode"}),a=Af(e),s=J(e,"openai"),i=await Fk(),c;try{c=await Jo(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(hf(e))}, "headers": { "${Mt}": "<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 Mr()?je("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=OL(c.data,e,l),g=u.length>0,y=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(A=>`provider.${A}`).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(A=>`provider.${A}`).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)"}`,...xL(e),...IL(e,i),a?`provider.github-copilot options.baseURL \u2192 ${hf(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. ${ff()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${ff()} 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).",...RL(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Dn} 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 v=m.length>0?"manual":"configured";if(t.dryRun)return{status:v,messages:b};let E=await Uk(n,c,d,!0)?[n]:[],x=dl();if(ce())try{let A=await Mk(x,za(Ze,["opencode"]));A==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${x} already exists and is not owned by Anyray.`):(A==="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 df(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:v,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await zo())try{let{data:n}=await Jo(t);if(!U(n.provider))continue;for(let r of Object.values(n.provider))if(!(!U(r)||!U(r.options))&&bf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await zo())try{let{data:t}=await Jo(e);if(!U(t.mcp))continue;let n=t.mcp[Dn];if(!Us(n)||!U(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 Bs(dl());e=i==="absent"?"missing":i,e==="owned"&&(t=await pl(dl(),"utf-8")===lf(za(Ze,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await zo()){let c;try{c=await Jo(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!U(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Dn];if(l!==void 0)if(Us(l))if(n=!0,!U(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;sc({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 Mr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await Gk(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await zo()){let{data:o}=await Jo(r);if(U(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!U(s)||!U(s.options)){e.add("unknown");continue}let i=s.options,c=U(i.headers)?i.headers:{};if(a===$n&&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===$n&&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(ul(c[Mt])||ul(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 zo(),n=dl(),r="absent";try{r=await Bs(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 Jo(i)}catch{s.push(i);continue}let{next:l,removed:d}=PL(c.data,await AL(i));d&&(await Uk(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await re(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 df(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 qk}from"node:os";import{join as ml}from"node:path";import{constants as ML,chmod as FL,copyFile as BL,readFile as Qk}from"node:fs/promises";import{applyEdits as UL,modify as HL}from"jsonc-parser";import{homedir as LL}from"node:os";import{dirname as DL,join as Hs}from"node:path";import{mkdir as NL,readFile as Xk,rm as $L}from"node:fs/promises";var Cf="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",Zk=[{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 vf=".anyray-source-sha",en=()=>Hs(LL(),".anyray","openclaw-plugin"),Jk=async(e=en())=>{try{if((await Xk(Hs(e,vf),"utf8")).trim()===Cf)return"current"}catch{}for(let t of Zk){let n=Hs(e,t.path);await NL(DL(n),{recursive:!0,mode:448}),await he(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await he(Hs(e,vf),`${Cf}
195
- `),"installed"},hl=async(e=en())=>{try{await Xk(Hs(e,vf),"utf8")}catch{return!1}return await $L(e,{recursive:!0,force:!0}),!0};var If="x-anyray-metadata",qo="x-anyray-api-key",Rf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],to="Authorization",no="anthropic-beta",yl="interleaved-thinking-2025-05-14",gl=["anthropic","openai"],eA="short",_f="anthropic-messages",Tf=32e3,wl="anthropic/claude-sonnet-4-5",Pf=["anthropic/claude-haiku-4-5"],Lf="anyray/claude-sonnet-4-5",Df=["anyray/claude-haiku-4-5"],WL=[wl,Lf],KL=[Pf,Df],Je="anyray",wr="ANYRAY_API_KEY",Ks="openclaw",tA=()=>process.env.OPENCLAW_STATE_DIR?.trim()||ml(qk(),".openclaw"),eo=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||ml(tA(),"openclaw.json"),D=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zk=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Ws=async e=>{let t=await R(e),n=t?await Qk(e,"utf8"):`{}
196
- `,r=n.trim()?pr(n):{};if(!D(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},nA=(e,t,n=[])=>{if(D(e)&&D(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...nA(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}]},Sf=async(e,t,n,r)=>{let o=nA(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await BL(e,`${e}.anyray-bak`,ML.COPYFILE_EXCL),await FL(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await he(`${e}.anyray-bak`,`{}
194
+ `),!0},IL=async e=>{try{let t=pr(await yl(`${e}.anyray-bak`,"utf8"));return U(t)?t:void 0}catch{return}},yf=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",gf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${yf()}/${vL}`,U=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Cf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},RL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===yr[0]||n===yr[1]||n===$n?[]:U(r)&&U(r.options)&&Cf(r.options.baseURL,t)?[n]:[]),wf=/claude/i,vf=["model","small_model"],zk=(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)||!wf.test(o)))return`${yr[0]}/${o}`},bf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)bf(n,t);return t}if(!U(e))return t;for(let[n,r]of Object.entries(e))vf.includes(n)&&typeof r=="string"?t.push(r):bf(r,t);return t},OL=(e,t,n)=>{if(!U(e)||!U(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>wf.test(a)))return!1;let o=`${n}/`;return bf(t).filter(a=>a.startsWith(o)).every(a=>wf.test(a.slice(o.length)))},kf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>kf(o,t,n));if(!U(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=vf.includes(o)?zk(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=kf(a,t,n)}return r},Af=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Af(o,t[a],n));if(!U(e)||!U(t))return e;let r={};for(let[o,a]of Object.entries(e))vf.includes(o)&&typeof a=="string"&&zk(t[o],n)===a?r[o]=t[o]:r[o]=Af(a,t[o],n);return r},_L=e=>{if(U(e))for(let t of yr){let n=e[t];if(U(n)&&U(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Ks=e=>{if(!U(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Xt({command:t,args:n},"profile")},ml=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),TL=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return U(t)&&t.tool==="opencode"}catch{return!1}},Sf=e=>J(e,"copilot")&&!!e.clientKey,PL=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".`]:[],LL=(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.`]:[],DL=e=>Sf(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."]:[],NL=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=hf);let o=!1;if(n)if("mcp"in r&&!U(r.mcp))o=!0;else{let y=U(r.mcp)?{...r.mcp}:{},b=y[Dn];b!==void 0&&!Ks(b)?o=!0:(y[Dn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(U(r.mcp)&&Ks(r.mcp[Dn])){let y={...r.mcp};delete y[Dn],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=U(r.provider)?{...r.provider}:{},s=RL(a,t.origin),i=s.every(y=>OL(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=kf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,h=ce({...t.metadata,tool:"opencode"});for(let y of c){let b={...a[y]},v={...b.options};if("headers"in v&&!U(v.headers)){u.push(y);continue}let S=U(v.headers)?{...v.headers}:{},E=!1;for(let[x,A]of[[Ft,p],...h?[[Nn,h]]:[]])x in S?(typeof S[x]!="string"||S[x].trim()==="")&&u.push(`${y}.${x}`):(S[x]=A,d.push(`${y}.${x}`),E=!0);E&&(v.headers=S,b.options=v,a[y]=b)}let m=c.length>0?[]:yr.filter(y=>y!=="openai"||!J(t,"openai")),w=t.byoUpstream;for(let y of m){let b=U(a[y])?{...a[y]}:{},v=U(b.options)?{...b.options}:{};v.baseURL=f;let S=U(v.headers)?{...v.headers}:{};if(y==="anthropic"&&w)v.apiKey=w.key,S[Ln]=`Bearer ${w.key}`,S["x-anyray-provider"]="anthropic",S["x-anyray-auth-mode"]="passthrough",S["x-anyray-custom-host"]=w.url;else{v.apiKey=p,"x-anyray-custom-host"in S&&delete S[Ln];for(let E of mf)delete S[E]}S[Ft]=p,h&&(S[Nn]=h),v.headers=S,b.options=v,a[y]=b}let g=c.length===0&&Sf(t);if(g){let y=U(a[$n])?{...a[$n]}:{},b=U(y.options)?{...y.options}:{};b.baseURL=gf(t);let v=U(b.headers)?{...b.headers}:{};v[Ft]=t.clientKey,h&&(v[Nn]=h),b.headers=v,y.options=b,a[$n]=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}},$L=["baseURL","apiKey"],Vk=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!U(s)||!U(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=U(c.headers)?{...c.headers}:void 0,f=u?.[Ft],p=ml(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let h=u,m=U(r)?r.options:void 0,w=U(m)&&U(m.headers)?m.headers:void 0;for(let g of[Ft,Nn])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=U(r)?r.options:void 0,u=U(d)?d:{},f=U(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Ft]=="string"||typeof f[Nn]=="string"||mf.some(h=>h in f);if(!o&&!p)return!1;for(let h of $L)h in u?c[h]!==u[h]&&(c[h]=u[h],l=!0):h in c&&(delete c[h],l=!0);if(U(c.headers)){let h={...c.headers},m=U(u.headers)?u.headers:{};"x-anyray-custom-host"in h&&Ln in h&&(Ln in m?h[Ln]!==m[Ln]&&(h[Ln]=m[Ln],l=!0):(delete h[Ln],l=!0));for(let w of[Ft,Nn,...mf])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},ML=(e,t,n)=>{let r=e[t];if(!U(r)||!U(r.options)||!U(n)||!U(n.options))return!1;let o={...r.options};if(!U(o.headers)||"headers"in n.options&&!U(n.options.headers))return!1;let a={...o.headers},s=U(n.options.headers)?n.options.headers:{},i=!1;return!(Ft in s)&&ml(a[Ft])&&(delete a[Ft],i=!0),!(Nn in s)&&TL(a[Nn])&&(delete a[Nn],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},FL=(e,t)=>{let n={...e},r=!1,o=_L(e.provider);if(U(n.mcp)&&Ks(n.mcp[Dn])){let c={...n.mcp};delete c[Dn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!U(n.provider))return{next:n,removed:r};let a={...n.provider},s=U(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===hf&&yr.every(c=>{let l=a[c];return U(l)&&U(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of yr)Vk(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...yr,$n]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;ML(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&U(u)&&U(u.options)&&Cf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Af(n,t,l))}return Vk(a,$n,!0,s[$n])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===hf&&(delete n.$schema,r=!0),{next:n,removed:r}},qk={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=gl(),t=Zk(),n=await R(e)||await R(t),r=n&&await Kk();return{installed:n,detail:n?`${await Gk()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await Gk(),r=e.openaiBaseUrl,o=ce({...e.metadata,tool:"opencode"}),a=Sf(e),s=J(e,"openai"),i=await Kk(),c;try{c=await Jo(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(gf(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 Nr()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=NL(c.data,e,l),g=u.length>0,y=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(A=>`provider.${A}`).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(A=>`provider.${A}`).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)"}`,...PL(e),...LL(e,i),a?`provider.github-copilot options.baseURL \u2192 ${gf(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. ${yf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${yf()} 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).",...DL(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Dn} 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 v=m.length>0?"manual":"configured";if(t.dryRun)return{status:v,messages:b};let E=await jk(n,c,d,!0)?[n]:[],x=hl();if(se())try{let A=await Wk(x,es(Ve,["opencode"]));A==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${x} already exists and is not owned by Anyray.`):(A==="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 ff(x)==="removed"&&E.push(x)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${_e()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:v,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await zo())try{let{data:n}=await Jo(t);if(!U(n.provider))continue;for(let r of Object.values(n.provider))if(!(!U(r)||!U(r.options))&&Cf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await zo())try{let{data:t}=await Jo(e);if(!U(t.mcp))continue;let n=t.mcp[Dn];if(!Ks(n)||!U(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 Ws(hl());e=i==="absent"?"missing":i,e==="owned"&&(t=await yl(hl(),"utf-8")===pf(es(Ve,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await zo()){let c;try{c=await Jo(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!U(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Dn];if(l!==void 0)if(Ks(l))if(n=!0,!U(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;dc({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 Nr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await Xk(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await zo()){let{data:o}=await Jo(r);if(U(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!U(s)||!U(s.options)){e.add("unknown");continue}let i=s.options,c=U(i.headers)?i.headers:{};if(a===$n&&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===$n&&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(ml(c[Ft])||ml(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 zo(),n=hl(),r="absent";try{r=await Ws(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 Jo(i)}catch{s.push(i);continue}let{next:l,removed:d}=FL(c.data,await IL(i));d&&(await jk(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await re(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 ff(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 rA}from"node:os";import{join as bl}from"node:path";import{constants as KL,chmod as GL,copyFile as jL,readFile as oA}from"node:fs/promises";import{applyEdits as VL,modify as YL}from"jsonc-parser";import{homedir as BL}from"node:os";import{dirname as UL,join as Gs}from"node:path";import{mkdir as HL,readFile as eA,rm as WL}from"node:fs/promises";var Ef="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",Qk=[{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 xf=".anyray-source-sha",tn=()=>Gs(BL(),".anyray","openclaw-plugin"),tA=async(e=tn())=>{try{if((await eA(Gs(e,xf),"utf8")).trim()===Ef)return"current"}catch{}for(let t of Qk){let n=Gs(e,t.path);await HL(UL(n),{recursive:!0,mode:448}),await me(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await me(Gs(e,xf),`${Ef}
195
+ `),"installed"},wl=async(e=tn())=>{try{await eA(Gs(e,xf),"utf8")}catch{return!1}return await WL(e,{recursive:!0,force:!0}),!0};var _f="x-anyray-metadata",qo="x-anyray-api-key",Tf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Qr="Authorization",eo="anthropic-beta",kl="interleaved-thinking-2025-05-14",Al=["anthropic","openai"],aA="short",Lf="anthropic-messages",Df=32e3,Cl="anthropic/claude-sonnet-4-5",Nf=["anthropic/claude-haiku-4-5"],$f="anyray/claude-sonnet-4-5",Mf=["anyray/claude-haiku-4-5"],ZL=[Cl,$f],XL=[Nf,Mf],Ze="anyray",wr="ANYRAY_API_KEY",Vs="openclaw",sA=()=>process.env.OPENCLAW_STATE_DIR?.trim()||bl(rA(),".openclaw"),qr=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||bl(sA(),"openclaw.json"),D=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nA=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},js=async e=>{let t=await R(e),n=t?await oA(e,"utf8"):`{}
196
+ `,r=n.trim()?pr(n):{};if(!D(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},iA=(e,t,n=[])=>{if(D(e)&&D(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...iA(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}]},If=async(e,t,n,r)=>{let o=iA(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await jL(e,`${e}.anyray-bak`,KL.COPYFILE_EXCL),await GL(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await me(`${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=UL(s,HL(s,i.path,i.value,{formattingOptions:a}));return await he(e,s.endsWith(`
200
+ `},s=t.raw;for(let i of o)s=VL(s,YL(s,i.path,i.value,{formattingOptions:a}));return await me(e,s.endsWith(`
201
201
  `)?s:`${s}
202
- `),!0},Ef=async e=>{try{let t=pr(await Qk(`${e}.anyray-bak`,"utf8"));return D(t)?t:void 0}catch{return}},Of=e=>{if(!D(e))return{};let t=e.models;return!D(t)||!D(t.providers)?{}:t.providers},GL=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=le({...t.metadata,tool:Ks}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!D(l.models)&&d.push("models");let u=D(l.models)?{...l.models}:{};if("providers"in u&&!D(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=D(u.providers)?{...u.providers}:{},p=!1;if(n){let S=D(l.plugins)?{...l.plugins}:{},E=D(S.load)?{...S.load}:{},x=D(S.entries)?{...S.entries}:{},A=D(x[Je])?{...x[Je]}:{},I=D(A.config)?{...A.config}:{};if("plugins"in l&&!D(l.plugins)||"load"in S&&!D(S.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in S&&!D(S.entries)||Je in x&&!D(x[Je])||"config"in A&&!D(A.config)||"env"in l&&!D(l.env))d.push("plugins");else{let T=Array.isArray(E.paths)?[...E.paths]:[];T.includes(n)||T.push(n),E.paths=T,S.load=E,A.enabled=!0,I.gatewayUrl=t.anthropicBaseUrl,I.apiKey=r;let B=t.metadata.user,X=t.metadata.team;B&&(I.user=B),X&&(I.team=X),A.config=I,x[Je]=A,S.entries=x,l.plugins=S;let V=D(l.env)?{...l.env}:{};V[wr]=r,l.env=V,p=!0}}let h=gl.filter(S=>S!=="openai"||!J(t,"openai"));for(let S of h){if(S in f&&!D(f[S])){d.push(`models.providers.${S}`);continue}let E=D(f[S])?{...f[S]}:{};if("headers"in E&&!D(E.headers)){i.push(S);continue}let x=D(E.headers)?{...E.headers}:{};if(E.baseUrl=S==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,S==="anthropic"&&(E.api=_f,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=Tf)),S==="anthropic"&&a)E.apiKey=a.key,x[to]=`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[to];for(let A of Rf)delete x[A]}x[qo]=r,o&&(x[If]=o),S==="anthropic"&&(no in x?c=x[no]!==yl:x[no]=yl),E.headers=x,f[S]=E,s.push(S)}u.providers=f,l.models=u;let m=!1,w=!1,g=!1,y,b=[],v="agents"in l&&!D(l.agents)||D(l.agents)&&"defaults"in l.agents&&!D(l.agents.defaults)||D(l.agents)&&D(l.agents.defaults)&&("params"in l.agents.defaults&&!D(l.agents.defaults.params)||"model"in l.agents.defaults&&!D(l.agents.defaults.model));if(v&&d.push("agents.defaults"),s.includes("anthropic")&&!v){let S=D(l.agents)?{...l.agents}:{},E=D(S.defaults)?{...S.defaults}:{},x=D(E.params)?{...E.params}:{};"cacheRetention"in x||(x.cacheRetention=eA,m=!0,E.params=x);let A=D(E.model)?{...E.model}:{},I=p?[...s,Je]:s,T=B=>typeof B=="string"&&I.some(X=>B.startsWith(`${X}/`));typeof A.primary!="string"||A.primary.trim()===""?(A.primary=p?Lf:wl,w=!0,E.model=A,"fallbacks"in A||(A.fallbacks=p?[...Df]:[...Pf],g=!0)):T(A.primary)||(y=A.primary),b=(Array.isArray(A.fallbacks)?A.fallbacks:[]).filter(B=>typeof B=="string"&&!T(B)),(m||w)&&(S.defaults=E,l.agents=S)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:g,unroutedPrimary:y,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},jL=["baseUrl","apiKey","api","maxTokens"],xf=(e,t,n=gl,r)=>{let o={...e},a=!("models"in o)||D(o.models)&&(!("providers"in o.models)||D(o.models.providers)),s=D(o.models)?{...o.models}:{},i=D(s.providers)?{...s.providers}:{},c=Of(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!D(f))continue;let p={...f},h=D(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof h[qo]=="string"||typeof h[If]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Rf.some(S=>S in h)))continue;let w=D(c[u])?c[u]:{},g=D(w.headers)?w.headers:{},y="x-anyray-custom-host"in h,b=S=>S==="api"?p.api===_f:S==="maxTokens"?p.maxTokens===Tf:S==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let S of jL)b(S)&&(S in w?p[S]!==w[S]&&(p[S]=w[S],l=!0):S in p&&(delete p[S],l=!0));let v=[qo,If,...Rf,..."x-anyray-custom-host"in h?[to]:[]];h[no]===yl&&v.push(no);for(let S of v)S in g?h[S]!==g[S]&&(h[S]=g[S],l=!0):S in h&&(delete h[S],l=!0);to in g&&!(to in h)&&(h[to]=g[to],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=D(o.plugins)?{...o.plugins}:{},f=D(u.load)?{...u.load}:{},p=D(u.entries)?{...u.entries}:{};if((!("plugins"in o)||D(o.plugins))&&(!("load"in u)||D(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||D(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[Je];if(D(m)){let w=D(m.config)?m.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let y=D(t?.plugins)?t.plugins:{},b=D(y.entries)?y.entries:{};Je in b?JSON.stringify(p[Je])!==JSON.stringify(b[Je])&&(p[Je]=b[Je],l=!0):(delete p[Je],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,D(o.env)){let w={...o.env},g=w[wr];if(typeof g=="string"&&g.startsWith("ark_")){let y=D(t?.env)?t.env:{};wr in y?w[wr]!==y[wr]&&(w[wr]=y[wr],l=!0):(delete w[wr],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||D(o.agents)&&(!("defaults"in o.agents)||D(o.agents.defaults)&&(!("params"in o.agents.defaults)||D(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||D(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=D(o.agents)?{...o.agents}:{},f=D(u.defaults)?{...u.defaults}:{},p=D(f.params)?{...f.params}:{},h=D(t.agents)?t.agents:{},m=D(h.defaults)?h.defaults:{},w=D(m.params)?m.params:{};p.cacheRetention===eA&&("cacheRetention"in w?p.cacheRetention!==w.cacheRetention&&(p.cacheRetention=w.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let g=D(f.model)?{...f.model}:{},y=D(m.model)?m.model:{};WL.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),KL.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}},rA={id:Ks,title:"OpenClaw",automatic:!0,async detect(){let e=await R(eo())||await R(tA());return{installed:e,detail:e?eo():`no ${ml(qk(),".openclaw")} state dir`}},async apply(e,t){let n=eo();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 ${Ks}\` 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 Ws(n)}catch{return{status:"held",messages:E}}let{next:A,removed:I}=xf(x.data,await Ef(n),gl,en());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 Sf(n,x,A,!1),await re(n),await hl(),{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 hl(),{status:"held",messages:E})}let r=en(),o=!1;if(!t.dryRun)try{await Jk(r)}catch{r=void 0,o=!0}let a;try{a=await Ws(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${_f}", "maxTokens": ${Tf}, "apiKey": "<your personal ark_ key>", "headers": { "${qo}": "<your personal ark_ key>", "${no}": "${yl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${qo}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${wl}") 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}=GL(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=xf(g,await Ef(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: ${le({...e.metadata,tool:Ks})??"(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 ${no} 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?Lf:wl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?Df:Pf).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 (${en()}) and registered it under plugins.entries.${Je}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${en()}; 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."],v=d.length>0||m.length>0?"manual":"configured";if(t.dryRun)return{status:v,messages:b};let S=await Sf(n,a,g,!0);return{status:v,messages:b,changedFiles:S?[n]:[]}},async pointsAt(e){try{let{data:t}=await Ws(eo());for(let a of Object.values(Of(t)))if(D(a)&&zk(a.baseUrl,e))return!0;let n=D(t.plugins)?t.plugins:{},o=(D(n.entries)?n.entries:{})[Je];if(D(o)&&D(o.config)&&zk(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[eo(),ml(en(),".anyray-source-sha")]},async routingExpected(e){return e.includes(Ks)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Ws(eo());for(let a of Object.values(Of(t))){if(!D(a))continue;let s=D(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[qo]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=D(t.plugins)?t.plugins:{},o=(D(n.entries)?n.entries:{})[Je];if(D(o)&&D(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=eo();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 Ws(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}=xf(n.data,await Ef(t),gl,en()),a=await hl();return o?(await Sf(t,n,r,!1),await re(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${en()}`]:[]],changedFiles:[t]}):(await re(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${en()}`]:[]]})}};import{execFile as L$}from"node:child_process";import{readFile as D$}from"node:fs/promises";import{homedir as ci,platform as kr}from"node:os";import{join as kn}from"node:path";import{isDeepStrictEqual as kh,promisify as N$}from"node:util";var Gs=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},bl=(e,t)=>{let n=Gs(e),r=Gs(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 JN}from"node:crypto";import{promises as hC}from"node:fs";import{platform as zN,tmpdir as qN}from"node:os";import{join as Ml}from"node:path";import{execFile as VL}from"node:child_process";import{promises as js}from"node:fs";import{homedir as YL,platform as ZL}from"node:os";import{delimiter as XL,join as kl}from"node:path";import{promisify as JL}from"node:util";var zL=JL(VL),qL=15*6e4,QL=64*1024*1024,eD=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],oA=async(e={})=>{let t=(e.home??YL)(),n=e.env??process.env,r=eD(e.runtimePlatform??ZL()),o=[kl(t,".local","bin"),kl(t,".claude","local"),...(n.PATH??"").split(XL).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=kl(a,`claude${s}`);try{return await js.access(i),i}catch{}}return null},tD=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},nD=async e=>{let t=kl(e,"projects"),n;try{n=(await js.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(!aD.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},rD=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:tD(n.projectList)}},oD=async e=>{let t,n;try{let r=await js.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}},aD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sD=/\.(?:cmd|bat)$/i,iD=(e,t)=>sD.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},aA=async(e,t={})=>{let n=t.exec??zL,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 js.mkdir(e.configDir,{recursive:!0,mode:448}),await js.mkdir(e.workDir,{recursive:!0,mode:448});let o=iD(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:qL,maxBuffer:QL,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=rD(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 oD(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await nD(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as cD}from"node:crypto";import{promises as Mn}from"node:fs";import{homedir as lD,platform as dD}from"node:os";import{join as St}from"node:path";var sA=448,Fn="local_",uD="local-agent-mode-sessions",Nf="-3p",pD="cowork_account_settings.json",ro=(e={})=>{let t=(e.home??lD)(),n=e.runtimePlatform??dD(),r=e.env??process.env;if(n==="darwin")return St(t,"Library","Application Support",`Claude${Nf}`);if(n==="win32"){let o=r.LOCALAPPDATA??St(t,"AppData","Local");return St(o,`Claude${Nf}`)}return null},Vs=(e={})=>{let t=ro(e);return t?t.slice(0,-Nf.length):null},$f=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)}`},Al=async e=>{let t=St(e,uD),n;try{n=(await Mn.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 Mn.readdir(St(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=St(t,o,s);try{await Mn.access(St(i,pD)),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]}},Mf=async e=>{try{let t=await Mn.readdir(e);return new Set(t.filter(n=>n.startsWith(Fn)&&n.endsWith(".json")).map(n=>n.slice(Fn.length,-5)))}catch{return new Set}},Qo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),fD=async(e,t)=>{let n=`${Fn}${t.sessionId}`,r=St(e,n),o=St(r,"outputs"),a=St(r,".claude"),s=St(a,"projects",$f(o));await Mn.mkdir(o,{recursive:!0,mode:sA}),await Mn.mkdir(s,{recursive:!0,mode:sA});let i=St(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${cD()}`;await Mn.copyFile(t.transcriptPath,c),await Mn.chmod(c,384),await Mn.rename(c,i);let l=t.createdAt??Date.now();await Z(St(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})},iA=async(e,t)=>{let n=await Mf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!Qo(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await fD(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as ea}from"node:fs";import{homedir as hD}from"node:os";import{dirname as mD,join as Ys}from"node:path";var yD=448,gD=["Documents","Claude","Projects"],wD="spaces.json",bD=(e={})=>Ys((e.home??hD)(),...gD),kD=async e=>{try{let t=JSON.parse(await ea.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}}},AD=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Ff=async e=>{try{return await ea.access(e),!0}catch{return!1}},CD=async(e,t,n)=>{let r=Ys(t,AD(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Ff(r)?o:r;return a===o&&await Ff(o)?null:(await ea.mkdir(mD(a),{recursive:!0}),await ea.cp(e,a,{recursive:!0}),a)},vD=async e=>{try{let t=(await ea.readFile(Ys(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},cA=async e=>{let t=bD({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=Ys(e.storageDir,wD),{spaces:a,readable:s}=await kD(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=Ys(e.stagedProjectsDir,l.dirName);try{if(!await Ff(d)){n.failed+=1;continue}let u=await CD(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await vD(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 ea.mkdir(e.storageDir,{recursive:!0,mode:yD}),await Z(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as ID}from"node:crypto";import{execFile as RD,spawnSync as bA}from"node:child_process";import{constants as kA}from"node:fs";import{access as Il,chmod as OD,mkdir as _D,readFile as Uf,rename as TD,rm as na,stat as AA,writeFile as PD}from"node:fs/promises";import{homedir as LD,platform as DD,userInfo as ND}from"node:os";import{dirname as $D,isAbsolute as ra,join as Ft,resolve as fA}from"node:path";import{isDeepStrictEqual as Xs,promisify as MD}from"node:util";var Zs="__anyray-claude-desktop-credential";var Cl=["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>`."],vl=["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."],lA="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 Sl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],dA=["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"],SD=new Set(dA),ED=new Set(dA.map(e=>e.toLowerCase())),xD=new Set(Sl.map(e=>e.toLowerCase())),El=(e,t=!1)=>(t?ED:SD).has(t?e.toLowerCase():e),uA=(e,t=!1)=>t?xD.has(e.toLowerCase()):Sl.some(n=>n===e),pA=["*"],oo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...pA]}),ta=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var Js=/^[a-f0-9-]{36}$/,CA="Anyray",Hf=4,Qs=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],ei=["deploymentMode","awaitingSignIn"],vA=[...Qs,...ei,"configLibrary","_meta.json"],gn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),lt=e=>structuredClone(e),zs=async e=>{try{return await Il(e),!0}catch{return!1}},FD=async e=>{try{return await Il(e),"present"}catch(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"?"absent":"unreadable"}},tn=(e={})=>{let t=(e.home??LD)(),n=(e.username??(()=>ND().username))(),r=Ft(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Ft("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Ft(r,"configLibrary"),meta:Ft(r,"configLibrary","_meta.json"),appConfig:Ft(r,"claude_desktop_config.json"),helper:Ft(t,".anyray","bin","claude-desktop-credential-helper"),journal:Ft(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Rl=()=>{let e=bA("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},SA=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],BD=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...SA(t)]}},Wf=(e="json")=>{let t=dn(SA(e)),n=fA(t.command),r=fA(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ce()&&(!o||r!==n)}},UD=e=>`'${e.replace(/'/g,`'"'"'`)}'`,Kf=e=>[e.command,...e.args].map(UD).join(" "),HD=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ra(e.command))throw new Error("the credential helper executable is not absolute")},EA=(e,t)=>{HD(e);let n=Ol(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!ra(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},xA=e=>(EA(e,"--json"),`#!/bin/sh
205
- exec ${Kf(e)}
206
- `),WD=`#!/bin/sh
207
- # Anyray subscription pass-through credential helper v2 for Claude Desktop`,IA=e=>{EA(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),Zs]};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 ${Kf(t)}`,""].join(`
208
- `)},KD=e=>e.args.at(-1)==="--passthrough-headers"?IA(e):xA(e),Ol=e=>/[\\/](node|node\.exe)$/i.test(e),Gf=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++}},GD=e=>{let t=`#!/bin/sh
202
+ `),!0},Rf=async e=>{try{let t=pr(await oA(`${e}.anyray-bak`,"utf8"));return D(t)?t:void 0}catch{return}},Pf=e=>{if(!D(e))return{};let t=e.models;return!D(t)||!D(t.providers)?{}:t.providers},JL=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=ce({...t.metadata,tool:Vs}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!D(l.models)&&d.push("models");let u=D(l.models)?{...l.models}:{};if("providers"in u&&!D(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=D(u.providers)?{...u.providers}:{},p=!1;if(n){let S=D(l.plugins)?{...l.plugins}:{},E=D(S.load)?{...S.load}:{},x=D(S.entries)?{...S.entries}:{},A=D(x[Ze])?{...x[Ze]}:{},I=D(A.config)?{...A.config}:{};if("plugins"in l&&!D(l.plugins)||"load"in S&&!D(S.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in S&&!D(S.entries)||Ze in x&&!D(x[Ze])||"config"in A&&!D(A.config)||"env"in l&&!D(l.env))d.push("plugins");else{let T=Array.isArray(E.paths)?[...E.paths]:[];T.includes(n)||T.push(n),E.paths=T,S.load=E,A.enabled=!0,I.gatewayUrl=t.anthropicBaseUrl,I.apiKey=r;let B=t.metadata.user,X=t.metadata.team;B&&(I.user=B),X&&(I.team=X),A.config=I,x[Ze]=A,S.entries=x,l.plugins=S;let V=D(l.env)?{...l.env}:{};V[wr]=r,l.env=V,p=!0}}let h=Al.filter(S=>S!=="openai"||!J(t,"openai"));for(let S of h){if(S in f&&!D(f[S])){d.push(`models.providers.${S}`);continue}let E=D(f[S])?{...f[S]}:{};if("headers"in E&&!D(E.headers)){i.push(S);continue}let x=D(E.headers)?{...E.headers}:{};if(E.baseUrl=S==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,S==="anthropic"&&(E.api=Lf,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=Df)),S==="anthropic"&&a)E.apiKey=a.key,x[Qr]=`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[Qr];for(let A of Tf)delete x[A]}x[qo]=r,o&&(x[_f]=o),S==="anthropic"&&(eo in x?c=x[eo]!==kl:x[eo]=kl),E.headers=x,f[S]=E,s.push(S)}u.providers=f,l.models=u;let m=!1,w=!1,g=!1,y,b=[],v="agents"in l&&!D(l.agents)||D(l.agents)&&"defaults"in l.agents&&!D(l.agents.defaults)||D(l.agents)&&D(l.agents.defaults)&&("params"in l.agents.defaults&&!D(l.agents.defaults.params)||"model"in l.agents.defaults&&!D(l.agents.defaults.model));if(v&&d.push("agents.defaults"),s.includes("anthropic")&&!v){let S=D(l.agents)?{...l.agents}:{},E=D(S.defaults)?{...S.defaults}:{},x=D(E.params)?{...E.params}:{};"cacheRetention"in x||(x.cacheRetention=aA,m=!0,E.params=x);let A=D(E.model)?{...E.model}:{},I=p?[...s,Ze]:s,T=B=>typeof B=="string"&&I.some(X=>B.startsWith(`${X}/`));typeof A.primary!="string"||A.primary.trim()===""?(A.primary=p?$f:Cl,w=!0,E.model=A,"fallbacks"in A||(A.fallbacks=p?[...Mf]:[...Nf],g=!0)):T(A.primary)||(y=A.primary),b=(Array.isArray(A.fallbacks)?A.fallbacks:[]).filter(B=>typeof B=="string"&&!T(B)),(m||w)&&(S.defaults=E,l.agents=S)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:g,unroutedPrimary:y,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},zL=["baseUrl","apiKey","api","maxTokens"],Of=(e,t,n=Al,r)=>{let o={...e},a=!("models"in o)||D(o.models)&&(!("providers"in o.models)||D(o.models.providers)),s=D(o.models)?{...o.models}:{},i=D(s.providers)?{...s.providers}:{},c=Pf(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!D(f))continue;let p={...f},h=D(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof h[qo]=="string"||typeof h[_f]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Tf.some(S=>S in h)))continue;let w=D(c[u])?c[u]:{},g=D(w.headers)?w.headers:{},y="x-anyray-custom-host"in h,b=S=>S==="api"?p.api===Lf:S==="maxTokens"?p.maxTokens===Df:S==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let S of zL)b(S)&&(S in w?p[S]!==w[S]&&(p[S]=w[S],l=!0):S in p&&(delete p[S],l=!0));let v=[qo,_f,...Tf,..."x-anyray-custom-host"in h?[Qr]:[]];h[eo]===kl&&v.push(eo);for(let S of v)S in g?h[S]!==g[S]&&(h[S]=g[S],l=!0):S in h&&(delete h[S],l=!0);Qr in g&&!(Qr in h)&&(h[Qr]=g[Qr],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=D(o.plugins)?{...o.plugins}:{},f=D(u.load)?{...u.load}:{},p=D(u.entries)?{...u.entries}:{};if((!("plugins"in o)||D(o.plugins))&&(!("load"in u)||D(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||D(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(D(m)){let w=D(m.config)?m.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let y=D(t?.plugins)?t.plugins:{},b=D(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,D(o.env)){let w={...o.env},g=w[wr];if(typeof g=="string"&&g.startsWith("ark_")){let y=D(t?.env)?t.env:{};wr in y?w[wr]!==y[wr]&&(w[wr]=y[wr],l=!0):(delete w[wr],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||D(o.agents)&&(!("defaults"in o.agents)||D(o.agents.defaults)&&(!("params"in o.agents.defaults)||D(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||D(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=D(o.agents)?{...o.agents}:{},f=D(u.defaults)?{...u.defaults}:{},p=D(f.params)?{...f.params}:{},h=D(t.agents)?t.agents:{},m=D(h.defaults)?h.defaults:{},w=D(m.params)?m.params:{};p.cacheRetention===aA&&("cacheRetention"in w?p.cacheRetention!==w.cacheRetention&&(p.cacheRetention=w.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let g=D(f.model)?{...f.model}:{},y=D(m.model)?m.model:{};ZL.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),XL.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}},cA={id:Vs,title:"OpenClaw",automatic:!0,async detect(){let e=await R(qr())||await R(sA());return{installed:e,detail:e?qr():`no ${bl(rA(),".openclaw")} state dir`}},async apply(e,t){let n=qr();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 ${Vs}\` 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 js(n)}catch{return{status:"held",messages:E}}let{next:A,removed:I}=Of(x.data,await Rf(n),Al,tn());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 If(n,x,A,!1),await re(n),await wl(),{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 wl(),{status:"held",messages:E})}let r=tn(),o=!1;if(!t.dryRun)try{await tA(r)}catch{r=void 0,o=!0}let a;try{a=await js(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Lf}", "maxTokens": ${Df}, "apiKey": "<your personal ark_ key>", "headers": { "${qo}": "<your personal ark_ key>", "${eo}": "${kl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${qo}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Cl}") 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}=JL(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=Of(g,await Rf(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: ${ce({...e.metadata,tool:Vs})??"(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 ${eo} 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?$f:Cl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?Mf:Nf).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 (${tn()}) 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 ${tn()}; 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."],v=d.length>0||m.length>0?"manual":"configured";if(t.dryRun)return{status:v,messages:b};let S=await If(n,a,g,!0);return{status:v,messages:b,changedFiles:S?[n]:[]}},async pointsAt(e){try{let{data:t}=await js(qr());for(let a of Object.values(Pf(t)))if(D(a)&&nA(a.baseUrl,e))return!0;let n=D(t.plugins)?t.plugins:{},o=(D(n.entries)?n.entries:{})[Ze];if(D(o)&&D(o.config)&&nA(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[qr(),bl(tn(),".anyray-source-sha")]},async routingExpected(e){return e.includes(Vs)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await js(qr());for(let a of Object.values(Pf(t))){if(!D(a))continue;let s=D(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[qo]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=D(t.plugins)?t.plugins:{},o=(D(n.entries)?n.entries:{})[Ze];if(D(o)&&D(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=qr();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 js(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}=Of(n.data,await Rf(t),Al,tn()),a=await wl();return o?(await If(t,n,r,!1),await re(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${tn()}`]:[]],changedFiles:[t]}):(await re(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${tn()}`]:[]]})}};import{execFile as B$}from"node:child_process";import{readFile as U$}from"node:fs/promises";import{homedir as ui,platform as kr}from"node:os";import{join as kn}from"node:path";import{isDeepStrictEqual as vh,promisify as H$}from"node:util";var Ys=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},vl=(e,t)=>{let n=Ys(e),r=Ys(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 n$}from"node:crypto";import{promises as bC}from"node:fs";import{platform as r$,tmpdir as o$}from"node:os";import{join as Hl}from"node:path";import{execFile as qL}from"node:child_process";import{promises as Zs}from"node:fs";import{homedir as QL,platform as eD}from"node:os";import{delimiter as tD,join as Sl}from"node:path";import{promisify as nD}from"node:util";var rD=nD(qL),oD=15*6e4,aD=64*1024*1024,sD=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],lA=async(e={})=>{let t=(e.home??QL)(),n=e.env??process.env,r=sD(e.runtimePlatform??eD()),o=[Sl(t,".local","bin"),Sl(t,".claude","local"),...(n.PATH??"").split(tD).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Sl(a,`claude${s}`);try{return await Zs.access(i),i}catch{}}return null},iD=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},cD=async e=>{let t=Sl(e,"projects"),n;try{n=(await Zs.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(!uD.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},lD=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:iD(n.projectList)}},dD=async e=>{let t,n;try{let r=await Zs.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}},uD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pD=/\.(?:cmd|bat)$/i,fD=(e,t)=>pD.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},dA=async(e,t={})=>{let n=t.exec??rD,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 Zs.mkdir(e.configDir,{recursive:!0,mode:448}),await Zs.mkdir(e.workDir,{recursive:!0,mode:448});let o=fD(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:oD,maxBuffer:aD,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=lD(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 dD(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await cD(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as hD}from"node:crypto";import{promises as Mn}from"node:fs";import{homedir as mD,platform as yD}from"node:os";import{join as St}from"node:path";var uA=448,Fn="local_",gD="local-agent-mode-sessions",Ff="-3p",wD="cowork_account_settings.json",to=(e={})=>{let t=(e.home??mD)(),n=e.runtimePlatform??yD(),r=e.env??process.env;if(n==="darwin")return St(t,"Library","Application Support",`Claude${Ff}`);if(n==="win32"){let o=r.LOCALAPPDATA??St(t,"AppData","Local");return St(o,`Claude${Ff}`)}return null},Xs=(e={})=>{let t=to(e);return t?t.slice(0,-Ff.length):null},Bf=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)}`},El=async e=>{let t=St(e,gD),n;try{n=(await Mn.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 Mn.readdir(St(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=St(t,o,s);try{await Mn.access(St(i,wD)),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]}},Uf=async e=>{try{let t=await Mn.readdir(e);return new Set(t.filter(n=>n.startsWith(Fn)&&n.endsWith(".json")).map(n=>n.slice(Fn.length,-5)))}catch{return new Set}},Qo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),bD=async(e,t)=>{let n=`${Fn}${t.sessionId}`,r=St(e,n),o=St(r,"outputs"),a=St(r,".claude"),s=St(a,"projects",Bf(o));await Mn.mkdir(o,{recursive:!0,mode:uA}),await Mn.mkdir(s,{recursive:!0,mode:uA});let i=St(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${hD()}`;await Mn.copyFile(t.transcriptPath,c),await Mn.chmod(c,384),await Mn.rename(c,i);let l=t.createdAt??Date.now();await Z(St(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})},pA=async(e,t)=>{let n=await Uf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!Qo(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await bD(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as ea}from"node:fs";import{homedir as kD}from"node:os";import{dirname as AD,join as Js}from"node:path";var CD=448,vD=["Documents","Claude","Projects"],SD="spaces.json",ED=(e={})=>Js((e.home??kD)(),...vD),xD=async e=>{try{let t=JSON.parse(await ea.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}}},ID=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Hf=async e=>{try{return await ea.access(e),!0}catch{return!1}},RD=async(e,t,n)=>{let r=Js(t,ID(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Hf(r)?o:r;return a===o&&await Hf(o)?null:(await ea.mkdir(AD(a),{recursive:!0}),await ea.cp(e,a,{recursive:!0}),a)},OD=async e=>{try{let t=(await ea.readFile(Js(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},fA=async e=>{let t=ED({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=Js(e.storageDir,SD),{spaces:a,readable:s}=await xD(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=Js(e.stagedProjectsDir,l.dirName);try{if(!await Hf(d)){n.failed+=1;continue}let u=await RD(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await OD(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 ea.mkdir(e.storageDir,{recursive:!0,mode:CD}),await Z(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as LD}from"node:crypto";import{execFile as DD,spawnSync as SA}from"node:child_process";import{constants as EA}from"node:fs";import{access as Tl,chmod as ND,mkdir as $D,readFile as Kf,rename as MD,rm as na,stat as xA,writeFile as FD}from"node:fs/promises";import{homedir as BD,platform as UD,userInfo as HD}from"node:os";import{dirname as WD,isAbsolute as ra,join as Bt,resolve as wA}from"node:path";import{isDeepStrictEqual as qs,promisify as KD}from"node:util";var zs="__anyray-claude-desktop-credential";var xl=["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>`."],Il=["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."],hA="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 Rl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],mA=["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"],_D=new Set(mA),TD=new Set(mA.map(e=>e.toLowerCase())),PD=new Set(Rl.map(e=>e.toLowerCase())),Ol=(e,t=!1)=>(t?TD:_D).has(t?e.toLowerCase():e),yA=(e,t=!1)=>t?PD.has(e.toLowerCase()):Rl.some(n=>n===e),gA=["*"],no=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...gA]}),ta=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var Qs=/^[a-f0-9-]{36}$/,IA="Anyray",Gf=4,ni=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],ri=["deploymentMode","awaitingSignIn"],RA=[...ni,...ri,"configLibrary","_meta.json"],gn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),st=e=>structuredClone(e),ei=async e=>{try{return await Tl(e),!0}catch{return!1}},GD=async e=>{try{return await Tl(e),"present"}catch(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"?"absent":"unreadable"}},nn=(e={})=>{let t=(e.home??BD)(),n=(e.username??(()=>HD().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}},Pl=()=>{let e=SA("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},OA=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],jD=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...OA(t)]}},jf=(e="json")=>{let t=dn(OA(e)),n=wA(t.command),r=wA(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:se()&&(!o||r!==n)}},VD=e=>`'${e.replace(/'/g,`'"'"'`)}'`,Vf=e=>[e.command,...e.args].map(VD).join(" "),YD=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ra(e.command))throw new Error("the credential helper executable is not absolute")},_A=(e,t)=>{YD(e);let n=Ll(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!ra(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},TA=e=>(_A(e,"--json"),`#!/bin/sh
205
+ exec ${Vf(e)}
206
+ `),ZD=`#!/bin/sh
207
+ # Anyray subscription pass-through credential helper v2 for Claude Desktop`,PA=e=>{_A(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),zs]};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 ${Vf(t)}`,""].join(`
208
+ `)},XD=e=>e.args.at(-1)==="--passthrough-headers"?PA(e):TA(e),Ll=e=>/[\\/](node|node\.exe)$/i.test(e),Yf=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++}},JD=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=Gf(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Ol(o);if(!ra(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!ra(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return xA(i)===e?i:void 0}catch{return}},jD=e=>{if(!e.startsWith(WD))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=Gf(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==Zs)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return IA(a)===e?a:void 0}catch{return}},VD=`#!/bin/sh
212
- # Anyray subscription pass-through credential helper`,YD=e=>{let t=Ol(e.command);if(!(!ra(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!ra(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=$(${Kf(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
- `)},ZD=e=>{if(!e.startsWith(VD))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=Gf(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return YD(a)===e?a:void 0},RA=e=>GD(e)??jD(e)??ZD(e),XD=async()=>{let e=bA("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},JD=async e=>{let t=[e.command,...Ol(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>AA(r)))).every(r=>r.isFile())?(await Il(e.command,kA.X_OK),!0):!1}catch{return!1}},zD=0,_l=async(e,t,n)=>{await _D($D(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${zD++}.tmp`;try{await PD(r,t,{mode:n}),await OD(r,n),await TD(r,e)}catch(o){throw await na(r,{force:!0}).catch(()=>{}),o}},Bn=async(e,t)=>{await _l(e,`${JSON.stringify(t,null,2)}
214
- `,384)},wn=async e=>{if(!await zs(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await Uf(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!gn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},ti=async e=>{if(!await zs(e))return{present:!1};let t=await AA(e);return{present:!0,content:await Uf(e,"utf-8"),mode:t.mode&511}},OA=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:lt(e[t])}:{present:!1},Bf=(e,t,n)=>{n.present?e[t]=lt(n.value):delete e[t]},hA=e=>gn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),qD=e=>gn(e)&&hA(e.original)&&hA(e.lastWritten),QD=e=>gn(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),mA=(e,t)=>gn(e)&&t.every(n=>qD(e[n])),eN=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],tN=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],jf=(e,t,n,r)=>!(!gn(e)||e.version!==n||typeof e.configId!="string"||!Js.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!Js.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!gn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==CA||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!mA(e.config,r)||r.some(o=>e.config[o].original.present)||!mA(e.deployment,ei)||!gn(e.helper)||e.helper.path!==t.helper||!QD(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),nN=(e,t)=>jf(e,t,Hf,Qs),rN=(e,t)=>jf(e,t,2,eN),oN=(e,t)=>jf(e,t,3,tN),aN=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),yA=e=>({...e,version:Hf,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),Vf=async e=>{if(!await zs(e.journal))return;let t;try{t=JSON.parse(await Uf(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(nN(t,e))return t;if(oN(t,e))return yA(t);if(rN(t,e))return yA(aN(t));throw new Error(`${e.journal} is not a valid ownership journal`)},gA=async(e,t)=>{await _l(e,`${JSON.stringify(t,null,2)}
215
- `,384)},qs=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!Js.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(!gn(o)||typeof o.id!="string"||!Js.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},sN=async(e,t,n)=>{let r=await wn(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=qs(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!Xs(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=qs(r.value);let c=Ft(e.library,`${o}.json`);if(!await zs(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=lt(r.value.entries)}let s=n();if(!Js.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await zs(Ft(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:CA};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?lt(r.value):{},appliedId:s,entries:[...a,i]}}},iN=(e,t)=>{let n=oo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},_A=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),cN=async(e,t,n,r,o,a,s)=>{let i=_A(),c=Object.fromEntries(Qs.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(ei.map(d=>[d,{original:s?.deployment[d].original??OA(r.value,d),lastWritten:i[d]}]));return{version:Hf,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 ti(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},xl=e=>({status:"manual",messages:[e]}),lN=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}`)]}},dN=MD(RD),uN=new Set(Sl),pN=async e=>{try{let{stdout:t}=await dN("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return gn(n)?Object.keys(n):void 0}catch{return}},ao=async(e,t={})=>{let n=t.readManagedPolicyKeys??pN;for(let r of e.managedPolicies){let o=await FD(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=>El(i)&&!uN.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},Yf=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.`},Zf=e=>(e.platform??DD)()==="darwin",TA=async(e,t,n={})=>{if(!Zf(n))return xl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Rl)()&&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=tn(n),a=await ao(o,n);if(a&&r.push({audience:"admin",message:Yf(a)}),r.length>0)return lN(r);let s=!1,i=!1,c=[o.journal];try{let l=J(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??XD)())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=BD((n.credentialCommand??(()=>Wf(d)))(),d),f=KD(u),p=await Vf(o),h=await ti(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 sN(o,p,n.randomUUID??ID),w=Ft(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await wn(w),y=await wn(o.appConfig),b=iN(e,o.helper),v=await cN(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 gA(o.journal,v),i=!0,await _l(o.helper,f,448),v.helper.previousWritten!==void 0&&(delete v.helper.previousWritten,await gA(o.journal,v));let S=lt(g.value);for(let A of Qs)Bf(S,A,b[A]);await Bn(w,S),m.metaToWrite&&await Bn(o.meta,m.metaToWrite);let E=lt(y.value),x=_A();for(let A of ei)Bf(E,A,x[A]);return await Bn(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.",...Cl]}}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.`]}:xl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},wA=(e,t,n,r)=>{let o=lt(e);for(let a of n){let s=t[a];Xs(OA(e,a),s.lastWritten)?Bf(o,a,s.original):r.push(a)}return o},PA=async(e,t={})=>{if(!Zf(t))return{status:"not-found",messages:[]};if((t.appRunning??Rl)())return xl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=tn(t);try{let r=await Vf(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Ft(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 wn(o),i=s.value;s.present&&(i=wA(s.value,r.config,Qs,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await wn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=qs(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&&Xs(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(v=>v.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=Xs(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 na(o,{force:!0}):await Bn(o,i)),l.present&&(u?await na(n.meta,{force:!0}):Xs(l.value,d)||await Bn(n.meta,d));let f=await wn(n.appConfig);if(f.present){let h=wA(f.value,r.deployment,ei,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await na(n.appConfig,{force:!0}):await Bn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await ti(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await _l(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await na(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await na(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?[]:vl]}}catch(r){return xl(`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.`)}},Xf=async(e,t={})=>{if(!Zf(t))return!1;let n=tn(t);if(await ao(n,t))return!1;try{let r=await wn(n.meta);if(!r.present)return!1;let o=qs(r.value),a=await wn(Ft(n.library,`${o}.json`)),s=await wn(n.appConfig);if(!a.present||!s.present)return!1;await Il(n.helper,kA.X_OK);let i=Ye(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}},LA=async(e={})=>{try{let t=tn(e),n=await ti(t.helper);if(!n.present||typeof n.content!="string")return;let r=RA(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},DA=async(e,t={})=>{if(!await Xf(e,t))return!1;let n=tn(t);try{let r=await Vf(n);if(!r)return!1;let o=await wn(n.meta);if(!o.present||qs(o.value)!==r.configId)return!1;let a=await ti(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=RA(a.content??"");return s?await(t.helperLauncherAvailable??JD)(s):!1}catch{return!1}};import{createHash as JA,randomUUID as zA}from"node:crypto";import{spawn as fN,spawnSync as hN}from"node:child_process";import{link as nh,mkdir as Jf,open as qA,readFile as zf,readdir as QA,rename as eC,rm as nn,stat as tC}from"node:fs/promises";import{homedir as rh}from"node:os";import{basename as nC,dirname as ri,join as da,win32 as mN}from"node:path";import{isDeepStrictEqual as oa}from"node:util";var Pe="HKCU\\SOFTWARE\\Policies\\Claude",ni="HKLM\\SOFTWARE\\Policies\\Claude",Dl=5,ua="inferenceGatewayApiKey",$e=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ua],NA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ua],$A=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ua],MA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ua],rC="Managed by anyray-connect; dynamic credential only.",yN=e=>/^[A-Za-z]:[\\/]/.test(e)&&mN.isAbsolute(e),FA=e=>{if(!yN(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)},oC=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!FA(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&&!FA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},oh=(e={})=>da((e.home??rh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),gN=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},wN=e=>(oC(e),["@echo off",`REM ${rC}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(gN).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
216
- `)),bN=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},aC=e=>{let t=e.split(`\r
217
- `);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${rC}`||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(bN);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return oC(s),s}catch{return}},kN=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>tC(r)))).every(r=>r.isFile())}catch{return!1}},AN=async(e,t)=>{let n=aC(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??kN)(n)}catch{return!1}},qf=e=>({sha256:so(e),content:e}),BA=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Bt(t,["sha256","content"])&&ON(t.sha256)&&typeof t.content=="string"&&so(t.content)===t.sha256&&aC(t.content)!==void 0},ah=()=>{let e=hN("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??"")},CN=async(e,t)=>{await Jf(ri(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await qA(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await nh(n,e)}finally{await nn(n,{force:!0}).catch(()=>{})}},vN=e=>`${nC(e)}.anyray-old-`,SN=e=>`${e}.anyray-old-${process.pid}-${zA()}`,sC=async(e,t)=>{try{await nh(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await nn(t,{force:!0}),!0},Pl=async(e,t,n,r,o)=>{let a=SN(e),s=n===void 0?void 0:so(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${zA()}`,c=!1;try{if(i&&n!==void 0){let d=await qA(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 eC(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ca(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await nh(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await la(e)!==s))throw new Error("credential helper publication verification failed");await nn(a,{force:!0}),c=!1}catch(l){throw c&&await sC(e,a).catch(()=>!1),l}finally{i&&await nn(i,{force:!0}).catch(()=>{})}},Qf=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,EN=String.raw`
211
+ `)||n.includes("\r"))return;let r=Yf(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Ll(o);if(!ra(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!ra(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return TA(i)===e?i:void 0}catch{return}},zD=e=>{if(!e.startsWith(ZD))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=Yf(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==zs)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return PA(a)===e?a:void 0}catch{return}},qD=`#!/bin/sh
212
+ # Anyray subscription pass-through credential helper`,QD=e=>{let t=Ll(e.command);if(!(!ra(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!ra(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=$(${Vf(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
+ `)},eN=e=>{if(!e.startsWith(qD))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=Yf(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return QD(a)===e?a:void 0},LA=e=>JD(e)??zD(e)??eN(e),tN=async()=>{let e=SA("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},nN=async e=>{let t=[e.command,...Ll(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>xA(r)))).every(r=>r.isFile())?(await Tl(e.command,EA.X_OK),!0):!1}catch{return!1}},rN=0,Dl=async(e,t,n)=>{await $D(WD(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${rN++}.tmp`;try{await FD(r,t,{mode:n}),await ND(r,n),await MD(r,e)}catch(o){throw await na(r,{force:!0}).catch(()=>{}),o}},Bn=async(e,t)=>{await Dl(e,`${JSON.stringify(t,null,2)}
214
+ `,384)},wn=async e=>{if(!await ei(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await Kf(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!gn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},oi=async e=>{if(!await ei(e))return{present:!1};let t=await xA(e);return{present:!0,content:await Kf(e,"utf-8"),mode:t.mode&511}},DA=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:st(e[t])}:{present:!1},Wf=(e,t,n)=>{n.present?e[t]=st(n.value):delete e[t]},bA=e=>gn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),oN=e=>gn(e)&&bA(e.original)&&bA(e.lastWritten),aN=e=>gn(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),kA=(e,t)=>gn(e)&&t.every(n=>oN(e[n])),sN=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],iN=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],Zf=(e,t,n,r)=>!(!gn(e)||e.version!==n||typeof e.configId!="string"||!Qs.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!Qs.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!gn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==IA||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!kA(e.config,r)||r.some(o=>e.config[o].original.present)||!kA(e.deployment,ri)||!gn(e.helper)||e.helper.path!==t.helper||!aN(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),cN=(e,t)=>Zf(e,t,Gf,ni),lN=(e,t)=>Zf(e,t,2,sN),dN=(e,t)=>Zf(e,t,3,iN),uN=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),AA=e=>({...e,version:Gf,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),Xf=async e=>{if(!await ei(e.journal))return;let t;try{t=JSON.parse(await Kf(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(cN(t,e))return t;if(dN(t,e))return AA(t);if(lN(t,e))return AA(uN(t));throw new Error(`${e.journal} is not a valid ownership journal`)},CA=async(e,t)=>{await Dl(e,`${JSON.stringify(t,null,2)}
215
+ `,384)},ti=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!Qs.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(!gn(o)||typeof o.id!="string"||!Qs.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},pN=async(e,t,n)=>{let r=await wn(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:st(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[st(t.metaEntry)]}}}let c=ti(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!qs(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:st(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...st(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=ti(r.value);let c=Bt(e.library,`${o}.json`);if(!await ei(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=st(r.value.entries)}let s=n();if(!Qs.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await ei(Bt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:IA};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?st(r.value):{},appliedId:s,entries:[...a,i]}}},fN=(e,t)=>{let n=no(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},NA=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),hN=async(e,t,n,r,o,a,s)=>{let i=NA(),c=Object.fromEntries(ni.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(ri.map(d=>[d,{original:s?.deployment[d].original??DA(r.value,d),lastWritten:i[d]}]));return{version:Gf,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??st(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await oi(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},_l=e=>({status:"manual",messages:[e]}),mN=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}`)]}},yN=KD(DD),gN=new Set(Rl),wN=async e=>{try{let{stdout:t}=await yN("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return gn(n)?Object.keys(n):void 0}catch{return}},ro=async(e,t={})=>{let n=t.readManagedPolicyKeys??wN;for(let r of e.managedPolicies){let o=await GD(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=>Ol(i)&&!gN.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},Jf=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.`},zf=e=>(e.platform??UD)()==="darwin",$A=async(e,t,n={})=>{if(!zf(n))return _l("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Pl)()&&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=nn(n),a=await ro(o,n);if(a&&r.push({audience:"admin",message:Jf(a)}),r.length>0)return mN(r);let s=!1,i=!1,c=[o.journal];try{let l=J(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??tN)())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=jD((n.credentialCommand??(()=>jf(d)))(),d),f=XD(u),p=await Xf(o),h=await oi(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 pN(o,p,n.randomUUID??LD),w=Bt(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await wn(w),y=await wn(o.appConfig),b=fN(e,o.helper),v=await hN(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 CA(o.journal,v),i=!0,await Dl(o.helper,f,448),v.helper.previousWritten!==void 0&&(delete v.helper.previousWritten,await CA(o.journal,v));let S=st(g.value);for(let A of ni)Wf(S,A,b[A]);await Bn(w,S),m.metaToWrite&&await Bn(o.meta,m.metaToWrite);let E=st(y.value),x=NA();for(let A of ri)Wf(E,A,x[A]);return await Bn(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.",...xl]}}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.`]}:_l(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},vA=(e,t,n,r)=>{let o=st(e);for(let a of n){let s=t[a];qs(DA(e,a),s.lastWritten)?Wf(o,a,s.original):r.push(a)}return o},MA=async(e,t={})=>{if(!zf(t))return{status:"not-found",messages:[]};if((t.appRunning??Pl)())return _l("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=nn(t);try{let r=await Xf(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 wn(o),i=s.value;s.present&&(i=vA(s.value,r.config,ni,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await wn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=ti(l.value),m=st(l.value.entries),w=m.findIndex(b=>b.id===r.configId),g=w>=0?m[w]:void 0,y=g!==void 0&&qs(g,r.metaEntry);if(g!==void 0&&!y&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=st(l.value),h===r.configId){let b=r.originalAppliedId;b&&m.some(v=>v.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=qs(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(y&&m.splice(w,1),d={...st(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await na(o,{force:!0}):await Bn(o,i)),l.present&&(u?await na(n.meta,{force:!0}):qs(l.value,d)||await Bn(n.meta,d));let f=await wn(n.appConfig);if(f.present){let h=vA(f.value,r.deployment,ri,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await na(n.appConfig,{force:!0}):await Bn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await oi(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Dl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await na(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await na(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?[]:Il]}}catch(r){return _l(`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.`)}},qf=async(e,t={})=>{if(!zf(t))return!1;let n=nn(t);if(await ro(n,t))return!1;try{let r=await wn(n.meta);if(!r.present)return!1;let o=ti(r.value),a=await wn(Bt(n.library,`${o}.json`)),s=await wn(n.appConfig);if(!a.present||!s.present)return!1;await Tl(n.helper,EA.X_OK);let i=je(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}},FA=async(e={})=>{try{let t=nn(e),n=await oi(t.helper);if(!n.present||typeof n.content!="string")return;let r=LA(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},BA=async(e,t={})=>{if(!await qf(e,t))return!1;let n=nn(t);try{let r=await Xf(n);if(!r)return!1;let o=await wn(n.meta);if(!o.present||ti(o.value)!==r.configId)return!1;let a=await oi(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=LA(a.content??"");return s?await(t.helperLauncherAvailable??nN)(s):!1}catch{return!1}};import{createHash as tC,randomUUID as nC}from"node:crypto";import{spawn as bN,spawnSync as kN}from"node:child_process";import{link as ah,mkdir as Qf,open as rC,readFile as eh,readdir as oC,rename as aC,rm as rn,stat as sC}from"node:fs/promises";import{homedir as sh}from"node:os";import{basename as iC,dirname as si,join as da,win32 as AN}from"node:path";import{isDeepStrictEqual as oa}from"node:util";var Le="HKCU\\SOFTWARE\\Policies\\Claude",ai="HKLM\\SOFTWARE\\Policies\\Claude",Fl=5,ua="inferenceGatewayApiKey",$e=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ua],UA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ua],HA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ua],WA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ua],cC="Managed by anyray-connect; dynamic credential only.",CN=e=>/^[A-Za-z]:[\\/]/.test(e)&&AN.isAbsolute(e),KA=e=>{if(!CN(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)},lC=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!KA(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&&!KA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},ih=(e={})=>da((e.home??sh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),vN=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},SN=e=>(lC(e),["@echo off",`REM ${cC}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(vN).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
216
+ `)),EN=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},dC=e=>{let t=e.split(`\r
217
+ `);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${cC}`||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(EN);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return lC(s),s}catch{return}},xN=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>sC(r)))).every(r=>r.isFile())}catch{return!1}},IN=async(e,t)=>{let n=dC(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??xN)(n)}catch{return!1}},th=e=>({sha256:oo(e),content:e}),GA=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Ut(t,["sha256","content"])&&NN(t.sha256)&&typeof t.content=="string"&&oo(t.content)===t.sha256&&dC(t.content)!==void 0},ch=()=>{let e=kN("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??"")},RN=async(e,t)=>{await Qf(si(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await rC(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await ah(n,e)}finally{await rn(n,{force:!0}).catch(()=>{})}},ON=e=>`${iC(e)}.anyray-old-`,_N=e=>`${e}.anyray-old-${process.pid}-${nC()}`,uC=async(e,t)=>{try{await ah(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await rn(t,{force:!0}),!0},$l=async(e,t,n,r,o)=>{let a=_N(e),s=n===void 0?void 0:oo(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${nC()}`,c=!1;try{if(i&&n!==void 0){let d=await rC(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 aC(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ca(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await ah(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await la(e)!==s))throw new Error("credential helper publication verification failed");await rn(a,{force:!0}),c=!1}catch(l){throw c&&await uC(e,a).catch(()=>!1),l}finally{i&&await rn(i,{force:!0}).catch(()=>{})}},nh=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,TN=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
- }`,Hn=async e=>new Promise((t,n)=>{let r=fN("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",EN],{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(Qf(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(Qf({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Ut=(e={})=>da((e.home??rh)(),".anyray","claude-desktop-windows.json"),xN=e=>da((e.home??rh)(),".anyray","claude-desktop-windows.lock"),ia=class extends Error{},IN=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},sh=async e=>{let t=xN(e);await Jf(ri(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=JA("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=da(t,"owner.json");try{await Jf(t,{mode:448}),await he(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
287
- `)}catch(a){if(a.code!=="EEXIST")throw await nn(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await zf(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!IN(i.pid)}catch{try{s=Date.now()-(await tC(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new ia;await nn(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await zf(o,"utf8")).nonce===r&&await nn(t,{recursive:!0,force:!0})}catch{}}}throw new ia},iC=()=>Object.fromEntries($e.map(e=>[e,{present:!1}])),so=e=>JA("sha256").update(e).digest("hex"),RN=(e,t)=>t.present?e===ua?{present:!0,type:t.type,sha256:so(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},aa=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?so(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)),Nl=(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===ua?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=>Nl(e[t],t)),HA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,NA)&&NA.every(t=>Nl(e[t],t)),ON=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),ih=(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===oh(t)&&(n.lastWritten===void 0||BA(n.lastWritten))&&(n.pending===void 0||BA(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},_N=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Dl&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&UA(e.lastWritten)&&(e.pending===void 0||UA(e.pending))&&ih(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),TN=e=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&HA(e.lastWritten)&&(e.pending===void 0||HA(e.pending)),WA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,$A)&&$A.every(t=>Nl(e[t],t)),PN=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&WA(e.lastWritten)&&(e.pending===void 0||WA(e.pending))&&ih(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),KA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,MA)&&MA.every(t=>Nl(e[t],t)),LN=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&KA(e.lastWritten)&&(e.pending===void 0||KA(e.pending))&&ih(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),GA=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),ch=e=>{let{pending:t,...n}=e;return{...n,version:Dl,lastWritten:GA(e.lastWritten),...t?{pending:GA(t)}:{}}},jA=e=>({...e,chatTabEnabled:{present:!1}}),DN=e=>{let{pending:t,...n}=e;return ch({...n,version:4,lastWritten:jA(e.lastWritten),...t?{pending:jA(t)}:{}})},VA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),NN=(e,t)=>ch({version:4,registryKey:Pe,keyExisted:e.keyExisted,lastWritten:VA(e.lastWritten),...e.pending?{pending:VA(e.pending)}:{},helper:{path:oh(t)}}),lh=async(e,t=!0)=>{let n=Ut(e),r=ri(n),o=`${nC(n)}.anyray-old-`,a=(await QA(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>da(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 eC(a[0],n):s=a[0]}let i=await M(s),c=TN(i)?NN(i,e):PN(i,e)?DN(i):LN(i,e)?ch(i):_N(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>nn(l,{force:!0}))),c},YA=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:Pe,keyExisted:e.keyExisted,lastWritten:YA(e.lastWritten),...e.pending?{pending:YA(e.pending)}:{}}:e,Tl=async(e,t)=>{let n=Ut(t),r=`${JSON.stringify($N(e),null,2)}
288
- `;t.writeJournalFile?await t.writeJournalFile(n,r):await he(n,r)},MN=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,FN=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),BN=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),UN=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),HN=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===UN(t).toUpperCase(),ZA=(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},WN=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,KN=(e,t)=>{if(!El(e,!0))return!1;let n=WN(t);if(BN.has(n))return!1;if(FN.has(n))return n==="REG_EXPAND_SZ"?!0:!uA(e,!0)},GN=(e,t)=>{let n=iC(),r=!1,o=!1,a=!1,s=t.toUpperCase()===ni.toUpperCase(),i=(l,d)=>{if(!s)return;let u=KN(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),ZA(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||HN(d,t))continue;let u=MN.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),ZA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Un=async(e,t=Pe)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:iC(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return GN(n.stdout,t)},br=async e=>{let t=await Un(e,ni);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...$e.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},dh=e=>e.unparsed?`This machine may have a Claude policy under ${ni} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${ni} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${ni} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var $l=(e,t)=>ta(oo(e,t)),cC=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],jN=(e,t)=>{let n=$l(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}]}))},VN=(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}}),YN=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,eh=e=>Object.fromEntries($e.map(t=>[t,RN(t,e[t])])),XA=(e,t,n,r)=>({version:Dl,registryKey:Pe,keyExisted:e,lastWritten:eh(t),helper:{path:n,lastWritten:qf(r)}}),ZN=(e,t,n,r,o,a)=>({version:Dl,registryKey:Pe,keyExisted:e,lastWritten:eh(t),pending:eh(n),helper:{path:r,...o?{lastWritten:qf(o)}:{},pending:qf(a)}}),th=(e,t,n)=>aa(n,e.lastWritten[t])||e.pending!==void 0&&aa(n,e.pending[t]),ca=async e=>{try{let t=await zf(e,"utf8");return{content:t,sha256:so(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},la=async e=>(await ca(e))?.sha256,sa=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Ll=async(e,t)=>{let n=vN(e),r;try{r=await QA(ri(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>da(ri(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([ca(e),ca(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!sa(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await sC(e,a))throw new Error("credential helper changed during recovery");return}if(t&&sa(t,s.sha256)&&sa(t,i.sha256)){await nn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},uh=async(e,t,n)=>(n.present?await e(cC(Pe,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Pe,"/v",t,"/f"])).code===0,XN=async(e,t,n)=>{let r=!0,o=await Un(e);for(let a of $e)if(!oa(o.values[a],t[a])){if(!oa(o.values[a],n[a])){r=!1;continue}await uh(e,a,t[a])||(r=!1),o=await Un(e)}return r&&$e.every(a=>oa(o.values[a],t[a]))},ze=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Ut(n)]}}),lC=async(e,t,n,r={})=>{if(!Ie(t))return ze("A valid personal ark_ gateway key is required.",!1,r);let o=oh(r),a;try{a=wN((r.credentialCommand??Wf)())}catch{return ze("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=so(a),i=r.runReg??Hn,c=Ut(r),l;if(!n.dryRun)try{l=await sh(r)}catch(m){return ze(m instanceof ia?"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 br(i);if(m)return ze(dh(m),!1,r);let w=await lh(r,!n.dryRun);n.dryRun||await Ll(o,w);let g=await Un(i),y=jN(e,o),b=await ca(o),v=b?.sha256,S=!1;if(d=w,u=g,f=y,w){let A=$e.find(I=>!th(w,I,g.values[I]));if(A)return ze(`Claude's ${A} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(v!==void 0&&!sa(w,v))return ze(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);S=YN(w)}else{if(v!==void 0&&v!==s)return ze(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let A=g.foreignState||$e.some(B=>g.values[B].present),I=$e.every(B=>oa(g.values[B],y[B])),T=$e.every(B=>oa(g.values[B],VN(e,t.trim())[B]));if(A&&!I&&!T)return ze(`Existing Claude third-party-inference policy values under ${Pe} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(S=T,I&&v===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Pe} into an owner-only journal without rewriting them.`]}:(await Tl(XA(g.keyPresent,y,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Pe} into the ownership journal.`]})}if(S){let A=!0;try{A=(r.appRunning??ah)()}catch{}if(A)return ze("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=ZN(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 ${Pe}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Tl(E,r),h=!0;for(let A of $e){let I=await Un(i);if(!aa(I.values[A],E.lastWritten[A])&&!aa(I.values[A],E.pending[A]))throw new Error("registry value changed during apply");if(!oa(I.values[A],y[A])&&!await uh(i,A,y[A]))throw new Error("registry write failed")}let x=await Un(i);if(!$e.every(A=>aa(x.values[A],E.pending[A])))throw new Error("registry verification failed");if(v!==s&&(v===void 0?await CN(o,a):await Pl(o,v,a,"apply",r)),await la(o)!==s)throw new Error("credential helper verification failed");return await Tl(XA(E.keyExisted,y,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Pe}.`,`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.",...Cl]}}catch{if(!h||!u||!f||!p)return ze("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Ll(o,p);let m=!0,w=await ca(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await Pl(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await la(o)===p.helper.lastWritten.sha256):await Pl(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await XN(i,u.values,f))return d?await Tl(d,r):await nn(c,{force:!0}),ze("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return ze("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?.()}},dC=async(e,t={})=>{let n=t.runReg??Hn,r=Ut(t),o;if(!e.dryRun)try{o=await sh(t)}catch(a){return ze(a instanceof ia?"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 lh(t,!e.dryRun);a&&!e.dryRun&&await Ll(a.helper.path,a);let s=await Un(n);if(!a)return $e.filter(h=>s.values[h].present).length>0?ze(`Claude policy values exist under ${Pe}, 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&&!th(a,p,s.values[p])),c=await la(a.helper.path),l=c!==void 0&&!sa(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Pe}.`,`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 Un(n)).values[p];if(m.present){if(!th(a,p,m)){u.add(p);continue}await uh(n,p,{present:!1})||(d=!0)}}let f=await la(a.helper.path);if(f!==void 0)if(sa(a,f))try{await Pl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?ze(`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 nn(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Pe}.`,"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?[]:vl]})}catch{return ze(`Could not safely inspect or revert ${Pe}; no unproven value was removed.`,!1,t)}finally{await o?.()}},uC=async(e,t={})=>{let n=t.runReg??Hn;if(!await R(Ut(t)))return;let r;try{r=await sh(t);let o=await lh(t);if(o&&await Ll(o.helper.path,o),!o||o.pending||await br(n)!==void 0)return;let a=await Un(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ye(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&$e.every(l=>aa(a.values[l],o.lastWritten[l]))))return;let i=await la(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 AN(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?.()}},pC=async(e,t={})=>await uC(e,t)!==void 0,fC=async(e,t={})=>await uC(e,t)==="dynamic";var pa=(e=zN())=>e==="win32"?ah:Rl,ph="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Fl=async(e,t={})=>{let n=(t.profileRoot??ro)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:ph};if((t.appRunning??pa(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await hC.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 Al(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 "+ph}:{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??oA)();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=Ml(t.stagingRoot??qN(),`anyray-history-${process.pid}-${JN()}`);try{let s=await(t.runImporter??aA)({binary:o,exportPath:e,configDir:Ml(a,"config"),workDir:Ml(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. "+ph};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 iA(r.dir,s.conversations),c=await cA({stagedProjectsDir:Ml(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 hC.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as xt}from"node:fs";import{homedir as k$}from"node:os";import{join as on,sep as A$}from"node:path";import{isDeepStrictEqual as Wl}from"node:util";import{constants as QN}from"node:fs";import{promises as G}from"node:fs";import{dirname as fa,isAbsolute as hh,join as Q,relative as Bl,resolve as rn,sep as oi}from"node:path";import{randomUUID as Kl}from"node:crypto";var bn=448,ai=384,wC=448,e$=4,mh=3e4,bC=5e3,t$=10*6e4,fh=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),dt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),si=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),kC=(e,t)=>{let n=Bl(rn(e),rn(t));return n===""||!n.startsWith(`..${oi}`)&&n!==".."&&!hh(n)},io=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 Et(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},Et=e=>e instanceof Error&&"code"in e,n$=e=>{try{return process.kill(e,0),!0}catch(t){return Et(t)&&t.code==="EPERM"}},AC=e=>e===0?"owner.json":`owner.${e}.json`,Ul=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=Q(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}},CC=e=>{if(e.pid===void 0||!n$(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>mh&&t-e.createdAtMs>t$},r$=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(fa(t),{recursive:!0,mode:bn});let n=Kl(),r,o=!1;try{await G.mkdir(t,{mode:bn}),o=!0}catch(i){if(!Et(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Ul(t);if(d){if(!CC(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)<=mh)return}let l=Q(t,AC(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
289
- `,{flag:"wx",mode:ai}),r=l}catch(d){if(Et(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{}})()},bC);return s.unref(),async()=>{clearInterval(s);try{(await Ul(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},o$=async(e,t,n)=>{await G.mkdir(fa(e),{recursive:!0,mode:bn});let r=await r$(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!Et(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${Kl()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
290
- `,{mode:ai,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},Gl=async(e,t)=>{for(let n=0;n<e$;n+=1){let r=await io(e);if(!r)return"failed";let o=t(r.value);if(!o||Wl(o,r.value))return"unchanged";try{if(await o$(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},mC=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},jl=async e=>{let t=[];for(let n of await mC(e))for(let r of await mC(Q(e,n)))t.push(Q(e,n,r));return t},a$=e=>Array.isArray(e.skills)?e.skills.filter(t=>dt(t)&&si(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],s$=async e=>{let t=Q(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await jl(t)){let o=await io(Q(r,"manifest.json"));if(!o)continue;let a=r.split(oi).at(-1)??"";for(let s of a$(o.value))n.push({account:a,packageDir:r,entry:s})}return n},i$=async e=>{let t=await io(Q(e,".claude-plugin","plugin.json"));return!!t&&si(t.value.name)},c$=(e,t)=>{let n=hh(t)?rn(t):rn(e,t);if(!kC(e,n)||n===rn(e))return;let r=Bl(rn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},l$=async e=>{let t=await jl(Q(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(oi).includes("skills-plugin"))continue;let o=Q(r,"cowork_plugins"),a=await io(Q(o,"installed_plugins.json"));if(!a||!dt(a.value.plugins))continue;let s=r.split(oi).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!si(i)||!Array.isArray(c)))for(let l of c){if(!dt(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=c$(o,l.installPath);!d||!await i$(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:Q(r,"cowork_account_settings.json")})}}return n},d$=async e=>{let t=await io(Q(e,"claude_desktop_config.json"));return!t||!dt(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>si(n)&&n.toLowerCase()!=="anyray"&&dt(r)))},vC=async e=>{let[t,n,r]=await Promise.all([s$(e),l$(e),d$(e)]);return{skills:t,plugins:n,localMcpServers:r}},yh=async e=>{let t=await vC(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)}},yC=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(!si(o.name))return!1;let a=Q(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)},u$=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=Q(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,bn);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?wC:ai)}}};await t(e),await G.chmod(e,bn)},SC=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},Hl=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(!Wl(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 Hl(Q(e,s),Q(t,s)))return!1}else if(!i.isFile()||!await SC(Q(e,s),Q(t,s)))return!1}return!0}catch{return!1}},EC=e=>`${e}.anyray-incomplete`,xC=async(e,t)=>{let n=!1;if(t){await G.mkdir(fa(e),{recursive:!0,mode:bn});try{await G.mkdir(e,{mode:bn}),n=!0}catch(l){if(!Et(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=Kl(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await Ul(e)}catch{return}if(f){if(!CC(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)<=mh)return}let u=Q(e,AC(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
291
- `,{flag:"wx",mode:ai}),o=u}catch(f){if(Et(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{}})()},bC);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Ul(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},IC=async e=>{let t=await xC(e,!1);t&&await t.complete()},p$=async(e,t,n)=>{let r=EC(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Hl(e,t))return await IC(r),"present"}catch(c){if(!Et(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 xC(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:bn})}catch(c){if(!Et(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=Q(c,u.name),p=Q(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(p,{mode:bn})}catch(m){if(!Et(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,QN.COPYFILE_EXCL);let h=await G.stat(f);await G.chmod(p,(h.mode&73)!==0?wC:ai)}catch(h){if(!Et(h)||h.code!=="EEXIST")throw h;if(!await SC(f,p))return"conflict"}else return"failed"}catch(h){return Et(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 Hl(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},RC=async(e,t,n,r)=>{if(!await yC(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Hl(e,t))return await IC(EC(t)),"present"}catch(a){if(!Et(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(fa(t),{recursive:!0,mode:bn});let o=Q(fa(t),`.anyray-stage-${Kl()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await yC(o)?(await u$(o),await n?.(t),await p$(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},gC=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),f$=async e=>{let t=await jl(Q(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await io(Q(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},h$=async e=>{let t=await jl(Q(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(oi).includes("skills-plugin"))try{await G.access(Q(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},m$=async(e,t,n,r,o)=>{let a=Q(t,"manifest.json");for(let s of e){let i=Q(s.packageDir,"skills",s.entry.name);try{await G.access(Q(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=Q(t,"skills",s.entry.name),l=await RC(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 Gl(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}},OC=(e,t)=>({...e,installPath:t}),y$=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=hh(r.installPath)?rn(r.installPath):rn(o,r.installPath),s=OC(e,Bl(rn(t),rn(n))),i={...r,installPath:Bl(rn(o),a)};return Wl(s,i)},g$=async(e,t,n)=>{let r=await io(e);if(!r||!dt(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":Gl(t,a=>{let s=dt(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},w$=async(e,t,n,r,o)=>{let a=Q(t,"cowork_plugins"),s=Q(a,"installed_plugins.json"),i=Q(t,"cowork_account_settings.json");for(let c of e){let l=Q(a,c.relativeInstallPath);if(!kC(a,l)){n.invalid+=1;continue}let d=await RC(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 Gl(s,h=>{let m=dt(h.plugins)?h.plugins:{},w=m[c.id],g=Array.isArray(w)?w:[],y=g.find(v=>dt(v)&&v.scope==="user");if(y){u=y$(c.entry,fa(c.settingsFile),c.packageDir,y,t),f=!u;return}let b=OC(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 g$(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},b$=async(e,t,n)=>{let r=Q(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await Gl(r,c=>{let l=dt(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=Wl(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}},_C=async(e,t,n={})=>{let r=await vC(e),o=fh("skill"),a=fh("plugin"),s=fh("local-mcp"),i=[],c=[],l=gC(r.skills,n.account,n.allAccounts),d=gC(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 f$(t);f.state==="found"?await m$(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 h$(t);f.state==="found"?await w$(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await b$(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 C$=async e=>{try{return await xt.access(e),!0}catch{return!1}},TC=448,v$=384,LC={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},S$=["code","cowork"],bh=(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.",gh=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),DC=async e=>{let t;try{t=(await xt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&Qo(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await xt.readdir(on(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&Qo(a.name)).map(a=>a.name);for(let a of o)n.push(on(e,r,a))}catch{}return n},E$=async e=>{try{return(await xt.readdir(e)).filter(t=>t.startsWith(Fn)&&t.endsWith(".json")).map(t=>t.slice(Fn.length,-5)).filter(Qo)}catch{return[]}},x$=async(e,t)=>{let n=await DC(on(e,LC[t])),r=[];for(let o of n){let a=await E$(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(A$).slice(-2)[0]})}return r},I$=async(e,t)=>{if(t==="cowork"){let r=await Al(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await DC(on(e,LC.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},R$=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await xt.copyFile(e,n),await xt.chmod(n,v$),await xt.rename(n,t)},O$=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||!Qo(o)?!1:(await xt.access(on(t,".claude","projects",$f(r),`${o}.jsonl`)),!0)}catch{return!1}},_$=async(e,t,n,r)=>{let o=gh(e),a=await Mf(n);for(let s of t)await T$(e,s,n,r,a,o);return o},T$=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Fn}${s}.json`,c=on(t.dir,i);try{if(e==="code"){if(!await O$(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=on(t.dir,`${Fn}${s}`),d=on(n,`${Fn}${s}`),u=await xt.readdir(l);await xt.mkdir(d,{mode:TC});for(let f of u)await xt.cp(on(l,f),on(d,f),{recursive:!0,force:!1,errorOnExist:!0});await xt.chmod(d,TC)}await R$(c,on(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},PC=(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
- `)}},wh=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),NC=async e=>{let t=[];for(let n of S$)t.push({lane:n,sources:await x$(e,n)});return t},$C=async(e={})=>{let t=(e.firstPartyRoot??(()=>Vs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([NC(t),yh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=wh(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}},co=async(e={})=>{let t=(e.home??k$)(),n=(e.firstPartyRoot??(()=>Vs()))(),r=(e.thirdPartyRoot??(()=>ro()))();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??pa())())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([NC(n),yh(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=wh(o);for(let w of h)m.add(w);if(m.size>1)return PC(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=wh(o);for(let h of a.accounts)p.add(h);if(p.size>1)return PC(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 C$(r),l=await _C(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(gh(p));continue}let m=await I$(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(gh(p));continue}d.push(await _$(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:bh(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 P$=e=>[ot(e)],MC=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...P$(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 FC="1.21459.0",$$=N$(L$),M$=async e=>{try{let{stdout:t}=await $$("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},F$=async e=>{try{return await D$(e)}catch{return}},BC="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",B$=["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."],ha=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(UC??=HC({}),UC):HC(e),UC,HC=async e=>{let t=(e.home??ci)(),n=["/Applications/Claude.app",kn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??M$,o=e.readClaudeAppBundle??F$;for(let a of n){let s=await r(kn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${BC}`}),c=bl(s,FC);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${FC} or newer.`);let l=await o(kn(a,"Contents","Resources","app.asar"));return l?vA.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. ${BC}`}},Vl="anyray",GC="--anyray-owner=claude-desktop-v1",Yl=(e={})=>{let t=(e.platform??kr)(),n=(e.home??ci)();return t==="darwin"?tn(e).appConfig:t==="win32"?kn(process.env.APPDATA??kn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):kn(n,".config","Claude","claude_desktop_config.json")},Sh=(e={})=>kn((e.home??ci)(),"Library","Application Support","Claude","claude_desktop_config.json"),jC=()=>{let e=je("profile");return{command:e.command,args:[...e.args,GC]}},lo=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),VC=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},U$=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),H$=e=>{if(!lo(e)||!VC(e,["command","args"]))return!1;let t=jC();return e.command===t.command&&U$(e.args,t.args)},W$=e=>lo(e)&&Array.isArray(e.args)&&e.args.at(-1)===GC,K$=e=>{if(!lo(e)||!VC(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||Ge(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===er&&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!Ge(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},G$=e=>e===void 0?"absent":H$(e)?"exact":W$(e)||K$(e)?"stale-owned":"foreign",Ue=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},uo=async e=>{let t=await R(e),n;try{n=await M(e)}catch{throw new Ue(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!lo(n.mcpServers))throw new Ue(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(lo(n.mcpServers)?n.mcpServers:void 0)?.[Vl];return{path:e,fileExisted:t,json:n,entry:o,ownership:G$(o)}},Zl=e=>{if(e.ownership==="foreign")throw new Ue(`MCP name conflict in ${e.path}: mcpServers.${Vl} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},YC=(e,t)=>{let n={...e},r=lo(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[Vl]:r[Vl]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Ah=async(e,t)=>{if(kh(e.entry,t))return;let n=await uo(e.path);if(!kh(n.entry,e.entry))throw new Ue(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Bn(e.path,YC(n.json,t)),{reading:e,afterEntry:t}},Ch=async e=>{let t=await uo(e.reading.path);if(!kh(t.entry,e.afterEntry))throw new Ue(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=YC(t.json,e.reading.entry);await Bn(e.reading.path,n)},j$=async e=>{if(!ce())throw new Ue(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Oe()} is temporary); no inference setting was changed.`);let t=await uo(Yl(e));Zl(t);let n=Sh(e),r=(e.platform??kr)()==="darwin"&&n!==t.path?await uo(n):void 0;return r&&Zl(r),{active:t,...r?{legacy:r}:{}}},WC=async e=>{let t=await uo(Yl(e));Zl(t);let n=Sh(e),r=(e.platform??kr)()==="darwin"&&n!==t.path?await uo(n):void 0;return r&&Zl(r),{active:t,...r?{legacy:r}:{}}},V$=async e=>{let t=[];try{let n=await Ah(e.active,jC());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Ah(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Ch(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ue(`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 Ch(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Ue(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},Y$=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Ah(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Ch(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ue(`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)},KC=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)."]},Z$={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Xl="claude-desktop",vh="migrate",ZC=new Set(["app-running","store-missing"]),X$={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},J$={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"}},z$="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",XC=e=>{let t=(e.platform??kr)(),n=e.home??ci;return{home:n,appRunning:e.appRunning??pa(t),firstPartyRoot:()=>Vs({home:n,runtimePlatform:t}),thirdPartyRoot:()=>ro({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},JC=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=X$[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.`:"")},zC=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=J$[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.`:"")},ii=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=XC(e),r=await(e.pendingDesktopMigrationCount??$C)(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??co)(n);if(a.ok){let c=JC(a.lanes),l=zC(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 Cs(Xl,vh);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(!ZC.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 Cs(Xl,vh);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."]}},q$=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await lr(Xl),[]}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."]}},Q$=e=>MC({id:Xl,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??kr)(),n=(e.home??ci)();return t==="darwin"?["/Applications/Claude.app",kn(n,"Applications","Claude.app")]:t==="win32"?[kn(process.env.LOCALAPPDATA??kn(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:",...KC(t)]:["Claude desktop org/API lane:",...KC(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`."]}),eM=(e={})=>{let t=Q$(e),n=()=>(e.platform??kr)()==="darwin",r=()=>(e.platform??kr)()==="win32",o=(s,i)=>n()?TA(s,i,e):lC(s,s.clientKey??"",i,e),a=s=>n()?PA(s,e):dC(s,e);return{...t,automatic:!0,quitGated:{isRunning:()=>(e.appRunning??pa((e.platform??kr)()))(),quitTarget:Z$,needsTarget:()=>!1,async complete(s){if(s!==vh)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??co)(XC(e));if(i.ok){let c=JC(i.lanes),l=zC(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 ZC.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?DA(s,e):r()?fC(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=tn(e),p=await ao(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[Yf(p),...await ii(e,i)]}}if(r()){let f;try{f=await br(e.runReg??Hn)}catch{return{status:"manual",manualAudience:"admin",messages:[z$,...await ii(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[dh(f),...await ii(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 ha(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await j$(e)}catch(f){let p=f instanceof Ue?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Ue?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 ii(e,i)]}}let d;try{d=await V$(c)}catch(f){let p=f instanceof Ue?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Ue?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 ii(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?B$:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=Yl(e),c=await q$(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 WC(e)}catch(m){return l({status:"manual",messages:[m instanceof Ue?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()?Ut(e):void 0;if(!(m!==void 0&&f.changedFiles?.includes(m)===!0&&!await R(m)))return l(f)}let p;try{p=await Y$(await WC(e))}catch(m){let w=m instanceof Ue?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof Ue?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await re(i);let h=Sh(e);return n()&&h!==i&&await re(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(!ce())return{registered:!1,command:null};try{let s=await uo(Yl(e));return s.ownership!=="exact"||!lo(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 ha(e)).supported?Xf(s,e):!1:r()?pC(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await ha(e)).supported)return["unknown"];let s=await LA(e);return s?[s]:["unknown"]}if(r())return await R(Ut(e))?await br(e.runReg??Hn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=tn(e);return!await R(s.journal)||await ao(s,e)?!1:(await ha(e)).supported}return r()&&await R(Ut(e))?!await br(e.runReg??Hn):!1}catch{return!1}}}},qC=eM();import{homedir as RM}from"node:os";import{join as OM}from"node:path";import{rm as od}from"node:fs/promises";import{constants as QC,accessSync as tM,statSync as nM}from"node:fs";import{platform as Eh}from"node:os";import{delimiter as rM,posix as oM,resolve as aM,win32 as sM}from"node:path";var iM="0.59.0",cM="1.1.4",Wn="Anyray \xB7 Claude",Kn="Anyray \xB7 Codex",Jl="__anyray-acp-agent",ev=(e,t,n)=>{let{command:r,args:o}=dn([Jl,e,t,n]);return{command:r,args:o,env:{}}},zl=(e=Eh())=>e==="win32"?"npx.cmd":"npx",ql=(e=process.env.PATH,t=Eh())=>{if(!e)return;let n=zl(t);for(let r of e.split(rM)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=aM(o,n);try{if(!nM(a).isFile())continue;return tM(a,t==="win32"?QC.F_OK:QC.X_OK),a}catch{}}},Ql=(e,t=Eh())=>{let n=t==="win32"?sM:oM;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==zl(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},lM="https://chatgpt.com/backend-api/codex",dM="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",tv="ANYRAY_ACP_CODEX_AUTHORIZATION",nv="ANYRAY_ACP_CODEX_CLIENT_KEY",rv="ANYRAY_ACP_CODEX_METADATA",ov=e=>le({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),uM=(e,t={})=>{let n=J(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":lM,"x-anyray-forward-headers":dM}:{},o=n?{...e.clientKey?{"x-anyray-api-key":nv}:{}}:{Authorization:tv};return ov(e)&&(o["x-anyray-metadata"]=rv),{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}}}:{}}},pM=e=>{let t=J(e,"openai"),n=ov(e);return{...t?e.clientKey?{[nv]:e.clientKey}:{}:{[tv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[rv]:n}:{}}},av=(e,t=zl(),n={})=>({[Wn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${iM}`],env:un(e).env},[Kn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${cM}`],env:{CODEX_CONFIG:JSON.stringify(uM(e,n)),...pM(e)}}}),li=(e=zl(),t="jetbrains")=>({[Wn]:ev("claude",e,t),[Kn]:ev("codex",e,t)}),po=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ed=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as fM}from"node:zlib";import{open as hM,readFile as _h,readdir as rd}from"node:fs/promises";import{dirname as sv,join as de}from"node:path";import{homedir as dv,platform as Th}from"node:os";var td="2025.3.2",ma="253.30387.147",di="com.intellij.ml.llm",xh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),mM=1e4,yM=256*1024*1024,gM=16*1024*1024,Ih=1024*1024,Rh=22,wM=Rh+65535,Oh=bl,bM=()=>{let e=dv(),t=de(e,".cache","JetBrains","RemoteDev");switch(Th()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:de(e,"Applications"),layout:"app-bundles"},{path:de(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:de(process.env.LOCALAPPDATA??de(e,"AppData","Local"),"Programs"),layout:"children"},{path:de(process.env.LOCALAPPDATA??de(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:de(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:de(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},kM=()=>Th()==="linux"?de(dv(),".local","share","JetBrains"):ot("JetBrains"),AM=()=>Th()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),CM=async(e,t=mM)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await rd(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=de(r.path,i.name),l=r.layout==="app-bundles"?de(c,"Contents","Resources","product-info.json"):de(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=de(s,"product-info.json"),l=de(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 rd(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=de(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)]},vM=e=>{let t=sv(e);return t.endsWith(`${de("Contents","Resources")}`)?sv(t):t},SM=async e=>{try{let t=JSON.parse(await _h(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Gs(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:vM(e)}}catch{return}},nd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},EM=async(e,t)=>{let n;try{n=await hM(e,"r");let{size:r}=await n.stat();if(r<Rh||r>yM)return;let o=Math.min(r,wM),a=await nd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Rh;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>gM||c+i>r)return;let l=await nd(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>Ih||p>Ih)return;let v=await nd(n,30,g);if(!v||v.readUInt32LE(0)!==67324752)return;let S=v.readUInt16LE(26),E=v.readUInt16LE(28),x=await nd(n,f,g+30+S+E);return x?u===0?x.toString("utf8"):u===8?fM(x,{maxOutputLength:Ih}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},iv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Gs(n)))return{id:t,version:n}},xM=async(e,t)=>{let n=de(e,"META-INF","plugin.xml");if(await R(n))try{let o=iv(await _h(n,"utf8"));return{present:o?.id===di||t,descriptor:o?.id===di?o:void 0}}catch{return{present:t}}let r=[];try{r=(await rd(de(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=>de(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await EM(o,"META-INF/plugin.xml"),s=a?iv(a):void 0;if(s?.id===di)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},cv=async e=>{let t;try{t=await rd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=xh.has(o.name.toLowerCase()),i=xh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=xh.has(o.name.toLowerCase());if(!a){let i=de(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await xM(de(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},IM=async e=>{try{return(await _h(de(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(di)}catch{return!1}},lv=e=>e.reduce((t,n)=>t?(Oh(n,t)??-1)>0?n:t:n,void 0),uv=async(e={})=>{let t=e.configRoot??ot("JetBrains"),n=e.userPluginsRoot??kM(),r=await CM(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):bM(),e.scanBudget),o=(await Promise.all(r.map(h=>SM(h)))).filter(h=>h!==void 0),a=o.length>0||await R(t);if(e.wsl??AM())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=>(Oh(h.version,td)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let h of s){let m=de(t,h.dataDirectoryName);if(!await R(m)){d=!0;continue}let w=[de(m,"plugins"),de(n,h.dataDirectoryName),de(n,h.dataDirectoryName,"plugins")],g;for(let y of[...new Set(w)]){let b=await cv(y);if(b.present){g=b;break}}if(g??=await cv(de(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==di)){if(i.push(g.descriptor.version),await IM(m)){c=!0;continue}if(!((Oh(g.descriptor.version,ma)??-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 ${td}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${td}+ once, enable AI Assistant ${ma}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${ma}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${ma}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${ma}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${ma}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${td}+ 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 _M=[Wn,Kn],Ph=()=>OM(RM(),".jetbrains","acp.json"),fo=()=>`${Ph()}.anyray-state`,TM=(e,t,n="npx")=>{let r=po(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,li(n,"jetbrains")),{...e,agent_servers:r}},PM=(e,t,n)=>{if(!po(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=po(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of _M)if(c in r){if(!ed(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}},LM=(e=uv)=>({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=Ph(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=ql();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 M(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=li(a,"jetbrains");return await Xi({configPath:r,current:c,next:TM(c,t,a),journalPath:fo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,fo()]}},async revert(t){let n=Ph(),r=async()=>{if(!await R(n))return t.dryRun||(await re(n),await od(fo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await re(n),await od(fo(),{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 M(fo());(u.version===1||u.version===2)&&po(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 M(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 Dr(n);let l=PM(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 od(n,{force:!0}):await Z(n,l.next,{backup:!1})),t.dryRun||(await re(n),await od(fo(),{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():Zi(n,fo(),r)}}),pv=LM();import{homedir as sd}from"node:os";import{join as id}from"node:path";import{rm as Lh}from"node:fs/promises";var Dh="1.0.0",cd=["anyray-claude-acp","anyray-codex-acp"],DM=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Nh=()=>id(sd(),".windsurf","acp","registry.json"),$h=()=>id(sd(),".windsurf-next","acp","registry.json"),ya=e=>`${e}.anyray-state`,fv=e=>({binary:Object.fromEntries(DM.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),mv=(e="npx")=>{let t=li(e,"windsurf");return[{id:cd[0],name:Wn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:fv(t[Wn])},{id:cd[1],name:Kn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:fv(t[Kn])}]},ad=e=>!Array.isArray(e)||e.some(t=>!po(t)||typeof t.id!="string")?null:e,NM=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Dh||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:ad(e.agents);if(!n)return null;let r=new Set(cd);return{...e,version:typeof e.version=="string"?e.version:Dh,agents:[...n.filter(o=>!r.has(o.id)),...mv(t)],extensions:e.extensions??[]}},$M=(e,t,n)=>{let r=ad(e.agents);if(!r)return null;let o=ad(t.agents)??[],a=new Map((ad(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!cd.includes(u.id)){l.push(u);continue}if(!ed(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===Dh&&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}},hv=async()=>{let e=[];return(await R($h())||await R(id(sd(),".windsurf-next")))&&e.push($h()),(await R(Nh())||await R(id(sd(),".windsurf"))||await R(ot("Devin"))||await R(ot("Windsurf")))&&e.push(Nh()),e},yv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await hv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await hv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=ql();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 M(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=NM(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=mv(r);await Xi({configPath:s,current:i,next:c,journalPath:ya(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,ya(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=[Nh(),$h()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await re(a),await Lh(ya(a),{force:!0}).catch(()=>{}));return}let i;try{i=await M(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 M(ya(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 M(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 Dr(a);let f=$M(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 Lh(a,{force:!0}):await Z(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 re(a),await Lh(ya(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await Zi(a,ya(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var oe=[nr,vw,Is,uk,Dk,Yk,rA,pv,qC,yv,Pw],Ht=e=>oe.find(t=>t.id===e);var MM=["hook_registration","mcp_registration","hook_binary","beacon_target"],ho=e=>e.status==="configured"||e.status==="queued",mo=async(e,t=oe)=>{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},Ar=async(e,t,n=oe)=>{let r=[];for(let o of await mo(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},Mh=async(e,t=oe)=>{let n=[];for(let r of await mo(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(MM.map(o=>[o,"unreadable"]))})}return n},gv=e=>e.filter(t=>!t.integrationStatus),FM=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=FM(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 VM,writeFile as YM}from"node:fs/promises";import{join as Sv}from"node:path";import{z as He}from"zod";var BM=["HTTPS_PROXY","https_proxy"],wv=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"]),bv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),kv=new Set(["ENOTFOUND","EAI_AGAIN"]),Av=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Cv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),UM=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 HM(e)},HM=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...wv,...bv,...kv,...Av,...Cv])if(t.includes(n))return n}},WM=e=>e?.name==="AbortError"||e?.name==="TimeoutError",KM=e=>BM.filter(t=>(e[t]??"").trim()!==""),GM=(e,t=process.env)=>{let n=UM(e),r=KM(t);return{kind:n&&wv.has(n)?"tls-unknown-issuer":n&&bv.has(n)?"tls-invalid-cert":n&&kv.has(n)?"dns":WM(e)||n&&Cv.has(n)?"timeout":n&&Av.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},jM=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)=>jM(GM(e,t));var ga="required",vv=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team;return{routingUpdated:n,teamUpdated:r,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{}}},ld=(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]??ga,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 ZM=1e4,XM=1,JM=He.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),zM=He.object({id:JM,name:He.string().min(1),version:He.string().min(1),body:He.string()}),qM=He.object({version:He.literal(XM).optional(),skills:He.array(zM),updatedAt:He.string().min(1).optional(),routing:He.object({origin:He.string().min(1)}).optional(),team:He.string().min(1).optional(),tools:He.object({enabled:He.array(He.string().min(1)),tiers:He.record(He.string().min(1),He.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),QM=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",dd=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",ud=async(e,t,n={})=>{let r=n.timeoutMs??ZM,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=dd(l),d}return qM.parse(c)},Ev=/^[a-z0-9][a-z0-9-]{0,31}$/,xv=64,eF=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>Ev.test(o)).slice(0,xv).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>Ev.test(o)).slice(0,xv).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},ui=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??ga)==="locked":!1},pd=async(e,t={})=>{let n=t.loadProfile??P,r=t.saveProfile??te,o=t.targetFromProfile??_e,a=t.adapters??oe,s=t.repairTools??gt,i=t.recordManaged??Xn,c=await n(),l={...c},d=vv(c,{routingOrigin:e.routing?.origin?ln(e.routing.origin):void 0,team:e.team}),{routingUpdated:u,teamUpdated:f}=d;(u||f)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),await r(l));let p=ld(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f),{candidateIds:h,freshIds:m}=p,w=0,g=0,y=0;if(h.length>0||m.length>0){let S=await o(async()=>l);if(S){let E;if(u||f){let I=new Set(h);E=[];for(let T of a)if(I.has(T.id))try{(await T.detect()).installed&&E.push(T)}catch{}}else E=await Ar(h,S.toolOrigin,a);let x=new Set(m),A=[];for(let I of a)if(x.has(I.id))try{(await I.detect()).installed&&A.push(I)}catch{}if(w=E.length+A.length,w>0){let I=await s([...E,...A],S.target);g=I.filter(ho).length;let T=I.filter(B=>x.has(B.id));if(y=T.filter(ho).length,T.length>0)try{await i(T,!1)}catch{}}}}let b=eF(e),v=await n();if(JSON.stringify(b??null)!==JSON.stringify(v.fleetToolPolicy??null)){let{fleetToolPolicy:S,...E}=v;await r({...E,...b?{fleetToolPolicy:b}:{}})}return{routingUpdated:u,teamUpdated:f,toolsRequested:w,toolsApplied:g,toolsEnrolled:y,toolsTombstoned:p.tombstonedIds,profileUpdated:u||f}},Iv=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!QM(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=Sv(d,i.id),f=Sv(u,"SKILL.md");await VM(u,{recursive:!0}),await YM(f,tF(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}},tF=e=>e.endsWith(`
286
+ }`,Hn=async e=>new Promise((t,n)=>{let r=bN("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",TN],{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(nh(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(nh({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={})=>da((e.home??sh)(),".anyray","claude-desktop-windows.json"),PN=e=>da((e.home??sh)(),".anyray","claude-desktop-windows.lock"),ia=class extends Error{},LN=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},lh=async e=>{let t=PN(e);await Qf(si(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=tC("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=da(t,"owner.json");try{await Qf(t,{mode:448}),await me(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
287
+ `)}catch(a){if(a.code!=="EEXIST")throw await rn(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await eh(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!LN(i.pid)}catch{try{s=Date.now()-(await sC(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new ia;await rn(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await eh(o,"utf8")).nonce===r&&await rn(t,{recursive:!0,force:!0})}catch{}}}throw new ia},pC=()=>Object.fromEntries($e.map(e=>[e,{present:!1}])),oo=e=>tC("sha256").update(e).digest("hex"),DN=(e,t)=>t.present?e===ua?{present:!0,type:t.type,sha256:oo(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},aa=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?oo(e.value??"")===t.sha256:e.value===t.value:!0,Ut=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Bl=(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===ua?Ut(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Ut(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},jA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Ut(e,$e)&&$e.every(t=>Bl(e[t],t)),VA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Ut(e,UA)&&UA.every(t=>Bl(e[t],t)),NN=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),dh=(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 Ut(n,r)&&n.path===ih(t)&&(n.lastWritten===void 0||GA(n.lastWritten))&&(n.pending===void 0||GA(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},$N=(e,t)=>Ut(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Fl&&e.registryKey===Le&&typeof e.keyExisted=="boolean"&&jA(e.lastWritten)&&(e.pending===void 0||jA(e.pending))&&dh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),MN=e=>Ut(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Le&&typeof e.keyExisted=="boolean"&&VA(e.lastWritten)&&(e.pending===void 0||VA(e.pending)),YA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Ut(e,HA)&&HA.every(t=>Bl(e[t],t)),FN=(e,t)=>Ut(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===Le&&typeof e.keyExisted=="boolean"&&YA(e.lastWritten)&&(e.pending===void 0||YA(e.pending))&&dh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),ZA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Ut(e,WA)&&WA.every(t=>Bl(e[t],t)),BN=(e,t)=>Ut(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===Le&&typeof e.keyExisted=="boolean"&&ZA(e.lastWritten)&&(e.pending===void 0||ZA(e.pending))&&dh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),XA=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),uh=e=>{let{pending:t,...n}=e;return{...n,version:Fl,lastWritten:XA(e.lastWritten),...t?{pending:XA(t)}:{}}},JA=e=>({...e,chatTabEnabled:{present:!1}}),UN=e=>{let{pending:t,...n}=e;return uh({...n,version:4,lastWritten:JA(e.lastWritten),...t?{pending:JA(t)}:{}})},zA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),HN=(e,t)=>uh({version:4,registryKey:Le,keyExisted:e.keyExisted,lastWritten:zA(e.lastWritten),...e.pending?{pending:zA(e.pending)}:{},helper:{path:ih(t)}}),ph=async(e,t=!0)=>{let n=Ht(e),r=si(n),o=`${iC(n)}.anyray-old-`,a=(await oC(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>da(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 aC(a[0],n):s=a[0]}let i=await M(s),c=MN(i)?HN(i,e):FN(i,e)?UN(i):BN(i,e)?uh(i):$N(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>rn(l,{force:!0}))),c},qA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),WN=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Le,keyExisted:e.keyExisted,lastWritten:qA(e.lastWritten),...e.pending?{pending:qA(e.pending)}:{}}:e,Nl=async(e,t)=>{let n=Ht(t),r=`${JSON.stringify(WN(e),null,2)}
288
+ `;t.writeJournalFile?await t.writeJournalFile(n,r):await me(n,r)},KN=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,GN=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),jN=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),VN=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),YN=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===VN(t).toUpperCase(),QA=(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},ZN=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,XN=(e,t)=>{if(!Ol(e,!0))return!1;let n=ZN(t);if(jN.has(n))return!1;if(GN.has(n))return n==="REG_EXPAND_SZ"?!0:!yA(e,!0)},JN=(e,t)=>{let n=pC(),r=!1,o=!1,a=!1,s=t.toUpperCase()===ai.toUpperCase(),i=(l,d)=>{if(!s)return;let u=XN(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),QA(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||YN(d,t))continue;let u=KN.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),QA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Un=async(e,t=Le)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:pC(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return JN(n.stdout,t)},br=async e=>{let t=await Un(e,ai);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...$e.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},fh=e=>e.unparsed?`This machine may have a Claude policy under ${ai} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${ai} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${ai} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Ul=(e,t)=>ta(no(e,t)),fC=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],zN=(e,t)=>{let n=Ul(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}]}))},qN=(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}}),QN=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,rh=e=>Object.fromEntries($e.map(t=>[t,DN(t,e[t])])),eC=(e,t,n,r)=>({version:Fl,registryKey:Le,keyExisted:e,lastWritten:rh(t),helper:{path:n,lastWritten:th(r)}}),e$=(e,t,n,r,o,a)=>({version:Fl,registryKey:Le,keyExisted:e,lastWritten:rh(t),pending:rh(n),helper:{path:r,...o?{lastWritten:th(o)}:{},pending:th(a)}}),oh=(e,t,n)=>aa(n,e.lastWritten[t])||e.pending!==void 0&&aa(n,e.pending[t]),ca=async e=>{try{let t=await eh(e,"utf8");return{content:t,sha256:oo(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},la=async e=>(await ca(e))?.sha256,sa=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Ml=async(e,t)=>{let n=ON(e),r;try{r=await oC(si(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>da(si(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([ca(e),ca(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!sa(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await uC(e,a))throw new Error("credential helper changed during recovery");return}if(t&&sa(t,s.sha256)&&sa(t,i.sha256)){await rn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},hh=async(e,t,n)=>(n.present?await e(fC(Le,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Le,"/v",t,"/f"])).code===0,t$=async(e,t,n)=>{let r=!0,o=await Un(e);for(let a of $e)if(!oa(o.values[a],t[a])){if(!oa(o.values[a],n[a])){r=!1;continue}await hh(e,a,t[a])||(r=!1),o=await Un(e)}return r&&$e.every(a=>oa(o.values[a],t[a]))},Xe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Ht(n)]}}),hC=async(e,t,n,r={})=>{if(!Re(t))return Xe("A valid personal ark_ gateway key is required.",!1,r);let o=ih(r),a;try{a=SN((r.credentialCommand??jf)())}catch{return Xe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=oo(a),i=r.runReg??Hn,c=Ht(r),l;if(!n.dryRun)try{l=await lh(r)}catch(m){return Xe(m instanceof ia?"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 br(i);if(m)return Xe(fh(m),!1,r);let w=await ph(r,!n.dryRun);n.dryRun||await Ml(o,w);let g=await Un(i),y=zN(e,o),b=await ca(o),v=b?.sha256,S=!1;if(d=w,u=g,f=y,w){let A=$e.find(I=>!oh(w,I,g.values[I]));if(A)return Xe(`Claude's ${A} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(v!==void 0&&!sa(w,v))return Xe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);S=QN(w)}else{if(v!==void 0&&v!==s)return Xe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let A=g.foreignState||$e.some(B=>g.values[B].present),I=$e.every(B=>oa(g.values[B],y[B])),T=$e.every(B=>oa(g.values[B],qN(e,t.trim())[B]));if(A&&!I&&!T)return Xe(`Existing Claude third-party-inference policy values under ${Le} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(S=T,I&&v===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Le} into an owner-only journal without rewriting them.`]}:(await Nl(eC(g.keyPresent,y,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Le} into the ownership journal.`]})}if(S){let A=!0;try{A=(r.appRunning??ch)()}catch{}if(A)return Xe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=e$(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 ${Le}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Nl(E,r),h=!0;for(let A of $e){let I=await Un(i);if(!aa(I.values[A],E.lastWritten[A])&&!aa(I.values[A],E.pending[A]))throw new Error("registry value changed during apply");if(!oa(I.values[A],y[A])&&!await hh(i,A,y[A]))throw new Error("registry write failed")}let x=await Un(i);if(!$e.every(A=>aa(x.values[A],E.pending[A])))throw new Error("registry verification failed");if(v!==s&&(v===void 0?await RN(o,a):await $l(o,v,a,"apply",r)),await la(o)!==s)throw new Error("credential helper verification failed");return await Nl(eC(E.keyExisted,y,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Le}.`,`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.",...xl]}}catch{if(!h||!u||!f||!p)return Xe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Ml(o,p);let m=!0,w=await ca(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await $l(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await la(o)===p.helper.lastWritten.sha256):await $l(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await t$(i,u.values,f))return d?await Nl(d,r):await rn(c,{force:!0}),Xe("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return Xe("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?.()}},mC=async(e,t={})=>{let n=t.runReg??Hn,r=Ht(t),o;if(!e.dryRun)try{o=await lh(t)}catch(a){return Xe(a instanceof ia?"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 ph(t,!e.dryRun);a&&!e.dryRun&&await Ml(a.helper.path,a);let s=await Un(n);if(!a)return $e.filter(h=>s.values[h].present).length>0?Xe(`Claude policy values exist under ${Le}, 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&&!oh(a,p,s.values[p])),c=await la(a.helper.path),l=c!==void 0&&!sa(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Le}.`,`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 Un(n)).values[p];if(m.present){if(!oh(a,p,m)){u.add(p);continue}await hh(n,p,{present:!1})||(d=!0)}}let f=await la(a.helper.path);if(f!==void 0)if(sa(a,f))try{await $l(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?Xe(`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 rn(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Le}.`,"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?[]:Il]})}catch{return Xe(`Could not safely inspect or revert ${Le}; no unproven value was removed.`,!1,t)}finally{await o?.()}},yC=async(e,t={})=>{let n=t.runReg??Hn;if(!await R(Ht(t)))return;let r;try{r=await lh(t);let o=await ph(t);if(o&&await Ml(o.helper.path,o),!o||o.pending||await br(n)!==void 0)return;let a=await Un(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===je(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&$e.every(l=>aa(a.values[l],o.lastWritten[l]))))return;let i=await la(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 IN(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?.()}},gC=async(e,t={})=>await yC(e,t)!==void 0,wC=async(e,t={})=>await yC(e,t)==="dynamic";var pa=(e=r$())=>e==="win32"?ch:Pl,mh="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Wl=async(e,t={})=>{let n=(t.profileRoot??to)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:mh};if((t.appRunning??pa(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await bC.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 El(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 "+mh}:{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??lA)();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=Hl(t.stagingRoot??o$(),`anyray-history-${process.pid}-${n$()}`);try{let s=await(t.runImporter??dA)({binary:o,exportPath:e,configDir:Hl(a,"config"),workDir:Hl(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. "+mh};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 pA(r.dir,s.conversations),c=await fA({stagedProjectsDir:Hl(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 bC.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as xt}from"node:fs";import{homedir as x$}from"node:os";import{join as an,sep as I$}from"node:path";import{isDeepStrictEqual as Vl}from"node:util";import{constants as a$}from"node:fs";import{promises as G}from"node:fs";import{dirname as fa,isAbsolute as gh,join as Q,relative as Kl,resolve as on,sep as ii}from"node:path";import{randomUUID as Yl}from"node:crypto";var bn=448,ci=384,vC=448,s$=4,wh=3e4,SC=5e3,i$=10*6e4,yh=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),it=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),li=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),EC=(e,t)=>{let n=Kl(on(e),on(t));return n===""||!n.startsWith(`..${ii}`)&&n!==".."&&!gh(n)},ao=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return it(n)?{raw:t,value:n}:void 0}catch(t){return Et(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},Et=e=>e instanceof Error&&"code"in e,c$=e=>{try{return process.kill(e,0),!0}catch(t){return Et(t)&&t.code==="EPERM"}},xC=e=>e===0?"owner.json":`owner.${e}.json`,Gl=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=Q(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));it(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}},IC=e=>{if(e.pid===void 0||!c$(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>wh&&t-e.createdAtMs>i$},l$=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(fa(t),{recursive:!0,mode:bn});let n=Yl(),r,o=!1;try{await G.mkdir(t,{mode:bn}),o=!0}catch(i){if(!Et(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Gl(t);if(d){if(!IC(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)<=wh)return}let l=Q(t,xC(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
289
+ `,{flag:"wx",mode:ci}),r=l}catch(d){if(Et(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(!it(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},SC);return s.unref(),async()=>{clearInterval(s);try{(await Gl(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},d$=async(e,t,n)=>{await G.mkdir(fa(e),{recursive:!0,mode:bn});let r=await l$(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!Et(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${Yl()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
290
+ `,{mode:ci,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},Zl=async(e,t)=>{for(let n=0;n<s$;n+=1){let r=await ao(e);if(!r)return"failed";let o=t(r.value);if(!o||Vl(o,r.value))return"unchanged";try{if(await d$(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},kC=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},Xl=async e=>{let t=[];for(let n of await kC(e))for(let r of await kC(Q(e,n)))t.push(Q(e,n,r));return t},u$=e=>Array.isArray(e.skills)?e.skills.filter(t=>it(t)&&li(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],p$=async e=>{let t=Q(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await Xl(t)){let o=await ao(Q(r,"manifest.json"));if(!o)continue;let a=r.split(ii).at(-1)??"";for(let s of u$(o.value))n.push({account:a,packageDir:r,entry:s})}return n},f$=async e=>{let t=await ao(Q(e,".claude-plugin","plugin.json"));return!!t&&li(t.value.name)},h$=(e,t)=>{let n=gh(t)?on(t):on(e,t);if(!EC(e,n)||n===on(e))return;let r=Kl(on(e),n);return r.length>0?{absolute:n,relative:r}:void 0},m$=async e=>{let t=await Xl(Q(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(ii).includes("skills-plugin"))continue;let o=Q(r,"cowork_plugins"),a=await ao(Q(o,"installed_plugins.json"));if(!a||!it(a.value.plugins))continue;let s=r.split(ii).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!li(i)||!Array.isArray(c)))for(let l of c){if(!it(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=h$(o,l.installPath);!d||!await f$(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:Q(r,"cowork_account_settings.json")})}}return n},y$=async e=>{let t=await ao(Q(e,"claude_desktop_config.json"));return!t||!it(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>li(n)&&n.toLowerCase()!=="anyray"&&it(r)))},RC=async e=>{let[t,n,r]=await Promise.all([p$(e),m$(e),y$(e)]);return{skills:t,plugins:n,localMcpServers:r}},bh=async e=>{let t=await RC(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)}},AC=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(!li(o.name))return!1;let a=Q(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)},g$=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=Q(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,bn);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?vC:ci)}}};await t(e),await G.chmod(e,bn)},OC=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},jl=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(!Vl(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 jl(Q(e,s),Q(t,s)))return!1}else if(!i.isFile()||!await OC(Q(e,s),Q(t,s)))return!1}return!0}catch{return!1}},_C=e=>`${e}.anyray-incomplete`,TC=async(e,t)=>{let n=!1;if(t){await G.mkdir(fa(e),{recursive:!0,mode:bn});try{await G.mkdir(e,{mode:bn}),n=!0}catch(l){if(!Et(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=Yl(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await Gl(e)}catch{return}if(f){if(!IC(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)<=wh)return}let u=Q(e,xC(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
291
+ `,{flag:"wx",mode:ci}),o=u}catch(f){if(Et(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(!it(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},SC);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Gl(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},PC=async e=>{let t=await TC(e,!1);t&&await t.complete()},w$=async(e,t,n)=>{let r=_C(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await jl(e,t))return await PC(r),"present"}catch(c){if(!Et(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 TC(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:bn})}catch(c){if(!Et(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=Q(c,u.name),p=Q(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(p,{mode:bn})}catch(m){if(!Et(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,a$.COPYFILE_EXCL);let h=await G.stat(f);await G.chmod(p,(h.mode&73)!==0?vC:ci)}catch(h){if(!Et(h)||h.code!=="EEXIST")throw h;if(!await OC(f,p))return"conflict"}else return"failed"}catch(h){return Et(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 jl(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},LC=async(e,t,n,r)=>{if(!await AC(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await jl(e,t))return await PC(_C(t)),"present"}catch(a){if(!Et(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(fa(t),{recursive:!0,mode:bn});let o=Q(fa(t),`.anyray-stage-${Yl()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await AC(o)?(await g$(o),await n?.(t),await w$(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},CC=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),b$=async e=>{let t=await Xl(Q(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await ao(Q(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},k$=async e=>{let t=await Xl(Q(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(ii).includes("skills-plugin"))try{await G.access(Q(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},A$=async(e,t,n,r,o)=>{let a=Q(t,"manifest.json");for(let s of e){let i=Q(s.packageDir,"skills",s.entry.name);try{await G.access(Q(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=Q(t,"skills",s.entry.name),l=await LC(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 Zl(a,f=>{let p=Array.isArray(f.skills)?f.skills:[];if(p.find(m=>it(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}},DC=(e,t)=>({...e,installPath:t}),C$=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=gh(r.installPath)?on(r.installPath):on(o,r.installPath),s=DC(e,Kl(on(t),on(n))),i={...r,installPath:Kl(on(o),a)};return Vl(s,i)},v$=async(e,t,n)=>{let r=await ao(e);if(!r||!it(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":Zl(t,a=>{let s=it(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},S$=async(e,t,n,r,o)=>{let a=Q(t,"cowork_plugins"),s=Q(a,"installed_plugins.json"),i=Q(t,"cowork_account_settings.json");for(let c of e){let l=Q(a,c.relativeInstallPath);if(!EC(a,l)){n.invalid+=1;continue}let d=await LC(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 Zl(s,h=>{let m=it(h.plugins)?h.plugins:{},w=m[c.id],g=Array.isArray(w)?w:[],y=g.find(v=>it(v)&&v.scope==="user");if(y){u=C$(c.entry,fa(c.settingsFile),c.packageDir,y,t),f=!u;return}let b=DC(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 v$(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},E$=async(e,t,n)=>{let r=Q(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await Zl(r,c=>{let l=it(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=Vl(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}},NC=async(e,t,n={})=>{let r=await RC(e),o=yh("skill"),a=yh("plugin"),s=yh("local-mcp"),i=[],c=[],l=CC(r.skills,n.account,n.allAccounts),d=CC(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 b$(t);f.state==="found"?await A$(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 k$(t);f.state==="found"?await S$(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await E$(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 R$=async e=>{try{return await xt.access(e),!0}catch{return!1}},$C=448,O$=384,FC={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},_$=["code","cowork"],Ch=(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.",kh=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),BC=async e=>{let t;try{t=(await xt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&Qo(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await xt.readdir(an(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&Qo(a.name)).map(a=>a.name);for(let a of o)n.push(an(e,r,a))}catch{}return n},T$=async e=>{try{return(await xt.readdir(e)).filter(t=>t.startsWith(Fn)&&t.endsWith(".json")).map(t=>t.slice(Fn.length,-5)).filter(Qo)}catch{return[]}},P$=async(e,t)=>{let n=await BC(an(e,FC[t])),r=[];for(let o of n){let a=await T$(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(I$).slice(-2)[0]})}return r},L$=async(e,t)=>{if(t==="cowork"){let r=await El(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await BC(an(e,FC.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},D$=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await xt.copyFile(e,n),await xt.chmod(n,O$),await xt.rename(n,t)},N$=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||!Qo(o)?!1:(await xt.access(an(t,".claude","projects",Bf(r),`${o}.jsonl`)),!0)}catch{return!1}},$$=async(e,t,n,r)=>{let o=kh(e),a=await Uf(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=`${Fn}${s}.json`,c=an(t.dir,i);try{if(e==="code"){if(!await N$(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=an(t.dir,`${Fn}${s}`),d=an(n,`${Fn}${s}`),u=await xt.readdir(l);await xt.mkdir(d,{mode:$C});for(let f of u)await xt.cp(an(l,f),an(d,f),{recursive:!0,force:!1,errorOnExist:!0});await xt.chmod(d,$C)}await D$(c,an(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},MC=(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
+ `)}},Ah=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),UC=async e=>{let t=[];for(let n of _$)t.push({lane:n,sources:await P$(e,n)});return t},HC=async(e={})=>{let t=(e.firstPartyRoot??(()=>Xs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([UC(t),bh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Ah(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}},so=async(e={})=>{let t=(e.home??x$)(),n=(e.firstPartyRoot??(()=>Xs()))(),r=(e.thirdPartyRoot??(()=>to()))();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??pa())())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([UC(n),bh(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=Ah(o);for(let w of h)m.add(w);if(m.size>1)return MC(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=Ah(o);for(let h of a.accounts)p.add(h);if(p.size>1)return MC(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 R$(r),l=await NC(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(kh(p));continue}let m=await L$(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(kh(p));continue}d.push(await $$(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:Ch(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 F$=e=>[tt(e)],WC=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...F$(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 KC="1.21459.0",W$=H$(B$),K$=async e=>{try{let{stdout:t}=await W$("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},G$=async e=>{try{return await U$(e)}catch{return}},GC="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",j$=["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."],ha=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(jC??=VC({}),jC):VC(e),jC,VC=async e=>{let t=(e.home??ui)(),n=["/Applications/Claude.app",kn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??K$,o=e.readClaudeAppBundle??G$;for(let a of n){let s=await r(kn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${GC}`}),c=vl(s,KC);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${KC} or newer.`);let l=await o(kn(a,"Contents","Resources","app.asar"));return l?RA.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. ${GC}`}},Jl="anyray",XC="--anyray-owner=claude-desktop-v1",zl=(e={})=>{let t=(e.platform??kr)(),n=(e.home??ui)();return t==="darwin"?nn(e).appConfig:t==="win32"?kn(process.env.APPDATA??kn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):kn(n,".config","Claude","claude_desktop_config.json")},Ih=(e={})=>kn((e.home??ui)(),"Library","Application Support","Claude","claude_desktop_config.json"),JC=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,XC]}},io=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zC=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},V$=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),Y$=e=>{if(!io(e)||!zC(e,["command","args"]))return!1;let t=JC();return e.command===t.command&&V$(e.args,t.args)},Z$=e=>io(e)&&Array.isArray(e.args)&&e.args.at(-1)===XC,X$=e=>{if(!io(e)||!zC(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||Ke(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===er&&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!Ke(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},J$=e=>e===void 0?"absent":Y$(e)?"exact":Z$(e)||X$(e)?"stale-owned":"foreign",Ue=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},co=async e=>{let t=await R(e),n;try{n=await M(e)}catch{throw new Ue(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!io(n.mcpServers))throw new Ue(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(io(n.mcpServers)?n.mcpServers:void 0)?.[Jl];return{path:e,fileExisted:t,json:n,entry:o,ownership:J$(o)}},ql=e=>{if(e.ownership==="foreign")throw new Ue(`MCP name conflict in ${e.path}: mcpServers.${Jl} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},qC=(e,t)=>{let n={...e},r=io(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[Jl]:r[Jl]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Sh=async(e,t)=>{if(vh(e.entry,t))return;let n=await co(e.path);if(!vh(n.entry,e.entry))throw new Ue(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Bn(e.path,qC(n.json,t)),{reading:e,afterEntry:t}},Eh=async e=>{let t=await co(e.reading.path);if(!vh(t.entry,e.afterEntry))throw new Ue(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=qC(t.json,e.reading.entry);await Bn(e.reading.path,n)},z$=async e=>{if(!se())throw new Ue(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${_e()} is temporary); no inference setting was changed.`);let t=await co(zl(e));ql(t);let n=Ih(e),r=(e.platform??kr)()==="darwin"&&n!==t.path?await co(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},YC=async e=>{let t=await co(zl(e));ql(t);let n=Ih(e),r=(e.platform??kr)()==="darwin"&&n!==t.path?await co(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},q$=async e=>{let t=[];try{let n=await Sh(e.active,JC());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Sh(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Eh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ue(`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 Eh(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Ue(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},Q$=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Sh(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Eh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ue(`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)},ZC=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)."]},eM={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Ql="claude-desktop",xh="migrate",QC=new Set(["app-running","store-missing"]),tM={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},nM={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"}},rM="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",ev=e=>{let t=(e.platform??kr)(),n=e.home??ui;return{home:n,appRunning:e.appRunning??pa(t),firstPartyRoot:()=>Xs({home:n,runtimePlatform:t}),thirdPartyRoot:()=>to({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},tv=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=tM[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.`:"")},nv=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=nM[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.`:"")},di=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=ev(e),r=await(e.pendingDesktopMigrationCount??HC)(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??so)(n);if(a.ok){let c=tv(a.lanes),l=nv(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 Es(Ql,xh);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(!QC.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 Es(Ql,xh);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."]}},oM=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await lr(Ql),[]}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."]}},aM=e=>WC({id:Ql,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??kr)(),n=(e.home??ui)();return t==="darwin"?["/Applications/Claude.app",kn(n,"Applications","Claude.app")]:t==="win32"?[kn(process.env.LOCALAPPDATA??kn(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:",...ZC(t)]:["Claude desktop org/API lane:",...ZC(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`."]}),sM=(e={})=>{let t=aM(e),n=()=>(e.platform??kr)()==="darwin",r=()=>(e.platform??kr)()==="win32",o=(s,i)=>n()?$A(s,i,e):hC(s,s.clientKey??"",i,e),a=s=>n()?MA(s,e):mC(s,e);return{...t,automatic:!0,quitGated:{isRunning:()=>(e.appRunning??pa((e.platform??kr)()))(),quitTarget:eM,needsTarget:()=>!1,async complete(s){if(s!==xh)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??so)(ev(e));if(i.ok){let c=tv(i.lanes),l=nv(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 QC.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?BA(s,e):r()?wC(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=nn(e),p=await ro(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[Jf(p),...await di(e,i)]}}if(r()){let f;try{f=await br(e.runReg??Hn)}catch{return{status:"manual",manualAudience:"admin",messages:[rM,...await di(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[fh(f),...await di(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 ha(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await z$(e)}catch(f){let p=f instanceof Ue?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Ue?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 di(e,i)]}}let d;try{d=await q$(c)}catch(f){let p=f instanceof Ue?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Ue?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 di(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?j$:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=zl(e),c=await oM(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 YC(e)}catch(m){return l({status:"manual",messages:[m instanceof Ue?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 Q$(await YC(e))}catch(m){let w=m instanceof Ue?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof Ue?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await re(i);let h=Ih(e);return n()&&h!==i&&await re(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(!se())return{registered:!1,command:null};try{let s=await co(zl(e));return s.ownership!=="exact"||!io(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 ha(e)).supported?qf(s,e):!1:r()?gC(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await ha(e)).supported)return["unknown"];let s=await FA(e);return s?[s]:["unknown"]}if(r())return await R(Ht(e))?await br(e.runReg??Hn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=nn(e);return!await R(s.journal)||await ro(s,e)?!1:(await ha(e)).supported}return r()&&await R(Ht(e))?!await br(e.runReg??Hn):!1}catch{return!1}}}},rv=sM();import{homedir as DM}from"node:os";import{join as NM}from"node:path";import{rm as cd}from"node:fs/promises";import{constants as ov,accessSync as iM,statSync as cM}from"node:fs";import{platform as Rh}from"node:os";import{delimiter as lM,posix as dM,resolve as uM,win32 as pM}from"node:path";var fM="0.59.0",hM="1.1.4",Wn="Anyray \xB7 Claude",Kn="Anyray \xB7 Codex",ed="__anyray-acp-agent",av=(e,t,n)=>{let{command:r,args:o}=dn([ed,e,t,n]);return{command:r,args:o,env:{}}},td=(e=Rh())=>e==="win32"?"npx.cmd":"npx",nd=(e=process.env.PATH,t=Rh())=>{if(!e)return;let n=td(t);for(let r of e.split(lM)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=uM(o,n);try{if(!cM(a).isFile())continue;return iM(a,t==="win32"?ov.F_OK:ov.X_OK),a}catch{}}},rd=(e,t=Rh())=>{let n=t==="win32"?pM:dM;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==td(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},mM="https://chatgpt.com/backend-api/codex",yM="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",sv="ANYRAY_ACP_CODEX_AUTHORIZATION",iv="ANYRAY_ACP_CODEX_CLIENT_KEY",cv="ANYRAY_ACP_CODEX_METADATA",lv=e=>ce({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),gM=(e,t={})=>{let n=J(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":mM,"x-anyray-forward-headers":yM}:{},o=n?{...e.clientKey?{"x-anyray-api-key":iv}:{}}:{Authorization:sv};return lv(e)&&(o["x-anyray-metadata"]=cv),{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}}}:{}}},wM=e=>{let t=J(e,"openai"),n=lv(e);return{...t?e.clientKey?{[iv]:e.clientKey}:{}:{[sv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[cv]:n}:{}}},dv=(e,t=td(),n={})=>({[Wn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${fM}`],env:un(e).env},[Kn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${hM}`],env:{CODEX_CONFIG:JSON.stringify(gM(e,n)),...wM(e)}}}),pi=(e=td(),t="jetbrains")=>({[Wn]:av("claude",e,t),[Kn]:av("codex",e,t)}),lo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),od=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as bM}from"node:zlib";import{open as kM,readFile as Lh,readdir as id}from"node:fs/promises";import{dirname as uv,join as ue}from"node:path";import{homedir as mv,platform as Dh}from"node:os";var ad="2025.3.2",ma="253.30387.147",fi="com.intellij.ml.llm",Oh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),AM=1e4,CM=256*1024*1024,vM=16*1024*1024,_h=1024*1024,Th=22,SM=Th+65535,Ph=vl,EM=()=>{let e=mv(),t=ue(e,".cache","JetBrains","RemoteDev");switch(Dh()){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"}]}},xM=()=>Dh()==="linux"?ue(mv(),".local","share","JetBrains"):tt("JetBrains"),IM=()=>Dh()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),RM=async(e,t=AM)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await id(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 id(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)]},OM=e=>{let t=uv(e);return t.endsWith(`${ue("Contents","Resources")}`)?uv(t):t},_M=async e=>{try{let t=JSON.parse(await Lh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Ys(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:OM(e)}}catch{return}},sd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},TM=async(e,t)=>{let n;try{n=await kM(e,"r");let{size:r}=await n.stat();if(r<Th||r>CM)return;let o=Math.min(r,SM),a=await sd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Th;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>vM||c+i>r)return;let l=await sd(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>_h||p>_h)return;let v=await sd(n,30,g);if(!v||v.readUInt32LE(0)!==67324752)return;let S=v.readUInt16LE(26),E=v.readUInt16LE(28),x=await sd(n,f,g+30+S+E);return x?u===0?x.toString("utf8"):u===8?bM(x,{maxOutputLength:_h}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},pv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Ys(n)))return{id:t,version:n}},PM=async(e,t)=>{let n=ue(e,"META-INF","plugin.xml");if(await R(n))try{let o=pv(await Lh(n,"utf8"));return{present:o?.id===fi||t,descriptor:o?.id===fi?o:void 0}}catch{return{present:t}}let r=[];try{r=(await id(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 TM(o,"META-INF/plugin.xml"),s=a?pv(a):void 0;if(s?.id===fi)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},fv=async e=>{let t;try{t=await id(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Oh.has(o.name.toLowerCase()),i=Oh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Oh.has(o.name.toLowerCase());if(!a){let i=ue(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await PM(ue(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},LM=async e=>{try{return(await Lh(ue(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(fi)}catch{return!1}},hv=e=>e.reduce((t,n)=>t?(Ph(n,t)??-1)>0?n:t:n,void 0),yv=async(e={})=>{let t=e.configRoot??tt("JetBrains"),n=e.userPluginsRoot??xM(),r=await RM(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):EM(),e.scanBudget),o=(await Promise.all(r.map(h=>_M(h)))).filter(h=>h!==void 0),a=o.length>0||await R(t);if(e.wsl??IM())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=>(Ph(h.version,ad)??-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 fv(y);if(b.present){g=b;break}}if(g??=await fv(ue(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==fi)){if(i.push(g.descriptor.version),await LM(m)){c=!0;continue}if(!((Ph(g.descriptor.version,ma)??-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=hv(o.map(h=>h.version)),f=hv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${ad}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${ad}+ once, enable AI Assistant ${ma}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${ma}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${ma}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${ma}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${ma}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${ad}+ 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 $M=[Wn,Kn],Nh=()=>NM(DM(),".jetbrains","acp.json"),uo=()=>`${Nh()}.anyray-state`,MM=(e,t,n="npx")=>{let r=lo(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,pi(n,"jetbrains")),{...e,agent_servers:r}},FM=(e,t,n)=>{if(!lo(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=lo(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of $M)if(c in r){if(!od(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}},BM=(e=yv)=>({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=Nh(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=nd();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 M(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=pi(a,"jetbrains");return await Qi({configPath:r,current:c,next:MM(c,t,a),journalPath:uo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,uo()]}},async revert(t){let n=Nh(),r=async()=>{if(!await R(n))return t.dryRun||(await re(n),await cd(uo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await re(n),await cd(uo(),{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 M(uo());(u.version===1||u.version===2)&&lo(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 M(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 Pr(n);let l=FM(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 cd(n,{force:!0}):await Z(n,l.next,{backup:!1})),t.dryRun||(await re(n),await cd(uo(),{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():qi(n,uo(),r)}}),gv=BM();import{homedir as dd}from"node:os";import{join as ud}from"node:path";import{rm as $h}from"node:fs/promises";var Mh="1.0.0",pd=["anyray-claude-acp","anyray-codex-acp"],UM=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Fh=()=>ud(dd(),".windsurf","acp","registry.json"),Bh=()=>ud(dd(),".windsurf-next","acp","registry.json"),ya=e=>`${e}.anyray-state`,wv=e=>({binary:Object.fromEntries(UM.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),kv=(e="npx")=>{let t=pi(e,"windsurf");return[{id:pd[0],name:Wn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:wv(t[Wn])},{id:pd[1],name:Kn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:wv(t[Kn])}]},ld=e=>!Array.isArray(e)||e.some(t=>!lo(t)||typeof t.id!="string")?null:e,HM=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Mh||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:ld(e.agents);if(!n)return null;let r=new Set(pd);return{...e,version:typeof e.version=="string"?e.version:Mh,agents:[...n.filter(o=>!r.has(o.id)),...kv(t)],extensions:e.extensions??[]}},WM=(e,t,n)=>{let r=ld(e.agents);if(!r)return null;let o=ld(t.agents)??[],a=new Map((ld(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!pd.includes(u.id)){l.push(u);continue}if(!od(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===Mh&&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}},bv=async()=>{let e=[];return(await R(Bh())||await R(ud(dd(),".windsurf-next")))&&e.push(Bh()),(await R(Fh())||await R(ud(dd(),".windsurf"))||await R(tt("Devin"))||await R(tt("Windsurf")))&&e.push(Fh()),e},Av={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await bv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await bv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=nd();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 M(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=HM(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=kv(r);await Qi({configPath:s,current:i,next:c,journalPath:ya(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,ya(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=[Fh(),Bh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await re(a),await $h(ya(a),{force:!0}).catch(()=>{}));return}let i;try{i=await M(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 M(ya(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 M(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 Pr(a);let f=WM(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 $h(a,{force:!0}):await Z(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 re(a),await $h(ya(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await qi(a,ya(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var oe=[nr,Rw,_s,yk,Bk,qk,cA,gv,rv,Av,Mw],Wt=e=>oe.find(t=>t.id===e);var KM=["hook_registration","mcp_registration","hook_binary","beacon_target"],po=e=>e.status==="configured"||e.status==="queued",fo=async(e,t=oe)=>{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},Ar=async(e,t,n=oe)=>{let r=[];for(let o of await fo(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},Uh=async(e,t=oe)=>{let n=[];for(let r of await fo(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(KM.map(o=>[o,"unreadable"]))})}return n},Cv=e=>e.filter(t=>!t.integrationStatus),GM=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},ht=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=GM(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 qM,writeFile as QM}from"node:fs/promises";import{join as Ov}from"node:path";import{z as He}from"zod";var jM=["HTTPS_PROXY","https_proxy"],vv=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"]),Sv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Ev=new Set(["ENOTFOUND","EAI_AGAIN"]),xv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Iv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),VM=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 YM(e)},YM=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...vv,...Sv,...Ev,...xv,...Iv])if(t.includes(n))return n}},ZM=e=>e?.name==="AbortError"||e?.name==="TimeoutError",XM=e=>jM.filter(t=>(e[t]??"").trim()!==""),JM=(e,t=process.env)=>{let n=VM(e),r=XM(t);return{kind:n&&vv.has(n)?"tls-unknown-issuer":n&&Sv.has(n)?"tls-invalid-cert":n&&Ev.has(n)?"dns":ZM(e)||n&&Iv.has(n)?"timeout":n&&xv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},zM=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}},mt=(e,t=process.env)=>zM(JM(e,t));var ga="required",Rv=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team;return{routingUpdated:n,teamUpdated:r,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{}}},fd=(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]??ga,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 eF=1e4,tF=1,nF=He.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),rF=He.object({id:nF,name:He.string().min(1),version:He.string().min(1),body:He.string()}),oF=He.object({version:He.literal(tF).optional(),skills:He.array(rF),updatedAt:He.string().min(1).optional(),routing:He.object({origin:He.string().min(1)}).optional(),team:He.string().min(1).optional(),tools:He.object({enabled:He.array(He.string().min(1)),tiers:He.record(He.string().min(1),He.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),aF=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",hd=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",md=async(e,t,n={})=>{let r=n.timeoutMs??eF,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.`:mt(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=hd(l),d}return oF.parse(c)},_v=/^[a-z0-9][a-z0-9-]{0,31}$/,Tv=64,sF=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>_v.test(o)).slice(0,Tv).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>_v.test(o)).slice(0,Tv).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},hi=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??ga)==="locked":!1},yd=async(e,t={})=>{let n=t.loadProfile??P,r=t.saveProfile??te,o=t.targetFromProfile??Te,a=t.adapters??oe,s=t.repairTools??ht,i=t.recordManaged??Xn,c=await n(),l={...c},d=Rv(c,{routingOrigin:e.routing?.origin?ln(e.routing.origin):void 0,team:e.team}),{routingUpdated:u,teamUpdated:f}=d;(u||f)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),await r(l));let p=fd(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f),{candidateIds:h,freshIds:m}=p,w=0,g=0,y=0;if(h.length>0||m.length>0){let S=await o(async()=>l);if(S){let E;if(u||f){let I=new Set(h);E=[];for(let T of a)if(I.has(T.id))try{(await T.detect()).installed&&E.push(T)}catch{}}else E=await Ar(h,S.toolOrigin,a);let x=new Set(m),A=[];for(let I of a)if(x.has(I.id))try{(await I.detect()).installed&&A.push(I)}catch{}if(w=E.length+A.length,w>0){let I=await s([...E,...A],S.target);g=I.filter(po).length;let T=I.filter(B=>x.has(B.id));if(y=T.filter(po).length,T.length>0)try{await i(T,!1)}catch{}}}}let b=sF(e),v=await n();if(JSON.stringify(b??null)!==JSON.stringify(v.fleetToolPolicy??null)){let{fleetToolPolicy:S,...E}=v;await r({...E,...b?{fleetToolPolicy:b}:{}})}return{routingUpdated:u,teamUpdated:f,toolsRequested:w,toolsApplied:g,toolsEnrolled:y,toolsTombstoned:p.tombstonedIds,profileUpdated:u||f}},Pv=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!aF(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=Ov(d,i.id),f=Ov(u,"SKILL.md");await qM(u,{recursive:!0}),await QM(f,iF(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}},iF=e=>e.endsWith(`
294
294
  `)?e:`${e}
295
- `;import{createHash as nF,createPrivateKey as rF,generateKeyPairSync as oF,randomBytes as Fh,sign as aF}from"node:crypto";var Bh=1e4,yo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(yo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${yo(e[n])}`).join(",")}}`,pi="stable-key-heartbeat-v1",Rv="key-heartbeat",sF=["reapply_config","remint","revert"];var Ov=e=>nF("sha256").update(e).digest("hex"),qe=e=>typeof e=="string"&&e.trim()?e.trim():void 0,iF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],Uh=async e=>{try{let t=await e.json(),n=qe(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},It=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Cr=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},Hh=(e,t,n)=>{try{let r=rF(t),o=new TextEncoder().encode(yo(e));return aF(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},fd=()=>{let{publicKey:e,privateKey:t}=oF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},an=async(e,t,n,r={})=>{let o=r.timeoutMs??Bh,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:Fh(16).toString("hex")},c=Hh(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":be},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 It(u.status,await Uh(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=cF(p.directive),g=iF(p.capabilities);return{key:h,user:m,team:qe(p.team),expiresAt:qe(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},hd=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Bh,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:Fh(16).toString("hex"),purpose:Rv},l=Hh(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":be},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 Cr(f.status,await Uh(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!==pi||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:pi}},_v=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Bh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=qe(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Fh(16).toString("hex"),purpose:Rv},d=Hh(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":be},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)}},cF=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"||!sF.includes(r)?null:{id:n,kind:r}},lF=1e4,dF=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)},uF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??lF,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 Uh(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!dF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},Tv=(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())},Pv=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=fd();return{cert:await uF(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 an(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 gF,randomBytes as wF,sign as bF}from"node:crypto";var pF="https://app.anyray.ai",fF=new Set(["localhost","::1","[::1]"]),hF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,mF=e=>fF.has(e)||hF.test(e),Wh=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&mF(t.hostname)},yF=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Gn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!Wh(e)?pF:yF(e)};var kF=1e4,AF="machine:",Lv=e=>e.startsWith(AF),CF="cert-renew",vF=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)},Dv=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Gn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:wF(16).toString("hex"),purpose:CF},c;try{let h=gF(t),m=new TextEncoder().encode(yo(i));c=bF(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),kF),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 vF(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var Kh=async(e,t=e.origin,n=oe)=>{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}},fi=async(e,t=e.origin,n=oe)=>(await Kh(e,t,n)).complete;var SF=["claude","codex","cursor","opencode"],EF=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],xF=new Set(["missing_key","key_expired"]);var IF=600*1e3,RF=600*1e3,Nv=1440*60*1e3,OF=1440*60*1e3,_F=10080*60*1e3,TF=3600*1e3,PF=720*60*1e3,LF=e=>Math.min(PF,TF*2**Math.max(0,e-1)),hi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wa=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,$v=e=>typeof e=="string"&&EF.includes(e),An=e=>{if(!hi(e))return{};let t={};if(wa(e.watchSince)&&(t.watchSince=e.watchSince),hi(e.invoked)){let n={};for(let r of SF){let o=e.invoked[r];wa(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return hi(e.authFailure)&&wa(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...$v(e.authFailure.code)?{code:e.authFailure.code}:{}}),hi(e.repair)&&wa(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,...wa(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},md=e=>{try{let n=JSON.parse(e);if(hi(n)&&$v(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"},Gh=e=>e!==void 0&&xF.has(e),jh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=IF},Mv=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),Vh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=RF},Fv=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),Bv=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,Uv=(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},Hv=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>Nv||!Gh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<LF(r.failures??1))},yd=e=>{let t=Object.values(e?.invoked??{}).filter(wa);return t.length>0?Math.max(...t):null},Yh=(e,t)=>{if(yd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=_F},Wv=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=OF)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=Nv)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var Zh="x-anyray-retrieve-probe",gd=8e3,DF=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Kv=(e,t)=>{let n=Xt(e);return t?.probe&&(n[Zh]="1"),n},ba=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(),gd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:Kv(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=DF(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)}},wd=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(),gd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:Kv(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 NF=5e3,$F=2048,MF=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}"`))},ka=async(e={})=>{let t=e.readTarget??rt,n=e.fetch??fetch,r=e.timeoutMs??NF,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=Xt(o);i["content-type"]="application/json",i[Zh]="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,$F);if(!MF(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=md(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)}},Xh=(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 FF,randomBytes as BF,sign as UF}from"node:crypto";var HF=500,Gv=2e3,WF=2e3,KF=250,jv=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),HF);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)}},GF=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},jF=e=>new Promise(t=>setTimeout(t,e)),VF=async(e,t,n=jF)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),Gv),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=GF(i)??KF,s>WF))return!1}finally{clearTimeout(a)}await n(s)}},YF=async e=>{try{let n=(await P()).enrolledCert,r=await Be(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:BF(16).toString("hex"),events:e},s;try{let i=FF(r),c=new TextEncoder().encode(yo(a));s=UF(null,c,i).toString("base64url")}catch{return!1}return await VF(`${Gn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},ZF=async(e,t)=>{try{let r=(await P()).enrolledCert,o=await Be();if(!r||!o)return;await an(e,r,o,{timeoutMs:Gv,health:{events:t},telemetryOnly:!0})}catch{}},Vv=async(e,t)=>{if(e.length!==0)try{let n=await rt(),r=n&&await jv(n.origin,Xt(n),e,t);if(n&&await ZF(n.origin,e),r)return;await YF(e)}catch{}},Jh=async(e,t,n={readTarget:()=>rt("profile"),post:jv})=>{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 wo=["hook_registration","mcp_registration","hook_binary","beacon_target"];var Zv=128,Xv=300*1e3,XF=["repaired","repair_failed","flapping","pending"],JF=["settings_not_writable","apply_unconfirmed","apply_threw"],Jv=["rebroke_same_day","repeat_days"],zv=new Set(oe.map(e=>e.id)),go=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),qv=e=>yi(e,wo),bd=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},vr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,mi=e=>{if(!(!Array.isArray(e)||!e.every(qv)))return jn(e)},zF=e=>{if(!go(e))return;let t=mi(e.checks);if(!(!vr(e.since)||!yi(e.reason,Jv)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},qF=e=>{if(!go(e))return;let t={};bd(e.day)&&(t.day=e.day),vr(e.attempts)&&(t.attempts=e.attempts);let n=mi(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=mi(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=mi(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=mi(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),bd(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),vr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),go(e.lastRepaired)){let i={};for(let c of wo){let l=e.lastRepaired[c];vr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=zF(e.flapping);return s&&(t.flapping=s),t},QF=e=>{if(!go(e)||!bd(e.day)||!vr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!zv.has(e.tool)||!qv(e.checkId)||!yi(e.status,XF)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!yi(e.errorClass,JF))return;t=e.errorClass}else if(e.status==="flapping"){if(!yi(e.errorClass,Jv))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,...vr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},Yv=e=>{if(!go(e))return{};let t={};if(go(e.adapters)){let n={};for(let r of zv){let o=qF(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(QF).filter(n=>n!==void 0).slice(-Zv)),vr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),go(e.report)&&bd(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...vr(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,jn=e=>[...new Set(e)],kd=(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}:{}}},gi=(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(-Zv),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,ke)??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=kd(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)},Qv=(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: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}},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=kd(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=Qv(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=gi(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=kd(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(v=>!(l.brokenReportedChecks??[]).includes(v));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:gi({...i,adapters:c},o,g.map(v=>({tool:e,checkId:v,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:gi({...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=kd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:jn([...l.awaiting??[],...t])},{next:gi({...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=Qv(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:gi({...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>=Xv));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??Jh)(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 wo){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??vc)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??dr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=Wv(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<Xv?{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??Jh)(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=eB(r()),a=e.managedTools??[],s={...n,readState:async()=>Yv(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(Yv(l)),c)};try{let i=await(s.findIntegrations??Mh)(a);await oB(i,o,s);let c=await(s.listPending??cr)().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??Ar)(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??ce)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?wo.filter(T=>y[T]==="missing"):[];if(b.length===0&&!f.has(g.id))continue;let v=y;if(g.integrationStatus)try{v=await g.integrationStatus()}catch{v=Object.fromEntries(wo.map(T=>[T,"unreadable"]))}let S=b.filter(T=>v[T]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),S.length===0&&!E)continue;let x=await sB(g.id,S,E,l.has(g.id),o,r(),s);if(!x)continue;let[A]=await(s.repair??gt)([g],d.target);if(!A)continue;h=!0;let I;A.status==="configured"&&g.integrationStatus&&(I=await g.integrationStatus().catch(()=>{})),await iB(g.id,x.checks,A,I,o,r(),s)}await cB(o,r(),t,s),i=await(s.findIntegrations??Mh)(a);let w=await(s.listPending??cr)().catch(()=>[]);return await dB(e,i,w,o,r(),t,s),h}catch{return!1}};var wB=14,bB=.35,kB=900*1e3,nS=360*60*1e3,AB=.2,CB=1800*1e3,rS=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,xB=900*1e3,IB=(e=0)=>Math.min(xB,EB*2**Math.max(0,e)),oS=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,aS=1440*60*1e3,OB=300*1e3,_B=.25,TB=.5,sS=3600*1e3,PB=720*60*60*1e3,LB=360*60*1e3,DB=1440*60*1e3,NB=4,Ad=e=>fB("sha256").update(e).digest("hex").slice(0,32),fS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Wt)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??P)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(Ad(e))},zh=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,NB)}),$B=()=>uS(hB(),".anyray"),Qh=()=>uS($B(),"refresh-state.json"),em=e=>process.env?.[e],hS=()=>em("ANYRAY_REFRESH_DISABLE")==="true",tm=()=>{let e=em("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:wB)*DB},bi=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},mS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),MB=10080*60*1e3,Cd=(e,t,n=Date.now())=>{let r=[],o=bi(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},ki=e=>{let t=tm(),n=e?bi(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=em("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(nS,Math.max(CB,Math.round(e*AB))):nS},Wt=async()=>{try{let e=await mB(Qh(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},vd=async e=>{try{let t=Qh(),n=`${t}.${process.pid}.tmp`;await pS(n,JSON.stringify(e),{mode:384}),await fe(n,t),await yB(t,384).catch(()=>{})}catch{}},BB=3e4,UB=()=>`${Qh()}.lock`,iS=async e=>{try{return await pS(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??Wt,a=n.writeState??vd,s=UB(),i=!1;try{if(i=await iS(s),!i){if(await gB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<BB)return t;await tS(s).catch(()=>{}),i=await iS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await tS(s).catch(()=>{})}},wi=async(e,t={})=>{await ut(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Aa=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??P)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?Ad(a.clientKey):void 0;await ut(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:zh(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},bo=async(e={})=>{let t=e.now??Date.now;await ut(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},HB=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(sS,Math.round(o*TB))):sS},qh=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,nm=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??te,a=n.loadProfile??P,s=n.loadDevKey??Be,i=n.renew??Dv,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(Lv(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()>HB(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 qh(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}},cS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*_B):aS,r=Math.min(aS,n);return Math.min(r,OB*2**Math.max(0,e-1))},WB=()=>{let{command:e,args:t}=pn(Qn);return{exe:e,args:t}},Sr=async(e={})=>{if(hS())return;let t=e.now??Date.now,n=e.readState??Wt,r=e.writeState??vd,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=WB();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=fi,GB=async(e,t=ke,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 Ar(r,o.toolOrigin),s=n?gv(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=oe.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?vn(l,d):l,u?`http://${ht}:${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??Wt,a=t.writeState??vd;return eS(e,be,{now:r,deadWatcherObserved:n,readHookLane:()=>Sd({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})})},Sd=async(e={})=>{let n=await(e.readState??Wt)().catch(()=>({}));return An(n.hookLane)},yS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Sd(t);if(!jh(r,e,n()))return;await ut(o=>{let a=An(o.hookLane);return jh(a,e,n())?{next:{...o,hookLane:Mv(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},gS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Sd(t);if(!Vh(r,n()))return;await ut(o=>{let a=An(o.hookLane);return Vh(a,n())?{next:{...o,hookLane:Fv(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},YB=async(e={})=>{try{let t=e.now??Date.now;if((await Sd(e)).watchSince!==void 0)return;await ut(n=>{let r=An(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:Bv(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=An(r.hookLane),a=Uv(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},wS=async(e={})=>{try{if((await(e.readState??Wt)()).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??pg)())return await r()?"stamped":"skipped";let o=await(e.load??P)(),s=await(e.findTools??mo)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await _e(async()=>o,void 0,e.probe??ke);return!i||!await r()?"skipped":(await(e.repair??gt)(s,i.target),"repathed")}catch{return"skipped"}},bS=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Wt)()).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??P)(),i=await(e.findTools??mo)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await _e(async()=>a,void 0,e.probe??ke);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"}},ZB=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await ud(e.gateway,e.clientKey),n=await pd(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},Qe=async(e={})=>{if(hS())return"disabled";let t=e.now??Date.now,n=e.loadProfile??P,r=e.saveProfile??te,o=e.loadDevKey??Be,a=e.readState??Wt,s=e.writeState??vd,i=e.remint??an,c=e.heartbeat??hd,l=e.detectSeat??Dt,d=e.rewriteTools??KB,u=e.rewriteHookLaneTools??Kh,f=e.probeHookLane??ka,p=e.classifyBeacon??uc,h=e.probe??ke,m=e.installProxy??Lt,w=e.pickProxyPort??yc,g=e.force===!0,y=!1,b=!1,v=!1,S=!1;e.hookLaneRepair===!0&&(g=!0,S=!0);let E=async A=>{if(!S){A==="repaired"&&await lS("none",{now:t,readState:a,writeState:s});return}let I=A;if(A==="repaired"){let T=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));I=T.verdict==="live"?"repaired":T.verdict==="dark"?"repair_failed":"unverified"}await lS(I,{now:t,readState:a,writeState:s})},x=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let A;try{A=await n()}catch{return!1}return(e.ambientSelfcheck??(T=>VB(T,{now:t,readState:a,writeState:s},v)))(A).catch(()=>!1)};try{e.runAmbientSelfcheck&&(v=await cr().then(_=>_.some(L=>!dr(L.watcherPid))).catch(()=>!1),await YB({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??Vw)();let A=await n();if(y=!0,!A.gateway||!A.enrolledCert)return"not-enrolled";let I=A.gateway,T=A.enrolledCertExpiry?Date.parse(A.enrolledCertExpiry):Date.parse(A.enrolledCert.payload.expiresAt);if(!Number.isFinite(T)||T<=t())return"cert-expired";let B=await o();if(!B)return"not-enrolled";let X=await nm(A,B,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});A=X.profile;let V=X.outcome==="renewed",W=A.enrolledCert;if(!W)return"not-enrolled";let z=Date.parse(A.clientKeyExpiresAt??""),me=Number.isFinite(z)?z-t():0,De=await a(),ee=!A.clientKey||me<=ki(A),Fe=A.credentialProtocol!=="stable-heartbeat-v1"&&t()-(De.lastSuccessAt??0)>=RB;if(!g&&Hv(An(De.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,S=!0),A.credentialProtocol==="stable-heartbeat-v1"&&A.clientKey&&(g||ee)){let _=await ut(L=>{let H=t()-(L.lastAttemptAt??0);return H<rS?{result:"throttled"}:L.failureCount&&H<cS(L.failureCount,L.keyTtlMs)?{result:"backoff"}:{next:{...L,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(_!=="ok")return _;try{let L=await c(I,A.clientKey,W,B),H=await n().catch(()=>A);return H.clientKey!==A.clientKey||H.enrolledCert?.sig!==W.sig?"failed":(await r({...H,clientKeyExpiresAt:L.expiresAt}),await wi(({lastError:ye,...se})=>({...se,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:bi(A)??se.keyTtlMs}),{now:t,readState:a,writeState:s}),S&&await E(await jB(A,I,A.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(L){let H=L;if(L instanceof Cr&&L.status===404)try{let se=await i(I,W,B),we=await l().catch(()=>{}),We=ge({origin:I,clientKey:se.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:we,user:A.name,team:A.team}),ue=A.fallbackPort,ie=Number.isInteger(ue)&&ue>0&&ue<=65535?ue:await w();if(!(await m({port:ie,remoteOrigin:I})).ok||await h(ie)===null)throw new Error("key-refresh proxy recovery failed");let Ne=await n().catch(()=>A);if(!await qh(Ne,W.sig,B,o))throw new Error("enrollment changed during proxy recovery");if(await r({...Ne,clientKey:se.key,clientKeyExpiresAt:se.expiresAt??Ne.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:ie}),await d(vn(We,ie),We.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let ft=se.expiresAt?Date.parse(se.expiresAt):NaN,Ve=bi(A)??(Number.isFinite(ft)&&ft-t()>0?ft-t():void 0);return await wi(({lastError:Pr,...cn})=>({...cn,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ve??cn.keyTtlMs,ownKeys:zh(cn.ownKeys,W.sig,Ad(se.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(se){H=se}let ye=oS(H);return await wi(se=>({...se,lastAttemptAt:t(),failureCount:(se.failureCount??0)+1,lastError:{name:H instanceof Error?H.name:"Error",...ye!==void 0?{code:ye}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),H instanceof Cr?"cert-rejected":"failed"}}if(!g&&A.clientKey&&!ee&&!Fe){let _=await dS(A,e,n,h),L=await x();return _||L?"repaired":V?"cert-renewed":"not-due"}let xe=await ut(_=>{let L=t()-(_.lastAttemptAt??0);if(g)return L<IB(_.failureCount)?{result:"throttled"}:{next:{..._,lastAttemptAt:t()},result:"ok"};let H=_.lastError?.code!==void 0&&vB.has(_.lastError.code)?SB:rS;return L<H?{result:"throttled"}:_.failureCount&&L<cS(_.failureCount,_.keyTtlMs)?{result:"backoff"}:{next:{..._,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(xe!=="ok")return xe;try{let _=await i(I,W,B),L=await l().catch(()=>{}),H=ge({origin:I,clientKey:_.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:L,user:A.name,team:A.team}),ye=H,se=H.origin;if(nt(A)){if(!Number.isInteger(A.fallbackPort)||A.fallbackPort<1||A.fallbackPort>65535)throw new Error("key-refresh proxy profile has no valid port");await h(A.fallbackPort)!==null&&(ye=vn(H,A.fallbackPort),se=`http://${ht}:${A.fallbackPort}`)}let we=await d(ye,se);if(A.directMigration==="pending"&&ye.viaLocalProxy===!0){let ft=await d(ye,H.origin);we=we!==!1&&ft!==!1}if(we===!1)throw new Error("one or more configured tools rejected the refreshed key");let We=await n().catch(()=>A),ue=null,ie;We.enrolledCert&&await qh(We,W.sig,B,o)&&(ie=Ad(_.key),ue={...We,clientKey:_.key,clientKeyExpiresAt:_.expiresAt??We.clientKeyExpiresAt},await r(ue));let Y=_.expiresAt?Date.parse(_.expiresAt):NaN,Ne=bi(A)??(Number.isFinite(Y)&&Y-t()>0?Y-t():void 0);return await wi(({lastError:ft,...Ve})=>({...Ve,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ne??Ve.keyTtlMs,...ie?{ownKeys:zh(Ve.ownKeys,W.sig,ie)}:{}}),{now:t,readState:a,writeState:s}),ue&&await dS(ue,e,n,h),await E(ue?"repaired":"repair_failed"),await x(),"refreshed"}catch(_){let L=oS(_);return await wi(H=>({...H,lastAttemptAt:t(),failureCount:(H.failureCount??0)+1,lastError:{name:_ instanceof Error?_.name:"Error",...L!==void 0?{code:L}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),_ instanceof It?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await x()}catch{}}};import{readFile as tU}from"node:fs/promises";import{isAbsolute as nU,posix as SS,win32 as am}from"node:path";var rm=1e4,XB=900*1e3,AS="tnt_",JB=/^\/sso\/([^/]+)\/?$/,zB=/^\/i\/([^/]+)\/?$/,qB=e=>{let t=e.match(JB);if(t)return t[1];let n=e.match(zB);return n?.[1].startsWith(AS)?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=qB(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(AS))return{cpOrigin:Gn(),tenantId:t}},ko=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Kt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},om=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)),Ed=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??fd)(),a;try{a=await om(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},rm,n)}catch(h){throw new ko("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 ko(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 ko("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??XB,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}`),eU(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},eU=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},xd=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 om(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},rm,o)}catch(c){throw new Kt("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 Kt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Kt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Kt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var kS="sdc_",CS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(kS))return{cpOrigin:Gn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!Wh(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(kS)))return{cpOrigin:n.origin,claim:r}},vS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??fd)(),o;try{o=await om(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},rm,t)}catch(s){throw new Kt("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 Kt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Kt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Kt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};var Ai=(e=process.platform,t=process.env)=>e==="darwin"?SS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?am.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):SS.join("/etc","anyray","bootstrap.json"),rU=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ES=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(nU(e)||am.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),oU=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}},Gt=async(e=Ai())=>{try{let t=await tU(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!rU(n)||n.v!==1||typeof n.sso!="string")return;let r=Rt(n.sso);if(!r)return;let o=oU(n.gateway)?n.gateway:void 0,a=ES(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=Rt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!ES(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&am.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 OU}from"node:child_process";import{chmod as aU,readFile as sU,rm as IS,writeFile as iU}from"node:fs/promises";import{join as cU}from"node:path";var sm=()=>cU(q(),"sso-gate.json"),lU=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))},Er=async()=>{try{let e=JSON.parse(await sU(sm(),"utf-8"));return lU(e)?e:null}catch{return null}},dU=0,Id=async e=>{await kt();let t=sm(),n=`${t}.${process.pid}.${dU++}.tmp`;try{await iU(n,`${JSON.stringify(e)}
297
- `,{mode:384}),await aU(n,384),await fe(n,t)}catch(r){throw await IS(n,{force:!0}).catch(()=>{}),r}},RS=async()=>{await IS(sm(),{force:!0}).catch(()=>{})},OS=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 fU}from"node:child_process";import{homedir as hU}from"node:os";import{join as mU}from"node:path";import{spawn as uU}from"node:child_process";import{platform as pU}from"node:os";var Ca=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=pU(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=uU(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var yU=3e4,gU=5*6e4,wU=30*6e4,bU=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},kU=()=>mU(hU(),".claude","settings.json"),AU=async e=>{try{let n=(await M(kU())).env;if(!n)return!1;let r=un(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}},CU=async e=>{await nr.apply(e,{dryRun:!1})},vU=()=>{let{command:e,args:t}=pn("__anyray-sso-poll");return{exe:e,args:t}},SU=()=>{let{exe:e,args:t}=vU(),n=fU(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))}}},EU=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},_S=(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}),va=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},TS=e=>`Anyray: one-time sign-in required to use AI tools on this device.
295
+ `;import{createHash as cF,createPrivateKey as lF,generateKeyPairSync as dF,randomBytes as Hh,sign as uF}from"node:crypto";var Wh=1e4,ho=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ho).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${ho(e[n])}`).join(",")}}`,mi="stable-key-heartbeat-v1",Lv="key-heartbeat",pF=["reapply_config","remint","revert"];var Dv=e=>cF("sha256").update(e).digest("hex"),Je=e=>typeof e=="string"&&e.trim()?e.trim():void 0,fF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],Kh=async e=>{try{let t=await e.json(),n=Je(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},It=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Cr=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},Gh=(e,t,n)=>{try{let r=lF(t),o=new TextEncoder().encode(ho(e));return uF(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},gd=()=>{let{publicKey:e,privateKey:t}=dF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},sn=async(e,t,n,r={})=>{let o=r.timeoutMs??Wh,a=`${e}/connect/verify`,s=Je(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:Hh(16).toString("hex")},c=Gh(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":be},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.`:mt(y);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:y})}finally{clearTimeout(d)}if(!u.ok)throw new It(u.status,await Kh(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=Je(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=Je(p.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=hF(p.directive),g=fF(p.capabilities);return{key:h,user:m,team:Je(p.team),expiresAt:Je(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},wd=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Wh,s=`${e}/connect/key/heartbeat`,i=Je(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:Hh(16).toString("hex"),purpose:Lv},l=Gh(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":be},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.`:mt(m);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:m})}finally{clearTimeout(u)}if(!f.ok)throw new Cr(f.status,await Kh(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=Je(p.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||p.credentialMode!==mi||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:mi}},Nv=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Wh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=Je(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Hh(16).toString("hex"),purpose:Lv},d=Gh(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":be},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)}},hF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=Je(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!pF.includes(r)?null:{id:n,kind:r}},mF=1e4,yF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!Je(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!Je(r.deploymentId)&&!!Je(r.user)&&!!Je(r.devPublicKey)&&!!Je(r.issuedAt)&&!!Je(r.expiresAt)},gF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??mF,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.`:mt(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 Kh(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!yF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},$v=(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())},Mv=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=gd();return{cert:await gF(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 sn(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 vF,randomBytes as SF,sign as EF}from"node:crypto";var wF="https://app.anyray.ai",bF=new Set(["localhost","::1","[::1]"]),kF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,AF=e=>bF.has(e)||kF.test(e),jh=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&AF(t.hostname)},CF=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Gn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!jh(e)?wF:CF(e)};var xF=1e4,IF="machine:",Fv=e=>e.startsWith(IF),RF="cert-renew",OF=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)},Bv=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Gn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:SF(16).toString("hex"),purpose:RF},c;try{let h=vF(t),m=new TextEncoder().encode(ho(i));c=EF(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),xF),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 OF(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var Vh=async(e,t=e.origin,n=oe)=>{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}},yi=async(e,t=e.origin,n=oe)=>(await Vh(e,t,n)).complete;var _F=["claude","codex","cursor","opencode"],TF=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],PF=new Set(["missing_key","key_expired"]);var LF=600*1e3,DF=600*1e3,Uv=1440*60*1e3,NF=1440*60*1e3,$F=10080*60*1e3,MF=3600*1e3,FF=720*60*1e3,BF=e=>Math.min(FF,MF*2**Math.max(0,e-1)),gi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wa=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Hv=e=>typeof e=="string"&&TF.includes(e),An=e=>{if(!gi(e))return{};let t={};if(wa(e.watchSince)&&(t.watchSince=e.watchSince),gi(e.invoked)){let n={};for(let r of _F){let o=e.invoked[r];wa(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return gi(e.authFailure)&&wa(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...Hv(e.authFailure.code)?{code:e.authFailure.code}:{}}),gi(e.repair)&&wa(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,...wa(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},bd=e=>{try{let n=JSON.parse(e);if(gi(n)&&Hv(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"},Yh=e=>e!==void 0&&PF.has(e),Zh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=LF},Wv=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),Xh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=DF},Kv=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),Gv=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,jv=(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},Vv=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>Uv||!Yh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<BF(r.failures??1))},kd=e=>{let t=Object.values(e?.invoked??{}).filter(wa);return t.length>0?Math.max(...t):null},Jh=(e,t)=>{if(kd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=$F},Yv=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=NF)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=Uv)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var zh="x-anyray-retrieve-probe",Ad=8e3,UF=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Zv=(e,t)=>{let n=Jt(e);return t?.probe&&(n[zh]="1"),n},ba=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(),Ad);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:Zv(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=UF(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)}},Cd=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(),Ad);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:Zv(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 HF=5e3,WF=2048,KF=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}"`))},ka=async(e={})=>{let t=e.readTarget??et,n=e.fetch??fetch,r=e.timeoutMs??HF,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=Jt(o);i["content-type"]="application/json",i[zh]="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,WF);if(!KF(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=bd(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)}},qh=(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 GF,randomBytes as jF,sign as VF}from"node:crypto";var YF=500,Xv=2e3,ZF=2e3,XF=250,Jv=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),YF);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)}},JF=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},zF=e=>new Promise(t=>setTimeout(t,e)),qF=async(e,t,n=zF)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),Xv),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=JF(i)??XF,s>ZF))return!1}finally{clearTimeout(a)}await n(s)}},QF=async e=>{try{let n=(await P()).enrolledCert,r=await Be(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:jF(16).toString("hex"),events:e},s;try{let i=GF(r),c=new TextEncoder().encode(ho(a));s=VF(null,c,i).toString("base64url")}catch{return!1}return await qF(`${Gn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},eB=async(e,t)=>{try{let r=(await P()).enrolledCert,o=await Be();if(!r||!o)return;await sn(e,r,o,{timeoutMs:Xv,health:{events:t},telemetryOnly:!0})}catch{}},zv=async(e,t)=>{if(e.length!==0)try{let n=await et(),r=n&&await Jv(n.origin,Jt(n),e,t);if(n&&await eB(n.origin,e),r)return;await QF(e)}catch{}},Qh=async(e,t,n={readTarget:()=>et("profile"),post:Jv})=>{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 yo=["hook_registration","mcp_registration","hook_binary","beacon_target"];var Qv=128,eS=300*1e3,tB=["repaired","repair_failed","flapping","pending"],nB=["settings_not_writable","apply_unconfirmed","apply_threw"],tS=["rebroke_same_day","repeat_days"],nS=new Set(oe.map(e=>e.id)),mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),rS=e=>bi(e,yo),vd=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},vr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,wi=e=>{if(!(!Array.isArray(e)||!e.every(rS)))return jn(e)},rB=e=>{if(!mo(e))return;let t=wi(e.checks);if(!(!vr(e.since)||!bi(e.reason,tS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},oB=e=>{if(!mo(e))return;let t={};vd(e.day)&&(t.day=e.day),vr(e.attempts)&&(t.attempts=e.attempts);let n=wi(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=wi(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=wi(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=wi(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),vd(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),vr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),mo(e.lastRepaired)){let i={};for(let c of yo){let l=e.lastRepaired[c];vr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=rB(e.flapping);return s&&(t.flapping=s),t},aB=e=>{if(!mo(e)||!vd(e.day)||!vr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!nS.has(e.tool)||!rS(e.checkId)||!bi(e.status,tB)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!bi(e.errorClass,nB))return;t=e.errorClass}else if(e.status==="flapping"){if(!bi(e.errorClass,tS))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,...vr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},qv=e=>{if(!mo(e))return{};let t={};if(mo(e.adapters)){let n={};for(let r of nS){let o=oB(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(aB).filter(n=>n!==void 0).slice(-Qv)),vr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),mo(e.report)&&vd(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...vr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},sB=e=>new Date(e).toISOString().slice(0,10),iB=(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)],Sd=(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}:{}}},ki=(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(-Qv),nextSequence:r}},cB=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),lB=async e=>await Te(async()=>e,void 0,ke)??null,dB=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=Sd(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)},oS=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:iB(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}},uB=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=Sd(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=oS(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=ki(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)},pB=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Sd(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(v=>!(l.brokenReportedChecks??[]).includes(v));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:ki({...i,adapters:c},o,g.map(v=>({tool:e,checkId:v,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:ki({...i,adapters:c},o,p.map(g=>({tool:e,checkId:g,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),fB=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Sd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:jn([...l.awaiting??[],...t])},{next:ki({...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=oS(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:ki({...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)},hB=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>=eS));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??Qh)(o.map(cB),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)},mB=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 yo){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??Ic)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??dr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=Yv(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},yB=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<eS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await mB(e,t,n,c,o,s);await(s.report??Qh)(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)},aS=async(e,t,n)=>{let r=n.now??Date.now,o=sB(r()),a=e.managedTools??[],s={...n,readState:async()=>qv(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(qv(l)),c)};try{let i=await(s.findIntegrations??Uh)(a);await dB(i,o,s);let c=await(s.listPending??cr)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await uB(i,l,o,r(),s);let d=await(s.resolveTarget??lB)(e),u=d?await(s.findDrifted??Ar)(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??se)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?yo.filter(T=>y[T]==="missing"):[];if(b.length===0&&!f.has(g.id))continue;let v=y;if(g.integrationStatus)try{v=await g.integrationStatus()}catch{v=Object.fromEntries(yo.map(T=>[T,"unreadable"]))}let S=b.filter(T=>v[T]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),S.length===0&&!E)continue;let x=await pB(g.id,S,E,l.has(g.id),o,r(),s);if(!x)continue;let[A]=await(s.repair??ht)([g],d.target);if(!A)continue;h=!0;let I;A.status==="configured"&&g.integrationStatus&&(I=await g.integrationStatus().catch(()=>{})),await fB(g.id,x.checks,A,I,o,r(),s)}await hB(o,r(),t,s),i=await(s.findIntegrations??Uh)(a);let w=await(s.listPending??cr)().catch(()=>[]);return await yB(e,i,w,o,r(),t,s),h}catch{return!1}};var SB=14,EB=.35,xB=900*1e3,iS=360*60*1e3,IB=.2,RB=1800*1e3,cS=3600*1e3,OB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),_B=300*1e3,TB=30*1e3,PB=900*1e3,LB=(e=0)=>Math.min(PB,TB*2**Math.max(0,e)),lS=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}},DB=720*60*1e3,dS=1440*60*1e3,NB=300*1e3,$B=.25,MB=.5,uS=3600*1e3,FB=720*60*60*1e3,BB=360*60*1e3,UB=1440*60*1e3,HB=4,Ed=e=>bB("sha256").update(e).digest("hex").slice(0,32),wS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Kt)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??P)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(Ed(e))},em=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,HB)}),WB=()=>yS(kB(),".anyray"),nm=()=>yS(WB(),"refresh-state.json"),rm=e=>process.env?.[e],bS=()=>rm("ANYRAY_REFRESH_DISABLE")==="true",om=()=>{let e=rm("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:SB)*UB},Ci=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},kS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),KB=10080*60*1e3,xd=(e,t,n=Date.now())=>{let r=[],o=Ci(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)<=KB},vi=e=>{let t=om(),n=e?Ci(e):void 0;if(!n)return t;let r=Math.max(xB,Math.round(n*EB));return Math.min(t,r)},GB=e=>{let t=rm("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(RB,Math.round(e*IB))):iS},Kt=async()=>{try{let e=await AB(nm(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Id=async e=>{try{let t=nm(),n=`${t}.${process.pid}.tmp`;await gS(n,JSON.stringify(e),{mode:384}),await he(n,t),await CB(t,384).catch(()=>{})}catch{}},jB=3e4,VB=()=>`${nm()}.lock`,pS=async e=>{try{return await gS(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},ct=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Kt,a=n.writeState??Id,s=VB(),i=!1;try{if(i=await pS(s),!i){if(await vB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<jB)return t;await sS(s).catch(()=>{}),i=await pS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await sS(s).catch(()=>{})}},Ai=async(e,t={})=>{await ct(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Aa=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??P)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?Ed(a.clientKey):void 0;await ct(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:em(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},go=async(e={})=>{let t=e.now??Date.now;await ct(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},YB=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(FB,Math.max(uS,Math.round(o*MB))):uS},tm=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,am=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??te,a=n.loadProfile??P,s=n.loadDevKey??Be,i=n.renew??Bv,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(Fv(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()>YB(e))return{outcome:"not-due",profile:e};if(!await ct(w=>r()-(w.lastCertRenewAt??0)<BB?{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 tm(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}},fS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*$B):dS,r=Math.min(dS,n);return Math.min(r,NB*2**Math.max(0,e-1))},ZB=()=>{let{command:e,args:t}=pn(Qn);return{exe:e,args:t}},Sr=async(e={})=>{if(bS())return;let t=e.now??Date.now,n=e.readState??Kt,r=e.writeState??Id,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=ZB();wB(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await ct(s=>t()-(s.lastSpawnAt??0)<GB(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},XB=yi,JB=async(e,t=ke,n=!1)=>{try{let r=e.managedTools??[];if(r.length===0)return!1;let o=await Te(async()=>e,void 0,t);if(!o)return!1;let a=await Ar(r,o.toolOrigin),s=n?Cv(a):a;return s.length===0?!1:(await ht(s,o.target),!0)}catch{return!1}},zB=async(e,t,n,r,o,a)=>{try{let s=new Set(e.managedTools??[]),i=oe.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=Qe(e)&&Number.isInteger(d)&&d>0&&d<=65535&&await o(d)!==null,f=await a(u?vn(l,d):l,u?`http://${ut}:${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??Id;return aS(e,be,{now:r,deadWatcherObserved:n,readHookLane:()=>Rd({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>ct(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Rd=async(e={})=>{let n=await(e.readState??Kt)().catch(()=>({}));return An(n.hookLane)},AS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Rd(t);if(!Zh(r,e,n()))return;await ct(o=>{let a=An(o.hookLane);return Zh(a,e,n())?{next:{...o,hookLane:Wv(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},CS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Rd(t);if(!Xh(r,n()))return;await ct(o=>{let a=An(o.hookLane);return Xh(a,n())?{next:{...o,hookLane:Kv(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},QB=async(e={})=>{try{let t=e.now??Date.now;if((await Rd(e)).watchSince!==void 0)return;await ct(n=>{let r=An(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:Gv(r,t())},result:void 0}},void 0,e)}catch{}},hS=async(e,t={})=>{try{let n=t.now??Date.now;await ct(r=>{let o=An(r.hookLane),a=jv(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},vS=async(e={})=>{try{if((await(e.readState??Kt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>ct(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??gg)())return await r()?"stamped":"skipped";let o=await(e.load??P)(),s=await(e.findTools??fo)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Te(async()=>o,void 0,e.probe??ke);return!i||!await r()?"skipped":(await(e.repair??ht)(s,i.target),"repathed")}catch{return"skipped"}},SS=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Kt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>ct(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??P)(),i=await(e.findTools??fo)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Te(async()=>a,void 0,e.probe??ke);return!c||!await o()?"skipped":(await(e.repair??ht)(i,c.target)).some(d=>d.status==="failed")?(await ct(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"}},eU=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await md(e.gateway,e.clientKey),n=await yd(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},mS=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??eU)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>JB(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},ze=async(e={})=>{if(bS())return"disabled";let t=e.now??Date.now,n=e.loadProfile??P,r=e.saveProfile??te,o=e.loadDevKey??Be,a=e.readState??Kt,s=e.writeState??Id,i=e.remint??sn,c=e.heartbeat??wd,l=e.detectSeat??Nt,d=e.rewriteTools??XB,u=e.rewriteHookLaneTools??Vh,f=e.probeHookLane??ka,p=e.classifyBeacon??mc,h=e.probe??ke,m=e.installProxy??Dt,w=e.pickProxyPort??kc,g=e.force===!0,y=!1,b=!1,v=!1,S=!1;e.hookLaneRepair===!0&&(g=!0,S=!0);let E=async A=>{if(!S){A==="repaired"&&await hS("none",{now:t,readState:a,writeState:s});return}let I=A;if(A==="repaired"){let T=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));I=T.verdict==="live"?"repaired":T.verdict==="dark"?"repair_failed":"unverified"}await hS(I,{now:t,readState:a,writeState:s})},x=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let A;try{A=await n()}catch{return!1}return(e.ambientSelfcheck??(T=>qB(T,{now:t,readState:a,writeState:s},v)))(A).catch(()=>!1)};try{e.runAmbientSelfcheck&&(v=await cr().then(_=>_.some(L=>!dr(L.watcherPid))).catch(()=>!1),await QB({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??zw)();let A=await n();if(y=!0,!A.gateway||!A.enrolledCert)return"not-enrolled";let I=A.gateway,T=A.enrolledCertExpiry?Date.parse(A.enrolledCertExpiry):Date.parse(A.enrolledCert.payload.expiresAt);if(!Number.isFinite(T)||T<=t())return"cert-expired";let B=await o();if(!B)return"not-enrolled";let X=await am(A,B,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});A=X.profile;let V=X.outcome==="renewed",H=A.enrolledCert;if(!H)return"not-enrolled";let z=Date.parse(A.clientKeyExpiresAt??""),ye=Number.isFinite(z)?z-t():0,Ne=await a(),ee=!A.clientKey||ye<=vi(A),Fe=A.credentialProtocol!=="stable-heartbeat-v1"&&t()-(Ne.lastSuccessAt??0)>=DB;if(!g&&Vv(An(Ne.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,S=!0),A.credentialProtocol==="stable-heartbeat-v1"&&A.clientKey&&(g||ee)){let _=await ct(L=>{let W=t()-(L.lastAttemptAt??0);return W<cS?{result:"throttled"}:L.failureCount&&W<fS(L.failureCount,L.keyTtlMs)?{result:"backoff"}:{next:{...L,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(_!=="ok")return _;try{let L=await c(I,A.clientKey,H,B),W=await n().catch(()=>A);return W.clientKey!==A.clientKey||W.enrolledCert?.sig!==H.sig?"failed":(await r({...W,clientKeyExpiresAt:L.expiresAt}),await Ai(({lastError:le,...ie})=>({...ie,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ci(A)??ie.keyTtlMs}),{now:t,readState:a,writeState:s}),S&&await E(await zB(A,I,A.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(L){let W=L;if(L instanceof Cr&&L.status===404)try{let ie=await i(I,H,B),gt=await l().catch(()=>{}),pe=ge({origin:I,clientKey:ie.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:gt,user:A.name,team:A.team}),fe=A.fallbackPort,de=Number.isInteger(fe)&&fe>0&&fe<=65535?fe:await w();if(!(await m({port:de,remoteOrigin:I})).ok||await h(de)===null)throw new Error("key-refresh proxy recovery failed");let Ie=await n().catch(()=>A);if(!await tm(Ie,H.sig,B,o))throw new Error("enrollment changed during proxy recovery");if(await r({...Ie,clientKey:ie.key,clientKeyExpiresAt:ie.expiresAt??Ie.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:de}),await d(vn(pe,de),pe.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let dt=ie.expiresAt?Date.parse(ie.expiresAt):NaN,wt=Ci(A)??(Number.isFinite(dt)&&dt-t()>0?dt-t():void 0);return await Ai(({lastError:vo,...bt})=>({...bt,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:wt??bt.keyTtlMs,ownKeys:em(bt.ownKeys,H.sig,Ed(ie.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(ie){W=ie}let le=lS(W);return await Ai(ie=>({...ie,lastAttemptAt:t(),failureCount:(ie.failureCount??0)+1,lastError:{name:W instanceof Error?W.name:"Error",...le!==void 0?{code:le}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),W instanceof Cr?"cert-rejected":"failed"}}if(!g&&A.clientKey&&!ee&&!Fe){let _=await mS(A,e,n,h),L=await x();return _||L?"repaired":V?"cert-renewed":"not-due"}let xe=await ct(_=>{let L=t()-(_.lastAttemptAt??0);if(g)return L<LB(_.failureCount)?{result:"throttled"}:{next:{..._,lastAttemptAt:t()},result:"ok"};let W=_.lastError?.code!==void 0&&OB.has(_.lastError.code)?_B:cS;return L<W?{result:"throttled"}:_.failureCount&&L<fS(_.failureCount,_.keyTtlMs)?{result:"backoff"}:{next:{..._,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(xe!=="ok")return xe;try{let _=await i(I,H,B),L=await l().catch(()=>{}),W=ge({origin:I,clientKey:_.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:L,user:A.name,team:A.team}),le=W,ie=W.origin;if(Qe(A)){if(!Number.isInteger(A.fallbackPort)||A.fallbackPort<1||A.fallbackPort>65535)throw new Error("key-refresh proxy profile has no valid port");await h(A.fallbackPort)!==null&&(le=vn(W,A.fallbackPort),ie=`http://${ut}:${A.fallbackPort}`)}let gt=await d(le,ie);if(A.directMigration==="pending"&&le.viaLocalProxy===!0){let dt=await d(le,W.origin);gt=gt!==!1&&dt!==!1}if(gt===!1)throw new Error("one or more configured tools rejected the refreshed key");let pe=await n().catch(()=>A),fe=null,de;pe.enrolledCert&&await tm(pe,H.sig,B,o)&&(de=Ed(_.key),fe={...pe,clientKey:_.key,clientKeyExpiresAt:_.expiresAt??pe.clientKeyExpiresAt},await r(fe));let Y=_.expiresAt?Date.parse(_.expiresAt):NaN,Ie=Ci(A)??(Number.isFinite(Y)&&Y-t()>0?Y-t():void 0);return await Ai(({lastError:dt,...wt})=>({...wt,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ie??wt.keyTtlMs,...de?{ownKeys:em(wt.ownKeys,H.sig,de)}:{}}),{now:t,readState:a,writeState:s}),fe&&await mS(fe,e,n,h),await E(fe?"repaired":"repair_failed"),await x(),"refreshed"}catch(_){let L=lS(_);return await Ai(W=>({...W,lastAttemptAt:t(),failureCount:(W.failureCount??0)+1,lastError:{name:_ instanceof Error?_.name:"Error",...L!==void 0?{code:L}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),_ instanceof It?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await x()}catch{}}};import{readFile as iU}from"node:fs/promises";import{isAbsolute as cU,posix as OS,win32 as cm}from"node:path";var sm=1e4,tU=900*1e3,xS="tnt_",nU=/^\/sso\/([^/]+)\/?$/,rU=/^\/i\/([^/]+)\/?$/,oU=e=>{let t=e.match(nU);if(t)return t[1];let n=e.match(rU);return n?.[1].startsWith(xS)?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=oU(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(xS))return{cpOrigin:Gn(),tenantId:t}},wo=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}},im=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)}},aU=e=>new Promise(t=>setTimeout(t,e)),Od=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??gd)(),a;try{a=await im(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},sm,n)}catch(h){throw new wo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${mt(h)}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new wo(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 wo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??tU,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}`),sU(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},sU=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},_d=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??aU,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 im(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},sm,o)}catch(c){throw new Gt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${mt(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 ES="sdc_",IS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(ES))return{cpOrigin:Gn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!jh(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(ES)))return{cpOrigin:n.origin,claim:r}},RS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??gd)(),o;try{o=await im(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},sm,t)}catch(s){throw new Gt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${mt(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 Si=(e=process.platform,t=process.env)=>e==="darwin"?OS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?cm.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):OS.join("/etc","anyray","bootstrap.json"),lU=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_S=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(cU(e)||cm.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),dU=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=Si())=>{try{let t=await iU(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!lU(n)||n.v!==1||typeof n.sso!="string")return;let r=Rt(n.sso);if(!r)return;let o=dU(n.gateway)?n.gateway:void 0,a=_S(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},TS=(e,t,n)=>{let r=Rt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!_S(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 NU}from"node:child_process";import{chmod as uU,readFile as pU,rm as PS,writeFile as fU}from"node:fs/promises";import{join as hU}from"node:path";var lm=()=>hU(q(),"sso-gate.json"),mU=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))},Er=async()=>{try{let e=JSON.parse(await pU(lm(),"utf-8"));return mU(e)?e:null}catch{return null}},yU=0,Td=async e=>{await kt();let t=lm(),n=`${t}.${process.pid}.${yU++}.tmp`;try{await fU(n,`${JSON.stringify(e)}
297
+ `,{mode:384}),await uU(n,384),await he(n,t)}catch(r){throw await PS(n,{force:!0}).catch(()=>{}),r}},LS=async()=>{await PS(lm(),{force:!0}).catch(()=>{})},DS=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 bU}from"node:child_process";import{homedir as kU}from"node:os";import{join as AU}from"node:path";import{spawn as gU}from"node:child_process";import{platform as wU}from"node:os";var Ca=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=wU(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=gU(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var CU=3e4,vU=5*6e4,SU=30*6e4,EU=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},xU=()=>AU(kU(),".claude","settings.json"),IU=async e=>{try{let n=(await M(xU())).env;if(!n)return!1;let r=un(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}},RU=async e=>{await nr.apply(e,{dryRun:!1})},OU=()=>{let{command:e,args:t}=pn("__anyray-sso-poll");return{exe:e,args:t}},_U=()=>{let{exe:e,args:t}=OU(),n=bU(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))}}},TU=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},NS=(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}),va=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},$S=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
- `,im=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
301
+ `,dm=(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
- `,xU=e=>Math.min(gU,yU*2**Math.max(0,e-1)),IU=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?wU:xU(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Vn=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??P,o=t.saveProfile??te,a=t.loadDevKey??Be,s=t.readGateState??Er,i=t.writeGateState??Id,c=t.isProcessAlive??OS,l=t.startGrant??Ed,d=t.verify??an,u=t.routingIntact??AU,f=t.applyClaudeCode??CU,p=t.maybeSpawnRefresh??Sr,h=t.recordMint??Aa,m=t.reserveMint??bo,w=t.spawnPoller??SU,g=t.openBrowser??Ca;try{let y=Rt(e.sso);if(!y)return{exitCode:0};let b=await r(),v=await s(),S=b.enrolledCert?await a():void 0,E=EU(b),x=!!(b.enrolledCert&&S)&&Number.isFinite(E)&&E>n(),A=e.gateway??b.gateway;if(x&&b.enrolledCert&&S&&A){let V=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(V)&&V>n()&&b.clientKey){let me=_S(A,b,e.team,b.clientKey);return await u(me)?(V-n()<=tm()&&await p(),{exitCode:0}):(await f(me),va(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
305
- `))}let z;await m();try{z=await d(A,b.enrolledCert,S,{timeoutMs:1e4})}catch(me){if(!(me instanceof It))return va(e,im("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:A,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(_S(A,me,e.team,z.key)),{exitCode:0}}}if(v?.status==="pending"&&(v.userCode&&v.verificationUriComplete)&&(v.grantExpiresAt??0)>n()&&c(v.pollerPid)){if(e.sessionStart&&v.verificationUriComplete)try{g(v.verificationUriComplete)}catch{}return va(e,TS(v))}if(v){let V=IU(v,n());if(V)return va(e,im(V,y.cpOrigin))}let I;try{I=await l({cpOrigin:y.cpOrigin,tenantId:y.tenantId,gatewayUrl:e.gateway,now:n})}catch(V){let W=V instanceof ko?V.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:v?.lastFailure===W?(v.failureCount??0)+1:1,lastFailure:W}),va(e,im(W,y.cpOrigin))}let T={v:1,status:"pending",userCode:I.userCode,verificationUriComplete:I.verificationUriComplete,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,lastAttemptAt:n(),failureCount:0};await i(T);let B=w(),X={...T,pollerPid:B.pid};if(await i(X),B.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 va(e,TS(X))}catch{return{exitCode:0}}},RU=async()=>{try{for await(let e of process.stdin);}catch{}},PS=async e=>{await RU();try{let t=await Vn(bU(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var _U=6e4,TU=10*6e4,Yn=(e,t)=>{let n=e[t];return typeof n=="string"?n:Array.isArray(n)?n[0]:void 0},PU=e=>{if(Yn(e,"x-anyray-api-key")?.trim())return!0;let t=Yn(e,"authorization")?.trim()??"";return/^bearer\s+\S+/i.test(t)?!0:(Yn(e,"x-api-key")?.trim()??"").startsWith("ark_")},DS=e=>{if(Yn(e,"x-anyray-api-key")?.trim())return!0;let t=Yn(e,"authorization")?.trim()??"";return/^bearer\s+ark_\S+/i.test(t)?!0:(Yn(e,"x-api-key")?.trim()??"").startsWith("ark_")},NS=e=>{let t=Yn(e,"x-anyray-api-key")?.trim();if(t?.startsWith("ark_"))return{key:t,slot:"x-anyray-api-key"};let r=(Yn(e,"authorization")?.trim()??"").match(/^bearer\s+(ark_\S+)/i);if(r)return{key:r[1],slot:"authorization"};let o=Yn(e,"x-api-key")?.trim()??"";return o.startsWith("ark_")?{key:o,slot:"x-api-key"}:void 0},LU=e=>e.split("?")[0].includes("/v1/"),LS=e=>e.replace(/[^\x20-\x7e]/g,"").replace(/["'`\\$]/g,"").slice(0,300),DU=(e,t,n=process.platform,r=OU)=>{let o=LS(e),a=LS(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{}},$S=(e={})=>{let t=e.readBootstrap??Gt,n=e.ssoGate??Vn,r=e.readState??Er,o=e.notify??DU,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<TU||(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(!LU(u)||PU(f)||l||a()-s<_U)return;s=a(),l=!0,d().catch(()=>{}).finally(()=>{l=!1})}catch{}}}};import{watch as NU}from"node:fs";import{basename as $U,dirname as MU}from"node:path";var FU=2e3,BU=6e4,Sa=e=>e instanceof Error?e.name:"UnknownError",UU=(e,t,n)=>{let r=NU(e,{persistent:!1},(o,a)=>{t(a==null?null:a.toString())});return r.on("error",n),r},HU=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 Ar(n,r.toolOrigin);return o.length===0?!1:(await gt(o,r.target),!0)}catch{return!1}},MS=(e={})=>{let t=e.loadProfile??P,n=e.adapters??oe,r=e.probe??ke,o=e.repairDrift??(A=>HU(A,r)),a=e.resolveProfileFile??Io,s=e.watchDir??UU,i=e.debounceMs??FU,c=e.repairFloorMs??BU,l=e.now??Date.now,d=e.logError??(A=>console.error(`anyray refresh proxy: drift watcher ${A}`)),u=!1,f=0,p,h=Promise.resolve(),m=new Map,w=A=>{let I=m.get(A);if(I){m.delete(A);try{I.handle.close()}catch{}}},g=()=>{if(u)return;p!==void 0&&clearTimeout(p);let A=setTimeout(()=>{p=void 0,h=h.then(E).catch(()=>{})},i);A.unref?.(),p=A},y=A=>I=>{if(!u)try{let T=m.get(A);if(!T||I!==null&&!T.files.has(I))return;g()}catch(T){d(Sa(T))}},b=A=>I=>{d(Sa(I)),w(A),g()},v=async A=>{let I=[],T=new Set(A.managedTools??[]);for(let V of n)if(!(!T.has(V.id)||!V.watchPaths))try{I.push(...await V.watchPaths())}catch(W){d(Sa(W))}let B=await a().catch(()=>{});B&&I.push(B);let X=new Map;for(let V of I){let W=MU(V),z=X.get(W)??new Set;z.add($U(V)),X.set(W,z)}return X},S=async A=>{let I=await v(A);if(!u){for(let T of[...m.keys()])I.has(T)||w(T);for(let[T,B]of I){let X=m.get(T);if(X){X.files=B;continue}try{m.set(T,{handle:s(T,y(T),b(T)),files:B})}catch(V){d(Sa(V))}}}},E=async()=>{if(!u)try{let A=await t().catch(()=>({}));if(await S(A),u||l()-f<c)return;f=l(),await o(A).catch(()=>!1)}catch(A){d(Sa(A))}};return{ready:t().then(A=>S(A)).catch(A=>d(Sa(A))),stop:()=>{u=!0,p!==void 0&&(clearTimeout(p),p=void 0);for(let A of[...m.keys()])w(A)}}};import{randomBytes as WU}from"node:crypto";import{chmod as KU,readFile as GU,rm as US,writeFile as jU}from"node:fs/promises";import{join as VU}from"node:path";var YU=/^[A-Za-z0-9_-]{43}$/,ZU=3600*1e3,FS=3900,XU=1e4,cm=()=>VU(q(),"device-token.json"),JU=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&YU.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},HS=async()=>{try{let e=JSON.parse(await GU(cm(),"utf-8"));return JU(e)?e:null}catch{return null}},zU=0,qU=async e=>{await kt();let t=cm(),n=`${t}.${process.pid}.${zU++}.tmp`;try{await jU(n,`${JSON.stringify(e)}
306
- `,{mode:384}),await KU(n,384),await fe(n,t)}catch(r){throw await US(n,{force:!0}).catch(()=>{}),r}},Rd=async()=>{await US(cm(),{force:!0}).catch(()=>{})},QU=()=>WU(32).toString("base64url"),e1=e=>e instanceof Error?e.name:"UnknownError",t1=(e,t)=>{let n=setInterval(e,t);return n.unref(),{stop:()=>clearInterval(n)}},BS=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??P)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=QU(),i=new AbortController,c=setTimeout(()=>i.abort(),XU),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:FS}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await qU({v:1,token:s,expiresAt:t()+FS*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${e1(r)}`),!1}},WS=(e={})=>{BS(e);let n=(e.scheduleRotation??t1)(()=>{BS(e)},ZU);return{stop:()=>n.stop()}};var r1=1800*1e3,KS=50,o1=15e3,a1=1e3,YS=as*1e3-1e4,GS=15*6e4,s1=75e3,i1=8e4,c1=async(e,t,n={})=>{let r=n.budgetMs??as*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 dm(o)}},Od=e=>{let t=e instanceof Error?e.name:"unknown",n=e?.code;return typeof n=="string"?`${t} ${n}`:t},l1=(e,t={})=>{let n=t.exit??(f=>process.exit(f)),r=t.exitCode??0,o=t.hardCapMs??YS,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()},ZS=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),d1=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]),u1=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),p1=45*1e3,f1=600*1e3,h1=new Set(["host","connection","keep-alive","proxy-connection","content-length","transfer-encoding","upgrade"]),m1=new Set(["content-encoding","content-length","transfer-encoding","connection","keep-alive"]),y1=new Set(["missing_key","key_expired"]),g1=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"&&y1.has(r)}catch{return!1}},w1=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(h1.has(n.toLowerCase())||(t[n.toLowerCase()]=Array.isArray(r)?r.join(", "):r));return t},b1=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))}),k1=(e,t)=>e?ZS.has(e)?!0:d1.has(e)&&u1.has(t.toUpperCase()):!1,A1=new Set(["127.0.0.1","localhost","[::1]","::1"]),C1=e=>{if(e[Gu]===void 0||e.origin!==void 0)return!1;let t=(e.host??"").replace(/:\d+$/,"");return A1.has(t)},v1=(e,t)=>{let n=(t??"").split("?")[0];return e==="GET"&&n==="/__anyray/health"||e==="POST"&&n==="/__anyray/shutdown"},S1=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}}}},dm=e=>new Promise(t=>setTimeout(t,e)),jS=async(e,t,n,r,o,a=o1)=>{let s=Date.now()+a,i=KS,c=!1;for(;;){let l=await S1(e,t,n,r);if("res"in l||!o())return l;let d=l.failure.code;if(d!==void 0&&ZS.has(d)){if(Date.now()+i>s)return l;await dm(i),i=Math.min(i*2,a1)}else if(!c&&k1(d,t))c=!0,await dm(KS);else return l;if(!o())return l}},lm=async(e,t)=>{let n={};if(t.headers.forEach((s,i)=>{m1.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()},VS=(e,t,n)=>{e.headersSent||e.destroyed||(e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify({error:{type:"anyray_proxy",message:n}})))},E1=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:be,inFlight:n}));return}if(c==="POST"&&(i==="/__anyray/shutdown"||i.startsWith("/__anyray/shutdown?"))){if(!C1(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):"",v=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:v});return}let l=await b1(a),d=w1(a.headers),u=NS(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&&!DS(a.headers)){h=!0;try{p=await e.resolveClientKey(),p&&f(p)}catch{}}let m=await jS(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("failure"in m){VS(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(g1(b)){let v=h?await e.recoverInjectedKey().catch(()=>{}):await e.resolveClientKey().catch(()=>{}),S=p??u?.key;if(v!==void 0&&v!==S){f(v);let E=await jS(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("res"in E){E.res.status===401&&w(),await lm(s,E.res);return}}}w(),await lm(s,new Response(b,{status:m.res.status,headers:m.res.headers}));return}w(),await lm(s,m.res)},o=n1.createServer((a,s)=>{s.on("error",()=>{}),v1(a.method,a.url)||(n++,s.once("close",()=>{n--})),r(a,s).catch(i=>{console.error(`anyray refresh proxy: request error ${Od(i)}`),s.headersSent?s.end():VS(s,502,"anyray proxy internal error")})});return o.keepAliveTimeout=s1,o.headersTimeout=i1,o.on("error",a=>{a.code!=="EADDRINUSE"&&console.error(`anyray refresh proxy: server error ${Od(a)}`)}),{server:o,inFlight:()=>n}},XS=5e3,x1=2e3,I1=(e={})=>{let t=e.now??Date.now,n=e.loadProfile??P,r=e.refresh??(()=>Qe()),o=e.remintBudgetMs??XS,a,s=-1/0,i=3e4;return Object.assign(async()=>{let l=a===void 0?x1: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<=ki(d)&&Promise.resolve().then(r).catch(()=>{})}return a=d.clientKey,s=t(),a},{invalidate:()=>{a=void 0,s=-1/0}})},JS=async()=>{let e=await P(),t=e.fallbackPort,n=e.gateway?.replace(/\/+$/,"");if(!t||!n){let p=await Gt().catch(()=>{});p?.gateway&&(n??=p.gateway.replace(/\/+$/,""),t??=Ae)}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=$S(),o=I1(),a=E1({port:t,remoteOrigin:n,onGatewayUnauthorized:(p,h)=>r.onGatewayUnauthorized(p,h),resolveClientKey:o,recoverInjectedKey:async()=>(o.invalidate(),await Promise.race([Qe({force:!0}).catch(()=>{}),new Promise(p=>setTimeout(p,XS).unref?.())]),o()),isOwnClientKey:p=>fS(p),onShutdown:p=>f(0,{drain:p.drain})});Qe().catch(()=>{});let s=setInterval(()=>{Qe().catch(()=>{})},r1);s.unref();let i=MS(),c=WS(),l=Date.now();a.server.on("request",()=>{l=Date.now()});let d=setInterval(()=>{Date.now()-l>f1||fetch(`${n}/`,{method:"HEAD"}).catch(()=>{})},p1);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"?GS:YS;qg(Date.now()+m),l1(a.server,{exitCode:p,inFlight:a.inFlight,ceilingMs:h.drain==="idle"?GS:void 0,exit:w=>{Zu(),process.exit(w)}})};return process.once("SIGTERM",()=>f()),process.once("SIGINT",()=>f()),process.on("uncaughtException",p=>{console.error(`anyray refresh proxy: uncaught exception ${Od(p)}`),f(1)}),process.on("unhandledRejection",p=>{console.error(`anyray refresh proxy: unhandled rejection ${p instanceof Error?Od(p):typeof p}`),f(1)}),Zu(),await Yg(ns()).catch(()=>{}),await c1(a.server,t),console.error(`anyray refresh proxy listening on 127.0.0.1:${t} \u2192 ${n}`),await new Promise(()=>{}),0};import{platform as R1}from"node:os";import{stat as O1}from"node:fs/promises";import{spawnSync as _1}from"node:child_process";var zS="/Applications/Anyray Connect Tray.app",T1=new Set(["V53XMA78UF"]),P1="ai.anyray.connect-tray",L1=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,D1=e=>{let t=_1("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
307
- ${t.stderr??""}`}},N1=async e=>{try{return(await O1(e)).isDirectory()}catch{return!1}},$1=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},um=async(e,t={})=>{if((t.os??R1())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??N1)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??D1;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?$1(a.output):void 0;return s?T1.has(s)?L1(a.output)!==P1?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},Ao=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await um(n,t)).ok?"healthy":"gone"},pm=async(e={})=>{try{let t=e.load??P,n=await t(),r=await Ao(n,e);if(r!=="gone")return r;let o=e.installScheduler??sr,a=e.installDaemon??Lt;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await a({port:n.fallbackPort??Ae,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??te)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var M1={"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."},F1=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},B1=async(e,t)=>{let n=t.stderr??console.error,r=F1(e,"--app-path")??zS,o=await um(r,t);if(!o.ok)return n(M1[o.reason]),1;let s=await(t.load??P)();await(t.save??te)({...s,persistenceOwner:"tray",trayAppPath:r});let c=t.uninstallScheduler??ir,l=t.uninstallDaemon??Jt;return await c().catch(()=>{}),await l(s.fallbackPort).catch(()=>{}),0},U1=async e=>{let t=e.load??P,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??sr,o=e.installDaemon??Lt;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await o({port:n.fallbackPort??Ae,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??te)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},qS=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await B1(e,t):e.includes("--release-tray")?await U1(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 QS,platform as eE}from"node:os";import{join as Ea}from"node:path";import{access as H1}from"node:fs/promises";var fm=(e=eE(),t=QS())=>{let n=a=>[Ea(t,"Library","LaunchAgents",`${a}.plist`)],r=Ea(t,".config","systemd","user"),o=a=>[Ea(t,".anyray","logs",a)];return e==="darwin"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:os,paths:n(os),dataPaths:o("connect-daemon.log")},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:us,paths:n(us),dataPaths:o("connect-refresh.log")}]:e==="linux"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:`${ar}.service`,paths:[Ea(r,`${ar}.service`)]},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:`${Wr}.timer`,paths:[Ea(r,`${Wr}.timer`),Ea(r,`${Wr}.service`)]}]:e==="win32"?[{kind:"scheduler",title:"key-refresh scheduler",supervisorName:kc,paths:[]}]:[]},tE=async e=>{try{return await H1(e),!0}catch{return!1}},Ci=async(e,t={})=>{let n=t.exists??tE;for(let r of fm(t.os,t.home))if(r.kind===e){for(let o of r.paths)if(await n(o))return!0}return!1},nE=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable)return t;let n=e.exists??tE,r=fm(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},W1=[os,`${ar}.service`,us,`${Wr}.timer`,`${Wr}.service`,kc],rE=(e,t=eE(),n=QS(),r=rr())=>{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 fm(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:",...W1.map(a=>` - ${a}`)),o};var hm=5e3,oE=3e4,K1=1440*60*1e3,G1=e=>new Promise(t=>setTimeout(t,e)),j1=async(e=P,t=Dt)=>(await _e(e,t))?.target,V1=e=>Ht(e)?.quitGated,aE=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??V1,o=t.readPending??Vc,a=t.clearPending??Op,s=t.targetFromProfile??j1,i=t.sleep??G1,c=t.now??Date.now,l=t.maxWaitMs??K1;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=hm;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=hm;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=hm}}catch{return 0}};import{writeFileSync as J1}from"node:fs";import{chmod as mm,stat as z1}from"node:fs/promises";import{platform as gm}from"node:os";import{dirname as lE,isAbsolute as q1}from"node:path";var xa=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,_d=xa(process.stdout,process.env),sE=xa(process.stderr,process.env),Ia=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,j=e=>Ia("1",e,_d),C=e=>Ia("2",e,_d),Y1=e=>Ia("32",e,_d),Z1=e=>Ia("33",e,sE),X1=e=>Ia("31",e,sE),et=e=>Ia("36",e,_d),k=e=>console.log(e),K=e=>console.log(`
308
- ${j(e)}`),F=e=>console.log(C(e)),$=e=>console.log(`${Y1("\u2713")} ${e}`),N=e=>console.error(`${Z1("!")} ${e}`),O=e=>console.error(`${X1("\u2717")} ${e}`);var ym=`${j("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
304
+ `,PU=e=>Math.min(vU,CU*2**Math.max(0,e-1)),LU=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?SU:PU(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Vn=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??P,o=t.saveProfile??te,a=t.loadDevKey??Be,s=t.readGateState??Er,i=t.writeGateState??Td,c=t.isProcessAlive??DS,l=t.startGrant??Od,d=t.verify??sn,u=t.routingIntact??IU,f=t.applyClaudeCode??RU,p=t.maybeSpawnRefresh??Sr,h=t.recordMint??Aa,m=t.reserveMint??go,w=t.spawnPoller??_U,g=t.openBrowser??Ca;try{let y=Rt(e.sso);if(!y)return{exitCode:0};let b=await r(),v=await s(),S=b.enrolledCert?await a():void 0,E=TU(b),x=!!(b.enrolledCert&&S)&&Number.isFinite(E)&&E>n(),A=e.gateway??b.gateway;if(x&&b.enrolledCert&&S&&A){let V=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(V)&&V>n()&&b.clientKey){let ye=NS(A,b,e.team,b.clientKey);return await u(ye)?(V-n()<=om()&&await p(),{exitCode:0}):(await f(ye),va(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
305
+ `))}let z;await m();try{z=await d(A,b.enrolledCert,S,{timeoutMs:1e4})}catch(ye){if(!(ye instanceof It))return va(e,dm("gateway-unreachable",y.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(z){let ye={...b,gateway:A,name:z.user,team:e.team??z.team??b.team,clientKey:z.key,clientKeyExpiresAt:z.expiresAt,authMode:"subscription"};return await o(ye),await h({expiresAt:z.expiresAt}),await f(NS(A,ye,e.team,z.key)),{exitCode:0}}}if(v?.status==="pending"&&(v.userCode&&v.verificationUriComplete)&&(v.grantExpiresAt??0)>n()&&c(v.pollerPid)){if(e.sessionStart&&v.verificationUriComplete)try{g(v.verificationUriComplete)}catch{}return va(e,$S(v))}if(v){let V=LU(v,n());if(V)return va(e,dm(V,y.cpOrigin))}let I;try{I=await l({cpOrigin:y.cpOrigin,tenantId:y.tenantId,gatewayUrl:e.gateway,now:n})}catch(V){let H=V instanceof wo?V.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:v?.lastFailure===H?(v.failureCount??0)+1:1,lastFailure:H}),va(e,dm(H,y.cpOrigin))}let T={v:1,status:"pending",userCode:I.userCode,verificationUriComplete:I.verificationUriComplete,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,lastAttemptAt:n(),failureCount:0};await i(T);let B=w(),X={...T,pollerPid:B.pid};if(await i(X),B.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 va(e,$S(X))}catch{return{exitCode:0}}},DU=async()=>{try{for await(let e of process.stdin);}catch{}},MS=async e=>{await DU();try{let t=await Vn(EU(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var $U=6e4,MU=10*6e4,Yn=(e,t)=>{let n=e[t];return typeof n=="string"?n:Array.isArray(n)?n[0]:void 0},FU=e=>{if(Yn(e,"x-anyray-api-key")?.trim())return!0;let t=Yn(e,"authorization")?.trim()??"";return/^bearer\s+\S+/i.test(t)?!0:(Yn(e,"x-api-key")?.trim()??"").startsWith("ark_")},BS=e=>{if(Yn(e,"x-anyray-api-key")?.trim())return!0;let t=Yn(e,"authorization")?.trim()??"";return/^bearer\s+ark_\S+/i.test(t)?!0:(Yn(e,"x-api-key")?.trim()??"").startsWith("ark_")},US=e=>{let t=Yn(e,"x-anyray-api-key")?.trim();if(t?.startsWith("ark_"))return{key:t,slot:"x-anyray-api-key"};let r=(Yn(e,"authorization")?.trim()??"").match(/^bearer\s+(ark_\S+)/i);if(r)return{key:r[1],slot:"authorization"};let o=Yn(e,"x-api-key")?.trim()??"";return o.startsWith("ark_")?{key:o,slot:"x-api-key"}:void 0},BU=e=>e.split("?")[0].includes("/v1/"),FS=e=>e.replace(/[^\x20-\x7e]/g,"").replace(/["'`\\$]/g,"").slice(0,300),UU=(e,t,n=process.platform,r=NU)=>{let o=FS(e),a=FS(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{}},HS=(e={})=>{let t=e.readBootstrap??jt,n=e.ssoGate??Vn,r=e.readState??Er,o=e.notify??UU,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<MU||(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(!BU(u)||FU(f)||l||a()-s<$U)return;s=a(),l=!0,d().catch(()=>{}).finally(()=>{l=!1})}catch{}}}};import{watch as HU}from"node:fs";import{basename as WU,dirname as KU}from"node:path";var GU=2e3,jU=6e4,Sa=e=>e instanceof Error?e.name:"UnknownError",VU=(e,t,n)=>{let r=HU(e,{persistent:!1},(o,a)=>{t(a==null?null:a.toString())});return r.on("error",n),r},YU=async(e,t)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Te(async()=>e,void 0,t);if(!r)return!1;let o=await Ar(n,r.toolOrigin);return o.length===0?!1:(await ht(o,r.target),!0)}catch{return!1}},WS=(e={})=>{let t=e.loadProfile??P,n=e.adapters??oe,r=e.probe??ke,o=e.repairDrift??(A=>YU(A,r)),a=e.resolveProfileFile??Io,s=e.watchDir??VU,i=e.debounceMs??GU,c=e.repairFloorMs??jU,l=e.now??Date.now,d=e.logError??(A=>console.error(`anyray refresh proxy: drift watcher ${A}`)),u=!1,f=0,p,h=Promise.resolve(),m=new Map,w=A=>{let I=m.get(A);if(I){m.delete(A);try{I.handle.close()}catch{}}},g=()=>{if(u)return;p!==void 0&&clearTimeout(p);let A=setTimeout(()=>{p=void 0,h=h.then(E).catch(()=>{})},i);A.unref?.(),p=A},y=A=>I=>{if(!u)try{let T=m.get(A);if(!T||I!==null&&!T.files.has(I))return;g()}catch(T){d(Sa(T))}},b=A=>I=>{d(Sa(I)),w(A),g()},v=async A=>{let I=[],T=new Set(A.managedTools??[]);for(let V of n)if(!(!T.has(V.id)||!V.watchPaths))try{I.push(...await V.watchPaths())}catch(H){d(Sa(H))}let B=await a().catch(()=>{});B&&I.push(B);let X=new Map;for(let V of I){let H=KU(V),z=X.get(H)??new Set;z.add(WU(V)),X.set(H,z)}return X},S=async A=>{let I=await v(A);if(!u){for(let T of[...m.keys()])I.has(T)||w(T);for(let[T,B]of I){let X=m.get(T);if(X){X.files=B;continue}try{m.set(T,{handle:s(T,y(T),b(T)),files:B})}catch(V){d(Sa(V))}}}},E=async()=>{if(!u)try{let A=await t().catch(()=>({}));if(await S(A),u||l()-f<c)return;f=l(),await o(A).catch(()=>!1)}catch(A){d(Sa(A))}};return{ready:t().then(A=>S(A)).catch(A=>d(Sa(A))),stop:()=>{u=!0,p!==void 0&&(clearTimeout(p),p=void 0);for(let A of[...m.keys()])w(A)}}};import{randomBytes as ZU}from"node:crypto";import{chmod as XU,readFile as JU,rm as jS,writeFile as zU}from"node:fs/promises";import{join as qU}from"node:path";var QU=/^[A-Za-z0-9_-]{43}$/,e1=3600*1e3,KS=3900,t1=1e4,um=()=>qU(q(),"device-token.json"),n1=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&QU.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},VS=async()=>{try{let e=JSON.parse(await JU(um(),"utf-8"));return n1(e)?e:null}catch{return null}},r1=0,o1=async e=>{await kt();let t=um(),n=`${t}.${process.pid}.${r1++}.tmp`;try{await zU(n,`${JSON.stringify(e)}
306
+ `,{mode:384}),await XU(n,384),await he(n,t)}catch(r){throw await jS(n,{force:!0}).catch(()=>{}),r}},Pd=async()=>{await jS(um(),{force:!0}).catch(()=>{})},a1=()=>ZU(32).toString("base64url"),s1=e=>e instanceof Error?e.name:"UnknownError",i1=(e,t)=>{let n=setInterval(e,t);return n.unref(),{stop:()=>clearInterval(n)}},GS=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??P)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=a1(),i=new AbortController,c=setTimeout(()=>i.abort(),t1),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:KS}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await o1({v:1,token:s,expiresAt:t()+KS*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${s1(r)}`),!1}},YS=(e={})=>{GS(e);let n=(e.scheduleRotation??i1)(()=>{GS(e)},e1);return{stop:()=>n.stop()}};var l1=1800*1e3,ZS=50,d1=15e3,u1=1e3,qS=cs*1e3-1e4,XS=15*6e4,p1=75e3,f1=8e4,h1=async(e,t,n={})=>{let r=n.budgetMs??cs*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 fm(o)}},Ld=e=>{let t=e instanceof Error?e.name:"unknown",n=e?.code;return typeof n=="string"?`${t} ${n}`:t},m1=(e,t={})=>{let n=t.exit??(f=>process.exit(f)),r=t.exitCode??0,o=t.hardCapMs??qS,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()},QS=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),y1=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]),g1=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),w1=45*1e3,b1=600*1e3,k1=new Set(["host","connection","keep-alive","proxy-connection","content-length","transfer-encoding","upgrade"]),A1=new Set(["content-encoding","content-length","transfer-encoding","connection","keep-alive"]),C1=new Set(["missing_key","key_expired"]),v1=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"&&C1.has(r)}catch{return!1}},S1=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(k1.has(n.toLowerCase())||(t[n.toLowerCase()]=Array.isArray(r)?r.join(", "):r));return t},E1=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))}),x1=(e,t)=>e?QS.has(e)?!0:y1.has(e)&&g1.has(t.toUpperCase()):!1,I1=new Set(["127.0.0.1","localhost","[::1]","::1"]),R1=e=>{if(e[Yu]===void 0||e.origin!==void 0)return!1;let t=(e.host??"").replace(/:\d+$/,"");return I1.has(t)},O1=(e,t)=>{let n=(t??"").split("?")[0];return e==="GET"&&n==="/__anyray/health"||e==="POST"&&n==="/__anyray/shutdown"},_1=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}}}},fm=e=>new Promise(t=>setTimeout(t,e)),JS=async(e,t,n,r,o,a=d1)=>{let s=Date.now()+a,i=ZS,c=!1;for(;;){let l=await _1(e,t,n,r);if("res"in l||!o())return l;let d=l.failure.code;if(d!==void 0&&QS.has(d)){if(Date.now()+i>s)return l;await fm(i),i=Math.min(i*2,u1)}else if(!c&&x1(d,t))c=!0,await fm(ZS);else return l;if(!o())return l}},pm=async(e,t)=>{let n={};if(t.headers.forEach((s,i)=>{A1.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()},zS=(e,t,n)=>{e.headersSent||e.destroyed||(e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify({error:{type:"anyray_proxy",message:n}})))},T1=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:be,inFlight:n}));return}if(c==="POST"&&(i==="/__anyray/shutdown"||i.startsWith("/__anyray/shutdown?"))){if(!R1(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):"",v=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:v});return}let l=await E1(a),d=S1(a.headers),u=US(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&&!BS(a.headers)){h=!0;try{p=await e.resolveClientKey(),p&&f(p)}catch{}}let m=await JS(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("failure"in m){zS(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(v1(b)){let v=h?await e.recoverInjectedKey().catch(()=>{}):await e.resolveClientKey().catch(()=>{}),S=p??u?.key;if(v!==void 0&&v!==S){f(v);let E=await JS(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("res"in E){E.res.status===401&&w(),await pm(s,E.res);return}}}w(),await pm(s,new Response(b,{status:m.res.status,headers:m.res.headers}));return}w(),await pm(s,m.res)},o=c1.createServer((a,s)=>{s.on("error",()=>{}),O1(a.method,a.url)||(n++,s.once("close",()=>{n--})),r(a,s).catch(i=>{console.error(`anyray refresh proxy: request error ${Ld(i)}`),s.headersSent?s.end():zS(s,502,"anyray proxy internal error")})});return o.keepAliveTimeout=p1,o.headersTimeout=f1,o.on("error",a=>{a.code!=="EADDRINUSE"&&console.error(`anyray refresh proxy: server error ${Ld(a)}`)}),{server:o,inFlight:()=>n}},eE=5e3,P1=2e3,L1=(e={})=>{let t=e.now??Date.now,n=e.loadProfile??P,r=e.refresh??(()=>ze()),o=e.remintBudgetMs??eE,a,s=-1/0,i=3e4;return Object.assign(async()=>{let l=a===void 0?P1: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<=vi(d)&&Promise.resolve().then(r).catch(()=>{})}return a=d.clientKey,s=t(),a},{invalidate:()=>{a=void 0,s=-1/0}})},tE=async()=>{let e=await P(),t=e.fallbackPort,n=e.gateway?.replace(/\/+$/,"");if(!t||!n){let p=await jt().catch(()=>{});p?.gateway&&(n??=p.gateway.replace(/\/+$/,""),t??=Ae)}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=HS(),o=L1(),a=T1({port:t,remoteOrigin:n,onGatewayUnauthorized:(p,h)=>r.onGatewayUnauthorized(p,h),resolveClientKey:o,recoverInjectedKey:async()=>(o.invalidate(),await Promise.race([ze({force:!0}).catch(()=>{}),new Promise(p=>setTimeout(p,eE).unref?.())]),o()),isOwnClientKey:p=>wS(p),onShutdown:p=>f(0,{drain:p.drain})});ze().catch(()=>{});let s=setInterval(()=>{ze().catch(()=>{})},l1);s.unref();let i=WS(),c=YS(),l=Date.now();a.server.on("request",()=>{l=Date.now()});let d=setInterval(()=>{Date.now()-l>b1||fetch(`${n}/`,{method:"HEAD"}).catch(()=>{})},w1);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"?XS:qS;rw(Date.now()+m),m1(a.server,{exitCode:p,inFlight:a.inFlight,ceilingMs:h.drain==="idle"?XS:void 0,exit:w=>{zu(),process.exit(w)}})};return process.once("SIGTERM",()=>f()),process.once("SIGINT",()=>f()),process.on("uncaughtException",p=>{console.error(`anyray refresh proxy: uncaught exception ${Ld(p)}`),f(1)}),process.on("unhandledRejection",p=>{console.error(`anyray refresh proxy: unhandled rejection ${p instanceof Error?Ld(p):typeof p}`),f(1)}),zu(),await qg(as()).catch(()=>{}),await h1(a.server,t),console.error(`anyray refresh proxy listening on 127.0.0.1:${t} \u2192 ${n}`),await new Promise(()=>{}),0};import{platform as D1}from"node:os";import{stat as N1}from"node:fs/promises";import{spawnSync as $1}from"node:child_process";var nE="/Applications/Anyray Connect Tray.app",M1=new Set(["V53XMA78UF"]),F1="ai.anyray.connect-tray",B1=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,U1=e=>{let t=$1("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
307
+ ${t.stderr??""}`}},H1=async e=>{try{return(await N1(e)).isDirectory()}catch{return!1}},W1=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},hm=async(e,t={})=>{if((t.os??D1())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??H1)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??U1;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?W1(a.output):void 0;return s?M1.has(s)?B1(a.output)!==F1?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},bo=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await hm(n,t)).ok?"healthy":"gone"},mm=async(e={})=>{try{let t=e.load??P,n=await t(),r=await bo(n,e);if(r!=="gone")return r;let o=e.installScheduler??sr,a=e.installDaemon??Dt;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await a({port:n.fallbackPort??Ae,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??te)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var K1={"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."},G1=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},j1=async(e,t)=>{let n=t.stderr??console.error,r=G1(e,"--app-path")??nE,o=await hm(r,t);if(!o.ok)return n(K1[o.reason]),1;let s=await(t.load??P)();await(t.save??te)({...s,persistenceOwner:"tray",trayAppPath:r});let c=t.uninstallScheduler??ir,l=t.uninstallDaemon??zt;return await c().catch(()=>{}),await l(s.fallbackPort).catch(()=>{}),0},V1=async e=>{let t=e.load??P,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??sr,o=e.installDaemon??Dt;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await o({port:n.fallbackPort??Ae,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??te)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},rE=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await j1(e,t):e.includes("--release-tray")?await V1(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 oE,platform as aE}from"node:os";import{join as Ea}from"node:path";import{access as Y1}from"node:fs/promises";var ym=(e=aE(),t=oE())=>{let n=a=>[Ea(t,"Library","LaunchAgents",`${a}.plist`)],r=Ea(t,".config","systemd","user"),o=a=>[Ea(t,".anyray","logs",a)];return e==="darwin"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:is,paths:n(is),dataPaths:o("connect-daemon.log")},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:hs,paths:n(hs),dataPaths:o("connect-refresh.log")}]:e==="linux"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:`${ar}.service`,paths:[Ea(r,`${ar}.service`)]},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:`${Ur}.timer`,paths:[Ea(r,`${Ur}.timer`),Ea(r,`${Ur}.service`)]}]:e==="win32"?[{kind:"scheduler",title:"key-refresh scheduler",supervisorName:Sc,paths:[]}]:[]},sE=async e=>{try{return await Y1(e),!0}catch{return!1}},Ei=async(e,t={})=>{let n=t.exists??sE;for(let r of ym(t.os,t.home))if(r.kind===e){for(let o of r.paths)if(await n(o))return!0}return!1},iE=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable)return t;let n=e.exists??sE,r=ym(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},Z1=[is,`${ar}.service`,hs,`${Ur}.timer`,`${Ur}.service`,Sc],cE=(e,t=aE(),n=oE(),r=rr())=>{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 ym(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:",...Z1.map(a=>` - ${a}`)),o};var gm=5e3,lE=3e4,X1=1440*60*1e3,J1=e=>new Promise(t=>setTimeout(t,e)),z1=async(e=P,t=Nt)=>(await Te(e,t))?.target,q1=e=>Wt(e)?.quitGated,dE=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??q1,o=t.readPending??Jc,a=t.clearPending??Pp,s=t.targetFromProfile??z1,i=t.sleep??J1,c=t.now??Date.now,l=t.maxWaitMs??X1;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=gm;for(;;){let h=await o(n);if(!h||c()-f>l)return 0;if(d.isRunning()){await i(p),p=Math.min(lE,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=gm;continue}if((await u(h.op,m,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(p),p=Math.min(lE,p*2);continue}if(await a(n,h)!=="superseded")return 0;await i(p),p=gm}}catch{return 0}};import{writeFileSync as nH}from"node:fs";import{chmod as wm,stat as rH}from"node:fs/promises";import{platform as km}from"node:os";import{dirname as hE,isAbsolute as oH}from"node:path";var xa=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Dd=xa(process.stdout,process.env),uE=xa(process.stderr,process.env),Ia=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,j=e=>Ia("1",e,Dd),C=e=>Ia("2",e,Dd),Q1=e=>Ia("32",e,Dd),eH=e=>Ia("33",e,uE),tH=e=>Ia("31",e,uE),qe=e=>Ia("36",e,Dd),k=e=>console.log(e),K=e=>console.log(`
308
+ ${j(e)}`),F=e=>console.log(C(e)),$=e=>console.log(`${Q1("\u2713")} ${e}`),N=e=>console.error(`${eH("!")} ${e}`),O=e=>console.error(`${tH("\u2717")} ${e}`);var bm=`${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`,iE=["claude-code","jetbrains","shell","bootstrap","proxy"],Q1=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(!iE.includes(a))throw new Error(`unknown --tool ${a} (expected ${iE.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 Td(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:[En(Ja(t.binaryPath,[Ze]),{matcher:"*"})],UserPromptSubmit:[En(Ja(t.binaryPath,o),{timeout:30}),En(Ja(t.binaryPath,[qn]))],SessionStart:[En(Ja(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=un(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(xn.map(o=>[o.name,""])),...r}}:{env:r}}var eH=(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 Fr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,Du(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},tH=e=>{let t=e.env,n=Du(e);if(t){for(let r of Fr)r in t&&(delete t[r],n=!0);for(let{name:r}of xn)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 z1(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(lE(e))!==void 0}},uE=async(e,t)=>(t.dirExisted||await mm(lE(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await mm(e,420),{mode:420,keptRestricted:!1}):(await mm(e,t.mode),{mode:t.mode,keptRestricted:!0})),pE=(e,t)=>{t.keptRestricted&&(N(`${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(C(" 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.")))},fE=()=>process.getuid?.()===0,Ce=e=>{process.stderr.write(`${e}
397
- `)},Co=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}J1(e.out,t,"utf8"),Ce(C(`# Wrote ${e.out}`))},wm=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??""}),Pd=e=>q1(e)||/^[A-Za-z]:[\\/]/.test(e),hE=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&&!ce())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(!Pd(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}},mE=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${le(e.metadata)??"(none \u2014 pass --team)"}`],bm=(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{}},nH=(e,t)=>({agent_servers:{[Wn]:{command:e,args:[Jl,"claude",t,"jetbrains"],env:{}},[Kn]:{command:e,args:[Jl,"codex",t,"jetbrains"],env:{}}}}),cE=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=${Se(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${Se(e.anthropicBaseUrl)}`,""].join(`
398
- `),rH=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(!Pd(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(!Ql(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return Co(e,`${JSON.stringify(nH(e.bin,e.npx),null,2)}
399
- `),Ce(C("# acp.json for ~/.jetbrains/acp.json (per user).")),Ce(C(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ce(C("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ce(C("# 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},oH=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&&!Pd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return Co(e,xS(e.sso,e.gateway,e.bin)),Ce(C(`# Fleet bootstrap for ${Ai("linux")}`)),Ce(C(`# macOS: ${Ai("darwin")}`)),Ce(C(`# Windows: ${Ai("win32",{ProgramData:"C:\\ProgramData"})}`)),Ce(C("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},aH=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:${Ae}`});return Co(e,cE(n)),Ce(C(`# Loopback shell snippet \u2014 pair with \`managed --tool proxy\` (daemon on :${Ae}) and \`--tool bootstrap\`.`)),0}let t=wm(e);return Co(e,cE(t)),Ce(C("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),bm(t,Ce),0},sH=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(!Pd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");let t=e.servicePlatform??(gm()==="darwin"?"launchd":"systemd"),n={command:e.bin,args:[Ku]};return t==="launchd"?(Co(e,is(n)),Ce(C("# launchd agent \u2014 deploy to /Library/LaunchAgents/ai.anyray.connect.fallback.plist (loads for every user at login)."))):(Co(e,cs(n)),Ce(C("# systemd user unit \u2014 deploy to /etc/systemd/user/anyray-fallback.service, then `systemctl --global enable anyray-fallback.service`."))),Ce(C(`# Pair with \`--tool bootstrap\` (the daemon's fleet boot needs it) and the \`--tool shell --loopback\` snippet (port ${Ae}).`)),Ce(C(`# Push the binary to ${e.bin} before this unit.`)),0},iH=e=>{let t=wm(e),n=hE(e),r=n?Td(t,n):Td(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(Co(e,`${JSON.stringify(r,null,2)}
400
- `),Ce(C(`# managed-settings.json for ${Pt()}`)),n)Ce(C("# Deferred SSO: hooks only; no credential or managed env block.")),Ce(C(`# Push the binary to ${n.binaryPath} before this file.`)),Ce(C("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of mE(t))Ce(C(`# ${o}`));bm(t,Ce)}return 0},cH=async e=>{let t=gm();if(t!=="darwin"&&t!=="linux")return O("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!fE())return O("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),k(C(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=wm(e),r=hE(e);r||bm(n,u=>N(u.replace(/^!\s*/,"")));let o=Pt(t),a=await M(o),s=r?Td(n,r):Td(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?xn.filter(({name:u})=>{let f=a.env?.[u];return typeof f=="string"&&f.trim()!==""}):[],c=eH(a,s),l=await dE(o);await Z(o,c);let d=await uE(o,l);$(`Wrote ${o}`),pE(o,d);for(let{name:u,cloud:f}of i)N(`${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(C(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),k(C(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of mE(n))k(` ${C(u)}`);return k(C(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},lH=async()=>{let e=gm();if(e!=="darwin"&&e!=="linux")return O("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!fE())return O("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Pt(e);if(!await R(t))return k(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await M(t);if(!tH(n))return k(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await dE(t);await Z(t,n);let o=await uE(t,r);return $(`Removed Anyray-owned keys from ${t} (other keys left intact).`),pE(t,o),0},yE=async e=>{let t;try{t=Q1(e)}catch(n){return O(n instanceof Error?n.message:"invalid managed arguments"),k(`
401
- `+ym),1}if(t.help||e.length===0&&!t.mode)return k(ym),0;if(!t.mode)return O("Specify a mode: --print, --write, or --revert."),k(`
402
- `+ym),1;if(t.out!==void 0&&t.mode!=="print")return O(`--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 O(`--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"?(O(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?rH(t):n==="bootstrap"?oH(t):n==="proxy"?sH(t):aH(t):t.mode==="print"?iH(t):t.mode==="write"?await cH(t):await lH()}catch(n){return O(n instanceof Error?n.message:"managed settings failed"),1}};var dH=`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 Nd(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:[En(Qa(t.binaryPath,[Ve]),{matcher:"*"})],UserPromptSubmit:[En(Qa(t.binaryPath,o),{timeout:30}),En(Qa(t.binaryPath,[qn]))],SessionStart:[En(Qa(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=un(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(xn.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 $r)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,Mu(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=Mu(e);if(t){for(let r of $r)r in t&&(delete t[r],n=!0);for(let{name:r}of xn)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},mE=async e=>{let t=async n=>{try{return(await rH(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(hE(e))!==void 0}},yE=async(e,t)=>(t.dirExisted||await wm(hE(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await wm(e,420),{mode:420,keptRestricted:!1}):(await wm(e,t.mode),{mode:t.mode,keptRestricted:!0})),gE=(e,t)=>{t.keptRestricted&&(N(`${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(C(" 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.")))},wE=()=>process.getuid?.()===0,Ce=e=>{process.stderr.write(`${e}
397
+ `)},ko=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}nH(e.out,t,"utf8"),Ce(C(`# Wrote ${e.out}`))},Am=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??""}),$d=e=>oH(e)||/^[A-Za-z]:[\\/]/.test(e),bE=e=>{if(!e.sso)return;let t=Rt(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??_e();if(!e.bin&&!se())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(!$d(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}},kE=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${ce(e.metadata)??"(none \u2014 pass --team)"}`],Cm=(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:{[Wn]:{command:e,args:[ed,"claude",t,"jetbrains"],env:{}},[Kn]:{command:e,args:[ed,"codex",t,"jetbrains"],env:{}}}}),fE=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=${Se(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${Se(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(!$d(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(!rd(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return ko(e,`${JSON.stringify(cH(e.bin,e.npx),null,2)}
399
+ `),Ce(C("# acp.json for ~/.jetbrains/acp.json (per user).")),Ce(C(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ce(C("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ce(C("# 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&&!$d(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return ko(e,TS(e.sso,e.gateway,e.bin)),Ce(C(`# Fleet bootstrap for ${Si("linux")}`)),Ce(C(`# macOS: ${Si("darwin")}`)),Ce(C(`# Windows: ${Si("win32",{ProgramData:"C:\\ProgramData"})}`)),Ce(C("# 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:${Ae}`});return ko(e,fE(n)),Ce(C(`# Loopback shell snippet \u2014 pair with \`managed --tool proxy\` (daemon on :${Ae}) and \`--tool bootstrap\`.`)),0}let t=Am(e);return ko(e,fE(t)),Ce(C("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),Cm(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(!$d(e.bin))throw new Error("--bin must be an absolute fleet-stable path");let t=e.servicePlatform??(km()==="darwin"?"launchd":"systemd"),n={command:e.bin,args:[Vu]};return t==="launchd"?(ko(e,ds(n)),Ce(C("# launchd agent \u2014 deploy to /Library/LaunchAgents/ai.anyray.connect.fallback.plist (loads for every user at login)."))):(ko(e,us(n)),Ce(C("# systemd user unit \u2014 deploy to /etc/systemd/user/anyray-fallback.service, then `systemctl --global enable anyray-fallback.service`."))),Ce(C(`# Pair with \`--tool bootstrap\` (the daemon's fleet boot needs it) and the \`--tool shell --loopback\` snippet (port ${Ae}).`)),Ce(C(`# Push the binary to ${e.bin} before this unit.`)),0},fH=e=>{let t=Am(e),n=bE(e),r=n?Nd(t,n):Nd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(ko(e,`${JSON.stringify(r,null,2)}
400
+ `),Ce(C(`# managed-settings.json for ${Lt()}`)),n)Ce(C("# Deferred SSO: hooks only; no credential or managed env block.")),Ce(C(`# Push the binary to ${n.binaryPath} before this file.`)),Ce(C("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of kE(t))Ce(C(`# ${o}`));Cm(t,Ce)}return 0},hH=async e=>{let t=km();if(t!=="darwin"&&t!=="linux")return O("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!wE())return O("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),k(C(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=Am(e),r=bE(e);r||Cm(n,u=>N(u.replace(/^!\s*/,"")));let o=Lt(t),a=await M(o),s=r?Nd(n,r):Nd(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?xn.filter(({name:u})=>{let f=a.env?.[u];return typeof f=="string"&&f.trim()!==""}):[],c=sH(a,s),l=await mE(o);await Z(o,c);let d=await yE(o,l);$(`Wrote ${o}`),gE(o,d);for(let{name:u,cloud:f}of i)N(`${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(C(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),k(C(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of kE(n))k(` ${C(u)}`);return k(C(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},mH=async()=>{let e=km();if(e!=="darwin"&&e!=="linux")return O("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!wE())return O("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Lt(e);if(!await R(t))return k(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await M(t);if(!iH(n))return k(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await mE(t);await Z(t,n);let o=await yE(t,r);return $(`Removed Anyray-owned keys from ${t} (other keys left intact).`),gE(t,o),0},AE=async e=>{let t;try{t=aH(e)}catch(n){return O(n instanceof Error?n.message:"invalid managed arguments"),k(`
401
+ `+bm),1}if(t.help||e.length===0&&!t.mode)return k(bm),0;if(!t.mode)return O("Specify a mode: --print, --write, or --revert."),k(`
402
+ `+bm),1;if(t.out!==void 0&&t.mode!=="print")return O(`--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 O(`--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"?(O(`--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 O(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
- `,uH=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}},pH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=ki(e):!0},gE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},wE=(e,t)=>{if(!Ie(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},km=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,fH=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${km(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 \`${km(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 \`${km(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""}},Am=async(e={})=>{let t=e.loadProfile??P,n=e.refreshIfDue??Qe,r=e.now??Date.now,o=await t();if(gE(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||pH(o,r)){let i=fH(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(gE(s),!Ie(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},bE=e=>le({user:e.name,team:e.team}),hH=({profile:e,token:t})=>{let n={},r=bE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Cm=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=bE(e);return r&&(n["x-anyray-metadata"]=r),n},mH=e=>JSON.stringify(Cm(e)),kE=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=uH(e);if(o.help)return n.write(dH),0;let a=await Am(t);a.warning&&r.write(`${a.warning}
415
- `);let s=o.passthroughHeaders?mH(a):o.json?hH(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()<=vi(e):!0},CE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},vE=(e,t)=>{if(!Re(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},vm=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 \`${vm(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 \`${vm(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 \`${vm(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""}},Sm=async(e={})=>{let t=e.loadProfile??P,n=e.refreshIfDue??ze,r=e.now??Date.now,o=await t();if(CE(o),!o.enrolledCert){if(!vE(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(!vE(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(CE(s),!Re(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},SE=e=>ce({user:e.name,team:e.team}),kH=({profile:e,token:t})=>{let n={},r=SE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Em=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=SE(e);return r&&(n["x-anyray-metadata"]=r),n},AH=e=>JSON.stringify(Em(e)),EE=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 Sm(t);a.warning&&r.write(`${a.warning}
415
+ `);let s=o.passthroughHeaders?AH(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 AE=`anyray-connect models [<model-id>] [--json]
417
+ `),1}};var xE=`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
- `,yH=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},gH=e=>{let t=oe.find(n=>n.id===Qr);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},wH=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(" / ")},bH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Fs(t)}/${Pn(n)==="responses"?"responses":"chat/completions"}`,CE=async(e=[],t={})=>{let n=yH(e);if(n.help)return process.stdout.write(AE),0;if(n.error)return O(n.error),process.stdout.write(AE),1;let r=await(t.loadTarget??_e)();if(!r)return O("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??cl)({allowKeychainPrompt:!0});if(!a.token)return O("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??Xo)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=cf(c);if(l.length===0)return O("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:Pn(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=wH(h);k(` ${m} ${h.id.padEnd(24)}${w?C(w):""}`)}return F("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),F("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 O(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??il)(bH(o,i,d.id),{...sf(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return O(`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"?N("Could not verify the model over the lane (offline?) \u2014 applying anyway."):$(`'${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??gH)(o);if(p.status!=="configured"){for(let h of p.messages)k(h);return O("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 $(`Copilot CLI startup model \u2192 ${d.id}`),F("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var kH=`anyray-connect copilot-login
429
+ `,CH=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=oe.find(n=>n.id===zr);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${Hs(t)}/${Pn(n)==="responses"?"responses":"chat/completions"}`,IE=async(e=[],t={})=>{let n=CH(e);if(n.help)return process.stdout.write(xE),0;if(n.error)return O(n.error),process.stdout.write(xE),1;let r=await(t.loadTarget??Te)();if(!r)return O("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??pl)({allowKeychainPrompt:!0});if(!a.token)return O("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??Xo)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=uf(c);if(l.length===0)return O("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:Pn(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?C(w):""}`)}return F("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),F("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 O(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??ul)(EH(o,i,d.id),{...df(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return O(`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"?N("Could not verify the model over the lane (offline?) \u2014 applying anyway."):$(`'${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 O("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 $(`Copilot CLI startup model \u2192 ${d.id}`),F("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(kH),0;k(j("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??hk)();if(!n)return O("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;k(` 1. Open ${et(n.verificationUri)}`),k(` 2. Enter the code: ${j(n.userCode)}`),F(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??mk)(n);if(r.status!=="ok")return O(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??yk)(r.token,o);$(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??Qp)(r.token);if(s.verdict==="no-copilot")return O("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??Xo)(r.token,{},s.capiSegment,c);return l.length===0?N("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."):$(`${l.length} models available (e.g. ${l[0].id}).`),F("Now run: anyray-connect --tools copilot-cli"),0};var SE=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??P)()}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??HS)();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 PE,dirname as _H}from"node:path";import{mkdir as TH,readFile as Im,rm as LE,writeFile as DE}from"node:fs/promises";import{fstatSync as vH,openSync as SH,statSync as EH}from"node:fs";import{createInterface as xH}from"node:readline/promises";import{ReadStream as IH}from"node:tty";import{execFileSync as AH}from"node:child_process";import CH from"node:os";var Sm=e=>{try{return AH("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},EE=()=>{try{return CH.userInfo().username||void 0}catch{return}},xE=()=>Sm("user.name")??Sm("user.email")??EE()??"unknown",vm=e=>{try{return e()?.trim()||void 0}catch{return}},IE=(e={})=>{let t=e.gitConfig??Sm,n=vm(e.osUsername??EE),r=vm(()=>t("user.email"));return r||(vm(()=>t("user.name"))??n??"unknown")};var jt=()=>!!process.stdin.isTTY,RH=()=>{try{let e=vH(0);return e.isCharacterDevice()&&e.rdev===EH("/dev/tty").rdev}catch{return!1}},Em=()=>{if(RH()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new IH(SH(`/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"}},RE=async(e,t)=>{let n=t.input??Em(),r=t.output??process.stdout,o=xH({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()}},Ra=async(e,t={})=>{let n=(await RE(`${e} ${C("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Oa=async(e,t,n={})=>{let r=t?` ${C(`[${t}]`)}`:"";return(await RE(`${e}${r}: `,n)).trim()||t},OE=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return F(`Your name: ${t} ${C("(cached \u2014 pass --user to change)")}`),t;let r=xE();return n||!jt()?(F(`Your name: ${r} ${C("(auto-detected \u2014 pass --user to change)")}`),r):Oa("? Your name",r)},_E=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return F(`Team: ${t} ${C("(cached \u2014 pass --team to change)")}`),t;if(!(n||!jt()))return Oa("? Team (optional)")},xr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return ln(e??n)},TE=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,_a="claude-desktop",vi=e=>e!=="cursor",Si=(e,t,n)=>vi(e)?n:t,Ld=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await br(e.runReg??Hn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Ut({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=tn(r);return await ao(o,r)?n("managed-policy"):(await ha({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")}},Dd=e=>e.id!==_a||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",OH={"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"},Nd=(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=OH[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 xm=["claude-code","codex"],PH="anyray-connect print-key",Rm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),LH=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:Wa,authMode:"placeholder",metadata:{}}),Om=e=>PE(e,".claude","settings.json"),DH=async(e,t,n)=>{let r=Om(e),o=await M(r),{env:a}=un(t,{includeAuthToken:!1,includeClientKey:!1}),s=Rm(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Ur(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=PH,n||await Z(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]}},NE=async(e=process.cwd())=>{let t=[],n=Om(e);try{if(await R(n)){let o=await M(n),a=Rm(o.env)?o.env:{};(Fr.some(s=>s in a)||Ur(o))&&t.push(n)}}catch{}let r=_m(e);try{if(await R(r)){let o=await Im(r,"utf-8");pp(o)&&t.push(r)}}catch{}return t},NH=async(e,t)=>{let n=Om(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await M(n),o=!1;if(Rm(r.env)){let s={...r.env};for(let i of Fr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Ur(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 LE(n,{force:!0}):await Z(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},_m=e=>PE(e,".codex","config.toml"),$H=async(e,t,n)=>{let r=_m(e),o=await Im(r,"utf-8").catch(()=>""),a=Lc(o,ms(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await TH(_H(r),{recursive:!0}),await DE(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]}},MH=async(e,t)=>{let n=_m(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Im(n,"utf-8"),o=Dc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await LE(n,{force:!0}):await DE(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},$E=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...xm],r=n.filter(s=>!xm.includes(s));if(r.length>0)return O(`--project supports ${xm.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 P(),i=e.gateway??s.gateway;if(!i)return O("--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 O(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=LH(Ye(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||(N(`
440
- A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),F(" 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(!jt())return O(`
438
+ `,RE=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??bk)();if(!n)return O("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;k(` 1. Open ${qe(n.verificationUri)}`),k(` 2. Enter the code: ${j(n.userCode)}`),F(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??kk)(n);if(r.status!=="ok")return O(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??Ak)(r.token,o);$(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??nf)(r.token);if(s.verdict==="no-copilot")return O("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??Te)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??Xo)(r.token,{},s.capiSegment,c);return l.length===0?N("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."):$(`${l.length} models available (e.g. ${l[0].id}).`),F("Now run: anyray-connect --tools copilot-cli"),0};var OE=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??P)()}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??VS)();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 ME,dirname as $H}from"node:path";import{mkdir as MH,readFile as _m,rm as FE,writeFile as BE}from"node:fs/promises";import{fstatSync as OH,openSync as _H,statSync as TH}from"node:fs";import{createInterface as PH}from"node:readline/promises";import{ReadStream as LH}from"node:tty";import{execFileSync as IH}from"node:child_process";import RH from"node:os";var Im=e=>{try{return IH("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},_E=()=>{try{return RH.userInfo().username||void 0}catch{return}},TE=()=>Im("user.name")??Im("user.email")??_E()??"unknown",xm=e=>{try{return e()?.trim()||void 0}catch{return}},PE=(e={})=>{let t=e.gitConfig??Im,n=xm(e.osUsername??_E),r=xm(()=>t("user.email"));return r||(xm(()=>t("user.name"))??n??"unknown")};var Vt=()=>!!process.stdin.isTTY,DH=()=>{try{let e=OH(0);return e.isCharacterDevice()&&e.rdev===TH("/dev/tty").rdev}catch{return!1}},Rm=()=>{if(DH()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new LH(_H(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},yt=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},LE=async(e,t)=>{let n=t.input??Rm(),r=t.output??process.stdout,o=PH({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 yt))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new yt)))})}finally{o.close(),n.close()}},Ra=async(e,t={})=>{let n=(await LE(`${e} ${C("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Oa=async(e,t,n={})=>{let r=t?` ${C(`[${t}]`)}`:"";return(await LE(`${e}${r}: `,n)).trim()||t},DE=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return F(`Your name: ${t} ${C("(cached \u2014 pass --user to change)")}`),t;let r=TE();return n||!Vt()?(F(`Your name: ${r} ${C("(auto-detected \u2014 pass --user to change)")}`),r):Oa("? Your name",r)},NE=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return F(`Team: ${t} ${C("(cached \u2014 pass --team to change)")}`),t;if(!(n||!Vt()))return Oa("? Team (optional)")},xr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return ln(e??n)},$E=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,_a="claude-desktop",xi=e=>e!=="cursor",Ii=(e,t,n)=>xi(e)?n:t,Md=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await br(e.runReg??Hn))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=nn(r);return await ro(o,r)?n("managed-policy"):(await ha({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")}},Fd=e=>e.id!==_a||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",NH={"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"},Bd=(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=NH[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 Om=["claude-code","codex"],FH="anyray-connect print-key",Tm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),BH=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:ja,authMode:"placeholder",metadata:{}}),Pm=e=>ME(e,".claude","settings.json"),UH=async(e,t,n)=>{let r=Pm(e),o=await M(r),{env:a}=un(t,{includeAuthToken:!1,includeClientKey:!1}),s=Tm(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Fr(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=FH,n||await Z(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]}},UE=async(e=process.cwd())=>{let t=[],n=Pm(e);try{if(await R(n)){let o=await M(n),a=Tm(o.env)?o.env:{};($r.some(s=>s in a)||Fr(o))&&t.push(n)}}catch{}let r=Lm(e);try{if(await R(r)){let o=await _m(r,"utf-8");mp(o)&&t.push(r)}}catch{}return t},HH=async(e,t)=>{let n=Pm(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await M(n),o=!1;if(Tm(r.env)){let s={...r.env};for(let i of $r)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Fr(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 FE(n,{force:!0}):await Z(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},Lm=e=>ME(e,".codex","config.toml"),WH=async(e,t,n)=>{let r=Lm(e),o=await _m(r,"utf-8").catch(()=>""),a=Mc(o,ws(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await MH($H(r),{recursive:!0}),await BE(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]}},KH=async(e,t)=>{let n=Lm(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await _m(n,"utf-8"),o=Fc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await FE(n,{force:!0}):await BE(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},HE=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Om],r=n.filter(s=>!Om.includes(s));if(r.length>0)return O(`--project supports ${Om.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 P(),i=e.gateway??s.gateway;if(!i)return O("--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 O(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=BH(je(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||(N(`
440
+ A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),F(" 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 O(`
441
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 Ra(`
442
442
  ${s} ${n.length} tool(s)?`))return F("Aborted. Nothing changed."),0}e.dryRun&&F(`
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 DH(t,o,e.dryRun):await $H(t,o,e.dryRun):s==="claude-code"?await NH(t,e.dryRun):await MH(t,e.dryRun);for(let c of i.messages)k(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(K("Next"),e.revert)$(" Project config removed. Commit the change to propagate it.");else{$(" Commit these files to route every checkout of this repo:");for(let s of a)k(` ${s}`);k(C(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as FH}from"node:child_process";var BH="/usr/bin/security",UH=["find-generic-password","-s","Claude Code-credentials","-w"],HH=1e4,WH=64*1024,KH=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,ME="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",GH=(e,t,n)=>new Promise((r,o)=>{FH(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),FE=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jH=e=>{let t=JSON.parse(e);if(!FE(t)||!FE(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!KH.test(n))throw new Error("unexpected keychain access token");return n},BE=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${ME}
444
- `),1;try{let o=await Am(t),a=Cm(o),s=await(t.execSecurity??GH)(BH,[...UH],{encoding:"utf8",timeout:HH,maxBuffer:WH,shell:!1}),i=jH(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 UH(t,o,e.dryRun):await WH(t,o,e.dryRun):s==="claude-code"?await HH(t,e.dryRun):await KH(t,e.dryRun);for(let c of i.messages)k(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(K("Next"),e.revert)$(" Project config removed. Commit the change to propagate it.");else{$(" Commit these files to route every checkout of this repo:");for(let s of a)k(` ${s}`);k(C(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as GH}from"node:child_process";var jH="/usr/bin/security",VH=["find-generic-password","-s","Claude Code-credentials","-w"],YH=1e4,ZH=64*1024,XH=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,WE="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",JH=(e,t,n)=>new Promise((r,o)=>{GH(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),KE=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zH=e=>{let t=JSON.parse(e);if(!KE(t)||!KE(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!XH.test(n))throw new Error("unexpected keychain access token");return n},GE=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${WE}
444
+ `),1;try{let o=await Sm(t),a=Em(o),s=await(t.execSecurity??JH)(jH,[...VH],{encoding:"utf8",timeout:YH,maxBuffer:ZH,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(`${ME}
447
- `),1}};import{mkdir as bW,writeFile as kW}from"node:fs/promises";import{dirname as AW}from"node:path";import{Buffer as CW}from"node:buffer";import{constants as UE}from"node:fs";import{access as VH,chmod as YH,mkdir as ZH,open as XH,readFile as JH,realpath as zH,rm as qH,stat as KE,writeFile as QH}from"node:fs/promises";import{randomUUID as eW}from"node:crypto";import{platform as GE}from"node:os";import{dirname as tW,join as nW,posix as rW,win32 as jE}from"node:path";var $d="/usr/local/bin/anyray-credential-helper",Md="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Tm="Managed by anyray-connect desktop helper; do not edit.",oW=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
446
+ `),0}catch{return r.write(`${WE}
447
+ `),1}};import{mkdir as EW,writeFile as xW}from"node:fs/promises";import{dirname as IW}from"node:path";import{Buffer as RW}from"node:buffer";import{constants as jE}from"node:fs";import{access as qH,chmod as QH,mkdir as eW,open as tW,readFile as nW,realpath as rW,rm as oW,stat as ZE,writeFile as aW}from"node:fs/promises";import{randomUUID as sW}from"node:crypto";import{platform as XE}from"node:os";import{dirname as iW,join as cW,posix as lW,win32 as JE}from"node:path";var Ud="/usr/local/bin/anyray-credential-helper",Hd="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Dm="Managed by anyray-connect desktop helper; do not edit.",dW=`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
- ${$d}
465
- ${Md}
464
+ ${Ud}
465
+ ${Hd}
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
- `,HE=(e=GE())=>e==="win32"?"windows":"posix",aW=e=>e==="windows"?Md:$d,WE=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},sW=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":WE(t,"write");break;case"--print":WE(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},iW=e=>/[\0\r\n]/.test(e),cW=e=>/^[A-Za-z]:[\\/]/.test(e)&&jE.isAbsolute(e),Ei=(e,t)=>!iW(e)&&(t==="windows"?cW(e):rW.isAbsolute(e)),Pm=e=>e.replace(/\\/g,"/").toLowerCase(),VE=(e,t)=>{if(!Ei(e,t))return!1;let n=Pm(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)))},Lm=(e,t)=>t==="windows"?jE.normalize(e):e,lW=e=>`'${e.replace(/'/g,`'"'"'`)}'`,dW=(e,t)=>{if(!VE(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Lm(t,e);if(e==="windows")return["@echo off",`REM ${Tm}`,'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=lW(n);return["#!/bin/sh",`# ${Tm}`,'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
- `)},Fd=(e,t)=>{if(!Ei(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Lm(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"]}},uW=async e=>{try{return await JH(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},pW=async(e,t)=>{try{let n=await zH(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!VE(r,t))throw new Error;if(!(await KE(n)).isFile())throw new Error;await VH(n,t==="posix"?UE.X_OK:UE.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},fW=e=>e.slice(0,300).includes(Tm),hW=async(e,t,n)=>{let r=await uW(e);if(r!==void 0&&r!==t&&!fW(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 KE(e)).mode&511)===493)return"unchanged"}catch{}}let o=tW(e);try{await ZH(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=nW(o,`.anyray-credential-helper.${process.pid}.${eW()}.tmp`),s=!1;try{await QH(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await YH(a,493);let i=await XH(a,"r");try{await Ka(i)}finally{await i.close()}await fe(a,e),s=!0}catch{throw new Error(`could not install credential helper at ${e}`)}finally{s||await qH(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},YE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=sW(e);if(o.help)return n.write(oW),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??GE)(),s=o.targetPlatform??HE(a),i=Lm(o.helperPath??aW(s),s);if(!Ei(i,s))throw new Error(`--path must be an absolute ${s} path`);if(s==="windows"&&Fd("windows",i),Pm(i)===Pm(o.binaryPath))throw new Error("--path must differ from --bin (the helper cannot invoke itself)");let c=dW(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!==HE(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await pW(o.binaryPath,s);let l=await hW(i,c,s);return r.write(l==="unchanged"?`Credential helper already current at ${i}.
477
+ `,VE=(e=XE())=>e==="win32"?"windows":"posix",uW=e=>e==="windows"?Hd:Ud,YE=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},pW=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":YE(t,"write");break;case"--print":YE(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},fW=e=>/[\0\r\n]/.test(e),hW=e=>/^[A-Za-z]:[\\/]/.test(e)&&JE.isAbsolute(e),Ri=(e,t)=>!fW(e)&&(t==="windows"?hW(e):lW.isAbsolute(e)),Nm=e=>e.replace(/\\/g,"/").toLowerCase(),zE=(e,t)=>{if(!Ri(e,t))return!1;let n=Nm(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)))},$m=(e,t)=>t==="windows"?JE.normalize(e):e,mW=e=>`'${e.replace(/'/g,`'"'"'`)}'`,yW=(e,t)=>{if(!zE(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=$m(t,e);if(e==="windows")return["@echo off",`REM ${Dm}`,'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=mW(n);return["#!/bin/sh",`# ${Dm}`,'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
+ `)},Wd=(e,t)=>{if(!Ri(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=$m(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"]}},gW=async e=>{try{return await nW(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},wW=async(e,t)=>{try{let n=await rW(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!zE(r,t))throw new Error;if(!(await ZE(n)).isFile())throw new Error;await qH(n,t==="posix"?jE.X_OK:jE.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},bW=e=>e.slice(0,300).includes(Dm),kW=async(e,t,n)=>{let r=await gW(e);if(r!==void 0&&r!==t&&!bW(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 ZE(e)).mode&511)===493)return"unchanged"}catch{}}let o=iW(e);try{await eW(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=cW(o,`.anyray-credential-helper.${process.pid}.${sW()}.tmp`),s=!1;try{await aW(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await QH(a,493);let i=await tW(a,"r");try{await Va(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 oW(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},qE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=pW(e);if(o.help)return n.write(dW),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??XE)(),s=o.targetPlatform??VE(a),i=$m(o.helperPath??uW(s),s);if(!Ri(i,s))throw new Error(`--path must be an absolute ${s} path`);if(s==="windows"&&Wd("windows",i),Nm(i)===Nm(o.binaryPath))throw new Error("--path must differ from --bin (the helper cannot invoke itself)");let c=yW(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!==VE(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await wW(o.binaryPath,s);let l=await kW(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 mW=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),yW=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,gW=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.")},wW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Bd=(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!==""||gW(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ta=(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()}},ZE=e=>{if(!wW(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!mW.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ta(e.clientId,"clientId",!0),r=Ta(e.scopes,"scopes",!0),o=Ta(e.issuer,"issuer",!1),a=Ta(e.authorizationUrl,"authorizationUrl",!1),s=Ta(e.tokenUrl,"tokenUrl",!1),i=Ta(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:Bd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Bd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Bd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},XE=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return ZE(t)},Dm=e=>{let t=Bd(e.url,"--bootstrap-url"),n=e.oidc?ZE(e.oidc):void 0,r;if(e.deploymentOrganizationUuid!==void 0&&(r=e.deploymentOrganizationUuid.trim(),!yW.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}:{}}},Nm=e=>ta(Dm(e));var vW=`anyray-connect desktop [disconnect] [options]
483
+ `),1}};var AW=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),CW=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,vW=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.")},SW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Kd=(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!==""||vW(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ta=(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()}},QE=e=>{if(!SW(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!AW.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ta(e.clientId,"clientId",!0),r=Ta(e.scopes,"scopes",!0),o=Ta(e.issuer,"issuer",!1),a=Ta(e.authorizationUrl,"authorizationUrl",!1),s=Ta(e.tokenUrl,"tokenUrl",!1),i=Ta(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:Kd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Kd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Kd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},e0=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return QE(t)},Mm=e=>{let t=Kd(e.url,"--bootstrap-url"),n=e.oidc?QE(e.oidc):void 0,r;if(e.deploymentOrganizationUuid!==void 0&&(r=e.deploymentOrganizationUuid.trim(),!CW.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}:{}}},Fm=e=>ta(Mm(e));var OW=`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
- `,SW=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",EW=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),xW=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[SW(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...EW(o)]},IW=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),$m=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>IW.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;"),JE=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),RW=(e,t)=>` <key>${Zn(e)}</key>
526
- <string>${Zn(t)}</string>`,Mm=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>RW(i,c)).join(`
525
+ `,_W=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",TW=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),PW=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[_W(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...TW(o)]},LW=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),Bm=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>LW.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;"),t0=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),DW=(e,t)=>` <key>${Zn(e)}</key>
526
+ <string>${Zn(t)}</string>`,Um=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>DW(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">
@@ -556,20 +556,20 @@ ${s}
556
556
  <string>${Zn(n)}</string>
557
557
  </dict>
558
558
  </plist>
559
- `},OW=(e,t)=>Mm("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",ta(oo(e,t))),_W=(e,t)=>`${JSON.stringify(oo(e,t),null,2)}
560
- `,TW=e=>Mm("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",Nm(e)),PW=e=>`${JSON.stringify(Dm(e),null,2)}
561
- `,qE=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries(e).map(([n,r])=>`"${JE(n)}"="${JE(r)}"`),""].join(`
562
- `),LW=(e,t)=>{let n=$l(e,t);return qE(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},DW=e=>qE(Nm(e)),NW=(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=Fd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${ms(e,o).join(`
559
+ `},NW=(e,t)=>Um("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",ta(no(e,t))),$W=(e,t)=>`${JSON.stringify(no(e,t),null,2)}
560
+ `,MW=e=>Um("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",Fm(e)),FW=e=>`${JSON.stringify(Mm(e),null,2)}
561
+ `,r0=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries(e).map(([n,r])=>`"${t0(n)}"="${t0(r)}"`),""].join(`
562
+ `),BW=(e,t)=>{let n=Ul(e,t);return r0(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},UW=e=>r0(Fm(e)),HW=(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=Wd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${ws(e,o).join(`
563
563
  `)}
564
- `},$W=e=>Mm("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:CW.from(e,"utf-8").toString("base64")}),MW=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},FW=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=ln(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:Wa,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},zE=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??bW,o=n.writeFile??kW;await r(AW(t),{recursive:!0}),await o(t,e)},BW=(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
+ `},WW=e=>Um("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:RW.from(e,"utf-8").toString("base64")}),KW=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},GW=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=ln(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:ja,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},n0=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??EW,o=n.writeFile??xW;await r(IW(t),{recursive:!0}),await o(t,e)},jW=(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
- `)},UW=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
+ `)},VW=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
- `)},HW=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??co)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
572
+ `)},YW=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??so)({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},QE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=xW(e);if(o[0]==="helper")return YE(o.slice(1),t);let a=MW(o);if(a.help)return n.write(vW),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 HW(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:XE(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?DW(u):a.artifact==="json"?PW(u):TW(u);return await zE(f,a.path,t),UW(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 ${$d} on macOS/Linux or ${Md} 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(!Ei(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"&&Fd("windows",i);let l=FW(a),d;if(a.target==="claude")d=a.artifact==="reg"?LW(l,i):a.artifact==="json"?_W(l,i):OW(l,i);else{let u=NW(l,i);d=a.artifact==="mobileconfig"?$W(u):u}return await zE(d,a.path,t),BW(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},o0=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=PW(e);if(o[0]==="helper")return qE(o.slice(1),t);let a=KW(o);if(a.help)return n.write(OW),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 YW(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:e0(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?UW(u):a.artifact==="json"?FW(u):MW(u);return await n0(f,a.path,t),VW(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 ${Ud} on macOS/Linux or ${Hd} 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(!Ri(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"&&Wd("windows",i);let l=GW(a),d;if(a.target==="claude")d=a.artifact==="reg"?BW(l,i):a.artifact==="json"?$W(l,i):NW(l,i);else{let u=HW(l,i);d=a.artifact==="mobileconfig"?WW(u):u}return await n0(d,a.path,t),jW(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 WW=`anyray-connect retrieve <handle> [--source auto|claude|profile]
586
+ `),1}};var ZW=`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
- `,KW=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
596
+ `,XW=`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
- `,e0=(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},GW=e=>e.replace(/[\t\r\n]+/g," ").trim(),t0=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=e0(e,!1);if(o.help)return n.write(WW),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??ba)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
607
+ `,a0=(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},JW=e=>e.replace(/[\t\r\n]+/g," ").trim(),s0=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=a0(e,!1);if(o.help)return n.write(ZW),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??et)(o.source),i=await(t.retrieve??ba)(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}},n0=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=e0(e,!0);if(o.help)return n.write(KW),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??wd)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
610
+ `),1}},i0=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=a0(e,!0);if(o.help)return n.write(XW),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??et)(o.source),i=await(t.recall??Cd)(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} ${GW(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} ${JW(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 yK}from"node:fs";var Cn=e=>typeof e=="string"?e:"",jW=e=>{let t=Cn(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=Cn(o.text).trim();a&&r.push(a)}return r.join(`
616
+ `),1}};import{promises as CK}from"node:fs";var Cn=e=>typeof e=="string"?e:"",zW=e=>{let t=Cn(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=Cn(o.text).trim();a&&r.push(a)}return r.join(`
617
617
 
618
- `).trim()},VW=e=>{let t=Cn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},YW=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=jW(r);if(!o)continue;let a=Cn(r.created_at).trim();t.push({role:VW(r),text:o,...a?{createdAt:a}:{}})}return t},Ud=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=YW(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(Cn(s.uuid)||Cn(s.id)).trim(),l=(Cn(s.name)||Cn(s.title)).trim()||"Untitled conversation",d=Cn(s.created_at).trim(),u=Cn(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 dK}from"node:crypto";import{promises as Ii}from"node:fs";import{homedir as l0}from"node:os";import{join as Kd}from"node:path";import{promises as r0}from"node:fs";import Fm from"node:path";var ZW=4e4,XW=16*1024*1024,xi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Hd=async(e,t={})=>{let n=(e??"").trim();if(!n)return xi("","path is required");let r=t.cwd??process.cwd(),o=Fm.resolve(r,n),a=Fm.relative(r,o);if(a.startsWith("..")||Fm.isAbsolute(a))return xi(n,"path is outside the workspace");let s=t.maxBytes??ZW,i;try{let w=await r0.stat(o);if(!w.isFile())return xi(n,"not a regular file");let g=t.maxFileBytes??XW;if(w.size>g)return xi(n,`file too large to read (${w.size} bytes; limit ${g})`);i=await r0.readFile(o,"utf8")}catch(w){return xi(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
618
+ `).trim()},qW=e=>{let t=Cn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},QW=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=zW(r);if(!o)continue;let a=Cn(r.created_at).trim();t.push({role:qW(r),text:o,...a?{createdAt:a}:{}})}return t},Gd=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=QW(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(Cn(s.uuid)||Cn(s.id)).trim(),l=(Cn(s.name)||Cn(s.title)).trim()||"Untitled conversation",d=Cn(s.created_at).trim(),u=Cn(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 yK}from"node:crypto";import{promises as _i}from"node:fs";import{homedir as h0}from"node:os";import{join as Yd}from"node:path";import{promises as c0}from"node:fs";import Hm from"node:path";var eK=4e4,tK=16*1024*1024,Oi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),jd=async(e,t={})=>{let n=(e??"").trim();if(!n)return Oi("","path is required");let r=t.cwd??process.cwd(),o=Hm.resolve(r,n),a=Hm.relative(r,o);if(a.startsWith("..")||Hm.isAbsolute(a))return Oi(n,"path is outside the workspace");let s=t.maxBytes??eK,i;try{let w=await c0.stat(o);if(!w.isFile())return Oi(n,"not a regular file");let g=t.maxFileBytes??tK;if(w.size>g)return Oi(n,`file too large to read (${w.size} bytes; limit ${g})`);i=await c0.readFile(o,"utf8")}catch(w){return Oi(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}:{}}}},Bm=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}:{}}}},Wm=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 JW}from"node:child_process";import{promises as Um}from"node:fs";import Hm from"node:path";var Wm=400,zW=240,qW=4e3,QW=4e3,eK=512*1024,tK=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),a0=(e,t)=>e.length>t?e.slice(0,t):e,nK=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"]),rK=8,oK=2e3,aK=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],sK=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")},s0=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!nK.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=rK))break}return n},i0=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},iK=(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)},o0=(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:a0(l,t)})}return r},cK=(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 aK)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=JW("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=o0(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=o0(d,o,r+1),w=m.length>r;f({ok:!0,matches:w?m.slice(0,r):m,truncated:w,engine:"ripgrep"})})}),lK=async(e,t,n,r,o,a,s)=>{let i=i0(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 Um.readdir(m,{withFileTypes:!0})}catch{return}for(let g of w){if(u.length>=r||Date.now()>a){p=!0;return}let y=Hm.join(m,g.name);if(g.isDirectory()){if(tK.has(g.name))continue;await h(y)}else if(g.isFile()){if(f>=QW){p=!0;return}if(d.length&&!d.some(S=>g.name.endsWith(S))||sK(Hm.relative(t,y)))continue;f+=1;let b;try{if((await Um.stat(y)).size>eK)continue;b=await Um.readFile(y,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let v=b.split(`
625
- `);for(let S=0;S<v.length;S+=1){let E=c(v[S]);if(l.some(x=>E.includes(x))&&(u.push({file:Hm.relative(t,y),line:S+1,text:a0(v[S],o)}),u.length>=r)){p=!0;return}}}}};return await h(t),{ok:!0,matches:u,truncated:p,engine:"walk"}},Wd=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??Wm,s=t.maxColumns??zW,i=t.timeoutMs??qW,c=Date.now()+i,l=s0(n),d=l.length>1,u=Math.min(a*4,oK),f=(g,y)=>lK(n,r,o,g,s,c,y),p=async g=>{let y=await g(u,l);if(!y.ok)return y;let b=iK(y.matches,l,i0(l)),v=b.length>a;return{...y,matches:v?b.slice(0,a):b,truncated:y.truncated||v,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)=>cK(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))},c0=(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=s0(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 nK}from"node:child_process";import{promises as Km}from"node:fs";import Gm from"node:path";var jm=400,rK=240,oK=4e3,aK=4e3,sK=512*1024,iK=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),d0=(e,t)=>e.length>t?e.slice(0,t):e,cK=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"]),lK=8,dK=2e3,uK=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],pK=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")},u0=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!cK.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=lK))break}return n},p0=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},fK=(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)},l0=(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:d0(l,t)})}return r},hK=(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 uK)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=nK("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=l0(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=l0(d,o,r+1),w=m.length>r;f({ok:!0,matches:w?m.slice(0,r):m,truncated:w,engine:"ripgrep"})})}),mK=async(e,t,n,r,o,a,s)=>{let i=p0(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 Km.readdir(m,{withFileTypes:!0})}catch{return}for(let g of w){if(u.length>=r||Date.now()>a){p=!0;return}let y=Gm.join(m,g.name);if(g.isDirectory()){if(iK.has(g.name))continue;await h(y)}else if(g.isFile()){if(f>=aK){p=!0;return}if(d.length&&!d.some(S=>g.name.endsWith(S))||pK(Gm.relative(t,y)))continue;f+=1;let b;try{if((await Km.stat(y)).size>sK)continue;b=await Km.readFile(y,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let v=b.split(`
625
+ `);for(let S=0;S<v.length;S+=1){let E=c(v[S]);if(l.some(x=>E.includes(x))&&(u.push({file:Gm.relative(t,y),line:S+1,text:d0(v[S],o)}),u.length>=r)){p=!0;return}}}}};return await h(t),{ok:!0,matches:u,truncated:p,engine:"walk"}},Vd=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??jm,s=t.maxColumns??rK,i=t.timeoutMs??oK,c=Date.now()+i,l=u0(n),d=l.length>1,u=Math.min(a*4,dK),f=(g,y)=>mK(n,r,o,g,s,c,y),p=async g=>{let y=await g(u,l);if(!y.ok)return y;let b=fK(y.matches,l,p0(l)),v=b.length>a;return{...y,matches:v?b.slice(0,a):b,truncated:y.truncated||v,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)=>hK(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))},f0=(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=u0(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 d0=448,uK=384,pK=4e4,Rr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=Kd(l0(),".anyray");try{if((await Ii.stat(t)).isDirectory())return Kd(t,"history")}catch{}return Kd(l0(),".anyray-history")},fK=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:hK(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},hK=e=>{let t=dK("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)},mK=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 m0=448,gK=384,wK=4e4,Rr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=Yd(h0(),".anyray");try{if((await _i.stat(t)).isDirectory())return Yd(t,"history")}catch{}return Yd(h0(),".anyray-history")},bK=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:kK(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},kK=e=>{let t=yK("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)},AK=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
- `},Gd=async e=>{let t=await Rr();await Ii.mkdir(t,{recursive:!0,mode:d0});try{await Ii.chmod(t,d0)}catch{}let n=0,r=0;for(let o of e)try{await Ii.writeFile(Kd(t,fK(o)),mK(o),{mode:uK}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Pa=async()=>{try{let e=await Rr();return(await Ii.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},u0=async e=>{let t=await Rr();return Wd(e,{cwd:t,globs:["*.md"]})},p0=async e=>{let t=await Rr();return Hd(e,{cwd:t,maxBytes:pK})};var f0=`anyray-connect history <command>
636
+ `},Zd=async e=>{let t=await Rr();await _i.mkdir(t,{recursive:!0,mode:m0});try{await _i.chmod(t,m0)}catch{}let n=0,r=0;for(let o of e)try{await _i.writeFile(Yd(t,bK(o)),AK(o),{mode:gK}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Pa=async()=>{try{let e=await Rr();return(await _i.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},y0=async e=>{let t=await Rr();return Vd(e,{cwd:t,globs:["*.md"]})},g0=async e=>{let t=await Rr();return jd(e,{cwd:t,maxBytes:wK})};var w0=`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
- `,gK=async e=>{try{return{raw:await yK.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"})`}}},wK=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return O("Usage: anyray-connect history import <conversations.json>"),k(C("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await gK(t);if("error"in n)return O(n.error),1;let r=Ud(n.raw);if(!r.ok)return O(`Could not read that export: ${r.message??"unrecognized format"}`),k(C("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 O("That export contains no conversations with readable messages."),1;let o;try{o=await Gd(r.conversations)}catch(a){let s=a?.code;return O(`Could not create the history archive (${s??"write failed"}).`),k(C("Check that ~/.anyray is a writable directory, then try again.")),1}return $(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&k(C(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&N(`${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(C(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),k(C(" and the assistant can search this archive and pull it up.")),k(C(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),k(C(" for them, they do not reappear as a clickable list in the app.")),0},bK=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return O("Usage: anyray-connect history restore <export.zip>"),k(C("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await Fl(t);return n.ok?($(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&k(C(` ${n.skipped} already present, left untouched.`)),n.failed>0&&N(`${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(C(" Anyray stays configured; this changed nothing about your routing.")),k(C(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),k(C(" undocumented. A future Desktop release could stop reading it \u2014 your export")),k(C(" file still works, and `history import` remains a second copy.")),0):(O(`Could not restore into Claude Desktop: ${n.reason}`),k(C(` ${n.remedy}`)),1)},kK=async()=>{let e=await Rr(),t=await Pa();return t===0?(k(`No conversations imported yet. Archive would live at ${e}`),k(C(" Import one with: anyray-connect history import <conversations.json>")),0):($(`${t} conversation${t===1?"":"s"} in ${e}`),0)},h0=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(f0),0):t==="import"?wK(e.slice(1)):t==="restore"?bK(e.slice(1)):t==="status"?kK():(O(`Unknown history command: ${t}`),console.log(f0),1)};import{promises as AK}from"node:fs";var CK=`anyray-connect migrate [options]
657
+ `,vK=async e=>{try{return{raw:await CK.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"})`}}},SK=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return O("Usage: anyray-connect history import <conversations.json>"),k(C("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await vK(t);if("error"in n)return O(n.error),1;let r=Gd(n.raw);if(!r.ok)return O(`Could not read that export: ${r.message??"unrecognized format"}`),k(C("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 O("That export contains no conversations with readable messages."),1;let o;try{o=await Zd(r.conversations)}catch(a){let s=a?.code;return O(`Could not create the history archive (${s??"write failed"}).`),k(C("Check that ~/.anyray is a writable directory, then try again.")),1}return $(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&k(C(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&N(`${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(C(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),k(C(" and the assistant can search this archive and pull it up.")),k(C(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),k(C(" for them, they do not reappear as a clickable list in the app.")),0},EK=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return O("Usage: anyray-connect history restore <export.zip>"),k(C("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await Wl(t);return n.ok?($(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&k(C(` ${n.skipped} already present, left untouched.`)),n.failed>0&&N(`${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(C(" Anyray stays configured; this changed nothing about your routing.")),k(C(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),k(C(" undocumented. A future Desktop release could stop reading it \u2014 your export")),k(C(" file still works, and `history import` remains a second copy.")),0):(O(`Could not restore into Claude Desktop: ${n.reason}`),k(C(` ${n.remedy}`)),1)},xK=async()=>{let e=await Rr(),t=await Pa();return t===0?(k(`No conversations imported yet. Archive would live at ${e}`),k(C(" Import one with: anyray-connect history import <conversations.json>")),0):($(`${t} conversation${t===1?"":"s"} in ${e}`),0)},b0=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(w0),0):t==="import"?SK(e.slice(1)):t==="restore"?EK(e.slice(1)):t==="status"?xK():(O(`Unknown history command: ${t}`),console.log(w0),1)};import{promises as IK}from"node:fs";var RK=`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
- `,vK=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},m0={code:"Claude Code sessions",cowork:"Cowork tasks"},SK=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`${m0[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},EK=async(e,t)=>{k(j("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??co)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){O(` ${n.reason}`);for(let s of n.remedy.split(`
687
- `).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${SK(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&&N(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&N(` 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&&N(` ${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??[])N(` ${m0[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${bh(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(C(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},xK=async(e,t)=>{if(k(""),k(j("2. Your claude.ai chats")),t){k(C(" 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(C(" claude.ai -> Settings -> Privacy -> Export data, then:")),k(C(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await Fl(e.exportZip);if(!n.ok){O(` ${n.reason}`),k(` ${n.remedy}`);return}$(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),k(C(" 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);$(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&k(C(` Instructions and docs are in ${r.root}, listed under Projects.`))}},IK=async e=>{if(k(""),k(j("3. Searchable from every Anyray client")),!e.conversations){let o=await Pa();o>0?k(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(k(C(" Optional. Pass the conversations.json inside the export:")),k(C(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await AK.readFile(e.conversations,"utf8")}catch{O(` could not read ${e.conversations}`);return}let n=Ud(t);if(!n.ok){O(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Gd(n.conversations);$(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),k(C(` Ask any Anyray-connected client about a past chat. ${await Rr()}`))},RK=e=>{k(""),k(j("Next")),k(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||N(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),k(C(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},y0=async(e,t={})=>{let n;try{n=vK(e)}catch(o){return O(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(CK),0;k(j("Migrating Claude Desktop onto Anyray")),k(C("Claude Desktop must be fully quit.")),k("");let r=await EK(n,t);return await xK(n,!r),await IK(n),r?(RK(n),0):(k(""),N("Fix the item above and re-run to finish the migration."),1)};var OK=3e3,jd=async(e,t={})=>{let n=t.timeoutMs??OK,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 _K="enl_",TK="enp_",g0=e=>e.startsWith(_K)||e.startsWith(TK),PK=/^\/enroll\/([^/]+)\/?$/,LK=/^\/i\/([^/]+)\/?$/,w0=e=>{let t=e.match(PK);if(t)return t[1];let n=e.match(LK);return n&&g0(n[1])?n[1]:void 0},DK=1e4,Vd=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=w0(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}return{cpOrigin:Gn(),token:t}},Oi=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:w0(n.pathname)!==void 0}catch{return g0(t)}},Ri=e=>typeof e=="string"&&e.trim()?e.trim():void 0,b0=async(e,t={})=>{let n=t.timeoutMs??DK,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"&&Ri(u.url)!==void 0),d=Ri(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:Ri(l?.deploymentId),org:Ri(i.org),email:Ri(i.email),seatMode:i.seatMode===!0}};var k0=()=>Em(),A0=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??k0)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},NK=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},C0=async(e,t={})=>{let n=(t.openInput??k0)(),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=xa(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
+ `,OK=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},k0={code:"Claude Code sessions",cowork:"Cowork tasks"},_K=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`${k0[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},TK=async(e,t)=>{k(j("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??so)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){O(` ${n.reason}`);for(let s of n.remedy.split(`
687
+ `).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${_K(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&&N(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&N(` 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&&N(` ${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??[])N(` ${k0[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${Ch(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(C(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},PK=async(e,t)=>{if(k(""),k(j("2. Your claude.ai chats")),t){k(C(" 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(C(" claude.ai -> Settings -> Privacy -> Export data, then:")),k(C(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await Wl(e.exportZip);if(!n.ok){O(` ${n.reason}`),k(` ${n.remedy}`);return}$(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),k(C(" 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);$(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&k(C(` Instructions and docs are in ${r.root}, listed under Projects.`))}},LK=async e=>{if(k(""),k(j("3. Searchable from every Anyray client")),!e.conversations){let o=await Pa();o>0?k(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(k(C(" Optional. Pass the conversations.json inside the export:")),k(C(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await IK.readFile(e.conversations,"utf8")}catch{O(` could not read ${e.conversations}`);return}let n=Gd(t);if(!n.ok){O(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Zd(n.conversations);$(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),k(C(` Ask any Anyray-connected client about a past chat. ${await Rr()}`))},DK=e=>{k(""),k(j("Next")),k(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||N(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),k(C(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},A0=async(e,t={})=>{let n;try{n=OK(e)}catch(o){return O(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(RK),0;k(j("Migrating Claude Desktop onto Anyray")),k(C("Claude Desktop must be fully quit.")),k("");let r=await TK(n,t);return await PK(n,!r),await LK(n),r?(DK(n),0):(k(""),N("Fix the item above and re-run to finish the migration."),1)};var NK=3e3,Xd=async(e,t={})=>{let n=t.timeoutMs??NK,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`:mt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};var $K="enl_",MK="enp_",C0=e=>e.startsWith($K)||e.startsWith(MK),FK=/^\/enroll\/([^/]+)\/?$/,BK=/^\/i\/([^/]+)\/?$/,v0=e=>{let t=e.match(FK);if(t)return t[1];let n=e.match(BK);return n&&C0(n[1])?n[1]:void 0},UK=1e4,Jd=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=v0(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}return{cpOrigin:Gn(),token:t}},Pi=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:v0(n.pathname)!==void 0}catch{return C0(t)}},Ti=e=>typeof e=="string"&&e.trim()?e.trim():void 0,S0=async(e,t={})=>{let n=t.timeoutMs??UK,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.`:mt(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"&&Ti(u.url)!==void 0),d=Ti(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:Ti(l?.deploymentId),org:Ti(i.org),email:Ti(i.email),seatMode:i.seatMode===!0}};var E0=()=>Rm(),x0=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??E0)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},HK=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},I0=async(e,t={})=>{let n=(t.openInput??E0)(),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=xa(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",S),r.off("end",b),r.off("close",b),r.off("error",v)},g=E=>{w(),h(E)},y=E=>{w(),m(E)},b=()=>g({kind:"cancelled"}),v=E=>y(E),S=E=>{try{for(let x of NK(E)){if(x===""||x==="\x1B"||x==="q"){g({kind:"cancelled"});return}if(e.items.length===0){(x==="\r"||x===`
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",S),r.off("end",b),r.off("close",b),r.off("error",v)},g=E=>{w(),h(E)},y=E=>{w(),m(E)},b=()=>g({kind:"cancelled"}),v=E=>y(E),S=E=>{try{for(let x of HK(E)){if(x===""||x==="\x1B"||x==="q"){g({kind:"cancelled"});return}if(e.items.length===0){(x==="\r"||x===`
691
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 A=!a[s];a.fill(!1),a[s]=A}else a[s]=!a[s];d()}else if(x==="a"&&!e.single){let A=e.items.map((T,B)=>({item:T,index:B})).filter(({item:T})=>T.requiresExplicitChoice!==!0),I=!A.every(({index:T})=>a[T]);for(let{index:T}of A)a[T]=I;d()}else if(x==="\r"||x===`
692
- `){g({kind:"ok",values:e.items.filter((A,I)=>a[I]).map(A=>A.value)});return}}}catch(x){y(x)}};r.on("data",S),r.on("end",b),r.on("close",b),r.on("error",v)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),p&&r.setRawMode(f)}catch{}n.close()}};var v0=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$K=80,_i=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&xa(r,n.env??process.env)))return r.write(`${e}
693
- `),t();let a=0,s=()=>{r.write(`\r${v0[a++%v0.length]} ${e}`)};s();let i=setInterval(s,$K);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as MK}from"node:fs";import{spawnSync as FK}from"node:child_process";import{chmod as BK,copyFile as jm,lstat as Vm,mkdir as La,readdir as Ym,realpath as Zd,rename as Yd,rm as Ot,stat as UK,symlink as HK,writeFile as WK}from"node:fs/promises";import{createHash as KK}from"node:crypto";import{basename as Km,dirname as Or,join as pt}from"node:path";import{Readable as GK}from"node:stream";import{pipeline as jK}from"node:stream/promises";var S0="https://github.com/anyrayHQ/install/releases",E0="connect-v",VK=new RegExp(`/releases/tag/${E0}([0-9][0-9A-Za-z.-]*)$`),YK=300*1024*1024,Xd=1e4,ZK=5*6e4,XK=360*6e4,JK=30*6e4,Da=(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)},x0=(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"}},zK=e=>{if(e)return VK.exec(e.trim())?.[1]},Zm=(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()}},I0=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&&Da(e.current,e.minVersion)<0&&Da(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},qK=e=>Da(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}:{...I0(e),downgradeBlocked:!1},Na=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",QK=(e=process.execPath)=>{let t=_u(e);return t?Or(t):Or(Or(e))},eG=async(e=mt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=pt(QK(e.execPath),"bin",Na());try{if(await Zd(t)!==await Zd(e.execPath))return}catch{return}return t},Xm=async(e=mt(),t=q())=>{let n=await eG(e);if(n)return{kind:"managed",root:Or(Or(n)),link:n,entryPath:Jn(e)};let r=Jn(e);return Pu(r,t)?{kind:"durable",root:t,entryPath:r}:Ru(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},Jd=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)}},Jm=async(e=Xd)=>{let t=await Jd(`${S0}/latest`,e,{redirect:"manual"});return zK(t.headers.get("location"))},tG=async e=>{try{let t=await Jd(`${e}/connect-update.json`,Xd);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}},Ti=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},zm=async(e,t,n)=>{let r=await Jd(e,ZK);if(!r.ok||!r.body)throw new Ti(r.status);let o=KK("sha256"),a=0;if(await jK(GK.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>YK)throw new Error("asset exceeds size cap");o.update(c),yield c}},MK(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},nG=e=>Km(e)===Na()?Km(Or(e)):Km(e),rG=async e=>{let t=await Ym(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Ot(pt(e,n),{force:!0}).catch(()=>{})},R0=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Ot(r,{force:!0}).catch(()=>{});let o=!1;try{await Yd(e,r),o=!0}catch{}try{await jm(t,e),await WK(Za(e),nG(t))}catch(a){throw o&&await Yd(r,e).catch(()=>{}),a}await Ot(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Ot(n,{force:!0}),await HK(t,n),await Yd(n,e)},oG=async(e,t={})=>{let n=pt(e.root,"bin"),r=pt(e.root,"versions"),o=pt(n,Na());await La(n,{recursive:!0,mode:448}),await La(r,{recursive:!0,mode:448});let a=pt(r,e.version),i=(await Vm(a).catch(()=>{}))?.isFile()?a:pt(a,Na());if(!(await Vm(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??Jd)(`${e.tagUrl}/SHA256SUMS`,Xd),d=l.ok?Zm(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await La(Or(i),{recursive:!0,mode:448}),await rG(Or(i));let u=`${i}.part-${process.pid}`;try{await(t.download??zm)(`${e.tagUrl}/${e.asset}`,u,d),await BK(u,493),await Yd(u,i)}catch(f){throw await Ot(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??R0)(o,i),{link:o,target:i,versionsDir:r}},aG=async e=>{let t=FK(e,["--version"],{stdio:"ignore",timeout:Xd});return!t.error&&t.status===0},sG=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??mo)(n);if(r.length>0){let o=await(t.resolveTarget??_e)(async()=>e);if(!o||!(await(t.repair??gt)(r,o.target)).every(ho))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??sr)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Lt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},iG=async e=>{let t=await e.install();if(!await(e.smoke??aG)(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},cG=async(e,t)=>{let n=await Ym(e).catch(()=>[]);for(let r of n)t.includes(r)||await Ot(pt(e,r),{force:!0,recursive:!0}).catch(()=>{})},lG=async e=>{let t=await Ym(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Ot(pt(e,n),{force:!0}).catch(()=>{})},dG=async(e,t)=>{let n=async()=>{await Ot(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await La(e,{recursive:!1}),n}catch{}let r=await UK(e).catch(()=>{});if(!(!r||t-r.mtimeMs<JK)){await n();try{return await La(e,{recursive:!1}),n}catch{return}}},Gm=e=>pt(e,"update-state.json"),uG=async e=>{let t=await M(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},pG=1e3,fG=16*6e4,hG=e=>e.inFlight===0,mG=async(e,t,n={})=>{let r=n.probe??ke,o=n.sleep??(i=>new Promise(c=>setTimeout(c,i))),a=n.now??Date.now,s=a()+(n.timeoutMs??fG);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&hG(i))return!0;if(a()>=s)return!1;await o(pG)}},Pi=async(e={})=>{let t=e.now??Date.now,n=be;if(At(yt(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??mt(),o=e.root??q(),a;try{let s=await Xm(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=x0(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Jm)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&Da(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await uG(Gm(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<XK)return{outcome:"failed",current:n,latest:l};let f=`${S0}/download/${E0}${l}`,p=await(e.load??P)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??tG)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?qK(w):{...I0(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 La(o,{recursive:!0,mode:448});let y=await dG(pt(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,v;try{await lG(pt(o,"bin"));let x=await Zd(pt(o,"versions")).catch(()=>{}),A=await Zd(pt(o,"bin",Na())).catch(()=>{}),I=A&&nc(A,x)?A:void 0,T=pt(o,"bin",Na());i&&process.platform==="win32"&&(await Vm(T).catch(()=>{}))?.isFile()&&(v=`${T}.rollback-${process.pid}`,await jm(T,v));let B=()=>(e.installBinary??oG)({root:o,version:l,asset:c,tagUrl:f});i?b=await iG({install:B,smoke:e.smoke,rollback:async({link:X,target:V})=>{v?(await jm(v,X),await Ot(Za(X),{force:!0}).catch(()=>{})):I&&I!==V?await R0(X,I):(await Ot(X,{force:!0}),await Ot(Za(X),{force:!0}).catch(()=>{}))},repoint:async X=>e.repoint?e.repoint(p,X):sG(p),prune:async()=>{await(e.pruneDurable??(X=>rc(X)))(r)}}):b=await B(),await cG(b.versionsDir,[l,n]),await Ot(Gm(o),{force:!0}).catch(()=>{})}finally{v&&await Ot(v,{force:!0}).catch(()=>{}),await y()}let S=e.bounceDaemon??Vu,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let x=p.fallbackPort??Ae,A=E?!0:await Xg().catch(()=>!0),I=await S(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!A&&p.gateway&&((I?await(e.waitForDaemon??mG)(x,l):!0)?await Lt({port:x,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??zg)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await Z(Gm(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},O0=async(e={})=>{let t=e.context??mt(),n=await Xm(t,e.root??q()),r=_o(e.root??q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:be,managedPath:n.link??r}:Pi({...e,context:t,allowNpmMigration:!0})},vo=async(e={})=>{let t=e.context??mt(),n=e.root??q(),r=await Xm(t,n),o=r.kind==="npm"||r.kind==="durable"?_o(n):void 0,a=await(e.load??P)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!x0(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=At(yt(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:be,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};var yG=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})},_0=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,gG=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},qm=async(e={})=>{let t=e.load??P,n=e.save??te,r=e.mutate??(e.load||e.save?gG(t,n):ag),o=e.loadDevKey??Be,a=e.heartbeat??hd,s=e.detectSeat??Dt,i=e.rewriteTools??fi,c=e.uninstallProxy??Jt;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 Cr&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!_0(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 yG(p,s);if(!h)return"pending";let m=l.keyRefreshEnabled===!0,w=Number.isInteger(l.fallbackPort)&&l.fallbackPort>0&&l.fallbackPort<=65535?l.fallbackPort:Ae;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"||!_0(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"}};var wG=12e3,bG="anyray-wiring-probe-not-a-real-token",kG={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},ey={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},So=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},P0=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},ty=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},T0=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."],AG=e=>e.includes("no provider key configured for"),ny=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},ry=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>"]}),Li=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."]}),CG=(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?ny(t)?ry(e):ty(t)?Li(e):P0(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${So(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)."]}:AG(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${So(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")?T0([" \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}): ${So(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).",...T0([" \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}: ${So(t)}`,remedy:[]},vG=(e,t)=>{if(ty(t))return Li(e);if(ny(t))return ry(e);if(P0(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}: ${So(t)}`,remedy:[]}},SG=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),EG=(e,t)=>{if(ty(t))return Li(e);if(ny(t))return ry(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")||SG(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}: ${So(t)}`,remedy:[`The probe asks for a fixed model (${ey.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."]}},Qm=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)}},xG=async(e,t)=>{if(!e.clientKey)return Li(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?Li(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${So(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},IG=(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."]}},Di=async(e,t={})=>{let n=t.timeoutMs??wG,r=le(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await xG(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 Qm(`${e.anthropicBaseUrl}/v1/messages`,l,ey,n);return EG(d,u)}if(J(e,"anthropic")){let l={Authorization:`Bearer ${bG}`,"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 Qm(`${e.anthropicBaseUrl}/v1/messages`,l,ey,n);return vG(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await Qm(`${e.openaiBaseUrl}/chat/completions`,s,kG,n);return CG(i,c,t.tools??[])}catch(o){return IG(n,o)}};var L0=async e=>{let t=await P(),n;try{n=xr(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),F(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${et(n)}`),t.gateway?F(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?F(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||F(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??C("(not set)")}`),k(` Team: ${t.team??C("(not set)")}`);let r=yt();r&&(K("Environment"),k(` Remote dev context: ${or(r)}`),At(r)&&F(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),F(" 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."),F(" The local proxy remains available until every managed tool moves.")):($(" Direct gateway routing with a proof-backed stable-key heartbeat."),F(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(nt(t)&&t.fallbackPort),a=o?`http://${ht}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await ke(t.fallbackPort)?$(` Running on 127.0.0.1:${t.fallbackPort} \u2192 ${n} `+C("(auto-refreshes your key so long sessions never 401)")):(N(` Enabled on 127.0.0.1:${t.fallbackPort} but NOT responding \u2014 your tools cannot reach any gateway until it's back.`),k(C(" Re-run `anyray-connect`, or check the service logs.")))),K("Tools");for(let s of oe){if(!(await s.detect()).installed){F(` ${s.title}: not installed`);continue}if(!s.pointsAt){F(` ${s.title}: installed ${C("(status not introspectable)")}`);continue}let c=await s.pointsAt(Si(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){$(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(C(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}$(` ${s.title}: pointed at Anyray${o&&vi(s.id)?C(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===_a&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await Ld();l=Dd({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=Nd(l,d);N(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(C(` ${f}`))}else F(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as LG}from"node:fs";import{isAbsolute as DG}from"node:path";import{access as RG}from"node:fs/promises";import{constants as OG}from"node:fs";import{platform as _G}from"node:os";var TG=async e=>{try{return await RG(e,OG.F_OK),!0}catch{return!1}},PG=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"]:[],$a=async(e={})=>{let t=e.os??_G(),n=e.exists??TG;for(let r of PG(t))if(await n(r))return!0;return!1};var sn="connect",oy=e=>e.replace(/-/g,"_"),D0=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:sn,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:sn,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:sn,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:sn,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:sn,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:sn,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=oy(e.retrieval.kind);t.push({tool:sn,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":oy(e.verify.kind);t.push({tool:sn,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:sn,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:oy(e.hookLane.reason)}:{}})}t.push({tool:sn,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:sn,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function NG(){return be}var $G="ctx_doctor-probe-synthetic",MG=(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: ${iy(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 FG(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function BG(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function iy(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 N0=e=>Dd({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&&N0(e)!=="unverifiable",$0=e=>e.registered&&e.command&&DG(e.command)?LG(e.command):null,sy=e=>(ay(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),UG=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,HG=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},M0=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},WG=(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(wo),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},KG=async(e,t,n,r,o,a,s=n,i=Di,c=!0,l=Ao,d=vo,u=Wt,f=ka)=>{let p=c?await jd(e):null,h=!!(nt(t)&&t.fallbackPort),m=h?await ke(t.fallbackPort):null,w=h?`http://${ht}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=t.enrolledCert?.payload,b=y?.expiresAt??t.enrolledCertExpiry??null,S=(await a())?.sso??null,E=BG({ssoLink:S,enrolledViaToken:!!t.enrolledTokenHash}),x=Ct(),A=await xw(x),I=A?[]:Tw(ge({origin:w})),T=[];for(let Y of r){let Ne=await Y.detect(),ft=null;if(Ne.installed&&Y.mcpStatus)try{let Lr=await Y.mcpStatus();ft={...Lr,commandOk:$0(Lr)}}catch{}let Ve=Ne.installed&&Y.id===_a?await o():void 0,Pr=Ne.installed&&Y.pointsAt?await Y.pointsAt(Si(Y.id,e,w)):null,cn=await UG(Pr,Y,t.managedTools??[]),Gi=Pr===!1&&cn===null,Ua=cn===!1&&Y.routingPendingReload?await Y.routingPendingReload().catch(()=>!1):!1,ji=Ne.installed?Y.runtimeDiagnostics?await Y.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:Y.routingOverrides?await Y.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Vi,claudeCodeHookPolicy:Ha}=ji,pe=t.fleetToolPolicy,tt=pe?.enabled.includes(Y.id)?pe.tiers?.[Y.id]??ga:void 0;T.push({id:Y.id,title:Y.title,installed:Ne.installed,...Ne.detail?{detail:Ne.detail}:{},pointedAt:cn,...Gi?{routingHeld:!0}:{},...Ua?{routingPendingReload:!0}:{},...Vi.length?{routingOverrides:Vi}:{},...Ha===void 0?{}:{claudeCodeHookPolicy:Ha},mcp:ft,...tt?{policyTier:tt}:{},...t.revertedTools?.includes(Y.id)?{tombstoned:!0}:{},...Y.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...Ve===void 0?{}:{inferenceIntrospectable:Ve.authoritative,...Ve.authoritative?{}:{inferenceUnverifiableReason:Ve.reason}}})}let B=s?await(async()=>{let{kind:Y,detail:Ne,remedy:ft}=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:Y,detail:Ne,remedy:ft}})():null,X=B?.kind==="provider-rejected"&&await HG(t.managedTools??[],r),V=B?{...B,...X?{notApplicableSubscription:!0}:{}}:null,W=n?MG(await ba({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:le({user:t.name,team:t.team})},$G,{probe:!0}),{mode:E,ssoLink:S}):null,z=await u().catch(()=>({})),me=An(z.hookLane),De=s?await M0(r):!1,ee=De?await(async()=>{let Y=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...Xh(Y,{hookRegistered:De,neverInvoked:Yh(me,Date.now())}),lastInvokedAt:yd(me)}})():null,Fe=(await cr()).map(Y=>({adapter:Y.adapter,op:Y.op,requestedAt:Y.requestedAt,watcherAlive:dr(Y.watcherPid)})),xe=Fe.find(Y=>Y.adapter==="cursor"),_=xe?{op:xe.op,requestedAt:xe.requestedAt,watcherAlive:xe.watcherAlive}:null,L=!!t.refreshSchedulerEnabled,H=await vc(),ye=await d(),se=t.persistenceOwner==="tray",we=se?await l(t)==="healthy":null,We=await nE({daemonEnabled:h&&!se,daemonHealthy:h?!!m:null,schedulerEnabled:L&&!se,schedulerInstalled:H,binaryDurable:!Ge(rr())}),ue=await Su(),ie=0;p&&!p.reachable&&(ie+=1),h&&!m&&(ie+=1),se?L&&!we&&(ie+=1):L&&!H&&(ie+=1);for(let Y of T)ie+=sy(Y);return V&&V.kind!=="ok"&&!V.notApplicableSubscription&&(ie+=1),W&&W.kind!=="ok"&&(ie+=1),ee?.verdict==="dark"&&(ie+=1),I.length>0&&(ie+=1),ie+=Fe.filter(Y=>!Y.watcherAlive).length,ue.length>0&&(ie+=1),{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:NG(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:yt(),selfUpdate:{managed:ye.managed,available:ye.available,autoUpdate:ye.autoUpdate,state:ye.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:L,installed:H,owner:se?"tray":"os",...se?{trayHealthy:!!we}:{}},serviceRemoval:We,retiredFallbackState:ue,fleetdPresent:await $a(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null},enrollment:{enrolled:!!y,deploymentId:y?.deploymentId??null,issuedAt:y?.issuedAt??null,expiresAt:b,expired:b?Date.parse(b)<Date.now():null,orgMode:E,ssoLink:S},shell:{profilePath:x,blockPresent:A,staleExports:I},tools:T,...t.fleetToolPolicy?{fleetPlan:ld(t,t.fleetToolPolicy,!1)}:{},cursorQueue:_,pendingOps:Fe,ambientRepairs:WG(z,r),verify:V,retrieval:W,hookLane:ee,problems:ie}},GG=e=>{if(e.serviceRemoval.suspected){K("Endpoint security"),N(" Anyray installed these background services, but their files are gone from disk \u2014"),N(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),N(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)k(C(` missing: ${t}`));k(C(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(C(" tools straight at the gateway (your key then needs a periodic re-run).")),k(C(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(C(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},jG=e=>{if(e.retiredFallbackState.length!==0){K("Retired fallback lane"),O(" A cached organization provider key from the removed --fallback lane is still on this machine.");for(let t of e.retiredFallbackState)k(C(` ${t}`));k(C(" Fix: `anyray-connect doctor --repair` deletes it (a normal `anyray-connect` run does too)."))}},VG=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${or(e.connect.remoteContext)}`),At(e.connect.remoteContext)&&k(C(" 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":$(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||N(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":N(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),k(C(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":N(" Self-update is unavailable on this platform because no standalone binary is published."),k(C(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(C(" This copy is externally managed; update it with the method that installed it."));break;case"container":k(C(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(K("Gateway"),e.gateway.reachable===null?k(C(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?$(` Reachable: ${e.gateway.origin} ${C(`(${e.gateway.detail})`)}`):(O(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),k(C(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.fallbackProxy.enabled&&(K("Local key-refresh proxy"),e.fallbackProxy.healthy?$(` Running on 127.0.0.1:${e.fallbackProxy.port} \u2192 ${e.gateway.origin} `+C("(auto-refreshes your key so long sessions never 401)")):(O(` 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(C(" 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?$(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh and supervises the daemon."):(O(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),k(C(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?$(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(O(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||k(C(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),GG(e),jG(e),K("Personal key"),FG(e)){case"env":$(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":$(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":N(" Enrolled, but no personal key is cached locally right now."),k(C(" 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:N(" Enrollment required \u2014 no personal gateway key is available."),k(C(` Fix: ${iy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?N(` Enrollment cert expired ${C(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):$(` Enrollment cert valid until ${e.enrollment.expiresAt} ${C(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(K("Shell"),O(" This terminal still exports Anyray, but the config is gone."),k(C(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(C(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(C(" Anything you start from this terminal keeps reaching the gateway with")),k(C(" no credential, and fails with 401.")),k(C(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(C(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(C(" reuses the environment it captured at launch, so a new terminal")),k(C(" (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"),O(` ${lc(c)}.`),k(C(` ${dc(c)}`))}K("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])O(` ${c.title}: ${l.problem}.`),k(C(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(O(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),k(C(" Fix: re-run `anyray-connect` to re-register the current binary."))):$(` ${c.title}: retrieval MCP server registered ${C("(anyray_retrieve / anyray_recall)")}`):(N(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),k(C(" 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(C(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){k(C(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){$(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),k(C(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}$(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&vi(c.id)?C(" (via key-refresh proxy)"):""}`),o(c),c.id==="claude-code"&&k(C(" 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===_a&&k(C(` ${lA}`)),c.id==="codex"&&k(C(" 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=N0(c);if(l==="not-routed"||l==="unverifiable"){let d=Nd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});N(` ${c.title}: ${d.headline}`);for(let u of d.detail)k(C(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(N(` ${c.title}: reverted locally against admin policy (out of compliance)`),k(C(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?N(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):k(C(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(O(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),k(C(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(O(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),k(C(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(N(" No tools are pointed at this gateway yet."),k(C(" 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?N(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(O(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),k(C(` 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?N(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&&N(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(K("Auth probe"),e.verify.notApplicableSubscription)$(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")$(` ${e.verify.detail}`);else{O(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(C(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")$(` ${e.retrieval.detail}`);else{O(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(C(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")$(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){O(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(C(` ${c}`))}else{N(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(C(` ${c}`))}e.hookLane.lastInvokedAt!==null&&k(C(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}K("Summary"),e.problems===0?(e.verify?$(" No problems found."):$(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(C(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):O(` ${e.problems} problem(s) found \u2014 see fixes above.`)},YG=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}),ZG=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Gh(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??ka,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Qe)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=An((await(t.readRefreshState??Wt)().catch(()=>({}))).hookLane),l=Xh(i,{hookRegistered:await M0(t.adapters??oe).catch(()=>!1),neverInvoked:Yh(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:yd(c)},note:d}},XG=async(e,t,n={})=>{let r=n.adapters??oe,o=n.resolveTarget??_e,a=n.applyTools??gt,s=await ZG(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,ke);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 ${iy(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(v=>v.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),!ho(y))continue;let b=e.tools.find(T=>T.id===y.id);if(!b)continue;let v=r.find(T=>T.id===y.id),S=b.mcp;if(v?.mcpStatus)try{let T=await v.mcpStatus();S={...T,commandOk:$0(T)}}catch{}let E=ay(b)?!0:b.pointedAt;if(v?.pointsAt&&b.pointedAt!==null)try{E=await v.pointsAt(Si(v.id,e.gateway.origin,e.toolOrigin))}catch{}let x=b.routingOverrides,A=b.claudeCodeHookPolicy;if(v?.runtimeDiagnostics)try{let T=await v.runtimeDiagnostics();x=T.routingOverrides.length?T.routingOverrides:void 0,A=T.claudeCodeHookPolicy}catch{}else if(v?.routingOverrides)try{let T=await v.routingOverrides();x=T.length?T:void 0}catch{}let I={...b,pointedAt:E,mcp:S,...x?{routingOverrides:x}:{},...A===void 0?{}:{claudeCodeHookPolicy:A}};x||delete I.routingOverrides,A===void 0&&delete I.claudeCodeHookPolicy,w.set(y.id,I),g+=sy(b)-sy(I)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},JG=e=>{K("Repair"),e.entries.length===0&&$(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?$(` ${t.title}: re-applied`):t.status==="queued"?$(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(C(` ${t.title}: ${t.status}`)):O(` ${t.title}: ${t.status}`);for(let t of e.notes)k(C(` ${t}`))},F0=async(e,t={})=>{let n=await P();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of rE(n.fallbackPort??Ae))k(c?` ${c}`:"");return 0}let r;try{r=xr(e.gateway,n)}catch(c){return e.json?(console.log(JSON.stringify({error:c.message})),1):(k(j("Anyray connect \u2014 doctor")),O(` Gateway URL: ${c.message}`),k(C(" 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")),O(" --quick skips the network probes; it cannot be combined with --verify.")),1;let o=!e.noVerify&&!e.quick,a=await KG(r,n,!!e.verify&&!e.quick,t.adapters??oe,t.inferenceIntrospection??Ld,t.fleetBootstrap??Gt,o,t.verifyAuth??Di,!e.quick,t.checkTray??Ao,t.updateStatus??vo,t.readRefreshState??Wt,t.probeHookLane??ka);e.repair&&a.retiredFallbackState.length>0&&(await Qi(),a.retiredFallbackState=await Su(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await XG(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(YG(i),null,2)):(VG(i),s&&JG(s));try{e.quick||await(t.reportHealth??Vv)(D0(i),i.connect.version)}catch{}return i.problems===0?0:1};var zG=()=>{let e=[];for(let t of oe){let n=t.skillsDir?.();n&&e.push(n)}return e},B0=async e=>{let t=await P();k(j("Anyray connect \u2014 sync"));let n;try{n=xr(e.gateway,t)}catch(s){return O(s.message),1}F(`Gateway: ${n}`);let r=TE(t.clientKey,"anyray-placeholder"),o;try{o=await ud(n,r)}catch(s){return O(`Team policy sync failed: ${dd(s)}`),1}let a=zG();if(a.length===0)qG();else if(o.skills.length===0)F("No team skills published yet \u2014 nothing to sync.");else{let s=await Iv(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?$(` ${i.name} ${C(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):F(` ${i.name} ${C(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await te({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){F(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await pd(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&&F(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){F(`Fleet policy reconcile skipped: ${dd(s)}`)}return 0},qG=()=>{F("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as tV}from"node:zlib";import{promisify as nV}from"node:util";var _r={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},cy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),U0=e=>`
692
+ `){g({kind:"ok",values:e.items.filter((A,I)=>a[I]).map(A=>A.value)});return}}}catch(x){y(x)}};r.on("data",S),r.on("end",b),r.on("close",b),r.on("error",v)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),p&&r.setRawMode(f)}catch{}n.close()}};var R0=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],WK=80,Li=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&xa(r,n.env??process.env)))return r.write(`${e}
693
+ `),t();let a=0,s=()=>{r.write(`\r${R0[a++%R0.length]} ${e}`)};s();let i=setInterval(s,WK);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as KK}from"node:fs";import{spawnSync as GK}from"node:child_process";import{chmod as jK,copyFile as Zm,lstat as Xm,mkdir as La,readdir as Jm,realpath as qd,rename as zd,rm as Ot,stat as VK,symlink as YK,writeFile as ZK}from"node:fs/promises";import{createHash as XK}from"node:crypto";import{basename as Vm,dirname as Or,join as lt}from"node:path";import{Readable as JK}from"node:stream";import{pipeline as zK}from"node:stream/promises";var O0="https://github.com/anyrayHQ/install/releases",_0="connect-v",qK=new RegExp(`/releases/tag/${_0}([0-9][0-9A-Za-z.-]*)$`),QK=300*1024*1024,Qd=1e4,eG=5*6e4,tG=360*6e4,nG=30*6e4,Da=(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)},T0=(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"}},rG=e=>{if(e)return qK.exec(e.trim())?.[1]},zm=(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()}},P0=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&&Da(e.current,e.minVersion)<0&&Da(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},oG=e=>Da(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}:{...P0(e),downgradeBlocked:!1},Na=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",aG=(e=process.execPath)=>{let t=Lu(e);return t?Or(t):Or(Or(e))},sG=async(e=pt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=lt(aG(e.execPath),"bin",Na());try{if(await qd(t)!==await qd(e.execPath))return}catch{return}return t},qm=async(e=pt(),t=q())=>{let n=await sG(e);if(n)return{kind:"managed",root:Or(Or(n)),link:n,entryPath:Jn(e)};let r=Jn(e);return Nu(r,t)?{kind:"durable",root:t,entryPath:r}:Tu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},eu=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)}},Qm=async(e=Qd)=>{let t=await eu(`${O0}/latest`,e,{redirect:"manual"});return rG(t.headers.get("location"))},iG=async e=>{try{let t=await eu(`${e}/connect-update.json`,Qd);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}},Di=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},ey=async(e,t,n)=>{let r=await eu(e,eG);if(!r.ok||!r.body)throw new Di(r.status);let o=XK("sha256"),a=0;if(await zK(JK.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>QK)throw new Error("asset exceeds size cap");o.update(c),yield c}},KK(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},cG=e=>Vm(e)===Na()?Vm(Or(e)):Vm(e),lG=async e=>{let t=await Jm(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Ot(lt(e,n),{force:!0}).catch(()=>{})},L0=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Ot(r,{force:!0}).catch(()=>{});let o=!1;try{await zd(e,r),o=!0}catch{}try{await Zm(t,e),await ZK(za(e),cG(t))}catch(a){throw o&&await zd(r,e).catch(()=>{}),a}await Ot(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Ot(n,{force:!0}),await YK(t,n),await zd(n,e)},dG=async(e,t={})=>{let n=lt(e.root,"bin"),r=lt(e.root,"versions"),o=lt(n,Na());await La(n,{recursive:!0,mode:448}),await La(r,{recursive:!0,mode:448});let a=lt(r,e.version),i=(await Xm(a).catch(()=>{}))?.isFile()?a:lt(a,Na());if(!(await Xm(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??eu)(`${e.tagUrl}/SHA256SUMS`,Qd),d=l.ok?zm(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await La(Or(i),{recursive:!0,mode:448}),await lG(Or(i));let u=`${i}.part-${process.pid}`;try{await(t.download??ey)(`${e.tagUrl}/${e.asset}`,u,d),await jK(u,493),await zd(u,i)}catch(f){throw await Ot(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??L0)(o,i),{link:o,target:i,versionsDir:r}},uG=async e=>{let t=GK(e,["--version"],{stdio:"ignore",timeout:Qd});return!t.error&&t.status===0},pG=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??fo)(n);if(r.length>0){let o=await(t.resolveTarget??Te)(async()=>e);if(!o||!(await(t.repair??ht)(r,o.target)).every(po))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??sr)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Dt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},fG=async e=>{let t=await e.install();if(!await(e.smoke??uG)(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},hG=async(e,t)=>{let n=await Jm(e).catch(()=>[]);for(let r of n)t.includes(r)||await Ot(lt(e,r),{force:!0,recursive:!0}).catch(()=>{})},mG=async e=>{let t=await Jm(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Ot(lt(e,n),{force:!0}).catch(()=>{})},yG=async(e,t)=>{let n=async()=>{await Ot(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await La(e,{recursive:!1}),n}catch{}let r=await VK(e).catch(()=>{});if(!(!r||t-r.mtimeMs<nG)){await n();try{return await La(e,{recursive:!1}),n}catch{return}}},Ym=e=>lt(e,"update-state.json"),gG=async e=>{let t=await M(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},wG=1e3,bG=16*6e4,kG=e=>e.inFlight===0,AG=async(e,t,n={})=>{let r=n.probe??ke,o=n.sleep??(i=>new Promise(c=>setTimeout(c,i))),a=n.now??Date.now,s=a()+(n.timeoutMs??bG);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&kG(i))return!0;if(a()>=s)return!1;await o(wG)}},Ni=async(e={})=>{let t=e.now??Date.now,n=be;if(At(ft(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??pt(),o=e.root??q(),a;try{let s=await qm(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=T0(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Qm)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&Da(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await gG(Ym(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<tG)return{outcome:"failed",current:n,latest:l};let f=`${O0}/download/${_0}${l}`,p=await(e.load??P)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??iG)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?oG(w):{...P0(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 La(o,{recursive:!0,mode:448});let y=await yG(lt(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,v;try{await mG(lt(o,"bin"));let x=await qd(lt(o,"versions")).catch(()=>{}),A=await qd(lt(o,"bin",Na())).catch(()=>{}),I=A&&sc(A,x)?A:void 0,T=lt(o,"bin",Na());i&&process.platform==="win32"&&(await Xm(T).catch(()=>{}))?.isFile()&&(v=`${T}.rollback-${process.pid}`,await Zm(T,v));let B=()=>(e.installBinary??dG)({root:o,version:l,asset:c,tagUrl:f});i?b=await fG({install:B,smoke:e.smoke,rollback:async({link:X,target:V})=>{v?(await Zm(v,X),await Ot(za(X),{force:!0}).catch(()=>{})):I&&I!==V?await L0(X,I):(await Ot(X,{force:!0}),await Ot(za(X),{force:!0}).catch(()=>{}))},repoint:async X=>e.repoint?e.repoint(p,X):pG(p),prune:async()=>{await(e.pruneDurable??(X=>ic(X)))(r)}}):b=await B(),await hG(b.versionsDir,[l,n]),await Ot(Ym(o),{force:!0}).catch(()=>{})}finally{v&&await Ot(v,{force:!0}).catch(()=>{}),await y()}let S=e.bounceDaemon??Xu,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let x=p.fallbackPort??Ae,A=E?!0:await ew().catch(()=>!0),I=await S(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!A&&p.gateway&&((I?await(e.waitForDaemon??AG)(x,l):!0)?await Dt({port:x,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??nw)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await Z(Ym(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},D0=async(e={})=>{let t=e.context??pt(),n=await qm(t,e.root??q()),r=_o(e.root??q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:be,managedPath:n.link??r}:Ni({...e,context:t,allowNpmMigration:!0})},Ao=async(e={})=>{let t=e.context??pt(),n=e.root??q(),r=await qm(t,n),o=r.kind==="npm"||r.kind==="durable"?_o(n):void 0,a=await(e.load??P)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!T0(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=At(ft(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:be,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};var CG=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})},N0=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,vG=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},ty=async(e={})=>{let t=e.load??P,n=e.save??te,r=e.mutate??(e.load||e.save?vG(t,n):dg),o=e.loadDevKey??Be,a=e.heartbeat??wd,s=e.detectSeat??Nt,i=e.rewriteTools??yi,c=e.uninstallProxy??zt;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 Cr&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!N0(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 CG(p,s);if(!h)return"pending";let m=l.keyRefreshEnabled===!0,w=Number.isInteger(l.fallbackPort)&&l.fallbackPort>0&&l.fallbackPort<=65535?l.fallbackPort:Ae;if(m){let y=`http://${ut}:${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"||!N0(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"}};var SG=12e3,EG="anyray-wiring-probe-not-a-real-token",xG={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},ry={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},Co=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},M0=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},oy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},$0=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."],IG=e=>e.includes("no provider key configured for"),ay=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},sy=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>"]}),$i=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."]}),RG=(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?ay(t)?sy(e):oy(t)?$i(e):M0(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Co(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)."]}:IG(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Co(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")?$0([" \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}): ${Co(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).",...$0([" \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}: ${Co(t)}`,remedy:[]},OG=(e,t)=>{if(oy(t))return $i(e);if(ay(t))return sy(e);if(M0(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}: ${Co(t)}`,remedy:[]}},_G=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),TG=(e,t)=>{if(oy(t))return $i(e);if(ay(t))return sy(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")||_G(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}: ${Co(t)}`,remedy:[`The probe asks for a fixed model (${ry.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."]}},ny=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)}},PG=async(e,t)=>{if(!e.clientKey)return $i(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?$i(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Co(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},LG=(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."]}},Mi=async(e,t={})=>{let n=t.timeoutMs??SG,r=ce(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await PG(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 ny(`${e.anthropicBaseUrl}/v1/messages`,l,ry,n);return TG(d,u)}if(J(e,"anthropic")){let l={Authorization:`Bearer ${EG}`,"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 ny(`${e.anthropicBaseUrl}/v1/messages`,l,ry,n);return OG(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await ny(`${e.openaiBaseUrl}/chat/completions`,s,xG,n);return RG(i,c,t.tools??[])}catch(o){return LG(n,o)}};var F0=async e=>{let t=await P(),n;try{n=xr(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),F(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${qe(n)}`),t.gateway?F(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?F(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||F(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??C("(not set)")}`),k(` Team: ${t.team??C("(not set)")}`);let r=ft();r&&(K("Environment"),k(` Remote dev context: ${or(r)}`),At(r)&&F(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),F(" 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."),F(" The local proxy remains available until every managed tool moves.")):($(" Direct gateway routing with a proof-backed stable-key heartbeat."),F(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(Qe(t)&&t.fallbackPort),a=o?`http://${ut}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await ke(t.fallbackPort)?$(` Running on 127.0.0.1:${t.fallbackPort} \u2192 ${n} `+C("(auto-refreshes your key so long sessions never 401)")):(N(` Enabled on 127.0.0.1:${t.fallbackPort} but NOT responding \u2014 your tools cannot reach any gateway until it's back.`),k(C(" Re-run `anyray-connect`, or check the service logs.")))),K("Tools");for(let s of oe){if(!(await s.detect()).installed){F(` ${s.title}: not installed`);continue}if(!s.pointsAt){F(` ${s.title}: installed ${C("(status not introspectable)")}`);continue}let c=await s.pointsAt(Ii(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){$(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(C(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}$(` ${s.title}: pointed at Anyray${o&&xi(s.id)?C(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===_a&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await Md();l=Fd({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=Bd(l,d);N(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(C(` ${f}`))}else F(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as BG}from"node:fs";import{isAbsolute as UG}from"node:path";import{access as DG}from"node:fs/promises";import{constants as NG}from"node:fs";import{platform as $G}from"node:os";var MG=async e=>{try{return await DG(e,NG.F_OK),!0}catch{return!1}},FG=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"]:[],$a=async(e={})=>{let t=e.os??$G(),n=e.exists??MG;for(let r of FG(t))if(await n(r))return!0;return!1};var cn="connect",iy=e=>e.replace(/-/g,"_"),B0=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:cn,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:cn,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:cn,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:cn,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:cn,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:cn,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=iy(e.retrieval.kind);t.push({tool:cn,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":iy(e.verify.kind);t.push({tool:cn,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:cn,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:iy(e.hookLane.reason)}:{}})}t.push({tool:cn,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:cn,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function HG(){return be}var WG="ctx_doctor-probe-synthetic",KG=(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: ${dy(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 GG(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function jG(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function dy(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 U0=e=>Fd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),cy=e=>e.pointedAt===!1&&e.tombstoned!==!0&&U0(e)!=="unverifiable",H0=e=>e.registered&&e.command&&UG(e.command)?BG(e.command):null,ly=e=>(cy(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),VG=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,YG=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},W0=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},ZG=(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(yo),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},XG=async(e,t,n,r,o,a,s=n,i=Mi,c=!0,l=bo,d=Ao,u=Kt,f=ka)=>{let p=c?await Xd(e):null,h=!!(Qe(t)&&t.fallbackPort),m=h?await ke(t.fallbackPort):null,w=h?`http://${ut}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=t.enrolledCert?.payload,b=y?.expiresAt??t.enrolledCertExpiry??null,S=(await a())?.sso??null,E=jG({ssoLink:S,enrolledViaToken:!!t.enrolledTokenHash}),x=Ct(),A=await Tw(x),I=A?[]:$w(ge({origin:w})),T=[];for(let Y of r){let Ie=await Y.detect(),dt=null;if(Ie.installed&&Y.mcpStatus)try{let Ga=await Y.mcpStatus();dt={...Ga,commandOk:H0(Ga)}}catch{}let wt=Ie.installed&&Y.id===_a?await o():void 0,vo=Ie.installed&&Y.pointsAt?await Y.pointsAt(Ii(Y.id,e,w)):null,bt=await VG(vo,Y,t.managedTools??[]),Ha=vo===!1&&bt===null,Yi=bt===!1&&Y.routingPendingReload?await Y.routingPendingReload().catch(()=>!1):!1,Zi=Ie.installed?Y.runtimeDiagnostics?await Y.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:Y.routingOverrides?await Y.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:So,claudeCodeHookPolicy:Wa}=Zi,Xi=t.fleetToolPolicy,Ka=Xi?.enabled.includes(Y.id)?Xi.tiers?.[Y.id]??ga:void 0;T.push({id:Y.id,title:Y.title,installed:Ie.installed,...Ie.detail?{detail:Ie.detail}:{},pointedAt:bt,...Ha?{routingHeld:!0}:{},...Yi?{routingPendingReload:!0}:{},...So.length?{routingOverrides:So}:{},...Wa===void 0?{}:{claudeCodeHookPolicy:Wa},mcp:dt,...Ka?{policyTier:Ka}:{},...t.revertedTools?.includes(Y.id)?{tombstoned:!0}:{},...Y.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...wt===void 0?{}:{inferenceIntrospectable:wt.authoritative,...wt.authoritative?{}:{inferenceUnverifiableReason:wt.reason}}})}let B=s?await(async()=>{let{kind:Y,detail:Ie,remedy:dt}=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:Y,detail:Ie,remedy:dt}})():null,X=B?.kind==="provider-rejected"&&await YG(t.managedTools??[],r),V=B?{...B,...X?{notApplicableSubscription:!0}:{}}:null,H=n?KG(await ba({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:ce({user:t.name,team:t.team})},WG,{probe:!0}),{mode:E,ssoLink:S}):null,z=await u().catch(()=>({})),ye=An(z.hookLane),Ne=s?await W0(r):!1,ee=Ne?await(async()=>{let Y=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...qh(Y,{hookRegistered:Ne,neverInvoked:Jh(ye,Date.now())}),lastInvokedAt:kd(ye)}})():null,Fe=(await cr()).map(Y=>({adapter:Y.adapter,op:Y.op,requestedAt:Y.requestedAt,watcherAlive:dr(Y.watcherPid)})),xe=Fe.find(Y=>Y.adapter==="cursor"),_=xe?{op:xe.op,requestedAt:xe.requestedAt,watcherAlive:xe.watcherAlive}:null,L=!!t.refreshSchedulerEnabled,W=await Ic(),le=await d(),ie=t.persistenceOwner==="tray",gt=ie?await l(t)==="healthy":null,pe=await iE({daemonEnabled:h&&!ie,daemonHealthy:h?!!m:null,schedulerEnabled:L&&!ie,schedulerInstalled:W,binaryDurable:!Ke(rr())}),fe=await Iu(),de=0;p&&!p.reachable&&(de+=1),h&&!m&&(de+=1),ie?L&&!gt&&(de+=1):L&&!W&&(de+=1);for(let Y of T)de+=ly(Y);return V&&V.kind!=="ok"&&!V.notApplicableSubscription&&(de+=1),H&&H.kind!=="ok"&&(de+=1),ee?.verdict==="dark"&&(de+=1),I.length>0&&(de+=1),de+=Fe.filter(Y=>!Y.watcherAlive).length,fe.length>0&&(de+=1),{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:HG(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:ft(),selfUpdate:{managed:le.managed,available:le.available,autoUpdate:le.autoUpdate,state:le.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:L,installed:W,owner:ie?"tray":"os",...ie?{trayHealthy:!!gt}:{}},serviceRemoval:pe,retiredFallbackState:fe,fleetdPresent:await $a(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null},enrollment:{enrolled:!!y,deploymentId:y?.deploymentId??null,issuedAt:y?.issuedAt??null,expiresAt:b,expired:b?Date.parse(b)<Date.now():null,orgMode:E,ssoLink:S},shell:{profilePath:x,blockPresent:A,staleExports:I},tools:T,...t.fleetToolPolicy?{fleetPlan:fd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:_,pendingOps:Fe,ambientRepairs:ZG(z,r),verify:V,retrieval:H,hookLane:ee,problems:de}},JG=e=>{if(e.serviceRemoval.suspected){K("Endpoint security"),N(" Anyray installed these background services, but their files are gone from disk \u2014"),N(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),N(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)k(C(` missing: ${t}`));k(C(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(C(" tools straight at the gateway (your key then needs a periodic re-run).")),k(C(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(C(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},zG=e=>{if(e.retiredFallbackState.length!==0){K("Retired fallback lane"),O(" A cached organization provider key from the removed --fallback lane is still on this machine.");for(let t of e.retiredFallbackState)k(C(` ${t}`));k(C(" Fix: `anyray-connect doctor --repair` deletes it (a normal `anyray-connect` run does too)."))}},qG=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${or(e.connect.remoteContext)}`),At(e.connect.remoteContext)&&k(C(" 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":$(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||N(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":N(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),k(C(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":N(" Self-update is unavailable on this platform because no standalone binary is published."),k(C(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(C(" This copy is externally managed; update it with the method that installed it."));break;case"container":k(C(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(K("Gateway"),e.gateway.reachable===null?k(C(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?$(` Reachable: ${e.gateway.origin} ${C(`(${e.gateway.detail})`)}`):(O(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),k(C(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.fallbackProxy.enabled&&(K("Local key-refresh proxy"),e.fallbackProxy.healthy?$(` Running on 127.0.0.1:${e.fallbackProxy.port} \u2192 ${e.gateway.origin} `+C("(auto-refreshes your key so long sessions never 401)")):(O(` 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(C(" 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?$(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh and supervises the daemon."):(O(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),k(C(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?$(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(O(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||k(C(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),JG(e),zG(e),K("Personal key"),GG(e)){case"env":$(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":$(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":N(" Enrolled, but no personal key is cached locally right now."),k(C(" 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:N(" Enrollment required \u2014 no personal gateway key is available."),k(C(` Fix: ${dy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?N(` Enrollment cert expired ${C(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):$(` Enrollment cert valid until ${e.enrollment.expiresAt} ${C(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(K("Shell"),O(" This terminal still exports Anyray, but the config is gone."),k(C(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(C(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(C(" Anything you start from this terminal keeps reaching the gateway with")),k(C(" no credential, and fails with 401.")),k(C(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(C(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(C(" reuses the environment it captured at launch, so a new terminal")),k(C(" (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"),O(` ${fc(c)}.`),k(C(` ${hc(c)}`))}K("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])O(` ${c.title}: ${l.problem}.`),k(C(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(O(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),k(C(" Fix: re-run `anyray-connect` to re-register the current binary."))):$(` ${c.title}: retrieval MCP server registered ${C("(anyray_retrieve / anyray_recall)")}`):(N(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),k(C(" 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(C(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){k(C(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){$(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),k(C(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}$(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&xi(c.id)?C(" (via key-refresh proxy)"):""}`),o(c),c.id==="claude-code"&&k(C(" 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===_a&&k(C(` ${hA}`)),c.id==="codex"&&k(C(" 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=U0(c);if(l==="not-routed"||l==="unverifiable"){let d=Bd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});N(` ${c.title}: ${d.headline}`);for(let u of d.detail)k(C(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(N(` ${c.title}: reverted locally against admin policy (out of compliance)`),k(C(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?N(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):k(C(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(O(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),k(C(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(O(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),k(C(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(N(" No tools are pointed at this gateway yet."),k(C(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){K("Queued operations");for(let c of e.pendingOps){let l=Wt(c.adapter)?.title??c.adapter;c.watcherAlive?N(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(O(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),k(C(` 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=Wt(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?N(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=>Wt(d)?.title??d).join(", ");i.freshIds.length>0&&k(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&N(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(K("Auth probe"),e.verify.notApplicableSubscription)$(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")$(` ${e.verify.detail}`);else{O(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(C(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")$(` ${e.retrieval.detail}`);else{O(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(C(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")$(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){O(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(C(` ${c}`))}else{N(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(C(` ${c}`))}e.hookLane.lastInvokedAt!==null&&k(C(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}K("Summary"),e.problems===0?(e.verify?$(" No problems found."):$(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(C(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):O(` ${e.problems} problem(s) found \u2014 see fixes above.`)},QG=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}),ej=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Yh(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??ka,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??ze)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=An((await(t.readRefreshState??Kt)().catch(()=>({}))).hookLane),l=qh(i,{hookRegistered:await W0(t.adapters??oe).catch(()=>!1),neverInvoked:Jh(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:kd(c)},note:d}},tj=async(e,t,n={})=>{let r=n.adapters??oe,o=n.resolveTarget??Te,a=n.applyTools??ht,s=await ej(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&&(cy(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,ke);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 ${dy(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(v=>v.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),!po(y))continue;let b=e.tools.find(T=>T.id===y.id);if(!b)continue;let v=r.find(T=>T.id===y.id),S=b.mcp;if(v?.mcpStatus)try{let T=await v.mcpStatus();S={...T,commandOk:H0(T)}}catch{}let E=cy(b)?!0:b.pointedAt;if(v?.pointsAt&&b.pointedAt!==null)try{E=await v.pointsAt(Ii(v.id,e.gateway.origin,e.toolOrigin))}catch{}let x=b.routingOverrides,A=b.claudeCodeHookPolicy;if(v?.runtimeDiagnostics)try{let T=await v.runtimeDiagnostics();x=T.routingOverrides.length?T.routingOverrides:void 0,A=T.claudeCodeHookPolicy}catch{}else if(v?.routingOverrides)try{let T=await v.routingOverrides();x=T.length?T:void 0}catch{}let I={...b,pointedAt:E,mcp:S,...x?{routingOverrides:x}:{},...A===void 0?{}:{claudeCodeHookPolicy:A}};x||delete I.routingOverrides,A===void 0&&delete I.claudeCodeHookPolicy,w.set(y.id,I),g+=ly(b)-ly(I)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},nj=e=>{K("Repair"),e.entries.length===0&&$(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?$(` ${t.title}: re-applied`):t.status==="queued"?$(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(C(` ${t.title}: ${t.status}`)):O(` ${t.title}: ${t.status}`);for(let t of e.notes)k(C(` ${t}`))},K0=async(e,t={})=>{let n=await P();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of cE(n.fallbackPort??Ae))k(c?` ${c}`:"");return 0}let r;try{r=xr(e.gateway,n)}catch(c){return e.json?(console.log(JSON.stringify({error:c.message})),1):(k(j("Anyray connect \u2014 doctor")),O(` Gateway URL: ${c.message}`),k(C(" 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")),O(" --quick skips the network probes; it cannot be combined with --verify.")),1;let o=!e.noVerify&&!e.quick,a=await XG(r,n,!!e.verify&&!e.quick,t.adapters??oe,t.inferenceIntrospection??Md,t.fleetBootstrap??jt,o,t.verifyAuth??Mi,!e.quick,t.checkTray??bo,t.updateStatus??Ao,t.readRefreshState??Kt,t.probeHookLane??ka);e.repair&&a.retiredFallbackState.length>0&&(await rc(),a.retiredFallbackState=await Iu(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await tj(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(QG(i),null,2)):(qG(i),s&&nj(s));try{e.quick||await(t.reportHealth??zv)(B0(i),i.connect.version)}catch{}return i.problems===0?0:1};var rj=()=>{let e=[];for(let t of oe){let n=t.skillsDir?.();n&&e.push(n)}return e},G0=async e=>{let t=await P();k(j("Anyray connect \u2014 sync"));let n;try{n=xr(e.gateway,t)}catch(s){return O(s.message),1}F(`Gateway: ${n}`);let r=$E(t.clientKey,"anyray-placeholder"),o;try{o=await md(n,r)}catch(s){return O(`Team policy sync failed: ${hd(s)}`),1}let a=rj();if(a.length===0)oj();else if(o.skills.length===0)F("No team skills published yet \u2014 nothing to sync.");else{let s=await Pv(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?$(` ${i.name} ${C(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):F(` ${i.name} ${C(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await te({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){F(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${qe(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await yd(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&&F(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){F(`Fleet policy reconcile skipped: ${hd(s)}`)}return 0},oj=()=>{F("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as iV}from"node:zlib";import{promisify as cV}from"node:util";var _r={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},uy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),j0=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
- `,zd=(e,t={})=>{if(typeof e!="string")return cy(String(e??""));let n=Math.max(1,t.maxChars??_r.maxChars);if(e.length<=n)return cy(e);let r=e.length,o=Math.max(0,t.headChars??_r.headChars),a=Math.max(0,t.tailChars??_r.tailChars),s=Math.max(0,t.middleWindows??_r.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 v=l+Math.round((b+.5)/s*g),S=Math.min(d,Math.max(l,v)+Math.ceil(y/2)),E=Math.max(l,S-y),x=e.lastIndexOf(`
698
+ `,tu=(e,t={})=>{if(typeof e!="string")return uy(String(e??""));let n=Math.max(1,t.maxChars??_r.maxChars);if(e.length<=n)return uy(e);let r=e.length,o=Math.max(0,t.headChars??_r.headChars),a=Math.max(0,t.tailChars??_r.tailChars),s=Math.max(0,t.middleWindows??_r.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 v=l+Math.round((b+.5)/s*g),S=Math.min(d,Math.max(l,v)+Math.ceil(y/2)),E=Math.max(l,S-y),x=e.lastIndexOf(`
699
699
  `,E);x>=l&&(E=x+1);let A=e.indexOf(`
700
- `,S);A!==-1&&A<d&&(S=A),S>E&&u.push([E,S])}}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+=U0(g-m)),h+=e.slice(g,y),m=y;if(r>m&&(h+=U0(r-m)),h.length>=r)return cy(e);let w=r-h.length;return{text:h,trimmed:!0,originalChars:r,trimmedChars:h.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},QG=["stdout","content","output","text","result"],H0=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} ---
700
+ `,S);A!==-1&&A<d&&(S=A),S>E&&u.push([E,S])}}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+=j0(g-m)),h+=e.slice(g,y),m=y;if(r>m&&(h+=j0(r-m)),h.length>=r)return uy(e);let w=r-h.length;return{text:h,trimmed:!0,originalChars:r,trimmedChars:h.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},aj=["stdout","content","output","text","result"],V0=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=QG.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 ej=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},Ni={minChars:8e3,minDataLineRatio:.6,minDataLines:20},qd=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Ni.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Ni.minDataLineRatio,o=t.minDataLines??Ni.minDataLines,a=e.split(`
705
- `),s=0,i=0;for(let c of a)c.trim()&&(s++,ej(c)&&i++);return s===0||i<o?!1:i/s>=r};var $i=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,Qd={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"},G0=new Set(["npm","pnpm","yarn","bun"]),eu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},tj=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=eu(r[0]);if(o in Qd)return Qd[o];if((o==="npx"||o==="bunx")&&r[1]){let a=eu(r[1]);if(a in Qd)return Qd[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||G0.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},dy=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=tj(t);if(n)return n}return null},nj={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},rj=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,oj=(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},j0=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=eu(r[0]);if(G0.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&rj.test(i)}let a=r[1]?eu(r[1]):void 0;if(oj(o,a,r))return!1;let s=nj[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},aj=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==="]"},sj=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},ij=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=sj(t);return r>0&&t[r+1]===":"},cj=80,lj=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/cj),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,ij(e[o])&&r++;return n>0&&r/n>.3},dj=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,uj=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();(dj.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},pj=[/\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],ly=8192,fj=e=>{let t=e.length>2*ly?`${e.slice(0,ly)}
706
- ${e.slice(-ly)}`:e;return pj.some(n=>n.test(t))},hj=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),mj=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),yj=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},gj=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),W0=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(mj(i)){t.push($i(i));continue}let c=yj(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push($i(c)),o=12;continue}hj(i)||gj(i)||o>0&&(t.push($i(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}},wj=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,V0=e=>{let t=wj.exec(e);return t&&/[/.]/.test(t[1])?t:null},bj=/^([^\s:]+)-(\d+)-/,kj=e=>{if(e==="--")return!0;let t=bj.exec(e);return t!=null&&/[/.]/.test(t[1])},Aj=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>V0(r)!=null).length;return n>=3&&n/t.length>=.7},K0=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=V0(c);if(!l){if(kj(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($i(` ${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}},Cj=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(),vj=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=Cj(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=$i(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}},Y0=(e,t)=>{if(typeof t!="string"||t.length===0||aj(t))return null;let n=t.split(`
710
- `).filter(s=>s.trim()!==""),r=dy(e),o=fj(t),a=null;return r==="test-run"&&o?a=W0(n):r==="grep"&&(a=K0(n,.5)),a||(o?a=W0(n):Aj(n)?a=K0(n,.7):!uj(n)&&!lj(n)&&(a=vj(n))),!a||a.text.length>=t.length?null:a},uy=(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=aj.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 sj=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},Fi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},nu=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Fi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Fi.minDataLineRatio,o=t.minDataLines??Fi.minDataLines,a=e.split(`
705
+ `),s=0,i=0;for(let c of a)c.trim()&&(s++,sj(c)&&i++);return s===0||i<o?!1:i/s>=r};var Bi=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,ru={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"},X0=new Set(["npm","pnpm","yarn","bun"]),ou=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},ij=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=ou(r[0]);if(o in ru)return ru[o];if((o==="npx"||o==="bunx")&&r[1]){let a=ou(r[1]);if(a in ru)return ru[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||X0.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},fy=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=ij(t);if(n)return n}return null},cj={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},lj=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,dj=(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},J0=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=ou(r[0]);if(X0.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&lj.test(i)}let a=r[1]?ou(r[1]):void 0;if(dj(o,a,r))return!1;let s=cj[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},uj=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==="]"},pj=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},fj=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=pj(t);return r>0&&t[r+1]===":"},hj=80,mj=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/hj),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,fj(e[o])&&r++;return n>0&&r/n>.3},yj=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,gj=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();(yj.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},wj=[/\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],py=8192,bj=e=>{let t=e.length>2*py?`${e.slice(0,py)}
706
+ ${e.slice(-py)}`:e;return wj.some(n=>n.test(t))},kj=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),Aj=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),Cj=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},vj=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),Y0=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(Aj(i)){t.push(Bi(i));continue}let c=Cj(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Bi(c)),o=12;continue}kj(i)||vj(i)||o>0&&(t.push(Bi(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}},Sj=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,z0=e=>{let t=Sj.exec(e);return t&&/[/.]/.test(t[1])?t:null},Ej=/^([^\s:]+)-(\d+)-/,xj=e=>{if(e==="--")return!0;let t=Ej.exec(e);return t!=null&&/[/.]/.test(t[1])},Ij=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>z0(r)!=null).length;return n>=3&&n/t.length>=.7},Z0=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=z0(c);if(!l){if(xj(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(Bi(` ${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}},Rj=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(),Oj=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=Rj(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=Bi(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}},q0=(e,t)=>{if(typeof t!="string"||t.length===0||uj(t))return null;let n=t.split(`
710
+ `).filter(s=>s.trim()!==""),r=fy(e),o=bj(t),a=null;return r==="test-run"&&o?a=Y0(n):r==="grep"&&(a=Z0(n,.5)),a||(o?a=Y0(n):Ij(n)?a=Z0(n,.7):!gj(n)&&!mj(n)&&(a=Oj(n))),!a||a.text.length>=t.length?null:a},hy=(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`,Z0=e=>`
714
+ \u2026[anyray-hook digest \u2014 ${e}]\u2026`,Q0=e=>`
715
715
 
716
- \u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as Sj}from"node:crypto";import{homedir as Ej}from"node:os";import{join as tu}from"node:path";import{mkdir as xj,readdir as Ij,stat as py,unlink as X0,writeFile as Rj}from"node:fs/promises";var Oj=1440*60*1e3,J0=50,_j=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",Tj=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=q();try{if((await py(t)).isDirectory())return tu(t,"hook-tee")}catch{}return tu(Ej(),".anyray-hook-tee")},Pj=async e=>{try{let t=Date.now(),n=[];for(let r of await Ij(e)){let o=tu(e,r);try{let a=await py(o);if(!a.isFile())continue;t-a.mtimeMs>Oj?await X0(o):n.push({path:o,mtimeMs:a.mtimeMs})}catch{}}if(n.length>J0){n.sort((r,o)=>r.mtimeMs-o.mtimeMs);for(let r of n.slice(0,n.length-J0))await X0(r.path).catch(()=>{})}}catch{}},z0=async e=>{if(_j())return null;try{let t=await Tj();await xj(t,{recursive:!0,mode:448});let n=`${Sj("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=tu(t,n);try{if((await py(r)).isFile())return r}catch{}return await Rj(r,e,{mode:384}),await Pj(t),r}catch{return null}};import{createHash as Lj}from"node:crypto";import{homedir as q0}from"node:os";import{join as fy}from"node:path";import{readFile as Dj,writeFile as Nj,chmod as $j,stat as Mj,unlink as Fj}from"node:fs/promises";var Bj=200,Uj=1440*60*1e3,Hj=4e6,Q0=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",ex=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},Wj=()=>ex("ANYRAY_HOOK_CACHE_MAX_ENTRIES",Bj),tx=()=>ex("ANYRAY_HOOK_CACHE_TTL_MS",Uj),nx=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=fy(q0(),".anyray");try{if((await Mj(t)).isDirectory())return fy(t,"hook-cache.json")}catch{}return fy(q0(),".anyray-hook-cache.json")},rx=(e,t,n)=>Lj("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),ox=async e=>{try{let t=JSON.parse(await Dj(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},ax=async e=>{if(Q0())return null;try{let n=(await ox(await nx())).entries[e];return!n||Date.now()-n.at>tx()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},Kj=e=>{let t=Date.now(),n=tx(),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=Wj();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>Hj&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},sx=async(e,t)=>{if(Q0())return;let n;try{let r=await nx(),o=await ox(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=Kj(o.entries),n=`${r}.${process.pid}.tmp`,await Nj(n,JSON.stringify(o),{mode:384}),await $j(n,384),await fe(n,r)}catch{if(n)try{await Fj(n)}catch{}}};import{open as Gj,stat as jj}from"node:fs/promises";var ix=600,Vj=3,Yj=256e3,Zj=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
- `):"",Xj=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),Jj=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},zj=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=Zj(o.message?.content).trim();if(!(!a||Xj(a))&&(t.unshift(a),n+=a.length,t.length>=Vj||n>=ix))break}return t.join(`
718
- `).slice(0,ix)};var qj=e=>/(^|[\\/])subagents[\\/]/i.test(e),Qj=e=>/\.jsonl$/i.test(e),eV=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),cx=async e=>{let t={intent:"",kind:"unknown"};if(!e||!Qj(e))return t;let n;try{let{size:r}=await jj(e),o=Math.max(0,r-Yj),a=r-o;if(a<=0)return t;n=await Gj(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=Jj(i.split(`
720
- `));return eV(c)?{intent:zj(c),kind:qj(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var rV=3e3,oV=1500,aV=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:rV},sV={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},iV=new Set(["claude","opencode"]),cV=(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:sV[t]})},lV={cacheGet:async()=>null,cachePut:async()=>{}},dV=(e,t={cacheGet:ax,cachePut:sx,tee:z0})=>e==="claude"?t:lV,uV=1e3,pV=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),nu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),fV=e=>{try{let t=JSON.parse(e);if(!nu(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 nu(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},hV=e=>{try{let t=JSON.parse(e);return nu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},mV=e=>nu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
721
- `:"",hy=e=>Math.round(Math.max(0,e)/4),lx=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",yV=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),gV=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),wV=["tool_output","tool_response","tool_result"],bV=e=>{for(let t of wV)if(t in e)return e[t]},kV=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},AV=120,CV=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??uV))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=uy(r.stat,null).length+AV;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=uy(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}}},vV=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(yV.has(o)||gV(o))return n;let a=H0(bV(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(dx(o)&&l.retrievalContext!=="available")return n;let d=await CV(t,kV(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!qd(i,{minChars:oV})))return n;let p=i.length-u.length-f.length,h=async(E,x,A=E.length+f.length)=>{let I=d?.teePath??null;if(!I&&t.tee)try{I=await t.tee(i)}catch{I=null}let T=I?E.replaceAll("; not retrievable in this context]","]"):E,B=I&&!f?Z0(I):"",X=T+f+B,V=B.length,W=X;if(t.finalizeOutput)try{let ee=t.finalizeOutput(X);ee.length<=X.length&&(W=ee)}catch{W=X}let z=X.length-W.length,me=hy(Math.max(0,p-V))+x+hy(z);me>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,A+V-z),estTokensSaved:me,...d&&{digest:d.decision}});let De=a.rebuild(W);return{stdout:pV(De),replacement:De}},m=async()=>d?h(u,0):n;if(d&&u.length<=t.sizeGate)return h(u,0);let w=l.intent?`${l.intent}
722
- ${lx(r.tool_input)}`:lx(r.tool_input),g=rx(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 v=null;try{v=OV(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{v=null}if(v&&!v.handled&&(v=null),v)return v.optimized&&v.output.length<u.length?(await y({optimized:!0,output:v.output,tokensSaved:hy(u.length-v.output.length)}),h(v.output,0,u.length+f.length)):(await y({optimized:!1}),m());let S;try{S=t.localTrim(u)}catch{return m()}return S.trimmed?h(S.text,S.estTokensSaved):m()},Mi=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},SV=()=>{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")}},EV=nV(tV),xV=async e=>{try{let t=await EV(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},dx=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),IV=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},RV=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),OV=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),_V=2048,TV=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,_V),n=md(t);if(!n)return;await gS({at:Date.now(),status:e.status,code:n})}catch{}},PV=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),aV());try{let c=await xV(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...dx(t)||IV(t)&&a==="available"?{reversible:!0}:{},...RV(t)?{semanticRerank:!0}:{},output:r})),l=Xt(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 TV(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)}},ux=async(e="claude")=>{let t=await Mi();if(e!=="cursor"&&hV(t))return 0;let n=e==="cursor"?fV(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await my(n,e);if(e==="cursor"){let a=mV(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},my=async(e,t="claude",n)=>{await Sr(),await yS(t);let r=SV(),o=await rt(),a=o&&{...o,metadata:cV(o.metadata,t)},s=dV(t);return vV(e,{optimize:(i,c,l,d,u)=>PV(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await cx(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>zd(i,r),beacon:(i,c)=>pc(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??_r.maxChars,digestCommand:Y0,tee:s.tee,mediumBand:iV.has(t),finalizeOutput:n})};var px=async()=>0;var LV=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},DV=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??Gt)();if(!r)return;let o=await(t.ssoGate??Vn)({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}},NV=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},$V=()=>{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")}},MV=(e,t)=>{let n=t.minChars??Ni.minChars,r={maxChars:Math.min(_r.maxChars,n)},o=zd(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},fx=async()=>{let e=await NV(),t=await DV(e);t&&process.stdout.write(t);let n=$V(),r=await rt();return await LV(e,{isPaste:o=>qd(o,n),measure:o=>MV(o,n),beacon:o=>pc(r,"prompt",o)}),0};import{spawn as FV}from"node:child_process";var hx=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),BV=/[|&;<>`$()\n]/,mx=e=>{if(BV.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},UV=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!hx(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!hx(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(Nu)||!t.isRecognized(o)||mx(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},HV=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?mx(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 _j}from"node:crypto";import{homedir as Tj}from"node:os";import{join as au}from"node:path";import{mkdir as Pj,readdir as Lj,stat as my,unlink as ex,writeFile as Dj}from"node:fs/promises";var Nj=1440*60*1e3,tx=50,$j=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",Mj=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=q();try{if((await my(t)).isDirectory())return au(t,"hook-tee")}catch{}return au(Tj(),".anyray-hook-tee")},Fj=async e=>{try{let t=Date.now(),n=[];for(let r of await Lj(e)){let o=au(e,r);try{let a=await my(o);if(!a.isFile())continue;t-a.mtimeMs>Nj?await ex(o):n.push({path:o,mtimeMs:a.mtimeMs})}catch{}}if(n.length>tx){n.sort((r,o)=>r.mtimeMs-o.mtimeMs);for(let r of n.slice(0,n.length-tx))await ex(r.path).catch(()=>{})}}catch{}},nx=async e=>{if($j())return null;try{let t=await Mj();await Pj(t,{recursive:!0,mode:448});let n=`${_j("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=au(t,n);try{if((await my(r)).isFile())return r}catch{}return await Dj(r,e,{mode:384}),await Fj(t),r}catch{return null}};import{createHash as Bj}from"node:crypto";import{homedir as rx}from"node:os";import{join as yy}from"node:path";import{readFile as Uj,writeFile as Hj,chmod as Wj,stat as Kj,unlink as Gj}from"node:fs/promises";var jj=200,Vj=1440*60*1e3,Yj=4e6,ox=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",ax=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},Zj=()=>ax("ANYRAY_HOOK_CACHE_MAX_ENTRIES",jj),sx=()=>ax("ANYRAY_HOOK_CACHE_TTL_MS",Vj),ix=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=yy(rx(),".anyray");try{if((await Kj(t)).isDirectory())return yy(t,"hook-cache.json")}catch{}return yy(rx(),".anyray-hook-cache.json")},cx=(e,t,n)=>Bj("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),lx=async e=>{try{let t=JSON.parse(await Uj(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},dx=async e=>{if(ox())return null;try{let n=(await lx(await ix())).entries[e];return!n||Date.now()-n.at>sx()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},Xj=e=>{let t=Date.now(),n=sx(),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=Zj();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>Yj&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},ux=async(e,t)=>{if(ox())return;let n;try{let r=await ix(),o=await lx(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=Xj(o.entries),n=`${r}.${process.pid}.tmp`,await Hj(n,JSON.stringify(o),{mode:384}),await Wj(n,384),await he(n,r)}catch{if(n)try{await Gj(n)}catch{}}};import{open as Jj,stat as zj}from"node:fs/promises";var px=600,qj=3,Qj=256e3,eV=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
+ `):"",tV=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),nV=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},rV=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=eV(o.message?.content).trim();if(!(!a||tV(a))&&(t.unshift(a),n+=a.length,t.length>=qj||n>=px))break}return t.join(`
718
+ `).slice(0,px)};var oV=e=>/(^|[\\/])subagents[\\/]/i.test(e),aV=e=>/\.jsonl$/i.test(e),sV=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),fx=async e=>{let t={intent:"",kind:"unknown"};if(!e||!aV(e))return t;let n;try{let{size:r}=await zj(e),o=Math.max(0,r-Qj),a=r-o;if(a<=0)return t;n=await Jj(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=nV(i.split(`
720
+ `));return sV(c)?{intent:rV(c),kind:oV(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var lV=3e3,dV=1500,uV=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:lV},pV={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},fV=new Set(["claude","opencode"]),hV=(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:pV[t]})},mV={cacheGet:async()=>null,cachePut:async()=>{}},yV=(e,t={cacheGet:dx,cachePut:ux,tee:nx})=>e==="claude"?t:mV,gV=1e3,wV=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),su=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),bV=e=>{try{let t=JSON.parse(e);if(!su(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 su(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},kV=e=>{try{let t=JSON.parse(e);return su(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},AV=e=>su(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
721
+ `:"",gy=e=>Math.round(Math.max(0,e)/4),hx=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",CV=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),vV=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),SV=["tool_output","tool_response","tool_result"],EV=e=>{for(let t of SV)if(t in e)return e[t]},xV=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},IV=120,RV=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??gV))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=hy(r.stat,null).length+IV;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=hy(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}}},OV=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(CV.has(o)||vV(o))return n;let a=V0(EV(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(mx(o)&&l.retrievalContext!=="available")return n;let d=await RV(t,xV(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!nu(i,{minChars:dV})))return n;let p=i.length-u.length-f.length,h=async(E,x,A=E.length+f.length)=>{let I=d?.teePath??null;if(!I&&t.tee)try{I=await t.tee(i)}catch{I=null}let T=I?E.replaceAll("; not retrievable in this context]","]"):E,B=I&&!f?Q0(I):"",X=T+f+B,V=B.length,H=X;if(t.finalizeOutput)try{let ee=t.finalizeOutput(X);ee.length<=X.length&&(H=ee)}catch{H=X}let z=X.length-H.length,ye=gy(Math.max(0,p-V))+x+gy(z);ye>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,A+V-z),estTokensSaved:ye,...d&&{digest:d.decision}});let Ne=a.rebuild(H);return{stdout:wV(Ne),replacement:Ne}},m=async()=>d?h(u,0):n;if(d&&u.length<=t.sizeGate)return h(u,0);let w=l.intent?`${l.intent}
722
+ ${hx(r.tool_input)}`:hx(r.tool_input),g=cx(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 v=null;try{v=NV(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{v=null}if(v&&!v.handled&&(v=null),v)return v.optimized&&v.output.length<u.length?(await y({optimized:!0,output:v.output,tokensSaved:gy(u.length-v.output.length)}),h(v.output,0,u.length+f.length)):(await y({optimized:!1}),m());let S;try{S=t.localTrim(u)}catch{return m()}return S.trimmed?h(S.text,S.estTokensSaved):m()},Ui=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},_V=()=>{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")}},TV=cV(iV),PV=async e=>{try{let t=await TV(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},mx=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),LV=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},DV=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),NV=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),$V=2048,MV=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,$V),n=bd(t);if(!n)return;await CS({at:Date.now(),status:e.status,code:n})}catch{}},FV=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),uV());try{let c=await PV(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...mx(t)||LV(t)&&a==="available"?{reversible:!0}:{},...DV(t)?{semanticRerank:!0}:{},output:r})),l=Jt(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 MV(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)}},yx=async(e="claude")=>{let t=await Ui();if(e!=="cursor"&&kV(t))return 0;let n=e==="cursor"?bV(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await wy(n,e);if(e==="cursor"){let a=AV(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},wy=async(e,t="claude",n)=>{await Sr(),await AS(t);let r=_V(),o=await et(),a=o&&{...o,metadata:hV(o.metadata,t)},s=yV(t);return OV(e,{optimize:(i,c,l,d,u)=>FV(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await fx(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>tu(i,r),beacon:(i,c)=>yc(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??_r.maxChars,digestCommand:q0,tee:s.tee,mediumBand:fV.has(t),finalizeOutput:n})};var gx=async()=>0;var BV=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},UV=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??Vn)({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}},HV=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},WV=()=>{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")}},KV=(e,t)=>{let n=t.minChars??Fi.minChars,r={maxChars:Math.min(_r.maxChars,n)},o=tu(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},wx=async()=>{let e=await HV(),t=await UV(e);t&&process.stdout.write(t);let n=WV(),r=await et();return await BV(e,{isPaste:o=>nu(o,n),measure:o=>KV(o,n),beacon:o=>yc(r,"prompt",o)}),0};import{spawn as GV}from"node:child_process";var bx=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jV=/[|&;<>`$()\n]/,kx=e=>{if(jV.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},VV=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!bx(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!bx(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(Fu)||!t.isRecognized(o)||kx(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},YV=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?kx(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},WV=16*1024*1024,KV=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=FV(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>WV){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)}}),GV=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await my(n,"cursor");return typeof r=="string"?r:t},yx=e=>{let t=e[0]==="--b64"?e[1]:void 0;return HV(t,{exec:KV,trim:GV,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},gx=async()=>{let e=await Mi();if(process.platform==="win32")return 0;let t=UV(e,{isRecognized:n=>dy(n)!==null||j0(n),wrap:n=>Tt(Nu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as jV}from"node:crypto";import{homedir as wx}from"node:os";import{extname as VV,isAbsolute as YV,join as yy,resolve as Fi,sep as bx}from"node:path";import{chmod as ZV,readFile as XV,stat as Sx,unlink as JV,writeFile as zV}from"node:fs/promises";var wy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qV=16*1024,kx=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],QV=["pattern","query","regex","search"],e2=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"]),t2=720*60*1e3,n2=512,gy=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},r2=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],Ax=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(bx)?n:n+bx)),o2=(e,t,n)=>YV(e)?[Fi(e)]:[...new Set([Fi(t,e),...n.map(r=>Fi(r,e))])],Cx=(e,t,n)=>jV("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),vx=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),a2=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!wy(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!wy(o))return"";let a=r2(n.workspace_roots).map(d=>Fi(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=gy(o,QV);if(!d)return"";let u=gy(o,kx);return u&&!Ax(Fi(s,u),a)||!await t.remember(Cx(i,"Grep",d))?"":vx(`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=gy(o,kx);if(!c||e2.has(VV(c).toLowerCase()))return"";let l=await t.resolveFile(o2(c,s,a));return!l||l.bytes<qV||!Ax(l.path,a)||!await t.remember(Cx(i,"Read",l.path))?"":vx(`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.`)},s2=async e=>{for(let t of e)try{let n=await Sx(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},i2=async()=>{let e=yy(wx(),".anyray");try{if((await Sx(e)).isDirectory())return yy(e,"cursor-redirects.json")}catch{}return yy(wx(),".anyray-cursor-redirects.json")},c2=async e=>{let t;try{let n=await i2(),r=Date.now(),o={};try{let s=JSON.parse(await XV(n,"utf-8"));if(s?.v===1&&wy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=t2&&(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,n2);return t=`${n}.${process.pid}.tmp`,await zV(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await ZV(t,384),await fe(t,n),!0}catch{if(t)try{await JV(t)}catch{}return!1}},Ex=async()=>{let e=await Mi(),t="";try{t=await a2(e,{resolveFile:s2,remember:c2})}catch{t=""}return t&&process.stdout.write(t),0};var Bi=(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,l2=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Bi(n,"deviceCode"),o=Bi(n,"privateKeyPem"),a=Bi(n,"publicKeyPem"),s=Bi(n,"cpOrigin"),i=Bi(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}},d2=e=>new Promise(t=>setTimeout(t,e)),u2=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})},p2=async(e,t={})=>{let n=t.poll??xd,r=t.verify??an,o=t.loadProfile??P,a=t.saveProfile??te,s=t.saveDevKey??zi,i=t.readGateState??Er,c=t.writeGateState??Id,l=t.clearGateState??RS,d=t.sleep??d2,u=t.now??Date.now,f=t.recordMint??Aa,p=t.reserveMint??bo,h=t.applyClaudeCode??(async x=>{await nr.apply(x,{dryRun:!1})}),m=x=>u2(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 A=x instanceof Kt?x.kind:"cp-unreachable";return await m(A),A}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),v={...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(v)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let S;await p();for(let x=0;x<3;x++)try{S=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(A){if(A instanceof It||x===2)break;await d(1e3)}if(!S)return await m("gateway-unreachable"),"gateway-unreachable";let E={...v,gateway:y,name:S.user,team:e.team??S.team??v.team,clientKey:S.key,clientKeyExpiresAt:S.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:S.expiresAt});let x=ge({origin:y,clientKey:S.key,subscription:!0,user:E.name,team:E.team});return await h(x),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},f2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},xx=async()=>{let e=l2(await f2());if(e)try{await p2(e)}catch{}return 0};var h2=1e4,ky=/^[\w.:-]{1,64}$/,Vt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Ay=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,Ix=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),h2);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 Vt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},m2=e=>{let t=Ay(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}},y2=e=>{let t=Ay(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&ky.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&ky.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},g2=e=>{let t=Ay(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ie(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!ky.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}}},w2=e=>new Promise(t=>setTimeout(t,e)),b2=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Vt("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 Oa("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 Vt("invalid-team","Choose one of the teams shown above.");return s},k2=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??w2,a=t.loadProfile??P,s=t.saveProfile??te,i=t.clearDevKey??Va,c=t.chooseTeam??b2,l=t.apply??(async g=>{await nr.apply(g,{dryRun:!1})}),d=t.log??F,u=await a(),f=xr(e.gateway,u),p=await Ix(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=m2(p.body);if(p.status!==200||!h)throw new Vt("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??Ca)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await Ix(`${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 Vt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new Vt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=y2(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new Vt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??jt());continue}let b=g2(g.body);if(g.status!==200||!b)throw new Vt("login-failed","SSO login could not be completed.");let v={...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(v),await l(ge({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Vt("expired","SSO login expired before it completed. Run anyray-connect login again.")},A2=`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},ZV=16*1024*1024,XV=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=GV(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>ZV){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)}}),JV=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await wy(n,"cursor");return typeof r=="string"?r:t},Ax=e=>{let t=e[0]==="--b64"?e[1]:void 0;return YV(t,{exec:XV,trim:JV,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},Cx=async()=>{let e=await Ui();if(process.platform==="win32")return 0;let t=VV(e,{isRecognized:n=>fy(n)!==null||J0(n),wrap:n=>Pt(Fu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as zV}from"node:crypto";import{homedir as vx}from"node:os";import{extname as qV,isAbsolute as QV,join as by,resolve as Hi,sep as Sx}from"node:path";import{chmod as e2,readFile as t2,stat as Ox,unlink as n2,writeFile as r2}from"node:fs/promises";var Ay=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),o2=16*1024,Ex=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],a2=["pattern","query","regex","search"],s2=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"]),i2=720*60*1e3,c2=512,ky=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},l2=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],xx=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(Sx)?n:n+Sx)),d2=(e,t,n)=>QV(e)?[Hi(e)]:[...new Set([Hi(t,e),...n.map(r=>Hi(r,e))])],Ix=(e,t,n)=>zV("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),Rx=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),u2=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!Ay(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!Ay(o))return"";let a=l2(n.workspace_roots).map(d=>Hi(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=ky(o,a2);if(!d)return"";let u=ky(o,Ex);return u&&!xx(Hi(s,u),a)||!await t.remember(Ix(i,"Grep",d))?"":Rx(`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=ky(o,Ex);if(!c||s2.has(qV(c).toLowerCase()))return"";let l=await t.resolveFile(d2(c,s,a));return!l||l.bytes<o2||!xx(l.path,a)||!await t.remember(Ix(i,"Read",l.path))?"":Rx(`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.`)},p2=async e=>{for(let t of e)try{let n=await Ox(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},f2=async()=>{let e=by(vx(),".anyray");try{if((await Ox(e)).isDirectory())return by(e,"cursor-redirects.json")}catch{}return by(vx(),".anyray-cursor-redirects.json")},h2=async e=>{let t;try{let n=await f2(),r=Date.now(),o={};try{let s=JSON.parse(await t2(n,"utf-8"));if(s?.v===1&&Ay(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=i2&&(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,c2);return t=`${n}.${process.pid}.tmp`,await r2(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await e2(t,384),await he(t,n),!0}catch{if(t)try{await n2(t)}catch{}return!1}},_x=async()=>{let e=await Ui(),t="";try{t=await u2(e,{resolveFile:p2,remember:h2})}catch{t=""}return t&&process.stdout.write(t),0};var Wi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Cy=e=>typeof e=="string"&&e.trim()?e.trim():void 0,m2=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Wi(n,"deviceCode"),o=Wi(n,"privateKeyPem"),a=Wi(n,"publicKeyPem"),s=Wi(n,"cpOrigin"),i=Wi(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=Cy(n.gatewayUrl),f=Cy(n.gatewayOverride),p=Cy(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}},y2=e=>new Promise(t=>setTimeout(t,e)),g2=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})},w2=async(e,t={})=>{let n=t.poll??_d,r=t.verify??sn,o=t.loadProfile??P,a=t.saveProfile??te,s=t.saveDevKey??tc,i=t.readGateState??Er,c=t.writeGateState??Td,l=t.clearGateState??LS,d=t.sleep??y2,u=t.now??Date.now,f=t.recordMint??Aa,p=t.reserveMint??go,h=t.applyClaudeCode??(async x=>{await nr.apply(x,{dryRun:!1})}),m=x=>g2(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 A=x instanceof Gt?x.kind:"cp-unreachable";return await m(A),A}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),v={...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(v)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let S;await p();for(let x=0;x<3;x++)try{S=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(A){if(A instanceof It||x===2)break;await d(1e3)}if(!S)return await m("gateway-unreachable"),"gateway-unreachable";let E={...v,gateway:y,name:S.user,team:e.team??S.team??v.team,clientKey:S.key,clientKeyExpiresAt:S.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:S.expiresAt});let x=ge({origin:y,clientKey:S.key,subscription:!0,user:E.name,team:E.team});return await h(x),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},b2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},Tx=async()=>{let e=m2(await b2());if(e)try{await w2(e)}catch{}return 0};var k2=1e4,vy=/^[\w.:-]{1,64}$/,Yt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Sy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,Px=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),k2);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 Yt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},A2=e=>{let t=Sy(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}},C2=e=>{let t=Sy(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&vy.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&vy.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},v2=e=>{let t=Sy(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Re(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!vy.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}}},S2=e=>new Promise(t=>setTimeout(t,e)),E2=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Yt("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 Oa("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 Yt("invalid-team","Choose one of the teams shown above.");return s},x2=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??S2,a=t.loadProfile??P,s=t.saveProfile??te,i=t.clearDevKey??Xa,c=t.chooseTeam??E2,l=t.apply??(async g=>{await nr.apply(g,{dryRun:!1})}),d=t.log??F,u=await a(),f=xr(e.gateway,u),p=await Px(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=A2(p.body);if(p.status!==200||!h)throw new Yt("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??Ca)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await Px(`${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 Yt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new Yt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=C2(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new Yt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??Vt());continue}let b=v2(g.body);if(g.status!==200||!b)throw new Yt("login-failed","SSO login could not be completed.");let v={...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(v),await l(ge({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Yt("expired","SSO login expired before it completed. Run anyray-connect login again.")},I2=`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.`,Rx=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(A2),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return O(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return O(`unknown login option: ${a}`),1}try{let o=await k2({gateway:n,team:r},t);return $(`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(o instanceof Vt?o.message:"SSO login failed."),1}};var Ox=`anyray-connect update [--check] [--auto on|off] [--json]
729
+ omitted only when the identity authority supplies a default or sole team.`,Lx=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(I2),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return O(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return O(`unknown login option: ${a}`),1}try{let o=await x2({gateway:n,team:r},t);return $(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof yt)throw o;return O(o instanceof Yt?o.message:"SSO login failed."),1}};var Dx=`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
- `,C2=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},v2=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}.`}},_x=async e=>{let t;try{t=C2(e)}catch(o){return O(o.message),process.stderr.write(Ox),1}if(t.help)return process.stdout.write(Ox),0;if(t.auto!==void 0){let o=await P();if(o.autoUpdate!==!1!==t.auto&&await te({...o,autoUpdate:t.auto}),t.json||($(`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 Pi({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await vo();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=v2(n);switch(n.outcome){case"updated":case"migrated":$(r);break;case"current":$(r);break;case"available":case"migration-available":k(r),t.check&&k(`Run ${j("anyray-connect update")} to install it.`);break;case"migration-deferred":N(r),k(C("Use the newer npm runtime until that standalone release is published."));break;case"disabled":N(r),k(`Run ${j("anyray-connect update")} to install it now, or ${j("--auto on")} to resume.`);break;case"unmanaged":k(r),k(C("A copy your IT team placed is theirs to roll."));break;case"container":k(r);break;case"platform-unsupported":N(r),k(C("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":N(r);break;case"failed":return O(r),1}return 0};var S2=3e3,Tx=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>Jm(S2)),o=e.updateStatus??vo;t(`anyray-connect ${be}
740
+ `,R2=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},O2=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}.`}},Nx=async e=>{let t;try{t=R2(e)}catch(o){return O(o.message),process.stderr.write(Dx),1}if(t.help)return process.stdout.write(Dx),0;if(t.auto!==void 0){let o=await P();if(o.autoUpdate!==!1!==t.auto&&await te({...o,autoUpdate:t.auto}),t.json||($(`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 Ni({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await Ao();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=O2(n);switch(n.outcome){case"updated":case"migrated":$(r);break;case"current":$(r);break;case"available":case"migration-available":k(r),t.check&&k(`Run ${j("anyray-connect update")} to install it.`);break;case"migration-deferred":N(r),k(C("Use the newer npm runtime until that standalone release is published."));break;case"disabled":N(r),k(`Run ${j("anyray-connect update")} to install it now, or ${j("--auto on")} to resume.`);break;case"unmanaged":k(r),k(C("A copy your IT team placed is theirs to roll."));break;case"container":k(r);break;case"platform-unsupported":N(r),k(C("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":N(r);break;case"failed":return O(r),1}return 0};var _2=3e3,$x=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>Qm(_2)),o=e.updateStatus??Ao;t(`anyray-connect ${be}
743
743
  `);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&Da(a,be)>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: ${be} \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 E2=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},x2=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),I2=async(e={})=>{try{let t=await(e.readBootstrap??Gt)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??Qe)().catch(()=>{});let n=await(e.loadProfile??P)();if(Ie(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Vn)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??P)(),Ie(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Er)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!E2(a)||!x2(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"}}},Px=async(e={})=>{let t=await I2(e);return process.stdout.write(`${JSON.stringify(t)}
746
- `),0};var R2="2025-06-18",O2={name:"anyray",version:"1"},Lx={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}},_2=20,Dx={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}},Fx=Wm,T2=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,Fx)},P2=e=>e==="paths"||e==="lines"||e==="full"?e:"full",Nx={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-${Fx}). 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}},$x={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}},L2=8,D2=3,Mx={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}},N2=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
- `)},$2=(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,L2).map(([a,s])=>{let i=s.slice(0,D2).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 T2=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},P2=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),L2=async(e={})=>{try{let t=await(e.readBootstrap??jt)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??ze)().catch(()=>{});let n=await(e.loadProfile??P)();if(Re(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Vn)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??P)(),Re(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Er)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!T2(a)||!P2(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"}}},Mx=async(e={})=>{let t=await L2(e);return process.stdout.write(`${JSON.stringify(t)}
746
+ `),0};var D2="2025-06-18",N2={name:"anyray",version:"1"},Fx={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}},$2=20,Bx={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}},Kx=jm,M2=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,Kx)},F2=e=>e==="paths"||e==="lines"||e==="full"?e:"full",Ux={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-${Kx}). 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}},Hx={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}},B2=8,U2=3,Wx={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}},H2=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
+ `)},W2=(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,B2).map(([a,s])=>{let i=s.slice(0,U2).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
- `)},Le=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),Cy=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),ve=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
750
+ `)},De=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),Ey=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),ve=(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}:{}}},M2=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 Le(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:R2,capabilities:{tools:{}},serverInfo:O2});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Le(n??null,{});case"tools/list":{let a=[Lx,Dx];t.advertiseContextTools!==!1&&a.push(Nx,$x);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(Mx),Le(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===Lx.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Le(n??null,ve("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 Le(n??null,ve("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return Le(n??null,ve("grep must be non-empty",!0));if(s.grep.length>256)return Le(n??null,ve("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 Le(n??null,ve(p.kind==="slice-unsupported"?h:p.message,!0));if(f&&(p.partial===void 0||typeof p.totalLines!="number"))return Le(n??null,ve(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 ${_2} 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 Le(n??null,ve(`${m}
756
- ${p.content}`))}return Le(n??null,ve(p.content))}if(a.name===Dx.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Le(n??null,ve("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 Le(n??null,l.ok?ve(N2(l.matches)):ve(l.message,!0))}if(a.name===Nx.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Le(n??null,ve("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=T2(s.maxResults),d=P2(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 Le(n??null,u.ok?ve(c0(i,u,d)):ve(u.message??"search failed",!0))}if(a.name===Mx.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 Le(n??null,d.ok?ve(Bm(d)):ve(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Le(n??null,ve("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 Le(n??null,l.ok?ve($2(c,l)):ve(l.message??"history search failed",!0))}if(a.name===$x.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Le(n??null,ve("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 Le(n??null,l.ok?ve(Bm(l)):ve(l.message??"read failed",!0))}return Cy(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Cy(n??null,-32601,`method not found: ${o}`)}},F2=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),gd);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Xt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},B2=(e,t=!0)=>({retrieve:async(n,r)=>ba(await e(),n,r),recall:async(n,r)=>wd(await e(),n,r),search:(n,r,o)=>Wd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Hd(n,r),historySearch:n=>u0(n),historyOpen:n=>p0(n),historyAvailable:async()=>await Pa()>0,advertiseContextTools:t,heartbeat:()=>{e().then(F2).catch(()=>{})}}),Bx=async(e="auto",t={})=>{let n=B2(()=>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,Sr().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 M2(h,n)}catch(w){console.error("anyray mcp: dispatch error",w instanceof Error?w.message:w),m=h?.id===void 0?null:Cy(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 U2}from"node:child_process";var H2=e=>e==="jetbrains"||e==="windsurf"?e:void 0,W2=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}:{}}},K2=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 De(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:D2,capabilities:{tools:{}},serverInfo:N2});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return De(n??null,{});case"tools/list":{let a=[Fx,Bx];t.advertiseContextTools!==!1&&a.push(Ux,Hx);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(Wx),De(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===Fx.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return De(n??null,ve("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 De(n??null,ve("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return De(n??null,ve("grep must be non-empty",!0));if(s.grep.length>256)return De(n??null,ve("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 De(n??null,ve(p.kind==="slice-unsupported"?h:p.message,!0));if(f&&(p.partial===void 0||typeof p.totalLines!="number"))return De(n??null,ve(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 ${$2} 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 De(n??null,ve(`${m}
756
+ ${p.content}`))}return De(n??null,ve(p.content))}if(a.name===Bx.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return De(n??null,ve("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 De(n??null,l.ok?ve(H2(l.matches)):ve(l.message,!0))}if(a.name===Ux.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return De(n??null,ve("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=M2(s.maxResults),d=F2(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 De(n??null,u.ok?ve(f0(i,u,d)):ve(u.message??"search failed",!0))}if(a.name===Wx.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 De(n??null,d.ok?ve(Wm(d)):ve(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return De(n??null,ve("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 De(n??null,l.ok?ve(W2(c,l)):ve(l.message??"history search failed",!0))}if(a.name===Hx.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return De(n??null,ve("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 De(n??null,l.ok?ve(Wm(l)):ve(l.message??"read failed",!0))}return Ey(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Ey(n??null,-32601,`method not found: ${o}`)}},G2=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),Ad);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Jt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},j2=(e,t=!0)=>({retrieve:async(n,r)=>ba(await e(),n,r),recall:async(n,r)=>Cd(await e(),n,r),search:(n,r,o)=>Vd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>jd(n,r),historySearch:n=>y0(n),historyOpen:n=>g0(n),historyAvailable:async()=>await Pa()>0,advertiseContextTools:t,heartbeat:()=>{e().then(G2).catch(()=>{})}}),Gx=async(e="auto",t={})=>{let n=j2(()=>et(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,Sr().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 K2(h,n)}catch(w){console.error("anyray mcp: dispatch error",w instanceof Error?w.message:w),m=h?.id===void 0?null:Ey(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 V2}from"node:child_process";var Y2=e=>e==="jetbrains"||e==="windsurf"?e:void 0,Z2=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}},K2={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},G2=(e,t,n)=>{let r=new Set(K2[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}},Ux=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||!Ql(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
762
- `),1;await(n.refreshIfDue??Qe)().catch(()=>{});let s=await(n.loadProfile??P)(),i=await(n.readBootstrap??Gt)().catch(()=>{});if(i){let y=await(n.ssoGate??Vn)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(y.exitCode===2&&y.stderr)return await W2(y.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(y.stderr),1;s=await(n.loadProfile??P)()}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??Dt)():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=H2(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",p=(n.hookBinaryIsDurable??ce)(),h=av(d,t,{mcpServer:p?je("profile"):void 0})[f],m=n.spawn??U2,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=G2(e,a,h.env),v=m(w,g,{env:b,stdio:"inherit",windowsHide:!0});v.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
765
- `),y(1)}),v.once("exit",(S,E)=>{y(typeof S=="number"?S:E?1:0)})})};import{createReadStream as j2}from"node:fs";import{spawnSync as qx}from"node:child_process";import{createHash as V2}from"node:crypto";import{access as Qx,chmod as Ey,copyFile as Y2,lstat as Z2,mkdir as X2,mkdtemp as eI,readFile as iu,rename as J2,rm as Tr,stat as z2,writeFile as q2}from"node:fs/promises";import{constants as tI}from"node:fs";import{platform as cu,tmpdir as Q2}from"node:os";import{dirname as eY,isAbsolute as tY,join as ou}from"node:path";import{z as Me}from"zod";var nY="fleetd-installer-v4.89.2",Hx=`https://github.com/anyrayHQ/install/releases/download/${nY}`,rY=1e4,oY=1e4,Wx=31,aY=1500,nI=20*1024,vy=20,sY="0.25",iY="/var/tmp",Fa="/Library/LaunchDaemons/com.fleetdm.orbit.plist",au="/etc/default/orbit",Hi="/opt/orbit/anyray-enroll-secret.txt",rI="/opt/orbit/secret-orbit-node-key.txt",cY="/opt/orbit/bin/orbit/orbit",Wi="C:\\Program Files\\Orbit",lY=`${Wi}\\bin\\orbit`,oI=`${Wi}\\secret-orbit-node-key.txt`,Ui=`${Wi}\\secret.txt`,dY=`${Wi}\\fleet_url.txt`,aI=`${Wi}\\anyray-managed.txt`,su="Fleet osquery",xy="C:\\Windows\\System32\\sc.exe",uY="C:\\Windows\\System32\\whoami.exe",ru="C:\\Windows\\System32\\icacls.exe",pY="C:\\Windows\\System32\\msiexec.exe",Iy="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",Kx=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],fY=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],hY=`anyray-connect endpoint install
760
+ `),!0)}catch{return!1}},X2={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},J2=(e,t,n)=>{let r=new Set(X2[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}},jx=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||!rd(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
762
+ `),1;await(n.refreshIfDue??ze)().catch(()=>{});let s=await(n.loadProfile??P)(),i=await(n.readBootstrap??jt)().catch(()=>{});if(i){let y=await(n.ssoGate??Vn)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(y.exitCode===2&&y.stderr)return await Z2(y.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(y.stderr),1;s=await(n.loadProfile??P)()}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=Y2(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",p=(n.hookBinaryIsDurable??se)(),h=dv(d,t,{mcpServer:p?Ge("profile"):void 0})[f],m=n.spawn??V2,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=J2(e,a,h.env),v=m(w,g,{env:b,stdio:"inherit",windowsHide:!0});v.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
765
+ `),y(1)}),v.once("exit",(S,E)=>{y(typeof S=="number"?S:E?1:0)})})};import{createReadStream as z2}from"node:fs";import{spawnSync as rI}from"node:child_process";import{createHash as q2}from"node:crypto";import{access as oI,chmod as Ry,copyFile as Q2,lstat as eY,mkdir as tY,mkdtemp as aI,readFile as uu,rename as nY,rm as Tr,stat as rY,writeFile as oY}from"node:fs/promises";import{constants as sI}from"node:fs";import{platform as Ba,tmpdir as aY}from"node:os";import{dirname as sY,isAbsolute as iY,join as cu}from"node:path";import{z as Me}from"zod";var cY="fleetd-installer-v4.89.2",Vx=`https://github.com/anyrayHQ/install/releases/download/${cY}`,lY=1e4,dY=1e4,Yx=31,uY=1500,iI=20*1024,xy=20,pY="0.25",fY="/var/tmp",Fa="/Library/LaunchDaemons/com.fleetdm.orbit.plist",lu="/etc/default/orbit",Gi="/opt/orbit/anyray-enroll-secret.txt",cI="/opt/orbit/secret-orbit-node-key.txt",hY="/opt/orbit/bin/orbit/orbit",ji="C:\\Program Files\\Orbit",mY=`${ji}\\bin\\orbit`,lI=`${ji}\\secret-orbit-node-key.txt`,Ki=`${ji}\\secret.txt`,yY=`${ji}\\fleet_url.txt`,dI=`${ji}\\anyray-managed.txt`,du="Fleet osquery",Oy="C:\\Windows\\System32\\sc.exe",gY="C:\\Windows\\System32\\whoami.exe",iu="C:\\Windows\\System32\\icacls.exe",wY="C:\\Windows\\System32\\msiexec.exe",_y="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",Zx=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],bY=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],kY=`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.`,sI=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),ae=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},mY=Me.object({kind:Me.enum(["pkg","deb","rpm","msi"]),path:Me.string().min(1).refine(tY),sha256:Me.string().regex(/^[0-9a-f]{64}$/)}).strict(),yY=Me.object({action:Me.literal("restart"),os:Me.enum(["darwin","linux","win32"])}).strict(),gY=Me.object({action:Me.literal("configure"),os:Me.enum(["darwin","linux","win32"]),fleetUrl:Me.string().min(1).max(2048),enrollSecret:Me.string().min(1).max(4096),package:mY.optional()}).strict(),wY=Me.discriminatedUnion("action",[yY,gY]),Ki=(e,t)=>{let n=qx(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},_y=async e=>{try{return await Qx(e,tI.F_OK),!0}catch{return!1}},bY=async e=>{try{let t=await z2(e);return t.isFile()&&t.size>0}catch{return!1}},Ty=(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}},Sy=(e,t)=>Ty(e,t)!==null,Gx=e=>e==="win32"?Ui:Hi,kY=e=>e==="win32"?oI:rI,AY=e=>Sy(e,"ORBIT_FLEET_URL")&&Sy(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Hi}</string>`)&&!Sy(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),CY=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",Hi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Ry=(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()},iI=e=>{let t=e(xy,["qc",su,"8192"]);return t.status===0?t.stdout:""},Oy=e=>{let t=e(Iy,fY(su)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},vY=async e=>{try{return e==="win32"?Ry(e,iI(Ki)):Ry(e,await iu(e==="darwin"?Fa:au,"utf8"))}catch{return}},SY=async e=>{try{if(e==="win32")return await _y(aI)&&Ry(e,iI(Ki))!==void 0;let n=await iu(e==="darwin"?Fa:au,"utf8");return e==="darwin"?AY(n):CY(n)}catch{return!1}},cI=async(e,t={})=>{let n=t.exists??_y,r=t.command??Ki,o,a="absent";if(e==="win32")a=Oy(r),o=await n(lY)&&a!=="absent";else{let l=e==="darwin"?await n(Fa):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(cY)&&l}let s=await(t.configured??SY)(e),i=await(t.hasNodeKey??(()=>bY(kY(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}},EY=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),lI=(e,t)=>{let n=Ty(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},xY=(e,t)=>{let n=lI(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},jx=(e,t,n)=>{let r=`
773
+ available; on Windows, run it from a shell started as Administrator.`,Ly=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),uI=(e,t=Ba())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),pI=(e,t=Ba())=>Ly(e)&&t!=="win32",ae=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},AY=Me.object({kind:Me.enum(["pkg","deb","rpm","msi"]),path:Me.string().min(1).refine(iY),sha256:Me.string().regex(/^[0-9a-f]{64}$/)}).strict(),CY=Me.object({action:Me.literal("restart"),os:Me.enum(["darwin","linux","win32"])}).strict(),vY=Me.object({action:Me.literal("configure"),os:Me.enum(["darwin","linux","win32"]),fleetUrl:Me.string().min(1).max(2048),enrollSecret:Me.string().min(1).max(4096),package:AY.optional()}).strict(),SY=Me.discriminatedUnion("action",[CY,vY]),Vi=(e,t)=>{let n=rI(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},Dy=async e=>{try{return await oI(e,sI.F_OK),!0}catch{return!1}},EY=async e=>{try{let t=await rY(e);return t.isFile()&&t.size>0}catch{return!1}},Ny=(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}},Iy=(e,t)=>Ny(e,t)!==null,Xx=e=>e==="win32"?Ki:Gi,xY=e=>e==="win32"?lI:cI,IY=e=>Iy(e,"ORBIT_FLEET_URL")&&Iy(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Gi}</string>`)&&!Iy(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),RY=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",Gi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Ty=(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()},fI=e=>{let t=e(Oy,["qc",du,"8192"]);return t.status===0?t.stdout:""},Py=e=>{let t=e(_y,bY(du)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},OY=async e=>{try{return e==="win32"?Ty(e,fI(Vi)):Ty(e,await uu(e==="darwin"?Fa:lu,"utf8"))}catch{return}},_Y=async e=>{try{if(e==="win32")return await Dy(dI)&&Ty(e,fI(Vi))!==void 0;let n=await uu(e==="darwin"?Fa:lu,"utf8");return e==="darwin"?IY(n):RY(n)}catch{return!1}},hI=async(e,t={})=>{let n=t.exists??Dy,r=t.command??Vi,o,a="absent";if(e==="win32")a=Py(r),o=await n(mY)&&a!=="absent";else{let l=e==="darwin"?await n(Fa):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(hY)&&l}let s=await(t.configured??_Y)(e),i=await(t.hasNodeKey??(()=>EY(xY(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}},TY=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),mI=(e,t)=>{let n=Ny(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},PY=(e,t)=>{let n=mI(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},Jx=(e,t,n)=>{let r=`
776
776
  <key>${t}</key>
777
- <string>${EY(n)}</string>`,o=lI(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Ty(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new ae("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)},IY=(e,t,n=Hi)=>{let r=xY(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=jx(r,"ORBIT_FLEET_URL",t),jx(r,"ORBIT_ENROLL_SECRET_PATH",n)},RY=(e,t,n=Hi)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
777
+ <string>${TY(n)}</string>`,o=mI(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Ny(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new ae("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)},LY=(e,t,n=Gi)=>{let r=PY(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=Jx(r,"ORBIT_FLEET_URL",t),Jx(r,"ORBIT_ENROLL_SECRET_PATH",n)},DY=(e,t,n=Gi)=>{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.`,sI=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
- `},dI=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}},OY=Me.object({code:Me.string().min(1).optional(),message:Me.string().min(1).optional()}).passthrough(),Vx=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},_Y=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=OY.safeParse(t);if(!r.success)return n;let o=Vx(r.data.message??""),a=Vx(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},Yx=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??oY),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":be},body:"{}",signal:r.signal})}catch{throw new ae("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new ae("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new ae(_Y(a.status,c))}let s;try{s=await a.json()}catch{throw new ae("The gateway returned malformed endpoint enrollment data.")}let i=Me.object({fleetUrl:Me.string().min(1).max(2048),enrollSecret:Me.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!dI(i.data.fleetUrl))throw new ae("The gateway returned invalid endpoint enrollment data.");return i.data},TY=async(e={})=>{let t=e.exists??_y;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 ae("Linux endpoint installation requires either dpkg or rpm.")},PY=async e=>e==="darwin"?"pkg":e==="win32"?"msi":TY(),Py=e=>`fleetd.${e}`,LY=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",DY=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),rY);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},NY=async(e,t={})=>{let n=Py(e),r=t.fetchResponse??fetch,o;try{o=await DY(`${Hx}/SHA256SUMS`,r)}catch{throw new ae("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new ae(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=Zm(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await eI(ou(Q2(),"anyray-endpoint-")),i=ou(s,n);try{await Ey(s,448),await(t.download??zm)(`${Hx}/${n}`,i,a)}catch(c){if(await Tr(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Ti&&c.status===404)return;throw new ae("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Tr(s,{recursive:!0,force:!0})}},$Y=async(e,t,n)=>{await X2(eY(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Tr(r,{force:!0});try{await q2(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await J2(r,e)}catch(o){throw await Tr(r,{force:!0}).catch(()=>{}),o}},Zx=async e=>{let t=V2("sha256");for await(let n of j2(e))t.update(n);return t.digest("hex")},MY=async(e,t={})=>{let n=await Z2(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new ae("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await Zx(e.path)!==e.sha256)throw new ae("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await eI(ou(iY,"anyray-endpoint-root-")),o=ou(r,Py(e.kind));try{if(await Ey(r,448),await Y2(e.path,o),await Ey(o,384),await Zx(o)!==e.sha256)throw new ae("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Tr(r,{recursive:!0,force:!0})}}catch(a){throw await Tr(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ma=(e,t)=>{if(e.status!==0)throw new ae(t)},Xx="com.fleetdm.fleetd.config",FY="com.fleetdm.fleetd.enroll.secret",BY=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",rI],UY=[dY,oI],HY=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(Xx))throw new ae(`This machine already receives its endpoint configuration from an MDM profile (${Xx}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},Jx=async(e,t,n)=>{let r=n.removeFile??(o=>Tr(o,{force:!0}));for(let o of e==="win32"?UY:BY)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",FY,"/Library/Keychains/System.keychain"])},WY=e=>{e(ru,[Ui,"/inheritance:r"]),e(ru,[Ui,"/grant:r","*S-1-5-18:(F)"]),e(ru,[Ui,"/grant:r","*S-1-5-32-544:(F)"]),e(ru,[Ui,"/remove:g","*S-1-5-32-545"])},KY=(e,t,n)=>{if(e.kind==="pkg"){Ma(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ma(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ma(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ma(t(pY,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},GY=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<vy;r++){if(n=t("/bin/launchctl",["bootstrap","system",Fa]),n.status===0)return;t("/bin/sleep",[sY])}throw new ae(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(xy,["stop",su]);for(let n=0;n<vy;n++){let r=Oy(t);if(r==="Stopped"||r==="absent")break;t(Iy,Kx)}for(let n=0;n<vy;n++){if(t(xy,["start",su]).status===0||Oy(t)==="Running")return;t(Iy,Kx)}throw new ae("Orbit was configured, but the Windows service could not be started.")}Ma(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ma(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},jY=e=>new Promise(t=>setTimeout(t,e)),uI=async(e,t={})=>{let n=t.command??Ki,r=t.readText??(c=>iu(c,"utf8")),o=t.writeText??$Y,a=t.removeSecret??(()=>Tr(Gx(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&HY(n),e.package&&!LY(e.os,e.package.kind))throw new ae("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new ae("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await Jx(e.os,n,t),e.package){let d=await(t.preparePackage??MY)(e.package);i=d.cleanup,KY(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Fa);await o(Fa,IY(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(au);await o(au,RY(d,e.fleetUrl),420)}else await o(aI,`anyray
788
- `,384);e.os!=="win32"&&await Jx(e.os,n,t),await o(Gx(e.os),`${e.enrollSecret}
789
- `,384),e.os==="win32"&&WY(n),s=e.os!=="win32"}GY(e.os,n);let c=t.checkIn??(async d=>{let u=await cI(d);return u.running&&u.checkedIn}),l=t.wait??jY;for(let d=0;d<(t.attempts??Wx);d++){if(await c(e.os))return;d+1<(t.attempts??Wx)&&await l(aY)}throw new ae("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(()=>{})}},VY=async()=>{try{return await Qx("/dev/tty",tI.R_OK),!0}catch{return!1}},YY=12288,ZY=e=>{let t=e(uY,["/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>=YY},XY=async(e,t={})=>{if((t.os??cu())==="win32")return(t.elevated??(()=>ZY(t.command??Ki)))()?(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??VY)()){if(await(t.reexec??(async()=>1))()!==0)throw new ae("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"},JY=async e=>{let t=`${JSON.stringify(e)}
792
- `;if(Buffer.byteLength(t)>nI)throw new ae("The privileged endpoint plan is unexpectedly large.");let n=dn(["__anyray-endpoint-install"]);return qx("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},zY=async(e,t={})=>(t.withRoot??XY)(()=>(t.apply??uI)(e),{...t.root,reexec:()=>(t.sudo??JY)(e)}),zx=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return P();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return P();let t;try{let s=(await iu("/etc/passwd","utf8")).split(`
793
- `).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=cu()==="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 P()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},pI=async(e={},t={})=>{let n=t.os??cu();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new ae("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??cI)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??zx)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??vY)(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??Yx)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};F("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new ae("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??zx)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new ae("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??Yx)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>PY(r)))();if(i=await(t.stagePackage??NY)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${Py(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??zY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},Ly=e=>e instanceof ae?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",fI=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return k(hY),0;if(e.length!==1||e[0]!=="install")return O("Usage: anyray-connect endpoint install"),1;try{let t=await pI();return t.message&&(t.outcome==="installed"?$(t.message):F(t.message)),0}catch(t){return O(Ly(t)),1}},qY=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>nI)throw new ae("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new ae("The privileged endpoint plan is malformed.")}let r=wY.safeParse(n);if(!r.success||r.data.os!==cu()||r.data.action==="configure"&&!dI(r.data.fleetUrl))throw new ae("The privileged endpoint plan is invalid.");return r.data},hI=async e=>{if((process.getuid?.()??-1)!==0)return O("The privileged endpoint step must run as root."),1;if(e.length!==0)return O("The privileged endpoint step does not accept arguments."),1;try{return await uI(await qY()),0}catch(t){return O(Ly(t)),1}},mI=async(e,t=pI)=>{try{let n=await t(e);n.message&&(n.outcome==="installed"?$(n.message):F(n.message))}catch(n){F(`Endpoint agent: ${Ly(n)} Tool routing remains configured.`)}};import{execSync as Dy}from"node:child_process";import{hostname as QY}from"node:os";var eZ=e=>{try{if(e==="darwin"){let t=Dy("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=Dy('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 Dy("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},lu=(e={platform:process.platform,read:()=>eZ(process.platform),hostname:QY})=>e.read().trim()||e.hostname().trim();var tZ=(e,t=Date.now())=>e.credentialProtocol==="stable-heartbeat-v1"||!Cd(e,void 0,t),yI=async(e,t={})=>{if(!await(t.fleetdPresent??$a)())return{retired:!1,reason:"no-fleetd",messages:[]};if(!tZ(e,t.now??Date.now()))return{retired:!1,reason:"seat-could-lapse",messages:[]};let r=[],o=await(t.uninstallScheduler??ir)();r.push(...o.messages);let a=await(t.uninstallProxy??Jt)();return r.push(...a.messages),{retired:!0,messages:r}};var gI=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();return t?t.toLowerCase():(e.platform??process.platform)==="darwin"?(e.readMacUuid??(()=>lu()))().trim().toLowerCase():""};var wI=["reapply_config","remint","revert","revert_tool"],nZ=/^[a-z0-9][a-z0-9-]{0,31}$/;var rZ=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"||!wI.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&nZ.test(t.tool):t.tool===void 0},Ny=e=>e?.name??"error",bI=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":wI.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!rZ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",Ny(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",Ny(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:",Ny(i))}return a.kind};var oZ=1e4,Ba=e=>e?.name??"Error",$y=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(oZ)})}catch(o){console.error(`anyray seat offboard report: ${Ba(o)}`)}},aZ=e=>e==="reverted"||e==="queued",kI=async(e={})=>{let t=e.loadProfile??P,n=e.clearDeviceTokenState??Rd,r=e.reportSeatOffboarded??$y,o=e.clearEnrollment??qi,a=e.recordManagedTools??Xn,s=e.markSeatOffboarded??ec,i=e.adapterById??Ht,c=e.uninstallProxy??Jt,l=e.uninstallScheduler??ir,d=e.unitsPresent??Ci,u=e.saveProfile??te,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: ${Ba(E)}`)}let w=[],g=[],y=[];for(let E of p){let x=i(E);if(!x){y.push(E);continue}try{let A=await x.revert({dryRun:!1,fullRevert:!0});w.push({id:E,status:A.status}),aZ(A.status)?g.push(E):y.push(E)}catch(A){console.error(`anyray offboard: reverting ${E}: ${Ba(A)}`),y.push(E)}}let b=!0;try{await a(w,!0,!0)}catch(E){b=!1,console.error(`anyray offboard: recording managed tools: ${Ba(E)}`)}let v=y.length===0&&b,S=!1;if(v)try{await s(),S=!0}catch(E){console.error(`anyray offboard: stamping offboard: ${Ba(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: ${Ba(E)}`)}return{reverted:g,unresolved:y,enrollmentCleared:h,credentialHeld:m,recordPersisted:b,offboardMarked:S,ok:y.length===0&&!m&&b&&S}};var AI=e=>e?.name??"Error",CI=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??P,r=t.recordManagedTools??Xn,o=t.adapterById??Ht,a=t.isLocked??ui,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}: ${AI(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${AI(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as iZ}from"node:os";var EI=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
787
+ `},yI=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}},NY=Me.object({code:Me.string().min(1).optional(),message:Me.string().min(1).optional()}).passthrough(),zx=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},$Y=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=NY.safeParse(t);if(!r.success)return n;let o=zx(r.data.message??""),a=zx(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},qx=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??dY),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":be},body:"{}",signal:r.signal})}catch{throw new ae("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new ae("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new ae($Y(a.status,c))}let s;try{s=await a.json()}catch{throw new ae("The gateway returned malformed endpoint enrollment data.")}let i=Me.object({fleetUrl:Me.string().min(1).max(2048),enrollSecret:Me.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!yI(i.data.fleetUrl))throw new ae("The gateway returned invalid endpoint enrollment data.");return i.data},MY=async(e={})=>{let t=e.exists??Dy;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 ae("Linux endpoint installation requires either dpkg or rpm.")},FY=async e=>e==="darwin"?"pkg":e==="win32"?"msi":MY(),$y=e=>`fleetd.${e}`,BY=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",UY=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),lY);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},HY=async(e,t={})=>{let n=$y(e),r=t.fetchResponse??fetch,o;try{o=await UY(`${Vx}/SHA256SUMS`,r)}catch{throw new ae("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new ae(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=zm(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await aI(cu(aY(),"anyray-endpoint-")),i=cu(s,n);try{await Ry(s,448),await(t.download??ey)(`${Vx}/${n}`,i,a)}catch(c){if(await Tr(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Di&&c.status===404)return;throw new ae("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Tr(s,{recursive:!0,force:!0})}},WY=async(e,t,n)=>{await tY(sY(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Tr(r,{force:!0});try{await oY(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await nY(r,e)}catch(o){throw await Tr(r,{force:!0}).catch(()=>{}),o}},Qx=async e=>{let t=q2("sha256");for await(let n of z2(e))t.update(n);return t.digest("hex")},KY=async(e,t={})=>{let n=await eY(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new ae("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await Qx(e.path)!==e.sha256)throw new ae("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await aI(cu(fY,"anyray-endpoint-root-")),o=cu(r,$y(e.kind));try{if(await Ry(r,448),await Q2(e.path,o),await Ry(o,384),await Qx(o)!==e.sha256)throw new ae("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Tr(r,{recursive:!0,force:!0})}}catch(a){throw await Tr(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ma=(e,t)=>{if(e.status!==0)throw new ae(t)},eI="com.fleetdm.fleetd.config",GY="com.fleetdm.fleetd.enroll.secret",jY=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",cI],VY=[yY,lI],YY=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(eI))throw new ae(`This machine already receives its endpoint configuration from an MDM profile (${eI}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},tI=async(e,t,n)=>{let r=n.removeFile??(o=>Tr(o,{force:!0}));for(let o of e==="win32"?VY:jY)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",GY,"/Library/Keychains/System.keychain"])},ZY=e=>{e(iu,[Ki,"/inheritance:r"]),e(iu,[Ki,"/grant:r","*S-1-5-18:(F)"]),e(iu,[Ki,"/grant:r","*S-1-5-32-544:(F)"]),e(iu,[Ki,"/remove:g","*S-1-5-32-545"])},XY=(e,t,n)=>{if(e.kind==="pkg"){Ma(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ma(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ma(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ma(t(wY,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},JY=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<xy;r++){if(n=t("/bin/launchctl",["bootstrap","system",Fa]),n.status===0)return;t("/bin/sleep",[pY])}throw new ae(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(Oy,["stop",du]);for(let n=0;n<xy;n++){let r=Py(t);if(r==="Stopped"||r==="absent")break;t(_y,Zx)}for(let n=0;n<xy;n++){if(t(Oy,["start",du]).status===0||Py(t)==="Running")return;t(_y,Zx)}throw new ae("Orbit was configured, but the Windows service could not be started.")}Ma(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ma(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},zY=e=>new Promise(t=>setTimeout(t,e)),gI=async(e,t={})=>{let n=t.command??Vi,r=t.readText??(c=>uu(c,"utf8")),o=t.writeText??WY,a=t.removeSecret??(()=>Tr(Xx(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&YY(n),e.package&&!BY(e.os,e.package.kind))throw new ae("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new ae("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await tI(e.os,n,t),e.package){let d=await(t.preparePackage??KY)(e.package);i=d.cleanup,XY(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Fa);await o(Fa,LY(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(lu);await o(lu,DY(d,e.fleetUrl),420)}else await o(dI,`anyray
788
+ `,384);e.os!=="win32"&&await tI(e.os,n,t),await o(Xx(e.os),`${e.enrollSecret}
789
+ `,384),e.os==="win32"&&ZY(n),s=e.os!=="win32"}JY(e.os,n);let c=t.checkIn??(async d=>{let u=await hI(d);return u.running&&u.checkedIn}),l=t.wait??zY;for(let d=0;d<(t.attempts??Yx);d++){if(await c(e.os))return;d+1<(t.attempts??Yx)&&await l(uY)}throw new ae("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(()=>{})}},qY=async()=>{try{return await oI("/dev/tty",sI.R_OK),!0}catch{return!1}},QY=12288,eZ=e=>{let t=e(gY,["/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>=QY},tZ=async(e,t={})=>{if((t.os??Ba())==="win32")return(t.elevated??(()=>eZ(t.command??Vi)))()?(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??qY)()){if(await(t.reexec??(async()=>1))()!==0)throw new ae("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"},nZ=async e=>{let t=`${JSON.stringify(e)}
792
+ `;if(Buffer.byteLength(t)>iI)throw new ae("The privileged endpoint plan is unexpectedly large.");let n=dn(["__anyray-endpoint-install"]);return rI("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},rZ=async(e,t={})=>(t.withRoot??tZ)(()=>(t.apply??gI)(e),{...t.root,reexec:()=>(t.sudo??nZ)(e)}),nI=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return P();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return P();let t;try{let s=(await uu("/etc/passwd","utf8")).split(`
793
+ `).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Ba()==="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 P()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},wI=async(e={},t={})=>{let n=t.os??Ba();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new ae("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??hI)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??nI)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??OY)(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??qx)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};F("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new ae("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??nI)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new ae("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??qx)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>FY(r)))();if(i=await(t.stagePackage??HY)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${$y(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??rZ)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},My=e=>e instanceof ae?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",bI=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return k(kY),0;if(e.length!==1||e[0]!=="install")return O("Usage: anyray-connect endpoint install"),1;try{let t=await wI();return t.message&&(t.outcome==="installed"?$(t.message):F(t.message)),0}catch(t){return O(My(t)),1}},oZ=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>iI)throw new ae("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new ae("The privileged endpoint plan is malformed.")}let r=SY.safeParse(n);if(!r.success||r.data.os!==Ba()||r.data.action==="configure"&&!yI(r.data.fleetUrl))throw new ae("The privileged endpoint plan is invalid.");return r.data},kI=async e=>{if((process.getuid?.()??-1)!==0)return O("The privileged endpoint step must run as root."),1;if(e.length!==0)return O("The privileged endpoint step does not accept arguments."),1;try{return await gI(await oZ()),0}catch(t){return O(My(t)),1}},AI=async(e,t=wI)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?$(n.message):F(n.message)),n.outcome}catch(n){F(`Endpoint agent: ${My(n)} Tool routing remains configured.`);return}};import{execSync as Fy}from"node:child_process";import{hostname as aZ}from"node:os";var sZ=e=>{try{if(e==="darwin"){let t=Fy("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=Fy('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 Fy("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},pu=(e={platform:process.platform,read:()=>sZ(process.platform),hostname:aZ})=>e.read().trim()||e.hostname().trim();var iZ=(e,t=Date.now())=>e.credentialProtocol==="stable-heartbeat-v1"||!xd(e,void 0,t),CI=async(e,t={})=>{if(!await(t.fleetdPresent??$a)())return{retired:!1,reason:"no-fleetd",messages:[]};if(!iZ(e,t.now??Date.now()))return{retired:!1,reason:"seat-could-lapse",messages:[]};let r=[],o=await(t.uninstallScheduler??ir)();r.push(...o.messages);let a=await(t.uninstallProxy??zt)();return r.push(...a.messages),{retired:!0,messages:r}};var vI=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();return t?t.toLowerCase():(e.platform??process.platform)==="darwin"?(e.readMacUuid??(()=>pu()))().trim().toLowerCase():""};var SI=["reapply_config","remint","revert","revert_tool"],cZ=/^[a-z0-9][a-z0-9-]{0,31}$/;var lZ=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"||!SI.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&cZ.test(t.tool):t.tool===void 0},By=e=>e?.name??"error",EI=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":SI.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!lZ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",By(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",By(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:",By(i))}return a.kind};var dZ=1e4,Ua=e=>e?.name??"Error",Uy=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(dZ)})}catch(o){console.error(`anyray seat offboard report: ${Ua(o)}`)}},uZ=e=>e==="reverted"||e==="queued",xI=async(e={})=>{let t=e.loadProfile??P,n=e.clearDeviceTokenState??Pd,r=e.reportSeatOffboarded??Uy,o=e.clearEnrollment??nc,a=e.recordManagedTools??Xn,s=e.markSeatOffboarded??oc,i=e.adapterById??Wt,c=e.uninstallProxy??zt,l=e.uninstallScheduler??ir,d=e.unitsPresent??Ei,u=e.saveProfile??te,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: ${Ua(E)}`)}let w=[],g=[],y=[];for(let E of p){let x=i(E);if(!x){y.push(E);continue}try{let A=await x.revert({dryRun:!1,fullRevert:!0});w.push({id:E,status:A.status}),uZ(A.status)?g.push(E):y.push(E)}catch(A){console.error(`anyray offboard: reverting ${E}: ${Ua(A)}`),y.push(E)}}let b=!0;try{await a(w,!0,!0)}catch(E){b=!1,console.error(`anyray offboard: recording managed tools: ${Ua(E)}`)}let v=y.length===0&&b,S=!1;if(v)try{await s(),S=!0}catch(E){console.error(`anyray offboard: stamping offboard: ${Ua(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: ${Ua(E)}`)}return{reverted:g,unresolved:y,enrollmentCleared:h,credentialHeld:m,recordPersisted:b,offboardMarked:S,ok:y.length===0&&!m&&b&&S}};var II=e=>e?.name??"Error",RI=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??P,r=t.recordManagedTools??Xn,o=t.adapterById??Wt,a=t.isLocked??hi,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}: ${II(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${II(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as fZ}from"node:os";var TI=`${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]
@@ -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 ${C("sync")} last wrote \u2014 for zero-question re-runs.`,xI=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
830
+ per-skill versions ${C("sync")} last wrote \u2014 for zero-question re-runs.`,PI=`${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]
@@ -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 ${C("sync")} last wrote \u2014 for zero-question re-runs.`,cZ=e=>{let t=e?.trim();return t||IE()},II=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},lZ=e=>!e||e.length===0?oe:e.map(t=>{let n=Ht(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${oe.map(r=>r.id).join(", ")}`);return n}),dZ=(e,t)=>{if(K("Gateway target"),k(` Origin: ${et(e.origin)}`),e.byoUpstream)k(` Auth: BYO upstream key ${C(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&k(` Client key: personal gateway key (${Nt(e.clientKey)}) ${C("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=J(e,"anthropic")?et("your subscription"):"org key",r=J(e,"openai")?et("your subscription"):"org key";k(` Auth: auto ${C("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&k(` Client key: personal gateway key (${Nt(e.clientKey)})`)}else e.authMode==="subscription"?(k(` Auth: subscription pass-through ${C("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&k(` Client key: personal gateway key (${Nt(e.clientKey)}) ${C("rides x-anyray-api-key")}`)):e.clientKey?k(` Auth: personal gateway key (${Nt(e.clientKey)}) ${C("(replaces the placeholder)")}`):k(` Enrollment: ${C("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&k(` Cursor: ${et("native Team subscription")} ${C("(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: ${et("subscription-backed Gateway lane")} ${C("(verified macOS builds; Windows fails closed)")}`),k(` ${C("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(k(` Claude Desktop: ${et("third-party API lane")} ${C("(API-billed; switches the active local inference profile)")}`),k(` ${C("The first-party Claude subscription remains untouched.")}`))),k(` Attribution: ${le(e.metadata)??C("(none \u2014 pass --user)")}`)},vI=async(e,t)=>{K("Selected tools");for(let n of e){let r=await n.detect();r.installed?k(` ${n.title} ${C(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):F(` ${n.title} ${C(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},uZ=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Ie(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},pZ={loadDevKey:Be,saveDevKey:zi,clearDevKey:Va,saveProfile:te},fZ=async(e,t,n,r=pZ,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}},hZ=async(e,t,n,r,o)=>{n.dryRun||await Qi();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} ${C(`(${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"?$(` ${p.status}`):p.status==="manual"?(s.push(u.title),p.manualAudience==="admin"?(i.push(u.title),c.push(u.id),N(" blocked by machine policy \u2014 your IT team owns this one")):N(" manual step required (see above)")):p.status==="held"?F(" left on its own plan (no change)"):F(` ${p.status}`)}catch(p){l.push({id:u.id,status:"failed"}),O(` failed: ${p instanceof Error?p.message:String(p)}`)}}if(d.length>0&&F(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await rc().catch(()=>[]);u.length&&F(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},mZ=(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},yZ=async(e,t,n=iZ())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!eb(i,n)||!Qw(i,n))continue;let c=zw(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:qw(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},gZ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,wZ=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?`}`,bZ=async(e,t={})=>{let n=t.requestQuit??(a=>nb(a)),r=t.waitFor??(a=>rb(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),$(` Closed ${a.title}.`);continue}N(` ${a.title} is still open \u2014 leaving it alone.`),F(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},kZ=(e,t={})=>{let n=t.relaunch??(o=>ob(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),$(` Reopened ${o.title}.`)):N(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},du=e=>e.changesBilling!==!0,AZ=async(e,t,n={})=>{let r=n.hasEnrollment??vu,o=n.canMultiSelect??A0,a=n.multiSelect??C0,s=n.prompt??Oa,i=n.registry??oe;if(k(j("Anyray connect \u2014 guided setup")),k(C("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||N("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&&Oi(d)&&Vd(d)){e.enroll=d;break}N("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}N("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&&Oi(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=ln(d);break}catch{N("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=>du(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:du(h)?void 0:"moves inference spend from your subscription to the org API bill",selected:du(h),requiresExplicitChoice:!du(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){N(`Unknown or unavailable tool id${m.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(f.length===0){N("Choose at least one installed tool.");continue}e.tools=f}if(!e.tools)throw new bt}l.length>0&&F(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},CZ=async(e,t)=>{K("Verifying the connection");let n=await _i("Checking the gateway\u2026",()=>Di(e,{tools:t}));n.kind==="ok"?$(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?N(` ${n.detail}`):O(` ${n.detail}`);for(let r of n.remedy)k(C(` ${r}`))},vZ=5e3,SZ=500,SI=3,EZ=600*1e3,xZ=async()=>{try{let e=await sZ(await Io());return Date.now()-e.mtimeMs}catch{return Number.POSITIVE_INFINITY}},IZ=async(e={})=>{try{let t=await(e.load??P)();if(t.keyRefreshEnabled!==!0){if((e.draining??Xu)()||!await(e.unitExists??Zg)()||await(e.profileAgeMs??xZ)()<EZ)return;await(e.uninstall??Jt)(t.fallbackPort??Ae);return}if(!t.gateway||t.persistenceOwner==="tray"&&await(e.checkTray??Ao)(t)==="healthy")return;let n=t.fallbackPort??Ae,r=e.probe??ke,o=e.probeGapMs??SZ;for(let s=0;s<SI;s++){if(await r(n,s===0?void 0:vZ)!==null)return;s<SI-1&&o>0&&await new Promise(c=>setTimeout(c,o))}if((e.draining??Xu)())return;let a=await(e.install??Lt)({port:n,remoteOrigin:new URL(t.gateway).origin});if(!a.ok)for(let s of a.messages)console.error(s)}catch{}},RZ=async(e,t,n={})=>{let r=n.install??Lt,o=n.probe??ke,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?($(` Running on 127.0.0.1:${t} \u2192 ${e.origin} \u2014 your key refreshes automatically, no restart needed.`),vn(e,t)):(N(" Key-refresh proxy did not come up \u2014 pointing tools directly at the gateway for now."),k(C(s.ok?" It will retry on the next run; check the service logs if it persists.":At(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)},OZ=async(e,t={})=>{if(e.dryRun)return;let n=t.install??sr,r=t.uninstall??ir;if(e.want&&e.trayManaged){e.announcePrimary&&(K("Automatic key refresh"),$(" 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&&$(" Your gateway key now re-mints every ~30 min \u2014 no tool will 401 on a stale key mid-session.")}o.ok||await te({...await P(),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 te({...await P(),refreshSchedulerEnabled:!1}),$(" Removed the automatic key-refresh schedule.")}},_Z=new Set(["login","wizard","status","doctor","sync","device-url"]),TZ=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),PZ=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."}},LZ=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=$m(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]||!TZ.has(e[0])},My=async(e,t)=>{try{return await $Z(e,t)}catch(n){if(n instanceof bt)return console.error(C("Cancelled \u2014 nothing was written.")),130;throw n}},DZ=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??jt)())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??Ra)(a)?"proceed":"declined"},NZ=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return ux(n)}if(e[0]==="__anyray-codex-hook")return px();if(e[0]==="__anyray-prompt-hook")return fx();if(e[0]==="__anyray-shell-pretool")return gx();if(e[0]==="__anyray-shell-run")return yx(e.slice(1));if(e[0]==="__anyray-read-pretool")return Ex();if(e[0]==="__anyray-sso-gate")return PS(e.slice(1));if(e[0]==="__anyray-sso-poll")return xx();if(e[0]==="__anyray-vscode-gate")return Px();if(e[0]==="__anyray-spawn-refresh")return await Sr(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return Bx(n)}if(e[0]==="__anyray-acp-agent")return Ux(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return hI(e.slice(1));if(e[0]==="__anyray-refresh"){await qm(),await Qe({runAmbientSelfcheck:!0}),await pm(),await IZ(),await wS(),await bS();let n=await P().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await te(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await $a().catch(()=>!1);if(await yI(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=gI(),i=n.enrolledCert;if(s&&i){let l=await Be().catch(()=>{});l&&await _v(o,a,i,l,s).catch(()=>{})}await bI(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await Qe({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?CI(d):(await kI()).ok?"ok":"failed"}).catch(()=>{})}}return await Pi(),0}if(e[0]==="__anyray-fallback-proxy")return JS();if(e[0]==="__anyray-persistence")return qS(e.slice(1));if(e[0]==="__anyray-quit-watch")return aE(e.slice(1));if(e[0]===Zs)return BE(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return Tx();try{let n=await hg(e);if(n!==void 0)return n}catch(n){return O(`Could not persist anyray-connect for long-lived integrations: ${n instanceof Error?n.message:String(n)}`),1}if(LZ(e)){let n=PZ(await O0());n?.level==="warn"?N(n.message):n&&console.error(n.message)}if(e[0]==="managed")return yE(e.slice(1));if(e[0]==="endpoint")return fI(e.slice(1));if(e[0]==="print-key")return kE(e.slice(1));if(e[0]==="models")return CE(e.slice(1));if(e[0]==="copilot-login")return vE(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=$m(n);return r?My(r,!1):QE(n)}if(e[0]==="retrieve")return t0(e.slice(1));if(e[0]==="recall")return n0(e.slice(1));if(e[0]==="history")return h0(e.slice(1));if(e[0]==="migrate")return y0(e.slice(1));if(e[0]==="login")return Rx(e.slice(1));if(e[0]==="update")return _x(e.slice(1));let t=e[0];if(t&&_Z.has(t)){let n=e.slice(1),r;try{r=II(n)}catch(o){return O(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?xI:EI),0):t==="status"?L0({gateway:r.gateway}):t==="doctor"?F0({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?B0({gateway:r.gateway}):t==="device-url"?SE():My(n,!0)}return My(e,!1)},RI=async e=>{try{return await NZ(e)}catch(t){if(t instanceof bt)return console.error(C("Cancelled.")),130;throw t}},$Z=async(e,t,n={})=>{let r=n.isInteractive??jt,o;try{o=II(e)}catch(_){return O(_.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?xI:EI),0;if(o.revert&&(o.sso||o.enroll||o.claim))return O("--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?(O("--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):$E({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return O("--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 O("--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 _;try{_=new URL(o.upstream.trim())}catch{return O(`invalid --upstream URL: "${o.upstream}"`),1}if(_.protocol!=="http:"&&_.protocol!=="https:")return O(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let L=o.upstreamKey.trim();if(!L)return O("--upstream-key must not be empty."),1;a={url:Ye(o.upstream),key:L}}let s=await P();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let _=await qm();(_==="migrated"||_==="already-direct")&&(s=await P())}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream),o.retiredFallbackFlag&&N("--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&&jt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??AZ)(o,s),c=!0);let l;try{l=lZ(o.tools)}catch(_){return O(_.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&Oi(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 _=Vd(o.enroll);if(_)try{let L=await _i("Resolving enrollment link\u2026",()=>b0(_)),H=!o.gateway;H&&(o.gateway=L.gatewayUrl),d=L.deploymentId,u=L.email,f=!0,H&&F(`Enrollment link${L.org?` for ${L.org}`:""}: gateway ${L.gatewayUrl}`),L.seatMode&&!o.subscription&&(o.subscription=!0,F("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(L){let H=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(H)F(`Could not resolve the gateway from the enrollment link \u2014 using ${H}.`);else return O(L instanceof Error?L.message:String(L)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)F("dry run: not enrolled (skipped redeeming the enrollment link).");else{let _=CS(o.claim);if(!_)return O("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let L=await _i("Connecting this machine\u2026",()=>vS({cpOrigin:_.cpOrigin,claim:_.claim,gatewayUrl:o.gateway}));p={cert:L.cert,privateKeyPem:L.privateKeyPem},L.deploymentId&&(d=L.deploymentId),!o.gateway&&L.gatewayUrl&&(o.gateway=L.gatewayUrl),h=L.ssoLink}catch(L){return O(L instanceof Error?L.message:String(L)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)F("dry run: not enrolled via SSO (skipped minting a personal key).");else{let _=Rt(o.sso);if(!_)return O(Oi(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 L=await Ed({cpOrigin:_.cpOrigin,tenantId:_.tenantId,gatewayUrl:o.gateway,log:ye=>F(ye),open:r()?Ca:void 0}),H=await _i("Waiting for SSO sign-in\u2026",()=>xd(L,{gatewayUrl:o.gateway}));p={cert:H.cert,privateKeyPem:H.privateKeyPem},H.deploymentId&&(d=H.deploymentId),!o.gateway&&H.gatewayUrl&&(o.gateway=H.gatewayUrl)}catch(L){return O(L instanceof Error?L.message:String(L)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=ln(o.gateway)}catch(_){return O(_.message),1}let g,y;m&&!o.revert&&F(`Gateway: ${w} ${C("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&By(w)&&N(`${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(),v=b||uZ(s),S,E,x,A,I,T,B=s.credentialProtocol==="stable-heartbeat-v1",X=async _=>{await bo();let L=Ov(_.token),H=Tv(s.enrolledCert,s.enrolledCertExpiry,_.deploymentId,Date.now(),L,s.enrolledTokenHash,_.expectedUser),ye=H?await Be():void 0,se=H&&ye&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:ye,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,we=ie=>Pv({cpOrigin:_.cpOrigin,token:_.token,gatewayOrigin:w,email:_.email,team:_.team,machineId:_.machineId,deploymentId:_.deploymentId,reuse:ie?se:void 0}),We=!!se,ue=await(async()=>{try{return await we(We)}catch(ie){if(se&&ie instanceof It)return F("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),We=!1,await we(!1);throw ie}})();v=ue.clientKey,o.user||=ue.user,o.team||=ue.team,S=ue.cert,E=ue.cert.payload.expiresAt,T=ue.expiresAt,B=ue.capabilities?.includes(pi)===!0,I=void 0,We||(x=ue.privateKeyPem),We||(A=L),$(`Enrolled${ue.user?` as ${ue.user}`:""}${We?" (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)F("dry run: not enrolled (skipped minting a personal key).");else{let _=Vd(o.enroll);if(!_)return O(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 L=o.machine?lu():void 0,H=u??cZ(o.user),ye=o.machine?`machine:${L}`:f?H:void 0;await X({cpOrigin:_.cpOrigin,token:_.token,email:H,team:o.team,machineId:L,deploymentId:d,expectedUser:ye})}catch(L){return O(L instanceof Error?L.message:String(L)),L instanceof It&&F("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 bo();try{let _=await an(w,p.cert,p.privateKeyPem);v=_.key,o.user||=_.user,o.team||=_.team,S=p.cert,E=p.cert.payload.expiresAt,x=p.privateKeyPem,T=_.expiresAt,B=_.capabilities?.includes(pi)===!0;let L=o.sso?Rt(o.sso):void 0;I=L?`${L.cpOrigin}/sso/${L.tenantId}`:h,$(`Enrolled${_.user?` as ${_.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(_){return O(_ instanceof Error?_.message:String(_)),_ instanceof It&&F("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.yes;g=await OE(o.user,s.name,_),y=await _E(o.team,s.team,_)}let V;!o.revert&&!o.subscription&&!o.placeholder&&(V=await Dt(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):V.anthropic?et("signed in \u2192 your subscription"):C("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${V.openai?et("signed in \u2192 your subscription"):C("not signed in \u2192 org key")}`),!V.anthropic&&!V.openai&&!V.copilot&&ts()&&(N(" No subscription sign-ins found on this host. Sign-ins do not cross the"),N(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),N(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),N(" and re-run, or everything below routes on the org key instead.")));let W=ge({origin:w,placeholderKey:o.key,clientKey:v,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:V,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&&!Ie(W.clientKey))return O("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 _="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(N(` ${_}`),F(" Dry run only \u2014 no placeholder configuration will be written."),await vI(l,"after-enrollment"),F(`
1029
- Dry run complete \u2014 no files were written.`),0):(O(` ${_}`),1)}o.revert||dZ(W,l),c&&!o.revert&&await vI(l,"plan"),o.dryRun&&F(`
1030
- Dry run \u2014 no files will be written.`);let De=await DZ(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(De==="non-interactive")return O(`
1031
- Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(De==="declined")return F(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 _=await jd(W.origin);if(!_.reachable)return O(`
1032
- Gateway ${W.origin} is not reachable (${_.detail}).`),k(C(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
1026
+ per-skill versions ${C("sync")} last wrote \u2014 for zero-question re-runs.`,hZ=e=>{let t=e?.trim();return t||PE()},LI=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},mZ=e=>!e||e.length===0?oe:e.map(t=>{let n=Wt(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${oe.map(r=>r.id).join(", ")}`);return n}),yZ=(e,t)=>{if(K("Gateway target"),k(` Origin: ${qe(e.origin)}`),e.byoUpstream)k(` Auth: BYO upstream key ${C(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&k(` Client key: personal gateway key (${$t(e.clientKey)}) ${C("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=J(e,"anthropic")?qe("your subscription"):"org key",r=J(e,"openai")?qe("your subscription"):"org key";k(` Auth: auto ${C("(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 ${C("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&k(` Client key: personal gateway key (${$t(e.clientKey)}) ${C("rides x-anyray-api-key")}`)):e.clientKey?k(` Auth: personal gateway key (${$t(e.clientKey)}) ${C("(replaces the placeholder)")}`):k(` Enrollment: ${C("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&k(` Cursor: ${qe("native Team subscription")} ${C("(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: ${qe("subscription-backed Gateway lane")} ${C("(verified macOS builds; Windows fails closed)")}`),k(` ${C("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(k(` Claude Desktop: ${qe("third-party API lane")} ${C("(API-billed; switches the active local inference profile)")}`),k(` ${C("The first-party Claude subscription remains untouched.")}`))),k(` Attribution: ${ce(e.metadata)??C("(none \u2014 pass --user)")}`)},OI=async(e,t)=>{K("Selected tools");for(let n of e){let r=await n.detect();r.installed?k(` ${n.title} ${C(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):F(` ${n.title} ${C(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},gZ=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Re(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},wZ={loadDevKey:Be,saveDevKey:tc,clearDevKey:Xa,saveProfile:te},bZ=async(e,t,n,r=wZ,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}},kZ=async(e,t,n,r,o)=>{n.dryRun||await rc();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} ${C(`(${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"?$(` ${p.status}`):p.status==="manual"?(s.push(u.title),p.manualAudience==="admin"?(i.push(u.title),c.push(u.id),N(" blocked by machine policy \u2014 your IT team owns this one")):N(" manual step required (see above)")):p.status==="held"?F(" left on its own plan (no change)"):F(` ${p.status}`)}catch(p){l.push({id:u.id,status:"failed"}),O(` failed: ${p instanceof Error?p.message:String(p)}`)}}if(d.length>0&&F(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await ic().catch(()=>[]);u.length&&F(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},AZ=(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},CZ=async(e,t,n=fZ())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!ab(i,n)||!ob(i,n))continue;let c=nb(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:rb(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},vZ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,SZ=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?`}`,EZ=async(e,t={})=>{let n=t.requestQuit??(a=>ib(a)),r=t.waitFor??(a=>cb(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),$(` Closed ${a.title}.`);continue}N(` ${a.title} is still open \u2014 leaving it alone.`),F(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},xZ=(e,t={})=>{let n=t.relaunch??(o=>lb(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),$(` Reopened ${o.title}.`)):N(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},fu=e=>e.changesBilling!==!0,IZ=async(e,t,n={})=>{let r=n.hasEnrollment??xu,o=n.canMultiSelect??x0,a=n.multiSelect??I0,s=n.prompt??Oa,i=n.registry??oe;if(k(j("Anyray connect \u2014 guided setup")),k(C("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 yt;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||N("Choose one of the three connection methods.")}if(!c)throw new yt;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&Pi(d)&&Jd(d)){e.enroll=d;break}N("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}N("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&&Pi(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=ln(d);break}catch{N("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new yt}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=>fu(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:fu(h)?void 0:"moves inference spend from your subscription to the org API bill",selected:fu(h),requiresExplicitChoice:!fu(h)}))});if(p.kind==="cancelled")throw new yt;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){N(`Unknown or unavailable tool id${m.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(f.length===0){N("Choose at least one installed tool.");continue}e.tools=f}if(!e.tools)throw new yt}l.length>0&&F(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},RZ=async(e,t)=>{K("Verifying the connection");let n=await Li("Checking the gateway\u2026",()=>Mi(e,{tools:t}));n.kind==="ok"?$(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?N(` ${n.detail}`):O(` ${n.detail}`);for(let r of n.remedy)k(C(` ${r}`))},OZ=5e3,_Z=500,_I=3,TZ=600*1e3,PZ=async()=>{try{let e=await pZ(await Io());return Date.now()-e.mtimeMs}catch{return Number.POSITIVE_INFINITY}},LZ=async(e={})=>{try{let t=await(e.load??P)();if(t.keyRefreshEnabled!==!0){if((e.draining??qu)()||!await(e.unitExists??Qg)()||await(e.profileAgeMs??PZ)()<TZ)return;await(e.uninstall??zt)(t.fallbackPort??Ae);return}if(!t.gateway||t.persistenceOwner==="tray"&&await(e.checkTray??bo)(t)==="healthy")return;let n=t.fallbackPort??Ae,r=e.probe??ke,o=e.probeGapMs??_Z;for(let s=0;s<_I;s++){if(await r(n,s===0?void 0:OZ)!==null)return;s<_I-1&&o>0&&await new Promise(c=>setTimeout(c,o))}if((e.draining??qu)())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{}},DZ=async(e,t,n={})=>{let r=n.install??Dt,o=n.probe??ke,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?($(` Running on 127.0.0.1:${t} \u2192 ${e.origin} \u2014 your key refreshes automatically, no restart needed.`),vn(e,t)):(N(" Key-refresh proxy did not come up \u2014 pointing tools directly at the gateway for now."),k(C(s.ok?" It will retry on the next run; check the service logs if it persists.":At(ft())?" 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)},NZ=async(e,t={})=>{if(e.dryRun)return;let n=t.install??sr,r=t.uninstall??ir;if(e.want&&e.trayManaged){e.announcePrimary&&(K("Automatic key refresh"),$(" 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&&$(" Your gateway key now re-mints every ~30 min \u2014 no tool will 401 on a stale key mid-session.")}o.ok||await te({...await P(),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 te({...await P(),refreshSchedulerEnabled:!1}),$(" Removed the automatic key-refresh schedule.")}},$Z=new Set(["login","wizard","status","doctor","sync","device-url"]),MZ=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),FZ=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."}},BZ=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=Bm(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]||!MZ.has(e[0])},Hy=async(e,t)=>{try{return await WZ(e,t)}catch(n){if(n instanceof yt)return console.error(C("Cancelled \u2014 nothing was written.")),130;throw n}},UZ=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??Ra)(a)?"proceed":"declined"},HZ=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return yx(n)}if(e[0]==="__anyray-codex-hook")return gx();if(e[0]==="__anyray-prompt-hook")return wx();if(e[0]==="__anyray-shell-pretool")return Cx();if(e[0]==="__anyray-shell-run")return Ax(e.slice(1));if(e[0]==="__anyray-read-pretool")return _x();if(e[0]==="__anyray-sso-gate")return MS(e.slice(1));if(e[0]==="__anyray-sso-poll")return Tx();if(e[0]==="__anyray-vscode-gate")return Mx();if(e[0]==="__anyray-spawn-refresh")return await Sr(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return Gx(n)}if(e[0]==="__anyray-acp-agent")return jx(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return kI(e.slice(1));if(e[0]==="__anyray-refresh"){await ty(),await ze({runAmbientSelfcheck:!0}),await mm(),await LZ(),await vS(),await SS();let n=await P().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await te(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await $a().catch(()=>!1);if(await CI(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=vI(),i=n.enrolledCert;if(s&&i){let l=await Be().catch(()=>{});l&&await Nv(o,a,i,l,s).catch(()=>{})}await EI(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await ze({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?RI(d):(await xI()).ok?"ok":"failed"}).catch(()=>{})}}return await Ni(),0}if(e[0]==="__anyray-fallback-proxy")return tE();if(e[0]==="__anyray-persistence")return rE(e.slice(1));if(e[0]==="__anyray-quit-watch")return dE(e.slice(1));if(e[0]===zs)return GE(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return $x();try{let n=await bg(e);if(n!==void 0)return n}catch(n){return O(`Could not persist anyray-connect for long-lived integrations: ${n instanceof Error?n.message:String(n)}`),1}if(BZ(e)){let n=FZ(await D0());n?.level==="warn"?N(n.message):n&&console.error(n.message)}if(e[0]==="managed")return AE(e.slice(1));if(e[0]==="endpoint")return bI(e.slice(1));if(e[0]==="print-key")return EE(e.slice(1));if(e[0]==="models")return IE(e.slice(1));if(e[0]==="copilot-login")return RE(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=Bm(n);return r?Hy(r,!1):o0(n)}if(e[0]==="retrieve")return s0(e.slice(1));if(e[0]==="recall")return i0(e.slice(1));if(e[0]==="history")return b0(e.slice(1));if(e[0]==="migrate")return A0(e.slice(1));if(e[0]==="login")return Lx(e.slice(1));if(e[0]==="update")return Nx(e.slice(1));let t=e[0];if(t&&$Z.has(t)){let n=e.slice(1),r;try{r=LI(n)}catch(o){return O(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?PI:TI),0):t==="status"?F0({gateway:r.gateway}):t==="doctor"?K0({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?G0({gateway:r.gateway}):t==="device-url"?OE():Hy(n,!0)}return Hy(e,!1)},DI=async e=>{try{return await HZ(e)}catch(t){if(t instanceof yt)return console.error(C("Cancelled.")),130;throw t}},WZ=async(e,t,n={})=>{let r=n.isInteractive??Vt,o;try{o=LI(e)}catch(_){return O(_.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?PI:TI),0;if(o.revert&&(o.sso||o.enroll||o.claim))return O("--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?(O("--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):HE({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return O("--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 O("--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 _;try{_=new URL(o.upstream.trim())}catch{return O(`invalid --upstream URL: "${o.upstream}"`),1}if(_.protocol!=="http:"&&_.protocol!=="https:")return O(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let L=o.upstreamKey.trim();if(!L)return O("--upstream-key must not be empty."),1;a={url:je(o.upstream),key:L}}let s=await P();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let _=await ty();(_==="migrated"||_==="already-direct")&&(s=await P())}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream),o.retiredFallbackFlag&&N("--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??IZ)(o,s),c=!0);let l;try{l=mZ(o.tools)}catch(_){return O(_.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&Pi(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 _=Jd(o.enroll);if(_)try{let L=await Li("Resolving enrollment link\u2026",()=>S0(_)),W=!o.gateway;W&&(o.gateway=L.gatewayUrl),d=L.deploymentId,u=L.email,f=!0,W&&F(`Enrollment link${L.org?` for ${L.org}`:""}: gateway ${L.gatewayUrl}`),L.seatMode&&!o.subscription&&(o.subscription=!0,F("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(L){let W=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(W)F(`Could not resolve the gateway from the enrollment link \u2014 using ${W}.`);else return O(L instanceof Error?L.message:String(L)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)F("dry run: not enrolled (skipped redeeming the enrollment link).");else{let _=IS(o.claim);if(!_)return O("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let L=await Li("Connecting this machine\u2026",()=>RS({cpOrigin:_.cpOrigin,claim:_.claim,gatewayUrl:o.gateway}));p={cert:L.cert,privateKeyPem:L.privateKeyPem},L.deploymentId&&(d=L.deploymentId),!o.gateway&&L.gatewayUrl&&(o.gateway=L.gatewayUrl),h=L.ssoLink}catch(L){return O(L instanceof Error?L.message:String(L)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)F("dry run: not enrolled via SSO (skipped minting a personal key).");else{let _=Rt(o.sso);if(!_)return O(Pi(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 L=await Od({cpOrigin:_.cpOrigin,tenantId:_.tenantId,gatewayUrl:o.gateway,log:le=>F(le),open:r()?Ca:void 0}),W=await Li("Waiting for SSO sign-in\u2026",()=>_d(L,{gatewayUrl:o.gateway}));p={cert:W.cert,privateKeyPem:W.privateKeyPem},W.deploymentId&&(d=W.deploymentId),!o.gateway&&W.gatewayUrl&&(o.gateway=W.gatewayUrl)}catch(L){return O(L instanceof Error?L.message:String(L)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=ln(o.gateway)}catch(_){return O(_.message),1}let g,y;m&&!o.revert&&F(`Gateway: ${w} ${C("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&Gy(w)&&N(`${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(),v=b||gZ(s),S,E,x,A,I,T,B=s.credentialProtocol==="stable-heartbeat-v1",X=async _=>{await go();let L=Dv(_.token),W=$v(s.enrolledCert,s.enrolledCertExpiry,_.deploymentId,Date.now(),L,s.enrolledTokenHash,_.expectedUser),le=W?await Be():void 0,ie=W&&le&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:le,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,gt=de=>Mv({cpOrigin:_.cpOrigin,token:_.token,gatewayOrigin:w,email:_.email,team:_.team,machineId:_.machineId,deploymentId:_.deploymentId,reuse:de?ie:void 0}),pe=!!ie,fe=await(async()=>{try{return await gt(pe)}catch(de){if(ie&&de instanceof It)return F("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),pe=!1,await gt(!1);throw de}})();v=fe.clientKey,o.user||=fe.user,o.team||=fe.team,S=fe.cert,E=fe.cert.payload.expiresAt,T=fe.expiresAt,B=fe.capabilities?.includes(mi)===!0,I=void 0,pe||(x=fe.privateKeyPem),pe||(A=L),$(`Enrolled${fe.user?` as ${fe.user}`:""}${pe?" (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)F("dry run: not enrolled (skipped minting a personal key).");else{let _=Jd(o.enroll);if(!_)return O(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 L=o.machine?pu():void 0,W=u??hZ(o.user),le=o.machine?`machine:${L}`:f?W:void 0;await X({cpOrigin:_.cpOrigin,token:_.token,email:W,team:o.team,machineId:L,deploymentId:d,expectedUser:le})}catch(L){return O(L instanceof Error?L.message:String(L)),L instanceof It&&F("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 go();try{let _=await sn(w,p.cert,p.privateKeyPem);v=_.key,o.user||=_.user,o.team||=_.team,S=p.cert,E=p.cert.payload.expiresAt,x=p.privateKeyPem,T=_.expiresAt,B=_.capabilities?.includes(mi)===!0;let L=o.sso?Rt(o.sso):void 0;I=L?`${L.cpOrigin}/sso/${L.tenantId}`:h,$(`Enrolled${_.user?` as ${_.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(_){return O(_ instanceof Error?_.message:String(_)),_ instanceof It&&F("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.yes;g=await DE(o.user,s.name,_),y=await NE(o.team,s.team,_)}let V;!o.revert&&!o.subscription&&!o.placeholder&&(V=await Nt(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?qe("BYO upstream key (passthrough)"):V.anthropic?qe("signed in \u2192 your subscription"):C("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${V.openai?qe("signed in \u2192 your subscription"):C("not signed in \u2192 org key")}`),!V.anthropic&&!V.openai&&!V.copilot&&os()&&(N(" No subscription sign-ins found on this host. Sign-ins do not cross the"),N(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),N(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),N(" and re-run, or everything below routes on the org key instead.")));let H=ge({origin:w,placeholderKey:o.key,clientKey:v,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:V,user:g,team:y,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),z=o.revert===!0&&(o.tools?.length??0)===0,ye={dryRun:o.dryRun,fullRevert:z};if(!o.revert&&H.clientKey&&!Re(H.clientKey))return O("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&&!H.clientKey){K("Enrollment required");let _="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(N(` ${_}`),F(" Dry run only \u2014 no placeholder configuration will be written."),await OI(l,"after-enrollment"),F(`
1029
+ Dry run complete \u2014 no files were written.`),0):(O(` ${_}`),1)}o.revert||yZ(H,l),c&&!o.revert&&await OI(l,"plan"),o.dryRun&&F(`
1030
+ Dry run \u2014 no files will be written.`);let Ne=await UZ(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(Ne==="non-interactive")return O(`
1031
+ Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(Ne==="declined")return F(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 _=await Xd(H.origin);if(!_.reachable)return O(`
1032
+ Gateway ${H.origin} is not reachable (${_.detail}).`),k(C(` 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;$(`Gateway reachable (${_.detail}).`)}let ee=o.revert?[]:await yZ(l,W.origin),Fe=[],xe=()=>{Fe.length!==0&&(K("Reopening"),kZ(Fe),Fe=[])};if(ee.length>0){let _=ee.map(H=>H.title),L=_.length===1?"it":"them";if(K("Open apps"),gZ(o,jt()))o.quitApps===!0||await Ra(wZ(_))?Fe=await bZ(ee):F(` Leaving ${L} open \u2014 restart when convenient.`);else{let H=o.noQuitApps===!0?"":" (or pass --quit-apps)";F(o.dryRun?` Would offer to quit ${_.join(", ")} \u2014 dry run, nothing was closed.`:` ${_.join(", ")} ${_.length===1?"is":"are"} open; restart ${L} to pick this up${H}.`)}}try{if(!o.dryRun)try{await kt()}catch{return O("Could not prepare the owner-only Anyray state directory."),1}let _=l.some(pe=>pe.id==="claude-code")&&J(W,"anthropic")||l.some(pe=>pe.id==="codex")&&J(W,"openai"),L=Cd(s,T),H=!o.revert&&o.noKeyRefresh!==!0&&_&&L&&!B,se=!o.revert&&(o.tools?.length??0)>0&&o.noKeyRefresh!==!0&&!!s.keyRefreshEnabled,we=!!(b&&W.clientKey===b&&!S),We=!we&&!!(S??s.enrolledCert),ue=l.some(pe=>mS.has(pe.id)),ie=!o.revert&&o.noKeyRefresh!==!0&&We&&(L||!ue),Y=o.dryRun?await Ao(s):await pm(),Ne=Y==="healthy";Y==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath);let ft=W,Ve=H||se,Pr=Ve?s.fallbackPort:void 0;if(H&&!o.dryRun&&(Pr=s.fallbackPort??await yc()),!o.revert&&!o.dryRun){let pe={...s,gateway:W.origin,name:g,team:y,clientKey:W.clientKey??s.clientKey,enrolledCert:we?void 0:S??s.enrolledCert,enrolledCertExpiry:we?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:we?void 0:A??s.enrolledTokenHash,ssoLink:we?void 0:p?I:S?void 0:s.ssoLink,clientKeyExpiresAt:we?void 0:T??(W.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:W.authMode,byoUpstream:W.byoUpstream,credentialProtocol:we?void 0:Ve?"rotating-proxy-v1":B?"stable-heartbeat-v1":s.credentialProtocol,directMigration:we?void 0:Ve?"pending":B?"complete":s.directMigration,keyRefreshEnabled:Ve,refreshSchedulerEnabled:ie,fallbackPort:Pr};try{await fZ(s,pe,x,void 0,we)}catch{return O("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}T&&!we&&await Aa({expiresAt:T})}if(H&&!o.dryRun&&(ft=await RZ(W,Pr,{trayManaged:Ne})),z)if(o.dryRun)await vu()&&(K("Enrollment"),k(" would remove the stored gateway credential"));else{await $y(s),await Rd().catch(()=>{});try{await qi()&&(K("Enrollment"),$(" Removed the stored gateway credential."),F(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(pe){K("Enrollment"),N(" Could not remove the stored gateway credential."),N(` 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 cn=l;if(o.revert&&!z){let pe=l.filter(tt=>ui(s,tt.id));if(pe.length>0){K("Fleet policy");for(let tt of pe)N(` ${tt.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);cn=l.filter(tt=>!ui(s,tt.id))}}let{changes:Gi,manual:Ua,manualAdminOnly:ji,manualAdminOnlyIds:Vi,results:Ha}=await hZ(cn,ft,me,o.revert,new Set(o.tools??[]));if(sI(o)){K("Endpoint agent");try{await(n.installEndpointAfterEnrollment??mI)({gateway:w,clientKey:W.clientKey})}catch{F("Endpoint agent setup did not complete. Tool routing remains configured.")}}if(o.dryRun||(await Xn(Ha,o.revert,z).catch(()=>{}),z&&await ec().catch(()=>{})),!Ve&&!o.dryRun&&(nt(s)||s.fallbackPort||await Ci("daemon"))){K("Local loopback proxy");let pe=await Jt(s.fallbackPort);for(let tt of pe.messages)k(` ${tt}`);await te({...await P(),keyRefreshEnabled:!1,fallbackPort:void 0}),$(" Removed the local loopback proxy.")}if(await OZ({want:ie,announcePrimary:!H,scopedRevert:!!o.revert&&!z,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!ie&&await Ci("scheduler"),trayManaged:Ne}),!o.revert&&!o.dryRun&&!we){let pe=x??await Be();pe&&await nm(await P(),pe).catch(()=>{})}if(xe(),K("Summary"),o.dryRun)F("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){$(`Reverted (${Gi} file(s) touched).`),F("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let pe=await NE();pe.length>0&&(K("This repo carries its own Anyray routing"),N(` Committed here: ${pe.join(", ")}`),N(" Those are tracked files, so they route every checkout of this"),N(" repo \u2014 this machine included, and your teammates' too. This"),N(" revert only removed THIS machine's own configuration."),k(`
1036
- Remove them from the repo (then commit):`),k(C(" anyray-connect --project --revert")));let tt=[W,...s.fallbackPort?[vn(W,s.fallbackPort)]:[]],Lr=Cp(tt);Lr.length>0&&(K("This terminal still points at the gateway"),N(` Still exported here: ${Lr.join(", ")}`),N(" Removing the block from your shell profile cannot reach a shell"),N(" that already ran it. Until these are gone, your tools keep"),N(" reaching the gateway and now fail with 401."),k(`
1037
- Fix this terminal:`),k(C(` unset ${Lr.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($(`Done (${Gi} file(s) written).`),Ua.length>0){let _t=ji.length===Ua.length;K(_t?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let Fy of mZ(Ua,ji,Vi.includes("claude-desktop")?process.platform:void 0))N(Fy);jt()&&!o.yes&&!_t&&(await Ra("Have you applied the manual settings shown above?")?$("Acknowledged."):N("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?F(`
1039
- Skipped the connection smoke test (--skip-verify).`):await CZ(W,l.map(_t=>_t.id)),K("What's next");let pe=new Set(Ha.filter(_t=>_t.status==="configured").map(_t=>_t.id)),tt=l.filter(_t=>pe.has(_t.id)).map(_t=>_t.title);if(k(tt.length>0?` Connected: ${tt.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
- Re-test by hand any time:`),W.authMode!=="placeholder"&&l.length===1&&l[0]?.id==="cursor"?(k(C(` curl -sS ${W.origin}/connect/savings \\
1041
- -H "x-anyray-api-key: $(anyray-connect print-key)"`)),k(C(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):k(C(` curl -sS ${W.openaiBaseUrl}/chat/completions \\
1034
+ Start the gateway and try again, or pass --force to configure anyway.`),1;$(`Gateway reachable (${_.detail}).`)}let ee=o.revert?[]:await CZ(l,H.origin),Fe=[],xe=()=>{Fe.length!==0&&(K("Reopening"),xZ(Fe),Fe=[])};if(ee.length>0){let _=ee.map(W=>W.title),L=_.length===1?"it":"them";if(K("Open apps"),vZ(o,Vt()))o.quitApps===!0||await Ra(SZ(_))?Fe=await EZ(ee):F(` Leaving ${L} open \u2014 restart when convenient.`);else{let W=o.noQuitApps===!0?"":" (or pass --quit-apps)";F(o.dryRun?` Would offer to quit ${_.join(", ")} \u2014 dry run, nothing was closed.`:` ${_.join(", ")} ${_.length===1?"is":"are"} open; restart ${L} to pick this up${W}.`)}}try{if(!o.dryRun)try{await kt()}catch{return O("Could not prepare the owner-only Anyray state directory."),1}let _=l.some(we=>we.id==="claude-code")&&J(H,"anthropic")||l.some(we=>we.id==="codex")&&J(H,"openai"),L=xd(s,T),W=pI(o),le=!o.revert&&o.noKeyRefresh!==!0&&_&&L&&!B&&!W,gt=!o.revert&&(o.tools?.length??0)>0&&o.noKeyRefresh!==!0&&!!s.keyRefreshEnabled,pe=!!(b&&H.clientKey===b&&!S),fe=!pe&&!!(S??s.enrolledCert),de=l.some(we=>kS.has(we.id)),Y=!o.revert&&o.noKeyRefresh!==!0&&fe&&(L||!de),Ie=Y&&!W,dt=o.dryRun?await bo(s):await mm(),wt=dt==="healthy";dt==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath);let vo=H,bt=le||gt,Ha=bt?s.fallbackPort:void 0;if(le&&!o.dryRun&&(Ha=s.fallbackPort??await kc()),!o.revert&&!o.dryRun){let we={...s,gateway:H.origin,name:g,team:y,clientKey:H.clientKey??s.clientKey,enrolledCert:pe?void 0:S??s.enrolledCert,enrolledCertExpiry:pe?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:pe?void 0:A??s.enrolledTokenHash,ssoLink:pe?void 0:p?I:S?void 0:s.ssoLink,clientKeyExpiresAt:pe?void 0:T??(H.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:H.authMode,byoUpstream:H.byoUpstream,credentialProtocol:pe?void 0:bt?"rotating-proxy-v1":B?"stable-heartbeat-v1":s.credentialProtocol,directMigration:pe?void 0:bt?"pending":B?"complete":s.directMigration,keyRefreshEnabled:bt,refreshSchedulerEnabled:Ie,fallbackPort:Ha};try{await bZ(s,we,x,void 0,pe)}catch{return O("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}T&&!pe&&await Aa({expiresAt:T})}if(le&&!o.dryRun&&(vo=await DZ(H,Ha,{trayManaged:wt})),z)if(o.dryRun)await xu()&&(K("Enrollment"),k(" would remove the stored gateway credential"));else{await Uy(s),await Pd().catch(()=>{});try{await nc()&&(K("Enrollment"),$(" Removed the stored gateway credential."),F(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(we){K("Enrollment"),N(" Could not remove the stored gateway credential."),N(` 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 Yi=l;if(o.revert&&!z){let we=l.filter(_t=>hi(s,_t.id));if(we.length>0){K("Fleet policy");for(let _t of we)N(` ${_t.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);Yi=l.filter(_t=>!hi(s,_t.id))}}let{changes:Zi,manual:So,manualAdminOnly:Wa,manualAdminOnlyIds:Xi,results:Ka}=await kZ(Yi,vo,ye,o.revert,new Set(o.tools??[])),Ga;if(Ly(o)){K("Endpoint agent");try{Ga=await(n.installEndpointAfterEnrollment??AI)({gateway:w,clientKey:H.clientKey})}catch{F("Endpoint agent setup did not complete. Tool routing remains configured.")}}let Wy=W&&!uI(Ga)&&Y;if(Wy&&!o.dryRun&&(F(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),await te({...await P(),refreshSchedulerEnabled:!0}).catch(()=>{})),o.dryRun||(await Xn(Ka,o.revert,z).catch(()=>{}),z&&await oc().catch(()=>{})),!bt&&!o.dryRun&&(Qe(s)||s.fallbackPort||await Ei("daemon"))){K("Local loopback proxy");let we=await zt(s.fallbackPort);for(let _t of we.messages)k(` ${_t}`);await te({...await P(),keyRefreshEnabled:!1,fallbackPort:void 0}),$(" Removed the local loopback proxy.")}if(await NZ({want:Ie||Wy,announcePrimary:!le,scopedRevert:!!o.revert&&!z,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!Ie&&await Ei("scheduler"),trayManaged:wt}),!o.revert&&!o.dryRun&&!pe){let we=x??await Be();we&&await am(await P(),we).catch(()=>{})}if(xe(),K("Summary"),o.dryRun)F("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){$(`Reverted (${Zi} file(s) touched).`),F("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let we=await UE();we.length>0&&(K("This repo carries its own Anyray routing"),N(` Committed here: ${we.join(", ")}`),N(" Those are tracked files, so they route every checkout of this"),N(" repo \u2014 this machine included, and your teammates' too. This"),N(" revert only removed THIS machine's own configuration."),k(`
1036
+ Remove them from the repo (then commit):`),k(C(" anyray-connect --project --revert")));let _t=[H,...s.fallbackPort?[vn(H,s.fallbackPort)]:[]],Ji=Ep(_t);Ji.length>0&&(K("This terminal still points at the gateway"),N(` Still exported here: ${Ji.join(", ")}`),N(" Removing the block from your shell profile cannot reach a shell"),N(" that already ran it. Until these are gone, your tools keep"),N(" reaching the gateway and now fail with 401."),k(`
1037
+ Fix this terminal:`),k(C(` unset ${Ji.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($(`Done (${Zi} file(s) written).`),So.length>0){let Tt=Wa.length===So.length;K(Tt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let Ky of AZ(So,Wa,Xi.includes("claude-desktop")?process.platform:void 0))N(Ky);Vt()&&!o.yes&&!Tt&&(await Ra("Have you applied the manual settings shown above?")?$("Acknowledged."):N("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?F(`
1039
+ Skipped the connection smoke test (--skip-verify).`):await RZ(H,l.map(Tt=>Tt.id)),K("What's next");let we=new Set(Ka.filter(Tt=>Tt.status==="configured").map(Tt=>Tt.id)),_t=l.filter(Tt=>we.has(Tt.id)).map(Tt=>Tt.title);if(k(_t.length>0?` Connected: ${_t.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
+ Re-test by hand any time:`),H.authMode!=="placeholder"&&l.length===1&&l[0]?.id==="cursor"?(k(C(` curl -sS ${H.origin}/connect/savings \\
1041
+ -H "x-anyray-api-key: $(anyray-connect print-key)"`)),k(C(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):k(C(` curl -sS ${H.openaiBaseUrl}/chat/completions \\
1042
1042
  -H "Content-Type: application/json" \\
1043
- -H "Authorization: Bearer ${W.clientKey?`<your personal key (${Nt(W.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
1044
- -d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(C(" Revert: npx anyray-connect --revert"))}return 0}finally{xe()}};RI(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
1043
+ -H "Authorization: Bearer ${H.clientKey?`<your personal key (${$t(H.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
1044
+ -d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(C(" Revert: npx anyray-connect --revert"))}return 0}finally{xe()}};DI(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});