anyray-connect 0.11.170 → 0.11.171

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 +240 -240
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- var PR="http://localhost:8787",ja="anyray-placeholder",Ee=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Ht=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},ku=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,DR=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),sg=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!DR.has(n)}catch{return!1}},Qt=e=>{let t=Ht(e||process.env.ANYRAY_GATEWAY_URL||PR),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},xe=(e={})=>{let t=Qt(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:ku(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:ku(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:ku(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 wc,platform as np}from"node:os";import{join as Hr}from"node:path";import{mkdir as ep,readFile as oT,rename as aT,writeFile as mc,rm as Wr}from"node:fs/promises";import{spawnSync as sT}from"node:child_process";import{homedir as uc}from"node:os";import{join as pc}from"node:path";import{access as BR,chmod as FR,mkdir as vu,open as Ru,readFile as fg,rm as Ut,stat as cg,utimes as WR}from"node:fs/promises";import{createHash as HR,randomUUID as mg}from"node:crypto";import{dirname as Ou,join as UR}from"node:path";import{isDeepStrictEqual as vo}from"node:util";import{randomUUID as LR}from"node:crypto";import{lstat as NR,rename as Ki,rm as $R}from"node:fs/promises";import{platform as ig}from"node:os";var MR=e=>e?.code==="ENOENT",_r=async(e,t=ig())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},he=async(e,t,n=ig())=>{if(n!=="win32"){await Ki(e,t);return}let r=`${t}.anyray-old-${process.pid}-${LR()}`,o=!1;try{let a=await NR(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await Ki(t,r),o=!0}catch(a){if(!MR(a))throw a}try{await Ki(e,t)}catch(a){if(o)try{await Ki(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await $R(r,{force:!0})};var Za=e=>`${e}.anyray-bak`,hg=async e=>{let t;try{t=await Ru(Ou(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},lg=async(e,t)=>{let n,r;try{n=await Ru(e,"wx",384),await n.writeFile(t,"utf-8"),await _r(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Ut(e,{force:!0}).catch(()=>{}),r;await hg(e)},GR=async e=>{let t;try{t=await Ru(e,"r"),await _r(t)}finally{await t?.close().catch(()=>{})}await hg(e)},x=async e=>{try{return await BR(e),!0}catch{return!1}},B=async e=>{if(!await x(e))return{};let t=await fg(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},Y=async(e,t,n={})=>{await vu(Ou(e),{recursive:!0,mode:448});let r=Za(e);if(n.backup!==!1&&!await x(r)){let a=await x(e),s=a?await fg(e,"utf-8"):`{}
3
- `;if(a||n.tombstoneAbsent!==!1)try{await lg(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${mg()}`;try{await lg(o,`${JSON.stringify(t,null,2)}
4
- `),await he(o,e),await FR(e,384),await GR(e)}finally{await Ut(o,{force:!0}).catch(()=>{})}},yg=1,dg=3e4,VR=5e3,KR=/^[a-f0-9]{64}$/,gg=e=>`${e}.pending`,jR=e=>`${e}.lock`,Su=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=>Su(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Su(t[n])}`).join(",")}}`},Iu=(e,t)=>({exists:e,sha256:HR("sha256").update(Su(t)).digest("hex")}),Eu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ug=e=>Eu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&KR.test(e.sha256),ZR=e=>Eu(e)&&e.transactionVersion===yg&&ug(e.before)&&ug(e.after)&&Eu(e.journal),xu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,So=async(e,t)=>{try{return await B(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},YR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},wg=async e=>{let t=jR(e),n=UR(t,"owner.json");await vu(Ou(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=mg();try{await vu(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await So(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 cg(n)).mtimeMs;i=!YR(c.pid)||l>dg}catch{try{i=Date.now()-(await cg(t)).mtimeMs>dg}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Ut(t,{recursive:!0,force:!0});continue}try{await Y(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Ut(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await So(n,"ownership journal")).nonce!==o)return;let i=new Date;await WR(n,i,i)}catch{}})()},VR);return a.unref(),async()=>{clearInterval(a);try{(await So(n,"ownership journal")).nonce===o&&await Ut(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},bg=async e=>{let t=await x(e),n={};if(t)try{n=await B(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:Iu(t,n)}},Ag=async(e,t)=>{let n=gg(t);if(!await x(n))return;let r=await So(n,"prepared ownership transaction");if(!ZR(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await bg(e),a=await x(t),s=await x(Za(e)),i=xu(o.fingerprint,r.before),c=xu(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await Y(t,r.journal,{backup:!1}),await Ut(n,{force:!0});return}if(i){await Ut(n,{force:!0}),a||await re(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},ji=async(e,t,n)=>{let r=await wg(t);try{return await Ag(e,t),await n()}finally{await r()}},pg=async(e,t,n,r)=>{if(!await x(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await So(e,"ownership journal");if(!(n&&vo(a,t))){if(!vo(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await Y(e,t,{backup:!1}):await Ut(e,{force:!0})}},Zi=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await wg(a);try{await Ag(n,a);let l=await bg(n),d=Iu(i,r),u=await x(a),p=u?await So(a,"ownership journal"):void 0,f=p&&typeof p.fileExisted=="boolean"?{...s,fileExisted:p.fileExisted}:s;if(!xu(l.fingerprint,d)){if(vo(l.value,o)&&p&&vo(p,f))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&vo(l.value,o)&&p&&vo(p,f))return;let m=await x(Za(n));if(p?.fileExisted===!0&&!m)throw new Error("ownership backup is missing; configuration was left unchanged");if(m&&!p)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let h=gg(a),w={transactionVersion:yg,before:l.fingerprint,after:Iu(!0,o),journal:f};await Y(h,w,{backup:!1});try{await Y(n,o,p?{backup:!1}:{tombstoneAbsent:!1}),await(t.writeJournal??Y)(a,f,{backup:!1}),await Ut(h,{force:!0})}catch(y){try{await pg(n,l.value,l.exists,o)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed and config rollback was incomplete")}try{await pg(a,p??{},u,f),await Ut(h,{force:!0}),!m&&!p&&await re(n)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed after config rollback")}throw y}}finally{await c()}},Pr=async e=>{try{return await B(Za(e))}catch{return{}}},re=async e=>{await Ut(Za(e),{force:!0}).catch(()=>{})};import{access as bO}from"node:fs/promises";import{spawnSync as oO}from"node:child_process";import{readFileSync as aO,realpathSync as za,statSync as Og}from"node:fs";import{access as sO,cp as Tg,mkdir as xg,readdir as iO,readFile as Bu,realpath as cO,rename as lO,rm as $u,writeFile as dO}from"node:fs/promises";import{tmpdir as uO}from"node:os";import{basename as Eo,dirname as He,join as Re,resolve as pO}from"node:path";import{writeFile as Yi,readFile as Ya,chmod as Pu,stat as Du,mkdir as vg,rm as Io}from"node:fs/promises";import{AsyncLocalStorage as JR}from"node:async_hooks";import{randomUUID as XR}from"node:crypto";import{homedir as Sg}from"node:os";import{join as Dr}from"node:path";var Q=()=>Dr(Sg(),".anyray"),Ig=async()=>{let e=Q();try{if((await Du(e)).isDirectory())return Dr(e,"connect.json")}catch{}return e},Lu=()=>Dr(Q(),"dev-key.pem"),tt=async()=>{let e=Q(),t;try{if(!(await Du(e)).isDirectory())t=await Ya(e,"utf-8").catch(()=>{}),await Io(e,{force:!0});else return}catch{}if(await vg(e,{recursive:!0,mode:448}),t!==void 0){let n=Dr(e,"connect.json");await Yi(n,t,{mode:384}),await Pu(n,384)}},Ji=async e=>{await tt();let t=Lu();await Yi(t,e,{mode:384}),await Pu(t,384)},$e=async()=>{try{let e=await Ya(Lu(),"utf-8");return e.trim()?e:void 0}catch{return}},Ja=async()=>{await Io(Lu(),{force:!0}).catch(()=>{})},D=async()=>{try{let e=await Ya(await Ig(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}},zR=0,qR=3e4,QR=5e3,eO=25,tO=()=>Dr(Sg(),".anyray-connect-profile.lock"),Tu=new JR,nO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},rO=async e=>{try{let t=JSON.parse(await Ya(Dr(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!nO(t.pid)}catch{}return Date.now()-(await Du(e)).mtimeMs>qR},Eg=async(e=QR)=>{let t=tO(),n=Dr(t,"owner.json"),r=Date.now()+e;for(;;){let o=XR();try{await vg(t,{mode:448});try{await Yi(n,`${JSON.stringify({pid:process.pid,nonce:o})}
5
- `,{mode:384})}catch(s){throw await Io(t,{recursive:!0,force:!0}).catch(()=>{}),s}return async()=>{try{JSON.parse(await Ya(n,"utf-8")).nonce===o&&await Io(t,{recursive:!0,force:!0})}catch{}}}catch(s){if(s.code!=="EEXIST")throw s}if(!(await rO(t).catch(()=>!1)&&await Io(t,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=r)throw new Error("connect profile is busy; retry the command");await new Promise(s=>setTimeout(s,eO))}}},Xa=async(e,t={})=>{if(Tu.getStore()===!0)return e();let n=await Eg(t.waitMs);try{return await Tu.run(!0,e)}finally{await n()}},Cg=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Ig(),r=`${n}.${process.pid}.${zR++}.tmp`;await Yi(r,`${JSON.stringify(t,null,2)}
6
- `,{mode:384}),await Pu(r,384);try{await he(r,n)}catch(o){throw await Io(r,{force:!0}).catch(()=>{}),o}},oe=async e=>{if(Tu.getStore()===!0){await Cg(e);return}let t=await Eg();try{await Cg(e)}finally{await t()}};var _u=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],kg="ssoLink",Nu=async()=>{let e=await D();return _u.some(t=>e[t]!==void 0)?!0:await $e()!==void 0},Xi=async()=>{let e=await D(),t=_u.some(a=>e[a]!==void 0),n=e[kg]!==void 0,r=e.byoUpstream!==void 0,o=await $e()!==void 0;if(t||n||r||e.managedEnrollmentDisabled!==!0){let a={...e};for(let s of _u)delete a[s];delete a[kg],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,delete a.anyrayFleetManaged,await oe(a)}if(await Ja(),await $e())throw new Error(`could not remove the dev key from ${Q()}`);return t||n||r||o},Vn=async(e,t,n=!1)=>{let r=await D(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let m of e){let h=m.status==="configured"||m.status==="queued";!t&&h&&(o.add(m.id),a.delete(m.id),s=void 0),t&&(m.status==="reverted"||m.status==="queued")&&(o.delete(m.id),a.add(m.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((m,h)=>m===c[h])&&r.revertedTools!=null&&l.length===d.length&&l.every((m,h)=>m===d[h])&&s===r.offboardedAt)return;let{offboardedAt:p,...f}=r;await oe({...f,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},zi=async(e=new Date().toISOString())=>{await oe({...await D(),offboardedAt:e})};var xo=e=>pO(e).replace(/\\/g,"/").toLowerCase(),Mu=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",qa=e=>`${e}.source`,_g=e=>/(^|\/)_npx(\/|$)/.test(xo(e)),Fu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(xo(e)),Wu=e=>{let t=xo(e),n=[uO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(xo);return _g(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},ft=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),Qa=e=>/[\\/](node|node\.exe)$/i.test(e),Kn=(e=ft())=>Qa(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,Rg=e=>{try{let t=Og(e);return t.isFile()?t.size:void 0}catch{return}},Hu=e=>{let t=He(e);if(Eo(t)==="versions")return t;let n=He(t);return Eo(n)==="versions"?n:void 0},Qi=(e,t)=>t!==void 0&&(He(e)===t||He(He(e))===t),fO=e=>{let t=Hu(e);if(!t)return;let n=Re(He(t),"bin",Mu());try{let r=za(n);return r===za(e)||Qi(r,za(t))?n:void 0}catch{return}},Ro=(e=Q(),t=process.platform)=>{let n=Re(e,"bin",Mu(t));try{let r=za(n),o=za(Re(e,"versions"));if(Qi(r,o))return n;if(t==="win32"){let a=aO(qa(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=Rg(Re(o,a,Mu(t)))??Rg(Re(o,a));if(s!==void 0&&s===Og(n).size)return n}}catch{return}},Lr=(e=ft())=>{let t=Kn(e),n=Fu(t)||Gu(t)?Ro():void 0;return fO(e.execPath)??n??t},Pg=(e=ft())=>Lr(e)!==Kn(e),en=(e,t=ft())=>{let n=Lr(t);return Qa(t.execPath)&&t.scriptPath!==void 0&&n===Kn(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},Dg=(e=ft())=>{let t=Lr(e);return!Qa(e.execPath)&&!Wu(t)?He(t):Re(Q(),"bin")},qi=async e=>{try{return await sO(e),!0}catch{return!1}},mO=async e=>{let t=await cO(e),n=He(t),r=He(n),o=Re(r,"package.json"),a=await Bu(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 qi(Re(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},hO=async(e,t)=>{let n=t;for(;;){let r=Re(n,"node_modules",e);if(await qi(Re(r,"package.json")))return r;let o=He(n);if(o===n)return;n=o}},yO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Bu(Re(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await hO(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Tg(i,Re(t,s),{recursive:!0}),r.push(i)}}},gO=async(e=ft())=>{let t=Ro();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 mO(e.scriptPath);await tt();let r=Re(Q(),"bin",`connect-runtime-${n.version}`),o=Re(r,"dist","index.js");if(!await qi(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await $u(a,{recursive:!0,force:!0}),await xg(a,{recursive:!0,mode:448});try{await Tg(n.dist,Re(a,"dist"),{recursive:!0}),await dO(Re(a,"package.json"),await Bu(n.packageJson),{mode:384}),await yO(n.root,Re(a,"node_modules")),await xg(He(r),{recursive:!0,mode:448});try{await lO(a,r)}catch(s){if(!await qi(o))throw s}}finally{await $u(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Uu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,wO=e=>{let t=Eo(He(He(e)));return Uu.test(t)?t:void 0},Gu=(e,t=Q())=>{let n=He(He(e));return xo(He(n))===xo(Re(t,"bin"))&&Uu.test(Eo(n))&&Eo(He(e))==="dist"&&Eo(e)==="index.js"},ec=async(e=ft())=>{let t=Re(Q(),"bin"),n=wO(Kn(e)),r=[];for(let o of await iO(t).catch(()=>[])){if(!Uu.test(o)||o===n)continue;let a=Re(t,o);await $u(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},Lg=async(e,t=ft())=>{let n=Kn(t);if(!Qa(t.execPath)||!_g(n)||Ro())return;let r=await gO(t),o=oO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Vu=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,es=(e,t)=>[e,...t].map(Vu).join(" "),kn=(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}:{}}]}),jn=(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))},tc=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!jn(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},Oo=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!jn(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)},Ku=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=>!jn(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",Ng="__anyray-codex-hook",Zn="__anyray-prompt-hook",$g="__anyray-shell-pretool",ju="__anyray-shell-run",Mg="__anyray-read-pretool",Yn="__anyray-refresh",ts=(e,t=[])=>{let{command:n,args:r}=en([e,...t]);return{command:n,args:r}},Rt=(e,t=[])=>{let n=ts(e,t);return[n.command,...n.args].map(Vu).join(" ")},nc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Rt(t,n),Bg=()=>Rt("print-key"),Oe=()=>Lr(),Ue=Wu,ce=()=>!Ue(Oe()),Nr=async()=>{if(!ce())return!1;try{return await bO(Oe()),!0}catch{return!1}},Jn="__anyray-mcp-server",Ge=e=>ts(Jn,[e]),AO=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),rc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ge(t);return n.command===r.command&&AO(n.args,r.args)},Gt=(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)===Jn&&r.at(-1)===t};var ee=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,ue=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"],Fg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],oc=[...$r,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],CO=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
7
- `)},tn=(e,t={})=>{let n=e.byoUpstream,r=!n&&ee(e,"anthropic"),o=ue({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1,s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=CO(o,r,a?e.clientKey:void 0,n?.url);return{env:{ANTHROPIC_BASE_URL:e.anthropicBaseUrl,...c?{ANTHROPIC_CUSTOM_HEADERS:c}:{},...n&&s?{ANTHROPIC_AUTH_TOKEN:n.key}:{},...r||n||!s?{}:{ANTHROPIC_AUTH_TOKEN:e.clientKey??e.placeholderKey},...n?{}:{ENABLE_TOOL_SEARCH:"true"},...n?{}:{_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL:"1"},...i!==void 0?{CLAUDE_CODE_MAX_CONTEXT_TOKENS:String(i)}:{}},subscription:r,byoUpstream:!!n,meta:o,headers:c}};import{z as Zu}from"zod";var kO=5e3,vO=1e3,SO=1e8,IO=Zu.object({modelContext:Zu.object({contextTokens:Zu.number().int().min(vO).max(SO)}).optional()}),Wg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},Hg=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??kO,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=IO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var EO=1e6,ns="[1m]",xO=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Ug=(e,t)=>!e||t===void 0?{}:xO(e)?{envTokens:t}:t<EO?{}:e.toLowerCase().endsWith(ns)?{}:{model:`${e}${ns}`},Gg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(ns))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(ns))return e.slice(0,-ns.length)};import{platform as RO}from"node:os";var Ot=(e=RO())=>{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 vn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],ac=e=>typeof e=="string"&&e.trim()!=="",OO=(e,t)=>typeof e[t]=="string"&&!ac(e[t]),Vg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},TO=()=>B(Ot()).catch(()=>({})),Kg=async(e={})=>{let t=e.env??process.env,n=Vg(e.userSettings??{}),r=Vg(await(e.readManaged??TO)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of vn)ac(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Ot()})`,repairable:!1}):ac(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!OO(n,a)&&ac(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Yu=e=>`${e.name} is set (${e.source}) \u2014 Claude Code sends requests straight to ${e.cloud} and ignores the gateway routing written here, so none of its traffic reaches Anyray until that setting is removed`,Ju=e=>"Fix: remove the setting where it is set"+(e.some(t=>t.kind==="managed")?" (the managed settings file is IT-owned \u2014 ask your admin)":"")+", then restart Claude Code. The gateway can serve Bedrock/Vertex itself once its provider is configured \u2014 see the Bedrock page in the Anyray docs.",jg=e=>`Disabled direct ${e.cloud} mode: ${e.name} was set (${e.source}), which would bypass the gateway route entirely \u2014 pinned it empty in settings.json (the env block outranks shell exports, and '' is Claude Code's documented unset). Delete the original setting to drop the pin.`;var _O=vn.map(e=>e.name),PO=oc.filter(e=>!_O.includes(e)),Zg=e=>typeof e=="string"&&e.trim()!=="",Yg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},DO=(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)},LO=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Xu=()=>B(Ot()).catch(()=>({})),Jg=Xu,NO=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=>jn(r,ze))},Xg=async(e={})=>{let t=await(e.readManaged??Jg)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!NO(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},sc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Ot()}) \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 (${Ot()}), 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",ic=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.",zg=async(e={})=>{let t=Yg(e.userSettings??{}),n=Yg(await(e.readManaged??Jg)().catch(()=>({}))),r=[];for(let o of PO){if(!Zg(n[o])||!Zg(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(DO(n[o],t[o],a))continue;let s=a?LO(n[o]):void 0;r.push({name:o,source:`managed settings (${Ot()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},qg=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`,Qg=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 $O}from"node:os";import{join as MO}from"node:path";import{readFile as BO}from"node:fs/promises";var FO=400,ew=async()=>{try{let e=MO($O(),".claude","settings.json"),n=JSON.parse(await BO(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
8
- `)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},tw=async()=>{try{let e=await D();return e.gateway?{origin:new URL(e.gateway).origin,metadata:ue({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},nt=async(e="auto")=>e==="profile"?tw():e==="claude"?ew():await ew()??await tw(),cc=async(e={})=>{let t=e.readTarget??nt,n=e.loadProfile??D,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a;try{a=new URL(r.gateway).origin}catch{return"unreadable"}return a===o.origin?"owned":"foreign"},Vt=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},lc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),FO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Vt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var Xn=()=>pc(uc(),".claude","settings.json"),dc=()=>pc(uc(),".claude.json"),WO=oc,zn="anyray",HO=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),Mr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),UO=e=>{if("mcpServers"in e&&!Mr(e.mcpServers))return"conflict";let t=Mr(e.mcpServers)?{...e.mcpServers}:{},n=t[zn];return n!==void 0&&!Gt(n,"claude")?"conflict":(t[zn]=HO(),e.mcpServers=t,"installed")},nw=e=>{let t=e.mcpServers;return!t||!(zn in t)||!Gt(t[zn],"claude")?!1:(delete t[zn],Object.keys(t).length===0&&delete e.mcpServers,!0)},GO=e=>{tc(e,"PostToolUse",ze,kn(Rt(ze),{matcher:"*"})),tc(e,"UserPromptSubmit",Zn,kn(Rt(Zn)))},VO=e=>{tc(e,"SessionStart",Yn,kn(Rt(Yn),{async:!0}))},aw=e=>Oo(e,"SessionStart",Yn),rw=e=>{let t=Oo(e,"PostToolUse",ze),n=Oo(e,"UserPromptSubmit",Zn),r=aw(e);return t||n||r},KO="print-key",jO=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Br=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===KO&&jO(t)},ZO=async(e,t)=>{let n=(await Pr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of WO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},YO=e=>typeof e.apiKeyHelper=="string"&&!Br(e),sw=async e=>{let t=await Xu(),n=async()=>t,[r,o,a]=await Promise.all([Kg({userSettings:e,readManaged:n}),zg({userSettings:e,readManaged:n}).catch(()=>[]),Xg({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},ow=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await sw(e),o=Ju(t),a=Qg(n);return{routingOverrides:[...t.map(i=>({problem:Yu(i),fix:i.repairable?"Fix: run `anyray-connect doctor --repair` (or re-run `anyray-connect`) \u2014 apply disables this switch by pinning it empty in settings.json.":o,repairable:i.repairable})),...n.map(i=>({problem:qg(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},qn={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=pc(uc(),".claude"),t=await x(e);return{installed:t,detail:t?Xn():"no ~/.claude directory"}},async apply(e,t){let n=Xn(),r=await B(n),o=Wg(r),a=await Hg(e.origin,e.clientKey,o),s=Ug(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=tn(e,{contextWindowTokens:s.envTokens}),{directOverrides:p,hookPolicy:f}=await sw(r),m=p.filter(R=>!R.repairable),h=p.filter(R=>R.repairable),w=[...m.map(R=>`WARNING: ${Yu(R)}.`),...m.length?[Ju(m)]:[],...f.state==="fine"?[]:[`WARNING: ${sc(f)}.`,ic(f)],...h.map(R=>jg(R)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let y=r.env??{};r.env={...y,...i};let g=r.env;for(let{name:R}of vn)h.some(P=>P.name===R)?g[R]="":g[R]===""&&(process.env[R]??"").trim()===""&&delete g[R];if(u||delete g.ANTHROPIC_CUSTOM_HEADERS,c&&(y.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete g.ANTHROPIC_AUTH_TOKEN),l)for(let R of Fg)delete g[R];let b=!!e.clientKey,k=ce(),C=YO(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=Bg(),g.ANTHROPIC_AUTH_TOKEN="",w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Br(r)&&delete r.apiKeyHelper,C&&!c&&!l&&b&&k&&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&&k?(VO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):aw(r),ce()?(GO(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.")):(rw(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 Y(n,r);let I=[n],E=dc();try{let R=await B(E),P=!1;ce()?UO(R)==="conflict"?w.push(`MCP name conflict in ${E}: mcpServers.${zn} is not owned by Anyray Connect, so it was left untouched.`):(P=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):P=nw(R),P&&(await Y(E,R),I.push(E))}catch(R){w.push(`Could not register the Anyray MCP server in ${E} (${R instanceof Error?R.message:String(R)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:I}},skillsDir(){return pc(uc(),".claude","skills")},async pointsAt(e){let t=Xn();if(!await x(t))return!1;try{let o=(await B(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await B(Xn()).catch(()=>({}));return ow(e)},async routingOverrides(){let e=await B(Xn()).catch(()=>({}));return(await ow(e)).routingOverrides},async mcpStatus(){let e=dc();if(!await x(e))return{registered:!1,command:null};try{let r=(await B(e)).mcpServers?.[zn];return!r||!Gt(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=Xn();if(!await x(n))e="missing";else try{let s=await B(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=>jn(c,ze))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>jn(c,ze)&&Mr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Mr(l)&&nc(l.command,ze))))}}catch{e="unreadable"}let r,o=!0,a=dc();if(!await x(a))r="missing";else try{let s=await B(a);if(s.mcpServers===void 0)r="missing";else if(!Mr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[zn];r=i===void 0?"missing":Gt(i,"claude")?"owned":"foreign",r==="owned"&&(o=rc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Nr()?"owned":"missing",beacon_target:await cc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await B(Xn()),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=Xn();if(!await x(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 B(t),r=n.env,o=rw(n),a=Br(n);a&&delete n.apiKeyHelper;let s=r?await ZO(t,r):[],i=Gg(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 Y(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=dc();try{let d=await B(l);nw(d)&&(await Y(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 Qn=e=>{let{command:t,args:n}=en([e]);return{command:t,args:n}},er=()=>Lr();import{homedir as qu,platform as cw}from"node:os";import{join as fc}from"node:path";import{mkdir as XO,rm as lw,writeFile as zO,link as qO,copyFile as QO,readFile as X5}from"node:fs/promises";import{spawnSync as eT}from"node:child_process";import{homedir as iw,userInfo as JO}from"node:os";var rs=()=>{try{return iw()!==JO().homedir}catch{return!1}},zu=e=>[`Skipped ${e} \u2014 HOME (${iw()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var Qu="ai.anyray.connect.app",os="Anyray",dw=(e=qu())=>fc(e,"Applications",`${os}.app`),uw="anyray-connect",tT=e=>`<?xml version="1.0" encoding="UTF-8"?>
2
+ var $R="http://localhost:8787",ja="anyray-placeholder",Ee=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Ht=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},Cu=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,MR=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),lg=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!MR.has(n)}catch{return!1}},Qt=e=>{let t=Ht(e||process.env.ANYRAY_GATEWAY_URL||$R),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},xe=(e={})=>{let t=Qt(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:Cu(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:Cu(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:Cu(e.session,"ANYRAY_METADATA_SESSION")},a=e.subscription?"subscription":e.placeholder?"placeholder":e.seat?"auto":"placeholder";return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:n,clientKey:r,authMode:a,byoUpstream:e.byoUpstream,seat:a==="auto"?e.seat:void 0,metadata:o}};import{homedir as wc,platform as tp}from"node:os";import{join as Ur}from"node:path";import{mkdir as Qu,readFile as pT,rename as fT,writeFile as mc,rm as Wr}from"node:fs/promises";import{spawnSync as mT}from"node:child_process";import{homedir as uc}from"node:os";import{join as pc}from"node:path";import{access as HR,chmod as GR,mkdir as ku,open as xu,readFile as yg,rm as Gt,stat as ug,utimes as VR}from"node:fs/promises";import{createHash as KR,randomUUID as gg}from"node:crypto";import{dirname as Ru,join as jR}from"node:path";import{isDeepStrictEqual as vo}from"node:util";import{randomUUID as BR}from"node:crypto";import{lstat as FR,rename as Ki,rm as WR}from"node:fs/promises";import{platform as dg}from"node:os";var UR=e=>e?.code==="ENOENT",Pr=async(e,t=dg())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},he=async(e,t,n=dg())=>{if(n!=="win32"){await Ki(e,t);return}let r=`${t}.anyray-old-${process.pid}-${BR()}`,o=!1;try{let a=await FR(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await Ki(t,r),o=!0}catch(a){if(!UR(a))throw a}try{await Ki(e,t)}catch(a){if(o)try{await Ki(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await WR(r,{force:!0})};var Za=e=>`${e}.anyray-bak`,wg=async e=>{let t;try{t=await xu(Ru(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},pg=async(e,t)=>{let n,r;try{n=await xu(e,"wx",384),await n.writeFile(t,"utf-8"),await Pr(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Gt(e,{force:!0}).catch(()=>{}),r;await wg(e)},ZR=async e=>{let t;try{t=await xu(e,"r"),await Pr(t)}finally{await t?.close().catch(()=>{})}await wg(e)},x=async e=>{try{return await HR(e),!0}catch{return!1}},M=async e=>{if(!await x(e))return{};let t=await yg(e,"utf-8");if(!t.trim())return{};let n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n},Y=async(e,t,n={})=>{await ku(Ru(e),{recursive:!0,mode:448});let r=Za(e);if(n.backup!==!1&&!await x(r)){let a=await x(e),s=a?await yg(e,"utf-8"):`{}
3
+ `;if(a||n.tombstoneAbsent!==!1)try{await pg(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${gg()}`;try{await pg(o,`${JSON.stringify(t,null,2)}
4
+ `),await he(o,e),await GR(e,384),await ZR(e)}finally{await Gt(o,{force:!0}).catch(()=>{})}},bg=1,fg=3e4,YR=5e3,JR=/^[a-f0-9]{64}$/,Ag=e=>`${e}.pending`,XR=e=>`${e}.lock`,vu=e=>{if(e===void 0)return"null";if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(n=>vu(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${vu(t[n])}`).join(",")}}`},Su=(e,t)=>({exists:e,sha256:KR("sha256").update(vu(t)).digest("hex")}),Iu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),mg=e=>Iu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&JR.test(e.sha256),zR=e=>Iu(e)&&e.transactionVersion===bg&&mg(e.before)&&mg(e.after)&&Iu(e.journal),Eu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,So=async(e,t)=>{try{return await M(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},qR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Cg=async e=>{let t=XR(e),n=jR(t,"owner.json");await ku(Ru(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=gg();try{await ku(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await So(n,"ownership journal");if(typeof c.pid!="number"||!Number.isSafeInteger(c.pid)||c.pid<=0)throw new Error("lock owner is missing or invalid");let l=Date.now()-(await ug(n)).mtimeMs;i=!qR(c.pid)||l>fg}catch{try{i=Date.now()-(await ug(t)).mtimeMs>fg}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Gt(t,{recursive:!0,force:!0});continue}try{await Y(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Gt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await So(n,"ownership journal")).nonce!==o)return;let i=new Date;await VR(n,i,i)}catch{}})()},YR);return a.unref(),async()=>{clearInterval(a);try{(await So(n,"ownership journal")).nonce===o&&await Gt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},kg=async e=>{let t=await x(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:Su(t,n)}},vg=async(e,t)=>{let n=Ag(t);if(!await x(n))return;let r=await So(n,"prepared ownership transaction");if(!zR(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await kg(e),a=await x(t),s=await x(Za(e)),i=Eu(o.fingerprint,r.before),c=Eu(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await Y(t,r.journal,{backup:!1}),await Gt(n,{force:!0});return}if(i){await Gt(n,{force:!0}),a||await oe(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},ji=async(e,t,n)=>{let r=await Cg(t);try{return await vg(e,t),await n()}finally{await r()}},hg=async(e,t,n,r)=>{if(!await x(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await So(e,"ownership journal");if(!(n&&vo(a,t))){if(!vo(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await Y(e,t,{backup:!1}):await Gt(e,{force:!0})}},Zi=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await Cg(a);try{await vg(n,a);let l=await kg(n),d=Su(i,r),u=await x(a),p=u?await So(a,"ownership journal"):void 0,f=p&&typeof p.fileExisted=="boolean"?{...s,fileExisted:p.fileExisted}:s;if(!Eu(l.fingerprint,d)){if(vo(l.value,o)&&p&&vo(p,f))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&vo(l.value,o)&&p&&vo(p,f))return;let m=await x(Za(n));if(p?.fileExisted===!0&&!m)throw new Error("ownership backup is missing; configuration was left unchanged");if(m&&!p)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let h=Ag(a),w={transactionVersion:bg,before:l.fingerprint,after:Su(!0,o),journal:f};await Y(h,w,{backup:!1});try{await Y(n,o,p?{backup:!1}:{tombstoneAbsent:!1}),await(t.writeJournal??Y)(a,f,{backup:!1}),await Gt(h,{force:!0})}catch(y){try{await hg(n,l.value,l.exists,o)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed and config rollback was incomplete")}try{await hg(a,p??{},u,f),await Gt(h,{force:!0}),!m&&!p&&await oe(n)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed after config rollback")}throw y}}finally{await c()}},Dr=async e=>{try{return await M(Za(e))}catch{return{}}},oe=async e=>{await Gt(Za(e),{force:!0}).catch(()=>{})};import{access as vO}from"node:fs/promises";import{spawnSync as cO}from"node:child_process";import{readFileSync as lO,realpathSync as za,statSync as Pg}from"node:fs";import{access as dO,cp as Dg,mkdir as Tg,readdir as uO,readFile as Mu,realpath as pO,rename as fO,rm as Nu,writeFile as mO}from"node:fs/promises";import{tmpdir as hO}from"node:os";import{basename as Eo,dirname as Ue,join as Re,resolve as yO}from"node:path";import{writeFile as Yi,readFile as Ya,chmod as _u,stat as Pu,mkdir as Eg,rm as Io}from"node:fs/promises";import{AsyncLocalStorage as QR}from"node:async_hooks";import{randomUUID as eO}from"node:crypto";import{homedir as xg}from"node:os";import{join as Lr}from"node:path";var Q=()=>Lr(xg(),".anyray"),Rg=async()=>{let e=Q();try{if((await Pu(e)).isDirectory())return Lr(e,"connect.json")}catch{}return e},Du=()=>Lr(Q(),"dev-key.pem"),tt=async()=>{let e=Q(),t;try{if(!(await Pu(e)).isDirectory())t=await Ya(e,"utf-8").catch(()=>{}),await Io(e,{force:!0});else return}catch{}if(await Eg(e,{recursive:!0,mode:448}),t!==void 0){let n=Lr(e,"connect.json");await Yi(n,t,{mode:384}),await _u(n,384)}},Ji=async e=>{await tt();let t=Du();await Yi(t,e,{mode:384}),await _u(t,384)},$e=async()=>{try{let e=await Ya(Du(),"utf-8");return e.trim()?e:void 0}catch{return}},Ja=async()=>{await Io(Du(),{force:!0}).catch(()=>{})},P=async()=>{try{let e=await Ya(await Rg(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}},tO=0,nO=3e4,rO=5e3,oO=25,aO=()=>Lr(xg(),".anyray-connect-profile.lock"),Ou=new QR,sO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},iO=async e=>{try{let t=JSON.parse(await Ya(Lr(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!sO(t.pid)}catch{}return Date.now()-(await Pu(e)).mtimeMs>nO},Og=async(e=rO)=>{let t=aO(),n=Lr(t,"owner.json"),r=Date.now()+e;for(;;){let o=eO();try{await Eg(t,{mode:448});try{await Yi(n,`${JSON.stringify({pid:process.pid,nonce:o})}
5
+ `,{mode:384})}catch(s){throw await Io(t,{recursive:!0,force:!0}).catch(()=>{}),s}return async()=>{try{JSON.parse(await Ya(n,"utf-8")).nonce===o&&await Io(t,{recursive:!0,force:!0})}catch{}}}catch(s){if(s.code!=="EEXIST")throw s}if(!(await iO(t).catch(()=>!1)&&await Io(t,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=r)throw new Error("connect profile is busy; retry the command");await new Promise(s=>setTimeout(s,oO))}}},Xa=async(e,t={})=>{if(Ou.getStore()===!0)return e();let n=await Og(t.waitMs);try{return await Ou.run(!0,e)}finally{await n()}},Sg=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Rg(),r=`${n}.${process.pid}.${tO++}.tmp`;await Yi(r,`${JSON.stringify(t,null,2)}
6
+ `,{mode:384}),await _u(r,384);try{await he(r,n)}catch(o){throw await Io(r,{force:!0}).catch(()=>{}),o}},ae=async e=>{if(Ou.getStore()===!0){await Sg(e);return}let t=await Og();try{await Sg(e)}finally{await t()}};var Tu=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],Ig="ssoLink",Lu=async()=>{let e=await P();return Tu.some(t=>e[t]!==void 0)?!0:await $e()!==void 0},Xi=async()=>{let e=await P(),t=Tu.some(a=>e[a]!==void 0),n=e[Ig]!==void 0,r=e.byoUpstream!==void 0,o=await $e()!==void 0;if(t||n||r||e.managedEnrollmentDisabled!==!0){let a={...e};for(let s of Tu)delete a[s];delete a[Ig],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,delete a.anyrayFleetManaged,await ae(a)}if(await Ja(),await $e())throw new Error(`could not remove the dev key from ${Q()}`);return t||n||r||o},Kn=async(e,t,n=!1)=>{let r=await P(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let m of e){let h=m.status==="configured"||m.status==="queued";!t&&h&&(o.add(m.id),a.delete(m.id),s=void 0),t&&(m.status==="reverted"||m.status==="queued")&&(o.delete(m.id),a.add(m.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((m,h)=>m===c[h])&&r.revertedTools!=null&&l.length===d.length&&l.every((m,h)=>m===d[h])&&s===r.offboardedAt)return;let{offboardedAt:p,...f}=r;await ae({...f,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},zi=async(e=new Date().toISOString())=>{await ae({...await P(),offboardedAt:e})};var xo=e=>yO(e).replace(/\\/g,"/").toLowerCase(),$u=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",qa=e=>`${e}.source`,Lg=e=>/(^|\/)_npx(\/|$)/.test(xo(e)),Bu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(xo(e)),Fu=e=>{let t=xo(e),n=[hO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(xo);return Lg(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},ft=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),Qa=e=>/[\\/](node|node\.exe)$/i.test(e),jn=(e=ft())=>Qa(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,_g=e=>{try{let t=Pg(e);return t.isFile()?t.size:void 0}catch{return}},Wu=e=>{let t=Ue(e);if(Eo(t)==="versions")return t;let n=Ue(t);return Eo(n)==="versions"?n:void 0},Qi=(e,t)=>t!==void 0&&(Ue(e)===t||Ue(Ue(e))===t),gO=e=>{let t=Wu(e);if(!t)return;let n=Re(Ue(t),"bin",$u());try{let r=za(n);return r===za(e)||Qi(r,za(t))?n:void 0}catch{return}},Ro=(e=Q(),t=process.platform)=>{let n=Re(e,"bin",$u(t));try{let r=za(n),o=za(Re(e,"versions"));if(Qi(r,o))return n;if(t==="win32"){let a=lO(qa(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=_g(Re(o,a,$u(t)))??_g(Re(o,a));if(s!==void 0&&s===Pg(n).size)return n}}catch{return}},Nr=(e=ft())=>{let t=jn(e),n=Bu(t)||Hu(t)?Ro():void 0;return gO(e.execPath)??n??t},Ng=(e=ft())=>Nr(e)!==jn(e),en=(e,t=ft())=>{let n=Nr(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}},$g=(e=ft())=>{let t=Nr(e);return!Qa(e.execPath)&&!Fu(t)?Ue(t):Re(Q(),"bin")},qi=async e=>{try{return await dO(e),!0}catch{return!1}},wO=async e=>{let t=await pO(e),n=Ue(t),r=Ue(n),o=Re(r,"package.json"),a=await Mu(o,"utf8"),s=JSON.parse(a);if(typeof s.version!="string"||!/^[0-9A-Za-z][0-9A-Za-z.-]*$/.test(s.version))throw new Error("published package has no safe version");if(!await qi(Re(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},bO=async(e,t)=>{let n=t;for(;;){let r=Re(n,"node_modules",e);if(await qi(Re(r,"package.json")))return r;let o=Ue(n);if(o===n)return;n=o}},AO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Mu(Re(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await bO(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Dg(i,Re(t,s),{recursive:!0}),r.push(i)}}},CO=async(e=ft())=>{let t=Ro();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 wO(e.scriptPath);await tt();let r=Re(Q(),"bin",`connect-runtime-${n.version}`),o=Re(r,"dist","index.js");if(!await qi(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Nu(a,{recursive:!0,force:!0}),await Tg(a,{recursive:!0,mode:448});try{await Dg(n.dist,Re(a,"dist"),{recursive:!0}),await mO(Re(a,"package.json"),await Mu(n.packageJson),{mode:384}),await AO(n.root,Re(a,"node_modules")),await Tg(Ue(r),{recursive:!0,mode:448});try{await fO(a,r)}catch(s){if(!await qi(o))throw s}}finally{await Nu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Uu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,kO=e=>{let t=Eo(Ue(Ue(e)));return Uu.test(t)?t:void 0},Hu=(e,t=Q())=>{let n=Ue(Ue(e));return xo(Ue(n))===xo(Re(t,"bin"))&&Uu.test(Eo(n))&&Eo(Ue(e))==="dist"&&Eo(e)==="index.js"},ec=async(e=ft())=>{let t=Re(Q(),"bin"),n=kO(jn(e)),r=[];for(let o of await uO(t).catch(()=>[])){if(!Uu.test(o)||o===n)continue;let a=Re(t,o);await Nu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},Mg=async(e,t=ft())=>{let n=jn(t);if(!Qa(t.execPath)||!Lg(n)||Ro())return;let r=await CO(t),o=cO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Gu=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,es=(e,t)=>[e,...t].map(Gu).join(" "),kn=(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))},tc=(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},Oo=(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)},Vu=e=>{let t=e.hooks;if(!t)return!1;let n=!1;for(let[r,o]of Object.entries(t)){if(!Array.isArray(o))continue;let a=o.filter(s=>!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",Bg="__anyray-codex-hook",Yn="__anyray-prompt-hook",Fg="__anyray-shell-pretool",Ku="__anyray-shell-run",Wg="__anyray-read-pretool",Jn="__anyray-refresh",ts=(e,t=[])=>{let{command:n,args:r}=en([e,...t]);return{command:n,args:r}},Rt=(e,t=[])=>{let n=ts(e,t);return[n.command,...n.args].map(Gu).join(" ")},nc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Rt(t,n),Ug=()=>Rt("print-key"),Oe=()=>Nr(),He=Fu,te=()=>!He(Oe()),$r=async()=>{if(!te())return!1;try{return await vO(Oe()),!0}catch{return!1}},Xn="__anyray-mcp-server",Ge=e=>ts(Xn,[e]),SO=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),rc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ge(t);return n.command===r.command&&SO(n.args,r.args)},Ot=(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)===Xn&&r.at(-1)===t};var ee=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,ue=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Mr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Hg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],oc=[...Mr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],IO=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
7
+ `)},tn=(e,t={})=>{let n=e.byoUpstream,r=!n&&ee(e,"anthropic"),o=ue({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1,s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=IO(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 ju}from"zod";var EO=5e3,xO=1e3,RO=1e8,OO=ju.object({modelContext:ju.object({contextTokens:ju.number().int().min(xO).max(RO)}).optional()}),Gg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},Vg=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??EO,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=OO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var TO=1e6,ns="[1m]",_O=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Kg=(e,t)=>!e||t===void 0?{}:_O(e)?{envTokens:t}:t<TO?{}:e.toLowerCase().endsWith(ns)?{}:{model:`${e}${ns}`},jg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(ns))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(ns))return e.slice(0,-ns.length)};import{platform as PO}from"node:os";var Tt=(e=PO())=>{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 vn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],ac=e=>typeof e=="string"&&e.trim()!=="",DO=(e,t)=>typeof e[t]=="string"&&!ac(e[t]),Zg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},LO=()=>M(Tt()).catch(()=>({})),Yg=async(e={})=>{let t=e.env??process.env,n=Zg(e.userSettings??{}),r=Zg(await(e.readManaged??LO)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of vn)ac(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Tt()})`,repairable:!1}):ac(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!DO(n,a)&&ac(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Zu=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`,Yu=e=>"Fix: remove the setting where it is set"+(e.some(t=>t.kind==="managed")?" (the managed settings file is IT-owned \u2014 ask your admin)":"")+", then restart Claude Code. The gateway can serve Bedrock/Vertex itself once its provider is configured \u2014 see the Bedrock page in the Anyray docs.",Jg=e=>`Disabled direct ${e.cloud} mode: ${e.name} was set (${e.source}), which would bypass the gateway route entirely \u2014 pinned it empty in settings.json (the env block outranks shell exports, and '' is Claude Code's documented unset). Delete the original setting to drop the pin.`;var NO=vn.map(e=>e.name),$O=oc.filter(e=>!NO.includes(e)),Xg=e=>typeof e=="string"&&e.trim()!=="",zg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},MO=(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)},BO=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Ju=()=>M(Tt()).catch(()=>({})),qg=Ju,FO=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))},Qg=async(e={})=>{let t=await(e.readManaged??qg)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!FO(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},sc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Tt()}) \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 (${Tt()}), 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",ic=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.",ew=async(e={})=>{let t=zg(e.userSettings??{}),n=zg(await(e.readManaged??qg)().catch(()=>({}))),r=[];for(let o of $O){if(!Xg(n[o])||!Xg(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(MO(n[o],t[o],a))continue;let s=a?BO(n[o]):void 0;r.push({name:o,source:`managed settings (${Tt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},tw=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`,nw=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 WO}from"node:os";import{join as UO}from"node:path";import{readFile as HO}from"node:fs/promises";var GO=400,rw=async()=>{try{let e=UO(WO(),".claude","settings.json"),n=JSON.parse(await HO(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
8
+ `)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},ow=async()=>{try{let e=await P();return e.gateway?{origin:new URL(e.gateway).origin,metadata:ue({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},nt=async(e="auto")=>e==="profile"?ow():e==="claude"?rw():await rw()??await ow(),cc=async(e={})=>{let t=e.readTarget??nt,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;try{a=new URL(r.gateway).origin}catch{return"unreadable"}return a===o.origin?"owned":"foreign"},Vt=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},lc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),GO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Vt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var zn=()=>pc(uc(),".claude","settings.json"),dc=()=>pc(uc(),".claude.json"),VO=oc,Sn="anyray",KO=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),qn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),jO=e=>e instanceof Error?e.name:"UnknownError",ZO=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${Sn} is not owned by Anyray Connect, so it was left untouched. Rename or remove that entry, then re-run anyray-connect.`;case"unreadable":return`Could not read ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is readable.`;case"unwritable":return`Could not write ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is writable.`;case"not-persisted":return`Registered the Anyray retrieval MCP server in ${t}, but the entry was gone when re-read \u2014 Claude Code rewrites that file wholesale while it runs. Fully quit Claude Code, then re-run anyray-connect.`}},YO={readJson:M,writeJson:(e,t)=>Y(e,t)},JO=async(e,t=YO)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(XO(r)==="conflict")return{outcome:"failed",failure:"foreign"};try{await t.writeJson(e,r)}catch{return{outcome:"failed",failure:"unwritable"}}let o;try{o=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}let a=o.mcpServers,s=qn(a)?a[Sn]:void 0;if(s&&Ot(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},XO=e=>{if("mcpServers"in e&&!qn(e.mcpServers))return"conflict";let t=qn(e.mcpServers)?{...e.mcpServers}:{},n=t[Sn];return n!==void 0&&!Ot(n,"claude")?"conflict":(t[Sn]=KO(),e.mcpServers=t,"installed")},aw=e=>{let t=e.mcpServers;return!t||!(Sn in t)||!Ot(t[Sn],"claude")?!1:(delete t[Sn],Object.keys(t).length===0&&delete e.mcpServers,!0)},zO=e=>{tc(e,"PostToolUse",ze,kn(Rt(ze),{matcher:"*"})),tc(e,"UserPromptSubmit",Yn,kn(Rt(Yn)))},qO=e=>{tc(e,"SessionStart",Jn,kn(Rt(Jn),{async:!0}))},cw=e=>Oo(e,"SessionStart",Jn),sw=e=>{let t=Oo(e,"PostToolUse",ze),n=Oo(e,"UserPromptSubmit",Yn),r=cw(e);return t||n||r},QO="print-key",eT=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Br=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===QO&&eT(t)},tT=async(e,t)=>{let n=(await Dr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of VO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},nT=e=>typeof e.apiKeyHelper=="string"&&!Br(e),lw=async e=>{let t=await Ju(),n=async()=>t,[r,o,a]=await Promise.all([Yg({userSettings:e,readManaged:n}),ew({userSettings:e,readManaged:n}).catch(()=>[]),Qg({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},iw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await lw(e),o=Yu(t),a=nw(n);return{routingOverrides:[...t.map(i=>({problem:Zu(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:tw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},Qn={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=pc(uc(),".claude"),t=await x(e);return{installed:t,detail:t?zn():"no ~/.claude directory"}},async apply(e,t){let n=zn(),r=await M(n),o=Gg(r),a=await Vg(e.origin,e.clientKey,o),s=Kg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=tn(e,{contextWindowTokens:s.envTokens}),{directOverrides:p,hookPolicy:f}=await lw(r),m=p.filter(R=>!R.repairable),h=p.filter(R=>R.repairable),w=[...m.map(R=>`WARNING: ${Zu(R)}.`),...m.length?[Yu(m)]:[],...f.state==="fine"?[]:[`WARNING: ${sc(f)}.`,ic(f)],...h.map(R=>Jg(R)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let y=r.env??{};r.env={...y,...i};let g=r.env;for(let{name:R}of vn)h.some(N=>N.name===R)?g[R]="":g[R]===""&&(process.env[R]??"").trim()===""&&delete g[R];if(u||delete g.ANTHROPIC_CUSTOM_HEADERS,c&&(y.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete g.ANTHROPIC_AUTH_TOKEN),l)for(let R of Hg)delete g[R];let b=!!e.clientKey,k=te(),C=nT(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=Ug(),g.ANTHROPIC_AUTH_TOKEN="",w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Br(r)&&delete r.apiKeyHelper,C&&!c&&!l&&b&&k&&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&&k?(qO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):cw(r),te()?(zO(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.")):(sw(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 Y(n,r);let I=[n],E=dc();if(te()){let R=await JO(E);R.outcome==="registered"?(I.push(E),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.")):w.push(ZO(R.failure,E))}else try{let R=await M(E);aw(R)&&(await Y(E,R),I.push(E))}catch(R){w.push(`Could not clean up a stale Anyray MCP registration in ${E} (${jO(R)}).`)}return{status:"configured",messages:w,changedFiles:I}},skillsDir(){return pc(uc(),".claude","skills")},async pointsAt(e){let t=zn();if(!await x(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(zn()).catch(()=>({}));return iw(e)},async routingOverrides(){let e=await M(zn()).catch(()=>({}));return(await iw(e)).routingOverrides},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=dc();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await M(e)).mcpServers?.[Sn];return r?Ot(r,"claude")?{registered:!0,command:typeof r.command=="string"?r.command:null}:{registered:!1,command:null,reason:"foreign"}:{registered:!1,command:null,reason:"absent"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=zn();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!qn(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)&&qn(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>qn(l)&&nc(l.command,ze))))}}catch{e="unreadable"}let r,o=!0,a=dc();if(!await x(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!qn(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Sn];r=i===void 0?"missing":Ot(i,"claude")?"owned":"foreign",r==="owned"&&(o=rc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await $r()?"owned":"missing",beacon_target:await cc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(zn()),t=qn(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=zn();if(!await x(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=sw(n),a=Br(n);a&&delete n.apiKeyHelper;let s=r?await tT(t,r):[],i=jg(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 Y(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=dc();try{let d=await M(l);aw(d)&&(await Y(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await oe(t),{status:"reverted",messages:c,changedFiles:[t]}}};var er=e=>{let{command:t,args:n}=en([e]);return{command:t,args:n}},tr=()=>Nr();import{homedir as zu,platform as uw}from"node:os";import{join as fc}from"node:path";import{mkdir as oT,rm as pw,writeFile as aT,link as sT,copyFile as iT,readFile as pX}from"node:fs/promises";import{spawnSync as cT}from"node:child_process";import{homedir as dw,userInfo as rT}from"node:os";var rs=()=>{try{return dw()!==rT().homedir}catch{return!1}},Xu=e=>[`Skipped ${e} \u2014 HOME (${dw()}) 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 qu="ai.anyray.connect.app",os="Anyray",fw=(e=zu())=>fc(e,"Applications",`${os}.app`),mw="anyray-connect",lT=e=>`<?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>CFBundleIdentifier</key><string>${Qu}</string>
12
+ <key>CFBundleIdentifier</key><string>${qu}</string>
13
13
  <key>CFBundleName</key><string>${os}</string>
14
14
  <key>CFBundleDisplayName</key><string>${os}</string>
15
- <key>CFBundleExecutable</key><string>${uw}</string>
15
+ <key>CFBundleExecutable</key><string>${mw}</string>
16
16
  <key>CFBundlePackageType</key><string>APPL</string>
17
17
  <key>CFBundleShortVersionString</key><string>${e}</string>
18
18
  <key>CFBundleVersion</key><string>${e}</string>
@@ -22,7 +22,7 @@ var PR="http://localhost:8787",ja="anyray-placeholder",Ee=e=>{let t=e?.trim();re
22
22
  <key>NSHumanReadableCopyright</key><string>Othentic Labs LTD</string>
23
23
  </dict>
24
24
  </plist>
25
- `,nT="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",rT=e=>{try{eT(nT,["-f",e],{stdio:"ignore",timeout:1e4})}catch{}},pw=async(e={})=>{if((e.os??cw())!=="darwin")return{ok:!0,messages:[]};let n=e.home??qu(),r=e.binaryPath??er();if(Ue(r))return{ok:!1,messages:[`Skipped the Login Items identity app \u2014 anyray-connect is running from a temporary path (${r}).`]};if(rs())return{ok:!1,messages:["Skipped the Login Items identity app \u2014 HOME is redirected away from the real account."]};let o=dw(n),a=fc(o,"Contents","MacOS"),s=fc(a,uw),i=e.version??"0.0.0";try{await lw(o,{recursive:!0,force:!0}),await XO(a,{recursive:!0}),await zO(fc(o,"Contents","Info.plist"),tT(i),"utf8");try{await qO(r,s)}catch{await QO(r,s)}return(e.register??rT)(o),{ok:!0,messages:[`Registered ${os} as the Login Items identity.`]}}catch(c){return{ok:!1,messages:[`Could not write the Login Items identity app (${c?.name??"Error"}). Background items will show the signing certificate name instead.`]}}},fw=async(e={})=>{if((e.os??cw())!=="darwin")return{ok:!0,messages:[]};if(rs())return{ok:!0,messages:[]};let n=dw(e.home??qu());try{return await lw(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed ${os}.app.`]}}catch(r){return{ok:!1,messages:[`Could not remove the Login Items identity app (${r?.name??"Error"}).`]}}};var Ae="0.11.170";var nn=(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,Fr=(e=process.env)=>nn(e)!==null,Sn=e=>e==="codespaces"||e==="devcontainer",To=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var mw=()=>Hr(wc(),".anyray","logs"),tp=()=>Hr(mw(),"connect-refresh.log"),gc=1800,bc="ai.anyray.connect.refresh",is="anyray-refresh",rp="\\AnyrayConnectKeyRefresh",Ac=bc,cs=is,ss=rp,iT=String(gc/60),op=(e,t)=>{let n=sT(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},ap=()=>Hr(wc(),"Library","LaunchAgents",`${Ac}.plist`),sp=()=>Hr(wc(),".config","systemd","user"),hw=()=>Hr(sp(),`${cs}.service`),yc=()=>Hr(sp(),`${cs}.timer`),hc=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Cc=()=>Qn(Yn),cT=(e=Cc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${hc(o)}</string>`).join(`
25
+ `,dT="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",uT=e=>{try{cT(dT,["-f",e],{stdio:"ignore",timeout:1e4})}catch{}},hw=async(e={})=>{if((e.os??uw())!=="darwin")return{ok:!0,messages:[]};let n=e.home??zu(),r=e.binaryPath??tr();if(He(r))return{ok:!1,messages:[`Skipped the Login Items identity app \u2014 anyray-connect is running from a temporary path (${r}).`]};if(rs())return{ok:!1,messages:["Skipped the Login Items identity app \u2014 HOME is redirected away from the real account."]};let o=fw(n),a=fc(o,"Contents","MacOS"),s=fc(a,mw),i=e.version??"0.0.0";try{await pw(o,{recursive:!0,force:!0}),await oT(a,{recursive:!0}),await aT(fc(o,"Contents","Info.plist"),lT(i),"utf8");try{await sT(r,s)}catch{await iT(r,s)}return(e.register??uT)(o),{ok:!0,messages:[`Registered ${os} as the Login Items identity.`]}}catch(c){return{ok:!1,messages:[`Could not write the Login Items identity app (${c?.name??"Error"}). Background items will show the signing certificate name instead.`]}}},yw=async(e={})=>{if((e.os??uw())!=="darwin")return{ok:!0,messages:[]};if(rs())return{ok:!0,messages:[]};let n=fw(e.home??zu());try{return await pw(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed ${os}.app.`]}}catch(r){return{ok:!1,messages:[`Could not remove the Login Items identity app (${r?.name??"Error"}).`]}}};var Ae="0.11.171";var nn=(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,Fr=(e=process.env)=>nn(e)!==null,In=e=>e==="codespaces"||e==="devcontainer",To=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var gw=()=>Ur(wc(),".anyray","logs"),ep=()=>Ur(gw(),"connect-refresh.log"),gc=1800,bc="ai.anyray.connect.refresh",is="anyray-refresh",np="\\AnyrayConnectKeyRefresh",Ac=bc,cs=is,ss=np,hT=String(gc/60),rp=(e,t)=>{let n=mT(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},op=()=>Ur(wc(),"Library","LaunchAgents",`${Ac}.plist`),ap=()=>Ur(wc(),".config","systemd","user"),ww=()=>Ur(ap(),`${cs}.service`),yc=()=>Ur(ap(),`${cs}.timer`),hc=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Cc=()=>er(Jn),yT=(e=Cc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${hc(o)}</string>`).join(`
26
26
  `);return`<?xml version="1.0" encoding="UTF-8"?>
27
27
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28
28
  <plist version="1.0">
@@ -30,7 +30,7 @@ var PR="http://localhost:8787",ja="anyray-placeholder",Ee=e=>{let t=e?.trim();re
30
30
  <key>Label</key><string>${Ac}</string>
31
31
  <key>AssociatedBundleIdentifiers</key>
32
32
  <array>
33
- <string>${hc(Qu)}</string>
33
+ <string>${hc(qu)}</string>
34
34
  </array>
35
35
  <key>ProgramArguments</key>
36
36
  <array>
@@ -40,18 +40,18 @@ ${r}
40
40
  <key>RunAtLoad</key><true/>
41
41
  <key>ProcessType</key><string>Background</string>
42
42
  <key>LowPriorityIO</key><true/>
43
- <key>StandardOutPath</key><string>${hc(tp())}</string>
44
- <key>StandardErrorPath</key><string>${hc(tp())}</string>
43
+ <key>StandardOutPath</key><string>${hc(ep())}</string>
44
+ <key>StandardErrorPath</key><string>${hc(ep())}</string>
45
45
  </dict>
46
46
  </plist>
47
- `},lT=(e=Cc())=>{let{command:t,args:n}=e;return`[Unit]
47
+ `},gT=(e=Cc())=>{let{command:t,args:n}=e;return`[Unit]
48
48
  Description=Anyray connect gateway key refresh
49
49
  After=network-online.target
50
50
 
51
51
  [Service]
52
52
  Type=oneshot
53
53
  ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
54
- `},dT=()=>`[Unit]
54
+ `},wT=()=>`[Unit]
55
55
  Description=Anyray connect gateway key refresh (every ${gc/60}m)
56
56
 
57
57
  [Timer]
@@ -61,65 +61,65 @@ Persistent=true
61
61
 
62
62
  [Install]
63
63
  WantedBy=timers.target
64
- `,uT=(e=Cc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),as=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(" ")}`],yw=e=>!e.run&&rs(),pT=async(e,t)=>await oT(ap(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Ac]).ok,tr=async(e={})=>{let t=e.os??np(),n=e.invocation??Cc(),r=e.run??op,o=e.binaryPath??er();if(Ue(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(yw(e))return{ok:!1,messages:zu("auto-refresh scheduling")};let a=nn(e.env??(e.run?{}:process.env));if(Sn(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${To(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=cT(n);if(await pT(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await ep(mw(),{recursive:!0,mode:448}),await ep(Hr(wc(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=await pw({os:t,binaryPath:o,version:Ae}),d=`${s}.new-${process.pid}`;await Wr(d,{force:!0}).catch(()=>{}),await mc(d,i),r("launchctl",["bootout",`gui/${c}`,s]),await Wr(s,{force:!0}).catch(()=>{});try{await aT(d,s)}catch{await mc(s,i),await Wr(d,{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}).`,...l.ok?[]:l.messages]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...as(n)]}}if(t==="linux")return await ep(sp(),{recursive:!0}),await mc(hw(),lT(n)),await mc(yc(),dT()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${cs}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${yc()}).`]}:{ok:!1,messages:[`Wrote ${yc()} but \`systemctl --user enable --now\` failed.`,...as(n)]};if(t==="win32"){let s=uT(n);return r("schtasks",["/Create","/TN",ss,"/TR",s,"/SC","MINUTE","/MO",iT,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",ss]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${ss}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...as(n)]}}return{ok:!1,messages:as(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...as(n)]}}},nr=async(e={})=>{await Wr(tp(),{force:!0}).catch(()=>{});let t=e.os??np(),n=e.run??op,r=[];if(yw(e))return{ok:!0,messages:zu("scheduler teardown")};try{if(t==="darwin"){let o=ap(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Wr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.");let s=await fw();s.ok||r.push(...s.messages)}else t==="linux"?(n("systemctl",["--user","disable","--now",`${cs}.timer`]),await Wr(yc(),{force:!0}),await Wr(hw(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",ss,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},_o=async(e=np(),t=op)=>e==="win32"?t("schtasks",["/Query","/TN",ss]).ok:e==="darwin"?t("launchctl",["list",Ac]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${cs}.timer`]).ok:!1;import{platform as fT}from"node:os";import{stat as mT}from"node:fs/promises";import{spawnSync as hT}from"node:child_process";var gw="/Applications/Anyray Connect Tray.app",yT=new Set(["V53XMA78UF"]),gT="ai.anyray.connect-tray",wT=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,bT=e=>{let t=hT("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
65
- ${t.stderr??""}`}},AT=async e=>{try{return(await mT(e)).isDirectory()}catch{return!1}},CT=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},ip=async(e,t={})=>{if((t.os??fT())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??AT)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??bT;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?CT(a.output):void 0;return s?yT.has(s)?wT(a.output)!==gT?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},Po=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await ip(n,t)).ok?"healthy":"gone"},cp=async(e={})=>{try{let t=e.load??D,n=await t(),r=await Po(n,e);if(r!=="gone")return r;let o=e.installScheduler??tr;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),await(e.save??oe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var kT={"not-macos":"persistence swap: macOS only \u2014 the LaunchAgent stays 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 LaunchAgent stays in place.","untrusted-bundle-id":"persistence swap: that bundle is not the Anyray Connect Tray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgent stays in place."},vT=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},ST=async(e,t)=>{let n=t.stderr??console.error,r=vT(e,"--app-path")??gw,o=await ip(r,t);if(!o.ok)return n(kT[o.reason]),1;let s=await(t.load??D)();return await(t.save??oe)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??nr)().catch(()=>{}),0},IT=async e=>{let t=e.load??D,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??tr;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),await(e.save??oe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},ww=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await ST(e,t):e.includes("--release-tray")?await IT(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{access as ET}from"node:fs/promises";import{homedir as bw,platform as lp}from"node:os";import{join as ls}from"node:path";var dp=(e=lp(),t=bw())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:bc,paths:[ls(t,"Library","LaunchAgents",`${bc}.plist`)],dataPaths:[ls(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=ls(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${is}.timer`,paths:[ls(n,`${is}.timer`),ls(n,`${is}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:rp,paths:[]}]:[]},Aw=async e=>{try{return await ET(e),!0}catch{return!1}},kc=async(e={})=>{let t=e.os??lp(),n=e.exists??Aw;for(let r of dp(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await _o(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},Cw=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable||!e.schedulerEnabled||e.schedulerInstalled)return t;let n=e.exists??Aw;for(let r of dp(e.os,e.home))for(let o of r.paths)await n(o)||(t.missingPaths.push(o),t.kinds.includes(r.kind)||t.kinds.push(r.kind));return t.suspected=t.missingPaths.length>0,t},kw=(e=lp(),t=bw(),n=er())=>{let r=["Anyray connect can install one per-user background scheduler. It is","unprivileged, runs as the logged-in user, and renews the seat gateway key","so a long AI-coding session does not lose access.","","Executable:",` ${n}`,""];for(let o of dp(e,t)){r.push(`${o.title} \u2014 supervisor name: ${o.supervisorName}`);for(let a of o.paths)r.push(` ${a}`);o.paths.length===0&&r.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let a of o.dataPaths??[])r.push(` ${a} (captured stdout/stderr \u2014 error names only)`);r.push("")}return r.push("Also spawns, detached and short-lived (same executable, hidden","subcommands \u2014 not a separate install):"," - Coding-tool MCP clients run `anyray-connect __anyray-mcp-server` as a"," stdio server, which may spawn `anyray-connect __anyray-refresh`."," - The Anyray VS Code extension may spawn"," `anyray-connect __anyray-spawn-refresh` on activation."," These triggers are throttled and serialized with the scheduler.","","Network behavior:"," - Outbound: your org's Anyray gateway and endpoint-control APIs over HTTPS.","","Why it looks like persistence to a heuristic scanner: it is a real login","item, by design, so key renewal survives reboots. Allow-list the paths above","or let Fleet provide the refresh trigger instead."),r};import{homedir as LT}from"node:os";import{join as Tc}from"node:path";import{chmod as NT,readFile as ds,rm as Rw,copyFile as $T}from"node:fs/promises";var Ur="# >>> anyray connect >>>",Ic="# <<< anyray connect <<<",up="# restore: ",vw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ec=e=>{let t=new RegExp(`\\n*${vw(Ur)}[\\s\\S]*?${vw(Ic)}\\n?`,"g");return e.replace(t,"")},pp=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},vc=(e,t)=>e.split(t).length-1,Sw=e=>vc(e,"[")-vc(e,"]"),xT=e=>e.replace(/^['"]|['"]$/g,""),Sc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){vc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+Sw(pp(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?xT(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=pp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])vc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+Sw(l)))}return t},fp=e=>e.findIndex(t=>t.kind==="table"),mp=e=>e.includes(Ur),Iw=(e,t)=>{let n=`[${t}]`;return e.split(`
66
- `).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},hp=(e,t)=>Iw(Ec(e),t),yp=e=>{let t=e.indexOf(Ur);if(t<0)return;let n=e.indexOf(Ic,t+Ur.length);if(!(n<0))return e.slice(t,n)},Ew=(e,t)=>{let n=e.indexOf(Ur);if(n<0)return!1;let r=e.indexOf(Ic,n+Ur.length);return r<0?!1:Iw(e.slice(n,r),t)},gp=(e,t)=>{let r=Ec(e).split(`
67
- `),o=Sc(r),a=fp(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=pp(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}},xc=(e,t,n)=>{let r=xw(e),a=Ec(e).split(`
68
- `),s=Sc(a),i=fp(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 k=s[b];if(b<l&&k.kind==="key"&&c.has(k.key)){u.has(k.key)||u.set(k.key,a[b].trim());continue}d.push(a[b])}let p=Sc(d),f=fp(p),m=(f===-1?d:d.slice(0,f)).join(`
64
+ `,bT=(e=Cc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),as=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(" ")}`],bw=e=>!e.run&&rs(),AT=async(e,t)=>await pT(op(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Ac]).ok,nr=async(e={})=>{let t=e.os??tp(),n=e.invocation??Cc(),r=e.run??rp,o=e.binaryPath??tr();if(He(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(bw(e))return{ok:!1,messages:Xu("auto-refresh scheduling")};let a=nn(e.env??(e.run?{}:process.env));if(In(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${To(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=op(),i=yT(n);if(await AT(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await Qu(gw(),{recursive:!0,mode:448}),await Qu(Ur(wc(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=await hw({os:t,binaryPath:o,version:Ae}),d=`${s}.new-${process.pid}`;await Wr(d,{force:!0}).catch(()=>{}),await mc(d,i),r("launchctl",["bootout",`gui/${c}`,s]),await Wr(s,{force:!0}).catch(()=>{});try{await fT(d,s)}catch{await mc(s,i),await Wr(d,{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}).`,...l.ok?[]:l.messages]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...as(n)]}}if(t==="linux")return await Qu(ap(),{recursive:!0}),await mc(ww(),gT(n)),await mc(yc(),wT()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${cs}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${yc()}).`]}:{ok:!1,messages:[`Wrote ${yc()} but \`systemctl --user enable --now\` failed.`,...as(n)]};if(t==="win32"){let s=bT(n);return r("schtasks",["/Create","/TN",ss,"/TR",s,"/SC","MINUTE","/MO",hT,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",ss]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${ss}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...as(n)]}}return{ok:!1,messages:as(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...as(n)]}}},rr=async(e={})=>{await Wr(ep(),{force:!0}).catch(()=>{});let t=e.os??tp(),n=e.run??rp,r=[];if(bw(e))return{ok:!0,messages:Xu("scheduler teardown")};try{if(t==="darwin"){let o=op(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Wr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.");let s=await yw();s.ok||r.push(...s.messages)}else t==="linux"?(n("systemctl",["--user","disable","--now",`${cs}.timer`]),await Wr(yc(),{force:!0}),await Wr(ww(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",ss,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},_o=async(e=tp(),t=rp)=>e==="win32"?t("schtasks",["/Query","/TN",ss]).ok:e==="darwin"?t("launchctl",["list",Ac]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${cs}.timer`]).ok:!1;import{platform as CT}from"node:os";import{stat as kT}from"node:fs/promises";import{spawnSync as vT}from"node:child_process";var Aw="/Applications/Anyray Connect Tray.app",ST=new Set(["V53XMA78UF"]),IT="ai.anyray.connect-tray",ET=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,xT=e=>{let t=vT("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
65
+ ${t.stderr??""}`}},RT=async e=>{try{return(await kT(e)).isDirectory()}catch{return!1}},OT=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},sp=async(e,t={})=>{if((t.os??CT())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??RT)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??xT;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?OT(a.output):void 0;return s?ST.has(s)?ET(a.output)!==IT?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},Po=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await sp(n,t)).ok?"healthy":"gone"},ip=async(e={})=>{try{let t=e.load??P,n=await t(),r=await Po(n,e);if(r!=="gone")return r;let o=e.installScheduler??nr;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),await(e.save??ae)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var TT={"not-macos":"persistence swap: macOS only \u2014 the LaunchAgent stays 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 LaunchAgent stays in place.","untrusted-bundle-id":"persistence swap: that bundle is not the Anyray Connect Tray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgent stays in place."},_T=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},PT=async(e,t)=>{let n=t.stderr??console.error,r=_T(e,"--app-path")??Aw,o=await sp(r,t);if(!o.ok)return n(TT[o.reason]),1;let s=await(t.load??P)();return await(t.save??ae)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??rr)().catch(()=>{}),0},DT=async e=>{let t=e.load??P,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??nr;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),await(e.save??ae)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},Cw=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await PT(e,t):e.includes("--release-tray")?await DT(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{access as LT}from"node:fs/promises";import{homedir as kw,platform as cp}from"node:os";import{join as ls}from"node:path";var lp=(e=cp(),t=kw())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:bc,paths:[ls(t,"Library","LaunchAgents",`${bc}.plist`)],dataPaths:[ls(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=ls(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${is}.timer`,paths:[ls(n,`${is}.timer`),ls(n,`${is}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:np,paths:[]}]:[]},vw=async e=>{try{return await LT(e),!0}catch{return!1}},kc=async(e={})=>{let t=e.os??cp(),n=e.exists??vw;for(let r of lp(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await _o(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},Sw=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable||!e.schedulerEnabled||e.schedulerInstalled)return t;let n=e.exists??vw;for(let r of lp(e.os,e.home))for(let o of r.paths)await n(o)||(t.missingPaths.push(o),t.kinds.includes(r.kind)||t.kinds.push(r.kind));return t.suspected=t.missingPaths.length>0,t},Iw=(e=cp(),t=kw(),n=tr())=>{let r=["Anyray connect can install one per-user background scheduler. It is","unprivileged, runs as the logged-in user, and renews the seat gateway key","so a long AI-coding session does not lose access.","","Executable:",` ${n}`,""];for(let o of lp(e,t)){r.push(`${o.title} \u2014 supervisor name: ${o.supervisorName}`);for(let a of o.paths)r.push(` ${a}`);o.paths.length===0&&r.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let a of o.dataPaths??[])r.push(` ${a} (captured stdout/stderr \u2014 error names only)`);r.push("")}return r.push("Also spawns, detached and short-lived (same executable, hidden","subcommands \u2014 not a separate install):"," - Coding-tool MCP clients run `anyray-connect __anyray-mcp-server` as a"," stdio server, which may spawn `anyray-connect __anyray-refresh`."," - The Anyray VS Code extension may spawn"," `anyray-connect __anyray-spawn-refresh` on activation."," These triggers are throttled and serialized with the scheduler.","","Network behavior:"," - Outbound: your org's Anyray gateway and endpoint-control APIs over HTTPS.","","Why it looks like persistence to a heuristic scanner: it is a real login","item, by design, so key renewal survives reboots. Allow-list the paths above","or let Fleet provide the refresh trigger instead."),r};import{homedir as HT}from"node:os";import{join as Tc}from"node:path";import{chmod as GT,readFile as ds,rm as _w,copyFile as VT}from"node:fs/promises";var Hr="# >>> anyray connect >>>",Ic="# <<< anyray connect <<<",dp="# restore: ",Ew=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ec=e=>{let t=new RegExp(`\\n*${Ew(Hr)}[\\s\\S]*?${Ew(Ic)}\\n?`,"g");return e.replace(t,"")},up=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},vc=(e,t)=>e.split(t).length-1,xw=e=>vc(e,"[")-vc(e,"]"),NT=e=>e.replace(/^['"]|['"]$/g,""),Sc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){vc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+xw(up(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?NT(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=up(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])vc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+xw(l)))}return t},pp=e=>e.findIndex(t=>t.kind==="table"),fp=e=>e.includes(Hr),Rw=(e,t)=>{let n=`[${t}]`;return e.split(`
66
+ `).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},mp=(e,t)=>Rw(Ec(e),t),hp=e=>{let t=e.indexOf(Hr);if(t<0)return;let n=e.indexOf(Ic,t+Hr.length);if(!(n<0))return e.slice(t,n)},Ow=(e,t)=>{let n=e.indexOf(Hr);if(n<0)return!1;let r=e.indexOf(Ic,n+Hr.length);return r<0?!1:Rw(e.slice(n,r),t)},yp=(e,t)=>{let r=Ec(e).split(`
67
+ `),o=Sc(r),a=pp(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=up(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}},xc=(e,t,n)=>{let r=Tw(e),a=Ec(e).split(`
68
+ `),s=Sc(a),i=pp(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 k=s[b];if(b<l&&k.kind==="key"&&c.has(k.key)){u.has(k.key)||u.set(k.key,a[b].trim());continue}d.push(a[b])}let p=Sc(d),f=pp(p),m=(f===-1?d:d.slice(0,f)).join(`
69
69
  `),h=f===-1?"":d.slice(f).join(`
70
- `),w=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${up}${b}`),y=[Ur,...w,...t,Ic].join(`
70
+ `),w=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${dp}${b}`),y=[Hr,...w,...t,Ic].join(`
71
71
  `);return[m.replace(/\s*$/,""),y,h.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
72
72
 
73
73
  `).replace(/\s*$/,"")+`
74
- `},xw=e=>{let t=new Map,n=yp(e);if(n===void 0)return t;for(let r of n.split(`
75
- `)){let o=r.trim();if(!o.startsWith(up))continue;let a=o.slice(up.length).trim(),[s]=Sc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Rc=e=>{if(!mp(e))return null;let t=[...xw(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Ec(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
74
+ `},Tw=e=>{let t=new Map,n=hp(e);if(n===void 0)return t;for(let r of n.split(`
75
+ `)){let o=r.trim();if(!o.startsWith(dp))continue;let a=o.slice(dp.length).trim(),[s]=Sc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Rc=e=>{if(!fp(e))return null;let t=[...Tw(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Ec(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
76
76
  `),n].filter(a=>a.length>0).join(`
77
77
 
78
78
  `);return o.length>0?o+`
79
- `:""};import{randomUUID as RT}from"node:crypto";import{chmod as OT,mkdir as TT,rm as _T,writeFile as PT}from"node:fs/promises";import{dirname as DT}from"node:path";var we=async(e,t)=>{await TT(DT(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${RT()}`;try{await PT(n,t,{flag:"wx",mode:384}),await he(n,e),await OT(e,384)}finally{await _T(n,{force:!0}).catch(()=>{})}};var MT="codex",BT="Codex app / CLI / IDE",FT="https://chatgpt.com/backend-api/codex",WT="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",HT="x-anyray-client-context-window",UT="x-anyray-client-auto-compact-limit",_c=()=>process.env.CODEX_HOME?.trim()||Tc(LT(),".codex"),Gr=()=>Tc(_c(),"config.toml"),Oc=()=>`${Gr()}.anyray-bak`,wp=()=>Tc(_c(),"hooks.json"),In=()=>Tc(_c(),"anyray.config.toml"),Ow=e=>Oo(e,"PostToolUse",Ng),Tw=(e,t=!1)=>ue({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||MT,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||BT}),rt=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,bp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,us=(e,t={})=>{let n=Tw(e,t.ignoreEnv),r=ee(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:bp(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${rt(FT)}`,`"x-anyray-forward-headers" = ${rt(WT)}`,...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(`"${HT}" = ${rt(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${UT}" = ${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(", ")}]`]:[]]},GT=()=>bp()?["model_provider","model"]:["model_provider"],_w={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=_c(),t=await x(e);return{installed:t,detail:t?Gr():`no ${e} directory`}},async apply(e,t){let n=Gr(),r=wp(),o=Tw(e),a=ee(e,"openai"),s=bp(),i=ce(),c={},l=await x(r);try{l&&(c=await B(r))}catch(k){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${k instanceof Error?k.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=Ow(c),u=await x(n),p=u?await ds(n,"utf-8"):"";if(hp(p,"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 f=hp(p,"mcp_servers.anyray"),m=gp(p,"model_context_window"),h=gp(p,"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.",h?`Context budget: follows model_auto_compact_token_limit=${h}.`:m?`Context budget: follows model_context_window=${m}.`:"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 y=[];d?(await Y(r,c,{backup:!1}),await re(r),y.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 x(Oc())&&(await $T(n,Oc()),await NT(Oc(),384),w.push(`Backed up your original config to ${Oc()}.`));let g=i&&!f?Ge("profile"):void 0;w.push(f?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:g?"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=xc(p,us(e,{mcpServer:g,modelContextWindow:m,modelAutoCompactTokenLimit:h}),GT());return await we(n,b),y.push(n),await x(In())&&(await Rw(In(),{force:!0}),y.push(In()),w.push(`Removed the old opt-in profile ${In()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:y}},async pointsAt(e){let t=Gr();if(!await x(t))return!1;try{let n=await ds(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=Gr();if(!await x(e))return{registered:!1,command:null};try{let t=await ds(e,"utf-8");if(!Ew(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 ds(Gr(),"utf-8"),t=yp(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=Gr(),n=await x(t),r=await x(In()),o=await x(wp());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=wp(),c;try{c=await B(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.`]}}Ow(c)&&(e.dryRun||(await Y(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=Rc(await ds(t,"utf-8"));i!==null&&(e.dryRun||await we(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 Rw(In(),{force:!0}),s.push(In()),a.push(e.dryRun?`would remove the old opt-in profile ${In()}`:`removed the old opt-in profile ${In()}`)),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 JT}from"node:os";import{join as XT}from"node:path";import{readFile as Nw,rm as Cp}from"node:fs/promises";import{readFile as VT,writeFile as Pw,access as KT}from"node:fs/promises";import{homedir as jT}from"node:os";import{join as Ap}from"node:path";var ZT="# >>> anyray connect >>>",YT="# <<< anyray connect <<<",ps=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:ZT,end:YT},gt=()=>{let e=jT(),t=process.env.SHELL||"";return t.includes("zsh")?Ap(e,".zshrc"):t.includes("bash")?Ap(e,".bashrc"):Ap(e,".profile")},Pc=async e=>{try{return await KT(e),await VT(e,"utf-8")}catch{return""}},Dw=(e,t)=>{let{begin:n,end:r}=ps(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]===`
79
+ `:""};import{randomUUID as $T}from"node:crypto";import{chmod as MT,mkdir as BT,rm as FT,writeFile as WT}from"node:fs/promises";import{dirname as UT}from"node:path";var we=async(e,t)=>{await BT(UT(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${$T()}`;try{await WT(n,t,{flag:"wx",mode:384}),await he(n,e),await MT(e,384)}finally{await FT(n,{force:!0}).catch(()=>{})}};var KT="codex",jT="Codex app / CLI / IDE",ZT="https://chatgpt.com/backend-api/codex",YT="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",JT="x-anyray-client-context-window",XT="x-anyray-client-auto-compact-limit",_c=()=>process.env.CODEX_HOME?.trim()||Tc(HT(),".codex"),Gr=()=>Tc(_c(),"config.toml"),Oc=()=>`${Gr()}.anyray-bak`,gp=()=>Tc(_c(),"hooks.json"),En=()=>Tc(_c(),"anyray.config.toml"),Pw=e=>Oo(e,"PostToolUse",Bg),Dw=(e,t=!1)=>ue({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||KT,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||jT}),rt=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,wp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,us=(e,t={})=>{let n=Dw(e,t.ignoreEnv),r=ee(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:wp(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${rt(ZT)}`,`"x-anyray-forward-headers" = ${rt(YT)}`,...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(`"${JT}" = ${rt(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${XT}" = ${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(", ")}]`]:[]]},zT=()=>wp()?["model_provider","model"]:["model_provider"],Lw={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=_c(),t=await x(e);return{installed:t,detail:t?Gr():`no ${e} directory`}},async apply(e,t){let n=Gr(),r=gp(),o=Dw(e),a=ee(e,"openai"),s=wp(),i=te(),c={},l=await x(r);try{l&&(c=await M(r))}catch(k){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${k instanceof Error?k.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=Pw(c),u=await x(n),p=u?await ds(n,"utf-8"):"";if(mp(p,"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 f=mp(p,"mcp_servers.anyray"),m=yp(p,"model_context_window"),h=yp(p,"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.",h?`Context budget: follows model_auto_compact_token_limit=${h}.`:m?`Context budget: follows model_context_window=${m}.`:"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 y=[];d?(await Y(r,c,{backup:!1}),await oe(r),y.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 x(Oc())&&(await VT(n,Oc()),await GT(Oc(),384),w.push(`Backed up your original config to ${Oc()}.`));let g=i&&!f?Ge("profile"):void 0;w.push(f?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:g?"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=xc(p,us(e,{mcpServer:g,modelContextWindow:m,modelAutoCompactTokenLimit:h}),zT());return await we(n,b),y.push(n),await x(En())&&(await _w(En(),{force:!0}),y.push(En()),w.push(`Removed the old opt-in profile ${En()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:y}},async pointsAt(e){let t=Gr();if(!await x(t))return!1;try{let n=await ds(t,"utf-8"),r=`base_url = ${rt(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Gr();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await ds(e,"utf-8");if(!Ow(t,"mcp_servers.anyray"))return{registered:!1,command:null,reason:"absent"};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,reason:"unreadable"}}},async inferenceAuthLanes(){try{let e=await ds(Gr(),"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=Gr(),n=await x(t),r=await x(En()),o=await x(gp());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=gp(),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.`]}}Pw(c)&&(e.dryRun||(await Y(i,c,{backup:!1}),await oe(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=Rc(await ds(t,"utf-8"));i!==null&&(e.dryRun||await we(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 _w(En(),{force:!0}),s.push(En()),a.push(e.dryRun?`would remove the old opt-in profile ${En()}`:`removed the old opt-in profile ${En()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await oe(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as r_}from"node:os";import{join as o_}from"node:path";import{readFile as Bw,rm as Ap}from"node:fs/promises";import{readFile as qT,writeFile as Nw,access as QT}from"node:fs/promises";import{homedir as e_}from"node:os";import{join as bp}from"node:path";var t_="# >>> anyray connect >>>",n_="# <<< anyray connect <<<",ps=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:t_,end:n_},gt=()=>{let e=e_(),t=process.env.SHELL||"";return t.includes("zsh")?bp(e,".zshrc"):t.includes("bash")?bp(e,".bashrc"):bp(e,".profile")},Pc=async e=>{try{return await QT(e),await qT(e,"utf-8")}catch{return""}},$w=(e,t)=>{let{begin:n,end:r}=ps(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]===`
80
80
  `;)s-=1;let i=a+r.length;return e[i]===`
81
- `&&(i+=1),e.slice(0,s)+e.slice(i)},Dc=async(e,t,n)=>{let r=await Pc(e),{begin:o,end:a}=ps(n),s=Dw(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
81
+ `&&(i+=1),e.slice(0,s)+e.slice(i)},Dc=async(e,t,n)=>{let r=await Pc(e),{begin:o,end:a}=ps(n),s=$w(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
82
82
  `),c=s?`${s}
83
83
 
84
84
  ${i}
85
85
  `:`${i}
86
- `;return await Pw(e,c),e},Lc=async(e,t)=>{let n=await Pc(e),{begin:r,end:o}=ps(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(`
87
- `).filter(c=>c.trim().length>0)},Lw=async(e,t)=>(await Pc(e)).includes(ps(t).begin),fs=async(e,t)=>{let n=await Pc(e);return n.includes(ps(t).begin)?(await Pw(e,Dw(n,t).replace(/\s*$/,"")+`
88
- `),!0):!1};var Tt=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var ve=e=>`'${e.replace(/'/g,"'\\''")}'`,zT=e=>{let t=ve(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},$w=(e,t,n,r)=>[`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${ve(t)}`],`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${ve(t)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]],qT=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],QT=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],kp=()=>XT(JT(),".anyray","shell-env.sh"),Bw="# Managed by anyray-connect. Do not source this file anywhere else.",Mw=e=>e.split(/\r?\n/,1)[0]===Bw,vp=e=>QT.some(t=>e.startsWith(`export ${t}=`)),Nc=(e,t=process.env)=>t.ANTHROPIC_BASE_URL===e.anthropicBaseUrl||t.OPENAI_BASE_URL===e.openaiBaseUrl?qT.filter(r=>(t[r]??"")!==""):[],Fw={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=gt();return{installed:!0,detail:await x(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await Lc(gt());return e?e.some(n=>vp(n)||n.includes(kp()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=gt(),r=ee(e,"openai"),o=ee(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=$w(e,s,r,o),c=i.filter(vp),l=i.filter(b=>!vp(b)),d=kp(),u=Dg(),p=[zT(u),...l,...c.length>0?[`[ -r ${ve(d)} ] && . ${ve(d)}`]:[]],f=e.clientKey?$w(e,Tt(e.clientKey),r,o):i,m=r&&o?"either family":r?"OpenAI":"Anthropic",h=[`${n} \u2190 managed Anyray block`,` ${u} added to PATH (so \`anyray-connect\` runs from a new shell)`,...f.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 ${m} \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 x(d),y=w?await Nw(d,"utf8"):void 0,g=y===void 0||Mw(y);if(c.length>0&&!g)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(g||h.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:h};try{c.length>0?await we(d,[Bw,...c,""].join(`
89
- `)):w&&g&&await Cp(d,{force:!0}),await Dc(n,p)}catch(b){try{y!==void 0&&g?await we(d,y):g&&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:h,changedFiles:[n,...c.length>0||w&&g?[d]:[]]}},async revert(e){let t=gt(),n=kp(),r=await x(n),o=r?Mw(await Nw(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 fs(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 $_}from"node:child_process";import{closeSync as M_,copyFileSync as B_,existsSync as Ce,mkdirSync as F_,openSync as W_,readFileSync as gb,readSync as H_,renameSync as U_,rmSync as rn,writeFileSync as Mp}from"node:fs";import{homedir as wb,platform as G_}from"node:os";import{dirname as bb,join as Mo,resolve as V_}from"node:path";import{isIP as _p}from"node:net";import{homedir as e_,platform as t_}from"node:os";import{join as $c}from"node:path";var Ve=e=>{let t=e_();switch(t_()){case"darwin":return $c(t,"Library","Application Support",e);case"win32":return $c(process.env.APPDATA??$c(t,"AppData","Roaming"),e);default:return $c(t,".config",e)}};import{execFileSync as Fc}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 Ww}from"node:path";var ms=class extends Error{},hs=e=>e instanceof ms?`: ${e.message}`:"",Hw=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new ms("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new ms(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},Uw=()=>{try{return Fc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Ip=64*1024*1024,i_=Ip*2+64,Bc=e=>`'${e.replace(/'/g,"''")}'`,c_=(e,t)=>Fc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:i_,stdio:["ignore","pipe","pipe"]}),l_=(e,t)=>Fc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Ip,stdio:["pipe","pipe","pipe"]}),Gw=(e,t,n=c_)=>{let r=Bc(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
86
+ `;return await Nw(e,c),e},Lc=async(e,t)=>{let n=await Pc(e),{begin:r,end:o}=ps(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(`
87
+ `).filter(c=>c.trim().length>0)},Mw=async(e,t)=>(await Pc(e)).includes(ps(t).begin),fs=async(e,t)=>{let n=await Pc(e);return n.includes(ps(t).begin)?(await Nw(e,$w(n,t).replace(/\s*$/,"")+`
88
+ `),!0):!1};var _t=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var ve=e=>`'${e.replace(/'/g,"'\\''")}'`,a_=e=>{let t=ve(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},Fw=(e,t,n,r)=>[`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${ve(t)}`],`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${ve(t)}`],...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"],Cp=()=>o_(r_(),".anyray","shell-env.sh"),Uw="# Managed by anyray-connect. Do not source this file anywhere else.",Ww=e=>e.split(/\r?\n/,1)[0]===Uw,kp=e=>i_.some(t=>e.startsWith(`export ${t}=`)),Nc=(e,t=process.env)=>t.ANTHROPIC_BASE_URL===e.anthropicBaseUrl||t.OPENAI_BASE_URL===e.openaiBaseUrl?s_.filter(r=>(t[r]??"")!==""):[],Hw={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=gt();return{installed:!0,detail:await x(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await Lc(gt());return e?e.some(n=>kp(n)||n.includes(Cp()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=gt(),r=ee(e,"openai"),o=ee(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=Fw(e,s,r,o),c=i.filter(kp),l=i.filter(b=>!kp(b)),d=Cp(),u=$g(),p=[a_(u),...l,...c.length>0?[`[ -r ${ve(d)} ] && . ${ve(d)}`]:[]],f=e.clientKey?Fw(e,_t(e.clientKey),r,o):i,m=r&&o?"either family":r?"OpenAI":"Anthropic",h=[`${n} \u2190 managed Anyray block`,` ${u} added to PATH (so \`anyray-connect\` runs from a new shell)`,...f.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 ${m} \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 x(d),y=w?await Bw(d,"utf8"):void 0,g=y===void 0||Ww(y);if(c.length>0&&!g)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(g||h.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:h};try{c.length>0?await we(d,[Uw,...c,""].join(`
89
+ `)):w&&g&&await Ap(d,{force:!0}),await Dc(n,p)}catch(b){try{y!==void 0&&g?await we(d,y):g&&await Ap(d,{force:!0})}catch{throw new Error("shell environment update failed and credential rollback could not be completed")}throw b}return{status:"configured",messages:h,changedFiles:[n,...c.length>0||w&&g?[d]:[]]}},async revert(e){let t=gt(),n=Cp(),r=await x(n),o=r?Ww(await Bw(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 fs(t);o&&await Ap(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 V_}from"node:child_process";import{closeSync as K_,copyFileSync as j_,existsSync as Ce,mkdirSync as Z_,openSync as Y_,readFileSync as Ab,readSync as J_,renameSync as X_,rmSync as rn,writeFileSync as $p}from"node:fs";import{homedir as Cb,platform as z_}from"node:os";import{dirname as kb,join as Mo,resolve as q_}from"node:path";import{isIP as Tp}from"node:net";import{homedir as c_,platform as l_}from"node:os";import{join as $c}from"node:path";var Ve=e=>{let t=c_();switch(l_()){case"darwin":return $c(t,"Library","Application Support",e);case"win32":return $c(process.env.APPDATA??$c(t,"AppData","Roaming"),e);default:return $c(t,".config",e)}};import{execFileSync as Fc}from"node:child_process";import{mkdtempSync as d_,rmSync as u_,writeFileSync as p_}from"node:fs";import{createRequire as f_}from"node:module";import{tmpdir as m_}from"node:os";import{join as Gw}from"node:path";var ms=class extends Error{},hs=e=>e instanceof ms?`: ${e.message}`:"",Vw=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new ms("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new ms(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},Kw=()=>{try{return Fc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Sp=64*1024*1024,h_=Sp*2+64,Bc=e=>`'${e.replace(/'/g,"''")}'`,y_=(e,t)=>Fc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:h_,stdio:["ignore","pipe","pipe"]}),g_=(e,t)=>Fc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Sp,stdio:["pipe","pipe","pipe"]}),jw=(e,t,n=y_)=>{let r=Bc(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
90
90
  `)?a.slice(0,-2):a.endsWith(`
91
- `)?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")},Vw=(e,t=l_)=>{let r=t(e,`.bail on
91
+ `)?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")},Zw=(e,t=g_)=>{let r=t(e,`.bail on
92
92
  .timeout 5000
93
93
  PRAGMA wal_checkpoint(TRUNCATE);
94
- `).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");Hw(o?.slice(1).map(Number))},d_=(e,t)=>{let n=n_(Ww(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=${Bc(a.key)};`;let i=Ww(n,`value-${s}`);return o_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${Bc(a.key)}, CAST(readfile(${Bc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
95
- `);Fc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Ip,stdio:["pipe","ignore","pipe"]})}finally{try{r_(n,{recursive:!0,force:!0})}catch{}}},u_={kind:"sqlite3-cli",readItem:(e,t)=>Gw(e,t),checkpointWal:e=>Vw(e),mutateRows:d_},p_=()=>{try{let t=a_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Sp=(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),m_=e=>({kind:"node-sqlite",readItem:(t,n)=>Sp(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=>Sp(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);Hw(o)}),mutateRows:(t,n)=>Sp(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}})}),Mc,Do=()=>{if(Mc!==void 0)return Mc;let e=p_();return Mc=e?m_(e):Uw()?u_:null,Mc};import{spawn as h_}from"node:child_process";import{randomUUID as Kw}from"node:crypto";import{constants as jw}from"node:fs";import{chmod as y_,copyFile as Zw,mkdir as g_,readdir as w_,readFile as b_,rename as A_,rm as ys,writeFile as C_}from"node:fs/promises";import{join as Ep}from"node:path";var xp=/^[a-z0-9][a-z0-9-]{0,31}$/,k_=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,Yw=/^[a-z0-9][a-z0-9-]{0,31}$/,v_=/^[0-9TZ:.+-]{1,40}$/,Rp=()=>Ep(Q(),"pending"),Hc=e=>{if(!xp.test(e)||k_.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Ep(Rp(),`${e}.json`)},Jw=()=>Ep(Q(),"cursor-pending.json"),S_=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),I_=(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"||!Yw.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}:{}}},Op=async(e,t)=>{try{return I_(JSON.parse(await b_(e,"utf-8")),t)}catch{return}},Xw=async()=>{let e=Jw(),t=await Op(e,"cursor");if(!t)return;let n=!1;try{await zw(),await Zw(e,Hc("cursor"),jw.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await ys(e,{force:!0})}catch{}return t},Uc=async e=>{let t=await Op(Hc(e),e);return t||(e==="cursor"?Xw():void 0)},rr=async()=>{let e;try{e=await w_(Rp())}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 Uc(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await Xw();n&&t.push(n)}return t},zw=async()=>{await tt();let e=Rp();await g_(e,{recursive:!0,mode:448});try{await y_(e,448)}catch{}},Wc=async e=>{await zw();let t=Hc(e.adapter),n=`${t}.${process.pid}.tmp`;await C_(n,`${JSON.stringify(e)}
96
- `,{mode:384}),await he(n,t)},E_=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,or=async(e,t)=>await Tp(e,t)==="claimed",Tp=async(e,t)=>{let n=Hc(e);if(t){let o=`${n}.${process.pid}.${Kw()}.claimed`;try{await A_(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Op(o,e);if(a&&E_(a,t))return await ys(o,{force:!0}),"claimed";let s=!1;try{await Zw(o,n,jw.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await ys(o,{force:!0})}return"superseded"}let r=!1;try{await ys(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await ys(Jw(),{force:!0})}catch{}return r?"claimed":"absent"},ar=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},x_=e=>{let{command:t,args:n}=Qn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},R_=e=>{let{exe:t,args:n}=x_(e),r=h_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},qw=R_;var Qw=async()=>{let e=[],t;try{t=await rr()}catch{return e}for(let n of t)if(!ar(n.watcherPid))try{let r=qw(n.adapter);if(!r)continue;await Wc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},gs=async(e,t)=>{if(!Yw.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await Uc(e),r=new Date().toISOString(),o=Kw();if(n&&ar(n.watcherPid))return await Wc({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await Wc({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=qw(e)}catch{a=void 0}return a&&await Wc({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as O_,spawnSync as tb}from"node:child_process";import{existsSync as Gc}from"node:fs";import{homedir as T_,platform as sr}from"node:os";import{join as nb,win32 as eb}from"node:path";var rb=(e,t={})=>{let n=t.env??process.env,r=t.exists??Gc,o=(t.home??T_)(),a={localAppData:n.LOCALAPPDATA??eb.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=eb.join(i,s.path);if(r(c))return c}},Vr=/^[A-Za-z0-9 ._-]{1,64}$/,__=/^[A-Za-z0-9.-]{1,128}$/,Vc=e=>e.darwinBundleId&&__.test(e.darwinBundleId)?e.darwinBundleId:void 0,ob=(e,t=sr())=>t==="darwin"?Vc(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",ab=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",sb=(e,t=sr(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return rb(e,r)!==void 0;let o=e.linuxProcess;return!o||!Vr.test(o)?!1:n.split(":").filter(Boolean).some(a=>Gc(nb(a,o)))},ib=(e,t=sr())=>{if(t==="darwin"&&Vc(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Vr.test(n))},cb=1e4,ws=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=nb(t,"System32",e);return Gc(n)?n:e},P_=e=>{let t=`/usr/bin/${e}`;return Gc(t)?t:e},D_=(e,t)=>{try{let n=tb(e,t,{encoding:"utf-8",timeout:cb,windowsHide:!0,...sr()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:sr()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},L_=e=>new Promise(t=>setTimeout(t,e)),lb=(e,t={})=>{let n=t.runtimePlatform??sr(),r=t.run??D_;if(n==="darwin"){let a=Vc(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(ws("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(P_("pkill"),["-TERM","-o","-x",o])},db=async(e,t=2e4,n={})=>{let r=n.sleep??L_,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=sr();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=tb(e,t,{stdio:"ignore",timeout:cb,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}},ub=(e,t={})=>{let n=t.runtimePlatform??sr(),r=t.launch??N_;if(n==="darwin"){let a=Vc(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=rb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(o,[])};var K_={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"}]},j_=e=>e==="apply"||e==="native"||e==="revert",Ab=()=>Ve("Cursor"),ir=()=>Mo(Ab(),"User","globalStorage","state.vscdb"),As=()=>`${ir()}.anyray-bak.json`,$o=()=>`${ir()}.anyray-bak`,Ke="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",at="cursorAuth/openAIKey";var Cb="/seat/cursor",Bp="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.",bs=Mo(".cursor","rules","anyray.mdc"),kb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",Z_=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",kb,"",Bp,""].join(`
97
- `),Y_=e=>{let t=V_(e);for(;;){if(Ce(Mo(t,".git")))return t;let n=bb(t);if(n===t)return null;t=n}},J_=e=>e.authMode!=="placeholder",on=()=>Mo(wb(),".cursor","hooks.json"),an=()=>Mo(wb(),".cursor","mcp.json"),_t="anyray",vb="--anyray-owner=cursor-v1",X_="postToolUse",z_="beforeSubmitPrompt",pb="preToolUse",q_="^MCP:",Q_="UserPromptSubmit",eP="Shell",tP="^(Read|Grep)$",Jc="--anyray-owner=cursor-hook-v1",Kr=[{event:X_,flag:ze,trailingArgs:["cursor"],matcher:q_},{event:z_,flag:Zn,trailingArgs:[],matcher:Q_},{event:pb,flag:$g,trailingArgs:[],matcher:eP},{event:pb,flag:Mg,trailingArgs:[],matcher:tP}];var fb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},nP=(e,t,n)=>$_(e,t,n),mb=nP,rP,oP=()=>{let e=rP??G_();if(e==="win32"){let t=mb(ws("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],fb);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=mb("pgrep",["-x",t],fb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},aP=oP,Zc=()=>aP();var sP=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Ke)??null,openAIKey:e.readItem(n,at)??null,lastWritten:r};Mp(t,`${JSON.stringify(o,null,2)}
98
- `,{encoding:"utf-8",flag:"wx",mode:384})},Sb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Mp(n,`${JSON.stringify(t,null,2)}
99
- `,{encoding:"utf-8",flag:"wx",mode:384});try{U_(n,e)}catch(r){throw rn(n,{force:!0}),r}},iP=(e,t)=>{let n=Lo(e);Sb(e,{...n,lastWritten:t})},ne=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),hb=e=>ne(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Lo=e=>{let t=gb(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[Ke],o=n.rows[at];if(!hb(r)||!hb(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}},yb=e=>{let t=Buffer.alloc(16),n=W_(e,"r");try{return H_(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{M_(n)}},cP=(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 Ib=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 Ib(`${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},Eb=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Ib(t.hostname)}catch{return!1}},lP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${Cb}`}catch{}return{...e,openaiBaseUrl:t}},No=["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."],Dp=()=>{let e=ir();if(!Ce(e))return"clear";let t=Do();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ke)}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"},dP=(e,t)=>{if(!Eb(e))return{routed:!1,problem:"gateway-not-public-https"};let n=ir();if(!Ce(n))return{routed:!1,problem:"state-db-missing"};let r=Do();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Ke),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=`${Ht(e)}/v1${Cb}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ee(a)||!Ee(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},uP=()=>{let e=ir();if(!Ce(e))return"unverifiable";let t=Do();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ke)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!ne(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},pP=(e,t=[])=>({command:Rt(e,[...t,Jc])}),Fp=(e,t,n)=>{if(!ne(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Rt(t,[...n,Jc])||r===Rt(t,n)||r.endsWith(` ${Jc}`)&&r.includes(` ${t} `)},fP=(e,t)=>ne(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),xb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Fp(a,t,n)){r=!0;continue}if(!ne(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!fP(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}},Wp=(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},Rb=(e,t,n,r,o)=>ne(e.hooks)&&Wp(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Fp(a,n,r)),mP=(e,t,n,r,o)=>ne(e.hooks)&&Wp(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Fp(a,n,r)&&nc(a.command,n,[...r,Jc])),Ob=(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}=xb(Wp(a,t),n,r);return s.push({...pP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},hP=(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}=xb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},yP=async()=>{let e=on();if(!ce()){let t=await _b();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 B(e);for(let n of Kr)t=Ob(t,n.event,n.flag,n.trailingArgs,n.matcher);return await Y(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}}},Yc=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,vb]}},Lp=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===Yc().command&&e.args.length===Yc().args.length&&e.args.every((t,n)=>t===Yc().args[n]),gP=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")||Ue(e.command))return!1;let t=e.args;if(t.at(-2)!==Jn||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!Ue(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},Xc=e=>ne(e)&&Array.isArray(e.args)&&e.args.at(-1)===vb||gP(e),wP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,bP=async()=>{if(!ce())return Tb();let e=an();try{let t=await B(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&&!Xc(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]=Yc(),await Y(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}}},Tb=async()=>{let e=an();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e);if(!ne(t.mcpServers)||!(_t in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!Xc(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 Y(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}}},_b=async()=>{let e=on();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e),n=t;for(let r of Kr)n=hP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await Y(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}}},AP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=Y_(e);if(!n)return t;let r=Mo(n,bs),o=Z_();try{if(Ce(r)){let a=gb(r,"utf8");if(a===o)return t;if(!a.includes(kb))return{...t,messages:[`Left ${bs} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Bp}"`]}}return F_(bb(r),{recursive:!0}),Mp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${bs} 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 ${bs} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Pb=async()=>{let e=await yP(),t=await bP(),n=await AP();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 _b(),t=await Tb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Db=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 B(on());for(let r of Kr)e=Ob(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await B(an());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&&!Xc(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${an()} 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 ${on()} and ${an()}, then re-run Connect.`],complete:!1}}},CP=async()=>{if(!ce())return!1;try{let e=await B(on());if(!ne(e.hooks)||!Kr.every(r=>Rb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await B(an()),n=ne(t.mcpServers)?t.mcpServers[_t]:void 0;return Lp(n)}catch{return!1}},Lb=["openAIBaseUrl","useOpenAIKey"],Cs=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},kP=(e,t,n)=>{let r=Cs(e),o=Cs(t??void 0),a=n===void 0?void 0:Cs(n),s={...r},i=[];for(let c of Lb){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:Ke}:{key:Ke,value:JSON.stringify(s)},conflicts:i}},Pp=(e,t)=>{let n=Cs(e),r=Cs(t??void 0),o={...n};for(let a of Lb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Ke}:{key:Ke,value:JSON.stringify(o)}},Kc=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=Kc(t)||n!==null&&(Kc(n.useOpenAIKey)||Kc(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,Kc(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.",...No];let n=ue(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.",...No]},$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 gs("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]}},vP=async(e,t)=>{if(!Ee(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 or("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 Db();if(!n.complete)return{status:"manual",messages:n.messages};let r=Ce(As())||Ce($o());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=Dp();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 ${Ce($o())?$o():As()}, 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 ${on()}, and register the Anyray retrieval MCP server in ${an()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await ks.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 Pb(),s=[];if(!t.preservePendingOp)try{await or("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 -- "${Bp}" (connect already writes ${bs} 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."]}},ks={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>Zc(),quitTarget:K_,needsTarget:e=>e!=="revert",async complete(e,t,n){return j_(e)?e!=="revert"&&t?ks.apply(t,n):ks.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=Ab(),t=Ce(e);return{installed:t,detail:t?ir():"Cursor user dir not found"}},async mcpStatus(){let e=an();if(!await x(e))return{registered:!1,command:null};try{let t=await B(e),n=ne(t.mcpServers)?t.mcpServers[_t]:void 0;return Lp(n)?{registered:!0,command:wP(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=on();if(!await x(n))e="missing";else try{let s=await B(n);if(s.hooks===void 0)e="missing";else if(!ne(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Kr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Kr.every(c=>Rb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Kr.every(c=>mP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=an();if(!await x(a))r="missing";else try{let s=await B(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":Xc(i)?"owned":"foreign",r==="owned"&&(o=Lp(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 D();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(J_(e))return vP(e,t);let n=lP(e),r=ir(),o=As(),a=$o();if(!Ee(e.clientKey))return{status:"manual",messages:ot(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let s={changedFiles:[],messages:[],complete:!0},i=y=>{let g=y.status==="configured"&&!s.complete;return{...y,status:g?"manual":y.status,changedFiles:[...y.changedFiles??[],...s.changedFiles],messages:[...y.messages,...s.messages,...g?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Eb(n.openaiBaseUrl))return i({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 private or LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect.",...No]});let c=await Db();if(!c.complete)return{status:"manual",messages:c.messages};let l=Do();if(!l)return i({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(!Ce(r))return i({status:"manual",messages:ot(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Ce(a)){if(Ce(o))return i({status:"manual",messages:ot(n,`Both a legacy Cursor Anyray backup (${a}) and a current value backup (${o}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{yb(a)?d="sqlite":(Lo(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:ot(n,`Legacy Cursor Anyray backup at ${a} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(Ce(o))try{p=Lo(o)}catch{return i({status:"manual",messages:ot(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(Zc())return i(await $p("apply",t,{status:"manual",messages:ot(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...No,...d?[`The legacy Anyray backup at ${a} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...d?[`Would migrate the legacy Anyray backup at ${a}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${r}, ${Ce(o)?`retain the original value backup at ${o}`:`create a mode-0600 value backup at ${o}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${on()}, and register the Anyray retrieval MCP server in ${an()}.`,...No]};if(d){try{l.checkpointWal(r)}catch(g){return i({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${hs(g)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=jc(l.readItem(a,Ke)??null,l.readItem(a,at)??null);else{let g=Lo(a);y=jc(g.applicationUser,g.openAIKey)}}catch{return i({status:"manual",messages:ot(n,`Couldn't read the legacy Anyray backup at ${a} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{l.mutateRows(r,[Pp(l.readItem(r,Ke),y.applicationUser),y.openAIKey===null?{key:at}:{key:at,value:y.openAIKey}])}catch{return i({status:"manual",messages:ot(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${a} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{rn(a,{force:!0}),rn(`${a}-wal`,{force:!0}),rn(`${a}-shm`,{force:!0}),u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held and removed it.`}catch{u=`Migrated the legacy Anyray backup at ${a}: 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{l.checkpointWal(r)}catch(y){return i({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${r}${hs(y)} \u2014 refusing to write; set it by hand:`)})}let f;try{f=l.readItem(r,Ke)}catch{return i({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=cP(f,n);if(!m)return i({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 h={applicationUser:m.value,openAIKey:e.clientKey};if(Ce(o))try{iP(o,h)}catch{return i({status:"manual",messages:ot(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{sP(l,o,r,h)}catch{return i({status:"manual",messages:ot(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:Ke,value:m.value},{key:at,value:e.clientKey}])}catch{let y=!0;if(p)try{Sb(o,p)}catch{y=!1}return i({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 ${o}. 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 ${o} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}s=await Pb();let w=[];if(!t.preservePendingOp)try{await or("cursor")}catch{w.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return i({status:"configured",changedFiles:[r],messages:[...u?[u]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${o}).`,"Stored the API key in Cursor's credential row (not shown here).",...w,...No,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await D().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Ce(As())||Ce($o())||Dp()!=="clear"?!1:CP():dP(e,n).routed},async routingOverrides(){return Dp()!=="active"?[]:uP()!=="none"?[]:[{problem:"no custom model is registered against Cursor\u2019s API-key lane, so every model in the picker still runs on Cursor-hosted inference and no request reaches the gateway",fix:"Cursor \u2192 Settings \u2192 Models: add a custom model named `anyray-default` (or an admin-registered alias) and enable it, quit Cursor fully, reopen, then select it in Ask, Plan, or Agent.",repairable:!1}]},async revert(e){let t=ir(),n=As(),r=$o(),o=Ce(n),a=Ce(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 ${on()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${on()} and unregister its owned retrieval MCP server.`]};if((o||a)&&Zc()){if(e.fullRevert){let m=await Np(),h=!0;try{await or("cursor")}catch{h=!1}return{status:"manual",changedFiles:m.changedFiles,messages:[...m.messages,...h?[]:["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=Do(),i=!1,c=!1,l,d=[];if(a)try{if(yb(r))if(Ce(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 m=jc(s.readItem(r,Ke)??null,s.readItem(r,at)??null);s.mutateRows(t,[Pp(s.readItem(t,Ke),m.applicationUser),m.openAIKey===null?{key:at}:{key:at,value:m.openAIKey}]),c=!0}else i=!0,B_(r,t),rn(`${t}-wal`,{force:!0}),rn(`${t}-shm`,{force:!0});else{let m=Lo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ce(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 h=jc(m.applicationUser,m.openAIKey);s.mutateRows(t,[Pp(s.readItem(t,Ke),h.applicationUser),h.openAIKey===null?{key:at}:{key:at,value:h.openAIKey}]),c=!0}}catch(m){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${hs(m)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Lo(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(!Ce(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 m=kP(s.readItem(t,Ke),l.applicationUser,l.lastWritten?.applicationUser);d.push(...m.conflicts);let h=[m.mutation],w=s.readItem(t,at);l.lastWritten&&w===l.lastWritten.openAIKey?h.push(l.openAIKey===null?{key:at}:{key:at,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,h)}catch(m){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${hs(m)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],p=!0;try{rn(r,{force:!0}),rn(`${r}-wal`,{force:!0}),rn(`${r}-shm`,{force:!0}),rn(n,{force:!0})}catch{p=!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 or("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let f=await Np();return p=p&&f.complete,{status:p?"reverted":"manual",changedFiles:[...o||a?[t]:[],...f.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(", ")}.`]:[],...f.messages,"Restart Cursor."]}}};import{chmod as ED,mkdir as xD,readFile as bA,rm as RD,writeFile as OD}from"node:fs/promises";import{randomUUID as TD}from"node:crypto";import{dirname as _D,join as AA}from"node:path";import{constants as EP,chmod as xP,copyFile as RP,readFile as Nb}from"node:fs/promises";import{applyEdits as OP,modify as TP}from"jsonc-parser";var SP=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]!==`
100
- `;)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},IP=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},wt=e=>JSON.parse(IP(SP(e)));var zc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),je=async e=>{let t=await x(e),n=t?await Nb(e,"utf8"):`{}
101
- `,r=n.trim()?wt(n):{};if(!zc(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},$b=(e,t,n=[])=>{if(zc(e)&&zc(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...$b(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}]},sn=async(e,t,n,r)=>{let o=$b(t.data,n);if(o.length===0)return!1;if(r&&!await x(`${e}.anyray-bak`))if(t.existed)try{await RP(e,`${e}.anyray-bak`,EP.COPYFILE_EXCL),await xP(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await we(`${e}.anyray-bak`,`{}
94
+ `).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");Vw(o?.slice(1).map(Number))},w_=(e,t)=>{let n=d_(Gw(m_(),"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=${Bc(a.key)};`;let i=Gw(n,`value-${s}`);return p_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${Bc(a.key)}, CAST(readfile(${Bc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
95
+ `);Fc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Sp,stdio:["pipe","ignore","pipe"]})}finally{try{u_(n,{recursive:!0,force:!0})}catch{}}},b_={kind:"sqlite3-cli",readItem:(e,t)=>jw(e,t),checkpointWal:e=>Zw(e),mutateRows:w_},A_=()=>{try{let t=f_(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{}}},C_=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)=>vp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:C_(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);Vw(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}})}),Mc,Do=()=>{if(Mc!==void 0)return Mc;let e=A_();return Mc=e?k_(e):Kw()?b_:null,Mc};import{spawn as v_}from"node:child_process";import{randomUUID as Yw}from"node:crypto";import{constants as Jw}from"node:fs";import{chmod as S_,copyFile as Xw,mkdir as I_,readdir as E_,readFile as x_,rename as R_,rm as ys,writeFile as O_}from"node:fs/promises";import{join as Ip}from"node:path";var Ep=/^[a-z0-9][a-z0-9-]{0,31}$/,T_=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,zw=/^[a-z0-9][a-z0-9-]{0,31}$/,__=/^[0-9TZ:.+-]{1,40}$/,xp=()=>Ip(Q(),"pending"),Uc=e=>{if(!Ep.test(e)||T_.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Ip(xp(),`${e}.json`)},qw=()=>Ip(Q(),"cursor-pending.json"),P_=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),D_=(e,t)=>{if(!P_(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Ep.test(n)||typeof e.op!="string"||!zw.test(e.op)||typeof e.requestedAt!="string"||!__.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 D_(JSON.parse(await x_(e,"utf-8")),t)}catch{return}},Qw=async()=>{let e=qw(),t=await Rp(e,"cursor");if(!t)return;let n=!1;try{await eb(),await Xw(e,Uc("cursor"),Jw.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await ys(e,{force:!0})}catch{}return t},Hc=async e=>{let t=await Rp(Uc(e),e);return t||(e==="cursor"?Qw():void 0)},or=async()=>{let e;try{e=await E_(xp())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Ep.test(r))continue;let o=await Hc(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await Qw();n&&t.push(n)}return t},eb=async()=>{await tt();let e=xp();await I_(e,{recursive:!0,mode:448});try{await S_(e,448)}catch{}},Wc=async e=>{await eb();let t=Uc(e.adapter),n=`${t}.${process.pid}.tmp`;await O_(n,`${JSON.stringify(e)}
96
+ `,{mode:384}),await he(n,t)},L_=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,ar=async(e,t)=>await Op(e,t)==="claimed",Op=async(e,t)=>{let n=Uc(e);if(t){let o=`${n}.${process.pid}.${Yw()}.claimed`;try{await R_(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&&L_(a,t))return await ys(o,{force:!0}),"claimed";let s=!1;try{await Xw(o,n,Jw.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await ys(o,{force:!0})}return"superseded"}let r=!1;try{await ys(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await ys(qw(),{force:!0})}catch{}return r?"claimed":"absent"},sr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},N_=e=>{let{command:t,args:n}=er("__anyray-quit-watch");return{exe:t,args:[...n,e]}},$_=e=>{let{exe:t,args:n}=N_(e),r=v_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},tb=$_;var nb=async()=>{let e=[],t;try{t=await or()}catch{return e}for(let n of t)if(!sr(n.watcherPid))try{let r=tb(n.adapter);if(!r)continue;await Wc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},gs=async(e,t)=>{if(!zw.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await Hc(e),r=new Date().toISOString(),o=Yw();if(n&&sr(n.watcherPid))return await Wc({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await Wc({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=tb(e)}catch{a=void 0}return a&&await Wc({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as M_,spawnSync as ob}from"node:child_process";import{existsSync as Gc}from"node:fs";import{homedir as B_,platform as ir}from"node:os";import{join as ab,win32 as rb}from"node:path";var sb=(e,t={})=>{let n=t.env??process.env,r=t.exists??Gc,o=(t.home??B_)(),a={localAppData:n.LOCALAPPDATA??rb.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=rb.join(i,s.path);if(r(c))return c}},Vr=/^[A-Za-z0-9 ._-]{1,64}$/,F_=/^[A-Za-z0-9.-]{1,128}$/,Vc=e=>e.darwinBundleId&&F_.test(e.darwinBundleId)?e.darwinBundleId:void 0,ib=(e,t=ir())=>t==="darwin"?Vc(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",cb=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",lb=(e,t=ir(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return sb(e,r)!==void 0;let o=e.linuxProcess;return!o||!Vr.test(o)?!1:n.split(":").filter(Boolean).some(a=>Gc(ab(a,o)))},db=(e,t=ir())=>{if(t==="darwin"&&Vc(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Vr.test(n))},ub=1e4,ws=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=ab(t,"System32",e);return Gc(n)?n:e},W_=e=>{let t=`/usr/bin/${e}`;return Gc(t)?t:e},U_=(e,t)=>{try{let n=ob(e,t,{encoding:"utf-8",timeout:ub,windowsHide:!0,...ir()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:ir()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},H_=e=>new Promise(t=>setTimeout(t,e)),pb=(e,t={})=>{let n=t.runtimePlatform??ir(),r=t.run??U_;if(n==="darwin"){let a=Vc(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(ws("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(W_("pkill"),["-TERM","-o","-x",o])},fb=async(e,t=2e4,n={})=>{let r=n.sleep??H_,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},G_=(e,t,n={})=>{let r=ir();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=ob(e,t,{stdio:"ignore",timeout:ub,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=M_(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},mb=(e,t={})=>{let n=t.runtimePlatform??ir(),r=t.launch??G_;if(n==="darwin"){let a=Vc(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=sb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(o,[])};var Q_={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"}]},eP=e=>e==="apply"||e==="native"||e==="revert",vb=()=>Ve("Cursor"),cr=()=>Mo(vb(),"User","globalStorage","state.vscdb"),As=()=>`${cr()}.anyray-bak.json`,$o=()=>`${cr()}.anyray-bak`,Ke="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",at="cursorAuth/openAIKey";var Sb="/seat/cursor",Mp="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.",bs=Mo(".cursor","rules","anyray.mdc"),Ib="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",tP=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",Ib,"",Mp,""].join(`
97
+ `),nP=e=>{let t=q_(e);for(;;){if(Ce(Mo(t,".git")))return t;let n=kb(t);if(n===t)return null;t=n}},rP=e=>e.authMode!=="placeholder",on=()=>Mo(Cb(),".cursor","hooks.json"),an=()=>Mo(Cb(),".cursor","mcp.json"),Pt="anyray",Eb="--anyray-owner=cursor-v1",oP="postToolUse",aP="beforeSubmitPrompt",hb="preToolUse",sP="^MCP:",iP="UserPromptSubmit",cP="Shell",lP="^(Read|Grep)$",Jc="--anyray-owner=cursor-hook-v1",Kr=[{event:oP,flag:ze,trailingArgs:["cursor"],matcher:sP},{event:aP,flag:Yn,trailingArgs:[],matcher:iP},{event:hb,flag:Fg,trailingArgs:[],matcher:cP},{event:hb,flag:Wg,trailingArgs:[],matcher:lP}];var yb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},dP=(e,t,n)=>V_(e,t,n),gb=dP,uP,pP=()=>{let e=uP??z_();if(e==="win32"){let t=gb(ws("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],yb);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=gb("pgrep",["-x",t],yb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},fP=pP,Zc=()=>fP();var mP=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Ke)??null,openAIKey:e.readItem(n,at)??null,lastWritten:r};$p(t,`${JSON.stringify(o,null,2)}
98
+ `,{encoding:"utf-8",flag:"wx",mode:384})},xb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;$p(n,`${JSON.stringify(t,null,2)}
99
+ `,{encoding:"utf-8",flag:"wx",mode:384});try{X_(n,e)}catch(r){throw rn(n,{force:!0}),r}},hP=(e,t)=>{let n=Lo(e);xb(e,{...n,lastWritten:t})},re=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wb=e=>re(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Lo=e=>{let t=Ab(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(re(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||re(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(!re(n)||n.version!==1||!re(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Ke],o=n.rows[at];if(!wb(r)||!wb(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}},bb=e=>{let t=Buffer.alloc(16),n=Y_(e,"r");try{return J_(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{K_(n)}},yP=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return re(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Rb=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(".")&&Tp(t)===0||t==="0.0.0.0")return!0;if(Tp(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(Tp(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 Rb(`${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},Ob=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Rb(t.hostname)}catch{return!1}},gP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${Sb}`}catch{}return{...e,openaiBaseUrl:t}},No=["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."],Pp=()=>{let e=cr();if(!Ce(e))return"clear";let t=Do();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ke)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return re(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},wP=(e,t)=>{if(!Ob(e))return{routed:!1,problem:"gateway-not-public-https"};let n=cr();if(!Ce(n))return{routed:!1,problem:"state-db-missing"};let r=Do();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Ke),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(!re(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ht(e)}/v1${Sb}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ee(a)||!Ee(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},bP=()=>{let e=cr();if(!Ce(e))return"unverifiable";let t=Do();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ke)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!re(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},AP=(e,t=[])=>({command:Rt(e,[...t,Jc])}),Bp=(e,t,n)=>{if(!re(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Rt(t,[...n,Jc])||r===Rt(t,n)||r.endsWith(` ${Jc}`)&&r.includes(` ${t} `)},CP=(e,t)=>re(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Tb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Bp(a,t,n)){r=!0;continue}if(!re(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!CP(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}},Fp=(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},_b=(e,t,n,r,o)=>re(e.hooks)&&Fp(e.hooks,t).some(a=>re(a)&&a.matcher===o&&Bp(a,n,r)),kP=(e,t,n,r,o)=>re(e.hooks)&&Fp(e.hooks,t).some(a=>re(a)&&a.matcher===o&&Bp(a,n,r)&&nc(a.command,n,[...r,Jc])),Pb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!re(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=re(e.hooks)?{...e.hooks}:{},{entries:s}=Tb(Fp(a,t),n,r);return s.push({...AP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},vP=(e,t,n,r=[])=>{if(!re(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Tb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},SP=async()=>{let e=on();if(!te()){let t=await Lb();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 Kr)t=Pb(t,n.event,n.flag,n.trailingArgs,n.matcher);return await Y(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}}},Yc=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,Eb]}},Dp=e=>re(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===Yc().command&&e.args.length===Yc().args.length&&e.args.every((t,n)=>t===Yc().args[n]),IP=e=>{if(!re(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")||He(e.command))return!1;let t=e.args;if(t.at(-2)!==Xn||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!He(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},Xc=e=>re(e)&&Array.isArray(e.args)&&e.args.at(-1)===Eb||IP(e),EP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,xP=async()=>{if(!te())return Db();let e=an();try{let t=await M(e);if(t.mcpServers!==void 0&&!re(t.mcpServers))throw new Error("mcpServers is not an object");let n=re(t.mcpServers)?{...t.mcpServers}:{},r=n[Pt];return r!==void 0&&!Xc(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Pt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Pt]=Yc(),await Y(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}}},Db=async()=>{let e=an();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!re(t.mcpServers)||!(Pt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!Xc(t.mcpServers[Pt]))return{changedFiles:[],messages:[`Preserved the foreign ${Pt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Pt];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await Y(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}}},Lb=async()=>{let e=on();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e),n=t;for(let r of Kr)n=vP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await Y(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}}},RP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=nP(e);if(!n)return t;let r=Mo(n,bs),o=tP();try{if(Ce(r)){let a=Ab(r,"utf8");if(a===o)return t;if(!a.includes(Ib))return{...t,messages:[`Left ${bs} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Mp}"`]}}return Z_(kb(r),{recursive:!0}),$p(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${bs} 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 ${bs} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Nb=async()=>{let e=await SP(),t=await xP(),n=await RP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Lp=async()=>{let e=await Lb(),t=await Db();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},$b=async()=>{if(!te()){let e=await Lp();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(on());for(let r of Kr)e=Pb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(an());if(t.mcpServers!==void 0&&!re(t.mcpServers))throw new Error("mcpServers is not an object");let n=re(t.mcpServers)?t.mcpServers[Pt]:void 0;return n!==void 0&&!Xc(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${an()} already contains a foreign ${Pt} 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 ${on()} and ${an()}, then re-run Connect.`],complete:!1}}},OP=async()=>{if(!te())return!1;try{let e=await M(on());if(!re(e.hooks)||!Kr.every(r=>_b(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(an()),n=re(t.mcpServers)?t.mcpServers[Pt]:void 0;return Dp(n)}catch{return!1}},Mb=["openAIBaseUrl","useOpenAIKey"],Cs=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!re(t))throw new Error("Cursor application-user settings are not an object");return t},TP=(e,t,n)=>{let r=Cs(e),o=Cs(t??void 0),a=n===void 0?void 0:Cs(n),s={...r},i=[];for(let c of Mb){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:Ke}:{key:Ke,value:JSON.stringify(s)},conflicts:i}},_p=(e,t)=>{let n=Cs(e),r=Cs(t??void 0),o={...n};for(let a of Mb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Ke}:{key:Ke,value:JSON.stringify(o)}},Kc=e=>typeof e=="string"&&e.startsWith("ark_"),jc=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);re(o)&&(n=o)}catch{}let r=Kc(t)||n!==null&&(Kc(n.useOpenAIKey)||Kc(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,Kc(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.",...No];let n=ue(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.",...No]},Np=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!te())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 gs("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]}},_P=async(e,t)=>{if(!Ee(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 ar("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=Ce(As())||Ce($o());if(r&&Zc())return Np("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=Pp();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 ${Ce($o())?$o():As()}, 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 ${on()}, and register the Anyray retrieval MCP server in ${an()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await ks.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 Nb(),s=[];if(!t.preservePendingOp)try{await ar("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 -- "${Mp}" (connect already writes ${bs} 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."]}},ks={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>Zc(),quitTarget:Q_,needsTarget:e=>e!=="revert",async complete(e,t,n){return eP(e)?e!=="revert"&&t?ks.apply(t,n):ks.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=vb(),t=Ce(e);return{installed:t,detail:t?cr():"Cursor user dir not found"}},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=an();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await M(e),n=re(t.mcpServers)?t.mcpServers[Pt]:void 0;return Dp(n)?{registered:!0,command:EP(n)}:{registered:!1,command:null,reason:n===void 0?"absent":"foreign"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=on();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!re(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Kr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Kr.every(c=>_b(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Kr.every(c=>kP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=an();if(!await x(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!re(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Pt];r=i===void 0?"missing":Xc(i)?"owned":"foreign",r==="owned"&&(o=Dp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await $r()?"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(rP(e))return _P(e,t);let n=gP(e),r=cr(),o=As(),a=$o();if(!Ee(e.clientKey))return{status:"manual",messages:ot(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let s={changedFiles:[],messages:[],complete:!0},i=y=>{let g=y.status==="configured"&&!s.complete;return{...y,status:g?"manual":y.status,changedFiles:[...y.changedFiles??[],...s.changedFiles],messages:[...y.messages,...s.messages,...g?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Ob(n.openaiBaseUrl))return i({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 private or LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect.",...No]});let c=await $b();if(!c.complete)return{status:"manual",messages:c.messages};let l=Do();if(!l)return i({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(!Ce(r))return i({status:"manual",messages:ot(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Ce(a)){if(Ce(o))return i({status:"manual",messages:ot(n,`Both a legacy Cursor Anyray backup (${a}) and a current value backup (${o}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{bb(a)?d="sqlite":(Lo(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:ot(n,`Legacy Cursor Anyray backup at ${a} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(Ce(o))try{p=Lo(o)}catch{return i({status:"manual",messages:ot(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(Zc())return i(await Np("apply",t,{status:"manual",messages:ot(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...No,...d?[`The legacy Anyray backup at ${a} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...d?[`Would migrate the legacy Anyray backup at ${a}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${r}, ${Ce(o)?`retain the original value backup at ${o}`:`create a mode-0600 value backup at ${o}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${on()}, and register the Anyray retrieval MCP server in ${an()}.`,...No]};if(d){try{l.checkpointWal(r)}catch(g){return i({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${hs(g)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=jc(l.readItem(a,Ke)??null,l.readItem(a,at)??null);else{let g=Lo(a);y=jc(g.applicationUser,g.openAIKey)}}catch{return i({status:"manual",messages:ot(n,`Couldn't read the legacy Anyray backup at ${a} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{l.mutateRows(r,[_p(l.readItem(r,Ke),y.applicationUser),y.openAIKey===null?{key:at}:{key:at,value:y.openAIKey}])}catch{return i({status:"manual",messages:ot(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${a} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{rn(a,{force:!0}),rn(`${a}-wal`,{force:!0}),rn(`${a}-shm`,{force:!0}),u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held and removed it.`}catch{u=`Migrated the legacy Anyray backup at ${a}: 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{l.checkpointWal(r)}catch(y){return i({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${r}${hs(y)} \u2014 refusing to write; set it by hand:`)})}let f;try{f=l.readItem(r,Ke)}catch{return i({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=yP(f,n);if(!m)return i({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 h={applicationUser:m.value,openAIKey:e.clientKey};if(Ce(o))try{hP(o,h)}catch{return i({status:"manual",messages:ot(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{mP(l,o,r,h)}catch{return i({status:"manual",messages:ot(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:Ke,value:m.value},{key:at,value:e.clientKey}])}catch{let y=!0;if(p)try{xb(o,p)}catch{y=!1}return i({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 ${o}. 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 ${o} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}s=await Nb();let w=[];if(!t.preservePendingOp)try{await ar("cursor")}catch{w.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return i({status:"configured",changedFiles:[r],messages:[...u?[u]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${o}).`,"Stored the API key in Cursor's credential row (not shown here).",...w,...No,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await P().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Ce(As())||Ce($o())||Pp()!=="clear"?!1:OP():wP(e,n).routed},async routingOverrides(){return Pp()!=="active"?[]:bP()!=="none"?[]:[{problem:"no custom model is registered against Cursor\u2019s API-key lane, so every model in the picker still runs on Cursor-hosted inference and no request reaches the gateway",fix:"Cursor \u2192 Settings \u2192 Models: add a custom model named `anyray-default` (or an admin-registered alias) and enable it, quit Cursor fully, reopen, then select it in Ask, Plan, or Agent.",repairable:!1}]},async revert(e){let t=cr(),n=As(),r=$o(),o=Ce(n),a=Ce(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 ${on()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${on()} and unregister its owned retrieval MCP server.`]};if((o||a)&&Zc()){if(e.fullRevert){let m=await Lp(),h=!0;try{await ar("cursor")}catch{h=!1}return{status:"manual",changedFiles:m.changedFiles,messages:[...m.messages,...h?[]:["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 Np("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Do(),i=!1,c=!1,l,d=[];if(a)try{if(bb(r))if(Ce(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 m=jc(s.readItem(r,Ke)??null,s.readItem(r,at)??null);s.mutateRows(t,[_p(s.readItem(t,Ke),m.applicationUser),m.openAIKey===null?{key:at}:{key:at,value:m.openAIKey}]),c=!0}else i=!0,j_(r,t),rn(`${t}-wal`,{force:!0}),rn(`${t}-shm`,{force:!0});else{let m=Lo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ce(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 h=jc(m.applicationUser,m.openAIKey);s.mutateRows(t,[_p(s.readItem(t,Ke),h.applicationUser),h.openAIKey===null?{key:at}:{key:at,value:h.openAIKey}]),c=!0}}catch(m){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${hs(m)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Lo(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(!Ce(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 m=TP(s.readItem(t,Ke),l.applicationUser,l.lastWritten?.applicationUser);d.push(...m.conflicts);let h=[m.mutation],w=s.readItem(t,at);l.lastWritten&&w===l.lastWritten.openAIKey?h.push(l.openAIKey===null?{key:at}:{key:at,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,h)}catch(m){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${hs(m)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],p=!0;try{rn(r,{force:!0}),rn(`${r}-wal`,{force:!0}),rn(`${r}-shm`,{force:!0}),rn(n,{force:!0})}catch{p=!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 ar("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let f=await Lp();return p=p&&f.complete,{status:p?"reverted":"manual",changedFiles:[...o||a?[t]:[],...f.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(", ")}.`]:[],...f.messages,"Restart Cursor."]}}};import{chmod as LD,mkdir as ND,readFile as kA,rm as $D,writeFile as MD}from"node:fs/promises";import{randomUUID as BD}from"node:crypto";import{dirname as FD,join as vA}from"node:path";import{constants as LP,chmod as NP,copyFile as $P,readFile as Bb}from"node:fs/promises";import{applyEdits as MP,modify as BP}from"jsonc-parser";var PP=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]!==`
100
+ `;)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},DP=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},wt=e=>JSON.parse(DP(PP(e)));var zc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),je=async e=>{let t=await x(e),n=t?await Bb(e,"utf8"):`{}
101
+ `,r=n.trim()?wt(n):{};if(!zc(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},Fb=(e,t,n=[])=>{if(zc(e)&&zc(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...Fb(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}]},sn=async(e,t,n,r)=>{let o=Fb(t.data,n);if(o.length===0)return!1;if(r&&!await x(`${e}.anyray-bak`))if(t.existed)try{await $P(e,`${e}.anyray-bak`,LP.COPYFILE_EXCL),await NP(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await we(`${e}.anyray-bak`,`{}
102
102
  `);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
103
103
  `)?`\r
104
104
  `:`
105
- `},s=t.raw;for(let i of o)s=OP(s,TP(s,i.path,i.value,{formattingOptions:a}));return await we(e,s.endsWith(`
105
+ `},s=t.raw;for(let i of o)s=MP(s,BP(s,i.path,i.value,{formattingOptions:a}));return await we(e,s.endsWith(`
106
106
  `)?s:`${s}
107
- `),!0},Bo=async e=>{try{let t=wt(await Nb(`${e}.anyray-bak`,"utf8"));return zc(t)?t:void 0}catch{return}};import{readFile as mD,writeFile as hD}from"node:fs/promises";import{dirname as yD,join as gD}from"node:path";import{mkdir as wD}from"node:fs/promises";var Mb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_P=e=>{let t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t+=1;continue}if(n==="/"&&e[t+1]==="/"){for(;t<e.length&&e[t]!==`
108
- `;)t+=1;continue}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);if(r===-1)return-1;t=r+2;continue}return n==="{"?t:-1}return-1},PP=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},DP=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},Hp=(e,t,n)=>{let r;try{r=wt(e)}catch{return{ok:!1,reason:"unsupported"}}if(!Mb(r))return{ok:!1,reason:"unsupported"};if(t in r)return{ok:!1,reason:"key-present"};let o=_P(e);if(o===-1)return{ok:!1,reason:"unsupported"};let a=PP(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=DP(e,o)?`
107
+ `),!0},Bo=async e=>{try{let t=wt(await Bb(`${e}.anyray-bak`,"utf8"));return zc(t)?t:void 0}catch{return}};import{readFile as kD,writeFile as vD}from"node:fs/promises";import{dirname as SD,join as ID}from"node:path";import{mkdir as ED}from"node:fs/promises";var Wb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),FP=e=>{let t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t+=1;continue}if(n==="/"&&e[t+1]==="/"){for(;t<e.length&&e[t]!==`
108
+ `;)t+=1;continue}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);if(r===-1)return-1;t=r+2;continue}return n==="{"?t:-1}return-1},WP=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},UP=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},Wp=(e,t,n)=>{let r;try{r=wt(e)}catch{return{ok:!1,reason:"unsupported"}}if(!Wb(r))return{ok:!1,reason:"unsupported"};if(t in r)return{ok:!1,reason:"key-present"};let o=FP(e);if(o===-1)return{ok:!1,reason:"unsupported"};let a=WP(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=UP(e,o)?`
109
109
  ${a}${s}
110
110
  `:`
111
- ${a}${s},`,d=`${i}${l}${c}`;try{let u=wt(d);if(!Mb(u))return{ok:!1,reason:"unsupported"};for(let[p,f]of Object.entries(r))if(JSON.stringify(u[p])!==JSON.stringify(f))return{ok:!1,reason:"unsupported"};if(JSON.stringify(u[t])!==JSON.stringify(n))return{ok:!1,reason:"unsupported"}}catch{return{ok:!1,reason:"unsupported"}}return{ok:!0,text:d}};import{execFile as WP}from"node:child_process";import{readdirSync as HP,statSync as UP}from"node:fs";import{createHash as Qb,randomBytes as GP,randomUUID as eA}from"node:crypto";import{chmod as VP,lstat as Jp,mkdir as Xp,readdir as tA,readFile as ln,rm as nA,unlink as el,writeFile as zp}from"node:fs/promises";import{homedir as Uo,platform as qp}from"node:os";import{dirname as jp,join as bt,posix as Xb,win32 as KP}from"node:path";import{promisify as jP}from"node:util";var cn="0.1.29";var cr="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",qc="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",Bb="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz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IEbHgAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAHAAcA1gEAAGdXAAAAAA==";import{readFile as Hb}from"node:fs/promises";import{homedir as jr,platform as Fo}from"node:os";import{join as En,posix as LP,win32 as NP}from"node:path";var vs=["Code","Code - Insiders","VSCodium"],Up="1.121.0",Fb=1,$P=121,Ub="1.102.0",Wb=1,MP=102,BP={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Qc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},Gp=e=>{let t=Qc(e);return t?t.major!==Fb?t.major>Fb:t.minor>=$P:!1},Gb=e=>{let t=Qc(e);return t?t.major!==Wb?t.major>Wb:t.minor>=MP:!1},FP=async e=>{if(Fo()!=="darwin")return;let t=En("/Applications",`${BP[e]}.app`,"Contents","Resources","app","package.json");if(await x(t))try{let n=JSON.parse(await Hb(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Vb=(e,t=Fo(),n=jr(),r=process.env)=>{switch(t){case"darwin":return En(n,"Library","Application Support",e);case"win32":return En(r.APPDATA??En(n,"AppData","Roaming"),e);default:return En(n,".config",e)}},Vp=(e,t)=>e?t==="win32"?NP.join:LP.join:En,Wo=(e,t=!1,n=Fo(),r=jr(),o=process.env)=>t?Vp(t,n)(r,Ss[e],"data","User"):En(Vb(e,n,r,o),"User"),Kb=async(e,t=!1,n=Fo(),r=jr(),o=process.env)=>{try{let a=Vp(t,n)(Wo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Hb(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[]}},jb=async(e,t=Fo(),n=jr(),r=process.env)=>{let a=(await Kb(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},Zb=async(e,t=!1,n=Fo(),r=jr(),o=process.env)=>{let a=Vp(t,n),s=Wo(e,t,n,r,o),i=await Kb(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Ho=async()=>{for(let e of vs)if(await x(Vb(e)))return e},Ss={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Yb=(e,t=jr())=>En(t,Ss[e],"extensions"),Kp=async(e=jr())=>{for(let t of vs)if(await x(En(e,Ss[t])))return t},Jb=async e=>{let t=e??await Ho();if(!t)return{status:"unknown"};let n=await FP(t);return n?{variant:t,version:n,status:Gp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var z="anyray.anyray-vscode",Qp="vscode-handoffs",rA="vscode-receipts",Is=2,ZP=jP(WP),xn={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"]}},YP={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"}},JP=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),oA=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&JP(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Es=e=>{if(oA(e))try{return new URL(e.trim()).origin}catch{return}},XP=(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)},zP=e=>{try{return HP(e)}catch{return[]}},qP=e=>{try{return UP(e).mtimeMs}catch{return}},QP=(e,t,n,r,o)=>{if(!Fr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=xn[e].commands[0],s=bt(t,Ss[e]),i=[];for(let{directory:c,suffix:l}of[{directory:bt(s,"bin"),suffix:["bin","remote-cli"]},{directory:bt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=bt(c,d,...l,a),p=o(u);p!==void 0&&i.push({path:u,mtime:p})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},eD=(e,t,n)=>{let{macAppName:r,commands:o}=xn[e],a=o[0],s=[];for(let i of["/Applications",Xb.join(t,"Applications")])for(let c of n(i))XP(c,r)&&s.push(Xb.join(i,c,"Contents/Resources/app/bin",a));return s},tD=(e,t=qp(),n=Uo(),r=process.env,o=zP,a=qP)=>{let s=QP(e,n,r,o,a);if(t==="darwin")return[...new Set([...xn[e].commands,...eD(e,n,o),...s])];if(t!=="win32"){let u=xn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=YP[e],c=KP.join,l=r.LOCALAPPDATA??c(n,"AppData","Local"),d=[c(l,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(u=>!!u);return[...new Set([...d.map(u=>c(u,i.directory,i.executable)),xn[e].commands[0],...s])]},aA={run:async(e,t)=>({stdout:(await ZP(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>GP(24).toString("base64url"),home:"",commandCandidates:e=>tD(e)},Zr=(e,t)=>bt(e,".anyray",rA,`${t}.json`),ef=(e,t)=>bt(e,".anyray",rA,`${t}.applied.json`),sA=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Qc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},Zp=async(e,t,n)=>{try{let r=await t.run(e,[...n===void 0?[]:["--profile",n],"--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===z.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===cn}catch{return}},iA=async(e,t)=>{let n=await sA(e,t);if(n)return Zp(n.command,t)},nD=async(e,t,n)=>{let r=bt(e,".anyray",Qp);for(let o of n){if(!o.endsWith(".json"))continue;let a=bt(r,o);try{if(!(await Jp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},rD=async(e,t)=>{let n=bt(e,".anyray",Qp),r;try{r=await tA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=bt(n,o);try{if(!(await Jp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},oD=async(e,t)=>{try{let n=JSON.parse(await ln(Zr(e,t),"utf8"));return n.extensionVersion===cn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==cr}catch{return!1}},cA=250,aD=9e4,sD=aD/cA,iD=async(e,t,n,r)=>{for(let o=0;o<sD;o++){try{let a=JSON.parse(await ln(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Is&&a.action===n?"confirmed":a.extensionVersion!==cn||a.extensionDistSha256!==cr?"reload-required":a.version===Is&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(cA)}return"timeout"},cD=200,zb=(e,t)=>{let n=e,r=[typeof n?.name=="string"&&n.name?n.name:"Error"];typeof n?.code=="number"?r.push(`exit ${n.code}`):typeof n?.code=="string"&&n.code&&r.push(n.code);let a=(typeof n?.stderr=="string"?n.stderr:"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0);if(a){let s=a;t&&(s=s.replaceAll(t,"<nonce>")),s=s.replace(/\b(ark_|sk-|adt_|enl_)[A-Za-z0-9_-]+/g,"$1\u2026"),r.push(s.slice(0,cD))}return r.join(": ")},lD=async e=>{try{let t=await Jp(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},qb=e=>Qb("sha256").update(e).digest("hex"),dD=async(e=Uo())=>{let t=Buffer.from(Bb,"base64");if(t.length<4||t[0]!==80||t[1]!==75||qb(t)!==qc)throw new Error("bundled VS Code extension failed integrity validation");let n=bt(e,".anyray","vscode-extension"),r=bt(n,`anyray-vscode-${cn}-${qc.slice(0,12)}.vsix`);try{if(qb(await ln(r))===qc)return r}catch{}await Xp(n,{recursive:!0,mode:448});let o=`${r}.${eA()}.tmp`;try{await zp(o,t,{mode:384}),await he(o,r),qp()!=="win32"&&await VP(r,384)}finally{await nA(o,{force:!0})}return r},Yp=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=>Yp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Yp(t[n])}`).join(",")}}`},lA=(e,t,n)=>Qb("sha256").update(Yp({gatewayUrl:Es(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:cn,extensionDistSha256:cr,profiles:[...n].sort()})).digest("hex"),uD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await ln(ef(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==lA(t,n,r))return!1;let i=JSON.parse(await ln(Zr(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===cn&&i.extensionDistSha256===cr&&i.gatewayUrl===Es(t.origin)?await iA(e,a)===!0:!1},pD=async(e,t,n,r)=>{let o=ef(e,t),a=`${o}.${eA()}.tmp`;try{await Xp(jp(o),{recursive:!0,mode:448}),await zp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
112
- `,{mode:384}),await he(a,o)}catch{}finally{await nA(a,{force:!0})}},fD=async(e,t)=>{await el(ef(e,t)).catch(()=>{})},dA=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...aA,...r,home:r.home??Uo()},s=xn[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!oA(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,k,C)=>typeof b.id=="string"&&b.id.length>0&&b.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.id)&&typeof b.name=="string"&&b.name.length>0&&b.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.name)&&C.findIndex(S=>S.id===b.id)===k);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await sA(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!Gp(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>jb(b,qp(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await uD(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:Zr(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let p=a.extensionPath;if(n==="configure"){try{p??=await dD(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await lD(p))return{ok:!1,reason:"extension-missing"}}let f=a.nonce(),m=bt(a.home,".anyray",Qp,`${f}.json`),h=Zr(a.home,s.slug);await Xp(jp(m),{recursive:!0,mode:448});let w=await tA(jp(m)).catch(()=>[]);await zp(m,`${JSON.stringify({version:Is,action:n,nonce:f,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:cn,expectedExtensionDistSha256:cr})}
113
- `,{mode:384}),await nD(a.home,s.slug,w).catch(()=>{});let y={installed:[],failed:[]},g=!1;try{if(n==="configure"){let k=await oD(a.home,s.slug);if(k||await Zp(l,a)!==!0)try{await a.run(l,["--install-extension",p,"--force"])}catch(C){return g=!0,{ok:!1,reason:"install-failed",detail:zb(C,f)}}for(let C of u)try{(k||await Zp(l,a,C)!==!0)&&await a.run(l,["--profile",C,"--install-extension",p,"--force"]),y.installed.push(C)}catch{y.failed.push(C)}}try{await a.run(l,["--open-url",`${s.scheme}://${z}/configure?nonce=${encodeURIComponent(f)}`])}catch(k){return{ok:!1,reason:"handoff-undeliverable",detail:zb(k,f)}}let b=await iD(h,f,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(g=!0,n==="configure")y.failed.length===0&&await pD(a.home,s.slug,lA(t,o,u),f);else{await fD(a.home,s.slug),await rD(a.home,s.slug).catch(()=>{});for(let k of[void 0,...u])try{await a.run(l,[...k?["--profile",k]:[],"--uninstall-extension",z])}catch{}}return{ok:!0,receipt:h,profiles:y}}catch{return{ok:!1,reason:"failed"}}finally{g&&await el(m).catch(()=>{})}},tl=async(e,t=Uo())=>{try{let n=JSON.parse(await ln(Zr(t,xn[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==cn||n.extensionDistSha256!==cr)}catch{return!1}},nl=async(e,t=Uo())=>{try{let n=JSON.parse(await ln(Zr(t,xn[e].slug),"utf8"));return n.version!==Is||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},uA=async(e,t,n=Uo(),r={})=>{try{let o=Es(t);if(!o)return!1;let a=JSON.parse(await ln(Zr(n,xn[e].slug),"utf8"));if(!(a.version===Is&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===cn&&a.extensionDistSha256===cr))return!1;let i={...aA,...r,home:n};return await iA(e,i)===!0}catch{return!1}};var dn="extensions.supportAgentsWindow",un="chat.agentHost.byokModels.enabled",xs=e=>gD(Ve(e),"User","settings.json"),pA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bD=e=>pA(e)&&e[z]===!0,fA=async(e,t={})=>{let n=xs(e),r=t.read??(f=>mD(f,"utf-8")),o=t.exists??x,a=t.write??(async(f,m)=>{await wD(yD(f),{recursive:!0}),await hD(f,m,"utf-8")}),s=await o(n)?await r(n).catch(()=>{}):"{}";if(s===void 0)return{status:"manual",reason:`could not read ${n}`};s.trim()===""&&(s="{}");let i;try{i=wt(s)}catch{return{status:"manual",reason:`${n} is not valid JSON/JSONC, so it was left untouched`}}if(!pA(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(dn in i)){let f=Hp(c,dn,{[z]:!0});if(!f.ok)return{status:"manual",reason:`could not add ${dn} to ${n} without rewriting it`};c=f.text,l=!0}if(!(un in i)){let f=Hp(c,un,!0);if(!f.ok)return{status:"manual",reason:`could not add ${un} to ${n} without rewriting it`};c=f.text,l=!0}l&&await a(n,c);let d=l?wt(c):i,u=bD(d[dn]),p=d[un]===!0;return!u||!p?{status:"manual",reason:`${n} already sets ${u?un:dn} to something else; left as it is`}:{status:"enabled",changed:l}},tf=(e,t)=>t?"Agents window: it runs on your laptop with the extensions installed there, and VS Code registers no model bridge while the agent host is remote, so this run cannot reach it. Run anyray-connect on your laptop too. Chat in this window is already routed.":e.status==="manual"?`Agents window: not enabled (${e.reason}). Add "${dn}": {"${z}": true} and "${un}": true to that file to use Anyray models there.`:e.changed?"Agents window: enabled. It takes effect the next time VS Code starts.":"Agents window: already enabled.";import{spawnSync as AD}from"node:child_process";import{platform as CD}from"node:os";var mA={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},kD=(e,t,n)=>AD(e,t,n),hA=kD,vD,SD=()=>{let e=vD??CD();if(e==="win32"){let n=hA(ws("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],mA);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=hA("pgrep",[n,r],mA);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},ID=SD,Rs=()=>ID();var rl={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"}]};var lr="Anyray",pn="anyray",CA="--anyray-owner=vscode-profile-v1",Os=e=>AA(Ve(e),"User","chatLanguageModels.json"),PD=e=>AA(Ve(e),"User","settings.json"),Ts="github.copilot.advanced",al="debug.overrideCapiUrl",At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),DD=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}},kA=e=>{let t=e[Ts];if(!At(t)||!DD(t[al]))return{next:e,removed:!1};let n={...t};delete n[al];let r={...e};return Object.keys(n).length>0?r[Ts]=n:delete r[Ts],{next:r,removed:!0}},_s="anyray-default",Ps=()=>{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:[_s]},vA=e=>e===_s?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),ol=async e=>{if(!await x(e))return{kind:"missing"};try{let t=await bA(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"}}},SA=async(e,t)=>{await xD(_D(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${TD()}`;try{await OD(n,`${JSON.stringify(t,null,2)}
114
- `,{flag:"wx",mode:384}),await he(n,e),await ED(e,384)}finally{await RD(n,{force:!0}).catch(()=>{})}},nf=e=>{if(!At(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!==lr||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(!At(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!==vA(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!At(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}})},rf=e=>{let t=e.filter(n=>!nf(n));return{next:t,removed:t.length!==e.length}},LD=async(e,t)=>{let n=Os(e),r=await ol(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 "${lr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=rf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${lr}" Custom Endpoint from ${n}.`]};try{return await SA(n,o),await re(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${lr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${lr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},ND=async e=>{try{let t=wt(await bA(e,"utf-8"));if(At(t))return kA(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Ts}.${al} 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 ${Ts}.${al} value manually if present.`]}},IA=async(e,t)=>{let n=PD(e),r;try{r=await B(n)}catch{return ND(n)}let{next:o,removed:a}=kA(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 Y(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.`]}}},$D=async(e,t)=>{let n=await LD(e,t),r=await IA(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},EA=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,CA]}},xA=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},RA=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),MD=e=>Array.isArray(e.args)&&e.args.at(-1)===CA,OA=(e,t)=>{if(!t.hookBinaryIsDurable()||!At(e)||!xA(e,["type","command","args"]))return!1;let n=EA(t);return e.type==="stdio"&&e.command===n.command&&RA(e.args,n.args)},BD=(e,t)=>{if(!At(e)||!xA(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&&RA(e.args,n.args))return!0;if(Ue(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===Jn&&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!Ue(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},of=(e,t)=>OA(e,t)?"exact":At(e)&&MD(e)||BD(e,t)?"stale-owned":"foreign",yA=e=>`MCP name conflict in ${e}: servers.${pn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,FD=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,p=[];for(let f of a)try{let m=await je(f),h=m.data;if(i){if("servers"in h&&!At(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${f} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let b=At(h.servers)?{...h.servers}:{},k=EA(o),C=b[pn],S=C===void 0?void 0:of(C,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(yA(f));continue}if(t){d+=1;continue}b[pn]=k,p.push({path:f,document:m,next:{...h,servers:b},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!At(h.servers)||!(pn in h.servers))continue;if(of(h.servers[pn],o)==="foreign"){u=!0,l.push(yA(f));continue}if(t)continue;let y={...h.servers};delete y[pn];let g={...h};Object.keys(y).length===0?delete g.servers:g.servers=y,p.push({path:f,document:m,next:g,backup:!1,clearBackupAfter:!0})}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${f} (${m instanceof Error?m.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let f of p)try{await sn(f.path,f.document,f.next,f.backup),f.clearBackupAfter&&await re(f.path),c.push(f.path),i&&(d+=1)}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${f.path} (${m instanceof Error?m.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 (${Ub}+).`),{changedFiles:c,messages:l,manual:u}},WD=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await x(c))try{let l=await je(c),d=l.data;if(!At(d.servers)||!(pn in d.servers)||of(d.servers[pn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[pn];let p={...d};Object.keys(u).length===0?delete p.servers:p.servers=u,await sn(c,l,p,!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}},TA=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.`]:[]],_A=()=>`${z} 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.)`,gA=e=>[`${z} 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."],PA=(e,t,n,r)=>({runMcp:o=>FD(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):$D(e,o)}),DA=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${z} VSIX${a}. Nothing was configured. Run \`${n?"code":t.toLowerCase()} --install-extension\` by hand on that VSIX to see the full error.`;case"handoff-undeliverable":return n?`Installed ${z} and staged its configuration, but could not hand it over${a}. A remote VS Code server's command-line launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\`. Reload the VS Code window attached to this machine (Developer: Reload Window): the extension applies the staged configuration as it loads, so there is nothing to re-run.`:`Installed ${z} and staged its configuration, but could not hand it to ${t}${a}. Reload ${t} (quit and reopen): the extension applies the staged configuration as it loads, so there is nothing to re-run.`;case"reload-required":return`A newer ${z} build was installed, but ${t} is still running the previous build. Reload VS Code completely \u2014 the new build applies the staged configuration as it loads, so there is nothing to re-run.`;case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher on this machine. Run anyray-connect from the integrated terminal of the VS Code window attached here (Terminal \u2192 New Terminal in that window) \u2014 a plain SSH shell has no "code" on PATH and cannot hand the key to a running window. No VS Code configuration was written.`:`The ${t} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`;case"unsupported-version":return`The Anyray language-model provider requires VS Code ${Up} or newer. Upgrade ${t}, then re-run anyray-connect; no extension configuration was written.`;case"unsafe-gateway":return"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.";case"extension-missing":return`This anyray-connect installation is missing its bundled ${z} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${z} installed and VS Code accepted the ${r}, but its extension host never confirmed. Reload the VS Code window attached to this machine (Developer: Reload Window): the staged configuration applies as it loads.`:`${z} installed and ${t} accepted the ${r}, but its extension host never confirmed. Reload ${t} completely (quit and reopen): the staged configuration applies as it loads.`;default:return n?`VS Code did not confirm the one-time ${z} ${r}${a}. The configuration is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension applies it as it loads.`:`VS Code did not confirm the one-time ${z} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},HD=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${z} still holds its SecretStorage configuration`;switch(e){case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher, so Anyray could not ask ${z} to clear its SecretStorage configuration. Re-run revert from the integrated terminal of the VS Code window attached to this machine.`:`The ${t} command-line launcher was not found, so Anyray could not ask ${z} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${z} reset to VS Code${o}, so ${a} until it reloads. A remote VS Code server's launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\` \u2014 but the reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`Could not hand the ${z} reset to ${t}${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;case"activation-timeout":return n?`VS Code accepted the ${z} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`${t} accepted the ${z} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;default:return n?`VS Code did not confirm the ${z} reset${o}, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`VS Code did not confirm the ${z} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},UD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=PA(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 m=await c(!0),h=await i(!0);return{status:m.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${z} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...gA(t),a?tf({status:"enabled",changed:!0},!0):`Would enable the VS Code Agents window in ${e}'s settings.json (two keys, each added only if absent).`,...h.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${z}; 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:[DA(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),p=await i(!1),f=a?void 0:await fA(e).catch(()=>({status:"manual",reason:"the settings file could not be read"}));return{status:u.manual||p.manual?"manual":"configured",changedFiles:[d.receipt,...p.changedFiles,...u.changedFiles,...f?.status==="enabled"&&f.changed?[xs(e)]:[]],messages:[...d.alreadyCurrent?[_A()]:[],...gA(t),tf(f??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:TA(d.profiles),...p.messages,...u.messages]}},wA=e=>[`${z} 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: ${Ps().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."],GD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=PA(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let f=await c(!0),m=await i(!0);return{status:f.manual||m.manual?"manual":"configured",messages:[`Would install the bundled ${z} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...wA(t),...m.messages,...f.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${z}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Ps().map(f=>({id:f,name:vA(f)}))});if(!d.ok)return{status:"manual",messages:[DA(d.reason,e,a,"gateway API configuration",d.detail)]};let u=await c(!1),p=await i(!1);return{status:u.manual||p.manual?"manual":"configured",changedFiles:[d.receipt,...p.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[_A()]:[],...wA(t),...d.alreadyCurrent?[]:TA(d.profiles),...p.messages,...u.messages]}},VD=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 x(s))return{registered:!1,command:null};try{let{data:i}=await je(s),c=At(i.servers)?i.servers[pn]:void 0;if(!OA(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 KD=async(e={installedVariant:Ho,remoteServerVariant:Kp,isRemoteDevContext:Fr})=>{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}},jD={installedVariant:Ho,remoteServerVariant:Kp,detectVscodeLmProviderEligibility:Jb,configureVscodeExtension:dA,vscodeExtensionPointsAt:uA,vscodeExtensionAwaitingReload:tl,vscodeExtensionReceiptMode:nl,hookBinaryIsDurable:ce,hookBinaryPath:Oe,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:Zb,isRemoteDevContext:Fr},ZD=(e={})=>{let t={...jD,...e},n=()=>KD(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Rs,quitTarget:rl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Wo(r,!0)}`:Os(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ee(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 ${Up} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||Gb(i.version);return ee(r,"copilot")?UD(a,r,o,t.configureVscodeExtension,c,s,t):GD(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?VD(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Es(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await ol(Os(o));if(s.kind==="array"){let c=s.entries.find(nf)?.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 ol(Os(r));if(o.kind==="array"&&o.entries.some(nf))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 WD(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await IA(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${z} to clear its global configuration and SecretStorage key`);else{let g=await t.configureVscodeExtension(o,void 0,"reset");g.ok?(c=!0,d=g.receipt,u.push(`Cleared ${z} gateway configuration and secret.`)):(l=!0,u.push(HD(g.reason,o,a,g.detail)))}let p=Os(o),f=await ol(p),m=f.kind==="missing"||f.kind==="array"&&!rf(f.entries).removed,h=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),m)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:h.length?h:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:h.length?h:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:h,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(f.kind==="unrecognized")return{status:"manual",changedFiles:h.length?h:void 0,messages:[...u,`Couldn't recognize ${p} \u2014 remove the "${lr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=rf(f.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${lr} Custom Endpoint from ${p}`]};await SA(p,w);let y=[...u,`Removed the ${lr} Custom Endpoint from ${p}.`];return await re(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,p],messages:y}}}},LA=ZD();import{accessSync as vL,constants as YA,statSync as SL}from"node:fs";import{readFile as JA,rm as Ls}from"node:fs/promises";import{homedir as hf,platform as rC}from"node:os";import{delimiter as IL,join as yf,resolve as EL}from"node:path";import{execFile as qD}from"node:child_process";import{readFile as QD}from"node:fs/promises";import{homedir as cf,platform as eL}from"node:os";import{join as Ds}from"node:path";import{join as YD}from"node:path";var af="Iv1.b507a08c87ecfe98",JD="https://github.com/login/device/code",XD="https://github.com/login/oauth/access_token",zD="read:user",NA=1e4,Go=()=>YD(Q(),"copilot-seat-login.json"),$A={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},sf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),MA=async(e={})=>{let t={...$A,...e};try{let n=await t.fetch(JD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:af,scope:zD}),signal:AbortSignal.timeout(NA)});if(!n.ok)return;let r=await n.json();if(!sf(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}},BA=async(e,t={})=>{let n={...$A,...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(XD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:af,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(NA)})).json();if(!sf(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"}},FA=async(e,t)=>{let n=Go();return await we(n,`${JSON.stringify({token:e,clientId:af,mintedAtIso:t},null,2)}
115
- `),n},sl=async()=>{try{let e=await B(Go());if(!sf(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var tL=5e3,lf=5e3,nL=["copilot-cli","CopilotCLI"],rL="https://api.github.com/copilot_internal/user",HA="~/.copilot/config.json",UA="macOS Keychain (Copilot CLI)",GA=e=>e===HA||e===UA,Vo=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),Kt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oL=()=>process.env.XDG_CONFIG_HOME?.trim()||Ds(cf(),".config"),aL=()=>process.env.XDG_DATA_HOME?.trim()||Ds(cf(),".local","share"),sL=async()=>{try{let e=await QD(Ds(cf(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return Vo(t)?t:void 0}catch{}},iL=async e=>{try{let t=await B(Ds(oL(),"github-copilot",e));if(!Kt(t))return;for(let n of Object.values(t))if(Kt(n)&&Vo(n.oauth_token))return n.oauth_token}catch{}},cL=async()=>{try{let e=await B(Ds(aL(),"opencode","auth.json")),t=Kt(e)?e["github-copilot"]:void 0;if(!Kt(t)||t.type!=="oauth")return;if(Vo(t.access))return t.access;if(Vo(t.refresh))return t.refresh}catch{}},lL=(e,t)=>new Promise((n,r)=>{try{qD(e,[...t],{timeout:tL},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),dL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return Vo(r)?r:void 0}catch{return}},uL=async(e=lL)=>{for(let t of nL){let n=await dL(t,e);if(n)return n}};var il={env:process.env,platform:eL,tokenFromDeviceLogin:sl,tokenFromCopilotCliConfig:sL,tokenFromSharedConfig:iL,tokenFromOpenCode:cL,tokenFromKeychain:uL,fetch:(...e)=>fetch(...e)},pL=new Set([401,403,404]),cl=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,VA=e=>{let t=e?.trim().toLowerCase()??"";return t&&t!=="default"&&cl.test(t)?t:"default"},fL=e=>e!=="default"&&cl.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",mL=e=>{if(typeof e!="string")return"default";let t=e.trim().match(/^https:\/\/api\.([a-z0-9-]{1,63})\.githubcopilot\.com\/?$/)?.[1];return t&&cl.test(t)?t:"default"},df=async(e,t={})=>{let n={...il,...t},r=new AbortController,o=setTimeout(()=>r.abort(),lf);try{let a=await n.fetch(rL,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=Kt(i)&&Kt(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:mL(s)}}return{verdict:pL.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var Ko=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${cl.test(n)?n:"default"}/header/models`,a=await WA(o,e,r.clientKey,t);if(a.length>0)return a}return WA(`${fL(n)}/models`,e,void 0,t)},WA=async(e,t,n,r={})=>{let o={...il,...r},a=new AbortController,s=setTimeout(()=>a.abort(),lf);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=Kt(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!Kt(u))continue;let p=u.id;if(typeof p!="string"||p.length===0||u.model_picker_enabled!==!0)continue;let f=u.policy;if(Kt(f)&&f.state!=="enabled")continue;let m=u.supported_endpoints,h=Array.isArray(m)?m.filter(S=>typeof S=="string"):[],w=u.capabilities,y=Kt(w)?w.limits:void 0,g=S=>{let I=Kt(y)?y[S]:void 0;return typeof I=="number"&&Number.isFinite(I)&&I>0?Math.floor(I):void 0},b={id:p,endpoints:h},k=g("max_prompt_tokens"),C=g("max_output_tokens");k!==void 0&&(b.maxPromptTokens=k),C!==void 0&&(b.maxOutputTokens=C),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},ll=async(e,t,n,r={})=>{let o={...il,...r},a=new AbortController,s=setTimeout(()=>a.abort(),lf);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)}},dl=async(e={},t={})=>{let n={...il,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return Vo(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:UA,read:()=>n.tokenFromKeychain()}]:[],{source:HA,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await df(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}};import{homedir as ul,platform as jA}from"node:os";import{join as st}from"node:path";import{execFile as hL}from"node:child_process";import{readFile as yL,readdir as gL}from"node:fs/promises";var wL=3e3,bL="Claude Code-credentials",AL=["copilot-cli","CopilotCLI"],ZA=e=>new Promise(t=>{try{hL("security",["find-generic-password","-s",e],{timeout:wL},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),CL=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=st(ul(),".claude");return!!(await x(st(e,".oauth_token"))||await x(st(e,".credentials.json"))||jA()==="darwin"&&await ZA(bL))},kL=async()=>{let e=st(process.env.CODEX_HOME?.trim()||st(ul(),".codex"),"auth.json");if(!await x(e))return!1;try{let t=JSON.parse(await yL(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},KA=async e=>{try{return(await gL(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},uf=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of vs){let n=st(Ve(t),"User","globalStorage");if(await x(st(n,"github.copilot-chat"))||await x(st(n,"github.copilot")))return!0}let e=st(ul(),".config","github-copilot");if(await x(st(e,"apps.json"))||await x(st(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await KA(st(ul(),t,"extensions")))return!0;for(let t of vs){if(await KA(Yb(t)))return!0;let n=st(Wo(t,!0),"globalStorage");if(await x(st(n,"github.copilot-chat"))||await x(st(n,"github.copilot")))return!0}if(jA()==="darwin"){for(let t of AL)if(await ZA(t))return!0}return!1},fn=async()=>{let[e,t,n]=await Promise.all([CL(),kL(),uf()]);return{anthropic:e,openai:t,copilot:n}};var Xr="copilot-cli",mn="copilot-cli",xL=Rs,RL=()=>xL()?["VS Code is open \u2014 its Copilot CLI runs inside the extension host, which","captured your shell environment when the editor launched. Restart VS Code,","or its CLI chat and Autopilot sessions stay on native GitHub traffic and","never reach the gateway (no spend, no traces) even though this block is set."]:[],oC=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],gf=()=>Object.fromEntries(oC.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),XA=()=>yf(hf(),".anyray","copilot-cli.sh"),aC="# Managed by anyray-connect. Do not source this file anywhere else.",zA=e=>e.split(/\r?\n/,1)[0]===aC,OL=["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"],pl="COPILOT_PROVIDER_API_KEY",qA=e=>e.startsWith(`export ${pl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),On=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",TL=()=>Ps()[0],Ns=(e="default")=>`/copilot/${e}/header`,L9=Ns(),Yr=e=>e.replace(/\/+$/,""),_L=(e,t="default")=>`${Yr(e.openaiBaseUrl)}${Ns(t)}`,pf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),mf="claude-sonnet-5",PL=()=>{let e=Ps()[0];return e===_s?mf:e},sC=e=>e.endpoints.includes(On(e.id)==="responses"?"/responses":"/chat/completions"),wf=e=>{let t=e.filter(sC),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)=>QA(a.version,s.version)?-1:QA(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var QA=(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},eC=(e,t,n,r,o,a="default")=>{let s=ue({...e.metadata,tool:Xr}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...oC];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(_L(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${On(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...o?.maxPromptTokens?[`export COPILOT_PROVIDER_MAX_PROMPT_TOKENS='${o.maxPromptTokens}'`]:[],...o?.maxOutputTokens?[`export COPILOT_PROVIDER_MAX_OUTPUT_TOKENS='${o.maxOutputTokens}'`]:[],...i.length>0?[`export COPILOT_PROVIDER_HEADERS=${ve(i.join(`
116
- `))}`]:[],`export ${pl}=${ve(n)}`]},ff=(e,t,n)=>{let r=ue({...e.metadata,tool:Xr});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${On(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${ve(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${pl}=${ve(n)}`]:[]]},DL=(e,t)=>t||!ee(e,"copilot"),tC=()=>{let e=OL.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).`]},nC=(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 ${Xr}\`), 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`."],LL=(e=process.env.PATH,t=rC())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(IL)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=EL(o,n);try{if(!SL(a).isFile())continue;return vL(a,t==="win32"?YA.F_OK:YA.X_OK),a}catch{}}},NL=()=>yf(hf(),".copilot","config.json"),Rn=()=>yf(hf(),".copilot","mcp-config.json"),Jr="anyray",$L=()=>({type:"local",...Ge("profile"),tools:["*"]}),dr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ML=async()=>{let e=Rn(),t;try{t=await B(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&&!dr(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=(dr(t.mcpServers)?t.mcpServers:{})[Jr];return r!==void 0&&!Gt(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}},BL=async e=>{let t=Rn(),n=e.json,r=dr(n.mcpServers)?n.mcpServers:{};r[Jr]=$L(),n.mcpServers=r,await Y(t,n)},FL=async()=>{let e=Rn(),t;try{let r=await B(e);if(!dr(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!dr(n)||!(Jr in n)||!Gt(n[Jr],"profile")?!1:(delete n[Jr],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Ls(e,{force:!0}):await Y(e,t,{backup:!1}),await re(e),!0)},WL={resolveCopilotCommand:LL,platform:rC,detectCopilotSeat:uf,discoverSeatToken:dl,readDeviceLoginToken:sl,fetchSeatModelCatalog:Ko,probeSeatChatModel:ll},HL=e=>`'${e.replace(/'/g,"''")}'`,UL=e=>e.split(`
117
- `).map(HL).join(" + [Environment]::NewLine + "),GL=(e={})=>{let t={...WL,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Lc(gt(),mn))?.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&&Yr(s)===`${Yr(i)}/v1`,a=(s,i)=>s!==void 0&&pf(s)&&Yr(s).startsWith(`${Yr(i)}/v1/copilot/`);return{id:Xr,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Rs,quitTarget:rl},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=NL();return await x(i)?{installed:!0,detail:i}:{installed:!1,detail:"no `copilot` on PATH and no ~/.copilot state"}},async apply(s,i){let c=gt(),l=async(S,I,E)=>{let R=S.filter(qA),P=S.filter(X=>!qA(X)),W=XA(),q=[...P,...R.length>0?[`[ -r ${ve(W)} ] && . ${ve(W)}`]:[]],de=await x(W),ie=de?await JA(W,"utf8"):void 0,K=ie===void 0||zA(ie);if(R.length>0&&!K)return{status:"manual",messages:[`Refused to overwrite user-managed ${W}; move or rename that file, then run Connect again.`]};let ge=ce(),me=ge?await ML():void 0,F=[`${c} \u2190 managed Anyray block (${mn})`,...I.map(X=>` ${X}`),...R.length>0?[`${W} \u2190 owner-only credential (mode 0600)`]:[],...E,me?.status==="skipped"?me.message:ge?`${Rn()} \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.`,...RL()];if(i.dryRun)return{status:"configured",messages:F};let Z=!1;me?.status==="installable"&&(await BL(me),Z=!0);try{R.length>0?await we(W,[aC,...R,""].join(`
118
- `)):de&&K&&await Ls(W,{force:!0}),await Dc(c,q,mn)}catch(X){try{ie!==void 0&&K?await we(W,ie):K&&await Ls(W,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw X}return{status:"configured",messages:F,changedFiles:[c,...R.length>0||de&&K?[W]:[],...Z?[Rn()]:[]]}},d=await r(),u=d!==void 0&&!pf(d),p=s.authMode==="placeholder",f=u,m=u&&(!f||!ee(s,"copilot")),h=p?void 0:await t.readDeviceLoginToken().catch(()=>{}),w=p||m&&!h?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),y=w.token,g=w.rejected;if(y){let S=w.capiSegment??"default",I=PL(),E=I!==mf||!!process.env.ANYRAY_COPILOT_MODEL,R=await t.fetchSeatModelCatalog(y.token,{},S,{laneOrigin:Yr(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),P=R.find(F=>F.id===I);if(!E){let F=wf(R);if(P=F[0],!i.dryRun&&F.length>0){let Z=T=>`${Yr(s.origin)}/v1${Ns(S)}/${On(T)==="responses"?"responses":"chat/completions"}`,X={...gf(),authorization:`Bearer ${y.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},Je=new Set,We;for(let T of F.slice(0,4)){let L=await t.probeSeatChatModel(Z(T.id),X,T.id);if(L==="ok"){We=T;break}if(L==="unreachable")break;Je.add(T.id)}P=We??F.find(T=>!Je.has(T.id))??F[0]}I=P?.id??mf}let W=s.clientKey??s.placeholderKey,q=W&&s.clientKey?Tt(W):W,de=eC(s,I,y.token,W,P,S),ie=eC(s,I,Tt(y.token),q,P,S),K=On(I),ge=R.filter(F=>sC(F)&&On(F.id)===K).map(F=>F.id).filter(F=>F!==I),me=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${y.source}).`,`Model: ${I}${E?" (pinned via ANYRAY_COPILOT_MODEL)":R.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...R.length===0&&GA(y.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."]:[],...ge.length>0?[`Your plan also serves: ${ge.slice(0,8).join(", ")}${ge.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",...ie.map(F=>{let Z=F.indexOf("="),X=F.slice(7,Z),Je=F.slice(Z+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${X}', ${UL(Je)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${y.source}, and the gateway key from \`anyray-connect print-key\`.)`,...me]}:l(de,ie,me)}if(!DL(s,m)){if(f&&!i.dryRun){let S=gt();if(await fs(S,mn))return{status:"reverted",changedFiles:[S],messages:[`removed a stale Anyray ${mn} block from ${S}`,"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:",...nC(t.platform(),g),...tC()]}}return{status:"held",messages:[...f&&i.dryRun?[`would remove a stale Anyray ${mn} block from ${gt()} (org lane, not chosen)`]:[],...nC(t.platform(),g)]}}let b=TL(),k=s.clientKey??s.placeholderKey,C=k&&s.clientKey?Tt(k):k;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...ff(s,b,C).map(S=>{let[I,...E]=S.replace(/^export /,"").split("=");return` setx ${I} "${E.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${pl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(ff(s,b,k),ff(s,b,C),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===_s?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=gt(),c=XA(),l=await x(c),d=l?zA(await JA(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${mn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Rn()} if registered`,...await x(Go())?[`would remove the Copilot sign-in Connect minted (${Go()})`]:[]]};let u=await fs(i,mn);d&&await Ls(c,{force:!0});let p=await FL(),f=Go(),m=await x(f);m&&await Ls(f,{force:!0});let h=[...u?[i]:[],...d?[c]:[],...p?[Rn()]:[],...m?[f]:[]];return{status:h.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${mn} block from ${i}`:`no Anyray ${mn} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...m?[`removed the Copilot sign-in Connect minted (${f})`]:[],...p?[`removed the Anyray MCP server from ${Rn()}`]:[],...tC()],changedFiles:h.length>0?h:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){try{let s=await B(Rn()),i=dr(s)?s.mcpServers:void 0,c=dr(i)?i[Jr]:void 0;return!dr(c)||!Gt(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"]:pf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(Xr)?!0:!await t.detectCopilotSeat()}}},iC=GL();import{homedir as mC}from"node:os";import{join as pr}from"node:path";import{readFile as hC}from"node:fs/promises";import{readFile as cC,rm as VL}from"node:fs/promises";var lC="// Managed by anyray-connect: OpenCode trim carrier v1",KL=5e3,bf=e=>`${lC}
111
+ ${a}${s},`,d=`${i}${l}${c}`;try{let u=wt(d);if(!Wb(u))return{ok:!1,reason:"unsupported"};for(let[p,f]of Object.entries(r))if(JSON.stringify(u[p])!==JSON.stringify(f))return{ok:!1,reason:"unsupported"};if(JSON.stringify(u[t])!==JSON.stringify(n))return{ok:!1,reason:"unsupported"}}catch{return{ok:!1,reason:"unsupported"}}return{ok:!0,text:d}};import{execFile as YP}from"node:child_process";import{readdirSync as JP,statSync as XP}from"node:fs";import{createHash as nA,randomBytes as zP,randomUUID as rA}from"node:crypto";import{chmod as qP,lstat as Yp,mkdir as Jp,readdir as oA,readFile as ln,rm as aA,unlink as el,writeFile as Xp}from"node:fs/promises";import{homedir as Ho,platform as zp}from"node:os";import{dirname as Kp,join as bt,posix as Qb,win32 as QP}from"node:path";import{promisify as eD}from"node:util";var cn="0.1.29";var lr="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",qc="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",Ub="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfiqg5aldZRjy9SCjdSklpgCSRKo6InP09C+VJqXKL1AaNc0qrT+sjrq253E36jzwDoaCRTuBYnv7y4yMaYQEOC+uciG2p0yaQ1G4ErKiiwx9F1/p5yNtQ9Dm4dYd1ZkvIa+T6rK9EV179zNqlm1tAC49aVM9ni3hoKFtafoMS835jY3Ef2OGUDrzGTh/Y2AElFE5Lxrk73hgIo7PEQkTAuked9rRmugjXKJLaBLCDhM6xZ6TVaYj5uDJ3nCCGgZgMfjPWJUTXbw2+80yL6qlhs9/QrBE9/EPPzuVEGLLObinQafxaiXxqNkfUnQ5HJg/22CTxAQfnLGMpks9rYB5Cw8NEg5f3huzGohXHIRgjRGVdk8sDe+H8AazGu722N0BRaZfLFYu3WuE5i3fW0Dd0trJsmjndD8mioAjtNlTZe1DmLO1cYV3cWbIU9/k9XdK+bKZcnI60Suno6bjGg0+iUQdoBvwWwPls/BOhP4/QO6NnHp2bG3lXmDNCRV2DNZ9Tbc/O2XB3MLOp+MHWIJ7CvwJ2cNqoqIQ3ao9uCpVjhGYBTjEujkMTIuCcSU19FtQetRYlupC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aAMAAFtDb250ZW50X1R5cGVzXS54bWxQSwECPwMUAAgICAAKWhhdcQ3Z86YCAAC7BQAAFgAAAAAAAAAAAAAApIFrBAAAZXh0ZW5zaW9uL3BhY2thZ2UuanNvblBLAQI/AxQACAgIAARaGF0wVq3AThEAACgTAAASAAAAAAAAAAAAAACkgVUHAABleHRlbnNpb24vaWNvbi5wbmdQSwECPwMUAAAICAAXWhhdC7fjr0sCAAB9BAAAEwAAAAAAAAAAAAAAtIHjGAAAZXh0ZW5zaW9uL3JlYWRtZS5tZFBLAQI/AxQACAgIAMtZGF2yhnqNeQIAACcEAAAVAAAAAAAAAAAAAACkgV8bAABleHRlbnNpb24vTElDRU5TRS50eHRQSwECPwMUAAgICAAXWhhdpzIc9AM5AAAjqQAAGwAAAAAAAAAAAAAApIEbHgAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAHAAcA1gEAAGdXAAAAAA==";import{readFile as Vb}from"node:fs/promises";import{homedir as jr,platform as Fo}from"node:os";import{join as xn,posix as HP,win32 as GP}from"node:path";var vs=["Code","Code - Insiders","VSCodium"],Up="1.121.0",Hb=1,VP=121,Kb="1.102.0",Gb=1,KP=102,jP={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Qc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},Hp=e=>{let t=Qc(e);return t?t.major!==Hb?t.major>Hb:t.minor>=VP:!1},jb=e=>{let t=Qc(e);return t?t.major!==Gb?t.major>Gb:t.minor>=KP:!1},ZP=async e=>{if(Fo()!=="darwin")return;let t=xn("/Applications",`${jP[e]}.app`,"Contents","Resources","app","package.json");if(await x(t))try{let n=JSON.parse(await Vb(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Zb=(e,t=Fo(),n=jr(),r=process.env)=>{switch(t){case"darwin":return xn(n,"Library","Application Support",e);case"win32":return xn(r.APPDATA??xn(n,"AppData","Roaming"),e);default:return xn(n,".config",e)}},Gp=(e,t)=>e?t==="win32"?GP.join:HP.join:xn,Wo=(e,t=!1,n=Fo(),r=jr(),o=process.env)=>t?Gp(t,n)(r,Ss[e],"data","User"):xn(Zb(e,n,r,o),"User"),Yb=async(e,t=!1,n=Fo(),r=jr(),o=process.env)=>{try{let a=Gp(t,n)(Wo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Vb(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[]}},Jb=async(e,t=Fo(),n=jr(),r=process.env)=>{let a=(await Yb(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},Xb=async(e,t=!1,n=Fo(),r=jr(),o=process.env)=>{let a=Gp(t,n),s=Wo(e,t,n,r,o),i=await Yb(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Uo=async()=>{for(let e of vs)if(await x(Zb(e)))return e},Ss={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},zb=(e,t=jr())=>xn(t,Ss[e],"extensions"),Vp=async(e=jr())=>{for(let t of vs)if(await x(xn(e,Ss[t])))return t},qb=async e=>{let t=e??await Uo();if(!t)return{status:"unknown"};let n=await ZP(t);return n?{variant:t,version:n,status:Hp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var z="anyray.anyray-vscode",qp="vscode-handoffs",sA="vscode-receipts",Is=2,tD=eD(YP),Rn={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"]}},nD={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"}},rD=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),iA=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&rD(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Es=e=>{if(iA(e))try{return new URL(e.trim()).origin}catch{return}},oD=(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)},aD=e=>{try{return JP(e)}catch{return[]}},sD=e=>{try{return XP(e).mtimeMs}catch{return}},iD=(e,t,n,r,o)=>{if(!Fr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=Rn[e].commands[0],s=bt(t,Ss[e]),i=[];for(let{directory:c,suffix:l}of[{directory:bt(s,"bin"),suffix:["bin","remote-cli"]},{directory:bt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=bt(c,d,...l,a),p=o(u);p!==void 0&&i.push({path:u,mtime:p})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},cD=(e,t,n)=>{let{macAppName:r,commands:o}=Rn[e],a=o[0],s=[];for(let i of["/Applications",Qb.join(t,"Applications")])for(let c of n(i))oD(c,r)&&s.push(Qb.join(i,c,"Contents/Resources/app/bin",a));return s},lD=(e,t=zp(),n=Ho(),r=process.env,o=aD,a=sD)=>{let s=iD(e,n,r,o,a);if(t==="darwin")return[...new Set([...Rn[e].commands,...cD(e,n,o),...s])];if(t!=="win32"){let u=Rn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=nD[e],c=QP.join,l=r.LOCALAPPDATA??c(n,"AppData","Local"),d=[c(l,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(u=>!!u);return[...new Set([...d.map(u=>c(u,i.directory,i.executable)),Rn[e].commands[0],...s])]},cA={run:async(e,t)=>({stdout:(await tD(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>zP(24).toString("base64url"),home:"",commandCandidates:e=>lD(e)},Zr=(e,t)=>bt(e,".anyray",sA,`${t}.json`),Qp=(e,t)=>bt(e,".anyray",sA,`${t}.applied.json`),lA=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Qc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},jp=async(e,t,n)=>{try{let r=await t.run(e,[...n===void 0?[]:["--profile",n],"--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===z.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===cn}catch{return}},dA=async(e,t)=>{let n=await lA(e,t);if(n)return jp(n.command,t)},dD=async(e,t,n)=>{let r=bt(e,".anyray",qp);for(let o of n){if(!o.endsWith(".json"))continue;let a=bt(r,o);try{if(!(await Yp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},uD=async(e,t)=>{let n=bt(e,".anyray",qp),r;try{r=await oA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=bt(n,o);try{if(!(await Yp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},pD=async(e,t)=>{try{let n=JSON.parse(await ln(Zr(e,t),"utf8"));return n.extensionVersion===cn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==lr}catch{return!1}},uA=250,fD=9e4,mD=fD/uA,hD=async(e,t,n,r)=>{for(let o=0;o<mD;o++){try{let a=JSON.parse(await ln(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Is&&a.action===n?"confirmed":a.extensionVersion!==cn||a.extensionDistSha256!==lr?"reload-required":a.version===Is&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(uA)}return"timeout"},yD=200,eA=(e,t)=>{let n=e,r=[typeof n?.name=="string"&&n.name?n.name:"Error"];typeof n?.code=="number"?r.push(`exit ${n.code}`):typeof n?.code=="string"&&n.code&&r.push(n.code);let a=(typeof n?.stderr=="string"?n.stderr:"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0);if(a){let s=a;t&&(s=s.replaceAll(t,"<nonce>")),s=s.replace(/\b(ark_|sk-|adt_|enl_)[A-Za-z0-9_-]+/g,"$1\u2026"),r.push(s.slice(0,yD))}return r.join(": ")},gD=async e=>{try{let t=await Yp(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},tA=e=>nA("sha256").update(e).digest("hex"),wD=async(e=Ho())=>{let t=Buffer.from(Ub,"base64");if(t.length<4||t[0]!==80||t[1]!==75||tA(t)!==qc)throw new Error("bundled VS Code extension failed integrity validation");let n=bt(e,".anyray","vscode-extension"),r=bt(n,`anyray-vscode-${cn}-${qc.slice(0,12)}.vsix`);try{if(tA(await ln(r))===qc)return r}catch{}await Jp(n,{recursive:!0,mode:448});let o=`${r}.${rA()}.tmp`;try{await Xp(o,t,{mode:384}),await he(o,r),zp()!=="win32"&&await qP(r,384)}finally{await aA(o,{force:!0})}return r},Zp=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=>Zp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Zp(t[n])}`).join(",")}}`},pA=(e,t,n)=>nA("sha256").update(Zp({gatewayUrl:Es(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:cn,extensionDistSha256:lr,profiles:[...n].sort()})).digest("hex"),bD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await ln(Qp(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==pA(t,n,r))return!1;let i=JSON.parse(await ln(Zr(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===cn&&i.extensionDistSha256===lr&&i.gatewayUrl===Es(t.origin)?await dA(e,a)===!0:!1},AD=async(e,t,n,r)=>{let o=Qp(e,t),a=`${o}.${rA()}.tmp`;try{await Jp(Kp(o),{recursive:!0,mode:448}),await Xp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
112
+ `,{mode:384}),await he(a,o)}catch{}finally{await aA(a,{force:!0})}},CD=async(e,t)=>{await el(Qp(e,t)).catch(()=>{})},fA=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...cA,...r,home:r.home??Ho()},s=Rn[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!iA(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,k,C)=>typeof b.id=="string"&&b.id.length>0&&b.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.id)&&typeof b.name=="string"&&b.name.length>0&&b.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.name)&&C.findIndex(S=>S.id===b.id)===k);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await lA(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!Hp(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>Jb(b,zp(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await bD(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:Zr(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let p=a.extensionPath;if(n==="configure"){try{p??=await wD(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await gD(p))return{ok:!1,reason:"extension-missing"}}let f=a.nonce(),m=bt(a.home,".anyray",qp,`${f}.json`),h=Zr(a.home,s.slug);await Jp(Kp(m),{recursive:!0,mode:448});let w=await oA(Kp(m)).catch(()=>[]);await Xp(m,`${JSON.stringify({version:Is,action:n,nonce:f,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:cn,expectedExtensionDistSha256:lr})}
113
+ `,{mode:384}),await dD(a.home,s.slug,w).catch(()=>{});let y={installed:[],failed:[]},g=!1;try{if(n==="configure"){let k=await pD(a.home,s.slug);if(k||await jp(l,a)!==!0)try{await a.run(l,["--install-extension",p,"--force"])}catch(C){return g=!0,{ok:!1,reason:"install-failed",detail:eA(C,f)}}for(let C of u)try{(k||await jp(l,a,C)!==!0)&&await a.run(l,["--profile",C,"--install-extension",p,"--force"]),y.installed.push(C)}catch{y.failed.push(C)}}try{await a.run(l,["--open-url",`${s.scheme}://${z}/configure?nonce=${encodeURIComponent(f)}`])}catch(k){return{ok:!1,reason:"handoff-undeliverable",detail:eA(k,f)}}let b=await hD(h,f,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(g=!0,n==="configure")y.failed.length===0&&await AD(a.home,s.slug,pA(t,o,u),f);else{await CD(a.home,s.slug),await uD(a.home,s.slug).catch(()=>{});for(let k of[void 0,...u])try{await a.run(l,[...k?["--profile",k]:[],"--uninstall-extension",z])}catch{}}return{ok:!0,receipt:h,profiles:y}}catch{return{ok:!1,reason:"failed"}}finally{g&&await el(m).catch(()=>{})}},tl=async(e,t=Ho())=>{try{let n=JSON.parse(await ln(Zr(t,Rn[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==cn||n.extensionDistSha256!==lr)}catch{return!1}},nl=async(e,t=Ho())=>{try{let n=JSON.parse(await ln(Zr(t,Rn[e].slug),"utf8"));return n.version!==Is||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},mA=async(e,t,n=Ho(),r={})=>{try{let o=Es(t);if(!o)return!1;let a=JSON.parse(await ln(Zr(n,Rn[e].slug),"utf8"));if(!(a.version===Is&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===cn&&a.extensionDistSha256===lr))return!1;let i={...cA,...r,home:n};return await dA(e,i)===!0}catch{return!1}};var dn="extensions.supportAgentsWindow",un="chat.agentHost.byokModels.enabled",xs=e=>ID(Ve(e),"User","settings.json"),hA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xD=e=>hA(e)&&e[z]===!0,yA=async(e,t={})=>{let n=xs(e),r=t.read??(f=>kD(f,"utf-8")),o=t.exists??x,a=t.write??(async(f,m)=>{await ED(SD(f),{recursive:!0}),await vD(f,m,"utf-8")}),s=await o(n)?await r(n).catch(()=>{}):"{}";if(s===void 0)return{status:"manual",reason:`could not read ${n}`};s.trim()===""&&(s="{}");let i;try{i=wt(s)}catch{return{status:"manual",reason:`${n} is not valid JSON/JSONC, so it was left untouched`}}if(!hA(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(dn in i)){let f=Wp(c,dn,{[z]:!0});if(!f.ok)return{status:"manual",reason:`could not add ${dn} to ${n} without rewriting it`};c=f.text,l=!0}if(!(un in i)){let f=Wp(c,un,!0);if(!f.ok)return{status:"manual",reason:`could not add ${un} to ${n} without rewriting it`};c=f.text,l=!0}l&&await a(n,c);let d=l?wt(c):i,u=xD(d[dn]),p=d[un]===!0;return!u||!p?{status:"manual",reason:`${n} already sets ${u?un:dn} to something else; left as it is`}:{status:"enabled",changed:l}},ef=(e,t)=>t?"Agents window: it runs on your laptop with the extensions installed there, and VS Code registers no model bridge while the agent host is remote, so this run cannot reach it. Run anyray-connect on your laptop too. Chat in this window is already routed.":e.status==="manual"?`Agents window: not enabled (${e.reason}). Add "${dn}": {"${z}": true} and "${un}": true to that file to use Anyray models there.`:e.changed?"Agents window: enabled. It takes effect the next time VS Code starts.":"Agents window: already enabled.";import{spawnSync as RD}from"node:child_process";import{platform as OD}from"node:os";var gA={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},TD=(e,t,n)=>RD(e,t,n),wA=TD,_D,PD=()=>{let e=_D??OD();if(e==="win32"){let n=wA(ws("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],gA);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=wA("pgrep",[n,r],gA);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},DD=PD,Rs=()=>DD();var rl={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"}]};var dr="Anyray",pn="anyray",SA="--anyray-owner=vscode-profile-v1",Os=e=>vA(Ve(e),"User","chatLanguageModels.json"),WD=e=>vA(Ve(e),"User","settings.json"),Ts="github.copilot.advanced",al="debug.overrideCapiUrl",At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),UD=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}},IA=e=>{let t=e[Ts];if(!At(t)||!UD(t[al]))return{next:e,removed:!1};let n={...t};delete n[al];let r={...e};return Object.keys(n).length>0?r[Ts]=n:delete r[Ts],{next:r,removed:!0}},_s="anyray-default",Ps=()=>{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:[_s]},EA=e=>e===_s?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),ol=async e=>{if(!await x(e))return{kind:"missing"};try{let t=await kA(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"}}},xA=async(e,t)=>{await ND(FD(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${BD()}`;try{await MD(n,`${JSON.stringify(t,null,2)}
114
+ `,{flag:"wx",mode:384}),await he(n,e),await LD(e,384)}finally{await $D(n,{force:!0}).catch(()=>{})}},tf=e=>{if(!At(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!==dr||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(!At(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!==EA(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!At(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}})},nf=e=>{let t=e.filter(n=>!tf(n));return{next:t,removed:t.length!==e.length}},HD=async(e,t)=>{let n=Os(e),r=await ol(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 "${dr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=nf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${dr}" Custom Endpoint from ${n}.`]};try{return await xA(n,o),await oe(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${dr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${dr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},GD=async e=>{try{let t=wt(await kA(e,"utf-8"));if(At(t))return IA(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Ts}.${al} 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 ${Ts}.${al} value manually if present.`]}},RA=async(e,t)=>{let n=WD(e),r;try{r=await M(n)}catch{return GD(n)}let{next:o,removed:a}=IA(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 Y(n,o,{backup:!1}),await oe(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.`]}}},VD=async(e,t)=>{let n=await HD(e,t),r=await RA(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},OA=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,SA]}},TA=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},_A=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),KD=e=>Array.isArray(e.args)&&e.args.at(-1)===SA,PA=(e,t)=>{if(!t.hookBinaryIsDurable()||!At(e)||!TA(e,["type","command","args"]))return!1;let n=OA(t);return e.type==="stdio"&&e.command===n.command&&_A(e.args,n.args)},jD=(e,t)=>{if(!At(e)||!TA(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&&_A(e.args,n.args))return!0;if(He(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===Xn&&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!He(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},sl=(e,t)=>PA(e,t)?"exact":At(e)&&KD(e)||jD(e,t)?"stale-owned":"foreign",bA=e=>`MCP name conflict in ${e}: servers.${pn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,ZD=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,p=[];for(let f of a)try{let m=await je(f),h=m.data;if(i){if("servers"in h&&!At(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${f} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let b=At(h.servers)?{...h.servers}:{},k=OA(o),C=b[pn],S=C===void 0?void 0:sl(C,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(bA(f));continue}if(t){d+=1;continue}b[pn]=k,p.push({path:f,document:m,next:{...h,servers:b},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!At(h.servers)||!(pn in h.servers))continue;if(sl(h.servers[pn],o)==="foreign"){u=!0,l.push(bA(f));continue}if(t)continue;let y={...h.servers};delete y[pn];let g={...h};Object.keys(y).length===0?delete g.servers:g.servers=y,p.push({path:f,document:m,next:g,backup:!1,clearBackupAfter:!0})}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${f} (${m instanceof Error?m.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let f of p)try{await sn(f.path,f.document,f.next,f.backup),f.clearBackupAfter&&await oe(f.path),c.push(f.path),i&&(d+=1)}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${f.path} (${m instanceof Error?m.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 (${Kb}+).`),{changedFiles:c,messages:l,manual:u}},YD=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await x(c))try{let l=await je(c),d=l.data;if(!At(d.servers)||!(pn in d.servers)||sl(d.servers[pn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[pn];let p={...d};Object.keys(u).length===0?delete p.servers:p.servers=u,await sn(c,l,p,!1),await oe(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}},DA=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.`]:[]],LA=()=>`${z} 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.)`,AA=e=>[`${z} 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."],NA=(e,t,n,r)=>({runMcp:o=>ZD(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):VD(e,o)}),$A=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${z} VSIX${a}. Nothing was configured. Run \`${n?"code":t.toLowerCase()} --install-extension\` by hand on that VSIX to see the full error.`;case"handoff-undeliverable":return n?`Installed ${z} and staged its configuration, but could not hand it over${a}. A remote VS Code server's command-line launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\`. Reload the VS Code window attached to this machine (Developer: Reload Window): the extension applies the staged configuration as it loads, so there is nothing to re-run.`:`Installed ${z} and staged its configuration, but could not hand it to ${t}${a}. Reload ${t} (quit and reopen): the extension applies the staged configuration as it loads, so there is nothing to re-run.`;case"reload-required":return`A newer ${z} build was installed, but ${t} is still running the previous build. Reload VS Code completely \u2014 the new build applies the staged configuration as it loads, so there is nothing to re-run.`;case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher on this machine. Run anyray-connect from the integrated terminal of the VS Code window attached here (Terminal \u2192 New Terminal in that window) \u2014 a plain SSH shell has no "code" on PATH and cannot hand the key to a running window. No VS Code configuration was written.`:`The ${t} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`;case"unsupported-version":return`The Anyray language-model provider requires VS Code ${Up} or newer. Upgrade ${t}, then re-run anyray-connect; no extension configuration was written.`;case"unsafe-gateway":return"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.";case"extension-missing":return`This anyray-connect installation is missing its bundled ${z} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${z} installed and VS Code accepted the ${r}, but its extension host never confirmed. Reload the VS Code window attached to this machine (Developer: Reload Window): the staged configuration applies as it loads.`:`${z} installed and ${t} accepted the ${r}, but its extension host never confirmed. Reload ${t} completely (quit and reopen): the staged configuration applies as it loads.`;default:return n?`VS Code did not confirm the one-time ${z} ${r}${a}. The configuration is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension applies it as it loads.`:`VS Code did not confirm the one-time ${z} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},JD=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${z} still holds its SecretStorage configuration`;switch(e){case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher, so Anyray could not ask ${z} to clear its SecretStorage configuration. Re-run revert from the integrated terminal of the VS Code window attached to this machine.`:`The ${t} command-line launcher was not found, so Anyray could not ask ${z} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${z} reset to VS Code${o}, so ${a} until it reloads. A remote VS Code server's launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\` \u2014 but the reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`Could not hand the ${z} reset to ${t}${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;case"activation-timeout":return n?`VS Code accepted the ${z} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`${t} accepted the ${z} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;default:return n?`VS Code did not confirm the ${z} reset${o}, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`VS Code did not confirm the ${z} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},XD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=NA(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 m=await c(!0),h=await i(!0);return{status:m.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${z} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...AA(t),a?ef({status:"enabled",changed:!0},!0):`Would enable the VS Code Agents window in ${e}'s settings.json (two keys, each added only if absent).`,...h.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${z}; 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:[$A(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),p=await i(!1),f=a?void 0:await yA(e).catch(()=>({status:"manual",reason:"the settings file could not be read"}));return{status:u.manual||p.manual?"manual":"configured",changedFiles:[d.receipt,...p.changedFiles,...u.changedFiles,...f?.status==="enabled"&&f.changed?[xs(e)]:[]],messages:[...d.alreadyCurrent?[LA()]:[],...AA(t),ef(f??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:DA(d.profiles),...p.messages,...u.messages]}},CA=e=>[`${z} 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: ${Ps().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."],zD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=NA(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let f=await c(!0),m=await i(!0);return{status:f.manual||m.manual?"manual":"configured",messages:[`Would install the bundled ${z} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...CA(t),...m.messages,...f.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${z}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Ps().map(f=>({id:f,name:EA(f)}))});if(!d.ok)return{status:"manual",messages:[$A(d.reason,e,a,"gateway API configuration",d.detail)]};let u=await c(!1),p=await i(!1);return{status:u.manual||p.manual?"manual":"configured",changedFiles:[d.receipt,...p.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[LA()]:[],...CA(t),...d.alreadyCurrent?[]:DA(d.profiles),...p.messages,...u.messages]}},qD=async(e,t,n)=>{if(!n.hookBinaryIsDurable())return{registered:!1,command:null,reason:"ephemeral-runtime"};let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null,reason:"no-config"};let o=[];for(let s of r){if(!await x(s))return{registered:!1,command:null,reason:"no-config"};try{let{data:i}=await je(s),c=At(i.servers)?i.servers[pn]:void 0;if(!PA(c,n))return{registered:!1,command:null,reason:c===void 0?"absent":sl(c,n)==="stale-owned"?"stale":"foreign"};o.push(c.command)}catch{return{registered:!1,command:null,reason:"unreadable"}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var QD=async(e={installedVariant:Uo,remoteServerVariant:Vp,isRemoteDevContext:Fr})=>{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}},eL={installedVariant:Uo,remoteServerVariant:Vp,detectVscodeLmProviderEligibility:qb,configureVscodeExtension:fA,vscodeExtensionPointsAt:mA,vscodeExtensionAwaitingReload:tl,vscodeExtensionReceiptMode:nl,hookBinaryIsDurable:te,hookBinaryPath:Oe,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:Xb,isRemoteDevContext:Fr},tL=(e={})=>{let t={...eL,...e},n=()=>QD(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Rs,quitTarget:rl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Wo(r,!0)}`:Os(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ee(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 ${Up} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||jb(i.version);return ee(r,"copilot")?XD(a,r,o,t.configureVscodeExtension,c,s,t):zD(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?qD(r,o,t):{registered:!1,command:null,reason:"no-config"}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Es(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await ol(Os(o));if(s.kind==="array"){let c=s.entries.find(tf)?.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 ol(Os(r));if(o.kind==="array"&&o.entries.some(tf))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 YD(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await RA(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${z} to clear its global configuration and SecretStorage key`);else{let g=await t.configureVscodeExtension(o,void 0,"reset");g.ok?(c=!0,d=g.receipt,u.push(`Cleared ${z} gateway configuration and secret.`)):(l=!0,u.push(JD(g.reason,o,a,g.detail)))}let p=Os(o),f=await ol(p),m=f.kind==="missing"||f.kind==="array"&&!nf(f.entries).removed,h=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),m)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:h.length?h:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:h.length?h:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:h,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(f.kind==="unrecognized")return{status:"manual",changedFiles:h.length?h:void 0,messages:[...u,`Couldn't recognize ${p} \u2014 remove the "${dr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=nf(f.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${dr} Custom Endpoint from ${p}`]};await xA(p,w);let y=[...u,`Removed the ${dr} Custom Endpoint from ${p}.`];return await oe(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,p],messages:y}}}},MA=tL();import{accessSync as _L,constants as zA,statSync as PL}from"node:fs";import{readFile as qA,rm as Ls}from"node:fs/promises";import{homedir as ff,platform as sC}from"node:os";import{delimiter as DL,join as mf,resolve as LL}from"node:path";import{execFile as sL}from"node:child_process";import{readFile as iL}from"node:fs/promises";import{homedir as af,platform as cL}from"node:os";import{join as Ds}from"node:path";import{join as nL}from"node:path";var rf="Iv1.b507a08c87ecfe98",rL="https://github.com/login/device/code",oL="https://github.com/login/oauth/access_token",aL="read:user",BA=1e4,Go=()=>nL(Q(),"copilot-seat-login.json"),FA={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},of=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),WA=async(e={})=>{let t={...FA,...e};try{let n=await t.fetch(rL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:rf,scope:aL}),signal:AbortSignal.timeout(BA)});if(!n.ok)return;let r=await n.json();if(!of(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}},UA=async(e,t={})=>{let n={...FA,...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(oL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:rf,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(BA)})).json();if(!of(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"}},HA=async(e,t)=>{let n=Go();return await we(n,`${JSON.stringify({token:e,clientId:rf,mintedAtIso:t},null,2)}
115
+ `),n},il=async()=>{try{let e=await M(Go());if(!of(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var lL=5e3,sf=5e3,dL=["copilot-cli","CopilotCLI"],uL="https://api.github.com/copilot_internal/user",VA="~/.copilot/config.json",KA="macOS Keychain (Copilot CLI)",jA=e=>e===VA||e===KA,Vo=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),Kt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pL=()=>process.env.XDG_CONFIG_HOME?.trim()||Ds(af(),".config"),fL=()=>process.env.XDG_DATA_HOME?.trim()||Ds(af(),".local","share"),mL=async()=>{try{let e=await iL(Ds(af(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return Vo(t)?t:void 0}catch{}},hL=async e=>{try{let t=await M(Ds(pL(),"github-copilot",e));if(!Kt(t))return;for(let n of Object.values(t))if(Kt(n)&&Vo(n.oauth_token))return n.oauth_token}catch{}},yL=async()=>{try{let e=await M(Ds(fL(),"opencode","auth.json")),t=Kt(e)?e["github-copilot"]:void 0;if(!Kt(t)||t.type!=="oauth")return;if(Vo(t.access))return t.access;if(Vo(t.refresh))return t.refresh}catch{}},gL=(e,t)=>new Promise((n,r)=>{try{sL(e,[...t],{timeout:lL},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),wL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return Vo(r)?r:void 0}catch{return}},bL=async(e=gL)=>{for(let t of dL){let n=await wL(t,e);if(n)return n}};var cl={env:process.env,platform:cL,tokenFromDeviceLogin:il,tokenFromCopilotCliConfig:mL,tokenFromSharedConfig:hL,tokenFromOpenCode:yL,tokenFromKeychain:bL,fetch:(...e)=>fetch(...e)},AL=new Set([401,403,404]),ll=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,ZA=e=>{let t=e?.trim().toLowerCase()??"";return t&&t!=="default"&&ll.test(t)?t:"default"},CL=e=>e!=="default"&&ll.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",kL=e=>{if(typeof e!="string")return"default";let t=e.trim().match(/^https:\/\/api\.([a-z0-9-]{1,63})\.githubcopilot\.com\/?$/)?.[1];return t&&ll.test(t)?t:"default"},cf=async(e,t={})=>{let n={...cl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),sf);try{let a=await n.fetch(uL,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=Kt(i)&&Kt(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:kL(s)}}return{verdict:AL.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var Ko=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${ll.test(n)?n:"default"}/header/models`,a=await GA(o,e,r.clientKey,t);if(a.length>0)return a}return GA(`${CL(n)}/models`,e,void 0,t)},GA=async(e,t,n,r={})=>{let o={...cl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),sf);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=Kt(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!Kt(u))continue;let p=u.id;if(typeof p!="string"||p.length===0||u.model_picker_enabled!==!0)continue;let f=u.policy;if(Kt(f)&&f.state!=="enabled")continue;let m=u.supported_endpoints,h=Array.isArray(m)?m.filter(S=>typeof S=="string"):[],w=u.capabilities,y=Kt(w)?w.limits:void 0,g=S=>{let I=Kt(y)?y[S]:void 0;return typeof I=="number"&&Number.isFinite(I)&&I>0?Math.floor(I):void 0},b={id:p,endpoints:h},k=g("max_prompt_tokens"),C=g("max_output_tokens");k!==void 0&&(b.maxPromptTokens=k),C!==void 0&&(b.maxOutputTokens=C),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},dl=async(e,t,n,r={})=>{let o={...cl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),sf);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)}},ul=async(e={},t={})=>{let n={...cl,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return Vo(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:KA,read:()=>n.tokenFromKeychain()}]:[],{source:VA,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await cf(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}};import{homedir as pl,platform as JA}from"node:os";import{join as st}from"node:path";import{execFile as vL}from"node:child_process";import{readFile as SL,readdir as IL}from"node:fs/promises";var EL=3e3,xL="Claude Code-credentials",RL=["copilot-cli","CopilotCLI"],XA=e=>new Promise(t=>{try{vL("security",["find-generic-password","-s",e],{timeout:EL},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),OL=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=st(pl(),".claude");return!!(await x(st(e,".oauth_token"))||await x(st(e,".credentials.json"))||JA()==="darwin"&&await XA(xL))},TL=async()=>{let e=st(process.env.CODEX_HOME?.trim()||st(pl(),".codex"),"auth.json");if(!await x(e))return!1;try{let t=JSON.parse(await SL(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},YA=async e=>{try{return(await IL(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},lf=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of vs){let n=st(Ve(t),"User","globalStorage");if(await x(st(n,"github.copilot-chat"))||await x(st(n,"github.copilot")))return!0}let e=st(pl(),".config","github-copilot");if(await x(st(e,"apps.json"))||await x(st(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await YA(st(pl(),t,"extensions")))return!0;for(let t of vs){if(await YA(zb(t)))return!0;let n=st(Wo(t,!0),"globalStorage");if(await x(st(n,"github.copilot-chat"))||await x(st(n,"github.copilot")))return!0}if(JA()==="darwin"){for(let t of RL)if(await XA(t))return!0}return!1},fn=async()=>{let[e,t,n]=await Promise.all([OL(),TL(),lf()]);return{anthropic:e,openai:t,copilot:n}};var Xr="copilot-cli",mn="copilot-cli",NL=Rs,$L=()=>NL()?["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."]:[],iC=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],hf=()=>Object.fromEntries(iC.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),QA=()=>mf(ff(),".anyray","copilot-cli.sh"),cC="# Managed by anyray-connect. Do not source this file anywhere else.",eC=e=>e.split(/\r?\n/,1)[0]===cC,ML=["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",tC=e=>e.startsWith(`export ${fl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Tn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",BL=()=>Ps()[0],Ns=(e="default")=>`/copilot/${e}/header`,X9=Ns(),Yr=e=>e.replace(/\/+$/,""),FL=(e,t="default")=>`${Yr(e.openaiBaseUrl)}${Ns(t)}`,df=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),pf="claude-sonnet-5",WL=()=>{let e=Ps()[0];return e===_s?pf:e},lC=e=>e.endpoints.includes(Tn(e.id)==="responses"?"/responses":"/chat/completions"),yf=e=>{let t=e.filter(lC),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)=>nC(a.version,s.version)?-1:nC(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var nC=(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},rC=(e,t,n,r,o,a="default")=>{let s=ue({...e.metadata,tool:Xr}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...iC];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(FL(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Tn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...o?.maxPromptTokens?[`export COPILOT_PROVIDER_MAX_PROMPT_TOKENS='${o.maxPromptTokens}'`]:[],...o?.maxOutputTokens?[`export COPILOT_PROVIDER_MAX_OUTPUT_TOKENS='${o.maxOutputTokens}'`]:[],...i.length>0?[`export COPILOT_PROVIDER_HEADERS=${ve(i.join(`
116
+ `))}`]:[],`export ${fl}=${ve(n)}`]},uf=(e,t,n)=>{let r=ue({...e.metadata,tool:Xr});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Tn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${ve(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${fl}=${ve(n)}`]:[]]},UL=(e,t)=>t||!ee(e,"copilot"),oC=()=>{let e=ML.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).`]},aC=(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 ${Xr}\`), 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`."],HL=(e=process.env.PATH,t=sC())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(DL)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=LL(o,n);try{if(!PL(a).isFile())continue;return _L(a,t==="win32"?zA.F_OK:zA.X_OK),a}catch{}}},GL=()=>mf(ff(),".copilot","config.json"),On=()=>mf(ff(),".copilot","mcp-config.json"),Jr="anyray",VL=()=>({type:"local",...Ge("profile"),tools:["*"]}),ur=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),KL=async()=>{let e=On(),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&&!ur(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=(ur(t.mcpServers)?t.mcpServers:{})[Jr];return r!==void 0&&!Ot(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}},jL=async e=>{let t=On(),n=e.json,r=ur(n.mcpServers)?n.mcpServers:{};r[Jr]=VL(),n.mcpServers=r,await Y(t,n)},ZL=async()=>{let e=On(),t;try{let r=await M(e);if(!ur(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!ur(n)||!(Jr in n)||!Ot(n[Jr],"profile")?!1:(delete n[Jr],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Ls(e,{force:!0}):await Y(e,t,{backup:!1}),await oe(e),!0)},YL={resolveCopilotCommand:HL,platform:sC,detectCopilotSeat:lf,discoverSeatToken:ul,readDeviceLoginToken:il,fetchSeatModelCatalog:Ko,probeSeatChatModel:dl},JL=e=>`'${e.replace(/'/g,"''")}'`,XL=e=>e.split(`
117
+ `).map(JL).join(" + [Environment]::NewLine + "),zL=(e={})=>{let t={...YL,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Lc(gt(),mn))?.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&&Yr(s)===`${Yr(i)}/v1`,a=(s,i)=>s!==void 0&&df(s)&&Yr(s).startsWith(`${Yr(i)}/v1/copilot/`);return{id:Xr,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Rs,quitTarget:rl},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=GL();return await x(i)?{installed:!0,detail:i}:{installed:!1,detail:"no `copilot` on PATH and no ~/.copilot state"}},async apply(s,i){let c=gt(),l=async(S,I,E)=>{let R=S.filter(tC),N=S.filter(X=>!tC(X)),U=QA(),q=[...N,...R.length>0?[`[ -r ${ve(U)} ] && . ${ve(U)}`]:[]],de=await x(U),ce=de?await qA(U,"utf8"):void 0,K=ce===void 0||eC(ce);if(R.length>0&&!K)return{status:"manual",messages:[`Refused to overwrite user-managed ${U}; move or rename that file, then run Connect again.`]};let ge=te(),me=ge?await KL():void 0,F=[`${c} \u2190 managed Anyray block (${mn})`,...I.map(X=>` ${X}`),...R.length>0?[`${U} \u2190 owner-only credential (mode 0600)`]:[],...E,me?.status==="skipped"?me.message:ge?`${On()} \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.`,...$L()];if(i.dryRun)return{status:"configured",messages:F};let Z=!1;me?.status==="installable"&&(await jL(me),Z=!0);try{R.length>0?await we(U,[cC,...R,""].join(`
118
+ `)):de&&K&&await Ls(U,{force:!0}),await Dc(c,q,mn)}catch(X){try{ce!==void 0&&K?await we(U,ce):K&&await Ls(U,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw X}return{status:"configured",messages:F,changedFiles:[c,...R.length>0||de&&K?[U]:[],...Z?[On()]:[]]}},d=await r(),u=d!==void 0&&!df(d),p=s.authMode==="placeholder",f=u,m=u&&(!f||!ee(s,"copilot")),h=p?void 0:await t.readDeviceLoginToken().catch(()=>{}),w=p||m&&!h?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),y=w.token,g=w.rejected;if(y){let S=w.capiSegment??"default",I=WL(),E=I!==pf||!!process.env.ANYRAY_COPILOT_MODEL,R=await t.fetchSeatModelCatalog(y.token,{},S,{laneOrigin:Yr(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),N=R.find(F=>F.id===I);if(!E){let F=yf(R);if(N=F[0],!i.dryRun&&F.length>0){let Z=T=>`${Yr(s.origin)}/v1${Ns(S)}/${Tn(T)==="responses"?"responses":"chat/completions"}`,X={...hf(),authorization:`Bearer ${y.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},Je=new Set,We;for(let T of F.slice(0,4)){let D=await t.probeSeatChatModel(Z(T.id),X,T.id);if(D==="ok"){We=T;break}if(D==="unreachable")break;Je.add(T.id)}N=We??F.find(T=>!Je.has(T.id))??F[0]}I=N?.id??pf}let U=s.clientKey??s.placeholderKey,q=U&&s.clientKey?_t(U):U,de=rC(s,I,y.token,U,N,S),ce=rC(s,I,_t(y.token),q,N,S),K=Tn(I),ge=R.filter(F=>lC(F)&&Tn(F.id)===K).map(F=>F.id).filter(F=>F!==I),me=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${y.source}).`,`Model: ${I}${E?" (pinned via ANYRAY_COPILOT_MODEL)":R.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...R.length===0&&jA(y.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."]:[],...ge.length>0?[`Your plan also serves: ${ge.slice(0,8).join(", ")}${ge.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",...ce.map(F=>{let Z=F.indexOf("="),X=F.slice(7,Z),Je=F.slice(Z+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${X}', ${XL(Je)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${y.source}, and the gateway key from \`anyray-connect print-key\`.)`,...me]}:l(de,ce,me)}if(!UL(s,m)){if(f&&!i.dryRun){let S=gt();if(await fs(S,mn))return{status:"reverted",changedFiles:[S],messages:[`removed a stale Anyray ${mn} block from ${S}`,"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:",...aC(t.platform(),g),...oC()]}}return{status:"held",messages:[...f&&i.dryRun?[`would remove a stale Anyray ${mn} block from ${gt()} (org lane, not chosen)`]:[],...aC(t.platform(),g)]}}let b=BL(),k=s.clientKey??s.placeholderKey,C=k&&s.clientKey?_t(k):k;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...uf(s,b,C).map(S=>{let[I,...E]=S.replace(/^export /,"").split("=");return` setx ${I} "${E.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${fl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(uf(s,b,k),uf(s,b,C),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===_s?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=gt(),c=QA(),l=await x(c),d=l?eC(await qA(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${mn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${On()} if registered`,...await x(Go())?[`would remove the Copilot sign-in Connect minted (${Go()})`]:[]]};let u=await fs(i,mn);d&&await Ls(c,{force:!0});let p=await ZL(),f=Go(),m=await x(f);m&&await Ls(f,{force:!0});let h=[...u?[i]:[],...d?[c]:[],...p?[On()]:[],...m?[f]:[]];return{status:h.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${mn} block from ${i}`:`no Anyray ${mn} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...m?[`removed the Copilot sign-in Connect minted (${f})`]:[],...p?[`removed the Anyray MCP server from ${On()}`]:[],...oC()],changedFiles:h.length>0?h:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let s=On();if(!await x(s))return{registered:!1,command:null,reason:"no-config"};try{let i=await M(s),c=ur(i)?i.mcpServers:void 0,l=ur(c)?c[Jr]:void 0;return!ur(l)||!Ot(l,"profile")?{registered:!1,command:null,reason:l===void 0?"absent":"foreign"}:{registered:!0,command:typeof l.command=="string"?l.command:null}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async inferenceAuthLanes(){try{let s=await r();return s===void 0?["native"]:df(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(Xr)?!0:!await t.detectCopilotSeat()}}},dC=zL();import{homedir as gC}from"node:os";import{join as fr}from"node:path";import{readFile as wC}from"node:fs/promises";import{readFile as uC,rm as qL}from"node:fs/promises";var pC="// Managed by anyray-connect: OpenCode trim carrier v1",QL=5e3,gf=e=>`${pC}
119
119
  import { spawn } from "node:child_process"
120
120
 
121
121
  const hookCommand = ${JSON.stringify([e.command,...e.args])}
122
- const hookTimeoutMs = ${KL}
122
+ const hookTimeoutMs = ${QL}
123
123
 
124
124
  const invokeHook = (payload) =>
125
125
  new Promise((resolve) => {
@@ -186,24 +186,24 @@ export const AnyrayTrimPlugin = async () => ({
186
186
  }
187
187
  },
188
188
  })
189
- `,$s=async e=>await x(e)?(await cC(e,"utf-8")).startsWith(`${lC}
190
- `)?"owned":"foreign":"absent",dC=async(e,t)=>{let n=bf(t),r=await $s(e);return r==="foreign"?"foreign":r==="owned"&&await cC(e,"utf-8")===n?"unchanged":(await we(e,n),"installed")},Af=async e=>{let t=await $s(e);return t!=="owned"?t:(await VL(e,{force:!0}),"removed")};var Cf="https://opencode.ai/config.json",Pn="x-anyray-metadata",Pt="x-anyray-api-key",kf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Tn="Authorization",ur=["anthropic","openai"],Dn="github-copilot",jL="header",_n="anyray",ZL=()=>process.env.XDG_CONFIG_HOME?.trim()||pr(mC(),".config"),YL=()=>process.env.XDG_DATA_HOME?.trim()||pr(mC(),".local","share"),hl=()=>pr(ZL(),"opencode"),fl=()=>pr(hl(),"plugins","anyrayTrim.js"),yC=()=>pr(YL(),"opencode"),gC=async()=>{try{let e=await hC(pr(yC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return H(t)?{chatGptOAuth:H(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}}},uC=async()=>(await gC()).chatGptOAuth,JL=["opencode.jsonc","opencode.json","config.json"],jo=async()=>{let e=hl(),t=[];for(let n of JL){let r=pr(e,n);await x(r)&&t.push(r)}return t},pC=async()=>(await jo())[0]??pr(hl(),"opencode.json"),vf=()=>VA(process.env.ANYRAY_COPILOT_PLAN),Sf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${vf()}/${jL}`,H=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Of=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},XL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===ur[0]||n===ur[1]||n===Dn?[]:H(r)&&H(r.options)&&Of(r.options.baseURL,t)?[n]:[]),If=/claude/i,Tf=["model","small_model"],wC=(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)||!If.test(o)))return`${ur[0]}/${o}`},Ef=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Ef(n,t);return t}if(!H(e))return t;for(let[n,r]of Object.entries(e))Tf.includes(n)&&typeof r=="string"?t.push(r):Ef(r,t);return t},zL=(e,t,n)=>{if(!H(e)||!H(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>If.test(a)))return!1;let o=`${n}/`;return Ef(t).filter(a=>a.startsWith(o)).every(a=>If.test(a.slice(o.length)))},xf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>xf(o,t,n));if(!H(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Tf.includes(o)?wC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=xf(a,t,n)}return r},Rf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Rf(o,t[a],n));if(!H(e)||!H(t))return e;let r={};for(let[o,a]of Object.entries(e))Tf.includes(o)&&typeof a=="string"&&wC(t[o],n)===a?r[o]=t[o]:r[o]=Rf(a,t[o],n);return r},qL=e=>{if(H(e))for(let t of ur){let n=e[t];if(H(n)&&H(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Ms=e=>{if(!H(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Gt({command:t,args:n},"profile")},ml=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),QL=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return H(t)&&t.tool==="opencode"}catch{return!1}},_f=e=>ee(e,"copilot")&&!!e.clientKey,eN=e=>e.byoUpstream?[]:ee(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".`]:[],tN=(e,t)=>ee(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.`]:[],nN=e=>_f(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."]:[],rN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Cf);let o=!1;if(n)if("mcp"in r&&!H(r.mcp))o=!0;else{let g=H(r.mcp)?{...r.mcp}:{},b=g[_n];b!==void 0&&!Ms(b)?o=!0:(g[_n]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=g)}else if(H(r.mcp)&&Ms(r.mcp[_n])){let g={...r.mcp};delete g[_n],Object.keys(g).length===0?delete r.mcp:r.mcp=g}let a=H(r.provider)?{...r.provider}:{},s=XL(a,t.origin),i=s.every(g=>zL(a[g],e,g))?s:[],c=s.filter(g=>!i.includes(g)),l=[];if(i.length>0){for(let g of i)delete a[g];r=xf(r,i,l)}let d=[],u=[],p=t.openaiBaseUrl,f=t.clientKey??t.placeholderKey,m=ue({...t.metadata,tool:"opencode"});for(let g of c){let b={...a[g]},k={...b.options};if("headers"in k&&!H(k.headers)){u.push(g);continue}let C=H(k.headers)?{...k.headers}:{},S=!1;for(let[I,E]of[[Pt,f],...m?[[Pn,m]]:[]])I in C?(typeof C[I]!="string"||C[I].trim()==="")&&u.push(`${g}.${I}`):(C[I]=E,d.push(`${g}.${I}`),S=!0);S&&(k.headers=C,b.options=k,a[g]=b)}let h=c.length>0?[]:ur.filter(g=>g!=="openai"||!ee(t,"openai")),w=t.byoUpstream;for(let g of h){let b=H(a[g])?{...a[g]}:{},k=H(b.options)?{...b.options}:{};k.baseURL=p;let C=H(k.headers)?{...k.headers}:{};if(g==="anthropic"&&w)k.apiKey=w.key,C[Tn]=`Bearer ${w.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=w.url;else{k.apiKey=f,"x-anyray-custom-host"in C&&delete C[Tn];for(let S of kf)delete C[S]}C[Pt]=f,m&&(C[Pn]=m),k.headers=C,b.options=k,a[g]=b}let y=c.length===0&&_f(t);if(y){let g=H(a[Dn])?{...a[Dn]}:{},b=H(g.options)?{...g.options}:{};b.baseURL=Sf(t);let k=H(b.headers)?{...b.headers}:{};k[Pt]=t.clientKey,m&&(k[Pn]=m),b.headers=k,g.options=b,a[Dn]=g}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:y,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},oN=["baseURL","apiKey"],fC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!H(s)||!H(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=H(c.headers)?{...c.headers}:void 0,p=u?.[Pt],f=ml(p);if(d&&(delete c.baseURL,l=!0),u&&(d||f)){let m=u,h=H(r)?r.options:void 0,w=H(h)&&H(h.headers)?h.headers:void 0;for(let y of[Pt,Pn])w&&y in w?m[y]!==w[y]&&(m[y]=w[y],l=!0):y in m&&(delete m[y],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}else{let d=H(r)?r.options:void 0,u=H(d)?d:{},p=H(c.headers)?c.headers:{},f=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof p[Pt]=="string"||typeof p[Pn]=="string"||kf.some(m=>m in p);if(!o&&!f)return!1;for(let m of oN)m in u?c[m]!==u[m]&&(c[m]=u[m],l=!0):m in c&&(delete c[m],l=!0);if(H(c.headers)){let m={...c.headers},h=H(u.headers)?u.headers:{};"x-anyray-custom-host"in m&&Tn in m&&(Tn in h?m[Tn]!==h[Tn]&&(m[Tn]=h[Tn],l=!0):(delete m[Tn],l=!0));for(let w of[Pt,Pn,...kf])w in h?m[w]!==h[w]&&(m[w]=h[w],l=!0):w in m&&(delete m[w],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}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},aN=(e,t,n)=>{let r=e[t];if(!H(r)||!H(r.options)||!H(n)||!H(n.options))return!1;let o={...r.options};if(!H(o.headers)||"headers"in n.options&&!H(n.options.headers))return!1;let a={...o.headers},s=H(n.options.headers)?n.options.headers:{},i=!1;return!(Pt in s)&&ml(a[Pt])&&(delete a[Pt],i=!0),!(Pn in s)&&QL(a[Pn])&&(delete a[Pn],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},sN=(e,t)=>{let n={...e},r=!1,o=qL(e.provider);if(H(n.mcp)&&Ms(n.mcp[_n])){let c={...n.mcp};delete c[_n],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!H(n.provider))return{next:n,removed:r};let a={...n.provider},s=H(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Cf&&ur.every(c=>{let l=a[c];return H(l)&&H(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of ur)fC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...ur,Dn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;aN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&H(u)&&H(u.options)&&Of(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Rf(n,t,l))}return fC(a,Dn,!0,s[Dn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Cf&&(delete n.$schema,r=!0),{next:n,removed:r}},bC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=hl(),t=yC(),n=await x(e)||await x(t),r=n&&await uC();return{installed:n,detail:n?`${await pC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await pC(),r=e.openaiBaseUrl,o=ue({...e.metadata,tool:"opencode"}),a=_f(e),s=ee(e,"openai"),i=await uC(),c;try{c=await je(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(Sf(e))}, "headers": { "${Pt}": "<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:p,modelRefsRemapped:f,customHeadersAdded:m,customHeaderConflicts:h,mcpConflict:w}=rN(c.data,e,l),y=u.length>0,g=p.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${p.map(E=>`provider.${E}`).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.`,...f.length>0?[`Updated model references: ${f.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=y?[`${n} already routes through ${e.origin} via ${u.map(E=>`provider.${E}`).join(", ")}; existing provider values were preserved.`,m.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${m.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...h.length>0?[`Could not safely add required headers at ${h.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."]:[...g,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)"}`,...eN(e),...tN(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Sf(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. ${vf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${vf()} 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).",...nN(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${_n} 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 k=h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let S=await sn(n,c,d,!0)?[n]:[],I=fl();if(ce())try{let E=await dC(I,ts(ze,["opencode"]));E==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${I} already exists and is not owned by Anyray.`):(E==="installed"&&S.push(I),b.push(`The OpenCode tool.execute.after carrier is active in ${I}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${I}. Gateway-side optimization remains active.`)}else{try{await Af(I)==="removed"&&S.push(I)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:k,messages:b,changedFiles:S}},async pointsAt(e){for(let t of await jo())try{let{data:n}=await je(t);if(!H(n.provider))continue;for(let r of Object.values(n.provider))if(!(!H(r)||!H(r.options))&&Of(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await jo())try{let{data:t}=await je(e);if(!H(t.mcp))continue;let n=t.mcp[_n];if(!Ms(n)||!H(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 $s(fl());e=i==="absent"?"missing":i,e==="owned"&&(t=await hC(fl(),"utf-8")===bf(ts(ze,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await jo()){let c;try{c=await je(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!H(c.data.mcp)){o=!0;continue}let l=c.data.mcp[_n];if(l!==void 0)if(Ms(l))if(n=!0,!H(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;rc({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 gC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await jo()){let{data:o}=await je(r);if(H(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!H(s)||!H(s.options)){e.add("unknown");continue}let i=s.options,c=H(i.headers)?i.headers:{};if(a===Dn&&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===Dn&&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[Pt])||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 jo(),n=fl(),r="absent";try{r=await $s(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 je(i)}catch{s.push(i);continue}let{next:l,removed:d}=sN(c.data,await Bo(i));d&&(await sn(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 Af(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 Bf}from"node:os";import{join as Cl}from"node:path";import{homedir as iN}from"node:os";import{dirname as cN,join as fr}from"node:path";import{mkdir as lN,readdir as dN,readFile as CC,rm as kC}from"node:fs/promises";var Pf="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",AC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJEZXBlbmRlbmNpZXMiOiB7CiAgICAib3BlbmNsYXciOiAiPj0yMDI2LjcuMSIKICB9LAogICJkZXZEZXBlbmRlbmNpZXMiOiB7CiAgICAidHN4IjogIl40LjIzLjEyIiwKICAgICJ0eXBlc2NyaXB0IjogIl41LjYuMyIKICB9Cn0K"},{path:"src/index.ts",contentBase64:"LyoqCiAqIEFueXJheSBPcGVuQ2xhdyBwbHVnaW4g4oCUIHJvdXRlcyBPcGVuQ2xhdydzIG1vZGVsIGNhbGxzIHR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Wyd4LWFueXJheS1wcm92aWRlciddID0gZ2F0ZXdheVByb3ZpZGVyOwogICAgfQogICAgb3B0cy5oZWFkZXJzID0gaGVhZGVyczsKICAgIGNvbnN0IHNlc3Npb25JZCA9CiAgICAgIHR5cGVvZiBvcHRzLnNlc3Npb25JZCA9PT0gJ3N0cmluZycgPyBvcHRzLnNlc3Npb25JZCA6IHVuZGVmaW5lZDsKICAgIGNvbnN0IGNhbGxlck9uUGF5bG9hZCA9IG9wdHMub25QYXlsb2FkOwogICAgb3B0cy5vblBheWxvYWQgPSBhc3luYyAocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA9PiB7CiAgICAgIGlmIChwYXlsb2FkICYmIHR5cGVvZiBwYXlsb2FkID09PSAnb2JqZWN0JyAmJiAhQXJyYXkuaXNBcnJheShwYXlsb2FkKSkgewogICAgICAgIHBhdGNoUGF5bG9hZFNlc3Npb25JZGVudGl0eSgKICAgICAgICAgIHBheWxvYWQgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4sCiAgICAgICAgICBzZXNzaW9uSWQKICAgICAgICApOwogICAgICB9CiAgICAgIHJldHVybiBjYWxsZXJPblBheWxvYWQgPyBjYWxsZXJPblBheWxvYWQocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Df=".anyray-source-sha",hn=()=>fr(iN(),".anyray","openclaw-plugin"),vC=async(e=hn())=>{try{if((await CC(fr(e,Df),"utf8")).trim()===Pf)return"current"}catch{}for(let t of AC){let n=fr(e,t.path);await lN(cN(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(fr(e,Df),`${Pf}
191
- `),"installed"},Bs=async(e,t=[])=>{let n=[],r=async a=>{let s=fr(a,"plugins","anyray","catalog.json");try{await kC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await dN(fr(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(fr(e,"agents",a,"agent"));return n},yl=async(e=hn())=>{try{await CC(fr(e,Df),"utf8")}catch{return!1}return await kC(e,{recursive:!0,force:!0}),!0};var Nf="x-anyray-metadata",Jo="x-anyray-api-key",$f=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],zr="Authorization",qr="anthropic-beta",wl="interleaved-thinking-2025-05-14",bl=["anthropic","openai"],IC="short",Ff="anthropic-messages",Wf=32e3,Al="anthropic/claude-sonnet-4-5",Hf=["anthropic/claude-haiku-4-5"],Uf="anyray/claude-sonnet-4-5",Gf=["anyray/claude-haiku-4-5"],uN=[Al,Uf],pN=[Hf,Gf],qe="anyray",mr="ANYRAY_API_KEY",Fs="openclaw",Yo=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Cl(Bf(),".openclaw"),Zo=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Cl(Yo(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),SC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Mf=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},fN=e=>e==="~"||e.startsWith("~/")?Cl(Bf(),e.slice(1)):e,gl=e=>{if(!N(e))return[];let t=e.agents;if(!N(t)||!Array.isArray(t.list))return[];let n=[];for(let r of t.list){if(!N(r))continue;let o=typeof r.agentDir=="string"?r.agentDir.trim():"";o&&n.push(fN(o))}return n},mN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=ue({...t.metadata,tool:Fs}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!N(l.models)&&d.push("models");let u=N(l.models)?{...l.models}:{};if("providers"in u&&!N(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let p=N(u.providers)?{...u.providers}:{},f=!1;if(n){let C=N(l.plugins)?{...l.plugins}:{},S=N(C.load)?{...C.load}:{},I=N(C.entries)?{...C.entries}:{},E=N(I[qe])?{...I[qe]}:{},R=N(E.config)?{...E.config}:{};if("plugins"in l&&!N(l.plugins)||"load"in C&&!N(C.load)||"paths"in S&&!Array.isArray(S.paths)||"entries"in C&&!N(C.entries)||qe in I&&!N(I[qe])||"config"in E&&!N(E.config)||"env"in l&&!N(l.env))d.push("plugins");else{let P=Array.isArray(S.paths)?[...S.paths]:[];P.includes(n)||P.push(n),S.paths=P,C.load=S,E.enabled=!0,R.gatewayUrl=t.anthropicBaseUrl,R.apiKey=r;let W=t.metadata.user,q=t.metadata.team;W&&(R.user=W),q&&(R.team=q),E.config=R,I[qe]=E,C.entries=I,l.plugins=C;let de=N(l.env)?{...l.env}:{};de[mr]=r,l.env=de,f=!0}}let m=bl.filter(C=>C!=="openai"||!ee(t,"openai"));for(let C of m){if(C in p&&!N(p[C])){d.push(`models.providers.${C}`);continue}let S=N(p[C])?{...p[C]}:{};if("headers"in S&&!N(S.headers)){i.push(C);continue}let I=N(S.headers)?{...S.headers}:{};if(S.baseUrl=C==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,C==="anthropic"&&(S.api=Ff,(typeof S.maxTokens!="number"||S.maxTokens<=0)&&(S.maxTokens=Wf)),C==="anthropic"&&a)S.apiKey=a.key,I[zr]=`Bearer ${a.key}`,I["x-anyray-provider"]="anthropic",I["x-anyray-auth-mode"]="passthrough",I["x-anyray-custom-host"]=a.url;else{S.apiKey=r,"x-anyray-custom-host"in I&&delete I[zr];for(let E of $f)delete I[E]}I[Jo]=r,o&&(I[Nf]=o),C==="anthropic"&&(qr in I?c=I[qr]!==wl:I[qr]=wl),S.headers=I,p[C]=S,s.push(C)}u.providers=p,l.models=u;let h=!1,w=!1,y=!1,g,b=[],k="agents"in l&&!N(l.agents)||N(l.agents)&&"defaults"in l.agents&&!N(l.agents.defaults)||N(l.agents)&&N(l.agents.defaults)&&("params"in l.agents.defaults&&!N(l.agents.defaults.params)||"model"in l.agents.defaults&&!N(l.agents.defaults.model));if(k&&d.push("agents.defaults"),s.includes("anthropic")&&!k){let C=N(l.agents)?{...l.agents}:{},S=N(C.defaults)?{...C.defaults}:{},I=N(S.params)?{...S.params}:{};"cacheRetention"in I||(I.cacheRetention=IC,h=!0,S.params=I);let E=N(S.model)?{...S.model}:{},R=f?[...s,qe]:s,P=W=>typeof W=="string"&&R.some(q=>W.startsWith(`${q}/`));typeof E.primary!="string"||E.primary.trim()===""?(E.primary=f?Uf:Al,w=!0,S.model=E,"fallbacks"in E||(E.fallbacks=f?[...Gf]:[...Hf],y=!0)):P(E.primary)||(g=E.primary),b=(Array.isArray(E.fallbacks)?E.fallbacks:[]).filter(W=>typeof W=="string"&&!P(W)),(h||w)&&(C.defaults=S,l.agents=C)}return{next:l,routed:s,cacheRetentionSeeded:h,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:y,unroutedPrimary:g,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:f}},hN=["baseUrl","apiKey","api","maxTokens"],Lf=(e,t,n=bl,r)=>{let o={...e},a=!("models"in o)||N(o.models)&&(!("providers"in o.models)||N(o.models.providers)),s=N(o.models)?{...o.models}:{},i=N(s.providers)?{...s.providers}:{},c=Mf(t),l=!1;for(let u of a?n:[]){let p=i[u];if(!N(p))continue;let f={...p},m=N(f.headers)?{...f.headers}:{};if(!(t!==void 0||typeof m[Jo]=="string"||typeof m[Nf]=="string"||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_")||$f.some(C=>C in m)))continue;let w=N(c[u])?c[u]:{},y=N(w.headers)?w.headers:{},g="x-anyray-custom-host"in m,b=C=>C==="api"?f.api===Ff:C==="maxTokens"?f.maxTokens===Wf:C==="apiKey"?g||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_"):!0;for(let C of hN)b(C)&&(C in w?f[C]!==w[C]&&(f[C]=w[C],l=!0):C in f&&(delete f[C],l=!0));let k=[Jo,Nf,...$f,..."x-anyray-custom-host"in m?[zr]:[]];m[qr]===wl&&k.push(qr);for(let C of k)C in y?m[C]!==y[C]&&(m[C]=y[C],l=!0):C in m&&(delete m[C],l=!0);zr in y&&!(zr in m)&&(m[zr]=y[zr],l=!0),Object.keys(m).length===0?delete f.headers:f.headers=m,Object.keys(f).length===0?delete i[u]:i[u]=f}if(a&&(Object.keys(i).length===0?delete s.providers:s.providers=i,Object.keys(s).length===0?delete o.models:o.models=s),r&&n.includes("anthropic")){let u=N(o.plugins)?{...o.plugins}:{},p=N(u.load)?{...u.load}:{},f=N(u.entries)?{...u.entries}:{};if((!("plugins"in o)||N(o.plugins))&&(!("load"in u)||N(u.load))&&(!("paths"in p)||Array.isArray(p.paths))&&(!("entries"in u)||N(u.entries))){if(Array.isArray(p.paths)&&p.paths.includes(r)){let w=p.paths.filter(y=>y!==r);w.length===0?delete p.paths:p.paths=w,l=!0}let h=f[qe];if(N(h)){let w=N(h.config)?h.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let g=N(t?.plugins)?t.plugins:{},b=N(g.entries)?g.entries:{};qe in b?JSON.stringify(f[qe])!==JSON.stringify(b[qe])&&(f[qe]=b[qe],l=!0):(delete f[qe],l=!0)}}if(Object.keys(p).length===0?delete u.load:u.load=p,Object.keys(f).length===0?delete u.entries:u.entries=f,Object.keys(u).length===0?delete o.plugins:o.plugins=u,N(o.env)){let w={...o.env},y=w[mr];if(typeof y=="string"&&y.startsWith("ark_")){let g=N(t?.env)?t.env:{};mr in g?w[mr]!==g[mr]&&(w[mr]=g[mr],l=!0):(delete w[mr],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||N(o.agents)&&(!("defaults"in o.agents)||N(o.agents.defaults)&&(!("params"in o.agents.defaults)||N(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||N(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=N(o.agents)?{...o.agents}:{},p=N(u.defaults)?{...u.defaults}:{},f=N(p.params)?{...p.params}:{},m=N(t.agents)?t.agents:{},h=N(m.defaults)?m.defaults:{},w=N(h.params)?h.params:{};f.cacheRetention===IC&&("cacheRetention"in w?f.cacheRetention!==w.cacheRetention&&(f.cacheRetention=w.cacheRetention,l=!0):(delete f.cacheRetention,l=!0));let y=N(p.model)?{...p.model}:{},g=N(h.model)?h.model:{};uN.includes(y.primary)&&("primary"in g?y.primary!==g.primary&&(y.primary=g.primary,l=!0):(delete y.primary,l=!0)),pN.some(b=>JSON.stringify(y.fallbacks)===JSON.stringify(b))&&("fallbacks"in g?JSON.stringify(y.fallbacks)!==JSON.stringify(g.fallbacks)&&(y.fallbacks=g.fallbacks,l=!0):(delete y.fallbacks,l=!0)),Object.keys(y).length===0?delete p.model:p.model=y,Object.keys(f).length===0?delete p.params:p.params=f,Object.keys(p).length===0?delete u.defaults:u.defaults=p,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},EC={id:Fs,title:"OpenClaw",automatic:!0,async detect(){let e=await x(Zo())||await x(Yo());return{installed:e,detail:e?Zo():`no ${Cl(Bf(),".openclaw")} state dir`}},async apply(e,t){let n=Zo();if(!e.byoUpstream&&ee(e,"anthropic")){let S=["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 ${Fs}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],I;try{I=await je(n)}catch{return{status:"held",messages:S}}let{next:E,removed:R}=Lf(I.data,await Bo(n),bl,hn());return R?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...S]}:(await sn(n,I,E,!1),await re(n),await yl(),await Bs(Yo(),gl(E)),{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.`,...S]}):(t.dryRun||(await yl(),await Bs(Yo(),gl(E))),{status:"held",messages:S})}let r=hn(),o=!1;if(!t.dryRun)try{await vC(r)}catch{r=void 0,o=!0}let a;try{a=await je(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Ff}", "maxTokens": ${Wf}, "apiKey": "<your personal ark_ key>", "headers": { "${Jo}": "<your personal ark_ key>", "${qr}": "${wl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${Jo}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Al}") 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:p,unroutedPrimary:f,unroutedFallbacks:m,structureConflicts:h,pluginConfigured:w}=mN(a.data,e,r),y=s,g=!1;if(!i.includes("openai")){let S=Lf(y,await Bo(n),["openai"]);S.removed&&(y=S.next,g=!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: ${ue({...e.metadata,tool:Fs})??"(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 ${qr} 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?Uf:Al} (none was set; routing is inert until the primary resolves to a routed provider).`,...p?[`Seeded agents.defaults.model.fallbacks = [${(w?Gf:Hf).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...f!==void 0?[`Your primary model (${f}) 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.`]:[],...m.length>0?[`Fallback model(s) ${m.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...g?["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 (${hn()}) and registered it under plugins.entries.${qe}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${hn()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...h.length>0?[`Left ${h.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."],k=d.length>0||h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let C=await sn(n,a,y,!0);return w&&await Bs(Yo(),gl(y)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await je(Zo());for(let a of Object.values(Mf(t)))if(N(a)&&SC(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[qe];if(N(o)&&N(o.config)&&SC(o.config.gatewayUrl,e))return!0}catch{}return!1},async routingExpected(e){return e.includes(Fs)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await je(Zo());for(let a of Object.values(Mf(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[Jo]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[qe];if(N(o)&&N(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=Zo();if(!await x(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 je(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}=Lf(n.data,await Bo(t),bl,hn()),a=await yl();return await Bs(Yo(),gl(r)),o?(await sn(t,n,r,!1),await re(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]],changedFiles:[t]}):(await re(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]]})}};import{execFile as aB}from"node:child_process";import{readFile as sB}from"node:fs/promises";import{homedir as oi,platform as wr}from"node:os";import{join as bn}from"node:path";import{isDeepStrictEqual as Om,promisify as iB}from"node:util";var Ws=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},kl=(e,t)=>{let n=Ws(e),r=Ws(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 kM}from"node:crypto";import{promises as Bk}from"node:fs";import{platform as vM,tmpdir as SM}from"node:os";import{join as Wl}from"node:path";import{execFile as yN}from"node:child_process";import{promises as Hs}from"node:fs";import{homedir as gN,platform as wN}from"node:os";import{delimiter as bN,join as vl}from"node:path";import{promisify as AN}from"node:util";var CN=AN(yN),kN=15*6e4,vN=64*1024*1024,SN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],xC=async(e={})=>{let t=(e.home??gN)(),n=e.env??process.env,r=SN(e.runtimePlatform??wN()),o=[vl(t,".local","bin"),vl(t,".claude","local"),...(n.PATH??"").split(bN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=vl(a,`claude${s}`);try{return await Hs.access(i),i}catch{}}return null},IN=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},EN=async e=>{let t=vl(e,"projects"),n;try{n=(await Hs.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(!ON.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},xN=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],p=o[d];if(typeof u!="string"||typeof p!="string"||u.length===0||p.length===0)continue;let f=a[d];l.push({sessionId:u,transcriptPath:p,title:typeof f=="string"&&f.length>0?f:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:IN(n.projectList)}},RN=async e=>{let t,n;try{let r=await Hs.readFile(e,"utf8");for(let o of r.split(`
192
- `)){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}},ON=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,TN=/\.(?:cmd|bat)$/i,_N=(e,t)=>TN.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},RC=async(e,t={})=>{let n=t.exec??CN,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 Hs.mkdir(e.configDir,{recursive:!0,mode:448}),await Hs.mkdir(e.workDir,{recursive:!0,mode:448});let o=_N(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:kN,maxBuffer:vN,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(`
193
- `).filter(d=>d.trim().length>0),i=xN(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 RN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await EN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as PN}from"node:crypto";import{promises as Ln}from"node:fs";import{homedir as DN,platform as LN}from"node:os";import{join as Ct}from"node:path";var OC=448,Nn="local_",NN="local-agent-mode-sessions",Vf="-3p",$N="cowork_account_settings.json",Qr=(e={})=>{let t=(e.home??DN)(),n=e.runtimePlatform??LN(),r=e.env??process.env;if(n==="darwin")return Ct(t,"Library","Application Support",`Claude${Vf}`);if(n==="win32"){let o=r.LOCALAPPDATA??Ct(t,"AppData","Local");return Ct(o,`Claude${Vf}`)}return null},Us=(e={})=>{let t=Qr(e);return t?t.slice(0,-Vf.length):null},Kf=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)}`},Sl=async e=>{let t=Ct(e,NN),n;try{n=(await Ln.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 Ln.readdir(Ct(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=Ct(t,o,s);try{await Ln.access(Ct(i,$N)),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]}},jf=async e=>{try{let t=await Ln.readdir(e);return new Set(t.filter(n=>n.startsWith(Nn)&&n.endsWith(".json")).map(n=>n.slice(Nn.length,-5)))}catch{return new Set}},Xo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),MN=async(e,t)=>{let n=`${Nn}${t.sessionId}`,r=Ct(e,n),o=Ct(r,"outputs"),a=Ct(r,".claude"),s=Ct(a,"projects",Kf(o));await Ln.mkdir(o,{recursive:!0,mode:OC}),await Ln.mkdir(s,{recursive:!0,mode:OC});let i=Ct(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${PN()}`;await Ln.copyFile(t.transcriptPath,c),await Ln.chmod(c,384),await Ln.rename(c,i);let l=t.createdAt??Date.now();await Y(Ct(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})},TC=async(e,t)=>{let n=await jf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!Xo(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await MN(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as zo}from"node:fs";import{homedir as BN}from"node:os";import{dirname as FN,join as Gs}from"node:path";var WN=448,HN=["Documents","Claude","Projects"],UN="spaces.json",GN=(e={})=>Gs((e.home??BN)(),...HN),VN=async e=>{try{let t=JSON.parse(await zo.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}}},KN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Zf=async e=>{try{return await zo.access(e),!0}catch{return!1}},jN=async(e,t,n)=>{let r=Gs(t,KN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Zf(r)?o:r;return a===o&&await Zf(o)?null:(await zo.mkdir(FN(a),{recursive:!0}),await zo.cp(e,a,{recursive:!0}),a)},ZN=async e=>{try{let t=(await zo.readFile(Gs(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},_C=async e=>{let t=GN({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=Gs(e.storageDir,UN),{spaces:a,readable:s}=await VN(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=Gs(e.stagedProjectsDir,l.dirName);try{if(!await Zf(d)){n.failed+=1;continue}let u=await jN(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await ZN(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...p?{instructions:p}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await zo.mkdir(e.storageDir,{recursive:!0,mode:WN}),await Y(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as zN}from"node:crypto";import{execFile as qN,spawnSync as UC}from"node:child_process";import{constants as GC}from"node:fs";import{access as Tl,chmod as QN,mkdir as e$,readdir as t$,readFile as Jf,rename as n$,rm as qo,stat as VC,writeFile as r$}from"node:fs/promises";import{homedir as o$,platform as a$,userInfo as s$}from"node:os";import{basename as i$,dirname as KC,isAbsolute as Qo,join as Dt,resolve as $C}from"node:path";import{isDeepStrictEqual as Ks,promisify as c$}from"node:util";var hr="__anyray-claude-desktop-credential",Vs="__anyray-claude-desktop-bootstrap-headers";var Il=["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>`."],El=["Your Claude account conversations are reachable in the app again once it reopens.","Chats made while third-party mode was active stay in its separate profile and come back if you configure it again."],PC="Note: third-party mode runs in a separate app profile, so Claude Desktop starts with empty conversation lists while it is active. Nothing is lost \u2014 local sessions come across on their own once the profile is signed in to and Claude Desktop is fully quit (see any queued migration above), claude.ai chats need your data export via `anyray-connect migrate --export <file.zip>`, and `anyray-connect desktop disconnect` restores the first-party profile.";var xl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],DC=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapHeaders","bootstrapHeadersHelper","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"],YN=new Set(DC),JN=new Set(DC.map(e=>e.toLowerCase())),XN=new Set(xl.map(e=>e.toLowerCase())),Rl=(e,t=!1)=>(t?JN:YN).has(t?e.toLowerCase():e),LC=(e,t=!1)=>t?XN.has(e.toLowerCase()):xl.some(n=>n===e),NC=["*"],eo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...NC]}),yr=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var js=/^[a-f0-9-]{36}$/,jC="Anyray",Xf=4,Js=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],Xs=["deploymentMode","awaitingSignIn"],ZC=[...Js,...Xs,"configLibrary","_meta.json"],yn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),it=e=>structuredClone(e),Zs=async e=>{try{return await Tl(e),!0}catch{return!1}},l$=async e=>{try{let t=await t$(KC(e)),n=i$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},d$=async e=>{try{return await Tl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":l$(e)}},jt=(e={})=>{let t=(e.home??o$)(),n=(e.username??(()=>s$().username))(),r=Dt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Dt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Dt(r,"configLibrary"),meta:Dt(r,"configLibrary","_meta.json"),appConfig:Dt(r,"claude_desktop_config.json"),helper:Dt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Dt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},_l=()=>{let e=UC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},YC=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],u$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...YC(t)]}},zf=(e="json")=>{let t=en(YC(e)),n=$C(t.command),r=$C(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ce()&&(!o||r!==n)}},p$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,qf=e=>[e.command,...e.args].map(p$).join(" "),f$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!Qo(e.command))throw new Error("the credential helper executable is not absolute")},JC=(e,t)=>{f$(e);let n=Pl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!Qo(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},XC=e=>(JC(e,"--json"),`#!/bin/sh
194
- exec ${qf(e)}
195
- `),m$=`#!/bin/sh
196
- # Anyray subscription pass-through credential helper v2 for Claude Desktop`,zC=e=>{JC(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),hr]};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 ${qf(t)}`,""].join(`
197
- `)},h$=e=>e.args.at(-1)==="--passthrough-headers"?zC(e):XC(e),Pl=e=>/[\\/](node|node\.exe)$/i.test(e),Qf=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++}},y$=e=>{let t=`#!/bin/sh
189
+ `,$s=async e=>await x(e)?(await uC(e,"utf-8")).startsWith(`${pC}
190
+ `)?"owned":"foreign":"absent",fC=async(e,t)=>{let n=gf(t),r=await $s(e);return r==="foreign"?"foreign":r==="owned"&&await uC(e,"utf-8")===n?"unchanged":(await we(e,n),"installed")},wf=async e=>{let t=await $s(e);return t!=="owned"?t:(await qL(e,{force:!0}),"removed")};var bf="https://opencode.ai/config.json",Dn="x-anyray-metadata",Dt="x-anyray-api-key",Af=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],_n="Authorization",pr=["anthropic","openai"],Ln="github-copilot",eN="header",Pn="anyray",tN=()=>process.env.XDG_CONFIG_HOME?.trim()||fr(gC(),".config"),nN=()=>process.env.XDG_DATA_HOME?.trim()||fr(gC(),".local","share"),yl=()=>fr(tN(),"opencode"),ml=()=>fr(yl(),"plugins","anyrayTrim.js"),bC=()=>fr(nN(),"opencode"),AC=async()=>{try{let e=await wC(fr(bC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return W(t)?{chatGptOAuth:W(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}}},mC=async()=>(await AC()).chatGptOAuth,rN=["opencode.jsonc","opencode.json","config.json"],jo=async()=>{let e=yl(),t=[];for(let n of rN){let r=fr(e,n);await x(r)&&t.push(r)}return t},hC=async()=>(await jo())[0]??fr(yl(),"opencode.json"),Cf=()=>ZA(process.env.ANYRAY_COPILOT_PLAN),kf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Cf()}/${eN}`,W=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},oN=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===pr[0]||n===pr[1]||n===Ln?[]:W(r)&&W(r.options)&&xf(r.options.baseURL,t)?[n]:[]),vf=/claude/i,Rf=["model","small_model"],CC=(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)||!vf.test(o)))return`${pr[0]}/${o}`},Sf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Sf(n,t);return t}if(!W(e))return t;for(let[n,r]of Object.entries(e))Rf.includes(n)&&typeof r=="string"?t.push(r):Sf(r,t);return t},aN=(e,t,n)=>{if(!W(e)||!W(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>vf.test(a)))return!1;let o=`${n}/`;return Sf(t).filter(a=>a.startsWith(o)).every(a=>vf.test(a.slice(o.length)))},If=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>If(o,t,n));if(!W(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Rf.includes(o)?CC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=If(a,t,n)}return r},Ef=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Ef(o,t[a],n));if(!W(e)||!W(t))return e;let r={};for(let[o,a]of Object.entries(e))Rf.includes(o)&&typeof a=="string"&&CC(t[o],n)===a?r[o]=t[o]:r[o]=Ef(a,t[o],n);return r},sN=e=>{if(W(e))for(let t of pr){let n=e[t];if(W(n)&&W(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Ms=e=>{if(!W(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Ot({command:t,args:n},"profile")},hl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),iN=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return W(t)&&t.tool==="opencode"}catch{return!1}},Of=e=>ee(e,"copilot")&&!!e.clientKey,cN=e=>e.byoUpstream?[]:ee(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".`]:[],lN=(e,t)=>ee(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.`]:[],dN=e=>Of(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."]:[],uN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=bf);let o=!1;if(n)if("mcp"in r&&!W(r.mcp))o=!0;else{let g=W(r.mcp)?{...r.mcp}:{},b=g[Pn];b!==void 0&&!Ms(b)?o=!0:(g[Pn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=g)}else if(W(r.mcp)&&Ms(r.mcp[Pn])){let g={...r.mcp};delete g[Pn],Object.keys(g).length===0?delete r.mcp:r.mcp=g}let a=W(r.provider)?{...r.provider}:{},s=oN(a,t.origin),i=s.every(g=>aN(a[g],e,g))?s:[],c=s.filter(g=>!i.includes(g)),l=[];if(i.length>0){for(let g of i)delete a[g];r=If(r,i,l)}let d=[],u=[],p=t.openaiBaseUrl,f=t.clientKey??t.placeholderKey,m=ue({...t.metadata,tool:"opencode"});for(let g of c){let b={...a[g]},k={...b.options};if("headers"in k&&!W(k.headers)){u.push(g);continue}let C=W(k.headers)?{...k.headers}:{},S=!1;for(let[I,E]of[[Dt,f],...m?[[Dn,m]]:[]])I in C?(typeof C[I]!="string"||C[I].trim()==="")&&u.push(`${g}.${I}`):(C[I]=E,d.push(`${g}.${I}`),S=!0);S&&(k.headers=C,b.options=k,a[g]=b)}let h=c.length>0?[]:pr.filter(g=>g!=="openai"||!ee(t,"openai")),w=t.byoUpstream;for(let g of h){let b=W(a[g])?{...a[g]}:{},k=W(b.options)?{...b.options}:{};k.baseURL=p;let C=W(k.headers)?{...k.headers}:{};if(g==="anthropic"&&w)k.apiKey=w.key,C[_n]=`Bearer ${w.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=w.url;else{k.apiKey=f,"x-anyray-custom-host"in C&&delete C[_n];for(let S of Af)delete C[S]}C[Dt]=f,m&&(C[Dn]=m),k.headers=C,b.options=k,a[g]=b}let y=c.length===0&&Of(t);if(y){let g=W(a[Ln])?{...a[Ln]}:{},b=W(g.options)?{...g.options}:{};b.baseURL=kf(t);let k=W(b.headers)?{...b.headers}:{};k[Dt]=t.clientKey,m&&(k[Dn]=m),b.headers=k,g.options=b,a[Ln]=g}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:y,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},pN=["baseURL","apiKey"],yC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!W(s)||!W(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=W(c.headers)?{...c.headers}:void 0,p=u?.[Dt],f=hl(p);if(d&&(delete c.baseURL,l=!0),u&&(d||f)){let m=u,h=W(r)?r.options:void 0,w=W(h)&&W(h.headers)?h.headers:void 0;for(let y of[Dt,Dn])w&&y in w?m[y]!==w[y]&&(m[y]=w[y],l=!0):y in m&&(delete m[y],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}else{let d=W(r)?r.options:void 0,u=W(d)?d:{},p=W(c.headers)?c.headers:{},f=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof p[Dt]=="string"||typeof p[Dn]=="string"||Af.some(m=>m in p);if(!o&&!f)return!1;for(let m of pN)m in u?c[m]!==u[m]&&(c[m]=u[m],l=!0):m in c&&(delete c[m],l=!0);if(W(c.headers)){let m={...c.headers},h=W(u.headers)?u.headers:{};"x-anyray-custom-host"in m&&_n in m&&(_n in h?m[_n]!==h[_n]&&(m[_n]=h[_n],l=!0):(delete m[_n],l=!0));for(let w of[Dt,Dn,...Af])w in h?m[w]!==h[w]&&(m[w]=h[w],l=!0):w in m&&(delete m[w],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}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},fN=(e,t,n)=>{let r=e[t];if(!W(r)||!W(r.options)||!W(n)||!W(n.options))return!1;let o={...r.options};if(!W(o.headers)||"headers"in n.options&&!W(n.options.headers))return!1;let a={...o.headers},s=W(n.options.headers)?n.options.headers:{},i=!1;return!(Dt in s)&&hl(a[Dt])&&(delete a[Dt],i=!0),!(Dn in s)&&iN(a[Dn])&&(delete a[Dn],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},mN=(e,t)=>{let n={...e},r=!1,o=sN(e.provider);if(W(n.mcp)&&Ms(n.mcp[Pn])){let c={...n.mcp};delete c[Pn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!W(n.provider))return{next:n,removed:r};let a={...n.provider},s=W(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===bf&&pr.every(c=>{let l=a[c];return W(l)&&W(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of pr)yC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...pr,Ln]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;fN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&W(u)&&W(u.options)&&xf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Ef(n,t,l))}return yC(a,Ln,!0,s[Ln])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===bf&&(delete n.$schema,r=!0),{next:n,removed:r}},kC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=yl(),t=bC(),n=await x(e)||await x(t),r=n&&await mC();return{installed:n,detail:n?`${await hC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await hC(),r=e.openaiBaseUrl,o=ue({...e.metadata,tool:"opencode"}),a=Of(e),s=ee(e,"openai"),i=await mC(),c;try{c=await je(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(kf(e))}, "headers": { "${Dt}": "<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 $r()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:p,modelRefsRemapped:f,customHeadersAdded:m,customHeaderConflicts:h,mcpConflict:w}=uN(c.data,e,l),y=u.length>0,g=p.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${p.map(E=>`provider.${E}`).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.`,...f.length>0?[`Updated model references: ${f.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=y?[`${n} already routes through ${e.origin} via ${u.map(E=>`provider.${E}`).join(", ")}; existing provider values were preserved.`,m.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${m.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...h.length>0?[`Could not safely add required headers at ${h.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."]:[...g,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)"}`,...cN(e),...lN(e,i),a?`provider.github-copilot options.baseURL \u2192 ${kf(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. ${Cf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Cf()} 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).",...dN(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Pn} 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 k=h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let S=await sn(n,c,d,!0)?[n]:[],I=ml();if(te())try{let E=await fC(I,ts(ze,["opencode"]));E==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${I} already exists and is not owned by Anyray.`):(E==="installed"&&S.push(I),b.push(`The OpenCode tool.execute.after carrier is active in ${I}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${I}. Gateway-side optimization remains active.`)}else{try{await wf(I)==="removed"&&S.push(I)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:k,messages:b,changedFiles:S}},async pointsAt(e){for(let t of await jo())try{let{data:n}=await je(t);if(!W(n.provider))continue;for(let r of Object.values(n.provider))if(!(!W(r)||!W(r.options))&&xf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await jo();if(e.length===0)return{registered:!1,command:null,reason:"no-config"};let t=!1,n=!1;for(let r of e)try{let{data:o}=await je(r);if(!W(o.mcp))continue;let a=o.mcp[Pn];if(!Ms(a)||!W(a)){a!==void 0&&(t=!0);continue}return{registered:!0,command:Array.isArray(a.command)&&typeof a.command[0]=="string"?a.command[0]:null}}catch{n=!0}return{registered:!1,command:null,reason:t?"foreign":n?"unreadable":"absent"}},async integrationStatus(){let e,t=!0;try{let i=await $s(ml());e=i==="absent"?"missing":i,e==="owned"&&(t=await wC(ml(),"utf-8")===gf(ts(ze,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await jo()){let c;try{c=await je(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!W(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Pn];if(l!==void 0)if(Ms(l))if(n=!0,!W(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;rc({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 $r()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await AC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await jo()){let{data:o}=await je(r);if(W(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!W(s)||!W(s.options)){e.add("unknown");continue}let i=s.options,c=W(i.headers)?i.headers:{};if(a===Ln&&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===Ln&&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(hl(c[Dt])||hl(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 jo(),n=ml(),r="absent";try{r=await $s(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 je(i)}catch{s.push(i);continue}let{next:l,removed:d}=mN(c.data,await Bo(i));d&&(await sn(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await oe(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 wf(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 $f}from"node:os";import{join as kl}from"node:path";import{homedir as hN}from"node:os";import{dirname as yN,join as mr}from"node:path";import{mkdir as gN,readdir as wN,readFile as SC,rm as IC}from"node:fs/promises";var Tf="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",vC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJEZXBlbmRlbmNpZXMiOiB7CiAgICAib3BlbmNsYXciOiAiPj0yMDI2LjcuMSIKICB9LAogICJkZXZEZXBlbmRlbmNpZXMiOiB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BnYXRld2F5UHJvdmlkZXJGb3JNb2RlbChtb2RlbC5pZCkKICAgICAgOiB1bmRlZmluZWQ7CiAgICBpZiAoZ2F0ZXdheVByb3ZpZGVyICYmIGhlYWRlcnNbJ3gtYW55cmF5LXByb3ZpZGVyJ10gPT09IHVuZGVmaW5lZCkgewogICAgICBoZWFkZXJzWyd4LWFueXJheS1wcm92aWRlciddID0gZ2F0ZXdheVByb3ZpZGVyOwogICAgfQogICAgb3B0cy5oZWFkZXJzID0gaGVhZGVyczsKICAgIGNvbnN0IHNlc3Npb25JZCA9CiAgICAgIHR5cGVvZiBvcHRzLnNlc3Npb25JZCA9PT0gJ3N0cmluZycgPyBvcHRzLnNlc3Npb25JZCA6IHVuZGVmaW5lZDsKICAgIGNvbnN0IGNhbGxlck9uUGF5bG9hZCA9IG9wdHMub25QYXlsb2FkOwogICAgb3B0cy5vblBheWxvYWQgPSBhc3luYyAocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA9PiB7CiAgICAgIGlmIChwYXlsb2FkICYmIHR5cGVvZiBwYXlsb2FkID09PSAnb2JqZWN0JyAmJiAhQXJyYXkuaXNBcnJheShwYXlsb2FkKSkgewogICAgICAgIHBhdGNoUGF5bG9hZFNlc3Npb25JZGVudGl0eSgKICAgICAgICAgIHBheWxvYWQgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4sCiAgICAgICAgICBzZXNzaW9uSWQKICAgICAgICApOwogICAgICB9CiAgICAgIHJldHVybiBjYWxsZXJPblBheWxvYWQgPyBjYWxsZXJPblBheWxvYWQocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var _f=".anyray-source-sha",hn=()=>mr(hN(),".anyray","openclaw-plugin"),EC=async(e=hn())=>{try{if((await SC(mr(e,_f),"utf8")).trim()===Tf)return"current"}catch{}for(let t of vC){let n=mr(e,t.path);await gN(yN(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(mr(e,_f),`${Tf}
191
+ `),"installed"},Bs=async(e,t=[])=>{let n=[],r=async a=>{let s=mr(a,"plugins","anyray","catalog.json");try{await IC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await wN(mr(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(mr(e,"agents",a,"agent"));return n},gl=async(e=hn())=>{try{await SC(mr(e,_f),"utf8")}catch{return!1}return await IC(e,{recursive:!0,force:!0}),!0};var Df="x-anyray-metadata",Jo="x-anyray-api-key",Lf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],zr="Authorization",qr="anthropic-beta",bl="interleaved-thinking-2025-05-14",Al=["anthropic","openai"],RC="short",Mf="anthropic-messages",Bf=32e3,Cl="anthropic/claude-sonnet-4-5",Ff=["anthropic/claude-haiku-4-5"],Wf="anyray/claude-sonnet-4-5",Uf=["anyray/claude-haiku-4-5"],bN=[Cl,Wf],AN=[Ff,Uf],qe="anyray",hr="ANYRAY_API_KEY",Fs="openclaw",Yo=()=>process.env.OPENCLAW_STATE_DIR?.trim()||kl($f(),".openclaw"),Zo=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||kl(Yo(),"openclaw.json"),L=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Nf=e=>{if(!L(e))return{};let t=e.models;return!L(t)||!L(t.providers)?{}:t.providers},CN=e=>e==="~"||e.startsWith("~/")?kl($f(),e.slice(1)):e,wl=e=>{if(!L(e))return[];let t=e.agents;if(!L(t)||!Array.isArray(t.list))return[];let n=[];for(let r of t.list){if(!L(r))continue;let o=typeof r.agentDir=="string"?r.agentDir.trim():"";o&&n.push(CN(o))}return n},kN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=ue({...t.metadata,tool:Fs}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!L(l.models)&&d.push("models");let u=L(l.models)?{...l.models}:{};if("providers"in u&&!L(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 p=L(u.providers)?{...u.providers}:{},f=!1;if(n){let C=L(l.plugins)?{...l.plugins}:{},S=L(C.load)?{...C.load}:{},I=L(C.entries)?{...C.entries}:{},E=L(I[qe])?{...I[qe]}:{},R=L(E.config)?{...E.config}:{};if("plugins"in l&&!L(l.plugins)||"load"in C&&!L(C.load)||"paths"in S&&!Array.isArray(S.paths)||"entries"in C&&!L(C.entries)||qe in I&&!L(I[qe])||"config"in E&&!L(E.config)||"env"in l&&!L(l.env))d.push("plugins");else{let N=Array.isArray(S.paths)?[...S.paths]:[];N.includes(n)||N.push(n),S.paths=N,C.load=S,E.enabled=!0,R.gatewayUrl=t.anthropicBaseUrl,R.apiKey=r;let U=t.metadata.user,q=t.metadata.team;U&&(R.user=U),q&&(R.team=q),E.config=R,I[qe]=E,C.entries=I,l.plugins=C;let de=L(l.env)?{...l.env}:{};de[hr]=r,l.env=de,f=!0}}let m=Al.filter(C=>C!=="openai"||!ee(t,"openai"));for(let C of m){if(C in p&&!L(p[C])){d.push(`models.providers.${C}`);continue}let S=L(p[C])?{...p[C]}:{};if("headers"in S&&!L(S.headers)){i.push(C);continue}let I=L(S.headers)?{...S.headers}:{};if(S.baseUrl=C==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,C==="anthropic"&&(S.api=Mf,(typeof S.maxTokens!="number"||S.maxTokens<=0)&&(S.maxTokens=Bf)),C==="anthropic"&&a)S.apiKey=a.key,I[zr]=`Bearer ${a.key}`,I["x-anyray-provider"]="anthropic",I["x-anyray-auth-mode"]="passthrough",I["x-anyray-custom-host"]=a.url;else{S.apiKey=r,"x-anyray-custom-host"in I&&delete I[zr];for(let E of Lf)delete I[E]}I[Jo]=r,o&&(I[Df]=o),C==="anthropic"&&(qr in I?c=I[qr]!==bl:I[qr]=bl),S.headers=I,p[C]=S,s.push(C)}u.providers=p,l.models=u;let h=!1,w=!1,y=!1,g,b=[],k="agents"in l&&!L(l.agents)||L(l.agents)&&"defaults"in l.agents&&!L(l.agents.defaults)||L(l.agents)&&L(l.agents.defaults)&&("params"in l.agents.defaults&&!L(l.agents.defaults.params)||"model"in l.agents.defaults&&!L(l.agents.defaults.model));if(k&&d.push("agents.defaults"),s.includes("anthropic")&&!k){let C=L(l.agents)?{...l.agents}:{},S=L(C.defaults)?{...C.defaults}:{},I=L(S.params)?{...S.params}:{};"cacheRetention"in I||(I.cacheRetention=RC,h=!0,S.params=I);let E=L(S.model)?{...S.model}:{},R=f?[...s,qe]:s,N=U=>typeof U=="string"&&R.some(q=>U.startsWith(`${q}/`));typeof E.primary!="string"||E.primary.trim()===""?(E.primary=f?Wf:Cl,w=!0,S.model=E,"fallbacks"in E||(E.fallbacks=f?[...Uf]:[...Ff],y=!0)):N(E.primary)||(g=E.primary),b=(Array.isArray(E.fallbacks)?E.fallbacks:[]).filter(U=>typeof U=="string"&&!N(U)),(h||w)&&(C.defaults=S,l.agents=C)}return{next:l,routed:s,cacheRetentionSeeded:h,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:y,unroutedPrimary:g,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:f}},vN=["baseUrl","apiKey","api","maxTokens"],Pf=(e,t,n=Al,r)=>{let o={...e},a=!("models"in o)||L(o.models)&&(!("providers"in o.models)||L(o.models.providers)),s=L(o.models)?{...o.models}:{},i=L(s.providers)?{...s.providers}:{},c=Nf(t),l=!1;for(let u of a?n:[]){let p=i[u];if(!L(p))continue;let f={...p},m=L(f.headers)?{...f.headers}:{};if(!(t!==void 0||typeof m[Jo]=="string"||typeof m[Df]=="string"||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_")||Lf.some(C=>C in m)))continue;let w=L(c[u])?c[u]:{},y=L(w.headers)?w.headers:{},g="x-anyray-custom-host"in m,b=C=>C==="api"?f.api===Mf:C==="maxTokens"?f.maxTokens===Bf:C==="apiKey"?g||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_"):!0;for(let C of vN)b(C)&&(C in w?f[C]!==w[C]&&(f[C]=w[C],l=!0):C in f&&(delete f[C],l=!0));let k=[Jo,Df,...Lf,..."x-anyray-custom-host"in m?[zr]:[]];m[qr]===bl&&k.push(qr);for(let C of k)C in y?m[C]!==y[C]&&(m[C]=y[C],l=!0):C in m&&(delete m[C],l=!0);zr in y&&!(zr in m)&&(m[zr]=y[zr],l=!0),Object.keys(m).length===0?delete f.headers:f.headers=m,Object.keys(f).length===0?delete i[u]:i[u]=f}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=L(o.plugins)?{...o.plugins}:{},p=L(u.load)?{...u.load}:{},f=L(u.entries)?{...u.entries}:{};if((!("plugins"in o)||L(o.plugins))&&(!("load"in u)||L(u.load))&&(!("paths"in p)||Array.isArray(p.paths))&&(!("entries"in u)||L(u.entries))){if(Array.isArray(p.paths)&&p.paths.includes(r)){let w=p.paths.filter(y=>y!==r);w.length===0?delete p.paths:p.paths=w,l=!0}let h=f[qe];if(L(h)){let w=L(h.config)?h.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let g=L(t?.plugins)?t.plugins:{},b=L(g.entries)?g.entries:{};qe in b?JSON.stringify(f[qe])!==JSON.stringify(b[qe])&&(f[qe]=b[qe],l=!0):(delete f[qe],l=!0)}}if(Object.keys(p).length===0?delete u.load:u.load=p,Object.keys(f).length===0?delete u.entries:u.entries=f,Object.keys(u).length===0?delete o.plugins:o.plugins=u,L(o.env)){let w={...o.env},y=w[hr];if(typeof y=="string"&&y.startsWith("ark_")){let g=L(t?.env)?t.env:{};hr in g?w[hr]!==g[hr]&&(w[hr]=g[hr],l=!0):(delete w[hr],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||L(o.agents)&&(!("defaults"in o.agents)||L(o.agents.defaults)&&(!("params"in o.agents.defaults)||L(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||L(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=L(o.agents)?{...o.agents}:{},p=L(u.defaults)?{...u.defaults}:{},f=L(p.params)?{...p.params}:{},m=L(t.agents)?t.agents:{},h=L(m.defaults)?m.defaults:{},w=L(h.params)?h.params:{};f.cacheRetention===RC&&("cacheRetention"in w?f.cacheRetention!==w.cacheRetention&&(f.cacheRetention=w.cacheRetention,l=!0):(delete f.cacheRetention,l=!0));let y=L(p.model)?{...p.model}:{},g=L(h.model)?h.model:{};bN.includes(y.primary)&&("primary"in g?y.primary!==g.primary&&(y.primary=g.primary,l=!0):(delete y.primary,l=!0)),AN.some(b=>JSON.stringify(y.fallbacks)===JSON.stringify(b))&&("fallbacks"in g?JSON.stringify(y.fallbacks)!==JSON.stringify(g.fallbacks)&&(y.fallbacks=g.fallbacks,l=!0):(delete y.fallbacks,l=!0)),Object.keys(y).length===0?delete p.model:p.model=y,Object.keys(f).length===0?delete p.params:p.params=f,Object.keys(p).length===0?delete u.defaults:u.defaults=p,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},OC={id:Fs,title:"OpenClaw",automatic:!0,async detect(){let e=await x(Zo())||await x(Yo());return{installed:e,detail:e?Zo():`no ${kl($f(),".openclaw")} state dir`}},async apply(e,t){let n=Zo();if(!e.byoUpstream&&ee(e,"anthropic")){let S=["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 ${Fs}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],I;try{I=await je(n)}catch{return{status:"held",messages:S}}let{next:E,removed:R}=Pf(I.data,await Bo(n),Al,hn());return R?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...S]}:(await sn(n,I,E,!1),await oe(n),await gl(),await Bs(Yo(),wl(E)),{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.`,...S]}):(t.dryRun||(await gl(),await Bs(Yo(),wl(E))),{status:"held",messages:S})}let r=hn(),o=!1;if(!t.dryRun)try{await EC(r)}catch{r=void 0,o=!0}let a;try{a=await je(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Mf}", "maxTokens": ${Bf}, "apiKey": "<your personal ark_ key>", "headers": { "${Jo}": "<your personal ark_ key>", "${qr}": "${bl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${Jo}": "<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:p,unroutedPrimary:f,unroutedFallbacks:m,structureConflicts:h,pluginConfigured:w}=kN(a.data,e,r),y=s,g=!1;if(!i.includes("openai")){let S=Pf(y,await Bo(n),["openai"]);S.removed&&(y=S.next,g=!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: ${ue({...e.metadata,tool:Fs})??"(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 ${qr} 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?Wf:Cl} (none was set; routing is inert until the primary resolves to a routed provider).`,...p?[`Seeded agents.defaults.model.fallbacks = [${(w?Uf:Ff).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...f!==void 0?[`Your primary model (${f}) 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.`]:[],...m.length>0?[`Fallback model(s) ${m.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...g?["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 (${hn()}) and registered it under plugins.entries.${qe}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${hn()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...h.length>0?[`Left ${h.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."],k=d.length>0||h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let C=await sn(n,a,y,!0);return w&&await Bs(Yo(),wl(y)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await je(Zo());for(let a of Object.values(Nf(t)))if(L(a)&&xC(a.baseUrl,e))return!0;let n=L(t.plugins)?t.plugins:{},o=(L(n.entries)?n.entries:{})[qe];if(L(o)&&L(o.config)&&xC(o.config.gatewayUrl,e))return!0}catch{}return!1},async routingExpected(e){return e.includes(Fs)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await je(Zo());for(let a of Object.values(Nf(t))){if(!L(a))continue;let s=L(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[Jo]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=L(t.plugins)?t.plugins:{},o=(L(n.entries)?n.entries:{})[qe];if(L(o)&&L(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=Zo();if(!await x(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 je(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}=Pf(n.data,await Bo(t),Al,hn()),a=await gl();return await Bs(Yo(),wl(r)),o?(await sn(t,n,r,!1),await oe(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]],changedFiles:[t]}):(await oe(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]]})}};import{execFile as fB}from"node:child_process";import{readFile as mB}from"node:fs/promises";import{homedir as oi,platform as br}from"node:os";import{join as bn}from"node:path";import{isDeepStrictEqual as xm,promisify as hB}from"node:util";var Ws=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=Ws(e),r=Ws(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 TM}from"node:crypto";import{promises as Uk}from"node:fs";import{platform as _M,tmpdir as PM}from"node:os";import{join as Ul}from"node:path";import{execFile as SN}from"node:child_process";import{promises as Us}from"node:fs";import{homedir as IN,platform as EN}from"node:os";import{delimiter as xN,join as Sl}from"node:path";import{promisify as RN}from"node:util";var ON=RN(SN),TN=15*6e4,_N=64*1024*1024,PN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],TC=async(e={})=>{let t=(e.home??IN)(),n=e.env??process.env,r=PN(e.runtimePlatform??EN()),o=[Sl(t,".local","bin"),Sl(t,".claude","local"),...(n.PATH??"").split(xN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Sl(a,`claude${s}`);try{return await Us.access(i),i}catch{}}return null},DN=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},LN=async e=>{let t=Sl(e,"projects"),n;try{n=(await Us.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(!MN.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},NN=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],p=o[d];if(typeof u!="string"||typeof p!="string"||u.length===0||p.length===0)continue;let f=a[d];l.push({sessionId:u,transcriptPath:p,title:typeof f=="string"&&f.length>0?f:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:DN(n.projectList)}},$N=async e=>{let t,n;try{let r=await Us.readFile(e,"utf8");for(let o of r.split(`
192
+ `)){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}},MN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,BN=/\.(?:cmd|bat)$/i,FN=(e,t)=>BN.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},_C=async(e,t={})=>{let n=t.exec??ON,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 Us.mkdir(e.configDir,{recursive:!0,mode:448}),await Us.mkdir(e.workDir,{recursive:!0,mode:448});let o=FN(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:TN,maxBuffer:_N,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(`
193
+ `).filter(d=>d.trim().length>0),i=NN(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 $N(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await LN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as WN}from"node:crypto";import{promises as Nn}from"node:fs";import{homedir as UN,platform as HN}from"node:os";import{join as Ct}from"node:path";var PC=448,$n="local_",GN="local-agent-mode-sessions",Hf="-3p",VN="cowork_account_settings.json",Qr=(e={})=>{let t=(e.home??UN)(),n=e.runtimePlatform??HN(),r=e.env??process.env;if(n==="darwin")return Ct(t,"Library","Application Support",`Claude${Hf}`);if(n==="win32"){let o=r.LOCALAPPDATA??Ct(t,"AppData","Local");return Ct(o,`Claude${Hf}`)}return null},Hs=(e={})=>{let t=Qr(e);return t?t.slice(0,-Hf.length):null},Gf=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)}`},Il=async e=>{let t=Ct(e,GN),n;try{n=(await Nn.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 Nn.readdir(Ct(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=Ct(t,o,s);try{await Nn.access(Ct(i,VN)),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]}},Vf=async e=>{try{let t=await Nn.readdir(e);return new Set(t.filter(n=>n.startsWith($n)&&n.endsWith(".json")).map(n=>n.slice($n.length,-5)))}catch{return new Set}},Xo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),KN=async(e,t)=>{let n=`${$n}${t.sessionId}`,r=Ct(e,n),o=Ct(r,"outputs"),a=Ct(r,".claude"),s=Ct(a,"projects",Gf(o));await Nn.mkdir(o,{recursive:!0,mode:PC}),await Nn.mkdir(s,{recursive:!0,mode:PC});let i=Ct(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${WN()}`;await Nn.copyFile(t.transcriptPath,c),await Nn.chmod(c,384),await Nn.rename(c,i);let l=t.createdAt??Date.now();await Y(Ct(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})},DC=async(e,t)=>{let n=await Vf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!Xo(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await KN(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as zo}from"node:fs";import{homedir as jN}from"node:os";import{dirname as ZN,join as Gs}from"node:path";var YN=448,JN=["Documents","Claude","Projects"],XN="spaces.json",zN=(e={})=>Gs((e.home??jN)(),...JN),qN=async e=>{try{let t=JSON.parse(await zo.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}}},QN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Kf=async e=>{try{return await zo.access(e),!0}catch{return!1}},e$=async(e,t,n)=>{let r=Gs(t,QN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Kf(r)?o:r;return a===o&&await Kf(o)?null:(await zo.mkdir(ZN(a),{recursive:!0}),await zo.cp(e,a,{recursive:!0}),a)},t$=async e=>{try{let t=(await zo.readFile(Gs(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},LC=async e=>{let t=zN({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=Gs(e.storageDir,XN),{spaces:a,readable:s}=await qN(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=Gs(e.stagedProjectsDir,l.dirName);try{if(!await Kf(d)){n.failed+=1;continue}let u=await e$(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await t$(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...p?{instructions:p}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await zo.mkdir(e.storageDir,{recursive:!0,mode:YN}),await Y(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as a$}from"node:crypto";import{execFile as s$,spawnSync as KC}from"node:child_process";import{constants as jC}from"node:fs";import{access as _l,chmod as i$,mkdir as c$,readdir as l$,readFile as Zf,rename as d$,rm as qo,stat as ZC,writeFile as u$}from"node:fs/promises";import{homedir as p$,platform as f$,userInfo as m$}from"node:os";import{basename as h$,dirname as YC,isAbsolute as Qo,join as Lt,resolve as FC}from"node:path";import{isDeepStrictEqual as Ks,promisify as y$}from"node:util";var yr="__anyray-claude-desktop-credential",Vs="__anyray-claude-desktop-bootstrap-headers";var El=["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>`."],xl=["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."],NC="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"],$C=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapHeaders","bootstrapHeadersHelper","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"],n$=new Set($C),r$=new Set($C.map(e=>e.toLowerCase())),o$=new Set(Rl.map(e=>e.toLowerCase())),Ol=(e,t=!1)=>(t?r$:n$).has(t?e.toLowerCase():e),MC=(e,t=!1)=>t?o$.has(e.toLowerCase()):Rl.some(n=>n===e),BC=["*"],eo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...BC]}),gr=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var js=/^[a-f0-9-]{36}$/,JC="Anyray",Yf=4,Js=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],Xs=["deploymentMode","awaitingSignIn"],XC=[...Js,...Xs,"configLibrary","_meta.json"],yn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),it=e=>structuredClone(e),Zs=async e=>{try{return await _l(e),!0}catch{return!1}},g$=async e=>{try{let t=await l$(YC(e)),n=h$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},w$=async e=>{try{return await _l(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":g$(e)}},jt=(e={})=>{let t=(e.home??p$)(),n=(e.username??(()=>m$().username))(),r=Lt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Lt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Lt(r,"configLibrary"),meta:Lt(r,"configLibrary","_meta.json"),appConfig:Lt(r,"claude_desktop_config.json"),helper:Lt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Lt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Pl=()=>{let e=KC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},zC=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],b$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...zC(t)]}},Jf=(e="json")=>{let t=en(zC(e)),n=FC(t.command),r=FC(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:te()&&(!o||r!==n)}},A$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,Xf=e=>[e.command,...e.args].map(A$).join(" "),C$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!Qo(e.command))throw new Error("the credential helper executable is not absolute")},qC=(e,t)=>{C$(e);let n=Dl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!Qo(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},QC=e=>(qC(e,"--json"),`#!/bin/sh
194
+ exec ${Xf(e)}
195
+ `),k$=`#!/bin/sh
196
+ # Anyray subscription pass-through credential helper v2 for Claude Desktop`,ek=e=>{qC(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),yr]};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 ${Xf(t)}`,""].join(`
197
+ `)},v$=e=>e.args.at(-1)==="--passthrough-headers"?ek(e):QC(e),Dl=e=>/[\\/](node|node\.exe)$/i.test(e),zf=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++}},S$=e=>{let t=`#!/bin/sh
198
198
  exec `;if(!e.startsWith(t)||!e.endsWith(`
199
199
  `))return;let n=e.slice(t.length,-1);if(n.includes(`
200
- `)||n.includes("\r"))return;let r=Qf(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Pl(o);if(!Qo(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!Qo(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return XC(i)===e?i:void 0}catch{return}},g$=e=>{if(!e.startsWith(m$))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=Qf(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==hr)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return zC(a)===e?a:void 0}catch{return}},w$=`#!/bin/sh
201
- # Anyray subscription pass-through credential helper`,b$=e=>{let t=Pl(e.command);if(!(!Qo(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!Qo(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=$(${qf(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(`
202
- `)},A$=e=>{if(!e.startsWith(w$))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=Qf(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return b$(a)===e?a:void 0},qC=e=>y$(e)??g$(e)??A$(e),C$=async()=>{let e=UC("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},k$=async e=>{let t=[e.command,...Pl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>VC(r)))).every(r=>r.isFile())?(await Tl(e.command,GC.X_OK),!0):!1}catch{return!1}},v$=0,Dl=async(e,t,n)=>{await e$(KC(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${v$++}.tmp`;try{await r$(r,t,{mode:n}),await QN(r,n),await n$(r,e)}catch(o){throw await qo(r,{force:!0}).catch(()=>{}),o}},$n=async(e,t)=>{await Dl(e,`${JSON.stringify(t,null,2)}
203
- `,384)},gn=async e=>{if(!await Zs(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await Jf(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!yn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},zs=async e=>{if(!await Zs(e))return{present:!1};let t=await VC(e);return{present:!0,content:await Jf(e,"utf-8"),mode:t.mode&511}},QC=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:it(e[t])}:{present:!1},Yf=(e,t,n)=>{n.present?e[t]=it(n.value):delete e[t]},MC=e=>yn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),S$=e=>yn(e)&&MC(e.original)&&MC(e.lastWritten),I$=e=>yn(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),BC=(e,t)=>yn(e)&&t.every(n=>S$(e[n])),E$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],x$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],em=(e,t,n,r)=>!(!yn(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)||!yn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==jC||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!BC(e.config,r)||r.some(o=>e.config[o].original.present)||!BC(e.deployment,Xs)||!yn(e.helper)||e.helper.path!==t.helper||!I$(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),R$=(e,t)=>em(e,t,Xf,Js),O$=(e,t)=>em(e,t,2,E$),T$=(e,t)=>em(e,t,3,x$),_$=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),FC=e=>({...e,version:Xf,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),tm=async e=>{if(!await Zs(e.journal))return;let t;try{t=JSON.parse(await Jf(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(R$(t,e))return t;if(T$(t,e))return FC(t);if(O$(t,e))return FC(_$(t));throw new Error(`${e.journal} is not a valid ownership journal`)},WC=async(e,t)=>{await Dl(e,`${JSON.stringify(t,null,2)}
204
- `,384)},Ys=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(!yn(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},P$=async(e,t,n)=>{let r=await gn(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:it(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[it(t.metaEntry)]}}}let c=Ys(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!Ks(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:it(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...it(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=Ys(r.value);let c=Dt(e.library,`${o}.json`);if(!await Zs(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=it(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(Dt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:jC};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?it(r.value):{},appliedId:s,entries:[...a,i]}}},D$=(e,t)=>{let n=eo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},ek=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),L$=async(e,t,n,r,o,a,s)=>{let i=ek(),c=Object.fromEntries(Js.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(Xs.map(d=>[d,{original:s?.deployment[d].original??QC(r.value,d),lastWritten:i[d]}]));return{version:Xf,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??it(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await zs(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Ol=e=>({status:"manual",messages:[e]}),N$=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}`)]}},$$=c$(qN),M$=new Set(xl),B$=async e=>{try{let{stdout:t}=await $$("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return yn(n)?Object.keys(n):void 0}catch{return}},to=async(e,t={})=>{let n=t.readManagedPolicyKeys??B$;for(let r of e.managedPolicies){let o=await d$(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=>Rl(i)&&!M$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},nm=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.`},rm=e=>(e.platform??a$)()==="darwin",tk=async(e,t,n={})=>{if(!rm(n))return Ol("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??_l)()&&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=jt(n),a=await to(o,n);if(a&&r.push({audience:"admin",message:nm(a)}),r.length>0)return N$(r);let s=!1,i=!1,c=[o.journal];try{let l=ee(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??C$)())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=u$((n.credentialCommand??(()=>zf(d)))(),d),p=h$(u),f=await tm(o),m=await zs(o.helper);if(f&&m.present&&m.content!==f.helper.lastWritten&&m.content!==f.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!f&&m.present&&m.content!==p)throw new Error("the Claude Desktop credential helper path contains a foreign file");let h=await P$(o,f,n.randomUUID??zN),w=Dt(o.library,`${h.configId}.json`);c=[o.journal,o.helper,w,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await gn(w),g=await gn(o.appConfig),b=D$(e,o.helper),k=await L$(o,h,y,g,p,b,f);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${h.configId} for ${e.anthropicBaseUrl}, activate it in third-party mode, and install a ${l?"subscription pass-through":"dynamic API-billed"} credential helper at ${o.helper}.`]};s=!0,await WC(o.journal,k),i=!0,await Dl(o.helper,p,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await WC(o.journal,k));let C=it(y.value);for(let E of Js)Yf(C,E,b[E]);await $n(w,C),h.metaToWrite&&await $n(o.meta,h.metaToWrite);let S=it(g.value),I=ek();for(let E of Xs)Yf(S,E,I[E]);return await $n(o.appConfig,S),{status:"configured",changedFiles:[o.journal,o.helper,w,...h.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.",...Il]}}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.`]}:Ol(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},HC=(e,t,n,r)=>{let o=it(e);for(let a of n){let s=t[a];Ks(QC(e,a),s.lastWritten)?Yf(o,a,s.original):r.push(a)}return o},nk=async(e,t={})=>{if(!rm(t))return{status:"not-found",messages:[]};if((t.appRunning??_l)())return Ol("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=jt(t);try{let r=await tm(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Dt(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 gn(o),i=s.value;s.present&&(i=HC(s.value,r.config,Js,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await gn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let m=Ys(l.value),h=it(l.value.entries),w=h.findIndex(b=>b.id===r.configId),y=w>=0?h[w]:void 0,g=y!==void 0&&Ks(y,r.metaEntry);if(y!==void 0&&!g&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=it(l.value),m===r.configId){let b=r.originalAppliedId;b&&h.some(k=>k.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&g?(h.splice(w,1),d.entries=h):c&&y===void 0&&(d.entries=h)}else{let b=Ks(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&m!==r.configId?(g&&h.splice(w,1),d={...it(l.value),entries:h}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await qo(o,{force:!0}):await $n(o,i)),l.present&&(u?await qo(n.meta,{force:!0}):Ks(l.value,d)||await $n(n.meta,d));let p=await gn(n.appConfig);if(p.present){let m=HC(p.value,r.deployment,Xs,a);!r.deploymentFileExisted&&Object.keys(m).length===0?await qo(n.appConfig,{force:!0}):await $n(n.appConfig,m)}else r.deploymentFileExisted&&a.push("deployment config file");let f=await zs(n.helper);return f.present&&(f.content===r.helper.lastWritten||f.content===r.helper.previousWritten)?r.helper.original.present?await Dl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await qo(n.helper,{force:!0}):(f.present||r.helper.original.present)&&a.push("credential helper"),await qo(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?[]:El]}}catch(r){return Ol(`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.`)}},om=async(e,t={})=>{if(!rm(t))return!1;let n=jt(t);if(await to(n,t))return!1;try{let r=await gn(n.meta);if(!r.present)return!1;let o=Ys(r.value),a=await gn(Dt(n.library,`${o}.json`)),s=await gn(n.appConfig);if(!a.present||!s.present)return!1;await Tl(n.helper,GC.X_OK);let i=Ht(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}},rk=async(e={})=>{try{let t=jt(e),n=await zs(t.helper);if(!n.present||typeof n.content!="string")return;let r=qC(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},ok=async(e,t={})=>{if(!await om(e,t))return!1;let n=jt(t);try{let r=await tm(n);if(!r)return!1;let o=await gn(n.meta);if(!o.present||Ys(o.value)!==r.configId)return!1;let a=await zs(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=qC(a.content??"");return s?await(t.helperLauncherAvailable??k$)(s):!1}catch{return!1}};import{createHash as Ak,randomUUID as Ck}from"node:crypto";import{spawn as F$,spawnSync as W$}from"node:child_process";import{link as um,mkdir as am,open as kk,readFile as sm,readdir as vk,rename as Sk,rm as Zt,stat as Ik}from"node:fs/promises";import{homedir as pm}from"node:os";import{basename as Ek,dirname as Qs,join as sa,win32 as H$}from"node:path";import{isDeepStrictEqual as ea}from"node:util";var Te="HKCU\\SOFTWARE\\Policies\\Claude",qs="HKLM\\SOFTWARE\\Policies\\Claude",Ml=5,ia="inferenceGatewayApiKey",Pe=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ia],ak=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ia],sk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ia],ik=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ia],xk="Managed by anyray-connect; dynamic credential only.",U$=e=>/^[A-Za-z]:[\\/]/.test(e)&&H$.isAbsolute(e),ck=e=>{if(!U$(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)},Rk=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ck(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&&!ck(e.args[0]))throw new Error("the credential helper does not use print-key --json")},fm=(e={})=>sa((e.home??pm)(),".anyray","bin","claude-desktop-credential-helper.cmd"),G$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},V$=e=>(Rk(e),["@echo off",`REM ${xk}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(G$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
205
- `)),K$=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},Ok=e=>{let t=e.split(`\r
206
- `);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${xk}`||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(K$);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return Rk(s),s}catch{return}},j$=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>Ik(r)))).every(r=>r.isFile())}catch{return!1}},Z$=async(e,t)=>{let n=Ok(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??j$)(n)}catch{return!1}},im=e=>({sha256:no(e),content:e}),lk=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Lt(t,["sha256","content"])&&tM(t.sha256)&&typeof t.content=="string"&&no(t.content)===t.sha256&&Ok(t.content)!==void 0},mm=()=>{let e=W$("tasklist.exe",["/FI","IMAGENAME eq Claude.exe","/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0,timeout:2e3,maxBuffer:65536});return e.error||e.signal||e.status!==0?!0:/(?:^|\r?\n)"Claude\.exe",/iu.test(e.stdout??"")},Y$=async(e,t)=>{await am(Qs(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await kk(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await um(n,e)}finally{await Zt(n,{force:!0}).catch(()=>{})}},J$=e=>`${Ek(e)}.anyray-old-`,X$=e=>`${e}.anyray-old-${process.pid}-${Ck()}`,Tk=async(e,t)=>{try{await um(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await Zt(t,{force:!0}),!0},Nl=async(e,t,n,r,o)=>{let a=X$(e),s=n===void 0?void 0:no(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${Ck()}`,c=!1;try{if(i&&n!==void 0){let d=await kk(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 Sk(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await oa(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await um(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await aa(e)!==s))throw new Error("credential helper publication verification failed");await Zt(a,{force:!0}),c=!1}catch(l){throw c&&await Tk(e,a).catch(()=>!1),l}finally{i&&await Zt(i,{force:!0}).catch(()=>{})}},cm=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,z$=String.raw`
200
+ `)||n.includes("\r"))return;let r=zf(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Dl(o);if(!Qo(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!Qo(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return QC(i)===e?i:void 0}catch{return}},I$=e=>{if(!e.startsWith(k$))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=zf(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==yr)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return ek(a)===e?a:void 0}catch{return}},E$=`#!/bin/sh
201
+ # Anyray subscription pass-through credential helper`,x$=e=>{let t=Dl(e.command);if(!(!Qo(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!Qo(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=$(${Xf(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(`
202
+ `)},R$=e=>{if(!e.startsWith(E$))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=zf(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return x$(a)===e?a:void 0},tk=e=>S$(e)??I$(e)??R$(e),O$=async()=>{let e=KC("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},T$=async e=>{let t=[e.command,...Dl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>ZC(r)))).every(r=>r.isFile())?(await _l(e.command,jC.X_OK),!0):!1}catch{return!1}},_$=0,Ll=async(e,t,n)=>{await c$(YC(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${_$++}.tmp`;try{await u$(r,t,{mode:n}),await i$(r,n),await d$(r,e)}catch(o){throw await qo(r,{force:!0}).catch(()=>{}),o}},Mn=async(e,t)=>{await Ll(e,`${JSON.stringify(t,null,2)}
203
+ `,384)},gn=async e=>{if(!await Zs(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await Zf(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!yn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},zs=async e=>{if(!await Zs(e))return{present:!1};let t=await ZC(e);return{present:!0,content:await Zf(e,"utf-8"),mode:t.mode&511}},nk=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:it(e[t])}:{present:!1},jf=(e,t,n)=>{n.present?e[t]=it(n.value):delete e[t]},WC=e=>yn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),P$=e=>yn(e)&&WC(e.original)&&WC(e.lastWritten),D$=e=>yn(e)&&typeof e.present=="boolean"&&(!e.present||typeof e.content=="string"&&typeof e.mode=="number"&&Number.isInteger(e.mode)&&e.mode>=0&&e.mode<=511),UC=(e,t)=>yn(e)&&t.every(n=>P$(e[n])),L$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],N$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],qf=(e,t,n,r)=>!(!yn(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)||!yn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==JC||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!UC(e.config,r)||r.some(o=>e.config[o].original.present)||!UC(e.deployment,Xs)||!yn(e.helper)||e.helper.path!==t.helper||!D$(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),$$=(e,t)=>qf(e,t,Yf,Js),M$=(e,t)=>qf(e,t,2,L$),B$=(e,t)=>qf(e,t,3,N$),F$=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),HC=e=>({...e,version:Yf,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),Qf=async e=>{if(!await Zs(e.journal))return;let t;try{t=JSON.parse(await Zf(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if($$(t,e))return t;if(B$(t,e))return HC(t);if(M$(t,e))return HC(F$(t));throw new Error(`${e.journal} is not a valid ownership journal`)},GC=async(e,t)=>{await Ll(e,`${JSON.stringify(t,null,2)}
204
+ `,384)},Ys=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(!yn(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},W$=async(e,t,n)=>{let r=await gn(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:it(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[it(t.metaEntry)]}}}let c=Ys(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!Ks(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:it(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...it(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=Ys(r.value);let c=Lt(e.library,`${o}.json`);if(!await Zs(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=it(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(Lt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:JC};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?it(r.value):{},appliedId:s,entries:[...a,i]}}},U$=(e,t)=>{let n=eo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},rk=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),H$=async(e,t,n,r,o,a,s)=>{let i=rk(),c=Object.fromEntries(Js.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(Xs.map(d=>[d,{original:s?.deployment[d].original??nk(r.value,d),lastWritten:i[d]}]));return{version:Yf,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??it(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await zs(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Tl=e=>({status:"manual",messages:[e]}),G$=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}`)]}},V$=y$(s$),K$=new Set(Rl),j$=async e=>{try{let{stdout:t}=await V$("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return yn(n)?Object.keys(n):void 0}catch{return}},to=async(e,t={})=>{let n=t.readManagedPolicyKeys??j$;for(let r of e.managedPolicies){let o=await w$(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)&&!K$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},em=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.`},tm=e=>(e.platform??f$)()==="darwin",ok=async(e,t,n={})=>{if(!tm(n))return Tl("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=jt(n),a=await to(o,n);if(a&&r.push({audience:"admin",message:em(a)}),r.length>0)return G$(r);let s=!1,i=!1,c=[o.journal];try{let l=ee(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??O$)())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=b$((n.credentialCommand??(()=>Jf(d)))(),d),p=v$(u),f=await Qf(o),m=await zs(o.helper);if(f&&m.present&&m.content!==f.helper.lastWritten&&m.content!==f.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!f&&m.present&&m.content!==p)throw new Error("the Claude Desktop credential helper path contains a foreign file");let h=await W$(o,f,n.randomUUID??a$),w=Lt(o.library,`${h.configId}.json`);c=[o.journal,o.helper,w,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await gn(w),g=await gn(o.appConfig),b=U$(e,o.helper),k=await H$(o,h,y,g,p,b,f);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${h.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 GC(o.journal,k),i=!0,await Ll(o.helper,p,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await GC(o.journal,k));let C=it(y.value);for(let E of Js)jf(C,E,b[E]);await Mn(w,C),h.metaToWrite&&await Mn(o.meta,h.metaToWrite);let S=it(g.value),I=rk();for(let E of Xs)jf(S,E,I[E]);return await Mn(o.appConfig,S),{status:"configured",changedFiles:[o.journal,o.helper,w,...h.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.",...El]}}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.`]}:Tl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},VC=(e,t,n,r)=>{let o=it(e);for(let a of n){let s=t[a];Ks(nk(e,a),s.lastWritten)?jf(o,a,s.original):r.push(a)}return o},ak=async(e,t={})=>{if(!tm(t))return{status:"not-found",messages:[]};if((t.appRunning??Pl)())return Tl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=jt(t);try{let r=await Qf(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Lt(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 gn(o),i=s.value;s.present&&(i=VC(s.value,r.config,Js,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await gn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let m=Ys(l.value),h=it(l.value.entries),w=h.findIndex(b=>b.id===r.configId),y=w>=0?h[w]:void 0,g=y!==void 0&&Ks(y,r.metaEntry);if(y!==void 0&&!g&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=it(l.value),m===r.configId){let b=r.originalAppliedId;b&&h.some(k=>k.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&g?(h.splice(w,1),d.entries=h):c&&y===void 0&&(d.entries=h)}else{let b=Ks(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&m!==r.configId?(g&&h.splice(w,1),d={...it(l.value),entries:h}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await qo(o,{force:!0}):await Mn(o,i)),l.present&&(u?await qo(n.meta,{force:!0}):Ks(l.value,d)||await Mn(n.meta,d));let p=await gn(n.appConfig);if(p.present){let m=VC(p.value,r.deployment,Xs,a);!r.deploymentFileExisted&&Object.keys(m).length===0?await qo(n.appConfig,{force:!0}):await Mn(n.appConfig,m)}else r.deploymentFileExisted&&a.push("deployment config file");let f=await zs(n.helper);return f.present&&(f.content===r.helper.lastWritten||f.content===r.helper.previousWritten)?r.helper.original.present?await Ll(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await qo(n.helper,{force:!0}):(f.present||r.helper.original.present)&&a.push("credential helper"),await qo(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?[]:xl]}}catch(r){return Tl(`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.`)}},nm=async(e,t={})=>{if(!tm(t))return!1;let n=jt(t);if(await to(n,t))return!1;try{let r=await gn(n.meta);if(!r.present)return!1;let o=Ys(r.value),a=await gn(Lt(n.library,`${o}.json`)),s=await gn(n.appConfig);if(!a.present||!s.present)return!1;await _l(n.helper,jC.X_OK);let i=Ht(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}},sk=async(e={})=>{try{let t=jt(e),n=await zs(t.helper);if(!n.present||typeof n.content!="string")return;let r=tk(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},ik=async(e,t={})=>{if(!await nm(e,t))return!1;let n=jt(t);try{let r=await Qf(n);if(!r)return!1;let o=await gn(n.meta);if(!o.present||Ys(o.value)!==r.configId)return!1;let a=await zs(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=tk(a.content??"");return s?await(t.helperLauncherAvailable??T$)(s):!1}catch{return!1}};import{createHash as vk,randomUUID as Sk}from"node:crypto";import{spawn as Z$,spawnSync as Y$}from"node:child_process";import{link as lm,mkdir as rm,open as Ik,readFile as om,readdir as Ek,rename as xk,rm as Zt,stat as Rk}from"node:fs/promises";import{homedir as dm}from"node:os";import{basename as Ok,dirname as Qs,join as sa,win32 as J$}from"node:path";import{isDeepStrictEqual as ea}from"node:util";var Te="HKCU\\SOFTWARE\\Policies\\Claude",qs="HKLM\\SOFTWARE\\Policies\\Claude",Bl=5,ia="inferenceGatewayApiKey",Pe=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ia],ck=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ia],lk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ia],dk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ia],Tk="Managed by anyray-connect; dynamic credential only.",X$=e=>/^[A-Za-z]:[\\/]/.test(e)&&J$.isAbsolute(e),uk=e=>{if(!X$(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)},_k=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!uk(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&&!uk(e.args[0]))throw new Error("the credential helper does not use print-key --json")},um=(e={})=>sa((e.home??dm)(),".anyray","bin","claude-desktop-credential-helper.cmd"),z$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},q$=e=>(_k(e),["@echo off",`REM ${Tk}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(z$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
205
+ `)),Q$=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},Pk=e=>{let t=e.split(`\r
206
+ `);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${Tk}`||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(Q$);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return _k(s),s}catch{return}},eM=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>Rk(r)))).every(r=>r.isFile())}catch{return!1}},tM=async(e,t)=>{let n=Pk(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??eM)(n)}catch{return!1}},am=e=>({sha256:no(e),content:e}),pk=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Nt(t,["sha256","content"])&&lM(t.sha256)&&typeof t.content=="string"&&no(t.content)===t.sha256&&Pk(t.content)!==void 0},pm=()=>{let e=Y$("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??"")},nM=async(e,t)=>{await rm(Qs(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await Ik(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await lm(n,e)}finally{await Zt(n,{force:!0}).catch(()=>{})}},rM=e=>`${Ok(e)}.anyray-old-`,oM=e=>`${e}.anyray-old-${process.pid}-${Sk()}`,Dk=async(e,t)=>{try{await lm(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await Zt(t,{force:!0}),!0},$l=async(e,t,n,r,o)=>{let a=oM(e),s=n===void 0?void 0:no(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${Sk()}`,c=!1;try{if(i&&n!==void 0){let d=await Ik(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 xk(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await oa(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await lm(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await aa(e)!==s))throw new Error("credential helper publication verification failed");await Zt(a,{force:!0}),c=!1}catch(l){throw c&&await Dk(e,a).catch(()=>!1),l}finally{i&&await Zt(i,{force:!0}).catch(()=>{})}},sm=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,aM=String.raw`
207
207
  $ErrorActionPreference = 'Stop'
208
208
  try {
209
209
  $request = ConvertFrom-Json ([Console]::In.ReadToEnd())
@@ -272,16 +272,16 @@ try {
272
272
  exit 5
273
273
  } catch {
274
274
  exit 6
275
- }`,Bn=async e=>new Promise((t,n)=>{let r=F$("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",z$],{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(cm(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(cm({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Nt=(e={})=>sa((e.home??pm)(),".anyray","claude-desktop-windows.json"),q$=e=>sa((e.home??pm)(),".anyray","claude-desktop-windows.lock"),ra=class extends Error{},Q$=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},hm=async e=>{let t=q$(e);await am(Qs(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=Ak("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=sa(t,"owner.json");try{await am(t,{mode:448}),await we(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
276
- `)}catch(a){if(a.code!=="EEXIST")throw await Zt(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await sm(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!Q$(i.pid)}catch{try{s=Date.now()-(await Ik(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new ra;await Zt(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await sm(o,"utf8")).nonce===r&&await Zt(t,{recursive:!0,force:!0})}catch{}}}throw new ra},_k=()=>Object.fromEntries(Pe.map(e=>[e,{present:!1}])),no=e=>Ak("sha256").update(e).digest("hex"),eM=(e,t)=>t.present?e===ia?{present:!0,type:t.type,sha256:no(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},ta=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?no(e.value??"")===t.sha256:e.value===t.value:!0,Lt=(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===ia?Lt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Lt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},dk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Lt(e,Pe)&&Pe.every(t=>Bl(e[t],t)),uk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Lt(e,ak)&&ak.every(t=>Bl(e[t],t)),tM=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),ym=(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 Lt(n,r)&&n.path===fm(t)&&(n.lastWritten===void 0||lk(n.lastWritten))&&(n.pending===void 0||lk(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},nM=(e,t)=>Lt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Ml&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&dk(e.lastWritten)&&(e.pending===void 0||dk(e.pending))&&ym(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),rM=e=>Lt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&uk(e.lastWritten)&&(e.pending===void 0||uk(e.pending)),pk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Lt(e,sk)&&sk.every(t=>Bl(e[t],t)),oM=(e,t)=>Lt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&pk(e.lastWritten)&&(e.pending===void 0||pk(e.pending))&&ym(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),fk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Lt(e,ik)&&ik.every(t=>Bl(e[t],t)),aM=(e,t)=>Lt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&fk(e.lastWritten)&&(e.pending===void 0||fk(e.pending))&&ym(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),mk=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),gm=e=>{let{pending:t,...n}=e;return{...n,version:Ml,lastWritten:mk(e.lastWritten),...t?{pending:mk(t)}:{}}},hk=e=>({...e,chatTabEnabled:{present:!1}}),sM=e=>{let{pending:t,...n}=e;return gm({...n,version:4,lastWritten:hk(e.lastWritten),...t?{pending:hk(t)}:{}})},yk=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),iM=(e,t)=>gm({version:4,registryKey:Te,keyExisted:e.keyExisted,lastWritten:yk(e.lastWritten),...e.pending?{pending:yk(e.pending)}:{},helper:{path:fm(t)}}),wm=async(e,t=!0)=>{let n=Nt(e),r=Qs(n),o=`${Ek(n)}.anyray-old-`,a=(await vk(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>sa(r,l)),s=n;if(!await x(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await Sk(a[0],n):s=a[0]}let i=await B(s),c=rM(i)?iM(i,e):oM(i,e)?sM(i):aM(i,e)?gm(i):nM(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>Zt(l,{force:!0}))),c},gk=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),cM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Te,keyExisted:e.keyExisted,lastWritten:gk(e.lastWritten),...e.pending?{pending:gk(e.pending)}:{}}:e,Ll=async(e,t)=>{let n=Nt(t),r=`${JSON.stringify(cM(e),null,2)}
277
- `;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},lM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,dM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),uM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),pM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),fM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===pM(t).toUpperCase(),wk=(e,t,n,r,o)=>{let a=Pe.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},mM=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,hM=(e,t)=>{if(!Rl(e,!0))return!1;let n=mM(t);if(uM.has(n))return!1;if(dM.has(n))return n==="REG_EXPAND_SZ"?!0:!LC(e,!0)},yM=(e,t)=>{let n=_k(),r=!1,o=!1,a=!1,s=t.toUpperCase()===qs.toUpperCase(),i=(l,d)=>{if(!s)return;let u=hM(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),wk(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||fM(d,t))continue;let u=lM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),wk(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Mn=async(e,t=Te)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:_k(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return yM(n.stdout,t)},gr=async e=>{let t=await Mn(e,qs);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...Pe.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},bm=e=>e.unparsed?`This machine may have a Claude policy under ${qs} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${qs} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${qs} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Fl=(e,t)=>yr(eo(e,t)),Pk=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],gM=(e,t)=>{let n=Fl(e,t);return Object.fromEntries(Pe.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},wM=(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}}),bM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,lm=e=>Object.fromEntries(Pe.map(t=>[t,eM(t,e[t])])),bk=(e,t,n,r)=>({version:Ml,registryKey:Te,keyExisted:e,lastWritten:lm(t),helper:{path:n,lastWritten:im(r)}}),AM=(e,t,n,r,o,a)=>({version:Ml,registryKey:Te,keyExisted:e,lastWritten:lm(t),pending:lm(n),helper:{path:r,...o?{lastWritten:im(o)}:{},pending:im(a)}}),dm=(e,t,n)=>ta(n,e.lastWritten[t])||e.pending!==void 0&&ta(n,e.pending[t]),oa=async e=>{try{let t=await sm(e,"utf8");return{content:t,sha256:no(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},aa=async e=>(await oa(e))?.sha256,na=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,$l=async(e,t)=>{let n=J$(e),r;try{r=await vk(Qs(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>sa(Qs(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([oa(e),oa(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!na(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await Tk(e,a))throw new Error("credential helper changed during recovery");return}if(t&&na(t,s.sha256)&&na(t,i.sha256)){await Zt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Am=async(e,t,n)=>(n.present?await e(Pk(Te,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Te,"/v",t,"/f"])).code===0,CM=async(e,t,n)=>{let r=!0,o=await Mn(e);for(let a of Pe)if(!ea(o.values[a],t[a])){if(!ea(o.values[a],n[a])){r=!1;continue}await Am(e,a,t[a])||(r=!1),o=await Mn(e)}return r&&Pe.every(a=>ea(o.values[a],t[a]))},Qe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Nt(n)]}}),Dk=async(e,t,n,r={})=>{if(!Ee(t))return Qe("A valid personal ark_ gateway key is required.",!1,r);let o=fm(r),a;try{a=V$((r.credentialCommand??zf)())}catch{return Qe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=no(a),i=r.runReg??Bn,c=Nt(r),l;if(!n.dryRun)try{l=await hm(r)}catch(h){return Qe(h instanceof ra?"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,p,f,m=!1;try{let h=await gr(i);if(h)return Qe(bm(h),!1,r);let w=await wm(r,!n.dryRun);n.dryRun||await $l(o,w);let y=await Mn(i),g=gM(e,o),b=await oa(o),k=b?.sha256,C=!1;if(d=w,u=y,p=g,w){let E=Pe.find(R=>!dm(w,R,y.values[R]));if(E)return Qe(`Claude's ${E} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!na(w,k))return Qe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=bM(w)}else{if(k!==void 0&&k!==s)return Qe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let E=y.foreignState||Pe.some(W=>y.values[W].present),R=Pe.every(W=>ea(y.values[W],g[W])),P=Pe.every(W=>ea(y.values[W],wM(e,t.trim())[W]));if(E&&!R&&!P)return Qe(`Existing Claude third-party-inference policy values under ${Te} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(C=P,R&&k===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Te} into an owner-only journal without rewriting them.`]}:(await Ll(bk(y.keyPresent,g,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Te} into the ownership journal.`]})}if(C){let E=!0;try{E=(r.appRunning??mm)()}catch{}if(E)return Qe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let S=AM(w?.keyExisted??y.keyPresent,y.values,g,o,b?.content,a);if(f=S,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Te}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Ll(S,r),m=!0;for(let E of Pe){let R=await Mn(i);if(!ta(R.values[E],S.lastWritten[E])&&!ta(R.values[E],S.pending[E]))throw new Error("registry value changed during apply");if(!ea(R.values[E],g[E])&&!await Am(i,E,g[E]))throw new Error("registry write failed")}let I=await Mn(i);if(!Pe.every(E=>ta(I.values[E],S.pending[E])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await Y$(o,a):await Nl(o,k,a,"apply",r)),await aa(o)!==s)throw new Error("credential helper verification failed");return await Ll(bk(S.keyExisted,g,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Te}.`,`Installed or updated the dynamic credential helper at ${o}; no personal key is stored in policy or the ownership journal.`,"Fully quit and reopen Claude Desktop to load the policy.",...Il]}}catch{if(!m||!u||!p||!f)return Qe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await $l(o,f);let h=!0,w=await oa(o),y=f.helper.pending;if(w?.sha256!==f.helper.lastWritten?.sha256&&(y!==void 0&&w?.sha256===y.sha256?f.helper.lastWritten?(await Nl(o,y.sha256,f.helper.lastWritten.content,"rollback",r),h=await aa(o)===f.helper.lastWritten.sha256):await Nl(o,y.sha256,void 0,"rollback",r):h=w===void 0&&f.helper.lastWritten===void 0),h&&await CM(i,u.values,p))return d?await Ll(d,r):await Zt(c,{force:!0}),Qe("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return Qe("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},Lk=async(e,t={})=>{let n=t.runReg??Bn,r=Nt(t),o;if(!e.dryRun)try{o=await hm(t)}catch(a){return Qe(a instanceof ra?"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 wm(t,!e.dryRun);a&&!e.dryRun&&await $l(a.helper.path,a);let s=await Mn(n);if(!a)return Pe.filter(m=>s.values[m].present).length>0?Qe(`Claude policy values exist under ${Te}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=Pe.filter(f=>s.values[f].present&&!dm(a,f,s.values[f])),c=await aa(a.helper.path),l=c!==void 0&&!na(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Te}.`,`Would remove the Anyray-owned credential helper at ${a.helper.path}.`,...i.length||l?[`Would preserve changed values: ${[...i,...l?["credential helper"]:[]].join(", ")}.`]:[]]};let d=!1,u=new Set(i);for(let f of Pe){let h=(await Mn(n)).values[f];if(h.present){if(!dm(a,f,h)){u.add(f);continue}await Am(n,f,{present:!1})||(d=!0)}}let p=await aa(a.helper.path);if(p!==void 0)if(na(a,p))try{await Nl(a.helper.path,p,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?Qe(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await Zt(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Te}.`,"Removed the Anyray-owned dynamic credential helper when its content still matched the journal.",...u.size?[`Preserved values changed after Connect: ${[...u].join(", ")}.`]:[],...u.size?[]:El]})}catch{return Qe(`Could not safely inspect or revert ${Te}; no unproven value was removed.`,!1,t)}finally{await o?.()}},Nk=async(e,t={})=>{let n=t.runReg??Bn;if(!await x(Nt(t)))return;let r;try{r=await hm(t);let o=await wm(t);if(o&&await $l(o.helper.path,o),!o||o.pending||await gr(n)!==void 0)return;let a=await Mn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ht(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Pe.every(l=>ta(a.values[l],o.lastWritten[l]))))return;let i=await aa(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 Z$(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?.()}},$k=async(e,t={})=>await Nk(e,t)!==void 0,Mk=async(e,t={})=>await Nk(e,t)==="dynamic";var ca=(e=vM())=>e==="win32"?mm:_l,Cm="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Hl=async(e,t={})=>{let n=(t.profileRoot??Qr)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Cm};if((t.appRunning??ca(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await Bk.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 Sl(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 "+Cm}:{ok:!1,reason:"no Claude Desktop third-party session store found \u2014 the app has not run in this mode yet",remedy:"Open Claude Desktop with Anyray configured, sign in with your usual Claude account, quit it, then run this again."};let o=await(t.findBinary??xC)();if(!o)return{ok:!1,reason:"the Claude Code CLI was not found",remedy:"Install Claude Code (the conversion step uses its importer), then run this again."};let a=Wl(t.stagingRoot??SM(),`anyray-history-${process.pid}-${kM()}`);try{let s=await(t.runImporter??RC)({binary:o,exportPath:e,configDir:Wl(a,"config"),workDir:Wl(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. "+Cm};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 TC(r.dir,s.conversations),c=await _C({stagedProjectsDir:Wl(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 Bk.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as vt}from"node:fs";import{homedir as jM}from"node:os";import{join as Jt,sep as ZM}from"node:path";import{isDeepStrictEqual as Kl}from"node:util";import{constants as IM}from"node:fs";import{promises as G}from"node:fs";import{dirname as la,isAbsolute as vm,join as te,relative as Ul,resolve as Yt,sep as ei}from"node:path";import{randomUUID as jl}from"node:crypto";var wn=448,ti=384,Uk=448,EM=4,Sm=3e4,Gk=5e3,xM=10*6e4,km=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ni=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),Vk=(e,t)=>{let n=Ul(Yt(e),Yt(t));return n===""||!n.startsWith(`..${ei}`)&&n!==".."&&!vm(n)},ro=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return ct(n)?{raw:t,value:n}:void 0}catch(t){return kt(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},kt=e=>e instanceof Error&&"code"in e,RM=e=>{try{return process.kill(e,0),!0}catch(t){return kt(t)&&t.code==="EPERM"}},Kk=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 p=Number(u[1]);return Number.isSafeInteger(p)&&p>0?{name:d,generation:p}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=te(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));ct(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}},jk=e=>{if(e.pid===void 0||!RM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Sm&&t-e.createdAtMs>xM},OM=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(la(t),{recursive:!0,mode:wn});let n=jl(),r,o=!1;try{await G.mkdir(t,{mode:wn}),o=!0}catch(i){if(!kt(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(!jk(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(p=>Date.now()-p.mtimeMs).catch(()=>0)<=Sm)return}let l=te(t,Kk(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
278
- `,{flag:"wx",mode:ti}),r=l}catch(d){if(kt(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(!ct(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},Gk);return s.unref(),async()=>{clearInterval(s);try{(await Gl(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},TM=async(e,t,n)=>{await G.mkdir(la(e),{recursive:!0,mode:wn});let r=await OM(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!kt(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${jl()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
279
- `,{mode:ti,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<EM;n+=1){let r=await ro(e);if(!r)return"failed";let o=t(r.value);if(!o||Kl(o,r.value))return"unchanged";try{if(await TM(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},Fk=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},Yl=async e=>{let t=[];for(let n of await Fk(e))for(let r of await Fk(te(e,n)))t.push(te(e,n,r));return t},_M=e=>Array.isArray(e.skills)?e.skills.filter(t=>ct(t)&&ni(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],PM=async e=>{let t=te(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await Yl(t)){let o=await ro(te(r,"manifest.json"));if(!o)continue;let a=r.split(ei).at(-1)??"";for(let s of _M(o.value))n.push({account:a,packageDir:r,entry:s})}return n},DM=async e=>{let t=await ro(te(e,".claude-plugin","plugin.json"));return!!t&&ni(t.value.name)},LM=(e,t)=>{let n=vm(t)?Yt(t):Yt(e,t);if(!Vk(e,n)||n===Yt(e))return;let r=Ul(Yt(e),n);return r.length>0?{absolute:n,relative:r}:void 0},NM=async e=>{let t=await Yl(te(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(ei).includes("skills-plugin"))continue;let o=te(r,"cowork_plugins"),a=await ro(te(o,"installed_plugins.json"));if(!a||!ct(a.value.plugins))continue;let s=r.split(ei).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!ni(i)||!Array.isArray(c)))for(let l of c){if(!ct(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=LM(o,l.installPath);!d||!await DM(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:te(r,"cowork_account_settings.json")})}}return n},$M=async e=>{let t=await ro(te(e,"claude_desktop_config.json"));return!t||!ct(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>ni(n)&&n.toLowerCase()!=="anyray"&&ct(r)))},Zk=async e=>{let[t,n,r]=await Promise.all([PM(e),NM(e),$M(e)]);return{skills:t,plugins:n,localMcpServers:r}},Im=async e=>{let t=await Zk(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)}},Wk=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(!ni(o.name))return!1;let a=te(n,o.name);if(o.isSymbolicLink())return!1;if(o.isDirectory()){if(!await t(a))return!1}else if(!o.isFile())return!1}return!0};return t(e)},MM=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=te(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,wn);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?Uk:ti)}}};await t(e),await G.chmod(e,wn)},Yk=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},Vl=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(!Kl(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 Vl(te(e,s),te(t,s)))return!1}else if(!i.isFile()||!await Yk(te(e,s),te(t,s)))return!1}return!0}catch{return!1}},Jk=e=>`${e}.anyray-incomplete`,Xk=async(e,t)=>{let n=!1;if(t){await G.mkdir(la(e),{recursive:!0,mode:wn});try{await G.mkdir(e,{mode:wn}),n=!0}catch(l){if(!kt(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=jl(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let p;try{p=await Gl(e)}catch{return}if(p){if(!jk(p)||!Number.isSafeInteger(p.generation+1))return;d=p.generation+1}else if(await G.stat(e).then(m=>Date.now()-m.mtimeMs).catch(()=>0)<=Sm)return}let u=te(e,Kk(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
280
- `,{flag:"wx",mode:ti}),o=u}catch(p){if(kt(p)&&p.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(!ct(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},Gk);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{}}}},zk=async e=>{let t=await Xk(e,!1);t&&await t.complete()},BM=async(e,t,n)=>{let r=Jk(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Vl(e,t))return await zk(r),"present"}catch(c){if(!kt(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 Xk(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:wn})}catch(c){if(!kt(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 p=te(c,u.name),f=te(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(f,{mode:wn})}catch(h){if(!kt(h)||h.code!=="EEXIST")throw h;let w=await G.lstat(f);if(!w.isDirectory()||w.isSymbolicLink())return"conflict"}let m=await s(p,f);if(m!=="copied")return m}else if(u.isFile())try{await G.copyFile(p,f,IM.COPYFILE_EXCL);let m=await G.stat(p);await G.chmod(f,(m.mode&73)!==0?Uk:ti)}catch(m){if(!kt(m)||m.code!=="EEXIST")throw m;if(!await Yk(p,f))return"conflict"}else return"failed"}catch(m){return kt(m)&&m.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await Vl(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},qk=async(e,t,n,r)=>{if(!await Wk(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Vl(e,t))return await zk(Jk(t)),"present"}catch(a){if(!kt(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(la(t),{recursive:!0,mode:wn});let o=te(la(t),`.anyray-stage-${jl()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await Wk(o)?(await MM(o),await n?.(t),await BM(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},Hk=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),FM=async e=>{let t=await Yl(te(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await ro(te(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},WM=async e=>{let t=await Yl(te(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(ei).includes("skills-plugin"))try{await G.access(te(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},HM=async(e,t,n,r,o)=>{let a=te(t,"manifest.json");for(let s of e){let i=te(s.packageDir,"skills",s.entry.name);try{await G.access(te(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=te(t,"skills",s.entry.name),l=await qk(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,p=>{let f=Array.isArray(p.skills)?p.skills:[];if(f.find(h=>ct(h)&&typeof h.name=="string"&&h.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...p,skills:[...f,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},Qk=(e,t)=>({...e,installPath:t}),UM=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=vm(r.installPath)?Yt(r.installPath):Yt(o,r.installPath),s=Qk(e,Ul(Yt(t),Yt(n))),i={...r,installPath:Ul(Yt(o),a)};return Kl(s,i)},GM=async(e,t,n)=>{let r=await ro(e);if(!r||!ct(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":Zl(t,a=>{let s=ct(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},VM=async(e,t,n,r,o)=>{let a=te(t,"cowork_plugins"),s=te(a,"installed_plugins.json"),i=te(t,"cowork_account_settings.json");for(let c of e){let l=te(a,c.relativeInstallPath);if(!Vk(a,l)){n.invalid+=1;continue}let d=await qk(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,p=!1;await Zl(s,m=>{let h=ct(m.plugins)?m.plugins:{},w=h[c.id],y=Array.isArray(w)?w:[],g=y.find(k=>ct(k)&&k.scope==="user");if(g){u=UM(c.entry,la(c.settingsFile),c.packageDir,g,t),p=!u;return}let b=Qk(c.entry,l);return{...m,version:typeof m.version=="number"?m.version:2,plugins:{...h,[c.id]:[...y,b]}}})==="failed"?n.failed+=1:p?n.conflicts+=1:await GM(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},KM=async(e,t,n)=>{let r=te(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await Zl(r,c=>{let l=ct(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=Kl(l[o],a)?"present":"conflict";return}return{...c,mcpServers:{...l,[o]:a}}})==="failed"?n.failed+=1:s.value==="present"?n.alreadyPresent+=1:s.value==="conflict"?n.conflicts+=1:n.migrated+=1}},ev=async(e,t,n={})=>{let r=await Zk(e),o=km("skill"),a=km("plugin"),s=km("local-mcp"),i=[],c=[],l=Hk(r.skills,n.account,n.allAccounts),d=Hk(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let p=new Set(n.allowedAccounts);if([...new Set([...l.map(m=>m.account),...d.map(m=>m.account)])].some(m=>!p.has(m)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,sourceChanged:!0,retryable:[]}}if(l.length>0){let p=await FM(t);p.state==="found"?await HM(l,p.path,o,n.beforeDirectoryPublish,n.afterDirectoryClaim):p.state==="missing"?i.push("skill"):(o.conflicts+=l.length,c.push("skill"))}if(d.length>0){let p=await WM(t);p.state==="found"?await VM(d,p.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):p.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await KM(r.localMcpServers,t,s);let u=[o,a,s];return{outcomes:u,blocked:i,ambiguous:c,sourceChanged:!1,retryable:u.filter(p=>p.failed>0).map(p=>p.kind)}};var YM=async e=>{try{return await vt.access(e),!0}catch{return!1}},tv=448,JM=384,rv={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},XM=["code","cowork"],Rm=(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.",Em=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),ov=async e=>{let t;try{t=(await vt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&Xo(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await vt.readdir(Jt(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&Xo(a.name)).map(a=>a.name);for(let a of o)n.push(Jt(e,r,a))}catch{}return n},zM=async e=>{try{return(await vt.readdir(e)).filter(t=>t.startsWith(Nn)&&t.endsWith(".json")).map(t=>t.slice(Nn.length,-5)).filter(Xo)}catch{return[]}},qM=async(e,t)=>{let n=await ov(Jt(e,rv[t])),r=[];for(let o of n){let a=await zM(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(ZM).slice(-2)[0]})}return r},QM=async(e,t)=>{if(t==="cowork"){let r=await Sl(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await ov(Jt(e,rv.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},eB=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await vt.copyFile(e,n),await vt.chmod(n,JM),await vt.rename(n,t)},tB=async(e,t)=>{try{let n=JSON.parse(await vt.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||!Xo(o)?!1:(await vt.access(Jt(t,".claude","projects",Kf(r),`${o}.jsonl`)),!0)}catch{return!1}},nB=async(e,t,n,r)=>{let o=Em(e),a=await jf(n);for(let s of t)await rB(e,s,n,r,a,o);return o},rB=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Nn}${s}.json`,c=Jt(t.dir,i);try{if(e==="code"){if(!await tB(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=Jt(t.dir,`${Nn}${s}`),d=Jt(n,`${Nn}${s}`),u=await vt.readdir(l);await vt.mkdir(d,{mode:tv});for(let p of u)await vt.cp(Jt(l,p),Jt(d,p),{recursive:!0,force:!1,errorOnExist:!0});await vt.chmod(d,tv)}await eB(c,Jt(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},nv=(e,t,n,r=[])=>{let o=new Map;for(let{sources:s}of e)for(let i of s){let c=o.get(i.account)??{sessions:0,portable:!1};c.sessions+=i.ids.length,o.set(i.account,c)}for(let s of r){let i=o.get(s)??{sessions:0,portable:!1};i.portable=!0,o.set(s,i)}let a=[...o.entries()].sort((s,i)=>i[1].sessions-s[1].sessions).map(([s,i])=>{let c=i.sessions===0?"portable configuration":`${i.sessions} session${i.sessions===1?"":"s"}${i.portable?" plus portable configuration":""}`;return` ${t} --account ${s.slice(0,8)} (${c})`});return{ok:!1,kind:"account-ambiguous",reason:n,remedy:["Pick the one you want, or take everything:",...a,` ${t} --all-accounts`].join(`
281
- `)}},xm=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),av=async e=>{let t=[];for(let n of XM)t.push({lane:n,sources:await qM(e,n)});return t},sv=async(e={})=>{let t=(e.firstPartyRoot??(()=>Us()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([av(t),Im(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=xm(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}},oo=async(e={})=>{let t=(e.home??jM)(),n=(e.firstPartyRoot??(()=>Us()))(),r=(e.thirdPartyRoot??(()=>Qr()))();if(!n||!r)return{ok:!1,kind:"platform-unsupported",reason:"this platform has no Claude Desktop third-party profile",remedy:"Migration applies to macOS and Windows, where Desktop runs third-party mode in its own profile."};if((e.appRunning??ca())())return{ok:!1,kind:"app-running",reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop and run this again \u2014 it rewrites its session list on exit, which would undo the migration."};let[o,a]=await Promise.all([av(n),Im(n)]),s;if(e.account){let f=e.account;for(let w of o)w.sources=w.sources.filter(y=>y.account.startsWith(f));let m=a.accounts.filter(w=>w.startsWith(f));if(o.every(w=>w.sources.length===0)&&m.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${f}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let h=xm(o);for(let w of m)h.add(w);if(h.size>1)return nv(o,e.command??"anyray-connect desktop --migrate",`"${f}" matches ${h.size} accounts`,m);s=[...h]}else if(!e.allAccounts){let f=xm(o);for(let m of a.accounts)f.add(m);if(f.size>1)return nv(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${f.size} accounts`,a.accounts);s=[...f]}let i=e.command??"anyray-connect desktop --migrate",c=!await YM(r),l=await ev(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:s});if(l.sourceChanged)return{ok:!1,kind:"account-ambiguous",reason:"the previous Claude Desktop profile changed during migration and now holds local data for another account",remedy:`Re-run \`${i}\` so the account choice is made from a fresh snapshot.`};let d=[],u=[];for(let{lane:f,sources:m}of o){if(m.length===0){d.push(Em(f));continue}let h=await QM(r,f);if("missing"in h){u.push({lane:f,reason:h.missing,waiting:m.reduce((w,y)=>w+y.ids.length,0)}),d.push(Em(f));continue}d.push(await nB(f,m,h.dir,t))}if(!(d.some(f=>f.migrated>0||f.alreadyPresent>0)||l.outcomes.some(f=>f.migrated>0||f.alreadyPresent>0||f.conflicts>0))&&(u.length>0||l.blocked.length>0)){let f=u[0];return f?{ok:!1,kind:f.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:f.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${f.lane} store`:`Claude Desktop has no ${f.lane} store in its third-party profile yet`,remedy:Rm(f.reason,f.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 oB=e=>[Ve(e)],iv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...oB(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await x(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var cv="1.21459.0",cB=iB(aB),lB=async e=>{try{let{stdout:t}=await cB("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},dB=async e=>{try{return await sB(e)}catch{return}},lv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",uB=["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."],da=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(dv??=uv({}),dv):uv(e),dv,uv=async e=>{let t=(e.home??oi)(),n=["/Applications/Claude.app",bn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??lB,o=e.readClaudeAppBundle??dB;for(let a of n){let s=await r(bn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${lv}`}),c=kl(s,cv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${cv} or newer.`);let l=await o(bn(a,"Contents","Resources","app.asar"));return l?ZC.some(d=>!l.includes(d))?i("its local config seam no longer matches the shape Connect writes."):{supported:!0,detectedVersion:s,appPath:a}:i("its app bundle could not be read to verify the local config seam.")}return{supported:!1,message:`Could not verify the installed Claude Desktop version. ${lv}`}},Jl="anyray",mv="--anyray-owner=claude-desktop-v1",Xl=(e={})=>{let t=(e.platform??wr)(),n=(e.home??oi)();return t==="darwin"?jt(e).appConfig:t==="win32"?bn(process.env.APPDATA??bn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):bn(n,".config","Claude","claude_desktop_config.json")},Dm=(e={})=>bn((e.home??oi)(),"Library","Application Support","Claude","claude_desktop_config.json"),hv=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,mv]}},ao=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),yv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},pB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),fB=e=>{if(!ao(e)||!yv(e,["command","args"]))return!1;let t=hv();return e.command===t.command&&pB(e.args,t.args)},mB=e=>ao(e)&&Array.isArray(e.args)&&e.args.at(-1)===mv,hB=e=>{if(!ao(e)||!yv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||Ue(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===Jn&&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!Ue(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},yB=e=>e===void 0?"absent":fB(e)?"exact":mB(e)||hB(e)?"stale-owned":"foreign",Me=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},so=async e=>{let t=await x(e),n;try{n=await B(e)}catch{throw new Me(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!ao(n.mcpServers))throw new Me(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(ao(n.mcpServers)?n.mcpServers:void 0)?.[Jl];return{path:e,fileExisted:t,json:n,entry:o,ownership:yB(o)}},zl=e=>{if(e.ownership==="foreign")throw new Me(`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.`)},gv=(e,t)=>{let n={...e},r=ao(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},Tm=async(e,t)=>{if(Om(e.entry,t))return;let n=await so(e.path);if(!Om(n.entry,e.entry))throw new Me(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await $n(e.path,gv(n.json,t)),{reading:e,afterEntry:t}},_m=async e=>{let t=await so(e.reading.path);if(!Om(t.entry,e.afterEntry))throw new Me(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=gv(t.json,e.reading.entry);await $n(e.reading.path,n)},gB=async e=>{if(!ce())throw new Me(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Oe()} is temporary); no inference setting was changed.`);let t=await so(Xl(e));zl(t);let n=Dm(e),r=(e.platform??wr)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&zl(r),{active:t,...r?{legacy:r}:{}}},pv=async e=>{let t=await so(Xl(e));zl(t);let n=Dm(e),r=(e.platform??wr)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&zl(r),{active:t,...r?{legacy:r}:{}}},wB=async e=>{let t=[];try{let n=await Tm(e.active,hv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Tm(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await _m(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Me(`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 _m(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Me(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},bB=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Tm(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await _m(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Me(`Claude Desktop MCP cleanup failed and could not restore ${r.join(", ")}. Re-run revert after resolving the file conflict.`,r):n}return t.map(n=>n.reading.path)},fv=e=>{let t=e.clientKey?`${e.clientKey} (your personal gateway key - keep it private)`:`${e.placeholderKey} (placeholder - the gateway holds the real key)`;return["Step 1 - Turn on Developer Mode."," In the menu bar at the VERY TOP of the screen (NOT the in-app help panel):"," Help -> Troubleshooting -> Enable Developer Mode"," (Windows: open the menu at the top-left of the sign-in screen.)",' A "Developer" menu then appears in that same top-of-screen menu bar.',"","Step 2 - Open the Developer MENU in the menu bar (shown below) - NOT Settings:",""," +----------------------------------------------------------------+"," | Claude File Edit View Window [Developer] Help | <- macOS menu bar (very top of screen)"," +-------------------------------------^--------------------------+"," |",' click Developer -> "Configure Third-Party Inference..."',"",' Heads up: use the "Developer" MENU in the bar above - NOT',' Settings -> Developer, which is the "Local MCP servers" pane'," (that's where Anyray's retrieval server appears, not inference)."," A separate setup window then opens.","","Step 3 - In that window's Connection section, paste:",""," Inference provider: Gateway",` Gateway base URL: ${e.anthropicBaseUrl}`," Auth scheme: Bearer",` API key: ${t}`,"",'Step 4 - Click "Apply locally", then fully quit and reopen Claude'," (the config is read once at launch).","","Billing: this route uses an Anyray gateway credential and provider/API billing, not a Claude subscription allowance.","Fleet/MDM: generate a managed profile with `anyray-connect desktop claude --mobileconfig` (applies with no Developer Mode and no paste)."]},AB={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},ql="claude-desktop",Pm="migrate",wv=new Set(["app-running","store-missing"]),CB={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},kB={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"}},vB="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",bv=e=>{let t=(e.platform??wr)(),n=e.home??oi;return{home:n,appRunning:e.appRunning??ca(t),firstPartyRoot:()=>Us({home:n,runtimePlatform:t}),thirdPartyRoot:()=>Qr({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Av=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=CB[a.lane];return`${a.migrated} ${a.migrated===1?s.one:s.many}`}).join(", ")}.`+(n>0?` ${n} skipped \u2014 the transcript is no longer on disk.`:"")+(r>0?` ${r} could not be copied.`:"")},Cv=e=>{let t=e.filter(s=>s.migrated>0),n=e.reduce((s,i)=>s+i.conflicts,0),r=e.reduce((s,i)=>s+i.invalid,0),o=e.reduce((s,i)=>s+i.failed,0);if(t.length===0&&n+r+o===0)return;let a=t.map(s=>{let i=kB[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.`:"")},ri=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=bv(e),r=await(e.pendingDesktopMigrationCount??sv)(n),o=r.userSkills+r.userPlugins+r.localMcpServers;if(r.sessions+o===0)return[];if(t.dryRun)return[`Would bring ${[r.sessions>0?`${r.sessions} existing Claude Desktop session${r.sessions===1?"":"s"}`:"",o>0?`${o} portable configuration ${o===1?"entry":"entries"}`:""].filter(Boolean).join(" and ")} into Claude Desktop's third-party profile, now or automatically the next time Claude Desktop is fully quit.`];let a=await(e.migrateDesktopProfile??oo)(n);if(a.ok){let c=Av(a.lanes),l=Cv(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,p=(a.blocked??[]).filter(g=>g.reason!=="ambiguous"),f=a.blockedAssets??[],m=a.retryableAssets??[];if(p.length===0&&f.length===0&&m.length===0)return[c,l,u].filter(g=>!!g);if(t.preservePendingOp)return[c,l,u].filter(g=>!!g);await gs(ql,Pm);let h=p.reduce((g,b)=>g+b.waiting,0),w=[h>0?`${h} more session${h===1?"":"s"}`:"",f.length>0?`${f.length} extension ${f.length===1?"store":"stores"}`:""].filter(Boolean),y=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...m.length>0?[`Queued: ${m.length} portable configuration ${m.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...y]}if(!wv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
282
- ${a.remedy}`];if(t.preservePendingOp)return[];await gs(ql,Pm);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."]}},SB=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await or(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."]}},IB=e=>iv({id:ql,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??wr)(),n=(e.home??oi)();return t==="darwin"?["/Applications/Claude.app",bn(n,"Applications","Claude.app")]:t==="win32"?[bn(process.env.LOCALAPPDATA??bn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>ee(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",...fv(t)]:["Claude desktop org/API lane:",...fv(t),"This Gateway route uses provider/API billing. On verified macOS builds, subscription mode instead installs the Keychain-backed Claude Code credential helper automatically."],revertMessages:["Claude Desktop third-party inference: switch back to the first-party Claude provider in Developer settings (or remove the managed profile). Native setup is restored automatically by `--revert`."]}),EB=(e={})=>{let t=IB(e),n=()=>(e.platform??wr)()==="darwin",r=()=>(e.platform??wr)()==="win32",o=(s,i)=>n()?tk(s,i,e):Dk(s,s.clientKey??"",i,e),a=s=>n()?nk(s,e):Lk(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ca((e.platform??wr)()))(),quitTarget:AB,needsTarget:()=>!1,async complete(s){if(s!==Pm)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??oo)(bv(e));if(i.ok){let c=Av(i.lanes),l=Cv(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let p=(i.blocked??[]).filter(h=>h.reason!=="ambiguous"),f=i.blockedAssets??[],m=i.retryableAssets??[];return p.length>0||f.length>0||m.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...p.length>0||f.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."]:[],...m.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(h=>!!h):["No portable Claude Desktop data was left to bring across."]}}return wv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?ok(s,e):r()?Mk(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let p=jt(e),f=await to(p,e);if(f)return{status:"manual",manualAudience:"admin",messages:[nm(f),...await ri(e,i)]}}if(r()){let p;try{p=await gr(e.runReg??Bn)}catch{return{status:"manual",manualAudience:"admin",messages:[vB,...await ri(e,i)]}}if(p)return{status:"manual",manualAudience:"admin",messages:[bm(p),...await ri(e,i)]}}if(r()&&ee(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 p=await da(e);if(!p.supported)return{status:"manual",messages:[p.message??"Claude Desktop version is unsupported."]}}let c;try{c=await gB(e)}catch(p){let f=p instanceof Me?p.changedFiles:[];return{status:"manual",...f.length>0?{changedFiles:f}:{},messages:[p instanceof Me?p.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 p=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...p&&p.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${p.path}.`]:[],...await ri(e,i)]}}let d;try{d=await wB(c)}catch(p){let f=p instanceof Me?p.changedFiles:[];return{status:"manual",...f.length>0?{changedFiles:f}:{},messages:[p instanceof Me?p.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 ri(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?uB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=Xl(e),c=await SB(s),l=h=>c.length===0?h:{...h,messages:[...h.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await pv(e)}catch(h){return l({status:"manual",messages:[h instanceof Me?h.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 h=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...h&&h.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${h.path}.`]:[]]})}let p=await a({dryRun:!1});if(p.status==="manual"){let h=r()?Nt(e):void 0;if(!(h!==void 0&&p.changedFiles?.includes(h)===!0&&!await x(h)))return l(p)}let f;try{f=await bB(await pv(e))}catch(h){let w=h instanceof Me?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...p.changedFiles??[],...w])],messages:[...p.messages,h instanceof Me?h.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await re(i);let m=Dm(e);return n()&&m!==i&&await re(m),l({...p,messages:[...p.messages,...f.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...p.changedFiles??[],...f])]})},async mcpStatus(){if(!ce())return{registered:!1,command:null};try{let s=await so(Xl(e));return s.ownership!=="exact"||!ao(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 da(e)).supported?om(s,e):!1:r()?$k(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await da(e)).supported)return["unknown"];let s=await rk(e);return s?[s]:["unknown"]}if(r())return await x(Nt(e))?await gr(e.runReg??Bn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=jt(e);return!await x(s.journal)||await to(s,e)?!1:(await da(e)).supported}return r()&&await x(Nt(e))?!await gr(e.runReg??Bn):!1}catch{return!1}}}},kv=EB();import{homedir as eF}from"node:os";import{join as tF}from"node:path";import{rm as id}from"node:fs/promises";import{constants as vv,accessSync as xB,statSync as RB}from"node:fs";import{platform as Lm}from"node:os";import{delimiter as OB,posix as TB,resolve as _B,win32 as PB}from"node:path";var DB="0.59.0",LB="1.1.4",Fn="Anyray \xB7 Claude",Wn="Anyray \xB7 Codex",Ql="__anyray-acp-agent",Sv=(e,t,n)=>{let{command:r,args:o}=en([Ql,e,t,n]);return{command:r,args:o,env:{}}},ed=(e=Lm())=>e==="win32"?"npx.cmd":"npx",td=(e=process.env.PATH,t=Lm())=>{if(!e)return;let n=ed(t);for(let r of e.split(OB)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=_B(o,n);try{if(!RB(a).isFile())continue;return xB(a,t==="win32"?vv.F_OK:vv.X_OK),a}catch{}}},nd=(e,t=Lm())=>{let n=t==="win32"?PB:TB;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==ed(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},NB="https://chatgpt.com/backend-api/codex",$B="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Iv="ANYRAY_ACP_CODEX_AUTHORIZATION",Ev="ANYRAY_ACP_CODEX_CLIENT_KEY",xv="ANYRAY_ACP_CODEX_METADATA",Rv=e=>ue({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),MB=(e,t={})=>{let n=ee(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":NB,"x-anyray-forward-headers":$B}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Ev}:{}}:{Authorization:Iv};return Rv(e)&&(o["x-anyray-metadata"]=xv),{model_provider:"anyray",model_providers:{anyray:{name:"Anyray Gateway",base_url:e.openaiBaseUrl,wire_api:"responses",...n?{requires_openai_auth:!0}:{},http_headers:r,env_http_headers:o}},...t.mcpServer?{mcp_servers:{anyray:{command:t.mcpServer.command,args:t.mcpServer.args}}}:{}}},BB=e=>{let t=ee(e,"openai"),n=Rv(e);return{...t?e.clientKey?{[Ev]:e.clientKey}:{}:{[Iv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[xv]:n}:{}}},Ov=(e,t=ed(),n={})=>({[Fn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${DB}`],env:tn(e).env},[Wn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${LB}`],env:{CODEX_CONFIG:JSON.stringify(MB(e,n)),...BB(e)}}}),ai=(e=ed(),t="jetbrains")=>({[Fn]:Sv("claude",e,t),[Wn]:Sv("codex",e,t)}),io=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as FB}from"node:zlib";import{open as WB,readFile as Fm,readdir as sd}from"node:fs/promises";import{dirname as Tv,join as fe}from"node:path";import{homedir as Lv,platform as Wm}from"node:os";var od="2025.3.2",ua="253.30387.147",si="com.intellij.ml.llm",Nm=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),HB=1e4,UB=256*1024*1024,GB=16*1024*1024,$m=1024*1024,Mm=22,VB=Mm+65535,Bm=kl,KB=()=>{let e=Lv(),t=fe(e,".cache","JetBrains","RemoteDev");switch(Wm()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:fe(e,"Applications"),layout:"app-bundles"},{path:fe(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:fe(process.env.LOCALAPPDATA??fe(e,"AppData","Local"),"Programs"),layout:"children"},{path:fe(process.env.LOCALAPPDATA??fe(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:fe(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:fe(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},jB=()=>Wm()==="linux"?fe(Lv(),".local","share","JetBrains"):Ve("JetBrains"),ZB=()=>Wm()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),YB=async(e,t=HB)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await sd(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=fe(r.path,i.name),l=r.layout==="app-bundles"?fe(c,"Contents","Resources","product-info.json"):fe(c,"product-info.json");await x(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=fe(s,"product-info.json"),l=fe(s,"Contents","Resources","product-info.json");if(await x(c)){n.push(c);return}if(await x(l)){n.push(l);return}let d;try{d=await sd(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let p=fe(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(p,i-1)}};await a(r.path,7)}return[...new Set(n)]},JB=e=>{let t=Tv(e);return t.endsWith(`${fe("Contents","Resources")}`)?Tv(t):t},XB=async e=>{try{let t=JSON.parse(await Fm(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Ws(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:JB(e)}}catch{return}},ad=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},zB=async(e,t)=>{let n;try{n=await WB(e,"r");let{size:r}=await n.stat();if(r<Mm||r>UB)return;let o=Math.min(r,VB),a=await ad(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Mm;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>GB||c+i>r)return;let l=await ad(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),p=l.readUInt32LE(d+20),f=l.readUInt32LE(d+24),m=l.readUInt16LE(d+28),h=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),g=d+46+m+h+w;if(g>l.length)return;let b=l.subarray(d+46,d+46+m).toString("utf8");if(d=g,b!==t)continue;if(p===4294967295||f===4294967295||p>$m||f>$m)return;let k=await ad(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),I=await ad(n,p,y+30+C+S);return I?u===0?I.toString("utf8"):u===8?FB(I,{maxOutputLength:$m}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},_v=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Ws(n)))return{id:t,version:n}},qB=async(e,t)=>{let n=fe(e,"META-INF","plugin.xml");if(await x(n))try{let o=_v(await Fm(n,"utf8"));return{present:o?.id===si||t,descriptor:o?.id===si?o:void 0}}catch{return{present:t}}let r=[];try{r=(await sd(fe(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=>fe(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await zB(o,"META-INF/plugin.xml"),s=a?_v(a):void 0;if(s?.id===si)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Pv=async e=>{let t;try{t=await sd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Nm.has(o.name.toLowerCase()),i=Nm.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Nm.has(o.name.toLowerCase());if(!a){let i=fe(e,o.name,"META-INF","plugin.xml");if(!await x(i))continue}let s=await qB(fe(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},QB=async e=>{try{return(await Fm(fe(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(si)}catch{return!1}},Dv=e=>e.reduce((t,n)=>t?(Bm(n,t)??-1)>0?n:t:n,void 0),Nv=async(e={})=>{let t=e.configRoot??Ve("JetBrains"),n=e.userPluginsRoot??jB(),r=await YB(e.productRoots?e.productRoots.map(m=>({path:m,layout:"recursive"})):KB(),e.scanBudget),o=(await Promise.all(r.map(m=>XB(m)))).filter(m=>m!==void 0),a=o.length>0||await x(t);if(e.wsl??ZB())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(m=>(Bm(m.version,od)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let m of s){let h=fe(t,m.dataDirectoryName);if(!await x(h)){d=!0;continue}let w=[fe(h,"plugins"),fe(n,m.dataDirectoryName),fe(n,m.dataDirectoryName,"plugins")],y;for(let g of[...new Set(w)]){let b=await Pv(g);if(b.present){y=b;break}}if(y??=await Pv(fe(m.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==si)){if(i.push(y.descriptor.version),await QB(h)){c=!0;continue}if(!((Bm(y.descriptor.version,ua)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${m.version}; AI Assistant ${y.descriptor.version}; ACP supported`,ideVersion:m.version,pluginVersion:y.descriptor.version}}}let u=Dv(o.map(m=>m.version)),p=Dv(i),f;return a?u?s.length===0?f=`JetBrains IDE ${u} is below the ACP minimum ${od}; no ACP config was written.`:d?f=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${od}+ once, enable AI Assistant ${ua}+, then run Connect again. No ACP config was written.`:c?f=`JetBrains AI Assistant is disabled; enable version ${ua}+ and run Connect again. No ACP config was written.`:p?f=`JetBrains AI Assistant ${p} is below the ACP minimum ${ua}; no ACP config was written.`:l?f=`Could not verify the local JetBrains AI Assistant version; require ${ua}+ before running Connect. No ACP config was written.`:f=`JetBrains AI Assistant ${ua}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:f=`Could not prove JetBrains IDE ${od}+ from local product-info.json; no ACP config was written.`:f="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:f,ideVersion:u,pluginVersion:p}};var nF=[Fn,Wn],Hm=()=>tF(eF(),".jetbrains","acp.json"),co=()=>`${Hm()}.anyray-state`,rF=(e,t,n="npx")=>{let r=io(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,ai(n,"jetbrains")),{...e,agent_servers:r}},oF=(e,t,n)=>{if(!io(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=io(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of nF)if(c in r){if(!rd(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}},aF=(e=Nv)=>({id:"jetbrains",title:"JetBrains AI Assistant",automatic:!0,async detect(){let t=await e();return{installed:t.installed,detail:t.detail}},async apply(t,n){let r=Hm(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=td();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 x(r),c;try{c=await B(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=ai(a,"jetbrains");return await Zi({configPath:r,current:c,next:rF(c,t,a),journalPath:co(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,co()]}},async revert(t){let n=Hm(),r=async()=>{if(!await x(n))return t.dryRun||(await re(n),await id(co(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await B(n)}catch{return t.dryRun||(await re(n),await id(co(),{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 B(co());(u.version===1||u.version===2)&&io(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 x(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 B(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=oF(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 id(n,{force:!0}):await Y(n,l.next,{backup:!1})),t.dryRun||(await re(n),await id(co(),{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():ji(n,co(),r)}}),$v=aF();import{homedir as ld}from"node:os";import{join as dd}from"node:path";import{rm as Um}from"node:fs/promises";var Gm="1.0.0",ud=["anyray-claude-acp","anyray-codex-acp"],sF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Vm=()=>dd(ld(),".windsurf","acp","registry.json"),Km=()=>dd(ld(),".windsurf-next","acp","registry.json"),pa=e=>`${e}.anyray-state`,Mv=e=>({binary:Object.fromEntries(sF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Fv=(e="npx")=>{let t=ai(e,"windsurf");return[{id:ud[0],name:Fn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Mv(t[Fn])},{id:ud[1],name:Wn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Mv(t[Wn])}]},cd=e=>!Array.isArray(e)||e.some(t=>!io(t)||typeof t.id!="string")?null:e,iF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Gm||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:cd(e.agents);if(!n)return null;let r=new Set(ud);return{...e,version:typeof e.version=="string"?e.version:Gm,agents:[...n.filter(o=>!r.has(o.id)),...Fv(t)],extensions:e.extensions??[]}},cF=(e,t,n)=>{let r=cd(e.agents);if(!r)return null;let o=cd(t.agents)??[],a=new Map((cd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!ud.includes(u.id)){l.push(u);continue}if(!rd(u,a.get(u.id))){c.push(u.id),l.push(u);continue}let p=s.get(u.id);p&&l.push(p),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===Gm&&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 x(Km())||await x(dd(ld(),".windsurf-next")))&&e.push(Km()),(await x(Vm())||await x(dd(ld(),".windsurf"))||await x(Ve("Devin"))||await x(Ve("Windsurf")))&&e.push(Vm()),e},Wv={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=td();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 B(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=iF(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 x(s),d=Fv(r);await Zi({configPath:s,current:i,next:c,journalPath:pa(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,pa(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=[Vm(),Km()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await re(a),await Um(pa(a),{force:!0}).catch(()=>{}));return}let i;try{i=await B(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 f=await B(pa(a));(f.version===1||f.version===2)&&Array.isArray(f.agents)&&(c=f.agents,l=f.version===2&&f.fileExisted===!1,d=f.version===2&&f.fileExisted===!0)}catch{}let u;if(d){let f=`${a}.anyray-bak`;if(!await x(f)){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 B(f)}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 p=cF(i,u,c);if(!p){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}p.removed.length&&(n.push(`Removed ${p.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(p.next).length===0?await Um(a,{force:!0}):await Y(a,p.next,{backup:!1}),r.push(a))),p.conflicts.length?(n.push(`Preserved user-modified agents: ${p.conflicts.join(", ")}.`),o=!0):e.dryRun||(await re(a),await Um(pa(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await ji(a,pa(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var le=[qn,_w,ks,LA,iC,bC,EC,$v,kv,Wv,Fw],mt=e=>le.find(t=>t.id===e);var Be=async(e=D,t=fn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:xe({origin:n.gateway,clientKey:n.clientKey,subscription:n.authMode==="subscription",placeholder:n.authMode==="placeholder",byoUpstream:n.byoUpstream,seat:r,user:n.name,team:n.team})}};var jm=5e3,Hv=3e4,lF=1440*60*1e3,dF=e=>new Promise(t=>setTimeout(t,e)),uF=async(e=D,t=fn)=>(await Be(e,t))?.target,pF=e=>mt(e)?.quitGated,Uv=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??pF,o=t.readPending??Uc,a=t.clearPending??Tp,s=t.targetFromProfile??uF,i=t.sleep??dF,c=t.now??Date.now,l=t.maxWaitMs??lF;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),p=c(),f=jm;for(;;){let m=await o(n);if(!m||c()-p>l)return 0;if(d.isRunning()){await i(f),f=Math.min(Hv,f*2);continue}let h;if(d.needsTarget?.(m.op)&&(h=await s(),!h)){if(await a(n,m)!=="superseded")return 0;await i(f),f=jm;continue}if((await u(m.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(f),f=Math.min(Hv,f*2);continue}if(await a(n,m)!=="superseded")return 0;await i(f),f=jm}}catch{return 0}};import{writeFileSync as eW}from"node:fs";import{chmod as oh,stat as tW}from"node:fs/promises";import{platform as bS}from"node:os";import{dirname as AS,isAbsolute as nW}from"node:path";var fF="https://app.anyray.ai",mF=new Set(["localhost","::1","[::1]"]),hF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,yF=e=>mF.has(e)||hF.test(e),Zm=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&yF(t.hostname)},gF=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Hn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!Zm(e)?fF:gF(e)};import{createHash as TF,generateKeyPairSync as _F,randomBytes as Xm}from"node:crypto";import{createPrivateKey as wF,sign as bF}from"node:crypto";var br=async(e,t)=>{let n=wF(t);return bF(null,new TextEncoder().encode(e),n).toString("base64url")};var AF=["HTTPS_PROXY","https_proxy"],Gv=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"]),Vv=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"]),jv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Zv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),CF=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 kF(e)},kF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...Gv,...Vv,...Kv,...jv,...Zv])if(t.includes(n))return n}},vF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",SF=e=>AF.filter(t=>(e[t]??"").trim()!==""),IF=(e,t=process.env)=>{let n=CF(e),r=SF(t);return{kind:n&&Gv.has(n)?"tls-unknown-issuer":n&&Vv.has(n)?"tls-invalid-cert":n&&Kv.has(n)?"dns":vF(e)||n&&Zv.has(n)?"timeout":n&&jv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},EF=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}},ht=(e,t=process.env)=>EF(IF(e,t));var xF="enl_",Yv="enp_",Jv=e=>e.startsWith(xF)||e.startsWith(Yv),Ym=e=>e.startsWith(Yv),RF=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],Jm=e=>RF.find(t=>e.startsWith(t.prefix)),Xv=/^\/enroll\/([^/]+)\/?$/,zv=/^\/i\/([^/]+)\/?$/,qv=e=>{let t=e.match(Xv);if(t)return Jm(t[1])?void 0:t[1];let n=e.match(zv);return n&&Jv(n[1])?n[1]:void 0},OF=1e4,pd=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=qv(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!Jm(t))return{cpOrigin:Hn(),token:t}},Qv=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(Xv)??o.pathname.match(zv);if(!a)return;n=a[1]}catch{}let r=Jm(n);return r?{flag:r.flag,what:r.what}:void 0},ci=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:qv(n.pathname)!==void 0}catch{return Jv(t)}},fa=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},ii=e=>typeof e=="string"&&e.trim()?e.trim():void 0,eS=async(e,t={})=>{let n=t.timeoutMs??OF,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 p=u instanceof Error&&u.name==="AbortError"?` no response within ${n}ms.`:ht(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${p}`)}finally{clearTimeout(a)}if(!s.ok){let u=`enrollment link lookup failed: ${e.cpOrigin} responded ${s.status} \u2014 the link may be expired or revoked; ask your admin for a fresh one.`;throw s.status>=400&&s.status<500&&s.status!==429?new fa(u):new Error(u)}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"&&ii(u.url)!==void 0),d=ii(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:ii(l?.deploymentId),org:ii(i.org),email:ii(i.email),seatMode:i.seatMode===!0,...i.provisioningKind==="manual"||i.provisioningKind==="mdm"?{provisioningKind:i.provisioningKind}:{},...i.provisioningProofMode==="managed-preference"?{provisioningProofMode:i.provisioningProofMode}:{},...Array.isArray(i.allowedDomains)?{allowedDomains:i.allowedDomains.filter(u=>typeof u=="string"&&u.length>0)}:{}}};var zm=1e4,lo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(lo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${lo(e[n])}`).join(",")}}`,tS="stable-key-heartbeat-v1",nS="key-heartbeat",PF=["reapply_config","remint","revert"],qm=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var rS=e=>TF("sha256").update(e).digest("hex"),Ze=e=>typeof e=="string"&&e.trim()?e.trim():void 0,DF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],oS={no_mdm_server_registered:"no MDM server is registered in the Anyray console",agent_missing:"the Anyray endpoint agent is not reporting for this machine",mdm_not_verified:"this machine is not enrolled in the registered MDM",endpoint_unreachable:"the endpoint service could not be reached"},LF=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${oS[e]}. Ask your IT admin.`,NF=e=>typeof e=="string"&&e in oS,Qm=async e=>{try{let t=await e.json(),n=Ze(t?.message),r=Ze(t?.error),o=NF(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:LF(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},$F=async e=>(await Qm(e)).message,lt=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this enrollment (HTTP ${t}): ${r.message}`),this.name="GatewayVerifyError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},aS=e=>e instanceof fa||e instanceof lt&&e.policyCode==="sso_required",ma=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this credential heartbeat (HTTP ${t}): ${r.message}`),this.name="GatewayHeartbeatError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},eh=async(e,t,n,r)=>{try{return await r(lo(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},fd=()=>{let{publicKey:e,privateKey:t}=_F("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},Xt=async(e,t,n,r={})=>{let o=r.timeoutMs??zm,a=`${e}/connect/verify`,s=Ze(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:Xm(16).toString("hex"),...qm(t,r.machineUuid)},c=await eh(i,n,"verification",r.signer??br),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":Ae},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(g){let b=g instanceof Error&&g.name==="AbortError"?` no response within ${o}ms.`:ht(g);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:g})}finally{clearTimeout(d)}if(!u.ok)throw new lt(u.status,await Qm(u));let p;try{p=await u.text()}catch{p=""}let f;try{f=JSON.parse(p)}catch{let g=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(g)||/^\s*<(?:!doctype|html)/i.test(p);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 m=Ze(f?.key);if(!m)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(m))throw new Error("developer verification failed: the gateway returned a malformed key");let h=Ze(f.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let w=MF(f.directive),y=DF(f.capabilities);return{key:m,user:h,team:Ze(f.team),expiresAt:Ze(f.expiresAt),...y.length>0?{capabilities:y}:{},...w?{directive:w}:{}}},sS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??zm,s=`${e}/connect/key/heartbeat`,i=Ze(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:Xm(16).toString("hex"),purpose:nS,...qm(n,o.machineUuid)},l=await eh(c,r,"heartbeat",o.signer??br),d=new AbortController,u=setTimeout(()=>d.abort(),a),p;try{p=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":Ae},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(h){let w=h instanceof Error&&h.name==="AbortError"?` no response within ${a}ms.`:ht(h);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:h})}finally{clearTimeout(u)}if(!p.ok)throw new ma(p.status,await Qm(p));let f;try{f=await p.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let m=Ze(f.expiresAt);if(!m||!Number.isFinite(Date.parse(m))||f.credentialMode!==tS||f.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:m,credentialMode:tS}},iS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??zm,i=`${e.replace(/\/$/,"")}/connect/machine`,c=Ze(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Xm(16).toString("hex"),purpose:nS,...qm(n,o)},d=await eh(l,r,"heartbeat",a.signer??br),u=new AbortController,p=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":Ae},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(f){return console.error("connect machine report skipped:",f instanceof Error?f.name:"error"),!1}finally{clearTimeout(p)}},MF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=Ze(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}},BF=1e4,FF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!Ze(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!Ze(r.deploymentId)&&!!Ze(r.user)&&!!Ze(r.devPublicKey)&&!!Ze(r.issuedAt)&&!!Ze(r.expiresAt)},WF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??BF,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 p=u instanceof Error&&u.name==="AbortError"?` no response within ${a}ms.`:ht(u);throw new Error(`could not reach the control plane at ${s}.${p}`)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await $F(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new fa(u):new Error(u)}let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!FF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},cS=(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())},lS=async e=>{let t={timeoutMs:e.timeoutMs,machineUuid:e.machineUuid,signer:e.signer},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=fd();return{cert:await WF(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await Xt(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}};var th=1e4,HF=900*1e3,uS="tnt_",UF=/^\/sso\/([^/]+)\/?$/,GF=/^\/i\/([^/]+)\/?$/,VF=e=>{let t=e.match(UF);if(t)return t[1];let n=e.match(GF);return n?.[1].startsWith(uS)?n[1]:void 0},St=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=VF(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(uS))return{cpOrigin:Hn(),tenantId:t}},uo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},$t=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},nh=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)}},KF=e=>new Promise(t=>setTimeout(t,e)),md=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??fd)(),a;try{a=await nh(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},th,n)}catch(m){throw new uo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ht(m)}`)}if(a.status!==200){let m=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new uo(m?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${h}). 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 uo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??HF,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),p={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},f=e.log??(()=>{});return f("To finish, sign in with your organization at:"),f(` ${p.verificationUriComplete}`),f(`Confirm this code matches your browser: ${p.userCode}`),jF(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},jF=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},hd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??KF,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 nh(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},th,o)}catch(c){throw new $t("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ht(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 $t("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new $t("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new $t("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var dS="sdc_",pS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(dS))return{cpOrigin:Hn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!Zm(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(dS)))return{cpOrigin:n.origin,claim:r}},fS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??fd)(),o;try{o=await nh(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},th,t)}catch(s){throw new $t("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ht(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 $t("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new $t("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new $t("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};import{readFile as ZF}from"node:fs/promises";import{isAbsolute as YF,posix as mS,win32 as rh}from"node:path";var li=(e=process.platform,t=process.env)=>e==="darwin"?mS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?rh.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):mS.join("/etc","anyray","bootstrap.json"),JF=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),hS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(YF(e)||rh.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),XF=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}},Ar=async(e=li())=>{try{let t=await ZF(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!JF(n)||n.v!==1||typeof n.sso!="string")return;let r=St(n.sso);if(!r)return;let o=XF(n.gateway)?n.gateway:void 0,a=hS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},yS=(e,t,n)=>{let r=St(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!hS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&rh.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)}
283
- `};var ha=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,yd=ha(process.stdout,process.env),gS=ha(process.stderr,process.env),ya=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,V=e=>ya("1",e,yd),v=e=>ya("2",e,yd),zF=e=>ya("32",e,yd),qF=e=>ya("33",e,gS),QF=e=>ya("31",e,gS),et=e=>ya("36",e,yd),A=e=>console.log(e),U=e=>console.log(`
284
- ${V(e)}`),$=e=>console.log(v(e)),M=e=>console.log(`${zF("\u2713")} ${e}`),_=e=>console.error(`${qF("!")} ${e}`),O=e=>console.error(`${QF("\u2717")} ${e}`);var ah=`${V("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
275
+ }`,Fn=async e=>new Promise((t,n)=>{let r=Z$("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",aM],{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(sm(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(sm({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),$t=(e={})=>sa((e.home??dm)(),".anyray","claude-desktop-windows.json"),sM=e=>sa((e.home??dm)(),".anyray","claude-desktop-windows.lock"),ra=class extends Error{},iM=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},fm=async e=>{let t=sM(e);await rm(Qs(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=vk("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=sa(t,"owner.json");try{await rm(t,{mode:448}),await we(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
276
+ `)}catch(a){if(a.code!=="EEXIST")throw await Zt(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await om(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!iM(i.pid)}catch{try{s=Date.now()-(await Rk(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new ra;await Zt(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await om(o,"utf8")).nonce===r&&await Zt(t,{recursive:!0,force:!0})}catch{}}}throw new ra},Lk=()=>Object.fromEntries(Pe.map(e=>[e,{present:!1}])),no=e=>vk("sha256").update(e).digest("hex"),cM=(e,t)=>t.present?e===ia?{present:!0,type:t.type,sha256:no(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},ta=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?no(e.value??"")===t.sha256:e.value===t.value:!0,Nt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Fl=(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===ia?Nt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Nt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},fk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Nt(e,Pe)&&Pe.every(t=>Fl(e[t],t)),mk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Nt(e,ck)&&ck.every(t=>Fl(e[t],t)),lM=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),mm=(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 Nt(n,r)&&n.path===um(t)&&(n.lastWritten===void 0||pk(n.lastWritten))&&(n.pending===void 0||pk(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},dM=(e,t)=>Nt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Bl&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&fk(e.lastWritten)&&(e.pending===void 0||fk(e.pending))&&mm(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),uM=e=>Nt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&mk(e.lastWritten)&&(e.pending===void 0||mk(e.pending)),hk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Nt(e,lk)&&lk.every(t=>Fl(e[t],t)),pM=(e,t)=>Nt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&hk(e.lastWritten)&&(e.pending===void 0||hk(e.pending))&&mm(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),yk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Nt(e,dk)&&dk.every(t=>Fl(e[t],t)),fM=(e,t)=>Nt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&yk(e.lastWritten)&&(e.pending===void 0||yk(e.pending))&&mm(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),gk=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),hm=e=>{let{pending:t,...n}=e;return{...n,version:Bl,lastWritten:gk(e.lastWritten),...t?{pending:gk(t)}:{}}},wk=e=>({...e,chatTabEnabled:{present:!1}}),mM=e=>{let{pending:t,...n}=e;return hm({...n,version:4,lastWritten:wk(e.lastWritten),...t?{pending:wk(t)}:{}})},bk=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),hM=(e,t)=>hm({version:4,registryKey:Te,keyExisted:e.keyExisted,lastWritten:bk(e.lastWritten),...e.pending?{pending:bk(e.pending)}:{},helper:{path:um(t)}}),ym=async(e,t=!0)=>{let n=$t(e),r=Qs(n),o=`${Ok(n)}.anyray-old-`,a=(await Ek(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>sa(r,l)),s=n;if(!await x(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await xk(a[0],n):s=a[0]}let i=await M(s),c=uM(i)?hM(i,e):pM(i,e)?mM(i):fM(i,e)?hm(i):dM(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>Zt(l,{force:!0}))),c},Ak=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),yM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Te,keyExisted:e.keyExisted,lastWritten:Ak(e.lastWritten),...e.pending?{pending:Ak(e.pending)}:{}}:e,Nl=async(e,t)=>{let n=$t(t),r=`${JSON.stringify(yM(e),null,2)}
277
+ `;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},gM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,wM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),bM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),AM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),CM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===AM(t).toUpperCase(),Ck=(e,t,n,r,o)=>{let a=Pe.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},kM=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,vM=(e,t)=>{if(!Ol(e,!0))return!1;let n=kM(t);if(bM.has(n))return!1;if(wM.has(n))return n==="REG_EXPAND_SZ"?!0:!MC(e,!0)},SM=(e,t)=>{let n=Lk(),r=!1,o=!1,a=!1,s=t.toUpperCase()===qs.toUpperCase(),i=(l,d)=>{if(!s)return;let u=vM(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),Ck(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||CM(d,t))continue;let u=gM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),Ck(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Bn=async(e,t=Te)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:Lk(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return SM(n.stdout,t)},wr=async e=>{let t=await Bn(e,qs);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...Pe.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},gm=e=>e.unparsed?`This machine may have a Claude policy under ${qs} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${qs} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${qs} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Wl=(e,t)=>gr(eo(e,t)),Nk=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],IM=(e,t)=>{let n=Wl(e,t);return Object.fromEntries(Pe.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},EM=(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}}),xM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,im=e=>Object.fromEntries(Pe.map(t=>[t,cM(t,e[t])])),kk=(e,t,n,r)=>({version:Bl,registryKey:Te,keyExisted:e,lastWritten:im(t),helper:{path:n,lastWritten:am(r)}}),RM=(e,t,n,r,o,a)=>({version:Bl,registryKey:Te,keyExisted:e,lastWritten:im(t),pending:im(n),helper:{path:r,...o?{lastWritten:am(o)}:{},pending:am(a)}}),cm=(e,t,n)=>ta(n,e.lastWritten[t])||e.pending!==void 0&&ta(n,e.pending[t]),oa=async e=>{try{let t=await om(e,"utf8");return{content:t,sha256:no(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},aa=async e=>(await oa(e))?.sha256,na=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Ml=async(e,t)=>{let n=rM(e),r;try{r=await Ek(Qs(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>sa(Qs(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([oa(e),oa(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!na(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await Dk(e,a))throw new Error("credential helper changed during recovery");return}if(t&&na(t,s.sha256)&&na(t,i.sha256)){await Zt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},wm=async(e,t,n)=>(n.present?await e(Nk(Te,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Te,"/v",t,"/f"])).code===0,OM=async(e,t,n)=>{let r=!0,o=await Bn(e);for(let a of Pe)if(!ea(o.values[a],t[a])){if(!ea(o.values[a],n[a])){r=!1;continue}await wm(e,a,t[a])||(r=!1),o=await Bn(e)}return r&&Pe.every(a=>ea(o.values[a],t[a]))},Qe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[$t(n)]}}),$k=async(e,t,n,r={})=>{if(!Ee(t))return Qe("A valid personal ark_ gateway key is required.",!1,r);let o=um(r),a;try{a=q$((r.credentialCommand??Jf)())}catch{return Qe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=no(a),i=r.runReg??Fn,c=$t(r),l;if(!n.dryRun)try{l=await fm(r)}catch(h){return Qe(h instanceof ra?"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,p,f,m=!1;try{let h=await wr(i);if(h)return Qe(gm(h),!1,r);let w=await ym(r,!n.dryRun);n.dryRun||await Ml(o,w);let y=await Bn(i),g=IM(e,o),b=await oa(o),k=b?.sha256,C=!1;if(d=w,u=y,p=g,w){let E=Pe.find(R=>!cm(w,R,y.values[R]));if(E)return Qe(`Claude's ${E} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!na(w,k))return Qe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=xM(w)}else{if(k!==void 0&&k!==s)return Qe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let E=y.foreignState||Pe.some(U=>y.values[U].present),R=Pe.every(U=>ea(y.values[U],g[U])),N=Pe.every(U=>ea(y.values[U],EM(e,t.trim())[U]));if(E&&!R&&!N)return Qe(`Existing Claude third-party-inference policy values under ${Te} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(C=N,R&&k===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Te} into an owner-only journal without rewriting them.`]}:(await Nl(kk(y.keyPresent,g,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Te} into the ownership journal.`]})}if(C){let E=!0;try{E=(r.appRunning??pm)()}catch{}if(E)return Qe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let S=RM(w?.keyExisted??y.keyPresent,y.values,g,o,b?.content,a);if(f=S,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Te}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Nl(S,r),m=!0;for(let E of Pe){let R=await Bn(i);if(!ta(R.values[E],S.lastWritten[E])&&!ta(R.values[E],S.pending[E]))throw new Error("registry value changed during apply");if(!ea(R.values[E],g[E])&&!await wm(i,E,g[E]))throw new Error("registry write failed")}let I=await Bn(i);if(!Pe.every(E=>ta(I.values[E],S.pending[E])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await nM(o,a):await $l(o,k,a,"apply",r)),await aa(o)!==s)throw new Error("credential helper verification failed");return await Nl(kk(S.keyExisted,g,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Te}.`,`Installed or updated the dynamic credential helper at ${o}; no personal key is stored in policy or the ownership journal.`,"Fully quit and reopen Claude Desktop to load the policy.",...El]}}catch{if(!m||!u||!p||!f)return Qe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Ml(o,f);let h=!0,w=await oa(o),y=f.helper.pending;if(w?.sha256!==f.helper.lastWritten?.sha256&&(y!==void 0&&w?.sha256===y.sha256?f.helper.lastWritten?(await $l(o,y.sha256,f.helper.lastWritten.content,"rollback",r),h=await aa(o)===f.helper.lastWritten.sha256):await $l(o,y.sha256,void 0,"rollback",r):h=w===void 0&&f.helper.lastWritten===void 0),h&&await OM(i,u.values,p))return d?await Nl(d,r):await Zt(c,{force:!0}),Qe("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return Qe("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},Mk=async(e,t={})=>{let n=t.runReg??Fn,r=$t(t),o;if(!e.dryRun)try{o=await fm(t)}catch(a){return Qe(a instanceof ra?"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 ym(t,!e.dryRun);a&&!e.dryRun&&await Ml(a.helper.path,a);let s=await Bn(n);if(!a)return Pe.filter(m=>s.values[m].present).length>0?Qe(`Claude policy values exist under ${Te}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=Pe.filter(f=>s.values[f].present&&!cm(a,f,s.values[f])),c=await aa(a.helper.path),l=c!==void 0&&!na(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Te}.`,`Would remove the Anyray-owned credential helper at ${a.helper.path}.`,...i.length||l?[`Would preserve changed values: ${[...i,...l?["credential helper"]:[]].join(", ")}.`]:[]]};let d=!1,u=new Set(i);for(let f of Pe){let h=(await Bn(n)).values[f];if(h.present){if(!cm(a,f,h)){u.add(f);continue}await wm(n,f,{present:!1})||(d=!0)}}let p=await aa(a.helper.path);if(p!==void 0)if(na(a,p))try{await $l(a.helper.path,p,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?Qe(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await Zt(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Te}.`,"Removed the Anyray-owned dynamic credential helper when its content still matched the journal.",...u.size?[`Preserved values changed after Connect: ${[...u].join(", ")}.`]:[],...u.size?[]:xl]})}catch{return Qe(`Could not safely inspect or revert ${Te}; no unproven value was removed.`,!1,t)}finally{await o?.()}},Bk=async(e,t={})=>{let n=t.runReg??Fn;if(!await x($t(t)))return;let r;try{r=await fm(t);let o=await ym(t);if(o&&await Ml(o.helper.path,o),!o||o.pending||await wr(n)!==void 0)return;let a=await Bn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ht(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Pe.every(l=>ta(a.values[l],o.lastWritten[l]))))return;let i=await aa(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 tM(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?.()}},Fk=async(e,t={})=>await Bk(e,t)!==void 0,Wk=async(e,t={})=>await Bk(e,t)==="dynamic";var ca=(e=_M())=>e==="win32"?pm:Pl,bm="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Hl=async(e,t={})=>{let n=(t.profileRoot??Qr)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:bm};if((t.appRunning??ca(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await Uk.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 Il(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 "+bm}:{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??TC)();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=Ul(t.stagingRoot??PM(),`anyray-history-${process.pid}-${TM()}`);try{let s=await(t.runImporter??_C)({binary:o,exportPath:e,configDir:Ul(a,"config"),workDir:Ul(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. "+bm};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 DC(r.dir,s.conversations),c=await LC({stagedProjectsDir:Ul(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 Uk.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as vt}from"node:fs";import{homedir as eB}from"node:os";import{join as Jt,sep as tB}from"node:path";import{isDeepStrictEqual as jl}from"node:util";import{constants as DM}from"node:fs";import{promises as G}from"node:fs";import{dirname as la,isAbsolute as Cm,join as ne,relative as Gl,resolve as Yt,sep as ei}from"node:path";import{randomUUID as Zl}from"node:crypto";var wn=448,ti=384,Kk=448,LM=4,km=3e4,jk=5e3,NM=10*6e4,Am=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ni=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),Zk=(e,t)=>{let n=Gl(Yt(e),Yt(t));return n===""||!n.startsWith(`..${ei}`)&&n!==".."&&!Cm(n)},ro=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return ct(n)?{raw:t,value:n}:void 0}catch(t){return kt(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},kt=e=>e instanceof Error&&"code"in e,$M=e=>{try{return process.kill(e,0),!0}catch(t){return kt(t)&&t.code==="EPERM"}},Yk=e=>e===0?"owner.json":`owner.${e}.json`,Vl=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 p=Number(u[1]);return Number.isSafeInteger(p)&&p>0?{name:d,generation:p}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=ne(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));ct(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}},Jk=e=>{if(e.pid===void 0||!$M(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>km&&t-e.createdAtMs>NM},MM=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(la(t),{recursive:!0,mode:wn});let n=Zl(),r,o=!1;try{await G.mkdir(t,{mode:wn}),o=!0}catch(i){if(!kt(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Vl(t);if(d){if(!Jk(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(p=>Date.now()-p.mtimeMs).catch(()=>0)<=km)return}let l=ne(t,Yk(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
278
+ `,{flag:"wx",mode:ti}),r=l}catch(d){if(kt(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(!ct(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},jk);return s.unref(),async()=>{clearInterval(s);try{(await Vl(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},BM=async(e,t,n)=>{await G.mkdir(la(e),{recursive:!0,mode:wn});let r=await MM(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!kt(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${Zl()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
279
+ `,{mode:ti,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},Yl=async(e,t)=>{for(let n=0;n<LM;n+=1){let r=await ro(e);if(!r)return"failed";let o=t(r.value);if(!o||jl(o,r.value))return"unchanged";try{if(await BM(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},Hk=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 Hk(e))for(let r of await Hk(ne(e,n)))t.push(ne(e,n,r));return t},FM=e=>Array.isArray(e.skills)?e.skills.filter(t=>ct(t)&&ni(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],WM=async e=>{let t=ne(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await Jl(t)){let o=await ro(ne(r,"manifest.json"));if(!o)continue;let a=r.split(ei).at(-1)??"";for(let s of FM(o.value))n.push({account:a,packageDir:r,entry:s})}return n},UM=async e=>{let t=await ro(ne(e,".claude-plugin","plugin.json"));return!!t&&ni(t.value.name)},HM=(e,t)=>{let n=Cm(t)?Yt(t):Yt(e,t);if(!Zk(e,n)||n===Yt(e))return;let r=Gl(Yt(e),n);return r.length>0?{absolute:n,relative:r}:void 0},GM=async e=>{let t=await Jl(ne(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(ei).includes("skills-plugin"))continue;let o=ne(r,"cowork_plugins"),a=await ro(ne(o,"installed_plugins.json"));if(!a||!ct(a.value.plugins))continue;let s=r.split(ei).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!ni(i)||!Array.isArray(c)))for(let l of c){if(!ct(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=HM(o,l.installPath);!d||!await UM(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:ne(r,"cowork_account_settings.json")})}}return n},VM=async e=>{let t=await ro(ne(e,"claude_desktop_config.json"));return!t||!ct(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>ni(n)&&n.toLowerCase()!=="anyray"&&ct(r)))},Xk=async e=>{let[t,n,r]=await Promise.all([WM(e),GM(e),VM(e)]);return{skills:t,plugins:n,localMcpServers:r}},vm=async e=>{let t=await Xk(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)}},Gk=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(!ni(o.name))return!1;let a=ne(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)},KM=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=ne(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,wn);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?Kk:ti)}}};await t(e),await G.chmod(e,wn)},zk=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},Kl=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(!jl(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 Kl(ne(e,s),ne(t,s)))return!1}else if(!i.isFile()||!await zk(ne(e,s),ne(t,s)))return!1}return!0}catch{return!1}},qk=e=>`${e}.anyray-incomplete`,Qk=async(e,t)=>{let n=!1;if(t){await G.mkdir(la(e),{recursive:!0,mode:wn});try{await G.mkdir(e,{mode:wn}),n=!0}catch(l){if(!kt(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=Zl(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let p;try{p=await Vl(e)}catch{return}if(p){if(!Jk(p)||!Number.isSafeInteger(p.generation+1))return;d=p.generation+1}else if(await G.stat(e).then(m=>Date.now()-m.mtimeMs).catch(()=>0)<=km)return}let u=ne(e,Yk(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
280
+ `,{flag:"wx",mode:ti}),o=u}catch(p){if(kt(p)&&p.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(!ct(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},jk);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Vl(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},ev=async e=>{let t=await Qk(e,!1);t&&await t.complete()},jM=async(e,t,n)=>{let r=qk(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Kl(e,t))return await ev(r),"present"}catch(c){if(!kt(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 Qk(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:wn})}catch(c){if(!kt(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 p=ne(c,u.name),f=ne(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(f,{mode:wn})}catch(h){if(!kt(h)||h.code!=="EEXIST")throw h;let w=await G.lstat(f);if(!w.isDirectory()||w.isSymbolicLink())return"conflict"}let m=await s(p,f);if(m!=="copied")return m}else if(u.isFile())try{await G.copyFile(p,f,DM.COPYFILE_EXCL);let m=await G.stat(p);await G.chmod(f,(m.mode&73)!==0?Kk:ti)}catch(m){if(!kt(m)||m.code!=="EEXIST")throw m;if(!await zk(p,f))return"conflict"}else return"failed"}catch(m){return kt(m)&&m.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await Kl(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},tv=async(e,t,n,r)=>{if(!await Gk(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Kl(e,t))return await ev(qk(t)),"present"}catch(a){if(!kt(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(la(t),{recursive:!0,mode:wn});let o=ne(la(t),`.anyray-stage-${Zl()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await Gk(o)?(await KM(o),await n?.(t),await jM(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},Vk=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),ZM=async e=>{let t=await Jl(ne(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await ro(ne(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},YM=async e=>{let t=await Jl(ne(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(ei).includes("skills-plugin"))try{await G.access(ne(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},JM=async(e,t,n,r,o)=>{let a=ne(t,"manifest.json");for(let s of e){let i=ne(s.packageDir,"skills",s.entry.name);try{await G.access(ne(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=ne(t,"skills",s.entry.name),l=await tv(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 Yl(a,p=>{let f=Array.isArray(p.skills)?p.skills:[];if(f.find(h=>ct(h)&&typeof h.name=="string"&&h.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...p,skills:[...f,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},nv=(e,t)=>({...e,installPath:t}),XM=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=Cm(r.installPath)?Yt(r.installPath):Yt(o,r.installPath),s=nv(e,Gl(Yt(t),Yt(n))),i={...r,installPath:Gl(Yt(o),a)};return jl(s,i)},zM=async(e,t,n)=>{let r=await ro(e);if(!r||!ct(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":Yl(t,a=>{let s=ct(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},qM=async(e,t,n,r,o)=>{let a=ne(t,"cowork_plugins"),s=ne(a,"installed_plugins.json"),i=ne(t,"cowork_account_settings.json");for(let c of e){let l=ne(a,c.relativeInstallPath);if(!Zk(a,l)){n.invalid+=1;continue}let d=await tv(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,p=!1;await Yl(s,m=>{let h=ct(m.plugins)?m.plugins:{},w=h[c.id],y=Array.isArray(w)?w:[],g=y.find(k=>ct(k)&&k.scope==="user");if(g){u=XM(c.entry,la(c.settingsFile),c.packageDir,g,t),p=!u;return}let b=nv(c.entry,l);return{...m,version:typeof m.version=="number"?m.version:2,plugins:{...h,[c.id]:[...y,b]}}})==="failed"?n.failed+=1:p?n.conflicts+=1:await zM(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},QM=async(e,t,n)=>{let r=ne(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await Yl(r,c=>{let l=ct(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=jl(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}},rv=async(e,t,n={})=>{let r=await Xk(e),o=Am("skill"),a=Am("plugin"),s=Am("local-mcp"),i=[],c=[],l=Vk(r.skills,n.account,n.allAccounts),d=Vk(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let p=new Set(n.allowedAccounts);if([...new Set([...l.map(m=>m.account),...d.map(m=>m.account)])].some(m=>!p.has(m)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,sourceChanged:!0,retryable:[]}}if(l.length>0){let p=await ZM(t);p.state==="found"?await JM(l,p.path,o,n.beforeDirectoryPublish,n.afterDirectoryClaim):p.state==="missing"?i.push("skill"):(o.conflicts+=l.length,c.push("skill"))}if(d.length>0){let p=await YM(t);p.state==="found"?await qM(d,p.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):p.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await QM(r.localMcpServers,t,s);let u=[o,a,s];return{outcomes:u,blocked:i,ambiguous:c,sourceChanged:!1,retryable:u.filter(p=>p.failed>0).map(p=>p.kind)}};var nB=async e=>{try{return await vt.access(e),!0}catch{return!1}},ov=448,rB=384,sv={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},oB=["code","cowork"],Em=(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.",Sm=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),iv=async e=>{let t;try{t=(await vt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&Xo(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await vt.readdir(Jt(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&Xo(a.name)).map(a=>a.name);for(let a of o)n.push(Jt(e,r,a))}catch{}return n},aB=async e=>{try{return(await vt.readdir(e)).filter(t=>t.startsWith($n)&&t.endsWith(".json")).map(t=>t.slice($n.length,-5)).filter(Xo)}catch{return[]}},sB=async(e,t)=>{let n=await iv(Jt(e,sv[t])),r=[];for(let o of n){let a=await aB(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(tB).slice(-2)[0]})}return r},iB=async(e,t)=>{if(t==="cowork"){let r=await Il(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await iv(Jt(e,sv.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},cB=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await vt.copyFile(e,n),await vt.chmod(n,rB),await vt.rename(n,t)},lB=async(e,t)=>{try{let n=JSON.parse(await vt.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||!Xo(o)?!1:(await vt.access(Jt(t,".claude","projects",Gf(r),`${o}.jsonl`)),!0)}catch{return!1}},dB=async(e,t,n,r)=>{let o=Sm(e),a=await Vf(n);for(let s of t)await uB(e,s,n,r,a,o);return o},uB=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${$n}${s}.json`,c=Jt(t.dir,i);try{if(e==="code"){if(!await lB(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=Jt(t.dir,`${$n}${s}`),d=Jt(n,`${$n}${s}`),u=await vt.readdir(l);await vt.mkdir(d,{mode:ov});for(let p of u)await vt.cp(Jt(l,p),Jt(d,p),{recursive:!0,force:!1,errorOnExist:!0});await vt.chmod(d,ov)}await cB(c,Jt(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},av=(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(`
281
+ `)}},Im=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),cv=async e=>{let t=[];for(let n of oB)t.push({lane:n,sources:await sB(e,n)});return t},lv=async(e={})=>{let t=(e.firstPartyRoot??(()=>Hs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([cv(t),vm(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Im(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}},oo=async(e={})=>{let t=(e.home??eB)(),n=(e.firstPartyRoot??(()=>Hs()))(),r=(e.thirdPartyRoot??(()=>Qr()))();if(!n||!r)return{ok:!1,kind:"platform-unsupported",reason:"this platform has no Claude Desktop third-party profile",remedy:"Migration applies to macOS and Windows, where Desktop runs third-party mode in its own profile."};if((e.appRunning??ca())())return{ok:!1,kind:"app-running",reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop and run this again \u2014 it rewrites its session list on exit, which would undo the migration."};let[o,a]=await Promise.all([cv(n),vm(n)]),s;if(e.account){let f=e.account;for(let w of o)w.sources=w.sources.filter(y=>y.account.startsWith(f));let m=a.accounts.filter(w=>w.startsWith(f));if(o.every(w=>w.sources.length===0)&&m.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${f}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let h=Im(o);for(let w of m)h.add(w);if(h.size>1)return av(o,e.command??"anyray-connect desktop --migrate",`"${f}" matches ${h.size} accounts`,m);s=[...h]}else if(!e.allAccounts){let f=Im(o);for(let m of a.accounts)f.add(m);if(f.size>1)return av(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${f.size} accounts`,a.accounts);s=[...f]}let i=e.command??"anyray-connect desktop --migrate",c=!await nB(r),l=await rv(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:f,sources:m}of o){if(m.length===0){d.push(Sm(f));continue}let h=await iB(r,f);if("missing"in h){u.push({lane:f,reason:h.missing,waiting:m.reduce((w,y)=>w+y.ids.length,0)}),d.push(Sm(f));continue}d.push(await dB(f,m,h.dir,t))}if(!(d.some(f=>f.migrated>0||f.alreadyPresent>0)||l.outcomes.some(f=>f.migrated>0||f.alreadyPresent>0||f.conflicts>0))&&(u.length>0||l.blocked.length>0)){let f=u[0];return f?{ok:!1,kind:f.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:f.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${f.lane} store`:`Claude Desktop has no ${f.lane} store in its third-party profile yet`,remedy:Em(f.reason,f.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 pB=e=>[Ve(e)],dv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...pB(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await x(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 uv="1.21459.0",yB=hB(fB),gB=async e=>{try{let{stdout:t}=await yB("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},wB=async e=>{try{return await mB(e)}catch{return}},pv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",bB=["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."],da=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(fv??=mv({}),fv):mv(e),fv,mv=async e=>{let t=(e.home??oi)(),n=["/Applications/Claude.app",bn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??gB,o=e.readClaudeAppBundle??wB;for(let a of n){let s=await r(bn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${pv}`}),c=vl(s,uv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${uv} or newer.`);let l=await o(bn(a,"Contents","Resources","app.asar"));return l?XC.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. ${pv}`}},Xl="anyray",gv="--anyray-owner=claude-desktop-v1",zl=(e={})=>{let t=(e.platform??br)(),n=(e.home??oi)();return t==="darwin"?jt(e).appConfig:t==="win32"?bn(process.env.APPDATA??bn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):bn(n,".config","Claude","claude_desktop_config.json")},_m=(e={})=>bn((e.home??oi)(),"Library","Application Support","Claude","claude_desktop_config.json"),wv=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,gv]}},ao=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),bv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},AB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),CB=e=>{if(!ao(e)||!bv(e,["command","args"]))return!1;let t=wv();return e.command===t.command&&AB(e.args,t.args)},kB=e=>ao(e)&&Array.isArray(e.args)&&e.args.at(-1)===gv,vB=e=>{if(!ao(e)||!bv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||He(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===Xn&&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!He(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},SB=e=>e===void 0?"absent":CB(e)?"exact":kB(e)||vB(e)?"stale-owned":"foreign",Me=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},so=async e=>{let t=await x(e),n;try{n=await M(e)}catch{throw new Me(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!ao(n.mcpServers))throw new Me(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(ao(n.mcpServers)?n.mcpServers:void 0)?.[Xl];return{path:e,fileExisted:t,json:n,entry:o,ownership:SB(o)}},ql=e=>{if(e.ownership==="foreign")throw new Me(`MCP name conflict in ${e.path}: mcpServers.${Xl} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},Av=(e,t)=>{let n={...e},r=ao(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[Xl]:r[Xl]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Rm=async(e,t)=>{if(xm(e.entry,t))return;let n=await so(e.path);if(!xm(n.entry,e.entry))throw new Me(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Mn(e.path,Av(n.json,t)),{reading:e,afterEntry:t}},Om=async e=>{let t=await so(e.reading.path);if(!xm(t.entry,e.afterEntry))throw new Me(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=Av(t.json,e.reading.entry);await Mn(e.reading.path,n)},IB=async e=>{if(!te())throw new Me(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Oe()} is temporary); no inference setting was changed.`);let t=await so(zl(e));ql(t);let n=_m(e),r=(e.platform??br)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},hv=async e=>{let t=await so(zl(e));ql(t);let n=_m(e),r=(e.platform??br)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},EB=async e=>{let t=[];try{let n=await Rm(e.active,wv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Rm(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Om(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Me(`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 Om(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Me(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},xB=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Rm(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Om(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Me(`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)},yv=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)."]},RB={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Ql="claude-desktop",Tm="migrate",Cv=new Set(["app-running","store-missing"]),OB={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},TB={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"}},_B="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",kv=e=>{let t=(e.platform??br)(),n=e.home??oi;return{home:n,appRunning:e.appRunning??ca(t),firstPartyRoot:()=>Hs({home:n,runtimePlatform:t}),thirdPartyRoot:()=>Qr({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},vv=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=OB[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.`:"")},Sv=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=TB[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.`:"")},ri=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=kv(e),r=await(e.pendingDesktopMigrationCount??lv)(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??oo)(n);if(a.ok){let c=vv(a.lanes),l=Sv(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,p=(a.blocked??[]).filter(g=>g.reason!=="ambiguous"),f=a.blockedAssets??[],m=a.retryableAssets??[];if(p.length===0&&f.length===0&&m.length===0)return[c,l,u].filter(g=>!!g);if(t.preservePendingOp)return[c,l,u].filter(g=>!!g);await gs(Ql,Tm);let h=p.reduce((g,b)=>g+b.waiting,0),w=[h>0?`${h} more session${h===1?"":"s"}`:"",f.length>0?`${f.length} extension ${f.length===1?"store":"stores"}`:""].filter(Boolean),y=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...m.length>0?[`Queued: ${m.length} portable configuration ${m.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...y]}if(!Cv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
282
+ ${a.remedy}`];if(t.preservePendingOp)return[];await gs(Ql,Tm);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."]}},PB=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await ar(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."]}},DB=e=>dv({id:Ql,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??br)(),n=(e.home??oi)();return t==="darwin"?["/Applications/Claude.app",bn(n,"Applications","Claude.app")]:t==="win32"?[bn(process.env.LOCALAPPDATA??bn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>ee(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:",...yv(t)]:["Claude desktop org/API lane:",...yv(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`."]}),LB=(e={})=>{let t=DB(e),n=()=>(e.platform??br)()==="darwin",r=()=>(e.platform??br)()==="win32",o=(s,i)=>n()?ok(s,i,e):$k(s,s.clientKey??"",i,e),a=s=>n()?ak(s,e):Mk(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ca((e.platform??br)()))(),quitTarget:RB,needsTarget:()=>!1,async complete(s){if(s!==Tm)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??oo)(kv(e));if(i.ok){let c=vv(i.lanes),l=Sv(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 p=(i.blocked??[]).filter(h=>h.reason!=="ambiguous"),f=i.blockedAssets??[],m=i.retryableAssets??[];return p.length>0||f.length>0||m.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...p.length>0||f.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."]:[],...m.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(h=>!!h):["No portable Claude Desktop data was left to bring across."]}}return Cv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?ik(s,e):r()?Wk(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let p=jt(e),f=await to(p,e);if(f)return{status:"manual",manualAudience:"admin",messages:[em(f),...await ri(e,i)]}}if(r()){let p;try{p=await wr(e.runReg??Fn)}catch{return{status:"manual",manualAudience:"admin",messages:[_B,...await ri(e,i)]}}if(p)return{status:"manual",manualAudience:"admin",messages:[gm(p),...await ri(e,i)]}}if(r()&&ee(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 p=await da(e);if(!p.supported)return{status:"manual",messages:[p.message??"Claude Desktop version is unsupported."]}}let c;try{c=await IB(e)}catch(p){let f=p instanceof Me?p.changedFiles:[];return{status:"manual",...f.length>0?{changedFiles:f}:{},messages:[p instanceof Me?p.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 p=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...p&&p.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${p.path}.`]:[],...await ri(e,i)]}}let d;try{d=await EB(c)}catch(p){let f=p instanceof Me?p.changedFiles:[];return{status:"manual",...f.length>0?{changedFiles:f}:{},messages:[p instanceof Me?p.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 ri(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?bB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=zl(e),c=await PB(s),l=h=>c.length===0?h:{...h,messages:[...h.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await hv(e)}catch(h){return l({status:"manual",messages:[h instanceof Me?h.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 h=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...h&&h.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${h.path}.`]:[]]})}let p=await a({dryRun:!1});if(p.status==="manual"){let h=r()?$t(e):void 0;if(!(h!==void 0&&p.changedFiles?.includes(h)===!0&&!await x(h)))return l(p)}let f;try{f=await xB(await hv(e))}catch(h){let w=h instanceof Me?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...p.changedFiles??[],...w])],messages:[...p.messages,h instanceof Me?h.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await oe(i);let m=_m(e);return n()&&m!==i&&await oe(m),l({...p,messages:[...p.messages,...f.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...p.changedFiles??[],...f])]})},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await so(zl(e));return s.ownership!=="exact"||!ao(s.entry)?{registered:!1,command:null,reason:s.fileExisted?s.ownership==="absent"?"absent":s.ownership==="stale-owned"?"stale":"foreign":"no-config"}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async pointsAt(s){return n()?(await da(e)).supported?nm(s,e):!1:r()?Fk(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await da(e)).supported)return["unknown"];let s=await sk(e);return s?[s]:["unknown"]}if(r())return await x($t(e))?await wr(e.runReg??Fn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=jt(e);return!await x(s.journal)||await to(s,e)?!1:(await da(e)).supported}return r()&&await x($t(e))?!await wr(e.runReg??Fn):!1}catch{return!1}}}},Iv=LB();import{homedir as cF}from"node:os";import{join as lF}from"node:path";import{rm as cd}from"node:fs/promises";import{constants as Ev,accessSync as NB,statSync as $B}from"node:fs";import{platform as Pm}from"node:os";import{delimiter as MB,posix as BB,resolve as FB,win32 as WB}from"node:path";var UB="0.59.0",HB="1.1.4",Wn="Anyray \xB7 Claude",Un="Anyray \xB7 Codex",ed="__anyray-acp-agent",xv=(e,t,n)=>{let{command:r,args:o}=en([ed,e,t,n]);return{command:r,args:o,env:{}}},td=(e=Pm())=>e==="win32"?"npx.cmd":"npx",nd=(e=process.env.PATH,t=Pm())=>{if(!e)return;let n=td(t);for(let r of e.split(MB)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=FB(o,n);try{if(!$B(a).isFile())continue;return NB(a,t==="win32"?Ev.F_OK:Ev.X_OK),a}catch{}}},rd=(e,t=Pm())=>{let n=t==="win32"?WB:BB;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==td(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},GB="https://chatgpt.com/backend-api/codex",VB="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Rv="ANYRAY_ACP_CODEX_AUTHORIZATION",Ov="ANYRAY_ACP_CODEX_CLIENT_KEY",Tv="ANYRAY_ACP_CODEX_METADATA",_v=e=>ue({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),KB=(e,t={})=>{let n=ee(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":GB,"x-anyray-forward-headers":VB}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Ov}:{}}:{Authorization:Rv};return _v(e)&&(o["x-anyray-metadata"]=Tv),{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}}}:{}}},jB=e=>{let t=ee(e,"openai"),n=_v(e);return{...t?e.clientKey?{[Ov]:e.clientKey}:{}:{[Rv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[Tv]:n}:{}}},Pv=(e,t=td(),n={})=>({[Wn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${UB}`],env:tn(e).env},[Un]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${HB}`],env:{CODEX_CONFIG:JSON.stringify(KB(e,n)),...jB(e)}}}),ai=(e=td(),t="jetbrains")=>({[Wn]:xv("claude",e,t),[Un]:xv("codex",e,t)}),io=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),od=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as ZB}from"node:zlib";import{open as YB,readFile as Mm,readdir as id}from"node:fs/promises";import{dirname as Dv,join as fe}from"node:path";import{homedir as Mv,platform as Bm}from"node:os";var ad="2025.3.2",ua="253.30387.147",si="com.intellij.ml.llm",Dm=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),JB=1e4,XB=256*1024*1024,zB=16*1024*1024,Lm=1024*1024,Nm=22,qB=Nm+65535,$m=vl,QB=()=>{let e=Mv(),t=fe(e,".cache","JetBrains","RemoteDev");switch(Bm()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:fe(e,"Applications"),layout:"app-bundles"},{path:fe(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:fe(process.env.LOCALAPPDATA??fe(e,"AppData","Local"),"Programs"),layout:"children"},{path:fe(process.env.LOCALAPPDATA??fe(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:fe(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:fe(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},eF=()=>Bm()==="linux"?fe(Mv(),".local","share","JetBrains"):Ve("JetBrains"),tF=()=>Bm()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),nF=async(e,t=JB)=>{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=fe(r.path,i.name),l=r.layout==="app-bundles"?fe(c,"Contents","Resources","product-info.json"):fe(c,"product-info.json");await x(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=fe(s,"product-info.json"),l=fe(s,"Contents","Resources","product-info.json");if(await x(c)){n.push(c);return}if(await x(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 p=fe(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(p,i-1)}};await a(r.path,7)}return[...new Set(n)]},rF=e=>{let t=Dv(e);return t.endsWith(`${fe("Contents","Resources")}`)?Dv(t):t},oF=async e=>{try{let t=JSON.parse(await Mm(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Ws(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:rF(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},aF=async(e,t)=>{let n;try{n=await YB(e,"r");let{size:r}=await n.stat();if(r<Nm||r>XB)return;let o=Math.min(r,qB),a=await sd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Nm;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>zB||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),p=l.readUInt32LE(d+20),f=l.readUInt32LE(d+24),m=l.readUInt16LE(d+28),h=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),g=d+46+m+h+w;if(g>l.length)return;let b=l.subarray(d+46,d+46+m).toString("utf8");if(d=g,b!==t)continue;if(p===4294967295||f===4294967295||p>Lm||f>Lm)return;let k=await sd(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),I=await sd(n,p,y+30+C+S);return I?u===0?I.toString("utf8"):u===8?ZB(I,{maxOutputLength:Lm}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},Lv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Ws(n)))return{id:t,version:n}},sF=async(e,t)=>{let n=fe(e,"META-INF","plugin.xml");if(await x(n))try{let o=Lv(await Mm(n,"utf8"));return{present:o?.id===si||t,descriptor:o?.id===si?o:void 0}}catch{return{present:t}}let r=[];try{r=(await id(fe(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=>fe(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await aF(o,"META-INF/plugin.xml"),s=a?Lv(a):void 0;if(s?.id===si)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Nv=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=Dm.has(o.name.toLowerCase()),i=Dm.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Dm.has(o.name.toLowerCase());if(!a){let i=fe(e,o.name,"META-INF","plugin.xml");if(!await x(i))continue}let s=await sF(fe(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},iF=async e=>{try{return(await Mm(fe(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(si)}catch{return!1}},$v=e=>e.reduce((t,n)=>t?($m(n,t)??-1)>0?n:t:n,void 0),Bv=async(e={})=>{let t=e.configRoot??Ve("JetBrains"),n=e.userPluginsRoot??eF(),r=await nF(e.productRoots?e.productRoots.map(m=>({path:m,layout:"recursive"})):QB(),e.scanBudget),o=(await Promise.all(r.map(m=>oF(m)))).filter(m=>m!==void 0),a=o.length>0||await x(t);if(e.wsl??tF())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(m=>($m(m.version,ad)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let m of s){let h=fe(t,m.dataDirectoryName);if(!await x(h)){d=!0;continue}let w=[fe(h,"plugins"),fe(n,m.dataDirectoryName),fe(n,m.dataDirectoryName,"plugins")],y;for(let g of[...new Set(w)]){let b=await Nv(g);if(b.present){y=b;break}}if(y??=await Nv(fe(m.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==si)){if(i.push(y.descriptor.version),await iF(h)){c=!0;continue}if(!(($m(y.descriptor.version,ua)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${m.version}; AI Assistant ${y.descriptor.version}; ACP supported`,ideVersion:m.version,pluginVersion:y.descriptor.version}}}let u=$v(o.map(m=>m.version)),p=$v(i),f;return a?u?s.length===0?f=`JetBrains IDE ${u} is below the ACP minimum ${ad}; no ACP config was written.`:d?f=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${ad}+ once, enable AI Assistant ${ua}+, then run Connect again. No ACP config was written.`:c?f=`JetBrains AI Assistant is disabled; enable version ${ua}+ and run Connect again. No ACP config was written.`:p?f=`JetBrains AI Assistant ${p} is below the ACP minimum ${ua}; no ACP config was written.`:l?f=`Could not verify the local JetBrains AI Assistant version; require ${ua}+ before running Connect. No ACP config was written.`:f=`JetBrains AI Assistant ${ua}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:f=`Could not prove JetBrains IDE ${ad}+ from local product-info.json; no ACP config was written.`:f="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:f,ideVersion:u,pluginVersion:p}};var dF=[Wn,Un],Fm=()=>lF(cF(),".jetbrains","acp.json"),co=()=>`${Fm()}.anyray-state`,uF=(e,t,n="npx")=>{let r=io(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,ai(n,"jetbrains")),{...e,agent_servers:r}},pF=(e,t,n)=>{if(!io(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=io(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of dF)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}},fF=(e=Bv)=>({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=Fm(),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 x(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=ai(a,"jetbrains");return await Zi({configPath:r,current:c,next:uF(c,t,a),journalPath:co(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,co()]}},async revert(t){let n=Fm(),r=async()=>{if(!await x(n))return t.dryRun||(await oe(n),await cd(co(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await oe(n),await cd(co(),{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(co());(u.version===1||u.version===2)&&io(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 x(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=pF(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 Y(n,l.next,{backup:!1})),t.dryRun||(await oe(n),await cd(co(),{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():ji(n,co(),r)}}),Fv=fF();import{homedir as dd}from"node:os";import{join as ud}from"node:path";import{rm as Wm}from"node:fs/promises";var Um="1.0.0",pd=["anyray-claude-acp","anyray-codex-acp"],mF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Hm=()=>ud(dd(),".windsurf","acp","registry.json"),Gm=()=>ud(dd(),".windsurf-next","acp","registry.json"),pa=e=>`${e}.anyray-state`,Wv=e=>({binary:Object.fromEntries(mF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Hv=(e="npx")=>{let t=ai(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:Un,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Wv(t[Un])}]},ld=e=>!Array.isArray(e)||e.some(t=>!io(t)||typeof t.id!="string")?null:e,hF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Um||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:Um,agents:[...n.filter(o=>!r.has(o.id)),...Hv(t)],extensions:e.extensions??[]}},yF=(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 p=s.get(u.id);p&&l.push(p),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===Um&&delete d.version,!Object.prototype.hasOwnProperty.call(t,"extensions")&&Array.isArray(d.extensions)&&d.extensions.length===0&&delete d.extensions,{next:d,removed:i,conflicts:c}},Uv=async()=>{let e=[];return(await x(Gm())||await x(ud(dd(),".windsurf-next")))&&e.push(Gm()),(await x(Hm())||await x(ud(dd(),".windsurf"))||await x(Ve("Devin"))||await x(Ve("Windsurf")))&&e.push(Hm()),e},Gv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Uv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Uv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=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=hF(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 x(s),d=Hv(r);await Zi({configPath:s,current:i,next:c,journalPath:pa(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,pa(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=[Hm(),Gm()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await oe(a),await Wm(pa(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 f=await M(pa(a));(f.version===1||f.version===2)&&Array.isArray(f.agents)&&(c=f.agents,l=f.version===2&&f.fileExisted===!1,d=f.version===2&&f.fileExisted===!0)}catch{}let u;if(d){let f=`${a}.anyray-bak`;if(!await x(f)){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(f)}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 p=yF(i,u,c);if(!p){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}p.removed.length&&(n.push(`Removed ${p.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(p.next).length===0?await Wm(a,{force:!0}):await Y(a,p.next,{backup:!1}),r.push(a))),p.conflicts.length?(n.push(`Preserved user-modified agents: ${p.conflicts.join(", ")}.`),o=!0):e.dryRun||(await oe(a),await Wm(pa(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await ji(a,pa(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var le=[Qn,Lw,ks,MA,dC,kC,OC,Fv,Iv,Gv,Hw],mt=e=>le.find(t=>t.id===e);var Be=async(e=P,t=fn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:xe({origin:n.gateway,clientKey:n.clientKey,subscription:n.authMode==="subscription",placeholder:n.authMode==="placeholder",byoUpstream:n.byoUpstream,seat:r,user:n.name,team:n.team})}};var Vm=5e3,Vv=3e4,gF=1440*60*1e3,wF=e=>new Promise(t=>setTimeout(t,e)),bF=async(e=P,t=fn)=>(await Be(e,t))?.target,AF=e=>mt(e)?.quitGated,Kv=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??AF,o=t.readPending??Hc,a=t.clearPending??Op,s=t.targetFromProfile??bF,i=t.sleep??wF,c=t.now??Date.now,l=t.maxWaitMs??gF;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),p=c(),f=Vm;for(;;){let m=await o(n);if(!m||c()-p>l)return 0;if(d.isRunning()){await i(f),f=Math.min(Vv,f*2);continue}let h;if(d.needsTarget?.(m.op)&&(h=await s(),!h)){if(await a(n,m)!=="superseded")return 0;await i(f),f=Vm;continue}if((await u(m.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(f),f=Math.min(Vv,f*2);continue}if(await a(n,m)!=="superseded")return 0;await i(f),f=Vm}}catch{return 0}};import{writeFileSync as cW}from"node:fs";import{chmod as nh,stat as lW}from"node:fs/promises";import{platform as kS}from"node:os";import{dirname as vS,isAbsolute as dW}from"node:path";var CF="https://app.anyray.ai",kF=new Set(["localhost","::1","[::1]"]),vF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,SF=e=>kF.has(e)||vF.test(e),Km=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&SF(t.hostname)},IF=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Hn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!Km(e)?CF:IF(e)};import{createHash as BF,generateKeyPairSync as FF,randomBytes as Ym}from"node:crypto";import{createPrivateKey as EF,sign as xF}from"node:crypto";var Ar=async(e,t)=>{let n=EF(t);return xF(null,new TextEncoder().encode(e),n).toString("base64url")};var RF=["HTTPS_PROXY","https_proxy"],jv=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"]),Zv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Yv=new Set(["ENOTFOUND","EAI_AGAIN"]),Jv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Xv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),OF=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 TF(e)},TF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...jv,...Zv,...Yv,...Jv,...Xv])if(t.includes(n))return n}},_F=e=>e?.name==="AbortError"||e?.name==="TimeoutError",PF=e=>RF.filter(t=>(e[t]??"").trim()!==""),DF=(e,t=process.env)=>{let n=OF(e),r=PF(t);return{kind:n&&jv.has(n)?"tls-unknown-issuer":n&&Zv.has(n)?"tls-invalid-cert":n&&Yv.has(n)?"dns":_F(e)||n&&Xv.has(n)?"timeout":n&&Jv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},LF=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}},ht=(e,t=process.env)=>LF(DF(e,t));var NF="enl_",zv="enp_",qv=e=>e.startsWith(NF)||e.startsWith(zv),jm=e=>e.startsWith(zv),$F=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],Zm=e=>$F.find(t=>e.startsWith(t.prefix)),Qv=/^\/enroll\/([^/]+)\/?$/,eS=/^\/i\/([^/]+)\/?$/,tS=e=>{let t=e.match(Qv);if(t)return Zm(t[1])?void 0:t[1];let n=e.match(eS);return n&&qv(n[1])?n[1]:void 0},MF=1e4,fd=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=tS(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!Zm(t))return{cpOrigin:Hn(),token:t}},nS=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(Qv)??o.pathname.match(eS);if(!a)return;n=a[1]}catch{}let r=Zm(n);return r?{flag:r.flag,what:r.what}:void 0},ci=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:tS(n.pathname)!==void 0}catch{return qv(t)}},fa=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},ii=e=>typeof e=="string"&&e.trim()?e.trim():void 0,rS=async(e,t={})=>{let n=t.timeoutMs??MF,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 p=u instanceof Error&&u.name==="AbortError"?` no response within ${n}ms.`:ht(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${p}`)}finally{clearTimeout(a)}if(!s.ok){let u=`enrollment link lookup failed: ${e.cpOrigin} responded ${s.status} \u2014 the link may be expired or revoked; ask your admin for a fresh one.`;throw s.status>=400&&s.status<500&&s.status!==429?new fa(u):new Error(u)}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"&&ii(u.url)!==void 0),d=ii(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:ii(l?.deploymentId),org:ii(i.org),email:ii(i.email),seatMode:i.seatMode===!0,...i.provisioningKind==="manual"||i.provisioningKind==="mdm"?{provisioningKind:i.provisioningKind}:{},...i.provisioningProofMode==="managed-preference"?{provisioningProofMode:i.provisioningProofMode}:{},...Array.isArray(i.allowedDomains)?{allowedDomains:i.allowedDomains.filter(u=>typeof u=="string"&&u.length>0)}:{}}};var Jm=1e4,lo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(lo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${lo(e[n])}`).join(",")}}`,oS="stable-key-heartbeat-v1",aS="key-heartbeat",WF=["reapply_config","remint","revert"],Xm=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var sS=e=>BF("sha256").update(e).digest("hex"),Ze=e=>typeof e=="string"&&e.trim()?e.trim():void 0,UF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],iS={no_mdm_server_registered:"no MDM server is registered in the Anyray console",agent_missing:"the Anyray endpoint agent is not reporting for this machine",mdm_not_verified:"this machine is not enrolled in the registered MDM",endpoint_unreachable:"the endpoint service could not be reached"},HF=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${iS[e]}. Ask your IT admin.`,GF=e=>typeof e=="string"&&e in iS,zm=async e=>{try{let t=await e.json(),n=Ze(t?.message),r=Ze(t?.error),o=GF(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:HF(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},VF=async e=>(await zm(e)).message,lt=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this enrollment (HTTP ${t}): ${r.message}`),this.name="GatewayVerifyError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},cS=e=>e instanceof fa||e instanceof lt&&e.policyCode==="sso_required",ma=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this credential heartbeat (HTTP ${t}): ${r.message}`),this.name="GatewayHeartbeatError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},qm=async(e,t,n,r)=>{try{return await r(lo(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},md=()=>{let{publicKey:e,privateKey:t}=FF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},Xt=async(e,t,n,r={})=>{let o=r.timeoutMs??Jm,a=`${e}/connect/verify`,s=Ze(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:Ym(16).toString("hex"),...Xm(t,r.machineUuid)},c=await qm(i,n,"verification",r.signer??Ar),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":Ae},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(g){let b=g instanceof Error&&g.name==="AbortError"?` no response within ${o}ms.`:ht(g);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:g})}finally{clearTimeout(d)}if(!u.ok)throw new lt(u.status,await zm(u));let p;try{p=await u.text()}catch{p=""}let f;try{f=JSON.parse(p)}catch{let g=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(g)||/^\s*<(?:!doctype|html)/i.test(p);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 m=Ze(f?.key);if(!m)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(m))throw new Error("developer verification failed: the gateway returned a malformed key");let h=Ze(f.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let w=KF(f.directive),y=UF(f.capabilities);return{key:m,user:h,team:Ze(f.team),expiresAt:Ze(f.expiresAt),...y.length>0?{capabilities:y}:{},...w?{directive:w}:{}}},lS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Jm,s=`${e}/connect/key/heartbeat`,i=Ze(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:Ym(16).toString("hex"),purpose:aS,...Xm(n,o.machineUuid)},l=await qm(c,r,"heartbeat",o.signer??Ar),d=new AbortController,u=setTimeout(()=>d.abort(),a),p;try{p=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":Ae},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(h){let w=h instanceof Error&&h.name==="AbortError"?` no response within ${a}ms.`:ht(h);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:h})}finally{clearTimeout(u)}if(!p.ok)throw new ma(p.status,await zm(p));let f;try{f=await p.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let m=Ze(f.expiresAt);if(!m||!Number.isFinite(Date.parse(m))||f.credentialMode!==oS||f.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:m,credentialMode:oS}},dS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Jm,i=`${e.replace(/\/$/,"")}/connect/machine`,c=Ze(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Ym(16).toString("hex"),purpose:aS,...Xm(n,o)},d=await qm(l,r,"heartbeat",a.signer??Ar),u=new AbortController,p=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":Ae},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(f){return console.error("connect machine report skipped:",f instanceof Error?f.name:"error"),!1}finally{clearTimeout(p)}},KF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=Ze(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!WF.includes(r)?null:{id:n,kind:r}},jF=1e4,ZF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!Ze(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!Ze(r.deploymentId)&&!!Ze(r.user)&&!!Ze(r.devPublicKey)&&!!Ze(r.issuedAt)&&!!Ze(r.expiresAt)},YF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??jF,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 p=u instanceof Error&&u.name==="AbortError"?` no response within ${a}ms.`:ht(u);throw new Error(`could not reach the control plane at ${s}.${p}`)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await VF(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new fa(u):new Error(u)}let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!ZF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},uS=(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())},pS=async e=>{let t={timeoutMs:e.timeoutMs,machineUuid:e.machineUuid,signer:e.signer},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=md();return{cert:await YF(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await Xt(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}};var Qm=1e4,JF=900*1e3,mS="tnt_",XF=/^\/sso\/([^/]+)\/?$/,zF=/^\/i\/([^/]+)\/?$/,qF=e=>{let t=e.match(XF);if(t)return t[1];let n=e.match(zF);return n?.[1].startsWith(mS)?n[1]:void 0},St=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=qF(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(mS))return{cpOrigin:Hn(),tenantId:t}},uo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Mt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},eh=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)}},QF=e=>new Promise(t=>setTimeout(t,e)),hd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??md)(),a;try{a=await eh(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},Qm,n)}catch(m){throw new uo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ht(m)}`)}if(a.status!==200){let m=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new uo(m?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${h}). 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 uo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??JF,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),p={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},f=e.log??(()=>{});return f("To finish, sign in with your organization at:"),f(` ${p.verificationUriComplete}`),f(`Confirm this code matches your browser: ${p.userCode}`),eW(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},eW=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},yd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??QF,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 eh(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},Qm,o)}catch(c){throw new Mt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ht(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 Mt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Mt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Mt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var fS="sdc_",hS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(fS))return{cpOrigin:Hn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!Km(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(fS)))return{cpOrigin:n.origin,claim:r}},yS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??md)(),o;try{o=await eh(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},Qm,t)}catch(s){throw new Mt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ht(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 Mt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Mt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Mt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};import{readFile as tW}from"node:fs/promises";import{isAbsolute as nW,posix as gS,win32 as th}from"node:path";var li=(e=process.platform,t=process.env)=>e==="darwin"?gS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?th.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):gS.join("/etc","anyray","bootstrap.json"),rW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(nW(e)||th.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),oW=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&!t.username&&!t.password}catch{return!1}},Cr=async(e=li())=>{try{let t=await tW(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!rW(n)||n.v!==1||typeof n.sso!="string")return;let r=St(n.sso);if(!r)return;let o=oW(n.gateway)?n.gateway:void 0,a=wS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},bS=(e,t,n)=>{let r=St(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!wS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&th.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)}
283
+ `};var ha=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,gd=ha(process.stdout,process.env),AS=ha(process.stderr,process.env),ya=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,V=e=>ya("1",e,gd),v=e=>ya("2",e,gd),aW=e=>ya("32",e,gd),sW=e=>ya("33",e,AS),iW=e=>ya("31",e,AS),et=e=>ya("36",e,gd),A=e=>console.log(e),H=e=>console.log(`
284
+ ${V(e)}`),$=e=>console.log(v(e)),B=e=>console.log(`${aW("\u2713")} ${e}`),_=e=>console.error(`${sW("!")} ${e}`),O=e=>console.error(`${iW("\u2717")} ${e}`);var rh=`${V("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
285
285
 
286
286
  Emit or install the OS \`managed-settings.json\` that points a managed fleet's
287
287
  Claude Code at the Anyray gateway. It reads at a HIGHER precedence than a user's
@@ -364,15 +364,15 @@ ${V("Examples")}
364
364
  anyray-connect managed --print --tool jetbrains --bin /usr/local/bin/anyray-connect --npx /usr/local/bin/npx > acp.json
365
365
 
366
366
  # Shell/SDK fleet snippet (base URLs only; keys stay per-user):
367
- anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,wS=["claude-code","jetbrains","shell","bootstrap"],rW=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"--out":t.out=o();break;case"--tool":{let a=o();if(!wS.includes(a))throw new Error(`unknown --tool ${a} (expected ${wS.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&&!St(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function gd(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:[kn(es(t.binaryPath,[ze]),{matcher:"*"})],UserPromptSubmit:[kn(es(t.binaryPath,o),{timeout:30}),kn(es(t.binaryPath,[Zn]))],SessionStart:[kn(es(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=tn(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(vn.map(o=>[o.name,""])),...r}}:{env:r}}var oW=(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,Ku(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},aW=e=>{let t=e.env,n=Ku(e);if(t){for(let r of $r)r in t&&(delete t[r],n=!0);for(let{name:r}of vn)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},CS=async e=>{let t=async n=>{try{return(await tW(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(AS(e))!==void 0}},kS=async(e,t)=>(t.dirExisted||await oh(AS(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await oh(e,420),{mode:420,keptRestricted:!1}):(await oh(e,t.mode),{mode:t.mode,keptRestricted:!0})),vS=(e,t)=>{t.keptRestricted&&(_(`${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.`),A(v(" 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.")))},SS=()=>process.getuid?.()===0,Ye=e=>{process.stderr.write(`${e}
368
- `)},wd=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}eW(e.out,t,"utf8"),Ye(v(`# Wrote ${e.out}`))},sh=e=>xe({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),ih=e=>nW(e)||/^[A-Za-z]:[\\/]/.test(e),IS=e=>{if(!e.sso)return;let t=St(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(!ih(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}},ES=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${ue(e.metadata)??"(none \u2014 pass --team)"}`],ch=(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{}},sW=(e,t)=>({agent_servers:{[Fn]:{command:e,args:[Ql,"claude",t,"jetbrains"],env:{}},[Wn]:{command:e,args:[Ql,"codex",t,"jetbrains"],env:{}}}}),iW=e=>["# Managed by anyray-connect (fleet). Routes shell/SDK traffic through the Anyray gateway.","# Per-user keys come from enrollment (`anyray-connect --enroll/--sso`); never add a key here.",`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,""].join(`
369
- `),cW=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(!ih(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(!nd(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return wd(e,`${JSON.stringify(sW(e.bin,e.npx),null,2)}
370
- `),Ye(v("# acp.json for ~/.jetbrains/acp.json (per user).")),Ye(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ye(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ye(v("# 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},lW=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&&!ih(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return wd(e,yS(e.sso,e.gateway,e.bin)),Ye(v(`# Fleet bootstrap for ${li("linux")}`)),Ye(v(`# macOS: ${li("darwin")}`)),Ye(v(`# Windows: ${li("win32",{ProgramData:"C:\\ProgramData"})}`)),Ye(v("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},dW=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: the snippet carries base URLs only (keys and attribution ride each user\u2019s enrollment)");let t=sh(e);return wd(e,iW(t)),Ye(v("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),ch(t,Ye),0},uW=e=>{let t=sh(e),n=IS(e),r=n?gd(t,n):gd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(wd(e,`${JSON.stringify(r,null,2)}
371
- `),Ye(v(`# managed-settings.json for ${Ot()}`)),n)Ye(v("# Deferred SSO: hooks only; no credential or managed env block.")),Ye(v(`# Push the binary to ${n.binaryPath} before this file.`)),Ye(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of ES(t))Ye(v(`# ${o}`));ch(t,Ye)}return 0},pW=async e=>{let t=bS();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(!SS())return O("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),A(v(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=sh(e),r=IS(e);r||ch(n,u=>_(u.replace(/^!\s*/,"")));let o=Ot(t),a=await B(o),s=r?gd(n,r):gd(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?vn.filter(({name:u})=>{let p=a.env?.[u];return typeof p=="string"&&p.trim()!==""}):[],c=oW(a,s),l=await CS(o);await Y(o,c);let d=await kS(o,l);M(`Wrote ${o}`),vS(o,d);for(let{name:u,cloud:p}of i)_(`${u} was set in this file and is now pinned empty \u2014 Claude Code no longer talks to ${p} directly. The gateway serves it instead; re-add the key here to undo.`);if(r)A(v(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),A(v(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of ES(n))A(` ${v(u)}`);return A(v(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},fW=async()=>{let e=bS();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(!SS())return O("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Ot(e);if(!await x(t))return A(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await B(t);if(!aW(n))return A(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await CS(t);await Y(t,n);let o=await kS(t,r);return M(`Removed Anyray-owned keys from ${t} (other keys left intact).`),vS(t,o),0},xS=async e=>{let t;try{t=rW(e)}catch(n){return O(n instanceof Error?n.message:"invalid managed arguments"),A(`
372
- `+ah),1}if(t.help||e.length===0&&!t.mode)return A(ah),0;if(!t.mode)return O("Specify a mode: --print, --write, or --revert."),A(`
373
- `+ah),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"?cW(t):n==="bootstrap"?lW(t):dW(t):t.mode==="print"?uW(t):t.mode==="write"?await pW(t):await fW()}catch(n){return O(n instanceof Error?n.message:"managed settings failed"),1}};import{spawn as AH}from"node:child_process";import{homedir as CH}from"node:os";import{join as pI}from"node:path";import{readFile as kH,writeFile as fI,chmod as vH,stat as SH,unlink as nI}from"node:fs/promises";var mW=["hook_registration","mcp_registration","hook_binary","beacon_target"],po=e=>e.status==="configured"||e.status==="queued",fo=async(e,t=le)=>{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},ga=async(e,t,n=le)=>{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},lh=async(e,t=le)=>{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(mW.map(o=>[o,"unreadable"]))})}return n},RS=e=>e.filter(t=>!t.integrationStatus),hW=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},Mt=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=hW(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 gW,writeFile as wW}from"node:fs/promises";import{join as TS}from"node:path";import{z as De}from"zod";var wa="required",yW=e=>e==="subscription"?"subscription":"placeholder",OS=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?yW(t.lane):void 0,a=o!=null&&o!==e.authMode;return{routingUpdated:n,teamUpdated:r,laneUpdated:a,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{},...a?{authMode:o}:{}}},bd=(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]??wa,l=[],d=[];for(let u of r){if(o.includes(u))continue;let p=c(u);if(p!=="optional"){if(p!=="locked"){if(!i)continue;if(s.has(u)){p==="required"&&d.push(u);continue}}l.push(u)}}return{candidateIds:a,freshIds:l,tombstonedIds:d}};var bW=1e4,AW=1,CW=De.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),kW=De.object({id:CW,name:De.string().min(1),version:De.string().min(1),body:De.string()}),vW=De.object({version:De.literal(AW).optional(),skills:De.array(kW),updatedAt:De.string().min(1).optional(),routing:De.object({origin:De.string().min(1)}).optional(),team:De.string().min(1).optional(),lane:De.enum(["subscription","org"]).optional().catch(void 0),tools:De.object({enabled:De.array(De.string().min(1)),tiers:De.record(De.string().min(1),De.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),ba=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},dh=e=>e instanceof ba&&e.kind==="auth",SW=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",uh=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",Aa=async(e,t,n={})=>{let r=n.timeoutMs??bW,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.`:ht(l);throw new ba("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new ba(i.status===401||i.status===403?"auth":"unavailable",`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch{throw new ba("malformed","team policy fetch failed: the gateway returned a malformed response")}return vW.parse(c)},_S=/^[a-z0-9][a-z0-9-]{0,31}$/,PS=64,IW=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>_S.test(o)).slice(0,PS).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>_S.test(o)).slice(0,PS).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},di=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??wa)==="locked":!1},Ca=async(e,t={})=>{let n=t.loadProfile??D,r=t.saveProfile??oe,o=t.targetFromProfile??Be,a=t.adapters??le,s=t.repairTools??Mt,i=t.recordManaged??Vn,c=await n(),l={...c},d=OS(c,{routingOrigin:e.routing?.origin?Qt(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:u,teamUpdated:p,laneUpdated:f}=d;(u||p||f)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),d.authMode!=null&&(l.authMode=d.authMode),await r(l));let m=bd(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||p||f),{candidateIds:h,freshIds:w}=m,y=0,g=0,b=0;if(h.length>0||w.length>0){let S=await o(async()=>l);if(S){let I;if(u||p||f){let P=new Set(h);I=[];for(let W of a)if(P.has(W.id))try{(await W.detect()).installed&&I.push(W)}catch{}}else I=await ga(h,S.target.origin,a);let E=new Set(w),R=[];for(let P of a)if(E.has(P.id))try{(await P.detect()).installed&&R.push(P)}catch{}if(y=I.length+R.length,y>0){let P=await s([...I,...R],S.target);g=P.filter(po).length;let W=P.filter(q=>E.has(q.id));if(b=W.filter(po).length,W.length>0)try{await i(W,!1)}catch{}}}}let k=IW(e),C=await n();if(JSON.stringify(k??null)!==JSON.stringify(C.fleetToolPolicy??null)){let{fleetToolPolicy:S,...I}=C;await r({...I,...k?{fleetToolPolicy:k}:{}})}return{routingUpdated:u,teamUpdated:p,laneUpdated:f,toolsRequested:y,toolsApplied:g,toolsEnrolled:b,toolsTombstoned:m.tombstonedIds,profileUpdated:u||p||f}},DS=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!SW(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=TS(d,i.id),p=TS(u,"SKILL.md");await gW(u,{recursive:!0}),await wW(p,EW(i.body),"utf-8"),l.push(p)}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}},EW=e=>e.endsWith(`
367
+ anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,CS=["claude-code","jetbrains","shell","bootstrap"],uW=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"--out":t.out=o();break;case"--tool":{let a=o();if(!CS.includes(a))throw new Error(`unknown --tool ${a} (expected ${CS.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&&!St(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function wd(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:[kn(es(t.binaryPath,[ze]),{matcher:"*"})],UserPromptSubmit:[kn(es(t.binaryPath,o),{timeout:30}),kn(es(t.binaryPath,[Yn]))],SessionStart:[kn(es(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=tn(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(vn.map(o=>[o.name,""])),...r}}:{env:r}}var pW=(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 Mr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,Vu(r),n.env&&(r.env={...o,...n.env}),n.hooks){let a=r.hooks??{};for(let[s,i]of Object.entries(n.hooks)){let c=Array.isArray(a[s])?a[s]:[];a[s]=[...c,...i]}r.hooks=a}return r},fW=e=>{let t=e.env,n=Vu(e);if(t){for(let r of Mr)r in t&&(delete t[r],n=!0);for(let{name:r}of vn)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},SS=async e=>{let t=async n=>{try{return(await lW(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(vS(e))!==void 0}},IS=async(e,t)=>(t.dirExisted||await nh(vS(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await nh(e,420),{mode:420,keptRestricted:!1}):(await nh(e,t.mode),{mode:t.mode,keptRestricted:!0})),ES=(e,t)=>{t.keptRestricted&&(_(`${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.`),A(v(" 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.")))},xS=()=>process.getuid?.()===0,Ye=e=>{process.stderr.write(`${e}
368
+ `)},bd=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}cW(e.out,t,"utf8"),Ye(v(`# Wrote ${e.out}`))},oh=e=>xe({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),ah=e=>dW(e)||/^[A-Za-z]:[\\/]/.test(e),RS=e=>{if(!e.sso)return;let t=St(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??Oe();if(!e.bin&&!te())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(!ah(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}},OS=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${ue(e.metadata)??"(none \u2014 pass --team)"}`],sh=(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{}},mW=(e,t)=>({agent_servers:{[Wn]:{command:e,args:[ed,"claude",t,"jetbrains"],env:{}},[Un]:{command:e,args:[ed,"codex",t,"jetbrains"],env:{}}}}),hW=e=>["# Managed by anyray-connect (fleet). Routes shell/SDK traffic through the Anyray gateway.","# Per-user keys come from enrollment (`anyray-connect --enroll/--sso`); never add a key here.",`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,""].join(`
369
+ `),yW=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(!ah(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 bd(e,`${JSON.stringify(mW(e.bin,e.npx),null,2)}
370
+ `),Ye(v("# acp.json for ~/.jetbrains/acp.json (per user).")),Ye(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ye(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ye(v("# 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},gW=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&&!ah(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return bd(e,bS(e.sso,e.gateway,e.bin)),Ye(v(`# Fleet bootstrap for ${li("linux")}`)),Ye(v(`# macOS: ${li("darwin")}`)),Ye(v(`# Windows: ${li("win32",{ProgramData:"C:\\ProgramData"})}`)),Ye(v("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},wW=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: the snippet carries base URLs only (keys and attribution ride each user\u2019s enrollment)");let t=oh(e);return bd(e,hW(t)),Ye(v("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),sh(t,Ye),0},bW=e=>{let t=oh(e),n=RS(e),r=n?wd(t,n):wd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(bd(e,`${JSON.stringify(r,null,2)}
371
+ `),Ye(v(`# managed-settings.json for ${Tt()}`)),n)Ye(v("# Deferred SSO: hooks only; no credential or managed env block.")),Ye(v(`# Push the binary to ${n.binaryPath} before this file.`)),Ye(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of OS(t))Ye(v(`# ${o}`));sh(t,Ye)}return 0},AW=async e=>{let t=kS();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(!xS())return O("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),A(v(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=oh(e),r=RS(e);r||sh(n,u=>_(u.replace(/^!\s*/,"")));let o=Tt(t),a=await M(o),s=r?wd(n,r):wd(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?vn.filter(({name:u})=>{let p=a.env?.[u];return typeof p=="string"&&p.trim()!==""}):[],c=pW(a,s),l=await SS(o);await Y(o,c);let d=await IS(o,l);B(`Wrote ${o}`),ES(o,d);for(let{name:u,cloud:p}of i)_(`${u} was set in this file and is now pinned empty \u2014 Claude Code no longer talks to ${p} directly. The gateway serves it instead; re-add the key here to undo.`);if(r)A(v(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),A(v(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of OS(n))A(` ${v(u)}`);return A(v(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},CW=async()=>{let e=kS();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(!xS())return O("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Tt(e);if(!await x(t))return A(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await M(t);if(!fW(n))return A(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await SS(t);await Y(t,n);let o=await IS(t,r);return B(`Removed Anyray-owned keys from ${t} (other keys left intact).`),ES(t,o),0},TS=async e=>{let t;try{t=uW(e)}catch(n){return O(n instanceof Error?n.message:"invalid managed arguments"),A(`
372
+ `+rh),1}if(t.help||e.length===0&&!t.mode)return A(rh),0;if(!t.mode)return O("Specify a mode: --print, --write, or --revert."),A(`
373
+ `+rh),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"?yW(t):n==="bootstrap"?gW(t):wW(t):t.mode==="print"?bW(t):t.mode==="write"?await AW(t):await CW()}catch(n){return O(n instanceof Error?n.message:"managed settings failed"),1}};import{spawn as RU}from"node:child_process";import{homedir as OU}from"node:os";import{join as hI}from"node:path";import{readFile as TU,writeFile as yI,chmod as _U,stat as PU,unlink as aI}from"node:fs/promises";var kW=["hook_registration","mcp_registration","hook_binary","beacon_target"],po=e=>e.status==="configured"||e.status==="queued",fo=async(e,t=le)=>{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},ga=async(e,t,n=le)=>{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},ih=async(e,t=le)=>{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(kW.map(o=>[o,"unreadable"]))})}return n},_S=e=>e.filter(t=>!t.integrationStatus),vW=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},Bt=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=vW(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 IW,writeFile as EW}from"node:fs/promises";import{join as DS}from"node:path";import{z as De}from"zod";var wa="required",SW=e=>e==="subscription"?"subscription":"placeholder",PS=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?SW(t.lane):void 0,a=o!=null&&o!==e.authMode;return{routingUpdated:n,teamUpdated:r,laneUpdated:a,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{},...a?{authMode:o}:{}}},Ad=(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]??wa,l=[],d=[];for(let u of r){if(o.includes(u))continue;let p=c(u);if(p!=="optional"){if(p!=="locked"){if(!i)continue;if(s.has(u)){p==="required"&&d.push(u);continue}}l.push(u)}}return{candidateIds:a,freshIds:l,tombstonedIds:d}};var xW=1e4,RW=1,OW=De.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),TW=De.object({id:OW,name:De.string().min(1),version:De.string().min(1),body:De.string()}),_W=De.object({version:De.literal(RW).optional(),skills:De.array(TW),updatedAt:De.string().min(1).optional(),routing:De.object({origin:De.string().min(1)}).optional(),team:De.string().min(1).optional(),lane:De.enum(["subscription","org"]).optional().catch(void 0),tools:De.object({enabled:De.array(De.string().min(1)),tiers:De.record(De.string().min(1),De.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),ba=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},ch=e=>e instanceof ba&&e.kind==="auth",PW=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",lh=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",Aa=async(e,t,n={})=>{let r=n.timeoutMs??xW,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.`:ht(l);throw new ba("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new ba(i.status===401||i.status===403?"auth":"unavailable",`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch{throw new ba("malformed","team policy fetch failed: the gateway returned a malformed response")}return _W.parse(c)},LS=/^[a-z0-9][a-z0-9-]{0,31}$/,NS=64,DW=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>LS.test(o)).slice(0,NS).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>LS.test(o)).slice(0,NS).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},di=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??wa)==="locked":!1},Ca=async(e,t={})=>{let n=t.loadProfile??P,r=t.saveProfile??ae,o=t.targetFromProfile??Be,a=t.adapters??le,s=t.repairTools??Bt,i=t.recordManaged??Kn,c=await n(),l={...c},d=PS(c,{routingOrigin:e.routing?.origin?Qt(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:u,teamUpdated:p,laneUpdated:f}=d;(u||p||f)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),d.authMode!=null&&(l.authMode=d.authMode),await r(l));let m=Ad(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||p||f),{candidateIds:h,freshIds:w}=m,y=0,g=0,b=0;if(h.length>0||w.length>0){let S=await o(async()=>l);if(S){let I;if(u||p||f){let N=new Set(h);I=[];for(let U of a)if(N.has(U.id))try{(await U.detect()).installed&&I.push(U)}catch{}}else I=await ga(h,S.target.origin,a);let E=new Set(w),R=[];for(let N of a)if(E.has(N.id))try{(await N.detect()).installed&&R.push(N)}catch{}if(y=I.length+R.length,y>0){let N=await s([...I,...R],S.target);g=N.filter(po).length;let U=N.filter(q=>E.has(q.id));if(b=U.filter(po).length,U.length>0)try{await i(U,!1)}catch{}}}}let k=DW(e),C=await n();if(JSON.stringify(k??null)!==JSON.stringify(C.fleetToolPolicy??null)){let{fleetToolPolicy:S,...I}=C;await r({...I,...k?{fleetToolPolicy:k}:{}})}return{routingUpdated:u,teamUpdated:p,laneUpdated:f,toolsRequested:y,toolsApplied:g,toolsEnrolled:b,toolsTombstoned:m.tombstonedIds,profileUpdated:u||p||f}},$S=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!PW(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=DS(d,i.id),p=DS(u,"SKILL.md");await IW(u,{recursive:!0}),await EW(p,LW(i.body),"utf-8"),l.push(p)}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}},LW=e=>e.endsWith(`
374
374
  `)?e:`${e}
375
- `;import{randomBytes as xW}from"node:crypto";var RW=1e4,OW="machine:",LS=e=>e.startsWith(OW),TW="cert-renew",_W=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)},NS=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Hn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:xW(16).toString("hex"),purpose:TW},c;try{c=await(n.signer??br)(lo(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),RW),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 f=(await u.json().catch(()=>null))?.cert;return _W(f)?{ok:!0,cert:f}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var ph=async(e,t=e.origin,n=le)=>{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}},fh=async(e,t=e.origin,n=le)=>(await ph(e,t,n)).complete;var PW=["claude","codex","cursor","opencode"],DW=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],LW=new Set(["missing_key","key_expired"]);var NW=600*1e3,$W=600*1e3,$S=1440*60*1e3,MW=1440*60*1e3,BW=10080*60*1e3,FW=3600*1e3,WW=720*60*1e3,HW=e=>Math.min(WW,FW*2**Math.max(0,e-1)),ui=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ka=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,MS=e=>typeof e=="string"&&DW.includes(e),An=e=>{if(!ui(e))return{};let t={};if(ka(e.watchSince)&&(t.watchSince=e.watchSince),ui(e.invoked)){let n={};for(let r of PW){let o=e.invoked[r];ka(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return ui(e.authFailure)&&ka(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...MS(e.authFailure.code)?{code:e.authFailure.code}:{}}),ui(e.repair)&&ka(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,...ka(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Ad=e=>{try{let n=JSON.parse(e);if(ui(n)&&MS(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"},mh=e=>e!==void 0&&LW.has(e),hh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=NW},BS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),yh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=$W},FS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),WS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,HS=(e,t,n)=>{if(n==="repair_failed"||n==="unverified")return{...e,repair:{at:t,outcome:n,failures:(e.repair?.failures??0)+1}};let{authFailure:r,...o}=e;return n==="repaired"?{...o,repair:{at:t,outcome:n}}:o},US=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>$S||!mh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<HW(r.failures??1))},Cd=e=>{let t=Object.values(e?.invoked??{}).filter(ka);return t.length>0?Math.max(...t):null},gh=(e,t)=>{if(Cd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=BW},GS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=MW)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=$S)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var wh="x-anyray-retrieve-probe",kd=8e3,UW=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",VS=(e,t)=>{let n=Vt(e);return t?.probe&&(n[wh]="1"),n},va=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(),kd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:VS(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=UW(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)}},vd=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(),kd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:VS(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 GW=5e3,VW=2048,KW=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}"`))},Sa=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??GW,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=Vt(o);i["content-type"]="application/json",i[wh]="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,VW);if(!KW(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let p=Ad(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...p?{code:p}:{}}}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)}},bh=(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{randomBytes as YW}from"node:crypto";import{execSync as Ah}from"node:child_process";import{hostname as jW}from"node:os";var ZW=e=>{try{if(e==="darwin"){let t=Ah("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=Ah('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 Ah("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Sd=(e={platform:process.platform,read:()=>ZW(process.platform),hostname:jW})=>e.read().trim()||e.hostname().trim();var Bt=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();if(t)return t.toLowerCase();if((e.platform??process.platform)==="darwin"){let r=e.readMacUuid??(()=>Sd());try{return r().trim().toLowerCase()}catch{return""}}return""};var JW=500,KS=2e3,XW=2e3,zW=250,jS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),JW);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)}},qW=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},QW=e=>new Promise(t=>setTimeout(t,e)),eH=async(e,t,n=QW)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),KS),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=qW(i)??zW,s>XW))return!1}finally{clearTimeout(a)}await n(s)}},tH=async(e,t={})=>{try{let r=(await(t.loadProfile??D)()).enrolledCert,o=await(t.loadDevKey??$e)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:YW(16).toString("hex"),events:e},i;try{i=await(t.signer??br)(lo(s),o)}catch{return!1}return await(t.post??eH)(`${t.origin??Hn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},nH=async(e,t,n={})=>{try{let o=(await(n.loadProfile??D)()).enrolledCert,a=await(n.loadDevKey??$e)();if(!o||!a)return;await(n.verify??Xt)(e,o,a,{timeoutMs:KS,machineUuid:(n.machineUuid??Bt)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},ZS=async(e,t)=>{if(e.length!==0)try{let n=await nt(),r=n&&await jS(n.origin,Vt(n),e,t);if(n&&await nH(n.origin,e),r)return;await tH(e)}catch{}},Ch=async(e,t,n={readTarget:()=>nt("profile"),post:jS})=>{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 ho=["hook_registration","mcp_registration","hook_binary","beacon_target"];var JS=128,XS=300*1e3,rH=["repaired","repair_failed","flapping","pending"],oH=["settings_not_writable","apply_unconfirmed","apply_threw"],zS=["rebroke_same_day","repeat_days"],qS=new Set(le.map(e=>e.id)),mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),QS=e=>fi(e,ho),Id=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},Cr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,pi=e=>{if(!(!Array.isArray(e)||!e.every(QS)))return Un(e)},aH=e=>{if(!mo(e))return;let t=pi(e.checks);if(!(!Cr(e.since)||!fi(e.reason,zS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},sH=e=>{if(!mo(e))return;let t={};Id(e.day)&&(t.day=e.day),Cr(e.attempts)&&(t.attempts=e.attempts);let n=pi(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=pi(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=pi(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=pi(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Id(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Cr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),mo(e.lastRepaired)){let i={};for(let c of ho){let l=e.lastRepaired[c];Cr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=aH(e.flapping);return s&&(t.flapping=s),t},iH=e=>{if(!mo(e)||!Id(e.day)||!Cr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!qS.has(e.tool)||!QS(e.checkId)||!fi(e.status,rH)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!fi(e.errorClass,oH))return;t=e.errorClass}else if(e.status==="flapping"){if(!fi(e.errorClass,zS))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,...Cr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},YS=e=>{if(!mo(e))return{};let t={};if(mo(e.adapters)){let n={};for(let r of qS){let o=sH(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(iH).filter(n=>n!==void 0).slice(-JS)),Cr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),mo(e.report)&&Id(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Cr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},cH=e=>new Date(e).toISOString().slice(0,10),lH=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Un=e=>[...new Set(e)],Ed=(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}:{}}},mi=(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(-JS),nextSequence:r}},dH=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),uH=async e=>await Be(async()=>e)??null,pH=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=Ed(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)},eI=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:lH(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:Un([...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:Un([...i?.checks??[],...t])}}:{}},slowFlap:a}},fH=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=Ed(d,n),p=u.awaiting??[],f=a.get(l);if(p.length===0||t.has(l)||!f){c[l]=u;continue}let m=p.filter(g=>f.checks[g]==="owned"),h=p.filter(g=>{let b=f.checks[g];return b==="missing"||b==="foreign"}),w=p.filter(g=>{let b=f.checks[g];return b===void 0||b==="unreadable"}),y=eI(u,m,n,r);c[l]={...y.adapter,awaiting:w.length>0?w:void 0},i=mi(i,n,[...m.map(g=>({tool:l,checkId:g,status:"repaired"})),...h.map(g=>({tool:l,checkId:g,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?m.map(g=>({tool:l,checkId:g,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},mH=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Ed(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],p=t.filter(y=>!d.includes(y)||u.includes(y)),f=p.filter(y=>u.includes(y)),m=l.attempts??0;if(m>=2||p.length===0&&!n){let y=f.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(y.length===0)return{result:void 0};let g=l.flapping;return c[e]={...l,brokenReportedChecks:Un([...l.brokenReportedChecks??[],...y]),flapping:{since:g?.since??a,reason:"rebroke_same_day",checks:Un([...g?.checks??[],...y])}},{next:mi({...i,adapters:c},o,y.map(k=>({tool:e,checkId:k,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let h=l.flapping;return c[e]={...l,attempts:m+1,attemptedChecks:Un([...d,...p]),confirmedChecks:u.filter(y=>!p.includes(y)),brokenReportedChecks:Un([...l.brokenReportedChecks??[],...f]),...f.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:Un([...h?.checks??[],...f])}}:{}},{next:mi({...i,adapters:c},o,f.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:p,fastFlaps:f}}},void 0),hH=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Ed(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:Un([...l.awaiting??[],...t])},{next:mi({...i,adapters:c},o,t.map(m=>({tool:e,checkId:m,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(m=>r[m]==="owned"):[],u=n.status==="configured"&&r?t.filter(m=>{let h=r[m];return h==="missing"||h==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],p=eI(l,d,o,a);c[e]=p.adapter;let f=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:mi({...i,adapters:c},o,[...d.map(m=>({tool:e,checkId:m,status:"repaired"})),...u.map(m=>({tool:e,checkId:m,status:"repair_failed",errorClass:f})),...p.slowFlap?d.map(m=>({tool:e,checkId:m,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},yH=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>=XS));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??Ch)(o.map(dH),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)},gH=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:p}of t){let f=r.adapters?.[u.id];for(let m of ho){let h=p[m];if(!h||h==="unreadable")continue;let w,y;f?.awaiting?.includes(m)&&c.has(u.id)?w="pending":h==="missing"&&f?.flapping?.checks.includes(m)?(w="flapping",y=f.flapping.reason):w=h==="owned"?"ok":h,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:m,status:w,...y?{errorClass:y}:{}})}}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??_o)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??ar)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=GS(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},wH=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<XS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await gH(e,t,n,c,o,s);await(s.report??Ch)(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)},tI=async(e,t,n)=>{let r=n.now??Date.now,o=cH(r()),a=e.managedTools??[],s={...n,readState:async()=>YS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(YS(l)),c)};try{let i=await(s.findIntegrations??lh)(a);await pH(i,o,s);let c=await(s.listPending??rr)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await fH(i,l,o,r(),s);let d=await(s.resolveTarget??uH)(e),u=d?await(s.findDrifted??ga)(a,d.target.origin):[],p=new Set(u.map(y=>y.id)),f=new Map(i.map(y=>[y.adapter.id,y]));for(let y of u)f.has(y.id)||f.set(y.id,{adapter:y,checks:{}});let m=!1,h=(s.runtimeDurable??ce)();if(d)for(let{adapter:y,checks:g}of f.values()){let b=h?ho.filter(P=>g[P]==="missing"):[];if(b.length===0&&!p.has(y.id))continue;let k=g;if(y.integrationStatus)try{k=await y.integrationStatus()}catch{k=Object.fromEntries(ho.map(P=>[P,"unreadable"]))}let C=b.filter(P=>k[P]==="missing"),S=p.has(y.id);if(S&&y.pointsAt&&(S=!await y.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!S)continue;let I=await mH(y.id,C,S,l.has(y.id),o,r(),s);if(!I)continue;let[E]=await(s.repair??Mt)([y],d.target);if(!E)continue;m=!0;let R;E.status==="configured"&&y.integrationStatus&&(R=await y.integrationStatus().catch(()=>{})),await hH(y.id,I.checks,E,R,o,r(),s)}await yH(o,r(),t,s),i=await(s.findIntegrations??lh)(a);let w=await(s.listPending??rr)().catch(()=>[]);return await wH(e,i,w,o,r(),t,s),m}catch{return!1}};var IH=14,EH=.35,xH=900*1e3,rI=360*60*1e3,RH=.2,OH=1800*1e3,oI=3600*1e3,TH=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),_H=300*1e3,PH=30*1e3,DH=900*1e3,LH=(e=0)=>Math.min(DH,PH*2**Math.max(0,e)),aI=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}},sI=1440*60*1e3,NH=300*1e3,$H=.25,MH=.5,iI=3600*1e3,BH=720*60*60*1e3,FH=360*60*1e3,WH=1440*60*1e3,HH=()=>pI(CH(),".anyray"),kh=()=>pI(HH(),"refresh-state.json"),vh=e=>process.env?.[e],mI=()=>vh("ANYRAY_REFRESH_DISABLE")==="true",Sh=()=>{let e=vh("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:IH)*WH},Rd=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},hI=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),UH=10080*60*1e3,yI=(e,t,n=Date.now())=>{let r=[],o=Rd(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)<=UH},Ih=e=>{let t=Sh(),n=e?Rd(e):void 0;if(!n)return t;let r=Math.max(xH,Math.round(n*EH));return Math.min(t,r)},GH=e=>{let t=vh("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(rI,Math.max(OH,Math.round(e*RH))):rI},It=async()=>{try{let e=await kH(kh(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Od=async e=>{try{let t=kh(),n=`${t}.${process.pid}.tmp`;await fI(n,JSON.stringify(e),{mode:384}),await he(n,t),await vH(t,384).catch(()=>{})}catch{}},VH=3e4,KH=()=>`${kh()}.lock`,cI=async e=>{try{return await fI(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},dt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??It,a=n.writeState??Od,s=KH(),i=!1;try{if(i=await cI(s),!i){if(await SH(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<VH)return t;await nI(s).catch(()=>{}),i=await cI(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await nI(s).catch(()=>{})}},xd=async(e,t={})=>{await dt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Ia=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);await dt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},yo=async(e={})=>{let t=e.now??Date.now;await dt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},jH=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(BH,Math.max(iI,Math.round(o*MH))):iI},gI=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Eh=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??oe,a=n.loadProfile??D,s=n.loadDevKey??$e,i=n.renew??NS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(LS(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()>jH(e))return{outcome:"not-due",profile:e};if(!await dt(w=>r()-(w.lastCertRenewAt??0)<FH?{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 p=await a().catch(()=>e);if(!p.enrolledCert)return{outcome:"failed",profile:e};if(!await gI(p,c.sig,t,s))return{outcome:"superseded",profile:p};let f=u.cert.payload.expiresAt,m=Date.parse(f)-r(),h={...p,enrolledCert:u.cert,enrolledCertExpiry:f,...Number.isFinite(m)&&m>0?{enrolledCertLifetimeMs:m}:{}};return await o(h),{outcome:"renewed",profile:h}},lI=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*$H):sI,r=Math.min(sI,n);return Math.min(r,NH*2**Math.max(0,e-1))},ZH=()=>{let{command:e,args:t}=Qn(Yn);return{exe:e,args:t}},kr=async(e={})=>{if(mI())return;let t=e.now??Date.now,n=e.readState??It,r=e.writeState??Od,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=ZH();AH(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await dt(s=>t()-(s.lastSpawnAt??0)<GH(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},YH=fh,JH=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Be(async()=>e);if(!r)return!1;let o=await ga(n,r.target.origin),a=t?RS(o):o;return a.length===0?!1:(await Mt(a,r.target),!0)}catch{return!1}},XH=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=le.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=xe({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:i,user:e.name,team:e.team}),l=await o(c,c.origin,s);return l.matched>0&&l.complete}catch{return!1}},zH=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??It,a=t.writeState??Od;return tI(e,Ae,{now:r,deadWatcherObserved:n,readHookLane:()=>Td({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>dt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Td=async(e={})=>{let n=await(e.readState??It)().catch(()=>({}));return An(n.hookLane)},wI=async(e,t={})=>{try{let n=t.now??Date.now,r=await Td(t);if(!hh(r,e,n()))return;await dt(o=>{let a=An(o.hookLane);return hh(a,e,n())?{next:{...o,hookLane:BS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},bI=async(e,t={})=>{try{let n=t.now??Date.now,r=await Td(t);if(!yh(r,n()))return;await dt(o=>{let a=An(o.hookLane);return yh(a,n())?{next:{...o,hookLane:FS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},qH=async(e={})=>{try{let t=e.now??Date.now;if((await Td(e)).watchSince!==void 0)return;await dt(n=>{let r=An(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:WS(r,t())},result:void 0}},void 0,e)}catch{}},dI=async(e,t={})=>{try{let n=t.now??Date.now;await dt(r=>{let o=An(r.hookLane),a=HS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},AI=async(e={})=>{try{if((await(e.readState??It)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>dt(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??D)(),s=await(e.findTools??fo)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Be(async()=>o);return!i||!await r()?"skipped":(await(e.repair??Mt)(s,i.target),"repathed")}catch{return"skipped"}},CI=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??It)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>dt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??D)(),i=await(e.findTools??fo)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Be(async()=>a);return!c||!await o()?"skipped":(await(e.repair??Mt)(i,c.target)).some(d=>d.status==="failed")?(await dt(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"}},QH=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await Aa(e.gateway,e.clientKey),n=await Ca(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},uI=async(e,t,n)=>{let o=await(t.reconcilePolicy??QH)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>JH(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},zt=async(e={})=>{if(mI())return"disabled";let t=e.now??Date.now,n=e.loadProfile??D,r=e.saveProfile??oe,o=e.loadDevKey??$e,a=e.readState??It,s=e.writeState??Od,i=e.remint??Xt,c=e.heartbeat??sS,l=e.detectSeat??fn,d=e.rewriteTools??YH,u=e.rewriteHookLaneTools??ph,p=e.probeHookLane??Sa,f=e.classifyBeacon??cc,m=e.force===!0,h=!1,w=!1,y=!1,g=!1;e.hookLaneRepair===!0&&(m=!0,g=!0);let b=async C=>{if(!g){C==="repaired"&&await dI("none",{now:t,readState:a,writeState:s});return}let S=C;if(C==="repaired"){let I=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));S=I.verdict==="live"?"repaired":I.verdict==="dark"?"repair_failed":"unverified"}await dI(S,{now:t,readState:a,writeState:s})},k=async()=>{if(!e.runAmbientSelfcheck||w||!h)return!1;w=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(I=>zH(I,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await rr().then(F=>F.some(Z=>!ar(Z.watcherPid))).catch(()=>!1),await qH({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??Qw)();let C=await n();if(h=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let S=C.gateway,I=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(I)||I<=t())return"cert-expired";let E=await o();if(!E)return"not-enrolled";let R=(e.resolveMachineUuid??Bt)()||void 0,P=await Eh(C,E,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=P.profile;let W=P.outcome==="renewed",q=C.enrolledCert;if(!q)return"not-enrolled";let de=Date.parse(C.clientKeyExpiresAt??""),ie=Number.isFinite(de)?de-t():0,K=await a(),ge=!C.clientKey||ie<=Ih(C);if(!m&&US(An(K.hookLane),t())&&await f().catch(()=>"unreadable")!=="foreign"&&(m=!0,g=!0),C.clientKey&&(m||ge)){let F=await dt(Z=>{let X=t()-(Z.lastAttemptAt??0);return X<oI?{result:"throttled"}:Z.failureCount&&X<lI(Z.failureCount,Z.keyTtlMs)?{result:"backoff"}:{next:{...Z,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(F!=="ok")return F;try{let Z=await c(S,C.clientKey,q,E,{machineUuid:R}),X=await n().catch(()=>C);return X.clientKey!==C.clientKey||X.enrolledCert?.sig!==q.sig?"failed":(await r({...X,clientKeyExpiresAt:Z.expiresAt}),await xd(({lastError:Je,...We})=>({...We,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Rd(C)??We.keyTtlMs}),{now:t,readState:a,writeState:s}),g?await b(await XH(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Z){let X=aI(Z);return await xd(Je=>({...Je,lastAttemptAt:t(),failureCount:(Je.failureCount??0)+1,lastError:{name:Z instanceof Error?Z.name:"Error",...X!==void 0?{code:X}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Z instanceof ma&&Z.policyCode==="managed_device_required"&&console.error(Z.message),Z instanceof ma?Z.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!m&&C.clientKey&&!ge){let F=await uI(C,e,n),Z=await k();return F||Z?"repaired":W?"cert-renewed":"not-due"}let me=await dt(F=>{let Z=t()-(F.lastAttemptAt??0);if(m)return Z<LH(F.failureCount)?{result:"throttled"}:{next:{...F,lastAttemptAt:t()},result:"ok"};let X=F.lastError?.code!==void 0&&TH.has(F.lastError.code)?_H:oI;return Z<X?{result:"throttled"}:F.failureCount&&Z<lI(F.failureCount,F.keyTtlMs)?{result:"backoff"}:{next:{...F,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(me!=="ok")return me;try{let F=await i(S,q,E,{machineUuid:R}),Z=await l().catch(()=>{}),X=xe({origin:S,clientKey:F.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Z,user:C.name,team:C.team});if(await d(X,X.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let We=await n().catch(()=>C),T=null;We.enrolledCert&&await gI(We,q.sig,E,o)&&(T={...We,clientKey:F.key,clientKeyExpiresAt:F.expiresAt??We.clientKeyExpiresAt},await r(T));let L=F.expiresAt?Date.parse(F.expiresAt):NaN,J=Rd(C)??(Number.isFinite(L)&&L-t()>0?L-t():void 0);return await xd(({lastError:pe,...ut})=>({...ut,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:J??ut.keyTtlMs}),{now:t,readState:a,writeState:s}),T&&await uI(T,e,n),await b(T?"repaired":"repair_failed"),await k(),"refreshed"}catch(F){let Z=aI(F);return await xd(X=>({...X,lastAttemptAt:t(),failureCount:(X.failureCount??0)+1,lastError:{name:F instanceof Error?F.name:"Error",...Z!==void 0?{code:Z}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),F instanceof lt&&F.policyCode==="managed_device_required"&&console.error(F.message),F instanceof lt?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var eU=`anyray-connect print-key [--json | --passthrough-headers]
375
+ `;import{randomBytes as NW}from"node:crypto";var $W=1e4,MW="machine:",MS=e=>e.startsWith(MW),BW="cert-renew",FW=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)},BS=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Hn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:NW(16).toString("hex"),purpose:BW},c;try{c=await(n.signer??Ar)(lo(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),$W),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 f=(await u.json().catch(()=>null))?.cert;return FW(f)?{ok:!0,cert:f}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var dh=async(e,t=e.origin,n=le)=>{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}},uh=async(e,t=e.origin,n=le)=>(await dh(e,t,n)).complete;var WW=["claude","codex","cursor","opencode"],UW=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],HW=new Set(["missing_key","key_expired"]);var GW=600*1e3,VW=600*1e3,FS=1440*60*1e3,KW=1440*60*1e3,jW=10080*60*1e3,ZW=3600*1e3,YW=720*60*1e3,JW=e=>Math.min(YW,ZW*2**Math.max(0,e-1)),ui=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ka=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,WS=e=>typeof e=="string"&&UW.includes(e),An=e=>{if(!ui(e))return{};let t={};if(ka(e.watchSince)&&(t.watchSince=e.watchSince),ui(e.invoked)){let n={};for(let r of WW){let o=e.invoked[r];ka(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return ui(e.authFailure)&&ka(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...WS(e.authFailure.code)?{code:e.authFailure.code}:{}}),ui(e.repair)&&ka(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,...ka(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Cd=e=>{try{let n=JSON.parse(e);if(ui(n)&&WS(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"},ph=e=>e!==void 0&&HW.has(e),fh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=GW},US=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),mh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=VW},HS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),GS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,VS=(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},KS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>FS||!ph(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<JW(r.failures??1))},kd=e=>{let t=Object.values(e?.invoked??{}).filter(ka);return t.length>0?Math.max(...t):null},hh=(e,t)=>{if(kd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=jW},jS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=KW)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=FS)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var yh="x-anyray-retrieve-probe",vd=8e3,XW=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",ZS=(e,t)=>{let n=Vt(e);return t?.probe&&(n[yh]="1"),n},va=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(),vd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:ZS(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=XW(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)}},Sd=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(),vd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:ZS(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 zW=5e3,qW=2048,QW=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}"`))},Sa=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??zW,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=Vt(o);i["content-type"]="application/json",i[yh]="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,qW);if(!QW(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let p=Cd(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...p?{code:p}:{}}}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)}},gh=(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{randomBytes as nU}from"node:crypto";import{execSync as wh}from"node:child_process";import{hostname as eU}from"node:os";var tU=e=>{try{if(e==="darwin"){let t=wh("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=wh('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 wh("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Id=(e={platform:process.platform,read:()=>tU(process.platform),hostname:eU})=>e.read().trim()||e.hostname().trim();var Ft=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();if(t)return t.toLowerCase();if((e.platform??process.platform)==="darwin"){let r=e.readMacUuid??(()=>Id());try{return r().trim().toLowerCase()}catch{return""}}return""};var rU=500,YS=2e3,oU=2e3,aU=250,JS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),rU);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)}},sU=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},iU=e=>new Promise(t=>setTimeout(t,e)),cU=async(e,t,n=iU)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),YS),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=sU(i)??aU,s>oU))return!1}finally{clearTimeout(a)}await n(s)}},lU=async(e,t={})=>{try{let r=(await(t.loadProfile??P)()).enrolledCert,o=await(t.loadDevKey??$e)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:nU(16).toString("hex"),events:e},i;try{i=await(t.signer??Ar)(lo(s),o)}catch{return!1}return await(t.post??cU)(`${t.origin??Hn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},dU=async(e,t,n={})=>{try{let o=(await(n.loadProfile??P)()).enrolledCert,a=await(n.loadDevKey??$e)();if(!o||!a)return;await(n.verify??Xt)(e,o,a,{timeoutMs:YS,machineUuid:(n.machineUuid??Ft)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},XS=async(e,t)=>{if(e.length!==0)try{let n=await nt(),r=n&&await JS(n.origin,Vt(n),e,t);if(n&&await dU(n.origin,e),r)return;await lU(e)}catch{}},bh=async(e,t,n={readTarget:()=>nt("profile"),post:JS})=>{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 ho=["hook_registration","mcp_registration","hook_binary","beacon_target"];var qS=128,QS=300*1e3,uU=["repaired","repair_failed","flapping","pending"],pU=["settings_not_writable","apply_unconfirmed","apply_threw"],eI=["rebroke_same_day","repeat_days"],tI=new Set(le.map(e=>e.id)),mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),nI=e=>fi(e,ho),Ed=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},kr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,pi=e=>{if(!(!Array.isArray(e)||!e.every(nI)))return Gn(e)},fU=e=>{if(!mo(e))return;let t=pi(e.checks);if(!(!kr(e.since)||!fi(e.reason,eI)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},mU=e=>{if(!mo(e))return;let t={};Ed(e.day)&&(t.day=e.day),kr(e.attempts)&&(t.attempts=e.attempts);let n=pi(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=pi(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=pi(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=pi(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Ed(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),kr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),mo(e.lastRepaired)){let i={};for(let c of ho){let l=e.lastRepaired[c];kr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=fU(e.flapping);return s&&(t.flapping=s),t},hU=e=>{if(!mo(e)||!Ed(e.day)||!kr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!tI.has(e.tool)||!nI(e.checkId)||!fi(e.status,uU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!fi(e.errorClass,pU))return;t=e.errorClass}else if(e.status==="flapping"){if(!fi(e.errorClass,eI))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,...kr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},zS=e=>{if(!mo(e))return{};let t={};if(mo(e.adapters)){let n={};for(let r of tI){let o=mU(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(hU).filter(n=>n!==void 0).slice(-qS)),kr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),mo(e.report)&&Ed(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...kr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},yU=e=>new Date(e).toISOString().slice(0,10),gU=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Gn=e=>[...new Set(e)],xd=(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}:{}}},mi=(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(-qS),nextSequence:r}},wU=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),bU=async e=>await Be(async()=>e)??null,AU=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=xd(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)},rI=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:gU(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:Gn([...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:Gn([...i?.checks??[],...t])}}:{}},slowFlap:a}},CU=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=xd(d,n),p=u.awaiting??[],f=a.get(l);if(p.length===0||t.has(l)||!f){c[l]=u;continue}let m=p.filter(g=>f.checks[g]==="owned"),h=p.filter(g=>{let b=f.checks[g];return b==="missing"||b==="foreign"}),w=p.filter(g=>{let b=f.checks[g];return b===void 0||b==="unreadable"}),y=rI(u,m,n,r);c[l]={...y.adapter,awaiting:w.length>0?w:void 0},i=mi(i,n,[...m.map(g=>({tool:l,checkId:g,status:"repaired"})),...h.map(g=>({tool:l,checkId:g,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?m.map(g=>({tool:l,checkId:g,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},kU=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=xd(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],p=t.filter(y=>!d.includes(y)||u.includes(y)),f=p.filter(y=>u.includes(y)),m=l.attempts??0;if(m>=2||p.length===0&&!n){let y=f.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(y.length===0)return{result:void 0};let g=l.flapping;return c[e]={...l,brokenReportedChecks:Gn([...l.brokenReportedChecks??[],...y]),flapping:{since:g?.since??a,reason:"rebroke_same_day",checks:Gn([...g?.checks??[],...y])}},{next:mi({...i,adapters:c},o,y.map(k=>({tool:e,checkId:k,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let h=l.flapping;return c[e]={...l,attempts:m+1,attemptedChecks:Gn([...d,...p]),confirmedChecks:u.filter(y=>!p.includes(y)),brokenReportedChecks:Gn([...l.brokenReportedChecks??[],...f]),...f.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:Gn([...h?.checks??[],...f])}}:{}},{next:mi({...i,adapters:c},o,f.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:p,fastFlaps:f}}},void 0),vU=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=xd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:Gn([...l.awaiting??[],...t])},{next:mi({...i,adapters:c},o,t.map(m=>({tool:e,checkId:m,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(m=>r[m]==="owned"):[],u=n.status==="configured"&&r?t.filter(m=>{let h=r[m];return h==="missing"||h==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],p=rI(l,d,o,a);c[e]=p.adapter;let f=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:mi({...i,adapters:c},o,[...d.map(m=>({tool:e,checkId:m,status:"repaired"})),...u.map(m=>({tool:e,checkId:m,status:"repair_failed",errorClass:f})),...p.slowFlap?d.map(m=>({tool:e,checkId:m,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},SU=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>=QS));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??bh)(o.map(wU),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)},IU=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:p}of t){let f=r.adapters?.[u.id];for(let m of ho){let h=p[m];if(!h||h==="unreadable")continue;let w,y;f?.awaiting?.includes(m)&&c.has(u.id)?w="pending":h==="missing"&&f?.flapping?.checks.includes(m)?(w="flapping",y=f.flapping.reason):w=h==="owned"?"ok":h,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:m,status:w,...y?{errorClass:y}:{}})}}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??_o)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??sr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=jS(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},EU=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<QS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await IU(e,t,n,c,o,s);await(s.report??bh)(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)},oI=async(e,t,n)=>{let r=n.now??Date.now,o=yU(r()),a=e.managedTools??[],s={...n,readState:async()=>zS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(zS(l)),c)};try{let i=await(s.findIntegrations??ih)(a);await AU(i,o,s);let c=await(s.listPending??or)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await CU(i,l,o,r(),s);let d=await(s.resolveTarget??bU)(e),u=d?await(s.findDrifted??ga)(a,d.target.origin):[],p=new Set(u.map(y=>y.id)),f=new Map(i.map(y=>[y.adapter.id,y]));for(let y of u)f.has(y.id)||f.set(y.id,{adapter:y,checks:{}});let m=!1,h=(s.runtimeDurable??te)();if(d)for(let{adapter:y,checks:g}of f.values()){let b=h?ho.filter(N=>g[N]==="missing"):[];if(b.length===0&&!p.has(y.id))continue;let k=g;if(y.integrationStatus)try{k=await y.integrationStatus()}catch{k=Object.fromEntries(ho.map(N=>[N,"unreadable"]))}let C=b.filter(N=>k[N]==="missing"),S=p.has(y.id);if(S&&y.pointsAt&&(S=!await y.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!S)continue;let I=await kU(y.id,C,S,l.has(y.id),o,r(),s);if(!I)continue;let[E]=await(s.repair??Bt)([y],d.target);if(!E)continue;m=!0;let R;E.status==="configured"&&y.integrationStatus&&(R=await y.integrationStatus().catch(()=>{})),await vU(y.id,I.checks,E,R,o,r(),s)}await SU(o,r(),t,s),i=await(s.findIntegrations??ih)(a);let w=await(s.listPending??or)().catch(()=>[]);return await EU(e,i,w,o,r(),t,s),m}catch{return!1}};var DU=14,LU=.35,NU=900*1e3,sI=360*60*1e3,$U=.2,MU=1800*1e3,iI=3600*1e3,BU=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),FU=300*1e3,WU=30*1e3,UU=900*1e3,HU=(e=0)=>Math.min(UU,WU*2**Math.max(0,e)),cI=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}},lI=1440*60*1e3,GU=300*1e3,VU=.25,KU=.5,dI=3600*1e3,jU=720*60*60*1e3,ZU=360*60*1e3,YU=1440*60*1e3,JU=()=>hI(OU(),".anyray"),Ah=()=>hI(JU(),"refresh-state.json"),Ch=e=>process.env?.[e],gI=()=>Ch("ANYRAY_REFRESH_DISABLE")==="true",kh=()=>{let e=Ch("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:DU)*YU},Od=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},wI=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),XU=10080*60*1e3,bI=(e,t,n=Date.now())=>{let r=[],o=Od(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)<=XU},vh=e=>{let t=kh(),n=e?Od(e):void 0;if(!n)return t;let r=Math.max(NU,Math.round(n*LU));return Math.min(t,r)},zU=e=>{let t=Ch("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(sI,Math.max(MU,Math.round(e*$U))):sI},It=async()=>{try{let e=await TU(Ah(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Td=async e=>{try{let t=Ah(),n=`${t}.${process.pid}.tmp`;await yI(n,JSON.stringify(e),{mode:384}),await he(n,t),await _U(t,384).catch(()=>{})}catch{}},qU=3e4,QU=()=>`${Ah()}.lock`,uI=async e=>{try{return await yI(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},dt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??It,a=n.writeState??Td,s=QU(),i=!1;try{if(i=await uI(s),!i){if(await PU(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<qU)return t;await aI(s).catch(()=>{}),i=await uI(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await aI(s).catch(()=>{})}},Rd=async(e,t={})=>{await dt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Ia=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);await dt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},yo=async(e={})=>{let t=e.now??Date.now;await dt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},eH=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(jU,Math.max(dI,Math.round(o*KU))):dI},AI=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Sh=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??ae,a=n.loadProfile??P,s=n.loadDevKey??$e,i=n.renew??BS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(MS(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()>eH(e))return{outcome:"not-due",profile:e};if(!await dt(w=>r()-(w.lastCertRenewAt??0)<ZU?{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 p=await a().catch(()=>e);if(!p.enrolledCert)return{outcome:"failed",profile:e};if(!await AI(p,c.sig,t,s))return{outcome:"superseded",profile:p};let f=u.cert.payload.expiresAt,m=Date.parse(f)-r(),h={...p,enrolledCert:u.cert,enrolledCertExpiry:f,...Number.isFinite(m)&&m>0?{enrolledCertLifetimeMs:m}:{}};return await o(h),{outcome:"renewed",profile:h}},pI=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*VU):lI,r=Math.min(lI,n);return Math.min(r,GU*2**Math.max(0,e-1))},tH=()=>{let{command:e,args:t}=er(Jn);return{exe:e,args:t}},vr=async(e={})=>{if(gI())return;let t=e.now??Date.now,n=e.readState??It,r=e.writeState??Td,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=tH();RU(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await dt(s=>t()-(s.lastSpawnAt??0)<zU(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},nH=uh,rH=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Be(async()=>e);if(!r)return!1;let o=await ga(n,r.target.origin),a=t?_S(o):o;return a.length===0?!1:(await Bt(a,r.target),!0)}catch{return!1}},oH=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=le.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=xe({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:i,user:e.name,team:e.team}),l=await o(c,c.origin,s);return l.matched>0&&l.complete}catch{return!1}},aH=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??It,a=t.writeState??Td;return oI(e,Ae,{now:r,deadWatcherObserved:n,readHookLane:()=>_d({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>dt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},_d=async(e={})=>{let n=await(e.readState??It)().catch(()=>({}));return An(n.hookLane)},CI=async(e,t={})=>{try{let n=t.now??Date.now,r=await _d(t);if(!fh(r,e,n()))return;await dt(o=>{let a=An(o.hookLane);return fh(a,e,n())?{next:{...o,hookLane:US(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},kI=async(e,t={})=>{try{let n=t.now??Date.now,r=await _d(t);if(!mh(r,n()))return;await dt(o=>{let a=An(o.hookLane);return mh(a,n())?{next:{...o,hookLane:HS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},sH=async(e={})=>{try{let t=e.now??Date.now;if((await _d(e)).watchSince!==void 0)return;await dt(n=>{let r=An(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:GS(r,t())},result:void 0}},void 0,e)}catch{}},fI=async(e,t={})=>{try{let n=t.now??Date.now;await dt(r=>{let o=An(r.hookLane),a=VS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},vI=async(e={})=>{try{if((await(e.readState??It)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>dt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??Ng)())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 Be(async()=>o);return!i||!await r()?"skipped":(await(e.repair??Bt)(s,i.target),"repathed")}catch{return"skipped"}},SI=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??It)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>dt(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 Be(async()=>a);return!c||!await o()?"skipped":(await(e.repair??Bt)(i,c.target)).some(d=>d.status==="failed")?(await dt(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"}},iH=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await Aa(e.gateway,e.clientKey),n=await Ca(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},mI=async(e,t,n)=>{let o=await(t.reconcilePolicy??iH)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>rH(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},zt=async(e={})=>{if(gI())return"disabled";let t=e.now??Date.now,n=e.loadProfile??P,r=e.saveProfile??ae,o=e.loadDevKey??$e,a=e.readState??It,s=e.writeState??Td,i=e.remint??Xt,c=e.heartbeat??lS,l=e.detectSeat??fn,d=e.rewriteTools??nH,u=e.rewriteHookLaneTools??dh,p=e.probeHookLane??Sa,f=e.classifyBeacon??cc,m=e.force===!0,h=!1,w=!1,y=!1,g=!1;e.hookLaneRepair===!0&&(m=!0,g=!0);let b=async C=>{if(!g){C==="repaired"&&await fI("none",{now:t,readState:a,writeState:s});return}let S=C;if(C==="repaired"){let I=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));S=I.verdict==="live"?"repaired":I.verdict==="dark"?"repair_failed":"unverified"}await fI(S,{now:t,readState:a,writeState:s})},k=async()=>{if(!e.runAmbientSelfcheck||w||!h)return!1;w=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(I=>aH(I,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await or().then(F=>F.some(Z=>!sr(Z.watcherPid))).catch(()=>!1),await sH({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??nb)();let C=await n();if(h=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let S=C.gateway,I=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(I)||I<=t())return"cert-expired";let E=await o();if(!E)return"not-enrolled";let R=(e.resolveMachineUuid??Ft)()||void 0,N=await Sh(C,E,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=N.profile;let U=N.outcome==="renewed",q=C.enrolledCert;if(!q)return"not-enrolled";let de=Date.parse(C.clientKeyExpiresAt??""),ce=Number.isFinite(de)?de-t():0,K=await a(),ge=!C.clientKey||ce<=vh(C);if(!m&&KS(An(K.hookLane),t())&&await f().catch(()=>"unreadable")!=="foreign"&&(m=!0,g=!0),C.clientKey&&(m||ge)){let F=await dt(Z=>{let X=t()-(Z.lastAttemptAt??0);return X<iI?{result:"throttled"}:Z.failureCount&&X<pI(Z.failureCount,Z.keyTtlMs)?{result:"backoff"}:{next:{...Z,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(F!=="ok")return F;try{let Z=await c(S,C.clientKey,q,E,{machineUuid:R}),X=await n().catch(()=>C);return X.clientKey!==C.clientKey||X.enrolledCert?.sig!==q.sig?"failed":(await r({...X,clientKeyExpiresAt:Z.expiresAt}),await Rd(({lastError:Je,...We})=>({...We,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Od(C)??We.keyTtlMs}),{now:t,readState:a,writeState:s}),g?await b(await oH(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Z){let X=cI(Z);return await Rd(Je=>({...Je,lastAttemptAt:t(),failureCount:(Je.failureCount??0)+1,lastError:{name:Z instanceof Error?Z.name:"Error",...X!==void 0?{code:X}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Z instanceof ma&&Z.policyCode==="managed_device_required"&&console.error(Z.message),Z instanceof ma?Z.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!m&&C.clientKey&&!ge){let F=await mI(C,e,n),Z=await k();return F||Z?"repaired":U?"cert-renewed":"not-due"}let me=await dt(F=>{let Z=t()-(F.lastAttemptAt??0);if(m)return Z<HU(F.failureCount)?{result:"throttled"}:{next:{...F,lastAttemptAt:t()},result:"ok"};let X=F.lastError?.code!==void 0&&BU.has(F.lastError.code)?FU:iI;return Z<X?{result:"throttled"}:F.failureCount&&Z<pI(F.failureCount,F.keyTtlMs)?{result:"backoff"}:{next:{...F,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(me!=="ok")return me;try{let F=await i(S,q,E,{machineUuid:R}),Z=await l().catch(()=>{}),X=xe({origin:S,clientKey:F.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Z,user:C.name,team:C.team});if(await d(X,X.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let We=await n().catch(()=>C),T=null;We.enrolledCert&&await AI(We,q.sig,E,o)&&(T={...We,clientKey:F.key,clientKeyExpiresAt:F.expiresAt??We.clientKeyExpiresAt},await r(T));let D=F.expiresAt?Date.parse(F.expiresAt):NaN,J=Od(C)??(Number.isFinite(D)&&D-t()>0?D-t():void 0);return await Rd(({lastError:pe,...ut})=>({...ut,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:J??ut.keyTtlMs}),{now:t,readState:a,writeState:s}),T&&await mI(T,e,n),await b(T?"repaired":"repair_failed"),await k(),"refreshed"}catch(F){let Z=cI(F);return await Rd(X=>({...X,lastAttemptAt:t(),failureCount:(X.failureCount??0)+1,lastError:{name:F instanceof Error?F.name:"Error",...Z!==void 0?{code:Z}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),F instanceof lt&&F.policyCode==="managed_device_required"&&console.error(F.message),F instanceof lt?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var cH=`anyray-connect print-key [--json | --passthrough-headers]
376
376
 
377
377
  Print the current short-lived Anyray client key for a consuming app.
378
378
 
@@ -384,10 +384,10 @@ Options:
384
384
  "x-anyray-provider":"anthropic","x-anyray-metadata":"..."}).
385
385
  Carries the client key, never the seat OAuth token.
386
386
  --help Show this help.
387
- `,tU=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}},nU=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Ih(e):!0},kI=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},vI=(e,t)=>{if(!Ee(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},xh=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,rU=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${xh(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 \`${xh(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"gateway-incompatible":return"The gateway key-renewal route is unavailable (HTTP 404). Check the deployment version and routing; your enrollment certificate was not rejected.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${xh(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"refreshed":return""}},hi=async(e={})=>{let t=e.loadProfile??D,n=e.refreshIfDue??zt,r=e.now??Date.now,o=await t();if(kI(o),!o.enrolledCert){if(!vI(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||nU(o,r)){let i=rU(await n(),o);if(i){if(!vI(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(kI(s),!Ee(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},SI=e=>ue({user:e.name,team:e.team}),_d=({profile:e,token:t})=>{let n={},r=SI(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Rh=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=SI(e);return r&&(n["x-anyray-metadata"]=r),n},oU=e=>JSON.stringify(Rh(e)),II=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=tU(e);if(o.help)return n.write(eU),0;let a=await hi(t);a.warning&&r.write(`${a.warning}
388
- `);let s=o.passthroughHeaders?oU(a):o.json?_d(a):a.token;return n.write(`${s}
387
+ `,lH=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}},dH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=vh(e):!0},II=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},EI=(e,t)=>{if(!Ee(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},Ih=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,uH=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Ih(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 \`${Ih(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"gateway-incompatible":return"The gateway key-renewal route is unavailable (HTTP 404). Check the deployment version and routing; your enrollment certificate was not rejected.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${Ih(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"refreshed":return""}},hi=async(e={})=>{let t=e.loadProfile??P,n=e.refreshIfDue??zt,r=e.now??Date.now,o=await t();if(II(o),!o.enrolledCert){if(!EI(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||dH(o,r)){let i=uH(await n(),o);if(i){if(!EI(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(II(s),!Ee(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},xI=e=>ue({user:e.name,team:e.team}),Pd=({profile:e,token:t})=>{let n={},r=xI(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Eh=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=xI(e);return r&&(n["x-anyray-metadata"]=r),n},pH=e=>JSON.stringify(Eh(e)),RI=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=lH(e);if(o.help)return n.write(cH),0;let a=await hi(t);a.warning&&r.write(`${a.warning}
388
+ `);let s=o.passthroughHeaders?pH(a):o.json?Pd(a):a.token;return n.write(`${s}
389
389
  `),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
390
- `),1}};var EI=`anyray-connect models [<model-id>] [--json]
390
+ `),1}};var OI=`anyray-connect models [<model-id>] [--json]
391
391
 
392
392
  List the Copilot models your seat can run on the Anyray lane, or switch the
393
393
  Copilot CLI's startup model. The CLI's own /models cannot list models on a
@@ -399,8 +399,8 @@ Options:
399
399
  --json Emit {"origin","current","models":[{"id","wire",...caps}]} instead
400
400
  of the table (listing only).
401
401
  --help Show this help.
402
- `,aU=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},sU=e=>{let t=le.find(n=>n.id===Xr);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},iU=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(" / ")},cU=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Ns(t)}/${On(n)==="responses"?"responses":"chat/completions"}`,xI=async(e=[],t={})=>{let n=aU(e);if(n.help)return process.stdout.write(EI),0;if(n.error)return O(n.error),process.stdout.write(EI),1;let r=await(t.loadTarget??Be)();if(!r)return O("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??dl)({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??Ko)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=wf(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 f=process.env.COPILOT_MODEL?.trim();if(n.json)return process.stdout.write(`${JSON.stringify({origin:o.origin,current:f??null,models:l.map(m=>({id:m.id,wire:On(m.id),...m.maxPromptTokens?{maxPromptTokens:m.maxPromptTokens}:{},...m.maxOutputTokens?{maxOutputTokens:m.maxOutputTokens}:{}}))})}
403
- `),0;A(V(`Copilot models your seat serves (via ${o.origin})`));for(let m of l){let h=m.id===f?"*":" ",w=iU(m);A(` ${h} ${m.id.padEnd(24)}${w?v(w):""}`)}return $("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),$("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(f=>f.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??ll)(cU(o,i,d.id),{...gf(),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"?_("Could not verify the model over the lane (offline?) \u2014 applying anyway."):M(`'${d.id}' answers on your lane.`);let p=process.env.ANYRAY_COPILOT_MODEL;process.env.ANYRAY_COPILOT_MODEL=d.id;try{let f=await(t.applyCopilotCli??sU)(o);if(f.status!=="configured"){for(let m of f.messages)A(m);return O("Apply did not complete \u2014 see above."),1}}finally{p===void 0?delete process.env.ANYRAY_COPILOT_MODEL:process.env.ANYRAY_COPILOT_MODEL=p}return M(`Copilot CLI startup model \u2192 ${d.id}`),$("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var lU=`anyray-connect copilot-login
402
+ `,fH=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},mH=e=>{let t=le.find(n=>n.id===Xr);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},hH=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(" / ")},yH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Ns(t)}/${Tn(n)==="responses"?"responses":"chat/completions"}`,TI=async(e=[],t={})=>{let n=fH(e);if(n.help)return process.stdout.write(OI),0;if(n.error)return O(n.error),process.stdout.write(OI),1;let r=await(t.loadTarget??Be)();if(!r)return O("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??ul)({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??Ko)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=yf(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 f=process.env.COPILOT_MODEL?.trim();if(n.json)return process.stdout.write(`${JSON.stringify({origin:o.origin,current:f??null,models:l.map(m=>({id:m.id,wire:Tn(m.id),...m.maxPromptTokens?{maxPromptTokens:m.maxPromptTokens}:{},...m.maxOutputTokens?{maxOutputTokens:m.maxOutputTokens}:{}}))})}
403
+ `),0;A(V(`Copilot models your seat serves (via ${o.origin})`));for(let m of l){let h=m.id===f?"*":" ",w=hH(m);A(` ${h} ${m.id.padEnd(24)}${w?v(w):""}`)}return $("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),$("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(f=>f.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??dl)(yH(o,i,d.id),{...hf(),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"?_("Could not verify the model over the lane (offline?) \u2014 applying anyway."):B(`'${d.id}' answers on your lane.`);let p=process.env.ANYRAY_COPILOT_MODEL;process.env.ANYRAY_COPILOT_MODEL=d.id;try{let f=await(t.applyCopilotCli??mH)(o);if(f.status!=="configured"){for(let m of f.messages)A(m);return O("Apply did not complete \u2014 see above."),1}}finally{p===void 0?delete process.env.ANYRAY_COPILOT_MODEL:process.env.ANYRAY_COPILOT_MODEL=p}return B(`Copilot CLI startup model \u2192 ${d.id}`),$("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var gH=`anyray-connect copilot-login
404
404
 
405
405
  Sign Anyray in to GitHub Copilot (device flow) so the Copilot CLI seat lane
406
406
  can run your plan's current models. Opens no browser for you: it prints a
@@ -408,23 +408,23 @@ code to type at github.com/login/device.
408
408
 
409
409
  Options:
410
410
  --help Show this help.
411
- `,RI=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(lU),0;A(V("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??MA)();if(!n)return O("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;A(` 1. Open ${et(n.verificationUri)}`),A(` 2. Enter the code: ${V(n.userCode)}`),$(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??BA)(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??FA)(r.token,o);M(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??df)(r.token);if(s.verdict==="no-copilot")return O("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??Be)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??Ko)(r.token,{},s.capiSegment,c);return l.length===0?_("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."):M(`${l.length} models available (e.g. ${l[0].id}).`),$("Now run: anyray-connect --tools copilot-cli"),0};import{randomBytes as dU}from"node:crypto";import{chmod as uU,readFile as pU,rm as TI,writeFile as fU}from"node:fs/promises";import{join as mU}from"node:path";var hU=/^[A-Za-z0-9_-]{43}$/,OI=3900,yU=1e4,Oh=()=>mU(Q(),"device-token.json"),gU=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&hU.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},_I=async()=>{try{let e=JSON.parse(await pU(Oh(),"utf-8"));return gU(e)?e:null}catch{return null}},wU=0,bU=async e=>{await tt();let t=Oh(),n=`${t}.${process.pid}.${wU++}.tmp`;try{await fU(n,`${JSON.stringify(e)}
412
- `,{mode:384}),await uU(n,384),await he(n,t)}catch(r){throw await TI(n,{force:!0}).catch(()=>{}),r}},Pd=async()=>{await TI(Oh(),{force:!0}).catch(()=>{})},AU=()=>dU(32).toString("base64url"),CU=e=>e instanceof Error?e.name:"UnknownError",PI=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??D)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=AU(),i=new AbortController,c=setTimeout(()=>i.abort(),yU),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:OI}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await bU({v:1,token:s,expiresAt:t()+OI*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${CU(r)}`),!1}};var DI=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??D)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=e.readState??_I,i=await s();return(!i||i.expiresAt<=r())&&(await(e.rotateToken??PI)(),i=await s()),!i||i.expiresAt<=r()?(n.write(`Could not register a device token \u2014 retry after checking gateway connectivity.
411
+ `,_I=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(gH),0;A(V("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??WA)();if(!n)return O("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;A(` 1. Open ${et(n.verificationUri)}`),A(` 2. Enter the code: ${V(n.userCode)}`),$(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??UA)(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??HA)(r.token,o);B(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??cf)(r.token);if(s.verdict==="no-copilot")return O("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??Be)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??Ko)(r.token,{},s.capiSegment,c);return l.length===0?_("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."):B(`${l.length} models available (e.g. ${l[0].id}).`),$("Now run: anyray-connect --tools copilot-cli"),0};import{randomBytes as wH}from"node:crypto";import{chmod as bH,readFile as AH,rm as DI,writeFile as CH}from"node:fs/promises";import{join as kH}from"node:path";var vH=/^[A-Za-z0-9_-]{43}$/,PI=3900,SH=1e4,xh=()=>kH(Q(),"device-token.json"),IH=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&vH.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},LI=async()=>{try{let e=JSON.parse(await AH(xh(),"utf-8"));return IH(e)?e:null}catch{return null}},EH=0,xH=async e=>{await tt();let t=xh(),n=`${t}.${process.pid}.${EH++}.tmp`;try{await CH(n,`${JSON.stringify(e)}
412
+ `,{mode:384}),await bH(n,384),await he(n,t)}catch(r){throw await DI(n,{force:!0}).catch(()=>{}),r}},Dd=async()=>{await DI(xh(),{force:!0}).catch(()=>{})},RH=()=>wH(32).toString("base64url"),OH=e=>e instanceof Error?e.name:"UnknownError",NI=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=RH(),i=new AbortController,c=setTimeout(()=>i.abort(),SH),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:PI}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await xH({v:1,token:s,expiresAt:t()+PI*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${OH(r)}`),!1}};var $I=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=e.readState??LI,i=await s();return(!i||i.expiresAt<=r())&&(await(e.rotateToken??NI)(),i=await s()),!i||i.expiresAt<=r()?(n.write(`Could not register a device token \u2014 retry after checking gateway connectivity.
413
413
  `),1):(t.write(`${a}/device?dt=${i.token}
414
- `),0)};import{join as UI,dirname as PU}from"node:path";import{mkdir as DU,readFile as Nh,rm as GI,writeFile as VI}from"node:fs/promises";import{fstatSync as IU,openSync as EU,statSync as xU}from"node:fs";import{createInterface as RU}from"node:readline/promises";import{ReadStream as OU}from"node:tty";import{execFileSync as LI}from"node:child_process";import kU from"node:os";var Th=e=>{try{return LI("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},vU=e=>{try{return LI("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},SU=new Set(["root","unknown","user","admin","administrator","developer","dev","node","ubuntu","debian","ec2-user","vagrant","docker","container","vscode","codespace","devcontainer","runner","builder","jenkins","build","ci"]),_h=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:SU.has(t):!0},Dd=()=>{try{return kU.userInfo().username||void 0}catch{return}},NI=()=>Th("user.name")??Th("user.email")??Dd()??"unknown",$I=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Th),global:e.globalGitConfig??(t||vU)}},go=e=>{try{return e()?.trim()||void 0}catch{return}},Ph=(e={})=>{let t=$I(e),n=go(e.osUsername??Dd),r=go(()=>t.global("user.email"))??go(()=>t.local("user.email"));return r||(go(()=>t.global("user.name"))??go(()=>t.local("user.name"))??n??"unknown")},MI=(e={})=>{let t=Ph(e);if(_h(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=$I(e);return!!(go(()=>n.global("user.email"))??go(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var Ft=()=>!!process.stdin.isTTY,TU=()=>{try{let e=IU(0);return e.isCharacterDevice()&&e.rdev===xU("/dev/tty").rdev}catch{return!1}},Dh=()=>{if(TU()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new OU(EU(`/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"}},BI=async(e,t)=>{let n=t.input??Dh(),r=t.output??process.stdout,o=RU({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()}},Ea=async(e,t={})=>{let n=(await BI(`${e} ${v("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},xa=async(e,t,n={})=>{let r=t?` ${v(`[${t}]`)}`:"";return(await BI(`${e}${r}: `,n)).trim()||t},FI=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return $(`Your name: ${t} ${v("(cached \u2014 pass --user to change)")}`),t;let r=NI();return n||!Ft()?($(`Your name: ${r} ${v("(auto-detected \u2014 pass --user to change)")}`),r):xa("? Your name",r)},WI=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return $(`Team: ${t} ${v("(cached \u2014 pass --team to change)")}`),t;if(!(n||!Ft()))return xa("? Team (optional)")},vr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return Qt(e??n)},HI=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,Ra="claude-desktop",Ld=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await gr(e.runReg??Bn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Nt({home:e.home});return await x(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=jt(r);return await to(o,r)?n("managed-policy"):(await da({home:e.home,readClaudeAppVersion:e.readClaudeAppVersion,readClaudeAppBundle:e.readClaudeAppBundle})).supported?await x(o.journal)?{authoritative:!0}:n("no-local-record"):n("unverified-build")}catch{return n("no-local-record")}},Nd=e=>e.id!==Ra||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",_U={"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"},$d=(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=_U[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 Lh=["claude-code","codex"],LU="anyray-connect print-key",$h=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),NU=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:ja,authMode:"placeholder",metadata:{}}),Mh=e=>UI(e,".claude","settings.json"),$U=async(e,t,n)=>{let r=Mh(e),o=await B(r),{env:a}=tn(t,{includeAuthToken:!1,includeClientKey:!1}),s=$h(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Br(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=LU,n||await Y(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]}},KI=async(e=process.cwd())=>{let t=[],n=Mh(e);try{if(await x(n)){let o=await B(n),a=$h(o.env)?o.env:{};($r.some(s=>s in a)||Br(o))&&t.push(n)}}catch{}let r=Bh(e);try{if(await x(r)){let o=await Nh(r,"utf-8");mp(o)&&t.push(r)}}catch{}return t},MU=async(e,t)=>{let n=Mh(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await B(n),o=!1;if($h(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(Br(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 GI(n,{force:!0}):await Y(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},Bh=e=>UI(e,".codex","config.toml"),BU=async(e,t,n)=>{let r=Bh(e),o=await Nh(r,"utf-8").catch(()=>""),a=xc(o,us(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await DU(PU(r),{recursive:!0}),await VI(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]}},FU=async(e,t)=>{let n=Bh(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Nh(n,"utf-8"),o=Rc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await GI(n,{force:!0}):await VI(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},jI=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Lh],r=n.filter(s=>!Lh.includes(s));if(r.length>0)return O(`--project supports ${Lh.join(", ")} \u2014 not: ${r.join(", ")}. Other tools keep per-machine state (run anyray-connect without --project there).`),1;let o;if(!e.revert){let s=await D(),i=e.gateway??s.gateway;if(!i)return 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=NU(Ht(i))}if(A(V(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),U("Project"),A(` Directory: ${t}`),o&&A(` Gateway: ${o.origin}`),A(` Tools: ${n.join(", ")}`),e.revert||(_(`
415
- A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),$(" 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(!Ft())return O(`
414
+ `),0)};import{join as KI,dirname as WH}from"node:path";import{mkdir as UH,readFile as Dh,rm as jI,writeFile as ZI}from"node:fs/promises";import{fstatSync as DH,openSync as LH,statSync as NH}from"node:fs";import{createInterface as $H}from"node:readline/promises";import{ReadStream as MH}from"node:tty";import{execFileSync as MI}from"node:child_process";import TH from"node:os";var Rh=e=>{try{return MI("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},_H=e=>{try{return MI("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},PH=new Set(["root","unknown","user","admin","administrator","developer","dev","node","ubuntu","debian","ec2-user","vagrant","docker","container","vscode","codespace","devcontainer","runner","builder","jenkins","build","ci"]),Oh=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:PH.has(t):!0},Ld=()=>{try{return TH.userInfo().username||void 0}catch{return}},BI=()=>Rh("user.name")??Rh("user.email")??Ld()??"unknown",FI=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Rh),global:e.globalGitConfig??(t||_H)}},go=e=>{try{return e()?.trim()||void 0}catch{return}},Th=(e={})=>{let t=FI(e),n=go(e.osUsername??Ld),r=go(()=>t.global("user.email"))??go(()=>t.local("user.email"));return r||(go(()=>t.global("user.name"))??go(()=>t.local("user.name"))??n??"unknown")},WI=(e={})=>{let t=Th(e);if(Oh(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=FI(e);return!!(go(()=>n.global("user.email"))??go(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var Wt=()=>!!process.stdin.isTTY,BH=()=>{try{let e=DH(0);return e.isCharacterDevice()&&e.rdev===NH("/dev/tty").rdev}catch{return!1}},_h=()=>{if(BH()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new MH(LH(`/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"}},UI=async(e,t)=>{let n=t.input??_h(),r=t.output??process.stdout,o=$H({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()}},Ea=async(e,t={})=>{let n=(await UI(`${e} ${v("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},xa=async(e,t,n={})=>{let r=t?` ${v(`[${t}]`)}`:"";return(await UI(`${e}${r}: `,n)).trim()||t},HI=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return $(`Your name: ${t} ${v("(cached \u2014 pass --user to change)")}`),t;let r=BI();return n||!Wt()?($(`Your name: ${r} ${v("(auto-detected \u2014 pass --user to change)")}`),r):xa("? Your name",r)},GI=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return $(`Team: ${t} ${v("(cached \u2014 pass --team to change)")}`),t;if(!(n||!Wt()))return xa("? Team (optional)")},Sr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return Qt(e??n)},VI=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,Ra="claude-desktop",Nd=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await wr(e.runReg??Fn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=$t({home:e.home});return await x(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=jt(r);return await to(o,r)?n("managed-policy"):(await da({home:e.home,readClaudeAppVersion:e.readClaudeAppVersion,readClaudeAppBundle:e.readClaudeAppBundle})).supported?await x(o.journal)?{authoritative:!0}:n("no-local-record"):n("unverified-build")}catch{return n("no-local-record")}},$d=e=>e.id!==Ra||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",FH={"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"},Md=(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=FH[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 Ph=["claude-code","codex"],HH="anyray-connect print-key",Lh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),GH=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:ja,authMode:"placeholder",metadata:{}}),Nh=e=>KI(e,".claude","settings.json"),VH=async(e,t,n)=>{let r=Nh(e),o=await M(r),{env:a}=tn(t,{includeAuthToken:!1,includeClientKey:!1}),s=Lh(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Br(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=HH,n||await Y(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]}},YI=async(e=process.cwd())=>{let t=[],n=Nh(e);try{if(await x(n)){let o=await M(n),a=Lh(o.env)?o.env:{};(Mr.some(s=>s in a)||Br(o))&&t.push(n)}}catch{}let r=$h(e);try{if(await x(r)){let o=await Dh(r,"utf-8");fp(o)&&t.push(r)}}catch{}return t},KH=async(e,t)=>{let n=Nh(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await M(n),o=!1;if(Lh(r.env)){let s={...r.env};for(let i of Mr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Br(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 jI(n,{force:!0}):await Y(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},$h=e=>KI(e,".codex","config.toml"),jH=async(e,t,n)=>{let r=$h(e),o=await Dh(r,"utf-8").catch(()=>""),a=xc(o,us(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await UH(WH(r),{recursive:!0}),await ZI(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]}},ZH=async(e,t)=>{let n=$h(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Dh(n,"utf-8"),o=Rc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await jI(n,{force:!0}):await ZI(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},JI=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Ph],r=n.filter(s=>!Ph.includes(s));if(r.length>0)return O(`--project supports ${Ph.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=GH(Ht(i))}if(A(V(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),H("Project"),A(` Directory: ${t}`),o&&A(` Gateway: ${o.origin}`),A(` Tools: ${n.join(", ")}`),e.revert||(_(`
415
+ A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),$(" 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(!Wt())return O(`
416
416
  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 Ea(`
417
417
  ${s} ${n.length} tool(s)?`))return $("Aborted. Nothing changed."),0}e.dryRun&&$(`
418
- Dry run \u2014 no files will be written.`);let a=[];for(let s of n){U(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await $U(t,o,e.dryRun):await BU(t,o,e.dryRun):s==="claude-code"?await MU(t,e.dryRun):await FU(t,e.dryRun);for(let c of i.messages)A(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(U("Next"),e.revert)M(" Project config removed. Commit the change to propagate it.");else{M(" Commit these files to route every checkout of this repo:");for(let s of a)A(` ${s}`);A(v(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as WU}from"node:child_process";var HU="/usr/bin/security",UU=["find-generic-password","-s","Claude Code-credentials","-w"],GU=1e4,VU=64*1024,KU=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,Fh="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",jU=(e,t,n)=>new Promise((r,o)=>{WU(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),ZI=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ZU=e=>{let t=JSON.parse(e);if(!ZI(t)||!ZI(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!KU.test(n))throw new Error("unexpected keychain access token");return n},YU=async(e,t)=>{let n=Rh(e),r=await(t.execSecurity??jU)(HU,[...UU],{encoding:"utf8",timeout:GU,maxBuffer:VU,shell:!1});return JSON.stringify({token:ZU(r.stdout),headers:n})},YI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${Fh}
419
- `),1;let o;try{o=await hi(t)}catch(i){let c=i instanceof Error&&i.message?i.message:Fh;return r.write(`${c}
420
- `),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=_d(o);else try{s=await YU(o,t)}catch{if(a==="subscription")return r.write(`${Fh}
421
- `),1;s=_d(o)}return o.warning&&r.write(`${o.warning}
418
+ Dry run \u2014 no files will be written.`);let a=[];for(let s of n){H(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await VH(t,o,e.dryRun):await jH(t,o,e.dryRun):s==="claude-code"?await KH(t,e.dryRun):await ZH(t,e.dryRun);for(let c of i.messages)A(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(H("Next"),e.revert)B(" Project config removed. Commit the change to propagate it.");else{B(" Commit these files to route every checkout of this repo:");for(let s of a)A(` ${s}`);A(v(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as YH}from"node:child_process";var JH="/usr/bin/security",XH=["find-generic-password","-s","Claude Code-credentials","-w"],zH=1e4,qH=64*1024,QH=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,Mh="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",eG=(e,t,n)=>new Promise((r,o)=>{YH(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),XI=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),tG=e=>{let t=JSON.parse(e);if(!XI(t)||!XI(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!QH.test(n))throw new Error("unexpected keychain access token");return n},nG=async(e,t)=>{let n=Eh(e),r=await(t.execSecurity??eG)(JH,[...XH],{encoding:"utf8",timeout:zH,maxBuffer:qH,shell:!1});return JSON.stringify({token:tG(r.stdout),headers:n})},zI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${Mh}
419
+ `),1;let o;try{o=await hi(t)}catch(i){let c=i instanceof Error&&i.message?i.message:Mh;return r.write(`${c}
420
+ `),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=Pd(o);else try{s=await nG(o,t)}catch{if(a==="subscription")return r.write(`${Mh}
421
+ `),1;s=Pd(o)}return o.warning&&r.write(`${o.warning}
422
422
  `),n.write(`${s}
423
- `),0};var JI="Anyray: could not resolve the Anyray client key for the Claude Desktop bootstrap fetch. Run `anyray-connect` and try again.",XI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${JI}
423
+ `),0};var qI="Anyray: could not resolve the Anyray client key for the Claude Desktop bootstrap fetch. Run `anyray-connect` and try again.",QI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${qI}
424
424
  `),1;try{let o=await hi(t);return o.warning&&r.write(`${o.warning}
425
425
  `),n.write(`${JSON.stringify({Authorization:`Bearer ${o.token}`})}
426
- `),0}catch{return r.write(`${JI}
427
- `),1}};import{mkdir as bG,writeFile as AG}from"node:fs/promises";import{dirname as CG}from"node:path";import{Buffer as kG}from"node:buffer";import{constants as zI}from"node:fs";import{access as JU,chmod as XU,lstat as zU,mkdir as qU,open as QU,readFile as eG,realpath as tG,rm as nG,stat as QI,writeFile as rG}from"node:fs/promises";import{randomUUID as oG}from"node:crypto";import{platform as Hh}from"node:os";import{dirname as aG,join as sG,posix as iG,win32 as eE}from"node:path";var wi="/usr/local/bin/anyray-credential-helper",bi="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Md="/usr/local/bin/anyray-bootstrap-headers-helper",Bd="C:\\Program Files\\Anyray\\anyray-bootstrap-headers-helper.cmd",gi="Managed by anyray-connect desktop helper; do not edit.",Fd="__anyray-refresh-desktop-helpers",cG=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
426
+ `),0}catch{return r.write(`${qI}
427
+ `),1}};import{mkdir as xG,writeFile as RG}from"node:fs/promises";import{dirname as OG}from"node:path";import{Buffer as TG}from"node:buffer";import{constants as eE}from"node:fs";import{access as rG,chmod as oG,lstat as aG,mkdir as sG,open as iG,readFile as cG,realpath as lG,rm as dG,stat as nE,writeFile as uG}from"node:fs/promises";import{randomUUID as pG}from"node:crypto";import{platform as Fh}from"node:os";import{dirname as fG,join as mG,posix as hG,win32 as rE}from"node:path";var wi="/usr/local/bin/anyray-credential-helper",bi="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Bd="/usr/local/bin/anyray-bootstrap-headers-helper",Fd="C:\\Program Files\\Anyray\\anyray-bootstrap-headers-helper.cmd",gi="Managed by anyray-connect desktop helper; do not edit.",Wd="__anyray-refresh-desktop-helpers",yG=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
428
428
 
429
429
  Create the helpers required by Claude Desktop and Codex fleet artifacts: the
430
430
  credential helper (inferenceCredentialHelper, also used by Codex) and the
@@ -449,8 +449,8 @@ Options:
449
449
  ${bi}
450
450
  --bootstrap-headers-path <absolute>
451
451
  Bootstrap-headers helper destination. Defaults:
452
- ${Md}
453
452
  ${Bd}
453
+ ${Fd}
454
454
  --help,-h Show this help.
455
455
 
456
456
  Examples:
@@ -466,15 +466,15 @@ Examples:
466
466
  anyray-connect desktop helper --print --wrapper bootstrap-headers \\
467
467
  --platform posix --bin /usr/local/bin/anyray-connect \\
468
468
  > anyray-bootstrap-headers-helper
469
- `,Wh=(e=Hh())=>e==="win32"?"windows":"posix",tE=e=>e==="windows"?bi:wi,nE=e=>e==="windows"?Bd:Md,qI=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},lG=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":qI(t,"write");break;case"--print":qI(t,"print");break;case"--bin":t.binaryPath=o();break;case"--path":t.helperPath=o();break;case"--bootstrap-headers-path":t.bootstrapHeadersHelperPath=o();break;case"--wrapper":{let a=o();if(a!=="credential"&&a!=="bootstrap-headers")throw new Error("--wrapper must be credential or bootstrap-headers");t.wrapper=a;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},dG=e=>/[\0\r\n]/.test(e),uG=e=>/^[A-Za-z]:[\\/]/.test(e)&&eE.isAbsolute(e),Ai=(e,t)=>!dG(e)&&(t==="windows"?uG(e):iG.isAbsolute(e)),yi=e=>e.replace(/\\/g,"/").toLowerCase(),Wd=(e,t)=>{if(!Ai(e,t))return!1;let n=yi(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)))},Ci=(e,t)=>t==="windows"?eE.normalize(e):e,Uh=e=>`'${e.replace(/'/g,`'"'"'`)}'`,rE=(e,t)=>{if(!Wd(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Ci(t,e);if(e==="windows")return["@echo off",`REM ${gi}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" ${hr}`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
470
- `);let r=Uh(n);return["#!/bin/sh",`# ${gi}`,'if [ "$#" -eq 0 ]; then',` exec ${r} ${hr}`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
471
- `)},oE=(e,t)=>{if(!Wd(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Ci(t,e);return e==="windows"?["@echo off",`REM ${gi}`,'if not "%~1"=="" exit /b 64',`"${n}" ${Vs}`,"exit /b %ERRORLEVEL%",""].join(`\r
472
- `):["#!/bin/sh",`# ${gi}`,'if [ "$#" -eq 0 ]; then',` exec ${Uh(n)} ${Vs}`,"fi","exit 64",""].join(`
473
- `)},Hd=(e,t)=>{if(!Ai(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Ci(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"]}},aE=async e=>{try{return await eG(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},pG=async(e,t)=>{try{let n=await tG(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!Wd(r,t))throw new Error;if(!(await QI(n)).isFile())throw new Error;await JU(n,t==="posix"?zI.X_OK:zI.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},sE=e=>e.slice(0,300).includes(gi),iE=async(e,t,n)=>{let r=await aE(e);if(r!==void 0&&r!==t&&!sE(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 QI(e)).mode&511)===493)return"unchanged"}catch{}}let o=aG(e);try{await qU(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=sG(o,`.anyray-helper.${process.pid}.${oG()}.tmp`),s=!1;try{await rG(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await XU(a,493);let i=await QU(a,"r");try{await _r(i)}finally{await i.close()}await he(a,e),s=!0}catch{throw new Error(`could not install helper at ${e}`)}finally{s||await nG(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},fG=(e,t,n)=>{let r=n==="windows"?`"${Ci(t,n)}" `:` exec ${Uh(t)} `;return e.split(/\r?\n/).some(o=>o.startsWith(r)&&o.length>r.length)},Ud=async(e,t={})=>{let n=Wh((t.platform??Hh)());if(!Wd(e,n))return;let r=[{path:t.helperPath??tE(n),content:rE(n,e)},{path:t.bootstrapHeadersHelperPath??nE(n),content:oE(n,e)}];for(let o of r)try{if((await zU(o.path).catch(()=>{}))?.isSymbolicLink())continue;let a=await aE(o.path);if(a===void 0||a===o.content||!sE(a)||!fG(a,e,n))continue;await iE(o.path,o.content,n)}catch{}},cE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=lG(e);if(o.help)return n.write(cG),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");if(o.wrapper&&o.mode!=="print")throw new Error("--wrapper applies to --print only; --write installs both helpers");let a=(t.platform??Hh)(),s=o.targetPlatform??Wh(a),i=o.binaryPath,c=(d,u,p)=>{let f=Ci(u??p,s);if(!Ai(f,s))throw new Error(`${d} must be an absolute ${s} path`);if(s==="windows"&&Hd("windows",f),yi(f)===yi(i))throw new Error(`${d} must differ from --bin (the helper cannot invoke itself)`);return f},l=[{kind:"credential",label:"credential helper",path:c("--path",o.helperPath,tE(s)),content:rE(s,i)},{kind:"bootstrap-headers",label:"bootstrap-headers helper",path:c("--bootstrap-headers-path",o.bootstrapHeadersHelperPath,nE(s)),content:oE(s,i)}];if(yi(l[0].path)===yi(l[1].path))throw new Error("--path and --bootstrap-headers-path must differ");if(o.mode==="print"){let d=o.wrapper??"credential",u=l.find(p=>p.kind===d);return n.write(u.content),r.write(`Deploy this wrapper at ${u.path} after deploying the binary at ${i}.
474
- `),0}if(s!==Wh(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await pG(i,s);for(let d of l){let u=await iE(d.path,d.content,s),p=d.label[0].toUpperCase()+d.label.slice(1);r.write(u==="unchanged"?`${p} already current at ${d.path}.
469
+ `,Bh=(e=Fh())=>e==="win32"?"windows":"posix",oE=e=>e==="windows"?bi:wi,aE=e=>e==="windows"?Fd:Bd,tE=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},gG=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":tE(t,"write");break;case"--print":tE(t,"print");break;case"--bin":t.binaryPath=o();break;case"--path":t.helperPath=o();break;case"--bootstrap-headers-path":t.bootstrapHeadersHelperPath=o();break;case"--wrapper":{let a=o();if(a!=="credential"&&a!=="bootstrap-headers")throw new Error("--wrapper must be credential or bootstrap-headers");t.wrapper=a;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},wG=e=>/[\0\r\n]/.test(e),bG=e=>/^[A-Za-z]:[\\/]/.test(e)&&rE.isAbsolute(e),Ai=(e,t)=>!wG(e)&&(t==="windows"?bG(e):hG.isAbsolute(e)),yi=e=>e.replace(/\\/g,"/").toLowerCase(),Ud=(e,t)=>{if(!Ai(e,t))return!1;let n=yi(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)))},Ci=(e,t)=>t==="windows"?rE.normalize(e):e,Wh=e=>`'${e.replace(/'/g,`'"'"'`)}'`,sE=(e,t)=>{if(!Ud(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Ci(t,e);if(e==="windows")return["@echo off",`REM ${gi}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" ${yr}`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
470
+ `);let r=Wh(n);return["#!/bin/sh",`# ${gi}`,'if [ "$#" -eq 0 ]; then',` exec ${r} ${yr}`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
471
+ `)},iE=(e,t)=>{if(!Ud(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Ci(t,e);return e==="windows"?["@echo off",`REM ${gi}`,'if not "%~1"=="" exit /b 64',`"${n}" ${Vs}`,"exit /b %ERRORLEVEL%",""].join(`\r
472
+ `):["#!/bin/sh",`# ${gi}`,'if [ "$#" -eq 0 ]; then',` exec ${Wh(n)} ${Vs}`,"fi","exit 64",""].join(`
473
+ `)},Hd=(e,t)=>{if(!Ai(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Ci(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"]}},cE=async e=>{try{return await cG(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},AG=async(e,t)=>{try{let n=await lG(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!Ud(r,t))throw new Error;if(!(await nE(n)).isFile())throw new Error;await rG(n,t==="posix"?eE.X_OK:eE.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},lE=e=>e.slice(0,300).includes(gi),dE=async(e,t,n)=>{let r=await cE(e);if(r!==void 0&&r!==t&&!lE(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 nE(e)).mode&511)===493)return"unchanged"}catch{}}let o=fG(e);try{await sG(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=mG(o,`.anyray-helper.${process.pid}.${pG()}.tmp`),s=!1;try{await uG(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await oG(a,493);let i=await iG(a,"r");try{await Pr(i)}finally{await i.close()}await he(a,e),s=!0}catch{throw new Error(`could not install helper at ${e}`)}finally{s||await dG(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},CG=(e,t,n)=>{let r=n==="windows"?`"${Ci(t,n)}" `:` exec ${Wh(t)} `;return e.split(/\r?\n/).some(o=>o.startsWith(r)&&o.length>r.length)},Gd=async(e,t={})=>{let n=Bh((t.platform??Fh)());if(!Ud(e,n))return;let r=[{path:t.helperPath??oE(n),content:sE(n,e)},{path:t.bootstrapHeadersHelperPath??aE(n),content:iE(n,e)}];for(let o of r)try{if((await aG(o.path).catch(()=>{}))?.isSymbolicLink())continue;let a=await cE(o.path);if(a===void 0||a===o.content||!lE(a)||!CG(a,e,n))continue;await dE(o.path,o.content,n)}catch{}},uE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=gG(e);if(o.help)return n.write(yG),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");if(o.wrapper&&o.mode!=="print")throw new Error("--wrapper applies to --print only; --write installs both helpers");let a=(t.platform??Fh)(),s=o.targetPlatform??Bh(a),i=o.binaryPath,c=(d,u,p)=>{let f=Ci(u??p,s);if(!Ai(f,s))throw new Error(`${d} must be an absolute ${s} path`);if(s==="windows"&&Hd("windows",f),yi(f)===yi(i))throw new Error(`${d} must differ from --bin (the helper cannot invoke itself)`);return f},l=[{kind:"credential",label:"credential helper",path:c("--path",o.helperPath,oE(s)),content:sE(s,i)},{kind:"bootstrap-headers",label:"bootstrap-headers helper",path:c("--bootstrap-headers-path",o.bootstrapHeadersHelperPath,aE(s)),content:iE(s,i)}];if(yi(l[0].path)===yi(l[1].path))throw new Error("--path and --bootstrap-headers-path must differ");if(o.mode==="print"){let d=o.wrapper??"credential",u=l.find(p=>p.kind===d);return n.write(u.content),r.write(`Deploy this wrapper at ${u.path} after deploying the binary at ${i}.
474
+ `),0}if(s!==Bh(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await AG(i,s);for(let d of l){let u=await dE(d.path,d.content,s),p=d.label[0].toUpperCase()+d.label.slice(1);r.write(u==="unchanged"?`${p} already current at ${d.path}.
475
475
  `:`${u==="installed"?"Installed":"Updated"} ${d.label} at ${d.path}.
476
476
  `)}return 0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
477
- `),1}};var mG=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),hG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,yG=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.")},gG=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gd=(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!==""||yG(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Oa=(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()}},lE=e=>{if(!gG(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!mG.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Oa(e.clientId,"clientId",!0),r=Oa(e.scopes,"scopes",!0),o=Oa(e.issuer,"issuer",!1),a=Oa(e.authorizationUrl,"authorizationUrl",!1),s=Oa(e.tokenUrl,"tokenUrl",!1),i=Oa(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:Gd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Gd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Gd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},dE=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return lE(t)},Gh=e=>e==="windows"?Bd:Md,wG=(e,t)=>{let n=new URL(e);return n.searchParams.set("os",t),n.toString()},Vd=(e,t)=>{let n=wG(Gd(e.url,"--bootstrap-url"),t),r=e.oidc?lE(e.oidc):void 0,o;if(e.deploymentOrganizationUuid!==void 0&&(o=e.deploymentOrganizationUuid.trim(),!hG.test(o)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:n,bootstrapHeadersHelper:Gh(t),...r?{bootstrapOidc:r}:{},...o?{deploymentOrganizationUuid:o}:{}}},uE=(e,t)=>yr(Vd(e,t));var vG=`anyray-connect desktop [disconnect] [options]
477
+ `),1}};var kG=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),vG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,SG=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.")},IG=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Vd=(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!==""||SG(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Oa=(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()}},pE=e=>{if(!IG(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!kG.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Oa(e.clientId,"clientId",!0),r=Oa(e.scopes,"scopes",!0),o=Oa(e.issuer,"issuer",!1),a=Oa(e.authorizationUrl,"authorizationUrl",!1),s=Oa(e.tokenUrl,"tokenUrl",!1),i=Oa(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:Vd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Vd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Vd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},fE=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return pE(t)},Uh=e=>e==="windows"?Fd:Bd,EG=(e,t)=>{let n=new URL(e);return n.searchParams.set("os",t),n.toString()},Kd=(e,t)=>{let n=EG(Vd(e.url,"--bootstrap-url"),t),r=e.oidc?pE(e.oidc):void 0,o;if(e.deploymentOrganizationUuid!==void 0&&(o=e.deploymentOrganizationUuid.trim(),!vG.test(o)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:n,bootstrapHeadersHelper:Uh(t),...r?{bootstrapOidc:r}:{},...o?{deploymentOrganizationUuid:o}:{}}},mE=(e,t)=>gr(Kd(e,t));var _G=`anyray-connect desktop [disconnect] [options]
478
478
 
479
479
  The minimum Claude Desktop workflow:
480
480
  anyray-connect desktop Connect this machine
@@ -519,8 +519,8 @@ Options:
519
519
 
520
520
  Older flag-based Claude artifacts and Codex fleet output remain accepted for
521
521
  compatibility, but are not part of the recommended Claude Desktop workflow.
522
- `,SG=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",IG=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),EG=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[SG(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...IG(o)]},xG=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),Vh=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>xG.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"]},Gn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),pE=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),RG=(e,t)=>` <key>${Gn(e)}</key>
523
- <string>${Gn(t)}</string>`,Kh=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>RG(i,c)).join(`
522
+ `,PG=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",DG=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),LG=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[PG(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...DG(o)]},NG=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),Hh=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>NG.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"]},Vn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),hE=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),$G=(e,t)=>` <key>${Vn(e)}</key>
523
+ <string>${Vn(t)}</string>`,Gh=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>$G(i,c)).join(`
524
524
  `);return`<?xml version="1.0" encoding="UTF-8"?>
525
525
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
526
526
  <plist version="1.0">
@@ -529,15 +529,15 @@ compatibility, but are not part of the recommended Claude Desktop workflow.
529
529
  <array>
530
530
  <dict>
531
531
  <key>PayloadType</key>
532
- <string>${Gn(e)}</string>
532
+ <string>${Vn(e)}</string>
533
533
  <key>PayloadVersion</key>
534
534
  <integer>1</integer>
535
535
  <key>PayloadIdentifier</key>
536
- <string>${Gn(t)}.payload</string>
536
+ <string>${Vn(t)}.payload</string>
537
537
  <key>PayloadUUID</key>
538
- <string>${Gn(o)}</string>
538
+ <string>${Vn(o)}</string>
539
539
  <key>PayloadDisplayName</key>
540
- <string>${Gn(n)}</string>
540
+ <string>${Vn(n)}</string>
541
541
  ${s}
542
542
  </dict>
543
543
  </array>
@@ -546,28 +546,28 @@ ${s}
546
546
  <key>PayloadVersion</key>
547
547
  <integer>1</integer>
548
548
  <key>PayloadIdentifier</key>
549
- <string>${Gn(t)}</string>
549
+ <string>${Vn(t)}</string>
550
550
  <key>PayloadUUID</key>
551
- <string>${Gn(r)}</string>
551
+ <string>${Vn(r)}</string>
552
552
  <key>PayloadDisplayName</key>
553
- <string>${Gn(n)}</string>
553
+ <string>${Vn(n)}</string>
554
554
  </dict>
555
555
  </plist>
556
- `},ki={disableDeploymentModeChooser:!0},mE=(e,t)=>Kh("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",yr({...eo(e,t),...ki})),OG=(e,t)=>`${JSON.stringify({...eo(e,t),...ki},null,2)}
557
- `,TG=e=>Kh("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",yr({...Vd(e,"macos"),...ki})),_G=e=>`${JSON.stringify({...Vd(e,"linux"),...ki},null,2)}
558
- `,hE=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries({...e,...yr(ki)}).map(([n,r])=>`"${pE(n)}"="${pE(r)}"`),""].join(`
559
- `),yE=(e,t)=>{let n=Fl(e,t);return hE(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},PG=e=>hE(uE(e,"windows")),gE=(e,t,n)=>{if(t==="darwin"){let r=wi;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:mE(e,r),helperPath:r}}if(t==="win32"){let r=bi;return{path:`${n}\\claude-desktop-anyray.reg`,content:yE(e,r),helperPath:r}}},wE=(e,t)=>[`Generated the complete Claude Desktop profile your administrator can deploy: ${e.path}`,t==="darwin"?"Send it to IT to push through MDM (Jamf, Intune, Kandji). It carries the full Anyray connection \u2014 no hand-merging, and no Developer Mode on the target machines.":"Send it to IT to import into machine policy (HKLM\\SOFTWARE\\Policies\\Claude), or push it through your device-management system.",`It references the shared credential helper at ${e.helperPath}, which IT deploys once per machine with \`anyray-connect desktop helper --write\`. The profile contains no credential.`,"Nothing on this machine changed; the managed policy stays authoritative until IT deploys it."],DG=(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=Hd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${us(e,o).join(`
556
+ `},ki={disableDeploymentModeChooser:!0},gE=(e,t)=>Gh("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",gr({...eo(e,t),...ki})),MG=(e,t)=>`${JSON.stringify({...eo(e,t),...ki},null,2)}
557
+ `,BG=e=>Gh("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",gr({...Kd(e,"macos"),...ki})),FG=e=>`${JSON.stringify({...Kd(e,"linux"),...ki},null,2)}
558
+ `,wE=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries({...e,...gr(ki)}).map(([n,r])=>`"${hE(n)}"="${hE(r)}"`),""].join(`
559
+ `),bE=(e,t)=>{let n=Wl(e,t);return wE(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},WG=e=>wE(mE(e,"windows")),AE=(e,t,n)=>{if(t==="darwin"){let r=wi;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:gE(e,r),helperPath:r}}if(t==="win32"){let r=bi;return{path:`${n}\\claude-desktop-anyray.reg`,content:bE(e,r),helperPath:r}}},CE=(e,t)=>[`Generated the complete Claude Desktop profile your administrator can deploy: ${e.path}`,t==="darwin"?"Send it to IT to push through MDM (Jamf, Intune, Kandji). It carries the full Anyray connection \u2014 no hand-merging, and no Developer Mode on the target machines.":"Send it to IT to import into machine policy (HKLM\\SOFTWARE\\Policies\\Claude), or push it through your device-management system.",`It references the shared credential helper at ${e.helperPath}, which IT deploys once per machine with \`anyray-connect desktop helper --write\`. The profile contains no credential.`,"Nothing on this machine changed; the managed policy stays authoritative until IT deploys it."],UG=(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=Hd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${us(e,o).join(`
560
560
  `)}
561
- `},LG=e=>Kh("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:kG.from(e,"utf-8").toString("base64")}),NG=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},$G=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=Qt(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}}},fE=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??bG,o=n.writeFile??AG;await r(CG(t),{recursive:!0}),await o(t,e)},MG=(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:
561
+ `},HG=e=>Gh("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:TG.from(e,"utf-8").toString("base64")}),GG=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},VG=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=Qt(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}}},yE=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??xG,o=n.writeFile??RG;await r(OG(t),{recursive:!0}),await o(t,e)},KG=(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:
562
562
  `),o.write(r==="windows"?` anyray-connect desktop helper --write --platform windows --bin "C:\\Program Files\\Anyray\\anyray-connect.exe" --path "${n}"
563
563
  `:` sudo anyray-connect desktop helper --write --platform posix --bin /usr/local/bin/anyray-connect --path '${n.replace(/'/g,`'"'"'`)}'
564
564
  `),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.
565
565
  `):t==="json"&&o.write(`Deploy this file to /etc/claude-desktop/managed-settings.json.
566
- `)},BG=(e,t)=>{t.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.
567
- `),t.write(`The bootstrap fetch is authenticated by the bootstrap-headers helper at ${Gh(e)}, and the response names the credential helper; install both on every managed machine first with \`anyray-connect desktop helper --write\` (deploy a stable anyray-connect binary through your software-distribution system before that).
566
+ `)},jG=(e,t)=>{t.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.
567
+ `),t.write(`The bootstrap fetch is authenticated by the bootstrap-headers helper at ${Uh(e)}, and the response names the credential helper; install both on every managed machine first with \`anyray-connect desktop helper --write\` (deploy a stable anyray-connect binary through your software-distribution system before that).
568
568
  `),t.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.
569
569
  `),t.write(`Each bootstrap response replaces the allowed managed configuration; omitted keys are unset.
570
- `)},FG=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??oo)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
570
+ `)},ZG=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??oo)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
571
571
  ${o.remedy}
572
572
  `),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("; ")})`:"")+`
573
573
  `)}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)`:"")+`
@@ -578,10 +578,10 @@ Reopen Claude Desktop \u2014 migrated ${c} available in the Anyray profile.
578
578
  Your previous profile is untouched, so \`desktop disconnect\` still works.
579
579
  `)}else n.write(`
580
580
  Nothing new to migrate \u2014 no local sessions or portable local data needed copying.
581
- `);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},bE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=EG(e);if(o[0]==="helper")return cE(o.slice(1),t);let a=NG(o);if(a.help)return n.write(vG),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 FG(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:dE(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},p=a.artifact==="reg"?PG(u):a.artifact==="json"?_G(u):TG(u);return await fE(p,a.path,t),BG(a.artifact==="reg"?"windows":a.artifact==="json"?"linux":"macos",r),a.path&&n.write(`Wrote ${a.path}
582
- `),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 ${wi} on macOS/Linux or ${bi} 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(!Ai(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"&&Hd("windows",i);let l=$G(a),d;if(a.target==="claude")d=a.artifact==="reg"?yE(l,i):a.artifact==="json"?OG(l,i):mE(l,i);else{let u=DG(l,i);d=a.artifact==="mobileconfig"?LG(u):u}return await fE(d,a.path,t),MG(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
581
+ `);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},kE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=LG(e);if(o[0]==="helper")return uE(o.slice(1),t);let a=GG(o);if(a.help)return n.write(_G),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 ZG(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:fE(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},p=a.artifact==="reg"?WG(u):a.artifact==="json"?FG(u):BG(u);return await yE(p,a.path,t),jG(a.artifact==="reg"?"windows":a.artifact==="json"?"linux":"macos",r),a.path&&n.write(`Wrote ${a.path}
582
+ `),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 ${wi} on macOS/Linux or ${bi} 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(!Ai(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"&&Hd("windows",i);let l=VG(a),d;if(a.target==="claude")d=a.artifact==="reg"?bE(l,i):a.artifact==="json"?MG(l,i):gE(l,i);else{let u=UG(l,i);d=a.artifact==="mobileconfig"?HG(u):u}return await yE(d,a.path,t),KG(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
583
583
  `),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
584
- `),1}};var WG=`anyray-connect retrieve <handle> [--source auto|claude|profile]
584
+ `),1}};var YG=`anyray-connect retrieve <handle> [--source auto|claude|profile]
585
585
 
586
586
  Print the original content Anyray externalized behind a "\xB7 retrieve ctx_\u2026"
587
587
  marker. The content is written to stdout byte-for-byte (no trailing newline
@@ -591,7 +591,7 @@ Options:
591
591
  --source <s> Which client config resolves the gateway: auto (default),
592
592
  claude (~/.claude/settings.json), or profile (~/.anyray).
593
593
  --help Show this help.
594
- `,HG=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
594
+ `,JG=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
595
595
 
596
596
  Semantic search over your externalized tool outputs. Prints one match per line
597
597
  to stdout as: handle<TAB>score<TAB>preview. Fetch a full original with
@@ -602,36 +602,36 @@ Options:
602
602
  --source <s> Which client config resolves the gateway: auto (default),
603
603
  claude (~/.claude/settings.json), or profile (~/.anyray).
604
604
  --help Show this help.
605
- `,AE=(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},UG=e=>e.replace(/[\t\r\n]+/g," ").trim(),CE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=AE(e,!1);if(o.help)return n.write(WG),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
605
+ `,vE=(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},XG=e=>e.replace(/[\t\r\n]+/g," ").trim(),SE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=vE(e,!1);if(o.help)return n.write(YG),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
606
606
  `),1;let s=await(t.readTarget??nt)(o.source),i=await(t.retrieve??va)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
607
607
  `),1)}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
608
- `),1}},kE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=AE(e,!0);if(o.help)return n.write(HG),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
609
- `),1;let s=await(t.readTarget??nt)(o.source),i=await(t.recall??vd)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
608
+ `),1}},IE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=vE(e,!0);if(o.help)return n.write(JG),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
609
+ `),1;let s=await(t.readTarget??nt)(o.source),i=await(t.recall??Sd)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
610
610
  `),1;if(i.matches.length===0)return r.write(`No matching externalized outputs found.
611
- `),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${UG(c.preview)}
611
+ `),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${XG(c.preview)}
612
612
  `)}return r.write(`Fetch a full original: anyray-connect retrieve <handle>
613
613
  `),0}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
614
- `),1}};import{promises as m1}from"node:fs";var Cn=e=>typeof e=="string"?e:"",GG=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(`
614
+ `),1}};import{promises as k1}from"node:fs";var Cn=e=>typeof e=="string"?e:"",zG=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(`
615
615
 
616
- `).trim()},VG=e=>{let t=Cn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},KG=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=GG(r);if(!o)continue;let a=Cn(r.created_at).trim();t.push({role:VG(r),text:o,...a?{createdAt:a}:{}})}return t},Kd=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=KG(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 c1}from"node:crypto";import{promises as Ii}from"node:fs";import{homedir as OE}from"node:os";import{join as Zd}from"node:path";import{promises as vE}from"node:fs";import jh from"node:path";var jG=4e4,ZG=16*1024*1024,vi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Si=async(e,t={})=>{let n=(e??"").trim();if(!n)return vi("","path is required");let r=t.cwd??process.cwd(),o=jh.resolve(r,n),a=jh.relative(r,o);if(a.startsWith("..")||jh.isAbsolute(a))return vi(n,"path is outside the workspace");let s=t.maxBytes??jG,i;try{let w=await vE.stat(o);if(!w.isFile())return vi(n,"not a regular file");let y=t.maxFileBytes??ZG;if(w.size>y)return vi(n,`file too large to read (${w.size} bytes; limit ${y})`);i=await vE.readFile(o,"utf8")}catch(w){return vi(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
616
+ `).trim()},qG=e=>{let t=Cn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},QG=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=zG(r);if(!o)continue;let a=Cn(r.created_at).trim();t.push({role:qG(r),text:o,...a?{createdAt:a}:{}})}return t},jd=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=QG(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 y1}from"node:crypto";import{promises as Ii}from"node:fs";import{homedir as PE}from"node:os";import{join as Yd}from"node:path";import{promises as EE}from"node:fs";import Vh from"node:path";var e1=4e4,t1=16*1024*1024,vi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Si=async(e,t={})=>{let n=(e??"").trim();if(!n)return vi("","path is required");let r=t.cwd??process.cwd(),o=Vh.resolve(r,n),a=Vh.relative(r,o);if(a.startsWith("..")||Vh.isAbsolute(a))return vi(n,"path is outside the workspace");let s=t.maxBytes??e1,i;try{let w=await EE.stat(o);if(!w.isFile())return vi(n,"not a regular file");let y=t.maxFileBytes??t1;if(w.size>y)return vi(n,`file too large to read (${w.size} bytes; limit ${y})`);i=await EE.readFile(o,"utf8")}catch(w){return vi(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
617
617
  `),l=Math.max(1,t.startLine??1),d=Math.min(c.length,t.endLine??c.length),u=l<=d?c.slice(l-1,d):[],p=u.join(`
618
618
  `),f=l<=d?d:l,m=!1,h=!1;if(Buffer.byteLength(p,"utf8")>s){let w=0,y=0;for(let g of u){let b=Buffer.byteLength(g,"utf8")+(y===0?0:1);if(w+b>s)break;w+=b,y+=1}y===0?(p=Buffer.from(u[0]??"","utf8").subarray(0,s).toString("utf8").replace(/\uFFFD$/,""),f=l,m=!0):(p=u.slice(0,y).join(`
619
- `),f=l+y-1),h=!0}return{ok:!0,content:p,path:n,lines:c.length,truncated:h,span:{startLine:l,endLine:f,...m?{partialLine:!0}:{}}}},Zh=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
619
+ `),f=l+y-1),h=!0}return{ok:!0,content:p,path:n,lines:c.length,truncated:h,span:{startLine:l,endLine:f,...m?{partialLine:!0}:{}}}},Kh=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
620
620
  ${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}
621
- ${e.content}`};import{spawn as YG}from"node:child_process";import{promises as Yh}from"node:fs";import Jh from"node:path";var Xh=400,JG=240,XG=4e3,zG=4e3,qG=512*1024,QG=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),IE=(e,t)=>e.length>t?e.slice(0,t):e,e1=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"]),t1=8,n1=2e3,r1=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],o1=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")},EE=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!e1.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=t1))break}return n},xE=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},a1=(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)},SE=(e,t,n)=>{let r=[];for(let o of e.split(`
622
- `)){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:IE(l,t)})}return r},s1=(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 m of n)c.push("-g",m);for(let m of r1)c.push("-g",m);if(s?.length){for(let m of s)c.push("-e",m);c.push("--",".")}else c.push("--",e,".");let l;try{l=YG("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,p=m=>{u||(u=!0,clearTimeout(f),i(m))},f=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let m=SE(d,o,r);p({ok:!0,matches:m,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",m=>{if(d+=m,d.length>r*(o+64))try{l.kill("SIGKILL")}catch{}}),l.on("error",()=>{p({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"})}),l.on("close",m=>{if(typeof m=="number"&&m>=2){p({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let h=SE(d,o,r+1),w=h.length>r;p({ok:!0,matches:w?h.slice(0,r):h,truncated:w,engine:"ripgrep"})})}),i1=async(e,t,n,r,o,a,s)=>{let i=xE(s?.length?s:e),c=h=>i?h:h.toLowerCase(),l=(s?.length?s:[e]).map(c),d=n.map(h=>h.replace(/^\*+/,"")).filter(h=>h.startsWith(".")),u=[],p=0,f=!1,m=async h=>{if(u.length>=r||Date.now()>a){f=!0;return}let w;try{w=await Yh.readdir(h,{withFileTypes:!0})}catch{return}for(let y of w){if(u.length>=r||Date.now()>a){f=!0;return}let g=Jh.join(h,y.name);if(y.isDirectory()){if(QG.has(y.name))continue;await m(g)}else if(y.isFile()){if(p>=zG){f=!0;return}if(d.length&&!d.some(C=>y.name.endsWith(C))||o1(Jh.relative(t,g)))continue;p+=1;let b;try{if((await Yh.stat(g)).size>qG)continue;b=await Yh.readFile(g,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let k=b.split(`
623
- `);for(let C=0;C<k.length;C+=1){let S=c(k[C]);if(l.some(I=>S.includes(I))&&(u.push({file:Jh.relative(t,g),line:C+1,text:IE(k[C],o)}),u.length>=r)){f=!0;return}}}}};return await m(t),{ok:!0,matches:u,truncated:f,engine:"walk"}},jd=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??Xh,s=t.maxColumns??JG,i=t.timeoutMs??XG,c=Date.now()+i,l=EE(n),d=l.length>1,u=Math.min(a*4,n1),p=(y,g)=>i1(n,r,o,y,s,c,g),f=async y=>{let g=await y(u,l);if(!g.ok)return g;let b=a1(g.matches,l,xE(l)),k=b.length>a;return{...g,matches:k?b.slice(0,a):b,truncated:g.truncated||k,matched:"tokens",tokens:l}};if(t.engine==="walk"){let y=await p(a);return y.matches.length>0||!d?y:f((g,b)=>p(g,b))}let m=(y,g)=>s1(n,r,o,y,s,Math.max(0,c-Date.now()),g),h=await m(a);if(h.ok){if(h.matches.length>0||!d)return h;let y=await f((g,b)=>m(g,b));return y.ok?y:f((g,b)=>p(g,b))}let w=await p(a);return w.matches.length>0||!d?w:f((y,g)=>p(y,g))},RE=(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=EE(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.
621
+ ${e.content}`};import{spawn as n1}from"node:child_process";import{promises as jh}from"node:fs";import Zh from"node:path";var Yh=400,r1=240,o1=4e3,a1=4e3,s1=512*1024,i1=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),RE=(e,t)=>e.length>t?e.slice(0,t):e,c1=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"]),l1=8,d1=2e3,u1=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],p1=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")},OE=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!c1.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=l1))break}return n},TE=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},f1=(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)},xE=(e,t,n)=>{let r=[];for(let o of e.split(`
622
+ `)){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:RE(l,t)})}return r},m1=(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 m of n)c.push("-g",m);for(let m of u1)c.push("-g",m);if(s?.length){for(let m of s)c.push("-e",m);c.push("--",".")}else c.push("--",e,".");let l;try{l=n1("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,p=m=>{u||(u=!0,clearTimeout(f),i(m))},f=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let m=xE(d,o,r);p({ok:!0,matches:m,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",m=>{if(d+=m,d.length>r*(o+64))try{l.kill("SIGKILL")}catch{}}),l.on("error",()=>{p({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"})}),l.on("close",m=>{if(typeof m=="number"&&m>=2){p({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let h=xE(d,o,r+1),w=h.length>r;p({ok:!0,matches:w?h.slice(0,r):h,truncated:w,engine:"ripgrep"})})}),h1=async(e,t,n,r,o,a,s)=>{let i=TE(s?.length?s:e),c=h=>i?h:h.toLowerCase(),l=(s?.length?s:[e]).map(c),d=n.map(h=>h.replace(/^\*+/,"")).filter(h=>h.startsWith(".")),u=[],p=0,f=!1,m=async h=>{if(u.length>=r||Date.now()>a){f=!0;return}let w;try{w=await jh.readdir(h,{withFileTypes:!0})}catch{return}for(let y of w){if(u.length>=r||Date.now()>a){f=!0;return}let g=Zh.join(h,y.name);if(y.isDirectory()){if(i1.has(y.name))continue;await m(g)}else if(y.isFile()){if(p>=a1){f=!0;return}if(d.length&&!d.some(C=>y.name.endsWith(C))||p1(Zh.relative(t,g)))continue;p+=1;let b;try{if((await jh.stat(g)).size>s1)continue;b=await jh.readFile(g,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let k=b.split(`
623
+ `);for(let C=0;C<k.length;C+=1){let S=c(k[C]);if(l.some(I=>S.includes(I))&&(u.push({file:Zh.relative(t,g),line:C+1,text:RE(k[C],o)}),u.length>=r)){f=!0;return}}}}};return await m(t),{ok:!0,matches:u,truncated:f,engine:"walk"}},Zd=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??Yh,s=t.maxColumns??r1,i=t.timeoutMs??o1,c=Date.now()+i,l=OE(n),d=l.length>1,u=Math.min(a*4,d1),p=(y,g)=>h1(n,r,o,y,s,c,g),f=async y=>{let g=await y(u,l);if(!g.ok)return g;let b=f1(g.matches,l,TE(l)),k=b.length>a;return{...g,matches:k?b.slice(0,a):b,truncated:g.truncated||k,matched:"tokens",tokens:l}};if(t.engine==="walk"){let y=await p(a);return y.matches.length>0||!d?y:f((g,b)=>p(g,b))}let m=(y,g)=>m1(n,r,o,y,s,Math.max(0,c-Date.now()),g),h=await m(a);if(h.ok){if(h.matches.length>0||!d)return h;let y=await f((g,b)=>m(g,b));return y.ok?y:f((g,b)=>p(g,b))}let w=await p(a);return w.matches.length>0||!d?w:f((y,g)=>p(y,g))},_E=(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=OE(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.
624
624
  `:"";if(n==="paths"){let d=new Map;for(let p of t.matches)d.set(p.file,(d.get(p.file)??0)+1);let u=[...d].map(([p,f])=>`${p} (${f} match${f===1?"":"es"})`);return[`${r}${d.size}${t.truncated?"+":""} file${d.size===1?"":"s"} match "${e}":`,...u].join(`
625
625
  `)}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(`
626
626
  `):[o,...a.slice(0,Math.max(1,l)),s(a.length-Math.max(1,l))].join(`
627
- `)};var TE=448,l1=384,d1=4e4,Ir=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=Zd(OE(),".anyray");try{if((await Ii.stat(t)).isDirectory())return Zd(t,"history")}catch{}return Zd(OE(),".anyray-history")},u1=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:p1(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},p1=e=>{let t=c1("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)},f1=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}
627
+ `)};var DE=448,g1=384,w1=4e4,Er=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=Yd(PE(),".anyray");try{if((await Ii.stat(t)).isDirectory())return Yd(t,"history")}catch{}return Yd(PE(),".anyray-history")},b1=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:A1(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},A1=e=>{let t=y1("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)},C1=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}
628
628
 
629
629
  ${r.text}
630
630
  `});return[...t,...n].join(`
631
631
  `).replace(/\n{3,}/g,`
632
632
 
633
633
  `)+`
634
- `},Yd=async e=>{let t=await Ir();await Ii.mkdir(t,{recursive:!0,mode:TE});try{await Ii.chmod(t,TE)}catch{}let n=0,r=0;for(let o of e)try{await Ii.writeFile(Zd(t,u1(o)),f1(o),{mode:l1}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Ta=async()=>{try{let e=await Ir();return(await Ii.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},_E=async e=>{let t=await Ir();return jd(e,{cwd:t,globs:["*.md"]})},PE=async e=>{let t=await Ir();return Si(e,{cwd:t,maxBytes:d1})};var DE=`anyray-connect history <command>
634
+ `},Jd=async e=>{let t=await Er();await Ii.mkdir(t,{recursive:!0,mode:DE});try{await Ii.chmod(t,DE)}catch{}let n=0,r=0;for(let o of e)try{await Ii.writeFile(Yd(t,b1(o)),C1(o),{mode:g1}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Ta=async()=>{try{let e=await Er();return(await Ii.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},LE=async e=>{let t=await Er();return Zd(e,{cwd:t,globs:["*.md"]})},NE=async e=>{let t=await Er();return Si(e,{cwd:t,maxBytes:w1})};var $E=`anyray-connect history <command>
635
635
 
636
636
  Make past Claude conversations searchable from any Anyray-connected client.
637
637
 
@@ -652,7 +652,7 @@ Which one you want:
652
652
  conversation into the chat when you ask for it. Recall, not a list.
653
653
 
654
654
  Running both is fine, and gets you both.
655
- `,h1=async e=>{try{return{raw:await m1.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"})`}}},y1=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return O("Usage: anyray-connect history import <conversations.json>"),A(v("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await h1(t);if("error"in n)return O(n.error),1;let r=Kd(n.raw);if(!r.ok)return O(`Could not read that export: ${r.message??"unrecognized format"}`),A(v("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 Yd(r.conversations)}catch(a){let s=a?.code;return O(`Could not create the history archive (${s??"write failed"}).`),A(v("Check that ~/.anyray is a writable directory, then try again.")),1}return M(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&A(v(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&_(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),A(""),A(V("Your history is now searchable from any Anyray-connected client.")),A(v(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),A(v(" and the assistant can search this archive and pull it up.")),A(v(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),A(v(" for them, they do not reappear as a clickable list in the app.")),0},g1=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return O("Usage: anyray-connect history restore <export.zip>"),A(v("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await Hl(t);return n.ok?(M(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&A(v(` ${n.skipped} already present, left untouched.`)),n.failed>0&&_(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),A(""),A(V("Open Claude Desktop \u2014 they are in the sidebar again.")),A(v(" Anyray stays configured; this changed nothing about your routing.")),A(v(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),A(v(" undocumented. A future Desktop release could stop reading it \u2014 your export")),A(v(" file still works, and `history import` remains a second copy.")),0):(O(`Could not restore into Claude Desktop: ${n.reason}`),A(v(` ${n.remedy}`)),1)},w1=async()=>{let e=await Ir(),t=await Ta();return t===0?(A(`No conversations imported yet. Archive would live at ${e}`),A(v(" Import one with: anyray-connect history import <conversations.json>")),0):(M(`${t} conversation${t===1?"":"s"} in ${e}`),0)},LE=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(DE),0):t==="import"?y1(e.slice(1)):t==="restore"?g1(e.slice(1)):t==="status"?w1():(O(`Unknown history command: ${t}`),console.log(DE),1)};import{promises as b1}from"node:fs";var A1=`anyray-connect migrate [options]
655
+ `,v1=async e=>{try{return{raw:await k1.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"})`}}},S1=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return O("Usage: anyray-connect history import <conversations.json>"),A(v("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await v1(t);if("error"in n)return O(n.error),1;let r=jd(n.raw);if(!r.ok)return O(`Could not read that export: ${r.message??"unrecognized format"}`),A(v("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 Jd(r.conversations)}catch(a){let s=a?.code;return O(`Could not create the history archive (${s??"write failed"}).`),A(v("Check that ~/.anyray is a writable directory, then try again.")),1}return B(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&A(v(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&_(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),A(""),A(V("Your history is now searchable from any Anyray-connected client.")),A(v(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),A(v(" and the assistant can search this archive and pull it up.")),A(v(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),A(v(" for them, they do not reappear as a clickable list in the app.")),0},I1=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return O("Usage: anyray-connect history restore <export.zip>"),A(v("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await Hl(t);return n.ok?(B(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&A(v(` ${n.skipped} already present, left untouched.`)),n.failed>0&&_(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),A(""),A(V("Open Claude Desktop \u2014 they are in the sidebar again.")),A(v(" Anyray stays configured; this changed nothing about your routing.")),A(v(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),A(v(" undocumented. A future Desktop release could stop reading it \u2014 your export")),A(v(" file still works, and `history import` remains a second copy.")),0):(O(`Could not restore into Claude Desktop: ${n.reason}`),A(v(` ${n.remedy}`)),1)},E1=async()=>{let e=await Er(),t=await Ta();return t===0?(A(`No conversations imported yet. Archive would live at ${e}`),A(v(" Import one with: anyray-connect history import <conversations.json>")),0):(B(`${t} conversation${t===1?"":"s"} in ${e}`),0)},ME=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log($E),0):t==="import"?S1(e.slice(1)):t==="restore"?I1(e.slice(1)):t==="status"?E1():(O(`Unknown history command: ${t}`),console.log($E),1)};import{promises as x1}from"node:fs";var R1=`anyray-connect migrate [options]
656
656
 
657
657
  Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
658
658
 
@@ -681,60 +681,88 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
681
681
  Open claude.ai -> Settings -> Privacy -> Export data. Anthropic emails a link.
682
682
  Pass the .zip to --export, and the conversations.json inside it to
683
683
  --conversations. Both are safe to re-run; they skip what is already there.
684
- `,C1=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},NE={code:"Claude Code sessions",cowork:"Cowork tasks"},k1=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`${NE[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},v1=async(e,t)=>{A(V("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??oo)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){O(` ${n.reason}`);for(let s of n.remedy.split(`
685
- `).filter(Boolean))A(` ${s}`);return!1}for(let s of n.lanes)A(` ${k1(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";A(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&_(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&_(` 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&&_(` ${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??[])_(` ${NE[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),A(` ${Rm(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)&&A(v(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},S1=async(e,t)=>{if(A(""),A(V("2. Your claude.ai chats")),t){A(v(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){A(" These live on your Claude account, not this machine, so they need"),A(" an export. Anyray cannot fetch them: the only credential that could"),A(" is your claude.ai session, which Connect never holds."),A(v(" claude.ai -> Settings -> Privacy -> Export data, then:")),A(v(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await Hl(e.exportZip);if(!n.ok){O(` ${n.reason}`),A(` ${n.remedy}`);return}M(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),A(v(" 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);M(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&A(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},I1=async e=>{if(A(""),A(V("3. Searchable from every Anyray client")),!e.conversations){let o=await Ta();o>0?A(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(A(v(" Optional. Pass the conversations.json inside the export:")),A(v(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await b1.readFile(e.conversations,"utf8")}catch{O(` could not read ${e.conversations}`);return}let n=Kd(t);if(!n.ok){O(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Yd(n.conversations);M(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),A(v(` Ask any Anyray-connected client about a past chat. ${await Ir()}`))},E1=e=>{A(""),A(V("Next")),A(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||_(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),A(v(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},$E=async(e,t={})=>{let n;try{n=C1(e)}catch(o){return O(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(A1),0;A(V("Migrating Claude Desktop onto Anyray")),A(v("Claude Desktop must be fully quit.")),A("");let r=await v1(n,t);return await S1(n,!r),await I1(n),r?(E1(n),0):(A(""),_("Fix the item above and re-run to finish the migration."),1)};var x1=3e3,Jd=async(e,t={})=>{let n=t.timeoutMs??x1,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`:ht(s).trim()||"connection failed"}}finally{clearTimeout(a)}};import{execFileSync as FE}from"node:child_process";import R1 from"node:os";var WE="ai.anyray.connect",zd="EnrollmentEmail",ME="EnrollmentUrl",O1="HKLM\\SOFTWARE\\Policies\\Anyray\\Connect",T1=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,_1=254,P1=2048,D1=()=>`/Library/Managed Preferences/${WE}.plist`,L1=e=>`/Library/Managed Preferences/${e}/${WE}.plist`;var BE=e=>{try{let t=JSON.parse(e);return{...typeof t[zd]=="string"?{email:t[zd]}:{},...typeof t[ME]=="string"?{enrollmentUrl:t[ME]}:{}}}catch{return{}}},N1=e=>new RegExp(`${zd}\\s+REG_SZ\\s+(.+)`).exec(e)?.[1]?.trim()||void 0,Xd=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(!t||t.length>_1))return T1.test(t)?t:void 0},$1=e=>{if(!e)return;let t=e.trim();if(!(!t||t.length>P1))try{let n=new URL(t);return n.protocol==="https:"&&n.username===""&&n.password===""&&n.search===""&&n.hash===""&&/^\/enroll\/enp_[A-Za-z0-9_-]{43}$/.test(n.pathname)?n.toString():void 0}catch{return}},M1=e=>{try{return FE("plutil",["-convert","json","-o","-",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},B1=()=>{try{return R1.userInfo().username||void 0}catch{return}},F1=()=>{try{return FE("reg",["query",O1,"/v",zd],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},HE={platform:process.platform,readMacPlistJson:M1,username:B1,readWindowsRegQuery:F1},zh=(e=HE)=>{try{if(e.platform==="darwin"){let t=e.username(),n=t?BE(e.readMacPlistJson(L1(t))??""):{},r=BE(e.readMacPlistJson(D1())??""),o=Xd(n.email)??Xd(r.email),a=$1(r.enrollmentUrl);return{...o?{email:o}:{},...a?{enrollmentUrl:a}:{}}}if(e.platform==="win32"){let t=e.readWindowsRegQuery(),n=t?Xd(N1(t)):void 0;return n?{email:n}:{}}return{}}catch{return{}}},UE=(e,t)=>{if(!e?.length)return;let n=t?.trim().toLowerCase();if(n)return Xd(`${n}@${e[0]}`)},GE=(e=HE)=>zh(e).email;import{spawn as W1}from"node:child_process";import{platform as H1}from"node:os";var _a=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=H1(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=W1(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var VE=()=>Dh(),KE=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??VE)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},U1=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},jE=async(e,t={})=>{let n=(t.openInput??VE)(),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(m=>m.selected===!0&&m.requiresExplicitChoice!==!0),s=0,i=0,c=ha(o,t.env??process.env),l=(m,h)=>c?`\x1B[${m}m${h}\x1B[0m`:h,d=()=>{let m=[l("1",e.title)];for(let h=0;h<e.items.length;h++){let w=e.items[h],y=h===s?l("36","\u276F"):" ",g=e.single?a[h]?"(\u25CF)":"(\u25CB)":a[h]?"[x]":"[ ]",b=w.hint?` ${l("2",w.hint)}`:"";m.push(`${y} ${g} ${w.label}${b}`)}m.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(m.map(h=>`\r\x1B[2K${h}`).join(`
684
+ `,O1=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},BE={code:"Claude Code sessions",cowork:"Cowork tasks"},T1=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`${BE[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},_1=async(e,t)=>{A(V("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??oo)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){O(` ${n.reason}`);for(let s of n.remedy.split(`
685
+ `).filter(Boolean))A(` ${s}`);return!1}for(let s of n.lanes)A(` ${T1(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";A(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&_(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&_(` 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&&_(` ${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??[])_(` ${BE[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),A(` ${Em(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)&&A(v(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},P1=async(e,t)=>{if(A(""),A(V("2. Your claude.ai chats")),t){A(v(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){A(" These live on your Claude account, not this machine, so they need"),A(" an export. Anyray cannot fetch them: the only credential that could"),A(" is your claude.ai session, which Connect never holds."),A(v(" claude.ai -> Settings -> Privacy -> Export data, then:")),A(v(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await Hl(e.exportZip);if(!n.ok){O(` ${n.reason}`),A(` ${n.remedy}`);return}B(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),A(v(" 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);B(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&A(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},D1=async e=>{if(A(""),A(V("3. Searchable from every Anyray client")),!e.conversations){let o=await Ta();o>0?A(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(A(v(" Optional. Pass the conversations.json inside the export:")),A(v(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await x1.readFile(e.conversations,"utf8")}catch{O(` could not read ${e.conversations}`);return}let n=jd(t);if(!n.ok){O(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Jd(n.conversations);B(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),A(v(` Ask any Anyray-connected client about a past chat. ${await Er()}`))},L1=e=>{A(""),A(V("Next")),A(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||_(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),A(v(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},FE=async(e,t={})=>{let n;try{n=O1(e)}catch(o){return O(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(R1),0;A(V("Migrating Claude Desktop onto Anyray")),A(v("Claude Desktop must be fully quit.")),A("");let r=await _1(n,t);return await P1(n,!r),await D1(n),r?(L1(n),0):(A(""),_("Fix the item above and re-run to finish the migration."),1)};var N1=3e3,Xd=async(e,t={})=>{let n=t.timeoutMs??N1,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`:ht(s).trim()||"connection failed"}}finally{clearTimeout(a)}};import{execFileSync as HE}from"node:child_process";import{lstatSync as $1,readFileSync as M1}from"node:fs";import B1 from"node:os";var GE="ai.anyray.connect",zh="EnrollmentEmail",qh="EnrollmentUrl",F1="HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Anyray\\Connect",WE="/etc/anyray/anyray-enroll.json",W1=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,U1=254,H1=2048,G1=64*1024,V1=e=>e.isFile()&&e.uid===0&&(e.mode&63)===0&&e.size<=G1,K1=()=>`/Library/Managed Preferences/${GE}.plist`,j1=e=>`/Library/Managed Preferences/${e}/${GE}.plist`;var Jh=e=>{try{let t=JSON.parse(e);return{...typeof t[zh]=="string"?{email:t[zh]}:{},...typeof t[qh]=="string"?{enrollmentUrl:t[qh]}:{}}}catch{return{}}},UE=(e,t)=>{for(let n of e.split(/\r?\n/u)){let r=/^\s*(\S+)\s+REG_SZ\s+([^\r\n]+)$/u.exec(n);if(r?.[1]===t)return r[2]?.trim()||void 0}},VE=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(!t||t.length>U1))return W1.test(t)?t:void 0},Z1=e=>{if(!e)return;let t=e.trim();if(!(!t||t.length>H1))try{let n=new URL(t);return n.protocol==="https:"&&n.username===""&&n.password===""&&n.search===""&&n.hash===""&&/^\/enroll\/enp_[A-Za-z0-9_-]{43}$/.test(n.pathname)?n.toString():void 0}catch{return}},Y1=e=>{try{return HE("plutil",["-convert","json","-o","-",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},J1=()=>{try{return B1.userInfo().username||void 0}catch{return}},X1=()=>{try{return HE("reg",["query",F1],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},z1=()=>{try{let e=$1(WE);return V1(e)?M1(WE,"utf8"):void 0}catch{return}},KE={platform:process.platform,readMacPlistJson:Y1,username:J1,readWindowsRegQuery:X1,readLinuxJson:z1},Xh=(e,t)=>{let n=e.map(VE).find(o=>o!==void 0),r=Z1(t);return{...n?{email:n}:{},...r?{enrollmentUrl:r}:{}}},Qh=(e=KE)=>{try{if(e.platform==="darwin"){let t=e.username(),n=t?Jh(e.readMacPlistJson(j1(t))??""):{},r=Jh(e.readMacPlistJson(K1())??"");return Xh([n.email,r.email],r.enrollmentUrl)}if(e.platform==="win32"){let t=e.readWindowsRegQuery();return t?Xh([UE(t,zh)],UE(t,qh)):{}}if(e.platform==="linux"){let t=Jh(e.readLinuxJson?.()??"");return Xh([t.email],t.enrollmentUrl)}return{}}catch{return{}}},jE=(e,t)=>{if(!e?.length)return;let n=t?.trim().split(/[\\/]/).at(-1)?.toLowerCase();if(n)return VE(`${n}@${e[0]}`)},ZE=(e=KE)=>Qh(e).email;import{spawn as q1}from"node:child_process";import{platform as Q1}from"node:os";var _a=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=Q1(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=q1(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var YE=()=>_h(),JE=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??YE)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},eV=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},XE=async(e,t={})=>{let n=(t.openInput??YE)(),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(m=>m.selected===!0&&m.requiresExplicitChoice!==!0),s=0,i=0,c=ha(o,t.env??process.env),l=(m,h)=>c?`\x1B[${m}m${h}\x1B[0m`:h,d=()=>{let m=[l("1",e.title)];for(let h=0;h<e.items.length;h++){let w=e.items[h],y=h===s?l("36","\u276F"):" ",g=e.single?a[h]?"(\u25CF)":"(\u25CB)":a[h]?"[x]":"[ ]",b=w.hint?` ${l("2",w.hint)}`:"";m.push(`${y} ${g} ${w.label}${b}`)}m.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(m.map(h=>`\r\x1B[2K${h}`).join(`
686
686
  `)),o.write(`
687
687
  `),i=m.length},u=()=>{i!==0&&(o.write(`\x1B[${i}A`),o.write(Array.from({length:i},()=>`\r\x1B[2K
688
- `).join("")),o.write(`\x1B[${i}A`))},p=!!r.isRaw,f=!1;try{return f=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((m,h)=>{let w=()=>{r.off("data",C),r.off("end",b),r.off("close",b),r.off("error",k)},y=S=>{w(),m(S)},g=S=>{w(),h(S)},b=()=>y({kind:"cancelled"}),k=S=>g(S),C=S=>{try{for(let I of U1(S)){if(I===""||I==="\x1B"||I==="q"){y({kind:"cancelled"});return}if(e.items.length===0){(I==="\r"||I===`
689
- `)&&y({kind:"ok",values:[]});continue}if(I==="\x1B[A"||I==="k")s=(s-1+e.items.length)%e.items.length,d();else if(I==="\x1B[B"||I==="j")s=(s+1)%e.items.length,d();else if(I===" "){if(e.single){let E=!a[s];a.fill(!1),a[s]=E}else a[s]=!a[s];d()}else if(I==="a"&&!e.single){let E=e.items.map((P,W)=>({item:P,index:W})).filter(({item:P})=>P.requiresExplicitChoice!==!0),R=!E.every(({index:P})=>a[P]);for(let{index:P}of E)a[P]=R;d()}else if(I==="\r"||I===`
690
- `){y({kind:"ok",values:e.items.filter((E,R)=>a[R]).map(E=>E.value)});return}}}catch(I){g(I)}};r.on("data",C),r.on("end",b),r.on("close",b),r.on("error",k)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),f&&r.setRawMode(p)}catch{}n.close()}};var ZE=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],G1=80,Ei=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&ha(r,n.env??process.env)))return r.write(`${e}
691
- `),t();let a=0,s=()=>{r.write(`\r${ZE[a++%ZE.length]} ${e}`)};s();let i=setInterval(s,G1);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as V1}from"node:fs";import{spawnSync as YE}from"node:child_process";import{chmod as JE,copyFile as Qh,lstat as ey,mkdir as ty,readdir as nu,realpath as tu,rename as qd,rm as Et,stat as XE,symlink as K1,writeFile as j1}from"node:fs/promises";import{createHash as Z1}from"node:crypto";import{basename as Qd,dirname as Er,join as Fe}from"node:path";import{Readable as Y1}from"node:stream";import{pipeline as J1}from"node:stream/promises";var zE="https://github.com/anyrayHQ/install/releases",qE="connect-v",X1=new RegExp(`/releases/tag/${qE}([0-9][0-9A-Za-z.-]*)$`),z1=300*1024*1024,Oi=1e4,q1=5*6e4,Q1=360*6e4,eV=30*6e4,Pa=(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)},QE=(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"}},tV=e=>{if(e)return X1.exec(e.trim())?.[1]},ny=(e,t)=>{for(let n of e.split(`
692
- `)){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()}},ex=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&&Pa(e.current,e.minVersion)<0&&Pa(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},nV=e=>Pa(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}:{...ex(e),downgradeBlocked:!1},Da=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",rV=(e=process.execPath)=>{let t=Hu(e);return t?Er(t):Er(Er(e))},oV=async(e=ft())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=Fe(rV(e.execPath),"bin",Da());try{if(await tu(t)!==await tu(e.execPath))return}catch{return}return t},ry=async(e=ft(),t=Q())=>{let n=await oV(e);if(n)return{kind:"managed",root:Er(Er(n)),link:n,entryPath:Kn(e)};let r=Kn(e);return Gu(r,t)?{kind:"durable",root:t,entryPath:r}:Fu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},ru=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)}},oy=async(e=Oi)=>{let t=await ru(`${zE}/latest`,e,{redirect:"manual"});return tV(t.headers.get("location"))},aV=async e=>{try{let t=await ru(`${e}/connect-update.json`,Oi);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}},Ri=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},ay=async(e,t,n)=>{let r=await ru(e,q1);if(!r.ok||!r.body)throw new Ri(r.status);let o=Z1("sha256"),a=0;if(await J1(Y1.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>z1)throw new Error("asset exceeds size cap");o.update(c),yield c}},V1(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},sV=e=>Qd(e)===Da()?Qd(Er(e)):Qd(e),iV=async e=>{let t=await nu(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Et(Fe(e,n),{force:!0}).catch(()=>{})},tx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Et(r,{force:!0}).catch(()=>{});let o=!1;try{await qd(e,r),o=!0}catch{}try{await Qh(t,e),await j1(qa(e),sV(t))}catch(a){throw o&&await qd(r,e).catch(()=>{}),a}await Et(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Et(n,{force:!0}),await K1(t,n),await qd(n,e)},cV=".anyray",sy=(e,t)=>e===t||Qd(e)===cV?448:493,xi=async(e,t)=>{let n=(await XE(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await JE(e,n&4095|t).catch(()=>{})},eu=async(e,t)=>{await ty(e,{recursive:!0,mode:t}),await xi(e,t)},lV=async(e,t,n)=>{let r=sy(e,Q());if(r!==448){let o=Fe(e,"versions");await xi(e,r),await xi(Fe(e,"bin"),r),await xi(o,r);for(let a of await nu(o).catch(()=>[]))await xi(Fe(o,a),r)}await(n.refreshDesktopHelpers??Ud)(t)},dV=async(e,t={})=>{let n=Fe(e.root,"bin"),r=Fe(e.root,"versions"),o=Fe(n,Da()),a=sy(e.root,(t.privateRoot??Q)());await eu(n,a),await eu(r,a);let s=Fe(r,e.version),c=(await ey(s).catch(()=>{}))?.isFile()?s:Fe(s,Da());if(!(await ey(c).catch(()=>{}))?.isFile()){let d=await(t.fetchResponse??ru)(`${e.tagUrl}/SHA256SUMS`,Oi),u=d.ok?ny(await d.text(),e.asset):void 0;if(!u)throw new Error("no published checksum");await eu(Er(c),a),await iV(Er(c));let p=`${c}.part-${process.pid}`;try{await(t.download??ay)(`${e.tagUrl}/${e.asset}`,p,u),await JE(p,493),await qd(p,c)}catch(f){throw await Et(p,{force:!0}).catch(()=>{}),f}}return await(t.activate??tx)(o,c),{link:o,target:c,versionsDir:r}},uV=async e=>{YE(e.target,[Fd,e.link],{stdio:"ignore",timeout:Oi})},pV=async e=>{let t=YE(e,["--version"],{stdio:"ignore",timeout:Oi});return!t.error&&t.status===0},fV=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??Be)(async()=>e);if(!o||!(await(t.repair??Mt)(r,o.target)).every(po))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??tr)()).ok)},mV=async e=>{let t=await e.install();if(!await(e.smoke??pV)(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},hV=async(e,t)=>{let n=await nu(e).catch(()=>[]);for(let r of n)t.includes(r)||await Et(Fe(e,r),{force:!0,recursive:!0}).catch(()=>{})},yV=async e=>{let t=await nu(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Et(Fe(e,n),{force:!0}).catch(()=>{})},gV=async(e,t)=>{let n=async()=>{await Et(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await ty(e,{recursive:!1}),n}catch{}let r=await XE(e).catch(()=>{});if(!(!r||t-r.mtimeMs<eV)){await n();try{return await ty(e,{recursive:!1}),n}catch{return}}},qh=e=>Fe(e,"update-state.json"),wV=async e=>{let t=await B(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},La=async(e={})=>{let t=e.now??Date.now,n=Ae;if(Sn(nn(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ft(),o=e.root??Q(),a;try{let s=await ry(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=e.force===!0,l=await(e.load??D)().catch(()=>({})),d=l.autoUpdate!==!1;!i&&s.link&&!e.checkOnly&&(d||c)&&await lV(o,s.link,e).catch(()=>{});let u=QE(e.platform??process.platform,e.arch??process.arch);if(!u)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??oy)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let p=a;if(!i&&p===n)return{outcome:"current",current:n,latest:p};if(i&&Pa(p,n)<0)return{outcome:"migration-deferred",current:n,latest:p};let f=await wV(qh(o));if((e.respectFailureBackoff===!0||!c)&&f.failedVersion===p&&f.failedAt!==void 0&&t()-f.failedAt<Q1)return{outcome:"failed",current:n,latest:p};let m=`${zE}/download/${qE}${p}`,h=d||c?void 0:await(e.minimumVersion??aV)(m),w={current:n,latest:p,autoUpdate:d,forced:c,minVersion:h},y=i?nV(w):{...ex(w),downgradeBlocked:!1};if(y.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:p};if(!y.apply)return{outcome:"disabled",current:n,latest:p};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:p,mandatory:y.mandatory};o===Q()?await tt():await eu(o,sy(o,Q()));let g=await gV(Fe(o,"update.lock"),t());if(!g)return{outcome:i?"migration-available":"available",current:n,latest:p};let b,k;try{await yV(Fe(o,"bin"));let C=await tu(Fe(o,"versions")).catch(()=>{}),S=await tu(Fe(o,"bin",Da())).catch(()=>{}),I=S&&Qi(S,C)?S:void 0,E=Fe(o,"bin",Da());i&&process.platform==="win32"&&(await ey(E).catch(()=>{}))?.isFile()&&(k=`${E}.rollback-${process.pid}`,await Qh(E,k));let R=()=>(e.installBinary??dV)({root:o,version:p,asset:u,tagUrl:m});i?b=await mV({install:R,smoke:e.smoke,rollback:async({link:P,target:W})=>{k?(await Qh(k,P),await Et(qa(P),{force:!0}).catch(()=>{})):I&&I!==W?await tx(P,I):(await Et(P,{force:!0}),await Et(qa(P),{force:!0}).catch(()=>{}))},repoint:async P=>e.repoint?e.repoint(l,P):fV(l),prune:async()=>{await(e.pruneDurable??(P=>ec(P)))(r)}}):b=await R(),await hV(b.versionsDir,[p,n]),await(e.refreshHelpersFromInstalled??uV)(b).catch(()=>{}),await Et(qh(o),{force:!0}).catch(()=>{})}finally{k&&await Et(k,{force:!0}).catch(()=>{}),await g()}return{outcome:i?"migrated":"updated",current:n,latest:p,managedPath:b.link,mandatory:y.mandatory}}catch{return a&&await Y(qh(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},nx=async(e={})=>{let t=e.context??ft(),n=await ry(t,e.root??Q()),r=Ro(e.root??Q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Ae,managedPath:n.link??r}:La({...e,context:t,allowNpmMigration:!0})},wo=async(e={})=>{let t=e.context??ft(),n=e.root??Q(),r=await ry(t,n),o=r.kind==="npm"||r.kind==="durable"?Ro(n):void 0,a=await(e.load??D)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!QE(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=Sn(nn(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:Ae,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};import{z as rx}from"zod";var bV=5e3,AV=rx.object({lane:rx.enum(["subscription","org"]).optional().catch(void 0)}),ox=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??bV);try{let a=await(n.fetchResponse??fetch)(`${e.replace(/\/$/,"")}/connect/policy`,{headers:{"x-anyray-api-key":t.trim()},signal:r.signal});if(!a.ok)return;let s=AV.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},ax=(e,t)=>{if(!e||t.byoUpstream)return{overrodeFlag:!1};let n=t.subscription?"subscription":t.org?"org":void 0;return{lane:e,overrodeFlag:n!=null&&n!==e}};var CV=12e3,kV="anyray-wiring-probe-not-a-real-token",vV={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},cy={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},bo=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},ix=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},ly=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},sx=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."],SV=e=>e.includes("no provider key configured for"),dy=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},uy=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>"]}),Ti=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."]}),IV=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:SV(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${bo(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")?sx([" \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."]]}:e===401||e===403?dy(t)?uy(e):ly(t)?Ti(e):ix(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${bo(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)."]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${bo(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).",...sx([" \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}: ${bo(t)}`,remedy:[]},EV=(e,t)=>{if(ly(t))return Ti(e);if(dy(t))return uy(e);if(ix(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}: ${bo(t)}`,remedy:[]}},xV=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),RV=(e,t)=>{if(ly(t))return Ti(e);if(dy(t))return uy(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")||xV(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}: ${bo(t)}`,remedy:[`The probe asks for a fixed model (${cy.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."]}},iy=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)}},OV=async(e,t)=>{if(!e.clientKey)return Ti(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?Ti(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${bo(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},TV=(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."]}},_i=async(e,t={})=>{let n=t.timeoutMs??CV,r=ue(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await OV(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 iy(`${e.anthropicBaseUrl}/v1/messages`,l,cy,n);return RV(d,u)}if(ee(e,"anthropic")){let l={Authorization:`Bearer ${kV}`,"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 iy(`${e.anthropicBaseUrl}/v1/messages`,l,cy,n);return EV(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await iy(`${e.openaiBaseUrl}/chat/completions`,s,vV,n);return IV(i,c,t.tools??[])}catch(o){return TV(n,o)}};var cx=async e=>{let t=await D(),n;try{n=vr(e.gateway,t)}catch(o){return A(V("Anyray connect \u2014 status")),$(`Gateway: ${o.message}`),0}A(V("Anyray connect \u2014 status")),U("Gateway"),A(` Origin: ${et(n)}`),t.gateway?$(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?$(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||$(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),U("Identity"),A(` Name: ${t.name??v("(not set)")}`),A(` Team: ${t.team??v("(not set)")}`);let r=nn();r&&(U("Environment"),A(` Remote dev context: ${To(r)}`),Sn(r)&&$(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),$(" VS Code tools configure the remote server variant backing this window.")),t.enrolledCert&&t.clientKey&&(U("Credential renewal"),M(" Direct gateway routing with a proof-backed key heartbeat."),$(" Renewal extends the same key; tool configuration is not rewritten.")),U("Tools");for(let o of le){if(!(await o.detect()).installed){$(` ${o.title}: not installed`);continue}if(!o.pointsAt){$(` ${o.title}: installed ${v("(status not introspectable)")}`);continue}let s=await o.pointsAt(n);if(s){if(o.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){M(` ${o.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}M(` ${o.title}: pointed at Anyray`)}else{let i=null,c=null;if(o.id===Ra&&o.mcpStatus)try{let l=(await o.mcpStatus()).registered,d=await Ld();i=Nd({id:o.id,installed:!0,pointedAt:s,mcpRegistered:l,introspectable:d.authoritative}),c={...d.authoritative?{}:{reason:d.reason},mcpRegistered:l}}catch{i=null,c=null}if((i==="not-routed"||i==="unverifiable")&&c){let l=$d(i,c);_(` ${o.title}: ${l.headline}`);for(let d of l.detail)A(v(` ${d}`))}else $(` ${o.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as jV}from"node:fs";import{isAbsolute as ZV}from"node:path";import{access as _V}from"node:fs/promises";import{constants as PV}from"node:fs";import{platform as DV}from"node:os";var LV=async e=>{try{return await _V(e,PV.F_OK),!0}catch{return!1}},NV=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"]:[],Ao=async(e={})=>{let t=e.os??DV(),n=e.exists??LV;for(let r of NV(t))if(await n(r))return!0;return!1};import{execFile as $V}from"node:child_process";import{readFile as MV}from"node:fs/promises";import{homedir as BV,platform as FV}from"node:os";import{promisify as WV}from"node:util";var HV=WV($V),UV="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",lx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),GV=async e=>{let t;try{t=await MV(e,"utf-8")}catch(n){return n?.code==="ENOENT"?{readable:!0}:{readable:!1}}try{if(t.trim()==="")return{readable:!0};let n=wt(t);if(!lx(n))return{readable:!1};let r=n[dn],o=n[un];return{readable:!0,supportsAnyray:lx(r)?r[z]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},VV=async(e=async()=>(await HV("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(FV()==="win32")return"unknown";let t;try{t=await e()}catch{return"unknown"}let n=!1;for(let r of t.split(`
693
- `)){let o=new RegExp(`${UV}=(\\w*)`).exec(r);if(!o)continue;let a=r.replace(/\bVSCODE_[A-Z0-9_]*=\S*/g,"");if(/Code Helper|MacOS\/Code|VSCodium|Visual Studio Code|agentHost/i.test(a)&&(n=!0,o[1]==="true"))return"on"}return n?"off":"unknown"},KV=e=>e.mode!=="copilot-seat"?"not-applicable":e.settings.readable?e.settings.supportsAnyray!==!0||e.settings.bridgeEnabled!==!0?"not-configured":e.bridge==="off"?"awaiting-relaunch":"ready":"unknown",ou=(e,t)=>{switch(e){case"ready":return t==="on"?"Agents window: Anyray models available (agent host is running with the model bridge on).":"Agents window: configured. No running agent host was found to confirm it, so it applies from the next VS Code start.";case"awaiting-relaunch":return"Agents window: configured, but the agent host running right now started before it. Quit and relaunch VS Code once; a window reload will not do it, because that process outlives every window.";case"not-configured":return`Agents window: not enabled. Re-run anyray-connect --tools copilot, then quit and relaunch VS Code (it sets ${dn} and ${un}; if you switched either off yourself, that choice is left alone).`;case"unknown":return"Agents window: could not read VS Code settings.json, so its state is unknown. Nothing is reported as missing on that basis.";case"not-applicable":return"Agents window: not applicable on this machine."}},dx=async(e={})=>{let{installedVariant:t=Ho,receiptMode:n=nl,awaitingReload:r=tl,readSettings:o=GV,probeBridge:a=VV,home:s=BV()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:ou("not-applicable","unknown")};let c=await n(i,s);if(c!=="copilot-seat"){let p=c===void 0&&await r(i,s);return{state:p?"unknown":"not-applicable",bridge:"unknown",detail:p?"Agents window: VS Code has an Anyray configuration staged but not applied yet, so its state is unknown. Restart VS Code to finish.":ou("not-applicable","unknown")}}let l=await o(xs(i)),d=await a(),u=KV({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:ou(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:ou("not-applicable","unknown")}}};var qt="connect",py=e=>e.replace(/-/g,"_"),ux=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:qt,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:qt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:qt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:qt,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:qt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:qt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=py(e.retrieval.kind);t.push({tool:qt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":py(e.verify.kind);t.push({tool:qt,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:qt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:py(e.hookLane.reason)}:{}})}t.push({tool:qt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:qt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function YV(){return Ae}var JV="ctx_doctor-probe-synthetic",XV=(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: ${hy(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 zV(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function qV(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function hy(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 px=e=>Nd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),fy=e=>e.pointedAt===!1&&e.tombstoned!==!0&&px(e)!=="unverifiable",fx=e=>e.registered&&e.command&&ZV(e.command)?jV(e.command):null,my=e=>(fy(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),QV=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,eK=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},mx=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},tK=(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(ho),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,y])=>({checkId:w,at:y})),p=n(l.flapping)?l.flapping:void 0,f=Array.isArray(p?.checks)?p.checks.filter(w=>typeof w=="string"&&a.has(w)):[],m=p?.reason==="rebroke_same_day"||p?.reason==="repeat_days"?p.reason:void 0,h=p&&r(p.since)&&m&&f.length>0?{since:p.since,reason:m,checks:f}:void 0;(u.length>0||h)&&s.push({tool:c,repaired:u,...h?{flapping:h}:{}})}return s},nK=async(e,t,n,r,o,a,s=n,i=_i,c=!0,l=Po,d=wo,u=It,p=Sa)=>{let f=c?await Jd(e):null,m=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,h=j=>j&&_h(j)?"machine_default":null,w=t.enrolledCert?.payload,y=w?.expiresAt??t.enrolledCertExpiry??null,b=(await a())?.sso??null,k=qV({ssoLink:b,enrolledViaToken:!!t.enrolledTokenHash}),C=gt(),S=await Lw(C),I=S?[]:Nc(xe({origin:e})),E=[];for(let j of r){let _e=await j.detect(),ke=null;if(_e.installed&&j.mcpStatus)try{let Ka=await j.mcpStatus();ke={...Ka,commandOk:fx(Ka)}}catch{}let Xe=_e.installed&&j.id===Ra?await o():void 0,pt=_e.installed&&j.pointsAt?await j.pointsAt(e):null,Tr=await QV(pt,j,t.managedTools??[]),Gi=pt===!1&&Tr===null,Ha=Tr===!1&&j.routingPendingReload?await j.routingPendingReload().catch(()=>!1):!1,Vi=_e.installed?j.runtimeDiagnostics?await j.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:j.routingOverrides?await j.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Ua,claudeCodeHookPolicy:Ga}=Vi,Va=t.fleetToolPolicy,ko=Va?.enabled.includes(j.id)?Va.tiers?.[j.id]??wa:void 0;E.push({id:j.id,title:j.title,installed:_e.installed,..._e.detail?{detail:_e.detail}:{},pointedAt:Tr,...Gi?{routingHeld:!0}:{},...Ha?{routingPendingReload:!0}:{},...Ua.length?{routingOverrides:Ua}:{},...Ga===void 0?{}:{claudeCodeHookPolicy:Ga},mcp:ke,...ko?{policyTier:ko}:{},...t.revertedTools?.includes(j.id)?{tombstoned:!0}:{},...j.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...Xe===void 0?{}:{inferenceIntrospectable:Xe.authoritative,...Xe.authoritative?{}:{inferenceUnverifiableReason:Xe.reason}}})}let R=s?await(async()=>{let{kind:j,detail:_e,remedy:ke}=await i(xe({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:j,detail:_e,remedy:ke}})():null,P=R?.kind==="provider-rejected"&&await eK(t.managedTools??[],r),W=R?{...R,...P?{notApplicableSubscription:!0}:{}}:null,q=n?XV(await va({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:ue({user:t.name,team:t.team})},JV,{probe:!0}),{mode:k,ssoLink:b}):null,de=await u().catch(()=>({})),ie=An(de.hookLane),K=s?await mx(r):!1,ge=K?await(async()=>{let j=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...bh(j,{hookRegistered:K,neverInvoked:gh(ie,Date.now())}),lastInvokedAt:Cd(ie)}})():null,me=(await rr()).map(j=>({adapter:j.adapter,op:j.op,requestedAt:j.requestedAt,watcherAlive:ar(j.watcherPid)})),F=me.find(j=>j.adapter==="cursor"),Z=F?{op:F.op,requestedAt:F.requestedAt,watcherAlive:F.watcherAlive}:null,X=!!t.refreshSchedulerEnabled,Je=await _o(),We=await d(),T=t.persistenceOwner==="tray",L=T?await l(t)==="healthy":null,J=await Cw({schedulerEnabled:X&&!T,schedulerInstalled:Je,binaryDurable:!Ue(er())}),pe=0;f&&!f.reachable&&(pe+=1),T?X&&!L&&(pe+=1):X&&!Je&&(pe+=1);for(let j of E)pe+=my(j);W&&W.kind!=="ok"&&!W.notApplicableSubscription&&(pe+=1),q&&q.kind!=="ok"&&(pe+=1),ge?.verdict==="dark"&&(pe+=1),I.length>0&&(pe+=1),pe+=me.filter(j=>!j.watcherAlive).length;let ut=await dx();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:YV(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:nn(),selfUpdate:{managed:We.managed,available:We.available,autoUpdate:We.autoUpdate,state:We.state}},gateway:{origin:e,reachable:f?f.reachable:null,detail:f?f.detail:"not probed (--quick)"},refreshScheduler:{enabled:X,installed:Je,owner:T?"tray":"os",...T?{trayHealthy:!!L}:{}},serviceRemoval:J,fleetdPresent:await Ao(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:m,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:h(t.name)},enrollment:{enrolled:!!w,deploymentId:w?.deploymentId??null,issuedAt:w?.issuedAt??null,expiresAt:y,expired:y?Date.parse(y)<Date.now():null,orgMode:k,ssoLink:b},shell:{profilePath:C,blockPresent:S,staleExports:I},tools:E,...t.fleetToolPolicy?{fleetPlan:bd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Z,pendingOps:me,ambientRepairs:tK(de,r),verify:W,retrieval:q,hookLane:ge,agentsWindow:ut,problems:pe}},rK=e=>{if(e.serviceRemoval.suspected){U("Endpoint security"),_(" Anyray installed these background services, but their files are gone from disk \u2014"),_(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),_(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)A(v(` missing: ${t}`));A(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),A(v(" tools straight at the gateway (your key then needs a periodic re-run).")),A(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),A(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},oK=e=>{switch(A(V("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(U("Environment"),A(` Remote dev context: ${To(e.connect.remoteContext)}`),Sn(e.connect.remoteContext)&&A(v(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),U("CLI updates"),e.connect.selfUpdate.state){case"managed":M(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||_(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":_(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),A(v(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":_(" Self-update is unavailable on this platform because no standalone binary is published."),A(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":A(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":A(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(U("Gateway"),e.gateway.reachable===null?A(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?M(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(O(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),A(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(U("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?M(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(O(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),A(v(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?M(" 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")||A(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),rK(e),U("Personal key"),zV(e)){case"env":M(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":M(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":_(" Enrolled, but no personal key is cached locally right now."),A(v(" 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:_(" Enrollment required \u2014 no personal gateway key is available."),A(v(` Fix: ${hy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?_(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):M(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(U("Shell"),O(" This terminal still exports Anyray, but the config is gone."),A(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),A(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),A(v(" Anything you start from this terminal keeps reaching the gateway with")),A(v(" no credential, and fails with 401.")),A(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),A(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),A(v(" reuses the environment it captured at launch, so a new terminal")),A(v(" (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};U("Claude Code hook policy"),O(` ${sc(c)}.`),A(v(` ${ic(c)}`))}U("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])O(` ${c.title}: ${l.problem}.`),A(v(` ${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}).`),A(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):M(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(_(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(" 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){A(v(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){A(v(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){M(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}M(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" 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===Ra&&A(v(` ${PC}`)),c.id==="codex"&&A(v(" 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=px(c);if(l==="not-routed"||l==="unverifiable"){let d=$d(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});_(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(_(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?_(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):A(v(` ${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`),A(v(" 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}`),A(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(_(" No tools are pointed at this gateway yet."),A(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){U("Queued operations");for(let c of e.pendingOps){let l=mt(c.adapter)?.title??c.adapter;c.watcherAlive?_(` ${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.`),A(v(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){U("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=mt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:f,at:m})=>`${c(f)} ${new Date(m).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let p=` ${d}: ${u.join("; ")}`;l.flapping?_(p):A(p)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){U("Fleet policy");let c=l=>l.map(d=>mt(d)?.title??d).join(", ");i.freshIds.length>0&&A(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&_(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(U("Auth probe"),e.verify.notApplicableSubscription)M(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")M(` ${e.verify.detail}`);else{O(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)A(v(` ${c}`))}if(e.retrieval)if(U("Retrieval loop"),e.retrieval.kind==="ok")M(` ${e.retrieval.detail}`);else{O(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)A(v(` ${c}`))}if(e.hookLane){if(U("Hook lane"),e.hookLane.verdict==="live")M(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){O(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}else{_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}e.hookLane.lastInvokedAt!==null&&A(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(U("VS Code Agents window"),_(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(U("VS Code Agents window"),M(` ${e.agentsWindow.detail}`)),U("Summary"),e.problems===0?(e.verify?M(" No problems found."):M(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):O(` ${e.problems} problem(s) found \u2014 see fixes above.`)},aK=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}),sK=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!mh(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??Sa,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??zt)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=An((await(t.readRefreshState??It)().catch(()=>({}))).hookLane),l=bh(i,{hookRegistered:await mx(t.adapters??le).catch(()=>!1),neverInvoked:gh(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:Cd(c)},note:d}},iK=async(e,t,n={})=>{let r=n.adapters??le,o=n.resolveTarget??Be,a=n.applyTools??Mt,s=await sK(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(g=>g.installed&&(fy(g)||g.mcp?.commandOk===!1||g.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);if(!d)return{entries:l.map(g=>({id:g.id,title:g.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 ${hy(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),p=[],f=[...c.notes],m=[];for(let g of l){let b=r.find(k=>k.id===g.id);if(!u.has(g.id)||!b){p.push({id:g.id,title:g.title,status:"skipped-unmanaged"});continue}m.push(b)}p.length>0&&f.push("Drifted tools outside the managed record are never auto-repaired \u2014 run `anyray-connect` once to (re)configure and record them.");let h=await a(m,d.target),w=new Map,y=0;for(let g of h){if(p.push(g),!po(g))continue;let b=e.tools.find(P=>P.id===g.id);if(!b)continue;let k=r.find(P=>P.id===g.id),C=b.mcp;if(k?.mcpStatus)try{let P=await k.mcpStatus();C={...P,commandOk:fx(P)}}catch{}let S=fy(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{S=await k.pointsAt(e.gateway.origin)}catch{}let I=b.routingOverrides,E=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let P=await k.runtimeDiagnostics();I=P.routingOverrides.length?P.routingOverrides:void 0,E=P.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let P=await k.routingOverrides();I=P.length?P:void 0}catch{}let R={...b,pointedAt:S,mcp:C,...I?{routingOverrides:I}:{},...E===void 0?{}:{claudeCodeHookPolicy:E}};I||delete R.routingOverrides,E===void 0&&delete R.claudeCodeHookPolicy,w.set(g.id,R),y+=my(b)-my(R)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:f}},cK=e=>{U("Repair"),e.entries.length===0&&M(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?M(` ${t.title}: re-applied`):t.status==="queued"?M(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):O(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},au=async(e,t={})=>{let n=await D();if(e.securityReview){if(!e.silent){A(V("Anyray connect \u2014 security review"));for(let c of kw())A(c?` ${c}`:"")}return 0}let r;try{r=vr(e.gateway,n)}catch(c){return e.silent?1:e.json?(console.log(JSON.stringify({error:c.message})),1):(A(V("Anyray connect \u2014 doctor")),O(` Gateway URL: ${c.message}`),A(v(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.silent||(e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(A(V("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 nK(r,n,!!e.verify&&!e.quick,t.adapters??le,t.inferenceIntrospection??Ld,t.fleetBootstrap??Ar,o,t.verifyAuth??_i,!e.quick,t.checkTray??Po,t.updateStatus??wo,t.readRefreshState??It,t.probeHookLane??Sa),s=e.repair?await iK(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;t.captureReport?.(i),e.silent||(e.json?console.log(JSON.stringify(aK(i),null,2)):(oK(i),s&&cK(s)));try{e.quick||await(t.reportHealth??ZS)(ux(i),i.connect.version)}catch{}return i.problems===0?0:1};var lK=()=>{let e=[];for(let t of le){let n=t.skillsDir?.();n&&e.push(n)}return e},hx=async e=>{let t=await D();A(V("Anyray connect \u2014 sync"));let n;try{n=vr(e.gateway,t)}catch(s){return O(s.message),1}$(`Gateway: ${n}`);let r=HI(t.clientKey,"anyray-placeholder"),o;try{o=await Aa(n,r)}catch(s){return O(`Team policy sync failed: ${uh(s)}`),1}let a=lK();if(a.length===0)dK();else if(o.skills.length===0)$("No team skills published yet \u2014 nothing to sync.");else{let s=await DS(o,a,t.syncedSkills??{});U("Skills");for(let i of s.results)i.written?M(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):$(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await oe({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){$(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}U("Summary"),A(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Ca(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(A(`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&&$(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){$(`Fleet policy reconcile skipped: ${uh(s)}`)}return 0},dK=()=>{$("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as mj}from"node:zlib";import{promisify as hj}from"node:util";var xr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},yy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),yx=e=>`
688
+ `).join("")),o.write(`\x1B[${i}A`))},p=!!r.isRaw,f=!1;try{return f=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((m,h)=>{let w=()=>{r.off("data",C),r.off("end",b),r.off("close",b),r.off("error",k)},y=S=>{w(),m(S)},g=S=>{w(),h(S)},b=()=>y({kind:"cancelled"}),k=S=>g(S),C=S=>{try{for(let I of eV(S)){if(I===""||I==="\x1B"||I==="q"){y({kind:"cancelled"});return}if(e.items.length===0){(I==="\r"||I===`
689
+ `)&&y({kind:"ok",values:[]});continue}if(I==="\x1B[A"||I==="k")s=(s-1+e.items.length)%e.items.length,d();else if(I==="\x1B[B"||I==="j")s=(s+1)%e.items.length,d();else if(I===" "){if(e.single){let E=!a[s];a.fill(!1),a[s]=E}else a[s]=!a[s];d()}else if(I==="a"&&!e.single){let E=e.items.map((N,U)=>({item:N,index:U})).filter(({item:N})=>N.requiresExplicitChoice!==!0),R=!E.every(({index:N})=>a[N]);for(let{index:N}of E)a[N]=R;d()}else if(I==="\r"||I===`
690
+ `){y({kind:"ok",values:e.items.filter((E,R)=>a[R]).map(E=>E.value)});return}}}catch(I){g(I)}};r.on("data",C),r.on("end",b),r.on("close",b),r.on("error",k)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),f&&r.setRawMode(p)}catch{}n.close()}};var zE=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],tV=80,Ei=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&ha(r,n.env??process.env)))return r.write(`${e}
691
+ `),t();let a=0,s=()=>{r.write(`\r${zE[a++%zE.length]} ${e}`)};s();let i=setInterval(s,tV);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as nV}from"node:fs";import{spawnSync as qE}from"node:child_process";import{chmod as QE,copyFile as ty,lstat as ny,mkdir as ry,readdir as tu,realpath as eu,rename as zd,rm as Et,stat as ex,symlink as rV,writeFile as oV}from"node:fs/promises";import{createHash as aV}from"node:crypto";import{basename as qd,dirname as xr,join as Fe}from"node:path";import{Readable as sV}from"node:stream";import{pipeline as iV}from"node:stream/promises";var tx="https://github.com/anyrayHQ/install/releases",nx="connect-v",cV=new RegExp(`/releases/tag/${nx}([0-9][0-9A-Za-z.-]*)$`),lV=300*1024*1024,Oi=1e4,dV=5*6e4,uV=360*6e4,pV=30*6e4,Pa=(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)},rx=(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"}},fV=e=>{if(e)return cV.exec(e.trim())?.[1]},oy=(e,t)=>{for(let n of e.split(`
692
+ `)){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()}},ox=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&&Pa(e.current,e.minVersion)<0&&Pa(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},mV=e=>Pa(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}:{...ox(e),downgradeBlocked:!1},Da=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",hV=(e=process.execPath)=>{let t=Wu(e);return t?xr(t):xr(xr(e))},yV=async(e=ft())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=Fe(hV(e.execPath),"bin",Da());try{if(await eu(t)!==await eu(e.execPath))return}catch{return}return t},ay=async(e=ft(),t=Q())=>{let n=await yV(e);if(n)return{kind:"managed",root:xr(xr(n)),link:n,entryPath:jn(e)};let r=jn(e);return Hu(r,t)?{kind:"durable",root:t,entryPath:r}:Bu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},nu=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)}},sy=async(e=Oi)=>{let t=await nu(`${tx}/latest`,e,{redirect:"manual"});return fV(t.headers.get("location"))},gV=async e=>{try{let t=await nu(`${e}/connect-update.json`,Oi);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}},Ri=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},iy=async(e,t,n)=>{let r=await nu(e,dV);if(!r.ok||!r.body)throw new Ri(r.status);let o=aV("sha256"),a=0;if(await iV(sV.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>lV)throw new Error("asset exceeds size cap");o.update(c),yield c}},nV(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},wV=e=>qd(e)===Da()?qd(xr(e)):qd(e),bV=async e=>{let t=await tu(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Et(Fe(e,n),{force:!0}).catch(()=>{})},ax=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Et(r,{force:!0}).catch(()=>{});let o=!1;try{await zd(e,r),o=!0}catch{}try{await ty(t,e),await oV(qa(e),wV(t))}catch(a){throw o&&await zd(r,e).catch(()=>{}),a}await Et(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Et(n,{force:!0}),await rV(t,n),await zd(n,e)},AV=".anyray",cy=(e,t)=>e===t||qd(e)===AV?448:493,xi=async(e,t)=>{let n=(await ex(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await QE(e,n&4095|t).catch(()=>{})},Qd=async(e,t)=>{await ry(e,{recursive:!0,mode:t}),await xi(e,t)},CV=async(e,t,n)=>{let r=cy(e,Q());if(r!==448){let o=Fe(e,"versions");await xi(e,r),await xi(Fe(e,"bin"),r),await xi(o,r);for(let a of await tu(o).catch(()=>[]))await xi(Fe(o,a),r)}await(n.refreshDesktopHelpers??Gd)(t)},kV=async(e,t={})=>{let n=Fe(e.root,"bin"),r=Fe(e.root,"versions"),o=Fe(n,Da()),a=cy(e.root,(t.privateRoot??Q)());await Qd(n,a),await Qd(r,a);let s=Fe(r,e.version),c=(await ny(s).catch(()=>{}))?.isFile()?s:Fe(s,Da());if(!(await ny(c).catch(()=>{}))?.isFile()){let d=await(t.fetchResponse??nu)(`${e.tagUrl}/SHA256SUMS`,Oi),u=d.ok?oy(await d.text(),e.asset):void 0;if(!u)throw new Error("no published checksum");await Qd(xr(c),a),await bV(xr(c));let p=`${c}.part-${process.pid}`;try{await(t.download??iy)(`${e.tagUrl}/${e.asset}`,p,u),await QE(p,493),await zd(p,c)}catch(f){throw await Et(p,{force:!0}).catch(()=>{}),f}}return await(t.activate??ax)(o,c),{link:o,target:c,versionsDir:r}},vV=async e=>{qE(e.target,[Wd,e.link],{stdio:"ignore",timeout:Oi})},SV=async e=>{let t=qE(e,["--version"],{stdio:"ignore",timeout:Oi});return!t.error&&t.status===0},IV=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??Be)(async()=>e);if(!o||!(await(t.repair??Bt)(r,o.target)).every(po))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??nr)()).ok)},EV=async e=>{let t=await e.install();if(!await(e.smoke??SV)(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},xV=async(e,t)=>{let n=await tu(e).catch(()=>[]);for(let r of n)t.includes(r)||await Et(Fe(e,r),{force:!0,recursive:!0}).catch(()=>{})},RV=async e=>{let t=await tu(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Et(Fe(e,n),{force:!0}).catch(()=>{})},OV=async(e,t)=>{let n=async()=>{await Et(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await ry(e,{recursive:!1}),n}catch{}let r=await ex(e).catch(()=>{});if(!(!r||t-r.mtimeMs<pV)){await n();try{return await ry(e,{recursive:!1}),n}catch{return}}},ey=e=>Fe(e,"update-state.json"),TV=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}},La=async(e={})=>{let t=e.now??Date.now,n=Ae;if(In(nn(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ft(),o=e.root??Q(),a;try{let s=await ay(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=e.force===!0,l=await(e.load??P)().catch(()=>({})),d=l.autoUpdate!==!1;!i&&s.link&&!e.checkOnly&&(d||c)&&await CV(o,s.link,e).catch(()=>{});let u=rx(e.platform??process.platform,e.arch??process.arch);if(!u)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??sy)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let p=a;if(!i&&p===n)return{outcome:"current",current:n,latest:p};if(i&&Pa(p,n)<0)return{outcome:"migration-deferred",current:n,latest:p};let f=await TV(ey(o));if((e.respectFailureBackoff===!0||!c)&&f.failedVersion===p&&f.failedAt!==void 0&&t()-f.failedAt<uV)return{outcome:"failed",current:n,latest:p};let m=`${tx}/download/${nx}${p}`,h=d||c?void 0:await(e.minimumVersion??gV)(m),w={current:n,latest:p,autoUpdate:d,forced:c,minVersion:h},y=i?mV(w):{...ox(w),downgradeBlocked:!1};if(y.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:p};if(!y.apply)return{outcome:"disabled",current:n,latest:p};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:p,mandatory:y.mandatory};o===Q()?await tt():await Qd(o,cy(o,Q()));let g=await OV(Fe(o,"update.lock"),t());if(!g)return{outcome:i?"migration-available":"available",current:n,latest:p};let b,k;try{await RV(Fe(o,"bin"));let C=await eu(Fe(o,"versions")).catch(()=>{}),S=await eu(Fe(o,"bin",Da())).catch(()=>{}),I=S&&Qi(S,C)?S:void 0,E=Fe(o,"bin",Da());i&&process.platform==="win32"&&(await ny(E).catch(()=>{}))?.isFile()&&(k=`${E}.rollback-${process.pid}`,await ty(E,k));let R=()=>(e.installBinary??kV)({root:o,version:p,asset:u,tagUrl:m});i?b=await EV({install:R,smoke:e.smoke,rollback:async({link:N,target:U})=>{k?(await ty(k,N),await Et(qa(N),{force:!0}).catch(()=>{})):I&&I!==U?await ax(N,I):(await Et(N,{force:!0}),await Et(qa(N),{force:!0}).catch(()=>{}))},repoint:async N=>e.repoint?e.repoint(l,N):IV(l),prune:async()=>{await(e.pruneDurable??(N=>ec(N)))(r)}}):b=await R(),await xV(b.versionsDir,[p,n]),await(e.refreshHelpersFromInstalled??vV)(b).catch(()=>{}),await Et(ey(o),{force:!0}).catch(()=>{})}finally{k&&await Et(k,{force:!0}).catch(()=>{}),await g()}return{outcome:i?"migrated":"updated",current:n,latest:p,managedPath:b.link,mandatory:y.mandatory}}catch{return a&&await Y(ey(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},sx=async(e={})=>{let t=e.context??ft(),n=await ay(t,e.root??Q()),r=Ro(e.root??Q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Ae,managedPath:n.link??r}:La({...e,context:t,allowNpmMigration:!0})},wo=async(e={})=>{let t=e.context??ft(),n=e.root??Q(),r=await ay(t,n),o=r.kind==="npm"||r.kind==="durable"?Ro(n):void 0,a=await(e.load??P)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!rx(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=In(nn(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:Ae,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};import{z as ix}from"zod";var _V=5e3,PV=ix.object({lane:ix.enum(["subscription","org"]).optional().catch(void 0)}),cx=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??_V);try{let a=await(n.fetchResponse??fetch)(`${e.replace(/\/$/,"")}/connect/policy`,{headers:{"x-anyray-api-key":t.trim()},signal:r.signal});if(!a.ok)return;let s=PV.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},lx=(e,t)=>{if(!e||t.byoUpstream)return{overrodeFlag:!1};let n=t.subscription?"subscription":t.org?"org":void 0;return{lane:e,overrodeFlag:n!=null&&n!==e}};var DV=12e3,LV="anyray-wiring-probe-not-a-real-token",NV={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},dy={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},bo=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},ux=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},uy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},dx=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."],$V=e=>e.includes("no provider key configured for"),py=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},fy=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>"]}),Ti=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."]}),MV=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:$V(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${bo(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")?dx([" \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."]]}:e===401||e===403?py(t)?fy(e):uy(t)?Ti(e):ux(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${bo(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)."]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${bo(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).",...dx([" \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}: ${bo(t)}`,remedy:[]},BV=(e,t)=>{if(uy(t))return Ti(e);if(py(t))return fy(e);if(ux(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}: ${bo(t)}`,remedy:[]}},FV=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),WV=(e,t)=>{if(uy(t))return Ti(e);if(py(t))return fy(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")||FV(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}: ${bo(t)}`,remedy:[`The probe asks for a fixed model (${dy.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."]}},ly=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)}},UV=async(e,t)=>{if(!e.clientKey)return Ti(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?Ti(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${bo(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},HV=(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."]}},_i=async(e,t={})=>{let n=t.timeoutMs??DV,r=ue(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await UV(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 ly(`${e.anthropicBaseUrl}/v1/messages`,l,dy,n);return WV(d,u)}if(ee(e,"anthropic")){let l={Authorization:`Bearer ${LV}`,"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 ly(`${e.anthropicBaseUrl}/v1/messages`,l,dy,n);return BV(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await ly(`${e.openaiBaseUrl}/chat/completions`,s,NV,n);return MV(i,c,t.tools??[])}catch(o){return HV(n,o)}};var px=async e=>{let t=await P(),n;try{n=Sr(e.gateway,t)}catch(o){return A(V("Anyray connect \u2014 status")),$(`Gateway: ${o.message}`),0}A(V("Anyray connect \u2014 status")),H("Gateway"),A(` Origin: ${et(n)}`),t.gateway?$(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?$(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||$(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),H("Identity"),A(` Name: ${t.name??v("(not set)")}`),A(` Team: ${t.team??v("(not set)")}`);let r=nn();r&&(H("Environment"),A(` Remote dev context: ${To(r)}`),In(r)&&$(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),$(" VS Code tools configure the remote server variant backing this window.")),t.enrolledCert&&t.clientKey&&(H("Credential renewal"),B(" Direct gateway routing with a proof-backed key heartbeat."),$(" Renewal extends the same key; tool configuration is not rewritten.")),H("Tools");for(let o of le){if(!(await o.detect()).installed){$(` ${o.title}: not installed`);continue}if(!o.pointsAt){$(` ${o.title}: installed ${v("(status not introspectable)")}`);continue}let s=await o.pointsAt(n);if(s){if(o.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){B(` ${o.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}B(` ${o.title}: pointed at Anyray`)}else{let i=null,c=null;if(o.id===Ra&&o.mcpStatus)try{let l=(await o.mcpStatus()).registered,d=await Nd();i=$d({id:o.id,installed:!0,pointedAt:s,mcpRegistered:l,introspectable:d.authoritative}),c={...d.authoritative?{}:{reason:d.reason},mcpRegistered:l}}catch{i=null,c=null}if((i==="not-routed"||i==="unverifiable")&&c){let l=Md(i,c);_(` ${o.title}: ${l.headline}`);for(let d of l.detail)A(v(` ${d}`))}else $(` ${o.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as oK}from"node:fs";import{isAbsolute as aK}from"node:path";import{access as GV}from"node:fs/promises";import{constants as VV}from"node:fs";import{platform as KV}from"node:os";var jV=async e=>{try{return await GV(e,VV.F_OK),!0}catch{return!1}},ZV=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"]:[],Ao=async(e={})=>{let t=e.os??KV(),n=e.exists??jV;for(let r of ZV(t))if(await n(r))return!0;return!1};import{execFile as YV}from"node:child_process";import{readFile as JV}from"node:fs/promises";import{homedir as XV,platform as zV}from"node:os";import{promisify as qV}from"node:util";var QV=qV(YV),eK="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",fx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tK=async e=>{let t;try{t=await JV(e,"utf-8")}catch(n){return n?.code==="ENOENT"?{readable:!0}:{readable:!1}}try{if(t.trim()==="")return{readable:!0};let n=wt(t);if(!fx(n))return{readable:!1};let r=n[dn],o=n[un];return{readable:!0,supportsAnyray:fx(r)?r[z]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},nK=async(e=async()=>(await QV("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(zV()==="win32")return"unknown";let t;try{t=await e()}catch{return"unknown"}let n=!1;for(let r of t.split(`
693
+ `)){let o=new RegExp(`${eK}=(\\w*)`).exec(r);if(!o)continue;let a=r.replace(/\bVSCODE_[A-Z0-9_]*=\S*/g,"");if(/Code Helper|MacOS\/Code|VSCodium|Visual Studio Code|agentHost/i.test(a)&&(n=!0,o[1]==="true"))return"on"}return n?"off":"unknown"},rK=e=>e.mode!=="copilot-seat"?"not-applicable":e.settings.readable?e.settings.supportsAnyray!==!0||e.settings.bridgeEnabled!==!0?"not-configured":e.bridge==="off"?"awaiting-relaunch":"ready":"unknown",ru=(e,t)=>{switch(e){case"ready":return t==="on"?"Agents window: Anyray models available (agent host is running with the model bridge on).":"Agents window: configured. No running agent host was found to confirm it, so it applies from the next VS Code start.";case"awaiting-relaunch":return"Agents window: configured, but the agent host running right now started before it. Quit and relaunch VS Code once; a window reload will not do it, because that process outlives every window.";case"not-configured":return`Agents window: not enabled. Re-run anyray-connect --tools copilot, then quit and relaunch VS Code (it sets ${dn} and ${un}; if you switched either off yourself, that choice is left alone).`;case"unknown":return"Agents window: could not read VS Code settings.json, so its state is unknown. Nothing is reported as missing on that basis.";case"not-applicable":return"Agents window: not applicable on this machine."}},mx=async(e={})=>{let{installedVariant:t=Uo,receiptMode:n=nl,awaitingReload:r=tl,readSettings:o=tK,probeBridge:a=nK,home:s=XV()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:ru("not-applicable","unknown")};let c=await n(i,s);if(c!=="copilot-seat"){let p=c===void 0&&await r(i,s);return{state:p?"unknown":"not-applicable",bridge:"unknown",detail:p?"Agents window: VS Code has an Anyray configuration staged but not applied yet, so its state is unknown. Restart VS Code to finish.":ru("not-applicable","unknown")}}let l=await o(xs(i)),d=await a(),u=rK({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:ru(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:ru("not-applicable","unknown")}}};var qt="connect",my=e=>e.replace(/-/g,"_"),hx=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:qt,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:qt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:qt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:qt,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:qt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:qt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=my(e.retrieval.kind);t.push({tool:qt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":my(e.verify.kind);t.push({tool:qt,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:qt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:my(e.hookLane.reason)}:{}})}t.push({tool:qt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:qt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function sK(){return Ae}var iK="ctx_doctor-probe-synthetic",cK=(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: ${gy(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 lK(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function dK(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function gy(e,t){let n=`\`anyray-connect --sso ${t??"<link>"}\``,r="`anyray-connect --enroll <link>`";switch(e){case"sso":return`enroll via SSO with ${n}`;case"passwordless":return`enroll with the link from your admin (${r})`;default:return`enroll \u2014 SSO org: use ${n}; passwordless org: use ${r} (link from your admin)`}}var yx=e=>$d({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),hy=e=>e.pointedAt===!1&&e.tombstoned!==!0&&yx(e)!=="unverifiable",gx=e=>e.registered&&e.command&&aK(e.command)?oK(e.command):null,uK=e=>{switch(e.mcp?.reason){case"ephemeral-runtime":return"this Connect is running from a temporary npx/cache path, so a registration naming it would rot \u2014 install it durably (`curl -fsSL https://app.anyray.ai/connect.sh | sh`) and re-run.";case"no-config":return`${e.title} has not written its config yet \u2014 launch it once, then re-run \`anyray-connect\`.`;case"stale":return"the entry was written by an older Connect \u2014 re-run `anyray-connect` to refresh it.";case"foreign":return"an MCP server named `anyray` that Connect did not write is already there, and it was left untouched. Rename or remove it, then re-run `anyray-connect`.";case"unreadable":return`${e.title}'s config could not be read or parsed \u2014 repair it (or check its permissions), then re-run \`anyray-connect\`.`;case"absent":return"re-run `anyray-connect` to register it.";default:return"re-run `anyray-connect` to register it."}},yy=e=>(hy(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),pK=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,fK=async(e,t)=>{if(e.length===0)return!1;for(let n of e){let r=t.find(a=>a.id===n);if(!r?.inferenceAuthLanes)return!1;let o=await r.inferenceAuthLanes().catch(()=>["unknown"]);if(o.length===0||o.some(a=>a!=="subscription"&&a!=="native"))return!1}return!0},wx=async e=>{for(let t of e)if(t.integrationStatus)try{if(!(await t.detect()).installed)continue;if((await t.integrationStatus()).hook_registration==="owned")return!0}catch{}return!1},mK=(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(ho),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,y])=>({checkId:w,at:y})),p=n(l.flapping)?l.flapping:void 0,f=Array.isArray(p?.checks)?p.checks.filter(w=>typeof w=="string"&&a.has(w)):[],m=p?.reason==="rebroke_same_day"||p?.reason==="repeat_days"?p.reason:void 0,h=p&&r(p.since)&&m&&f.length>0?{since:p.since,reason:m,checks:f}:void 0;(u.length>0||h)&&s.push({tool:c,repaired:u,...h?{flapping:h}:{}})}return s},hK=async(e,t,n,r,o,a,s=n,i=_i,c=!0,l=Po,d=wo,u=It,p=Sa)=>{let f=c?await Xd(e):null,m=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,h=j=>j&&Oh(j)?"machine_default":null,w=t.enrolledCert?.payload,y=w?.expiresAt??t.enrolledCertExpiry??null,b=(await a())?.sso??null,k=dK({ssoLink:b,enrolledViaToken:!!t.enrolledTokenHash}),C=gt(),S=await Mw(C),I=S?[]:Nc(xe({origin:e})),E=[];for(let j of r){let _e=await j.detect(),ke=null;if(_e.installed&&j.mcpStatus)try{let Ka=await j.mcpStatus();ke={...Ka,commandOk:gx(Ka)}}catch{}let Xe=_e.installed&&j.id===Ra?await o():void 0,pt=_e.installed&&j.pointsAt?await j.pointsAt(e):null,_r=await pK(pt,j,t.managedTools??[]),Gi=pt===!1&&_r===null,Ua=_r===!1&&j.routingPendingReload?await j.routingPendingReload().catch(()=>!1):!1,Vi=_e.installed?j.runtimeDiagnostics?await j.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:j.routingOverrides?await j.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Ha,claudeCodeHookPolicy:Ga}=Vi,Va=t.fleetToolPolicy,ko=Va?.enabled.includes(j.id)?Va.tiers?.[j.id]??wa:void 0;E.push({id:j.id,title:j.title,installed:_e.installed,..._e.detail?{detail:_e.detail}:{},pointedAt:_r,...Gi?{routingHeld:!0}:{},...Ua?{routingPendingReload:!0}:{},...Ha.length?{routingOverrides:Ha}:{},...Ga===void 0?{}:{claudeCodeHookPolicy:Ga},mcp:ke,...ko?{policyTier:ko}:{},...t.revertedTools?.includes(j.id)?{tombstoned:!0}:{},...j.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...Xe===void 0?{}:{inferenceIntrospectable:Xe.authoritative,...Xe.authoritative?{}:{inferenceUnverifiableReason:Xe.reason}}})}let R=s?await(async()=>{let{kind:j,detail:_e,remedy:ke}=await i(xe({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:j,detail:_e,remedy:ke}})():null,N=R?.kind==="provider-rejected"&&await fK(t.managedTools??[],r),U=R?{...R,...N?{notApplicableSubscription:!0}:{}}:null,q=n?cK(await va({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:ue({user:t.name,team:t.team})},iK,{probe:!0}),{mode:k,ssoLink:b}):null,de=await u().catch(()=>({})),ce=An(de.hookLane),K=s?await wx(r):!1,ge=K?await(async()=>{let j=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...gh(j,{hookRegistered:K,neverInvoked:hh(ce,Date.now())}),lastInvokedAt:kd(ce)}})():null,me=(await or()).map(j=>({adapter:j.adapter,op:j.op,requestedAt:j.requestedAt,watcherAlive:sr(j.watcherPid)})),F=me.find(j=>j.adapter==="cursor"),Z=F?{op:F.op,requestedAt:F.requestedAt,watcherAlive:F.watcherAlive}:null,X=!!t.refreshSchedulerEnabled,Je=await _o(),We=await d(),T=t.persistenceOwner==="tray",D=T?await l(t)==="healthy":null,J=await Sw({schedulerEnabled:X&&!T,schedulerInstalled:Je,binaryDurable:!He(tr())}),pe=0;f&&!f.reachable&&(pe+=1),T?X&&!D&&(pe+=1):X&&!Je&&(pe+=1);for(let j of E)pe+=yy(j);U&&U.kind!=="ok"&&!U.notApplicableSubscription&&(pe+=1),q&&q.kind!=="ok"&&(pe+=1),ge?.verdict==="dark"&&(pe+=1),I.length>0&&(pe+=1),pe+=me.filter(j=>!j.watcherAlive).length;let ut=await mx();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:sK(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:nn(),selfUpdate:{managed:We.managed,available:We.available,autoUpdate:We.autoUpdate,state:We.state}},gateway:{origin:e,reachable:f?f.reachable:null,detail:f?f.detail:"not probed (--quick)"},refreshScheduler:{enabled:X,installed:Je,owner:T?"tray":"os",...T?{trayHealthy:!!D}:{}},serviceRemoval:J,fleetdPresent:await Ao(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:m,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:h(t.name)},enrollment:{enrolled:!!w,deploymentId:w?.deploymentId??null,issuedAt:w?.issuedAt??null,expiresAt:y,expired:y?Date.parse(y)<Date.now():null,orgMode:k,ssoLink:b},shell:{profilePath:C,blockPresent:S,staleExports:I},tools:E,...t.fleetToolPolicy?{fleetPlan:Ad(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Z,pendingOps:me,ambientRepairs:mK(de,r),verify:U,retrieval:q,hookLane:ge,agentsWindow:ut,problems:pe}},yK=e=>{if(e.serviceRemoval.suspected){H("Endpoint security"),_(" Anyray installed these background services, but their files are gone from disk \u2014"),_(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),_(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)A(v(` missing: ${t}`));A(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),A(v(" tools straight at the gateway (your key then needs a periodic re-run).")),A(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),A(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},gK=e=>{switch(A(V("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(H("Environment"),A(` Remote dev context: ${To(e.connect.remoteContext)}`),In(e.connect.remoteContext)&&A(v(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),H("CLI updates"),e.connect.selfUpdate.state){case"managed":B(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||_(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":_(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),A(v(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":_(" Self-update is unavailable on this platform because no standalone binary is published."),A(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":A(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":A(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(H("Gateway"),e.gateway.reachable===null?A(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?B(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(O(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),A(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(H("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(O(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),A(v(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?B(" 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")||A(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),yK(e),H("Personal key"),lK(e)){case"env":B(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":B(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":_(" Enrolled, but no personal key is cached locally right now."),A(v(" 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:_(" Enrollment required \u2014 no personal gateway key is available."),A(v(` Fix: ${gy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?_(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):B(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(H("Shell"),O(" This terminal still exports Anyray, but the config is gone."),A(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),A(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),A(v(" Anything you start from this terminal keeps reaching the gateway with")),A(v(" no credential, and fails with 401.")),A(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),A(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),A(v(" reuses the environment it captured at launch, so a new terminal")),A(v(" (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};H("Claude Code hook policy"),O(` ${sc(c)}.`),A(v(` ${ic(c)}`))}H("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])O(` ${c.title}: ${l.problem}.`),A(v(` ${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}).`),A(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):B(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(_(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(` Fix: ${uK(c)}`))))};for(let c of e.tools){if(!c.installed){A(v(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){A(v(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){B(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}B(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" 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===Ra&&A(v(` ${NC}`)),c.id==="codex"&&A(v(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=yx(c);if(l==="not-routed"||l==="unverifiable"){let d=Md(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});_(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(_(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?_(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):A(v(` ${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`),A(v(" 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}`),A(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(_(" No tools are pointed at this gateway yet."),A(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){H("Queued operations");for(let c of e.pendingOps){let l=mt(c.adapter)?.title??c.adapter;c.watcherAlive?_(` ${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.`),A(v(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){H("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=mt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:f,at:m})=>`${c(f)} ${new Date(m).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let p=` ${d}: ${u.join("; ")}`;l.flapping?_(p):A(p)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){H("Fleet policy");let c=l=>l.map(d=>mt(d)?.title??d).join(", ");i.freshIds.length>0&&A(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&_(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(H("Auth probe"),e.verify.notApplicableSubscription)B(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")B(` ${e.verify.detail}`);else{O(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)A(v(` ${c}`))}if(e.retrieval)if(H("Retrieval loop"),e.retrieval.kind==="ok")B(` ${e.retrieval.detail}`);else{O(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)A(v(` ${c}`))}if(e.hookLane){if(H("Hook lane"),e.hookLane.verdict==="live")B(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){O(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}else{_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}e.hookLane.lastInvokedAt!==null&&A(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(H("VS Code Agents window"),_(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(H("VS Code Agents window"),B(` ${e.agentsWindow.detail}`)),H("Summary"),e.problems===0?(e.verify?B(" No problems found."):B(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):O(` ${e.problems} problem(s) found \u2014 see fixes above.`)},wK=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}),bK=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!ph(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??Sa,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??zt)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=An((await(t.readRefreshState??It)().catch(()=>({}))).hookLane),l=gh(i,{hookRegistered:await wx(t.adapters??le).catch(()=>!1),neverInvoked:hh(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}},AK=async(e,t,n={})=>{let r=n.adapters??le,o=n.resolveTarget??Be,a=n.applyTools??Bt,s=await bK(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(g=>g.installed&&(hy(g)||g.mcp?.commandOk===!1||g.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);if(!d)return{entries:l.map(g=>({id:g.id,title:g.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 ${gy(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),p=[],f=[...c.notes],m=[];for(let g of l){let b=r.find(k=>k.id===g.id);if(!u.has(g.id)||!b){p.push({id:g.id,title:g.title,status:"skipped-unmanaged"});continue}m.push(b)}p.length>0&&f.push("Drifted tools outside the managed record are never auto-repaired \u2014 run `anyray-connect` once to (re)configure and record them.");let h=await a(m,d.target),w=new Map,y=0;for(let g of h){if(p.push(g),!po(g))continue;let b=e.tools.find(N=>N.id===g.id);if(!b)continue;let k=r.find(N=>N.id===g.id),C=b.mcp;if(k?.mcpStatus)try{let N=await k.mcpStatus();C={...N,commandOk:gx(N)}}catch{}let S=hy(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{S=await k.pointsAt(e.gateway.origin)}catch{}let I=b.routingOverrides,E=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let N=await k.runtimeDiagnostics();I=N.routingOverrides.length?N.routingOverrides:void 0,E=N.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let N=await k.routingOverrides();I=N.length?N:void 0}catch{}let R={...b,pointedAt:S,mcp:C,...I?{routingOverrides:I}:{},...E===void 0?{}:{claudeCodeHookPolicy:E}};I||delete R.routingOverrides,E===void 0&&delete R.claudeCodeHookPolicy,w.set(g.id,R),y+=yy(b)-yy(R)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:f}},CK=e=>{H("Repair"),e.entries.length===0&&B(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?B(` ${t.title}: re-applied`):t.status==="queued"?B(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):O(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},ou=async(e,t={})=>{let n=await P();if(e.securityReview){if(!e.silent){A(V("Anyray connect \u2014 security review"));for(let c of Iw())A(c?` ${c}`:"")}return 0}let r;try{r=Sr(e.gateway,n)}catch(c){return e.silent?1:e.json?(console.log(JSON.stringify({error:c.message})),1):(A(V("Anyray connect \u2014 doctor")),O(` Gateway URL: ${c.message}`),A(v(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.silent||(e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(A(V("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 hK(r,n,!!e.verify&&!e.quick,t.adapters??le,t.inferenceIntrospection??Nd,t.fleetBootstrap??Cr,o,t.verifyAuth??_i,!e.quick,t.checkTray??Po,t.updateStatus??wo,t.readRefreshState??It,t.probeHookLane??Sa),s=e.repair?await AK(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;t.captureReport?.(i),e.silent||(e.json?console.log(JSON.stringify(wK(i),null,2)):(gK(i),s&&CK(s)));try{e.quick||await(t.reportHealth??XS)(hx(i),i.connect.version)}catch{}return i.problems===0?0:1};var kK=()=>{let e=[];for(let t of le){let n=t.skillsDir?.();n&&e.push(n)}return e},bx=async e=>{let t=await P();A(V("Anyray connect \u2014 sync"));let n;try{n=Sr(e.gateway,t)}catch(s){return O(s.message),1}$(`Gateway: ${n}`);let r=VI(t.clientKey,"anyray-placeholder"),o;try{o=await Aa(n,r)}catch(s){return O(`Team policy sync failed: ${lh(s)}`),1}let a=kK();if(a.length===0)vK();else if(o.skills.length===0)$("No team skills published yet \u2014 nothing to sync.");else{let s=await $S(o,a,t.syncedSkills??{});H("Skills");for(let i of s.results)i.written?B(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):$(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await ae({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){$(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}H("Summary"),A(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Ca(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(A(`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&&$(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){$(`Fleet policy reconcile skipped: ${lh(s)}`)}return 0},vK=()=>{$("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as x2}from"node:zlib";import{promisify as R2}from"node:util";var Rr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},wy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),Ax=e=>`
694
694
 
695
695
  \u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
696
696
 
697
- `,su=(e,t={})=>{if(typeof e!="string")return yy(String(e??""));let n=Math.max(1,t.maxChars??xr.maxChars);if(e.length<=n)return yy(e);let r=e.length,o=Math.max(0,t.headChars??xr.headChars),a=Math.max(0,t.tailChars??xr.tailChars),s=Math.max(0,t.middleWindows??xr.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 p=c-o-a;if(s>0&&p>0&&d>l){let y=d-l,g=Math.max(1,Math.floor(p/s));for(let b=0;b<s;b++){let k=l+Math.round((b+.5)/s*y),C=Math.min(d,Math.max(l,k)+Math.ceil(g/2)),S=Math.max(l,C-g),I=e.lastIndexOf(`
697
+ `,au=(e,t={})=>{if(typeof e!="string")return wy(String(e??""));let n=Math.max(1,t.maxChars??Rr.maxChars);if(e.length<=n)return wy(e);let r=e.length,o=Math.max(0,t.headChars??Rr.headChars),a=Math.max(0,t.tailChars??Rr.tailChars),s=Math.max(0,t.middleWindows??Rr.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 p=c-o-a;if(s>0&&p>0&&d>l){let y=d-l,g=Math.max(1,Math.floor(p/s));for(let b=0;b<s;b++){let k=l+Math.round((b+.5)/s*y),C=Math.min(d,Math.max(l,k)+Math.ceil(g/2)),S=Math.max(l,C-g),I=e.lastIndexOf(`
698
698
  `,S);I>=l&&(S=I+1);let E=e.indexOf(`
699
- `,C);E!==-1&&E<d&&(C=E),C>S&&u.push([S,C])}}a>0&&u.push([d,r]),u.sort((y,g)=>y[0]-g[0]);let f=[];for(let[y,g]of u){let b=f[f.length-1];b&&y<=b[1]?b[1]=Math.max(b[1],g):f.push([y,g])}let m="",h=0;for(let[y,g]of f)y>h&&(m+=yx(y-h)),m+=e.slice(y,g),h=g;if(r>h&&(m+=yx(r-h)),m.length>=r)return yy(e);let w=r-m.length;return{text:m,trimmed:!0,originalChars:r,trimmedChars:m.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},uK=["stdout","content","output","text","result"],gx=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} ---
699
+ `,C);E!==-1&&E<d&&(C=E),C>S&&u.push([S,C])}}a>0&&u.push([d,r]),u.sort((y,g)=>y[0]-g[0]);let f=[];for(let[y,g]of u){let b=f[f.length-1];b&&y<=b[1]?b[1]=Math.max(b[1],g):f.push([y,g])}let m="",h=0;for(let[y,g]of f)y>h&&(m+=Ax(y-h)),m+=e.slice(y,g),h=g;if(r>h&&(m+=Ax(r-h)),m.length>=r)return wy(e);let w=r-m.length;return{text:m,trimmed:!0,originalChars:r,trimmedChars:m.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},SK=["stdout","content","output","text","result"],Cx=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
700
  ${d}`);s&&i.push(`--- MCP structuredContent ---
701
701
  ${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
702
702
 
703
- `),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((p,f)=>l.has(f)?f!==c?.index?[]:[{...c.part,text:d}]:[p]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=uK.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 pK=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},Pi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},iu=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Pi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Pi.minDataLineRatio,o=t.minDataLines??Pi.minDataLines,a=e.split(`
704
- `),s=0,i=0;for(let c of a)c.trim()&&(s++,pK(c)&&i++);return s===0||i<o?!1:i/s>=r};var Di=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,cu={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"},Ax=new Set(["npm","pnpm","yarn","bun"]),lu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},fK=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=lu(r[0]);if(o in cu)return cu[o];if((o==="npx"||o==="bunx")&&r[1]){let a=lu(r[1]);if(a in cu)return cu[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||Ax.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},wy=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=fK(t);if(n)return n}return null},mK={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},hK=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,yK=(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},Cx=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=lu(r[0]);if(Ax.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&hK.test(i)}let a=r[1]?lu(r[1]):void 0;if(yK(o,a,r))return!1;let s=mK[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},gK=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==="]"},wK=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},bK=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=wK(t);return r>0&&t[r+1]===":"},AK=80,CK=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/AK),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,bK(e[o])&&r++;return n>0&&r/n>.3},kK=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,vK=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();(kK.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},SK=[/\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],gy=8192,IK=e=>{let t=e.length>2*gy?`${e.slice(0,gy)}
705
- ${e.slice(-gy)}`:e;return SK.some(n=>n.test(t))},EK=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),xK=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),RK=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},OK=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),wx=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(xK(i)){t.push(Di(i));continue}let c=RK(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Di(c)),o=12;continue}EK(i)||OK(i)||o>0&&(t.push(Di(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
706
- `),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},TK=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,kx=e=>{let t=TK.exec(e);return t&&/[/.]/.test(t[1])?t:null},_K=/^([^\s:]+)-(\d+)-/,PK=e=>{if(e==="--")return!0;let t=_K.exec(e);return t!=null&&/[/.]/.test(t[1])},DK=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>kx(r)!=null).length;return n>=3&&n/t.length>=.7},bx=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=kx(c);if(!l){if(PK(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(Di(` ${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(`
707
- `),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},LK=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(),NK=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=LK(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=Di(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
708
- `),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},vx=(e,t)=>{if(typeof t!="string"||t.length===0||gK(t))return null;let n=t.split(`
709
- `).filter(s=>s.trim()!==""),r=wy(e),o=IK(t),a=null;return r==="test-run"&&o?a=wx(n):r==="grep"&&(a=bx(n,.5)),a||(o?a=wx(n):DK(n)?a=bx(n,.7):!vK(n)&&!CK(n)&&(a=NK(n))),!a||a.text.length>=t.length?null:a},Sx=e=>`full output: Read ${e}`,by=(e,t)=>t?`
710
-
711
- \u2026[anyray-hook digest \u2014 ${e}; ${Sx(t)}]\u2026`:`
712
-
713
- \u2026[anyray-hook digest \u2014 ${e}]\u2026`,Ix=e=>`
714
-
715
- \u2026[anyray-hook \u2014 ${Sx(e)}]\u2026`;import{createHash as $K}from"node:crypto";import{homedir as MK}from"node:os";import{join as Rr}from"node:path";import{chmod as BK,mkdir as FK,readdir as Ox,stat as Ni,unlink as Li,utimes as WK,writeFile as Cy}from"node:fs/promises";var du={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},Tx=".swept",HK=".sweeping",Ex=64,xx=448,ky=384,vy=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",_x=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,Sy=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=Q();try{if((await Ni(t)).isDirectory())return Rr(t,"hook-tee")}catch{}return Rr(MK(),".anyray-hook-tee")},UK=/^(?:ctx_)?([0-9a-f]{16})$/,Iy=e=>e.trim().match(UK)?.[1]??null,Ey=async e=>{let t=Iy(e);return t?Rr(await Sy(),`${t}.txt`):null},GK=async(e,t={})=>{let n=t.limits??du;try{let r=Date.now(),o=(await Ox(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=Ex)await Promise.all(o.slice(c,c+Ex).map(async l=>{let d=Rr(e,l);try{let u=await Ni(d);if(!u.isFile())return;let p=r-u.mtimeMs>n.ttlMs||r-_x(u)>n.maxAgeMs;if(d!==t.protect&&p){await Li(d);return}a.push({path:d,mtimeMs:u.mtimeMs,size:u.size})}catch{}}));a.sort((c,l)=>l.mtimeMs-c.mtimeMs);let s=0,i=0;for(let c of a){let l=s<n.maxFiles&&i+c.size<=n.maxTotalBytes,d=r-c.mtimeMs<n.writeGraceMs;if(l||s===0||c.path===t.protect||d){s+=1,i+=c.size;continue}await Li(c.path).catch(()=>{})}}catch{}},Px=async e=>{try{return Date.now()-(await Ni(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},Rx=async e=>{try{return await Cy(e,"",{mode:ky,flag:"wx"}),!0}catch{return!1}},VK=async(e,t)=>{let n=du,r=Rr(e,HK),o=Rr(e,Tx);if(!await Rx(r)){let a=0;try{a=Date.now()-(await Ni(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await Li(r).catch(()=>{}),!await Rx(r)))return!1}try{return await Px(o)<n.sweepIntervalMs?!1:(await Cy(o,"",{mode:ky}).catch(()=>{}),await GK(e,{protect:t}),!0)}finally{await Li(r).catch(()=>{})}},Ay=async(e,t)=>await Px(Rr(e,Tx))<du.sweepIntervalMs?!1:VK(e,t),KK=async()=>{try{let e=await Sy();if(!(await Ox(e)).some(t=>t.endsWith(".txt")))return;await Ay(e)}catch{}},Dx=async e=>{if(vy())return await KK(),null;try{let t=await Sy();await FK(t,{recursive:!0,mode:xx}),await BK(t,xx).catch(()=>{});let n=`${$K("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=Rr(t,n),o=Date.now();try{let a=await Ni(r);if(a.isFile()){if(o-_x(a)<=du.maxAgeMs){let s=new Date(o);return await WK(r,s,s).catch(()=>{}),await Ay(t,r),r}await Li(r).catch(()=>{})}}catch{}return await Cy(r,e,{mode:ky}),await Ay(t,r),r}catch{return null}};import{createHash as jK}from"node:crypto";import{homedir as Lx}from"node:os";import{join as xy}from"node:path";import{readFile as ZK,writeFile as YK,chmod as JK,stat as XK,unlink as zK}from"node:fs/promises";var qK=200,QK=1440*60*1e3,ej=4e6,Nx=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",$x=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},tj=()=>$x("ANYRAY_HOOK_CACHE_MAX_ENTRIES",qK),Mx=()=>$x("ANYRAY_HOOK_CACHE_TTL_MS",QK),Bx=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=xy(Lx(),".anyray");try{if((await XK(t)).isDirectory())return xy(t,"hook-cache.json")}catch{}return xy(Lx(),".anyray-hook-cache.json")},Fx=(e,t,n)=>jK("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),Wx=async e=>{try{let t=JSON.parse(await ZK(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},Hx=async e=>{if(Nx())return null;try{let n=(await Wx(await Bx())).entries[e];return!n||Date.now()-n.at>Mx()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},nj=e=>{let t=Date.now(),n=Mx(),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=tj();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>ej&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},Ux=async(e,t)=>{if(Nx())return;let n;try{let r=await Bx(),o=await Wx(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=nj(o.entries),n=`${r}.${process.pid}.tmp`,await YK(n,JSON.stringify(o),{mode:384}),await JK(n,384),await he(n,r)}catch{if(n)try{await zK(n)}catch{}}};import{open as rj,stat as oj}from"node:fs/promises";var Gx=600,aj=3,sj=256e3,ij=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(`
716
- `):"",cj=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),lj=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},dj=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=ij(o.message?.content).trim();if(!(!a||cj(a))&&(t.unshift(a),n+=a.length,t.length>=aj||n>=Gx))break}return t.join(`
717
- `).slice(0,Gx)};var uj=e=>/(^|[\\/])subagents[\\/]/i.test(e),pj=e=>/\.jsonl$/i.test(e),fj=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),Vx=async e=>{let t={intent:"",kind:"unknown"};if(!e||!pj(e))return t;let n;try{let{size:r}=await oj(e),o=Math.max(0,r-sj),a=r-o;if(a<=0)return t;n=await rj(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(`
718
- `);i=l>=0?i.slice(l+1):""}let c=lj(i.split(`
719
- `));return fj(c)?{intent:dj(c),kind:uj(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var yj=3e3,gj=1500,wj=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:yj},bj={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},Aj=new Set(["claude","opencode"]),Cj=(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:bj[t]})},kj={cacheGet:async()=>null,cachePut:async()=>{}},vj=(e,t={cacheGet:Hx,cachePut:Ux,tee:Dx})=>e==="claude"?t:kj,Sj=1e3,Ij=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),uu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ej=e=>{try{let t=JSON.parse(e);if(!uu(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 uu(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},xj=e=>{try{let t=JSON.parse(e);return uu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},Rj=e=>uu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
720
- `:"",Ry=e=>Math.round(Math.max(0,e)/4),Kx=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",Oj=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),Tj=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),_j=["tool_output","tool_response","tool_result"],Pj=e=>{for(let t of _j)if(t in e)return e[t]},Dj=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},Lj=120,Nj=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??Sj))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=by(r.stat,null).length+Lj;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=by(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}}},$j=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let S=JSON.parse(e);if(!S||typeof S!="object")return n;r=S}catch{return n}let o=typeof r.tool_name=="string"?r.tool_name:"unknown";if(Oj.has(o)||Tj(o))return n;let a=gx(Pj(r));if(!a)return n;let s=async S=>{try{await t.beacon(o,S)}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(jx(o)&&l.retrievalContext!=="available")return n;let d=await Nj(t,Dj(o,r.tool_input),i),u=d?.body??i,p=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!iu(i,{minChars:gj})))return n;let f=i.length-u.length-p.length,m=async(S,I,E=S.length+p.length)=>{let R=d?.teePath??null;if(!R&&t.tee)try{R=await t.tee(i)}catch{R=null}let P=R?S.replaceAll("; not retrievable in this context]","]"):S,W=R&&!p?Ix(R):"",q=P+p+W,de=W.length,ie=q;if(t.finalizeOutput)try{let F=t.finalizeOutput(q);F.length<=q.length&&(ie=F)}catch{ie=q}let K=q.length-ie.length,ge=Ry(Math.max(0,f-de))+I+Ry(K);ge>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,E+de-K),estTokensSaved:ge,...d&&{digest:d.decision}});let me=a.rebuild(ie);return{stdout:Ij(me),replacement:me}},h=async()=>d?m(u,0):n;if(d&&u.length<=t.sizeGate)return m(u,0);let w=l.intent?`${l.intent}
721
- ${Kx(r.tool_input)}`:Kx(r.tool_input),y=Fx(o,w,u),g=async S=>{try{await t.cachePut(y,S)}catch{}},b=null;try{b=await t.cacheGet(y)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?m(b.output,b.tokensSaved):h();let k=null;try{k=Uj(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{k=null}if(k&&!k.handled&&(k=null),k)return k.optimized&&k.output.length<u.length?(await g({optimized:!0,output:k.output,tokensSaved:Ry(u.length-k.output.length)}),m(k.output,0,u.length+p.length)):(await g({optimized:!1}),h());let C;try{C=t.localTrim(u)}catch{return h()}return C.trimmed?m(C.text,C.estTokensSaved):h()},$i=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},Mj=()=>{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")}},Bj=hj(mj),Fj=async e=>{try{let t=await Bj(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},jx=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),Wj=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},Hj=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),Uj=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),Gj=2048,Vj=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,Gj),n=Ad(t);if(!n)return;await bI({at:Date.now(),status:e.status,code:n})}catch{}},Kj=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),wj());try{let c=await Fj(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...jx(t)||Wj(t)&&a==="available"?{reversible:!0}:{},...Hj(t)?{semanticRerank:!0}:{},output:r})),l=Vt(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 Vj(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)}},Zx=async(e="claude")=>{let t=await $i();if(e!=="cursor"&&xj(t))return 0;let n=e==="cursor"?Ej(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Oy(n,e);if(e==="cursor"){let a=Rj(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Oy=async(e,t="claude",n)=>{await kr(),await wI(t);let r=Mj(),o=await nt(),a=o&&{...o,metadata:Cj(o.metadata,t)},s=vj(t);return $j(e,{optimize:(i,c,l,d,u)=>Kj(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await Vx(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>su(i,r),beacon:(i,c)=>lc(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??xr.maxChars,digestCommand:vx,tee:s.tee,mediumBand:Aj.has(t),finalizeOutput:n})};var Yx=async()=>0;import{spawn as qj}from"node:child_process";import{homedir as Qj}from"node:os";import{join as e2}from"node:path";import{chmod as jj,readFile as Zj,rm as Jx,writeFile as Yj}from"node:fs/promises";import{join as Jj}from"node:path";var Ty=()=>Jj(Q(),"sso-gate.json"),Xj=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))},Na=async()=>{try{let e=JSON.parse(await Zj(Ty(),"utf-8"));return Xj(e)?e:null}catch{return null}},zj=0,pu=async e=>{await tt();let t=Ty(),n=`${t}.${process.pid}.${zj++}.tmp`;try{await Yj(n,`${JSON.stringify(e)}
722
- `,{mode:384}),await jj(n,384),await he(n,t)}catch(r){throw await Jx(n,{force:!0}).catch(()=>{}),r}},Xx=async()=>{await Jx(Ty(),{force:!0}).catch(()=>{})},zx=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"}};var t2=3e4,n2=5*6e4,r2=30*6e4,o2=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},a2=()=>e2(Qj(),".claude","settings.json"),s2=async e=>{try{let n=(await B(a2())).env;if(!n)return!1;let r=tn(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}},i2=async e=>{await qn.apply(e,{dryRun:!1})},c2=()=>{let{command:e,args:t}=Qn("__anyray-sso-poll");return{exe:e,args:t}},l2=()=>{let{exe:e,args:t}=c2(),n=qj(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))}}},d2=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},qx=(e,t,n,r)=>xe({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),$a=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},Qx=e=>`Anyray: one-time sign-in required to use AI tools on this device.
703
+ `),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((p,f)=>l.has(f)?f!==c?.index?[]:[{...c.part,text:d}]:[p]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=SK.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 IK=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},Pi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},su=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Pi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Pi.minDataLineRatio,o=t.minDataLines??Pi.minDataLines,a=e.split(`
704
+ `),s=0,i=0;for(let c of a)c.trim()&&(s++,IK(c)&&i++);return s===0||i<o?!1:i/s>=r};var Di=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,iu={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"},Sx=new Set(["npm","pnpm","yarn","bun"]),cu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},EK=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=cu(r[0]);if(o in iu)return iu[o];if((o==="npx"||o==="bunx")&&r[1]){let a=cu(r[1]);if(a in iu)return iu[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||Sx.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},Ay=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=EK(t);if(n)return n}return null},xK={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},RK=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,OK=(e,t,n)=>{let r=(...o)=>n.some(a=>o.includes(a));return(e==="docker"||e==="podman"||e==="kubectl")&&t==="logs"||e==="journalctl"?r("-f","--follow"):e==="kubectl"&&t==="get"||e==="tsc"?r("-w","--watch"):!1},Ix=e=>{if(typeof e!="string"||!e.trim())return!1;let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return!1;let o=cu(r[0]);if(Sx.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&RK.test(i)}let a=r[1]?cu(r[1]):void 0;if(OK(o,a,r))return!1;let s=xK[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},TK=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==="]"},_K=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},PK=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=_K(t);return r>0&&t[r+1]===":"},DK=80,LK=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/DK),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,PK(e[o])&&r++;return n>0&&r/n>.3},NK=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,$K=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();(NK.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},MK=[/\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],by=8192,BK=e=>{let t=e.length>2*by?`${e.slice(0,by)}
705
+ ${e.slice(-by)}`:e;return MK.some(n=>n.test(t))},FK=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),WK=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),UK=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},HK=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),kx=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(WK(i)){t.push(Di(i));continue}let c=UK(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Di(c)),o=12;continue}FK(i)||HK(i)||o>0&&(t.push(Di(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
706
+ `),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},GK=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,Ex=e=>{let t=GK.exec(e);return t&&/[/.]/.test(t[1])?t:null},VK=/^([^\s:]+)-(\d+)-/,KK=e=>{if(e==="--")return!0;let t=VK.exec(e);return t!=null&&/[/.]/.test(t[1])},jK=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>Ex(r)!=null).length;return n>=3&&n/t.length>=.7},vx=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=Ex(c);if(!l){if(KK(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(Di(` ${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(`
707
+ `),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},ZK=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(),YK=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=ZK(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=Di(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
708
+ `),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},xx=(e,t)=>{if(typeof t!="string"||t.length===0||TK(t))return null;let n=t.split(`
709
+ `).filter(s=>s.trim()!==""),r=Ay(e),o=BK(t),a=null;return r==="test-run"&&o?a=kx(n):r==="grep"&&(a=vx(n,.5)),a||(o?a=kx(n):jK(n)?a=vx(n,.7):!$K(n)&&!LK(n)&&(a=YK(n))),!a||a.text.length>=t.length?null:a},Rx=e=>`full output: Read ${e}`,Cy=(e,t)=>t?`
710
+
711
+ \u2026[anyray-hook digest \u2014 ${e}; ${Rx(t)}]\u2026`:`
712
+
713
+ \u2026[anyray-hook digest \u2014 ${e}]\u2026`,Ox=e=>`
714
+
715
+ \u2026[anyray-hook \u2014 ${Rx(e)}]\u2026`;import{createHash as JK}from"node:crypto";import{homedir as XK}from"node:os";import{join as Or}from"node:path";import{chmod as zK,mkdir as qK,readdir as Dx,stat as Ni,unlink as Li,utimes as QK,writeFile as vy}from"node:fs/promises";var lu={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},Lx=".swept",e2=".sweeping",Tx=64,_x=448,Sy=384,Iy=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",Nx=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,Ey=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=Q();try{if((await Ni(t)).isDirectory())return Or(t,"hook-tee")}catch{}return Or(XK(),".anyray-hook-tee")},t2=/^(?:ctx_)?([0-9a-f]{16})$/,xy=e=>e.trim().match(t2)?.[1]??null,Ry=async e=>{let t=xy(e);return t?Or(await Ey(),`${t}.txt`):null},n2=async(e,t={})=>{let n=t.limits??lu;try{let r=Date.now(),o=(await Dx(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=Tx)await Promise.all(o.slice(c,c+Tx).map(async l=>{let d=Or(e,l);try{let u=await Ni(d);if(!u.isFile())return;let p=r-u.mtimeMs>n.ttlMs||r-Nx(u)>n.maxAgeMs;if(d!==t.protect&&p){await Li(d);return}a.push({path:d,mtimeMs:u.mtimeMs,size:u.size})}catch{}}));a.sort((c,l)=>l.mtimeMs-c.mtimeMs);let s=0,i=0;for(let c of a){let l=s<n.maxFiles&&i+c.size<=n.maxTotalBytes,d=r-c.mtimeMs<n.writeGraceMs;if(l||s===0||c.path===t.protect||d){s+=1,i+=c.size;continue}await Li(c.path).catch(()=>{})}}catch{}},$x=async e=>{try{return Date.now()-(await Ni(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},Px=async e=>{try{return await vy(e,"",{mode:Sy,flag:"wx"}),!0}catch{return!1}},r2=async(e,t)=>{let n=lu,r=Or(e,e2),o=Or(e,Lx);if(!await Px(r)){let a=0;try{a=Date.now()-(await Ni(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await Li(r).catch(()=>{}),!await Px(r)))return!1}try{return await $x(o)<n.sweepIntervalMs?!1:(await vy(o,"",{mode:Sy}).catch(()=>{}),await n2(e,{protect:t}),!0)}finally{await Li(r).catch(()=>{})}},ky=async(e,t)=>await $x(Or(e,Lx))<lu.sweepIntervalMs?!1:r2(e,t),o2=async()=>{try{let e=await Ey();if(!(await Dx(e)).some(t=>t.endsWith(".txt")))return;await ky(e)}catch{}},Mx=async e=>{if(Iy())return await o2(),null;try{let t=await Ey();await qK(t,{recursive:!0,mode:_x}),await zK(t,_x).catch(()=>{});let n=`${JK("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=Or(t,n),o=Date.now();try{let a=await Ni(r);if(a.isFile()){if(o-Nx(a)<=lu.maxAgeMs){let s=new Date(o);return await QK(r,s,s).catch(()=>{}),await ky(t,r),r}await Li(r).catch(()=>{})}}catch{}return await vy(r,e,{mode:Sy}),await ky(t,r),r}catch{return null}};import{createHash as a2}from"node:crypto";import{homedir as Bx}from"node:os";import{join as Oy}from"node:path";import{readFile as s2,writeFile as i2,chmod as c2,stat as l2,unlink as d2}from"node:fs/promises";var u2=200,p2=1440*60*1e3,f2=4e6,Fx=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",Wx=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},m2=()=>Wx("ANYRAY_HOOK_CACHE_MAX_ENTRIES",u2),Ux=()=>Wx("ANYRAY_HOOK_CACHE_TTL_MS",p2),Hx=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Oy(Bx(),".anyray");try{if((await l2(t)).isDirectory())return Oy(t,"hook-cache.json")}catch{}return Oy(Bx(),".anyray-hook-cache.json")},Gx=(e,t,n)=>a2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),Vx=async e=>{try{let t=JSON.parse(await s2(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},Kx=async e=>{if(Fx())return null;try{let n=(await Vx(await Hx())).entries[e];return!n||Date.now()-n.at>Ux()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},h2=e=>{let t=Date.now(),n=Ux(),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=m2();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>f2&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},jx=async(e,t)=>{if(Fx())return;let n;try{let r=await Hx(),o=await Vx(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=h2(o.entries),n=`${r}.${process.pid}.tmp`,await i2(n,JSON.stringify(o),{mode:384}),await c2(n,384),await he(n,r)}catch{if(n)try{await d2(n)}catch{}}};import{open as y2,stat as g2}from"node:fs/promises";var Zx=600,w2=3,b2=256e3,A2=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(`
716
+ `):"",C2=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),k2=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},v2=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=A2(o.message?.content).trim();if(!(!a||C2(a))&&(t.unshift(a),n+=a.length,t.length>=w2||n>=Zx))break}return t.join(`
717
+ `).slice(0,Zx)};var S2=e=>/(^|[\\/])subagents[\\/]/i.test(e),I2=e=>/\.jsonl$/i.test(e),E2=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),Yx=async e=>{let t={intent:"",kind:"unknown"};if(!e||!I2(e))return t;let n;try{let{size:r}=await g2(e),o=Math.max(0,r-b2),a=r-o;if(a<=0)return t;n=await y2(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(`
718
+ `);i=l>=0?i.slice(l+1):""}let c=k2(i.split(`
719
+ `));return E2(c)?{intent:v2(c),kind:S2(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var O2=3e3,T2=1500,_2=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:O2},P2={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},D2=new Set(["claude","opencode"]),L2=(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:P2[t]})},N2={cacheGet:async()=>null,cachePut:async()=>{}},$2=(e,t={cacheGet:Kx,cachePut:jx,tee:Mx})=>e==="claude"?t:N2,M2=1e3,B2=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),du=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),F2=e=>{try{let t=JSON.parse(e);if(!du(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 du(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},W2=e=>{try{let t=JSON.parse(e);return du(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},U2=e=>du(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
720
+ `:"",Ty=e=>Math.round(Math.max(0,e)/4),Jx=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",H2=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),G2=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),V2=["tool_output","tool_response","tool_result"],K2=e=>{for(let t of V2)if(t in e)return e[t]},j2=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},Z2=120,Y2=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??M2))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=Cy(r.stat,null).length+Z2;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=Cy(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}}},J2=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let S=JSON.parse(e);if(!S||typeof S!="object")return n;r=S}catch{return n}let o=typeof r.tool_name=="string"?r.tool_name:"unknown";if(H2.has(o)||G2(o))return n;let a=Cx(K2(r));if(!a)return n;let s=async S=>{try{await t.beacon(o,S)}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(Xx(o)&&l.retrievalContext!=="available")return n;let d=await Y2(t,j2(o,r.tool_input),i),u=d?.body??i,p=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!su(i,{minChars:T2})))return n;let f=i.length-u.length-p.length,m=async(S,I,E=S.length+p.length)=>{let R=d?.teePath??null;if(!R&&t.tee)try{R=await t.tee(i)}catch{R=null}let N=R?S.replaceAll("; not retrievable in this context]","]"):S,U=R&&!p?Ox(R):"",q=N+p+U,de=U.length,ce=q;if(t.finalizeOutput)try{let F=t.finalizeOutput(q);F.length<=q.length&&(ce=F)}catch{ce=q}let K=q.length-ce.length,ge=Ty(Math.max(0,f-de))+I+Ty(K);ge>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,E+de-K),estTokensSaved:ge,...d&&{digest:d.decision}});let me=a.rebuild(ce);return{stdout:B2(me),replacement:me}},h=async()=>d?m(u,0):n;if(d&&u.length<=t.sizeGate)return m(u,0);let w=l.intent?`${l.intent}
721
+ ${Jx(r.tool_input)}`:Jx(r.tool_input),y=Gx(o,w,u),g=async S=>{try{await t.cachePut(y,S)}catch{}},b=null;try{b=await t.cacheGet(y)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?m(b.output,b.tokensSaved):h();let k=null;try{k=tj(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{k=null}if(k&&!k.handled&&(k=null),k)return k.optimized&&k.output.length<u.length?(await g({optimized:!0,output:k.output,tokensSaved:Ty(u.length-k.output.length)}),m(k.output,0,u.length+p.length)):(await g({optimized:!1}),h());let C;try{C=t.localTrim(u)}catch{return h()}return C.trimmed?m(C.text,C.estTokensSaved):h()},$i=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},X2=()=>{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")}},z2=R2(x2),q2=async e=>{try{let t=await z2(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},Xx=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),Q2=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},ej=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),tj=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),nj=2048,rj=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,nj),n=Cd(t);if(!n)return;await kI({at:Date.now(),status:e.status,code:n})}catch{}},oj=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),_2());try{let c=await q2(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...Xx(t)||Q2(t)&&a==="available"?{reversible:!0}:{},...ej(t)?{semanticRerank:!0}:{},output:r})),l=Vt(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 rj(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)}},zx=async(e="claude")=>{let t=await $i();if(e!=="cursor"&&W2(t))return 0;let n=e==="cursor"?F2(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await _y(n,e);if(e==="cursor"){let a=U2(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},_y=async(e,t="claude",n)=>{await vr(),await CI(t);let r=X2(),o=await nt(),a=o&&{...o,metadata:L2(o.metadata,t)},s=$2(t);return J2(e,{optimize:(i,c,l,d,u)=>oj(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await Yx(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>au(i,r),beacon:(i,c)=>lc(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Rr.maxChars,digestCommand:xx,tee:s.tee,mediumBand:D2.has(t),finalizeOutput:n})};var qx=async()=>0;import{spawn as uj}from"node:child_process";import{homedir as pj}from"node:os";import{join as fj}from"node:path";import{chmod as aj,readFile as sj,rm as Qx,writeFile as ij}from"node:fs/promises";import{join as cj}from"node:path";var Py=()=>cj(Q(),"sso-gate.json"),lj=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))},Na=async()=>{try{let e=JSON.parse(await sj(Py(),"utf-8"));return lj(e)?e:null}catch{return null}},dj=0,uu=async e=>{await tt();let t=Py(),n=`${t}.${process.pid}.${dj++}.tmp`;try{await ij(n,`${JSON.stringify(e)}
722
+ `,{mode:384}),await aj(n,384),await he(n,t)}catch(r){throw await Qx(n,{force:!0}).catch(()=>{}),r}},e0=async()=>{await Qx(Py(),{force:!0}).catch(()=>{})},t0=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"}};var mj=3e4,hj=5*6e4,yj=30*6e4,gj=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},wj=()=>fj(pj(),".claude","settings.json"),bj=async e=>{try{let n=(await M(wj())).env;if(!n)return!1;let r=tn(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}},Aj=async e=>{await Qn.apply(e,{dryRun:!1})},Cj=()=>{let{command:e,args:t}=er("__anyray-sso-poll");return{exe:e,args:t}},kj=()=>{let{exe:e,args:t}=Cj(),n=uj(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))}}},vj=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},n0=(e,t,n,r)=>xe({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),$a=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},r0=e=>`Anyray: one-time sign-in required to use AI tools on this device.
723
723
  1. Open ${e.verificationUriComplete}
724
724
  2. Confirm code ${e.userCode}
725
725
  Your prompt was not sent \u2014 complete sign-in, then resubmit it.
726
- `,_y=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
726
+ `,Dy=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
727
727
  `:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
728
728
  `:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
729
- `,u2=e=>Math.min(n2,t2*2**Math.max(0,e-1)),p2=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?r2:u2(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Co=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??D,o=t.saveProfile??oe,a=t.loadDevKey??$e,s=t.readGateState??Na,i=t.writeGateState??pu,c=t.isProcessAlive??zx,l=t.startGrant??md,d=t.verify??Xt,u=t.routingIntact??s2,p=t.applyClaudeCode??i2,f=t.maybeSpawnRefresh??kr,m=t.recordMint??Ia,h=t.reserveMint??yo,w=t.spawnPoller??l2,y=t.openBrowser??_a;try{let g=St(e.sso);if(!g)return{exitCode:0};let b=await r(),k=await s(),C=b.enrolledCert?await a():void 0,S=d2(b),I=!!(b.enrolledCert&&C)&&Number.isFinite(S)&&S>n(),E=e.gateway??b.gateway;if(I&&b.enrolledCert&&C&&E){let de=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(de)&&de>n()&&b.clientKey){let me=qx(E,b,e.team,b.clientKey);return await u(me)?(de-n()<=Sh()&&await f(),{exitCode:0}):(await p(me),$a(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
730
- `))}let K;await h();let ge=(t.resolveMachineUuid??Bt)()||void 0;try{K=await d(E,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:ge})}catch(me){if(!(me instanceof lt))return $a(e,_y("gateway-unreachable",g.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(K){let me={...b,gateway:E,name:K.user,team:e.team??K.team??b.team,clientKey:K.key,clientKeyExpiresAt:K.expiresAt,authMode:"subscription"};return await o(me),await m({expiresAt:K.expiresAt}),await p(qx(E,me,e.team,K.key)),{exitCode:0}}}if(k?.status==="pending"&&(k.userCode&&k.verificationUriComplete)&&(k.grantExpiresAt??0)>n()&&c(k.pollerPid)){if(e.sessionStart&&k.verificationUriComplete)try{y(k.verificationUriComplete)}catch{}return $a(e,Qx(k))}if(k){let de=p2(k,n());if(de)return $a(e,_y(de,g.cpOrigin))}let R;try{R=await l({cpOrigin:g.cpOrigin,tenantId:g.tenantId,gatewayUrl:e.gateway,now:n})}catch(de){let ie=de instanceof uo?de.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:k?.lastFailure===ie?(k.failureCount??0)+1:1,lastFailure:ie}),$a(e,_y(ie,g.cpOrigin))}let P={v:1,status:"pending",userCode:R.userCode,verificationUriComplete:R.verificationUriComplete,grantExpiresAt:R.grantExpiresAt,startedAt:R.startedAt,lastAttemptAt:n(),failureCount:0};await i(P);let W=w(),q={...P,pollerPid:W.pid};if(await i(q),W.handoff({deviceCode:R.deviceCode,privateKeyPem:R.privateKeyPem,publicKeyPem:R.publicKeyPem,cpOrigin:R.cpOrigin,tenantId:R.tenantId,intervalMs:R.intervalMs,grantExpiresAt:R.grantExpiresAt,startedAt:R.startedAt,gatewayUrl:R.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{y(R.verificationUriComplete)}catch{}return $a(e,Qx(q))}catch{return{exitCode:0}}},f2=async()=>{try{for await(let e of process.stdin);}catch{}},e0=async e=>{await f2();try{let t=await Co(o2(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var m2=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},h2=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??Ar)();if(!r)return;let o=await(t.ssoGate??Co)({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})}
731
- `}catch{return}},y2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},g2=()=>{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")}},w2=(e,t)=>{let n=t.minChars??Pi.minChars,r={maxChars:Math.min(xr.maxChars,n)},o=su(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},t0=async()=>{let e=await y2(),t=await h2(e);t&&process.stdout.write(t);let n=g2(),r=await nt();return await m2(e,{isPaste:o=>iu(o,n),measure:o=>w2(o,n),beacon:o=>lc(r,"prompt",o)}),0};import{spawn as b2}from"node:child_process";var n0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),A2=/[|&;<>`$()\n]/,r0=e=>{if(A2.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},C2=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!n0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!n0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(ju)||!t.isRecognized(o)||r0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},k2=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?r0(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
729
+ `,Sj=e=>Math.min(hj,mj*2**Math.max(0,e-1)),Ij=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?yj:Sj(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Co=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??P,o=t.saveProfile??ae,a=t.loadDevKey??$e,s=t.readGateState??Na,i=t.writeGateState??uu,c=t.isProcessAlive??t0,l=t.startGrant??hd,d=t.verify??Xt,u=t.routingIntact??bj,p=t.applyClaudeCode??Aj,f=t.maybeSpawnRefresh??vr,m=t.recordMint??Ia,h=t.reserveMint??yo,w=t.spawnPoller??kj,y=t.openBrowser??_a;try{let g=St(e.sso);if(!g)return{exitCode:0};let b=await r(),k=await s(),C=b.enrolledCert?await a():void 0,S=vj(b),I=!!(b.enrolledCert&&C)&&Number.isFinite(S)&&S>n(),E=e.gateway??b.gateway;if(I&&b.enrolledCert&&C&&E){let de=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(de)&&de>n()&&b.clientKey){let me=n0(E,b,e.team,b.clientKey);return await u(me)?(de-n()<=kh()&&await f(),{exitCode:0}):(await p(me),$a(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
730
+ `))}let K;await h();let ge=(t.resolveMachineUuid??Ft)()||void 0;try{K=await d(E,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:ge})}catch(me){if(!(me instanceof lt))return $a(e,Dy("gateway-unreachable",g.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(K){let me={...b,gateway:E,name:K.user,team:e.team??K.team??b.team,clientKey:K.key,clientKeyExpiresAt:K.expiresAt,authMode:"subscription"};return await o(me),await m({expiresAt:K.expiresAt}),await p(n0(E,me,e.team,K.key)),{exitCode:0}}}if(k?.status==="pending"&&(k.userCode&&k.verificationUriComplete)&&(k.grantExpiresAt??0)>n()&&c(k.pollerPid)){if(e.sessionStart&&k.verificationUriComplete)try{y(k.verificationUriComplete)}catch{}return $a(e,r0(k))}if(k){let de=Ij(k,n());if(de)return $a(e,Dy(de,g.cpOrigin))}let R;try{R=await l({cpOrigin:g.cpOrigin,tenantId:g.tenantId,gatewayUrl:e.gateway,now:n})}catch(de){let ce=de instanceof uo?de.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:k?.lastFailure===ce?(k.failureCount??0)+1:1,lastFailure:ce}),$a(e,Dy(ce,g.cpOrigin))}let N={v:1,status:"pending",userCode:R.userCode,verificationUriComplete:R.verificationUriComplete,grantExpiresAt:R.grantExpiresAt,startedAt:R.startedAt,lastAttemptAt:n(),failureCount:0};await i(N);let U=w(),q={...N,pollerPid:U.pid};if(await i(q),U.handoff({deviceCode:R.deviceCode,privateKeyPem:R.privateKeyPem,publicKeyPem:R.publicKeyPem,cpOrigin:R.cpOrigin,tenantId:R.tenantId,intervalMs:R.intervalMs,grantExpiresAt:R.grantExpiresAt,startedAt:R.startedAt,gatewayUrl:R.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{y(R.verificationUriComplete)}catch{}return $a(e,r0(q))}catch{return{exitCode:0}}},Ej=async()=>{try{for await(let e of process.stdin);}catch{}},o0=async e=>{await Ej();try{let t=await Co(gj(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var xj=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},Rj=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??Cr)();if(!r)return;let o=await(t.ssoGate??Co)({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})}
731
+ `}catch{return}},Oj=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},Tj=()=>{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")}},_j=(e,t)=>{let n=t.minChars??Pi.minChars,r={maxChars:Math.min(Rr.maxChars,n)},o=au(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},a0=async()=>{let e=await Oj(),t=await Rj(e);t&&process.stdout.write(t);let n=Tj(),r=await nt();return await xj(e,{isPaste:o=>su(o,n),measure:o=>_j(o,n),beacon:o=>lc(r,"prompt",o)}),0};import{spawn as Pj}from"node:child_process";var s0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Dj=/[|&;<>`$()\n]/,i0=e=>{if(Dj.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},Lj=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!s0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!s0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(Ku)||!t.isRecognized(o)||i0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},Nj=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?i0(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
732
732
  `),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
733
- `),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},v2=16*1024*1024,S2=e=>new Promise(t=>{let n=[],r=0,o=!1,a=!1,s=new Map,i=c=>{if(!a){a=!0;for(let[l,d]of s)process.off(l,d);t({output:o?"":Buffer.concat(n).toString("utf8"),code:c,...o?{alreadyWritten:!0}:{}})}};try{let c=b2(e[0],e.slice(1),{stdio:["inherit","pipe","pipe"]});for(let d of["SIGINT","SIGTERM","SIGHUP"]){let u=()=>{if(c.exitCode===null&&c.signalCode===null)try{c.kill(d)}catch{}};s.set(d,u),process.on(d,u)}let l=d=>{if(o){process.stdout.write(d);return}if(r+d.byteLength>v2){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)}}),I2=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Oy(n,"cursor");return typeof r=="string"?r:t},o0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return k2(t,{exec:S2,trim:I2,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},a0=async()=>{let e=await $i();if(process.platform==="win32")return 0;let t=C2(e,{isRecognized:n=>wy(n)!==null||Cx(n),wrap:n=>Rt(ju,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as E2}from"node:crypto";import{homedir as s0}from"node:os";import{extname as x2,isAbsolute as R2,join as Py,resolve as Mi,sep as i0}from"node:path";import{chmod as O2,readFile as T2,stat as p0,unlink as _2,writeFile as P2}from"node:fs/promises";var Ly=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),D2=16*1024,c0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],L2=["pattern","query","regex","search"],N2=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"]),$2=720*60*1e3,M2=512,Dy=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},B2=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],l0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(i0)?n:n+i0)),F2=(e,t,n)=>R2(e)?[Mi(e)]:[...new Set([Mi(t,e),...n.map(r=>Mi(r,e))])],d0=(e,t,n)=>E2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),u0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),W2=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!Ly(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!Ly(o))return"";let a=B2(n.workspace_roots).map(d=>Mi(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=Dy(o,L2);if(!d)return"";let u=Dy(o,c0);return u&&!l0(Mi(s,u),a)||!await t.remember(d0(i,"Grep",d))?"":u0(`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=Dy(o,c0);if(!c||N2.has(x2(c).toLowerCase()))return"";let l=await t.resolveFile(F2(c,s,a));return!l||l.bytes<D2||!l0(l.path,a)||!await t.remember(d0(i,"Read",l.path))?"":u0(`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.`)},H2=async e=>{for(let t of e)try{let n=await p0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},U2=async()=>{let e=Py(s0(),".anyray");try{if((await p0(e)).isDirectory())return Py(e,"cursor-redirects.json")}catch{}return Py(s0(),".anyray-cursor-redirects.json")},G2=async e=>{let t;try{let n=await U2(),r=Date.now(),o={};try{let s=JSON.parse(await T2(n,"utf-8"));if(s?.v===1&&Ly(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=$2&&(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,M2);return t=`${n}.${process.pid}.tmp`,await P2(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await O2(t,384),await he(t,n),!0}catch{if(t)try{await _2(t)}catch{}return!1}},f0=async()=>{let e=await $i(),t="";try{t=await W2(e,{resolveFile:H2,remember:G2})}catch{t=""}return t&&process.stdout.write(t),0};var m0=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},h0=async e=>{try{if(e.platform!=="darwin")return 0;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return 0;let n=e.readManagedEnrollment().enrollmentUrl;return n?await e.runApply(["--enroll",n,"--yes"],t.revertedTools??[]):0}catch{return 1}},y0=e=>({platform:process.platform,readManagedEnrollment:zh,loadProfile:D,runApply:e});var Bi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Ny=e=>typeof e=="string"&&e.trim()?e.trim():void 0,V2=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=Ny(n.gatewayUrl),p=Ny(n.gatewayOverride),f=Ny(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...p?{gatewayOverride:p}:{},...f?{team:f}:{}}}catch{return null}},K2=e=>new Promise(t=>setTimeout(t,e)),j2=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})},Z2=async(e,t={})=>{let n=t.poll??hd,r=t.verify??Xt,o=t.loadProfile??D,a=t.saveProfile??oe,s=t.saveDevKey??Ji,i=t.readGateState??Na,c=t.writeGateState??pu,l=t.clearGateState??Xx,d=t.sleep??K2,u=t.now??Date.now,p=t.recordMint??Ia,f=t.reserveMint??yo,m=t.applyClaudeCode??(async E=>{await qn.apply(E,{dryRun:!1})}),h=E=>j2(E,{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},y;try{y=await n(w,{gatewayUrl:e.gatewayOverride})}catch(E){let R=E instanceof $t?E.kind:"cp-unreachable";return await h(R),R}let g=e.gatewayOverride??y.gatewayUrl,b=await o(),k={...b,gateway:g??b.gateway,name:y.cert.payload.user||b.name,team:e.team??y.cert.payload.team??b.team,enrolledCert:y.cert,enrolledCertExpiry:y.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(y.privateKeyPem),await a(k)}catch{return"failed"}if(!g)return await h("gateway-unreachable"),"gateway-unreachable";let C;await f();let S=(t.resolveMachineUuid??Bt)()||void 0;for(let E=0;E<3;E++)try{C=await r(g,y.cert,y.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(R){if(R instanceof lt||E===2)break;await d(1e3)}if(!C)return await h("gateway-unreachable"),"gateway-unreachable";let I={...k,gateway:g,name:C.user,team:e.team??C.team??k.team,clientKey:C.key,clientKeyExpiresAt:C.expiresAt,authMode:"subscription"};try{await a(I),await p({expiresAt:C.expiresAt});let E=xe({origin:g,clientKey:C.key,subscription:!0,user:I.name,team:I.team});return await m(E),await l(),"enrolled"}catch{return await h("gateway-unreachable"),"failed"}},Y2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},g0=async()=>{let e=V2(await Y2());if(e)try{await Z2(e)}catch{}return 0};var J2=1e4,$y=/^[\w.:-]{1,64}$/,Wt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},My=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,w0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),J2);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 Wt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},X2=e=>{let t=My(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}},z2=e=>{let t=My(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&$y.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&$y.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},q2=e=>{let t=My(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ee(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!$y.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}}},Q2=e=>new Promise(t=>setTimeout(t,e)),eZ=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Wt("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}A("Available teams:"),e.forEach((i,c)=>A(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await xa("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 Wt("invalid-team","Choose one of the teams shown above.");return s},tZ=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??Q2,a=t.loadProfile??D,s=t.saveProfile??oe,i=t.clearDevKey??Ja,c=t.chooseTeam??eZ,l=t.apply??(async y=>{await qn.apply(y,{dryRun:!1})}),d=t.log??$,u=await a(),p=vr(e.gateway,u),f=await w0(`${p}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),m=X2(f.body);if(f.status!==200||!m)throw new Wt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${m.browser_url}`),d(`Enter this code in the browser: ${m.user_code}`),(t.openBrowser??_a)(m.browser_url);let h=r()+m.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<h;){let y=await w0(`${p}/sso/cli/poll/${encodeURIComponent(m.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":m.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(y.status===202){await o(m.interval*1e3);continue}if(y.status===401)throw new Wt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new Wt("expired","SSO login expired before it completed. Run anyray-connect login again.");let g=z2(y.body);if(y.status===200&&g){if(w&&!g.teams.includes(w))throw new Wt("invalid-team",`Team ${w} is not available for this account.`);w=await c(g.teams,g.default_team,e.interactive??Ft());continue}let b=q2(y.body);if(y.status!==200||!b)throw new Wt("login-failed","SSO login could not be completed.");let k={...u,gateway:p,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(k),await l(xe({origin:p,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Wt("expired","SSO login expired before it completed. Run anyray-connect login again.")},nZ=`anyray-connect login [--gateway <url>] [--team <name>]
733
+ `),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},$j=16*1024*1024,Mj=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=Pj(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>$j){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)}}),Bj=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await _y(n,"cursor");return typeof r=="string"?r:t},c0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return Nj(t,{exec:Mj,trim:Bj,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},l0=async()=>{let e=await $i();if(process.platform==="win32")return 0;let t=Lj(e,{isRecognized:n=>Ay(n)!==null||Ix(n),wrap:n=>Rt(Ku,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as Fj}from"node:crypto";import{homedir as d0}from"node:os";import{extname as Wj,isAbsolute as Uj,join as Ly,resolve as Mi,sep as u0}from"node:path";import{chmod as Hj,readFile as Gj,stat as y0,unlink as Vj,writeFile as Kj}from"node:fs/promises";var $y=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jj=16*1024,p0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],Zj=["pattern","query","regex","search"],Yj=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"]),Jj=720*60*1e3,Xj=512,Ny=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},zj=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],f0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(u0)?n:n+u0)),qj=(e,t,n)=>Uj(e)?[Mi(e)]:[...new Set([Mi(t,e),...n.map(r=>Mi(r,e))])],m0=(e,t,n)=>Fj("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),h0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),Qj=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!$y(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!$y(o))return"";let a=zj(n.workspace_roots).map(d=>Mi(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=Ny(o,Zj);if(!d)return"";let u=Ny(o,p0);return u&&!f0(Mi(s,u),a)||!await t.remember(m0(i,"Grep",d))?"":h0(`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=Ny(o,p0);if(!c||Yj.has(Wj(c).toLowerCase()))return"";let l=await t.resolveFile(qj(c,s,a));return!l||l.bytes<jj||!f0(l.path,a)||!await t.remember(m0(i,"Read",l.path))?"":h0(`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.`)},eZ=async e=>{for(let t of e)try{let n=await y0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},tZ=async()=>{let e=Ly(d0(),".anyray");try{if((await y0(e)).isDirectory())return Ly(e,"cursor-redirects.json")}catch{}return Ly(d0(),".anyray-cursor-redirects.json")},nZ=async e=>{let t;try{let n=await tZ(),r=Date.now(),o={};try{let s=JSON.parse(await Gj(n,"utf-8"));if(s?.v===1&&$y(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=Jj&&(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,Xj);return t=`${n}.${process.pid}.tmp`,await Kj(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await Hj(t,384),await he(t,n),!0}catch{if(t)try{await Vj(t)}catch{}return!1}},g0=async()=>{let e=await $i(),t="";try{t=await Qj(e,{resolveFile:eZ,remember:nZ})}catch{t=""}return t&&process.stdout.write(t),0};import{execFileSync as dY}from"node:child_process";import{createReadStream as rZ}from"node:fs";import{spawnSync as O0}from"node:child_process";import{createHash as oZ}from"node:crypto";import{access as T0,chmod as Fy,copyFile as aZ,lstat as sZ,mkdir as iZ,mkdtemp as _0,readFile as yu,rename as cZ,rm as Tr,stat as lZ,writeFile as dZ}from"node:fs/promises";import{constants as P0}from"node:fs";import{platform as Fa,tmpdir as uZ}from"node:os";import{dirname as pZ,isAbsolute as fZ,join as fu}from"node:path";import{z as Le}from"zod";var mZ="fleetd-installer-v4.89.2",w0=`https://github.com/anyrayHQ/install/releases/download/${mZ}`,hZ=1e4,yZ=1e4,b0=31,gZ=1500,D0=20*1024,My=20,wZ="0.25",bZ="/var/tmp",Ba="/Library/LaunchDaemons/com.fleetdm.orbit.plist",mu="/etc/default/orbit",Fi="/opt/orbit/anyray-enroll-secret.txt",L0="/opt/orbit/secret-orbit-node-key.txt",AZ="/opt/orbit/bin/orbit/orbit",Wi="C:\\Program Files\\Orbit",CZ=`${Wi}\\bin\\orbit`,N0=`${Wi}\\secret-orbit-node-key.txt`,Bi=`${Wi}\\secret.txt`,kZ=`${Wi}\\fleet_url.txt`,$0=`${Wi}\\anyray-managed.txt`,hu="Fleet osquery",Wy="C:\\Windows\\System32\\sc.exe",Vy="C:\\Windows\\System32\\whoami.exe",pu="C:\\Windows\\System32\\icacls.exe",vZ="C:\\Windows\\System32\\msiexec.exe",Uy="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",A0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],SZ=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],IZ=`anyray-connect endpoint install
734
+
735
+ Install Fleet's signed endpoint agent and enroll this machine in Anyray.
736
+
737
+ Supported on macOS, Linux and Windows.
738
+
739
+ The command uses the current seat's stored gateway key. Administrator access is
740
+ required: on macOS and Linux Connect asks through sudo once when /dev/tty is
741
+ available; on Windows, run it from a shell started as Administrator.`,Ky=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),M0=(e,t=Fa())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),B0=(e,t=Fa(),n=!1)=>(Ky(e)||n)&&t!=="win32",se=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},EZ=Le.object({kind:Le.enum(["pkg","deb","rpm","msi"]),path:Le.string().min(1).refine(fZ),sha256:Le.string().regex(/^[0-9a-f]{64}$/)}).strict(),xZ=Le.object({action:Le.literal("restart"),os:Le.enum(["darwin","linux","win32"])}).strict(),RZ=Le.object({action:Le.literal("configure"),os:Le.enum(["darwin","linux","win32"]),fleetUrl:Le.string().min(1).max(2048),enrollSecret:Le.string().min(1).max(4096),package:EZ.optional()}).strict(),OZ=Le.discriminatedUnion("action",[xZ,RZ]),Ui=(e,t)=>{let n=O0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},jy=async e=>{try{return await T0(e,P0.F_OK),!0}catch{return!1}},TZ=async e=>{try{let t=await lZ(e);return t.isFile()&&t.size>0}catch{return!1}},Zy=(e,t)=>{for(let n=0;;){let r=e.indexOf("<key>",n);if(r<0)return null;let o=e.indexOf("</key>",r);if(o<0)return null;if(e.slice(r+5,o).trim()===t)return{start:r,end:o+6};n=o+6}},By=(e,t)=>Zy(e,t)!==null,C0=e=>e==="win32"?Bi:Fi,_Z=e=>e==="win32"?N0:L0,PZ=e=>By(e,"ORBIT_FLEET_URL")&&By(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Fi}</string>`)&&!By(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),DZ=e=>{let t=(n,r)=>e.split(`
742
+ `).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Fi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Hy=(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()},F0=e=>{let t=e(Wy,["qc",hu,"8192"]);return t.status===0?t.stdout:""},Gy=e=>{let t=e(Uy,SZ(hu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},LZ=async e=>{try{return e==="win32"?Hy(e,F0(Ui)):Hy(e,await yu(e==="darwin"?Ba:mu,"utf8"))}catch{return}},NZ=async e=>{try{if(e==="win32")return await jy($0)&&Hy(e,F0(Ui))!==void 0;let n=await yu(e==="darwin"?Ba:mu,"utf8");return e==="darwin"?PZ(n):DZ(n)}catch{return!1}},W0=async(e,t={})=>{let n=t.exists??jy,r=t.command??Ui,o,a="absent";if(e==="win32")a=Gy(r),o=await n(CZ)&&a!=="absent";else{let l=e==="darwin"?await n(Ba):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(AZ)&&l}let s=await(t.configured??NZ)(e),i=await(t.hasNodeKey??(()=>TZ(_Z(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}},$Z=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),U0=(e,t)=>{let n=Zy(e,t);if(!n)return null;let r=n.start;for(;r>0&&(e[r-1]===" "||e[r-1]===" ");)r--;r>0&&e[r-1]===`
743
+ `&&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},MZ=(e,t)=>{let n=U0(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},k0=(e,t,n)=>{let r=`
744
+ <key>${t}</key>
745
+ <string>${$Z(n)}</string>`,o=U0(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Zy(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new se("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)},BZ=(e,t,n=Fi)=>{let r=MZ(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=k0(r,"ORBIT_FLEET_URL",t),k0(r,"ORBIT_ENROLL_SECRET_PATH",n)},FZ=(e,t,n=Fi)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
746
+ `).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(`
747
+ `).trimEnd()}
748
+
749
+ # Managed by anyray-connect endpoint install.
750
+ # ORBIT_ENROLL_SECRET is deliberately ABSENT: orbit refuses to start when both
751
+ # it and ORBIT_ENROLL_SECRET_PATH are set, and the secret belongs in a 0600
752
+ # file, never in this world-readable one.
753
+ ORBIT_FLEET_URL=${t}
754
+ ORBIT_ENROLL_SECRET_PATH=${n}
755
+ `},H0=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}},WZ=Le.object({code:Le.string().min(1).optional(),message:Le.string().min(1).optional()}).passthrough(),v0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},UZ=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=WZ.safeParse(t);if(!r.success)return n;let o=v0(r.data.message??""),a=v0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},S0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??yZ),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":Ae},body:"{}",signal:r.signal})}catch{throw new se("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new se("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new se(UZ(a.status,c))}let s;try{s=await a.json()}catch{throw new se("The gateway returned malformed endpoint enrollment data.")}let i=Le.object({fleetUrl:Le.string().min(1).max(2048),enrollSecret:Le.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!H0(i.data.fleetUrl))throw new se("The gateway returned invalid endpoint enrollment data.");return i.data},HZ=async(e={})=>{let t=e.exists??jy;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 se("Linux endpoint installation requires either dpkg or rpm.")},GZ=async e=>e==="darwin"?"pkg":e==="win32"?"msi":HZ(),Yy=e=>`fleetd.${e}`,VZ=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",KZ=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),hZ);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},jZ=async(e,t={})=>{let n=Yy(e),r=t.fetchResponse??fetch,o;try{o=await KZ(`${w0}/SHA256SUMS`,r)}catch{throw new se("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new se(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=oy(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await _0(fu(uZ(),"anyray-endpoint-")),i=fu(s,n);try{await Fy(s,448),await(t.download??iy)(`${w0}/${n}`,i,a)}catch(c){if(await Tr(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Ri&&c.status===404)return;throw new se("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Tr(s,{recursive:!0,force:!0})}},ZZ=async(e,t,n)=>{await iZ(pZ(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Tr(r,{force:!0});try{await dZ(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await cZ(r,e)}catch(o){throw await Tr(r,{force:!0}).catch(()=>{}),o}},I0=async e=>{let t=oZ("sha256");for await(let n of rZ(e))t.update(n);return t.digest("hex")},YZ=async(e,t={})=>{let n=await sZ(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new se("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await I0(e.path)!==e.sha256)throw new se("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await _0(fu(bZ,"anyray-endpoint-root-")),o=fu(r,Yy(e.kind));try{if(await Fy(r,448),await aZ(e.path,o),await Fy(o,384),await I0(o)!==e.sha256)throw new se("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 se(t)},E0="com.fleetdm.fleetd.config",JZ="com.fleetdm.fleetd.enroll.secret",XZ=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",L0],zZ=[kZ,N0],qZ=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(E0))throw new se(`This machine already receives its endpoint configuration from an MDM profile (${E0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},x0=async(e,t,n)=>{let r=n.removeFile??(o=>Tr(o,{force:!0}));for(let o of e==="win32"?zZ:XZ)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",JZ,"/Library/Keychains/System.keychain"])},QZ=e=>{e(pu,[Bi,"/inheritance:r"]),e(pu,[Bi,"/grant:r","*S-1-5-18:(F)"]),e(pu,[Bi,"/grant:r","*S-1-5-32-544:(F)"]),e(pu,[Bi,"/remove:g","*S-1-5-32-545"])},eY=(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(vZ,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},tY=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<My;r++){if(n=t("/bin/launchctl",["bootstrap","system",Ba]),n.status===0)return;t("/bin/sleep",[wZ])}throw new se(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(Wy,["stop",hu]);for(let n=0;n<My;n++){let r=Gy(t);if(r==="Stopped"||r==="absent")break;t(Uy,A0)}for(let n=0;n<My;n++){if(t(Wy,["start",hu]).status===0||Gy(t)==="Running")return;t(Uy,A0)}throw new se("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.")},nY=e=>new Promise(t=>setTimeout(t,e)),G0=async(e,t={})=>{let n=t.command??Ui,r=t.readText??(c=>yu(c,"utf8")),o=t.writeText??ZZ,a=t.removeSecret??(()=>Tr(C0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&qZ(n),e.package&&!VZ(e.os,e.package.kind))throw new se("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new se("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await x0(e.os,n,t),e.package){let d=await(t.preparePackage??YZ)(e.package);i=d.cleanup,eY(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Ba);await o(Ba,BZ(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(mu);await o(mu,FZ(d,e.fleetUrl),420)}else await o($0,`anyray
756
+ `,384);e.os!=="win32"&&await x0(e.os,n,t),await o(C0(e.os),`${e.enrollSecret}
757
+ `,384),e.os==="win32"&&QZ(n),s=e.os!=="win32"}tY(e.os,n);let c=t.checkIn??(async d=>{let u=await W0(d);return u.running&&u.checkedIn}),l=t.wait??nY;for(let d=0;d<(t.attempts??b0);d++){if(await c(e.os))return;d+1<(t.attempts??b0)&&await l(gZ)}throw new se("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(()=>{})}},rY=async()=>{try{return await T0("/dev/tty",P0.R_OK),!0}catch{return!1}},oY=12288,aY=e=>{let t=e(Vy,["/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>=oY},sY=async(e,t={})=>{if((t.os??Fa())==="win32")return(t.elevated??(()=>aY(t.command??Ui)))()?(await e(),"direct"):((t.print??A)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
758
+ anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??rY)()){if(await(t.reexec??(async()=>1))()!==0)throw new se("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??A)(`Administrator access is required. Run:
759
+ sudo anyray-connect endpoint install`),"deferred"},iY=async e=>{let t=`${JSON.stringify(e)}
760
+ `;if(Buffer.byteLength(t)>D0)throw new se("The privileged endpoint plan is unexpectedly large.");let n=en(["__anyray-endpoint-install"]);return O0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},cY=async(e,t={})=>(t.withRoot??sY)(()=>(t.apply??G0)(e),{...t.root,reexec:()=>(t.sudo??iY)(e)}),R0=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 yu("/etc/passwd","utf8")).split(`
761
+ `).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Fa()==="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}},V0=async(e={},t={})=>{let n=t.os??Fa();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new se("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??W0)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??R0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??LZ)(r);if(!l||!d||u===void 0)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};let p=await(t.fetchEnrollment??S0)(l,d);if(u===p.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};$("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new se("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??R0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new se("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??S0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let p=await(t.packageKind??(()=>GZ(r)))();if(i=await(t.stagePackage??jZ)(p),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${Yy(p)} 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??cY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},Jy=e=>e instanceof se?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",K0=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return A(IZ),0;if(e.length!==1||e[0]!=="install")return O("Usage: anyray-connect endpoint install"),1;try{let t=await V0();return t.message&&(t.outcome==="installed"?B(t.message):$(t.message)),0}catch(t){return O(Jy(t)),1}},lY=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>D0)throw new se("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new se("The privileged endpoint plan is malformed.")}let r=OZ.safeParse(n);if(!r.success||r.data.os!==Fa()||r.data.action==="configure"&&!H0(r.data.fleetUrl))throw new se("The privileged endpoint plan is invalid.");return r.data},j0=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 G0(await lY()),0}catch(t){return O(Jy(t)),1}},Z0=async(e,t=V0)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?B(n.message):$(n.message)),n.outcome}catch(n){$(`Endpoint agent: ${Jy(n)} Tool routing remains configured.`);return}};var uY=new Set(["darwin","win32","linux"]),pY=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),fY=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!pY.has(t)},Y0=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},J0=async e=>{try{if(!uY.has(e.platform)||e.isUserSession?.()===!1)return 0;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return 0;let n=e.readManagedEnrollment().enrollmentUrl;return n?await e.runApply(["--enroll",n,"--yes"],t.revertedTools??[]):0}catch{return 1}},X0=e=>({platform:process.platform,readManagedEnrollment:Qh,loadProfile:P,isUserSession:()=>{try{if(process.platform==="win32"){let t=dY(Vy,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return fY(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var Hi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Xy=e=>typeof e=="string"&&e.trim()?e.trim():void 0,mY=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Hi(n,"deviceCode"),o=Hi(n,"privateKeyPem"),a=Hi(n,"publicKeyPem"),s=Hi(n,"cpOrigin"),i=Hi(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=Xy(n.gatewayUrl),p=Xy(n.gatewayOverride),f=Xy(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...p?{gatewayOverride:p}:{},...f?{team:f}:{}}}catch{return null}},hY=e=>new Promise(t=>setTimeout(t,e)),yY=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})},gY=async(e,t={})=>{let n=t.poll??yd,r=t.verify??Xt,o=t.loadProfile??P,a=t.saveProfile??ae,s=t.saveDevKey??Ji,i=t.readGateState??Na,c=t.writeGateState??uu,l=t.clearGateState??e0,d=t.sleep??hY,u=t.now??Date.now,p=t.recordMint??Ia,f=t.reserveMint??yo,m=t.applyClaudeCode??(async E=>{await Qn.apply(E,{dryRun:!1})}),h=E=>yY(E,{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},y;try{y=await n(w,{gatewayUrl:e.gatewayOverride})}catch(E){let R=E instanceof Mt?E.kind:"cp-unreachable";return await h(R),R}let g=e.gatewayOverride??y.gatewayUrl,b=await o(),k={...b,gateway:g??b.gateway,name:y.cert.payload.user||b.name,team:e.team??y.cert.payload.team??b.team,enrolledCert:y.cert,enrolledCertExpiry:y.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(y.privateKeyPem),await a(k)}catch{return"failed"}if(!g)return await h("gateway-unreachable"),"gateway-unreachable";let C;await f();let S=(t.resolveMachineUuid??Ft)()||void 0;for(let E=0;E<3;E++)try{C=await r(g,y.cert,y.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(R){if(R instanceof lt||E===2)break;await d(1e3)}if(!C)return await h("gateway-unreachable"),"gateway-unreachable";let I={...k,gateway:g,name:C.user,team:e.team??C.team??k.team,clientKey:C.key,clientKeyExpiresAt:C.expiresAt,authMode:"subscription"};try{await a(I),await p({expiresAt:C.expiresAt});let E=xe({origin:g,clientKey:C.key,subscription:!0,user:I.name,team:I.team});return await m(E),await l(),"enrolled"}catch{return await h("gateway-unreachable"),"failed"}},wY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},z0=async()=>{let e=mY(await wY());if(e)try{await gY(e)}catch{}return 0};var bY=1e4,zy=/^[\w.:-]{1,64}$/,Ut=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},qy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,q0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),bY);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 Ut("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},AY=e=>{let t=qy(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}},CY=e=>{let t=qy(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&zy.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&zy.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},kY=e=>{let t=qy(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ee(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!zy.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}}},vY=e=>new Promise(t=>setTimeout(t,e)),SY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Ut("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}A("Available teams:"),e.forEach((i,c)=>A(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await xa("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 Ut("invalid-team","Choose one of the teams shown above.");return s},IY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??vY,a=t.loadProfile??P,s=t.saveProfile??ae,i=t.clearDevKey??Ja,c=t.chooseTeam??SY,l=t.apply??(async y=>{await Qn.apply(y,{dryRun:!1})}),d=t.log??$,u=await a(),p=Sr(e.gateway,u),f=await q0(`${p}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),m=AY(f.body);if(f.status!==200||!m)throw new Ut("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${m.browser_url}`),d(`Enter this code in the browser: ${m.user_code}`),(t.openBrowser??_a)(m.browser_url);let h=r()+m.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<h;){let y=await q0(`${p}/sso/cli/poll/${encodeURIComponent(m.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":m.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(y.status===202){await o(m.interval*1e3);continue}if(y.status===401)throw new Ut("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new Ut("expired","SSO login expired before it completed. Run anyray-connect login again.");let g=CY(y.body);if(y.status===200&&g){if(w&&!g.teams.includes(w))throw new Ut("invalid-team",`Team ${w} is not available for this account.`);w=await c(g.teams,g.default_team,e.interactive??Wt());continue}let b=kY(y.body);if(y.status!==200||!b)throw new Ut("login-failed","SSO login could not be completed.");let k={...u,gateway:p,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(k),await l(xe({origin:p,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Ut("expired","SSO login expired before it completed. Run anyray-connect login again.")},EY=`anyray-connect login [--gateway <url>] [--team <name>]
734
762
 
735
763
  Start browser SSO, choose a team, mint a personal gateway key, and configure
736
764
  the subscription-backed Connect lane. In a non-interactive shell, --team may be
737
- omitted only when the identity authority supplies a default or sole team.`,b0=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return A(nZ),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 tZ({gateway:n,team:r},t);return M(`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 Wt?o.message:"SSO login failed."),1}};var A0=`anyray-connect update [--check] [--auto on|off] [--json]
765
+ omitted only when the identity authority supplies a default or sole team.`,Q0=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return A(EY),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 IY({gateway:n,team:r},t);return B(`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 Ut?o.message:"SSO login failed."),1}};var eR=`anyray-connect update [--check] [--auto on|off] [--json]
738
766
 
739
767
  Keep this machine's anyray-connect binary on the published release. Runs
740
768
  automatically about every 30 minutes; this command forces it now.
@@ -745,34 +773,34 @@ Options:
745
773
  Off still accepts a release the Anyray team marks mandatory.
746
774
  --json Emit the result as JSON.
747
775
  --help Show this help.
748
- `,rZ=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},oZ=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}.`}},C0=async e=>{let t;try{t=rZ(e)}catch(o){return O(o.message),process.stderr.write(A0),1}if(t.help)return process.stdout.write(A0),0;if(t.auto!==void 0){let o=await D();if(o.autoUpdate!==!1!==t.auto&&await oe({...o,autoUpdate:t.auto}),t.json||(M(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||A("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)}
776
+ `,xY=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},RY=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}.`}},tR=async e=>{let t;try{t=xY(e)}catch(o){return O(o.message),process.stderr.write(eR),1}if(t.help)return process.stdout.write(eR),0;if(t.auto!==void 0){let o=await P();if(o.autoUpdate!==!1!==t.auto&&await ae({...o,autoUpdate:t.auto}),t.json||(B(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||A("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)}
749
777
  `),0}let n=await La({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await wo();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state},null,2)}
750
- `),n.outcome==="failed"?1:0}let r=oZ(n);switch(n.outcome){case"updated":case"migrated":M(r);break;case"current":M(r);break;case"available":case"migration-available":A(r),t.check&&A(`Run ${V("anyray-connect update")} to install it.`);break;case"migration-deferred":_(r),A(v("Use the newer npm runtime until that standalone release is published."));break;case"disabled":_(r),A(`Run ${V("anyray-connect update")} to install it now, or ${V("--auto on")} to resume.`);break;case"unmanaged":A(r),A(v("A copy your IT team placed is theirs to roll."));break;case"container":A(r);break;case"platform-unsupported":_(r),A(v("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":_(r);break;case"failed":return O(r),1}return 0};var aZ=3e3,k0=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>oy(aZ)),o=e.updateStatus??wo;t(`anyray-connect ${Ae}
778
+ `),n.outcome==="failed"?1:0}let r=RY(n);switch(n.outcome){case"updated":case"migrated":B(r);break;case"current":B(r);break;case"available":case"migration-available":A(r),t.check&&A(`Run ${V("anyray-connect update")} to install it.`);break;case"migration-deferred":_(r),A(v("Use the newer npm runtime until that standalone release is published."));break;case"disabled":_(r),A(`Run ${V("anyray-connect update")} to install it now, or ${V("--auto on")} to resume.`);break;case"unmanaged":A(r),A(v("A copy your IT team placed is theirs to roll."));break;case"container":A(r);break;case"platform-unsupported":_(r),A(v("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":_(r);break;case"failed":return O(r),1}return 0};var OY=3e3,nR=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>sy(OY)),o=e.updateStatus??wo;t(`anyray-connect ${Ae}
751
779
  `);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&Pa(a,Ae)>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: ${Ae} \u2192 ${a}
752
780
  ${i}
753
- `)}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 sZ=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},iZ=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),cZ=async(e={})=>{try{let t=await(e.readBootstrap??Ar)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??zt)().catch(()=>{});let n=await(e.loadProfile??D)();if(Ee(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Co)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??D)(),Ee(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Na)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!sZ(a)||!iZ(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"}}},v0=async(e={})=>{let t=await cZ(e);return process.stdout.write(`${JSON.stringify(t)}
754
- `),0};import lZ from"node:path";var dZ="2025-06-18",uZ={name:"anyray",version:"1"},S0={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}},pZ=20,I0={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}},T0=Xh,fZ=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,T0)},mZ=e=>e==="paths"||e==="lines"||e==="full"?e:"full",E0={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-${T0}). 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}},x0={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}},hZ=8,yZ=3,R0={name:"anyray_history",description:'Search the user\'s imported Claude conversation history (past chats from their Claude account, imported with `anyray-connect history import`). Use whenever the user refers to an earlier conversation you cannot see ("what did we decide about X?"), especially in a client whose own history is unavailable. Call with `query` to find conversations, then `open` (a filename from those results) to read one in full.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Words to look for in past conversations (topic, name, phrase)."},open:{type:"string",description:"Filename from a previous result, to read that conversation in full."}},additionalProperties:!1}},gZ=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(`
755
- `)},wZ=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
756
- 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,hZ).map(([a,s])=>{let i=s.slice(0,yZ).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
781
+ `)}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 TY=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},_Y=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),PY=async(e={})=>{try{let t=await(e.readBootstrap??Cr)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??zt)().catch(()=>{});let n=await(e.loadProfile??P)();if(Ee(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Co)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??P)(),Ee(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Na)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!TY(a)||!_Y(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"}}},rR=async(e={})=>{let t=await PY(e);return process.stdout.write(`${JSON.stringify(t)}
782
+ `),0};import DY from"node:path";var LY="2025-06-18",NY={name:"anyray",version:"1"},oR={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}},$Y=20,aR={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}},dR=Yh,MY=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,dR)},BY=e=>e==="paths"||e==="lines"||e==="full"?e:"full",sR={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-${dR}). 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}},iR={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}},FY=8,WY=3,cR={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}},UY=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(`
783
+ `)},HY=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
784
+ 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,FY).map(([a,s])=>{let i=s.slice(0,WY).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
757
785
  `)});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(`
758
- `)},be=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),By=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),O0=e=>e?.name??"error",ye=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
786
+ `)},be=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),Qy=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),lR=e=>e?.name??"error",ye=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
759
787
 
760
788
  [anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
761
789
 
762
790
  [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(`
763
- `);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},bZ=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 be(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:dZ,capabilities:{tools:{}},serverInfo:uZ});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return be(n??null,{});case"tools/list":{let a=[S0,I0];t.advertiseContextTools!==!1&&a.push(E0,x0);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(R0),be(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===S0.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return be(n??null,ye("handle is required",!0));let c=w=>{if(w!==void 0)return typeof w!="number"||!Number.isFinite(w)?null:Math.max(Math.round(w),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return be(n??null,ye("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return be(n??null,ye("grep must be non-empty",!0));if(s.grep.length>256)return be(n??null,ye("grep is limited to 256 characters",!0));u=s.grep}let p=l!==void 0||d!==void 0||u!==void 0,f=Iy(i);if(f){let w=await Ey(f);if(u!==void 0)return be(n??null,ye(`${i} is a local hook-tee file, not a stash handle, and grep is not supported on these \u2014 re-call with startLine/endLine, or Read ${w??"the path in the footer"} directly.`,!0));let y=t.readTee?await t.readTee(f,{startLine:l,endLine:d}).catch(b=>({ok:!1,content:"",path:w??f,lines:0,truncated:!1,message:b instanceof Error?b.message:"tee read failed"})):null;if(y?.ok){let b=y.span?`lines ${y.span.startLine}-${y.span.endLine} of ${y.lines}`:`${y.lines} line(s)`,k=y.truncated&&!y.span?.partialLine&&y.span?` Continue with anyray_retrieve(handle="${i}", startLine=${y.span.endLine+1}).`:"";return be(n??null,ye(`[anyray: ${i} is a local hook-tee file, not a stash handle \u2014 served ${b} from ${y.teePath??w}.${k} Read that path directly next time.]
764
- `+y.content))}let g=y!==null;return be(n??null,ye(`${i} is a hook-tee file id, not a stash handle`+(g&&w?`, and ${w} is not readable`+(y?.message?` (${y.message})`:"")+". The hook writes these files when it trims a tool output; this one has been swept, or the tee is off. Re-run the command to regenerate its output.":`. Read ${w??"the path in its footer"} directly.`),!0))}let m;try{m=await t.retrieve(i,p?{startLine:l,endLine:d,grep:u}:void 0)}catch(w){m={ok:!1,message:w instanceof Error?w.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(!m.ok)return be(n??null,ye(m.kind==="slice-unsupported"?h:m.message,!0));if(p&&(m.partial===void 0||typeof m.totalLines!="number"))return be(n??null,ye(h,!0));if(m.partial===!0&&typeof m.totalLines=="number"){let w=m.grepMatches!==void 0?`[anyray: partial \u2014 ${m.grepMatches} matching line(s) in lines ${m.startLine}-${m.endLine} of ${m.totalLines}`+(m.grepTruncated?`, windows around the first ${pZ} 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 ${m.startLine}-${m.endLine} of ${m.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return be(n??null,ye(`${w}
765
- ${m.content}`))}return be(n??null,ye(m.content))}if(a.name===I0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return be(n??null,ye("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 be(n??null,l.ok?ye(gZ(l.matches)):ye(l.message,!0))}if(a.name===E0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return be(n??null,ye("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(p=>typeof p=="string"):void 0,l=fZ(s.maxResults),d=mZ(s.resultShape),u;try{u=await t.search(i,c,l)}catch(p){u={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:p instanceof Error?p.message:"search failed"}}return be(n??null,u.ok?ye(RE(i,u,d)):ye(u.message??"search failed",!0))}if(a.name===R0.name){let i=typeof s.open=="string"?s.open.trim():"";if(i){let d;try{d=await t.historyOpen(i)}catch(u){d={ok:!1,content:"",path:i,lines:0,truncated:!1,message:u instanceof Error?u.message:"history open failed"}}return be(n??null,d.ok?ye(Zh(d)):ye(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return be(n??null,ye("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 be(n??null,l.ok?ye(wZ(c,l)):ye(l.message??"history search failed",!0))}if(a.name===x0.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return be(n??null,ye("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 be(n??null,l.ok?ye(Zh(l)):ye(l.message??"read failed",!0))}return By(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:By(n??null,-32601,`method not found: ${o}`)}},AZ=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),kd);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Vt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},CZ=(e,t=!0)=>({retrieve:async(n,r)=>va(await e(),n,r),recall:async(n,r)=>vd(await e(),n,r),search:(n,r,o)=>jd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Si(n,r),readTee:async(n,r)=>{if(vy())return{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"the hook tee is off (ANYRAY_HOOK_TEE=off)"};let o=await Ey(n);return o?{...await Si(o,{cwd:lZ.dirname(o),...r}),teePath:o}:{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"not a tee id"}},historySearch:n=>_E(n),historyOpen:n=>PE(n),historyAvailable:async()=>await Ta()>0,advertiseContextTools:t,heartbeat:()=>{e().then(AZ).catch(()=>{})}}),_0=async(e="auto",t={})=>{let n=CZ(()=>nt(e),e!=="claude"),r=t.stdin??process.stdin,o=t.stdout??process.stdout,a=0,s=t.refreshTick??(()=>{let p=Date.now();p<a||(a=p+6e4,kr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=p=>{try{o.write(JSON.stringify(p)+`
766
- `)}catch{}},l=async p=>{let f=p.trim();if(!f)return;let m;try{m=JSON.parse(f)}catch{console.error("anyray mcp: dropping unparseable frame");return}let h;try{h=await bZ(m,n)}catch(w){console.error("anyray mcp: dispatch error",O0(w)),h=m?.id===void 0?null:By(m.id,-32603,"internal error")}h&&c(h),i()};i();let d=setInterval(i,30*6e4);d.unref?.();let u="";try{for await(let p of r){u+=p.toString("utf-8");let f;for(;(f=u.indexOf(`
767
- `))>=0;){let m=u.slice(0,f);u=u.slice(f+1),await l(m)}}u.trim()&&await l(u)}catch(p){console.error("anyray mcp: stdin error",O0(p))}finally{clearInterval(d)}return 0};import{spawn as kZ}from"node:child_process";var vZ=e=>e==="jetbrains"||e==="windsurf"?e:void 0,SZ=async(e,t,n,r=1e4)=>{let o=await new Promise(a=>{let s="",i=!1,c=f=>{i||(i=!0,clearTimeout(l),t.off("data",d),t.off("error",u),t.off("end",p),a(f))},l=setTimeout(()=>c(void 0),r),d=f=>{s+=f.toString();let m=s.indexOf(`
791
+ `);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},GY=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 be(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:LY,capabilities:{tools:{}},serverInfo:NY});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return be(n??null,{});case"tools/list":{let a=[oR,aR];t.advertiseContextTools!==!1&&a.push(sR,iR);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(cR),be(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===oR.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return be(n??null,ye("handle is required",!0));let c=w=>{if(w!==void 0)return typeof w!="number"||!Number.isFinite(w)?null:Math.max(Math.round(w),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return be(n??null,ye("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return be(n??null,ye("grep must be non-empty",!0));if(s.grep.length>256)return be(n??null,ye("grep is limited to 256 characters",!0));u=s.grep}let p=l!==void 0||d!==void 0||u!==void 0,f=xy(i);if(f){let w=await Ry(f);if(u!==void 0)return be(n??null,ye(`${i} is a local hook-tee file, not a stash handle, and grep is not supported on these \u2014 re-call with startLine/endLine, or Read ${w??"the path in the footer"} directly.`,!0));let y=t.readTee?await t.readTee(f,{startLine:l,endLine:d}).catch(b=>({ok:!1,content:"",path:w??f,lines:0,truncated:!1,message:b instanceof Error?b.message:"tee read failed"})):null;if(y?.ok){let b=y.span?`lines ${y.span.startLine}-${y.span.endLine} of ${y.lines}`:`${y.lines} line(s)`,k=y.truncated&&!y.span?.partialLine&&y.span?` Continue with anyray_retrieve(handle="${i}", startLine=${y.span.endLine+1}).`:"";return be(n??null,ye(`[anyray: ${i} is a local hook-tee file, not a stash handle \u2014 served ${b} from ${y.teePath??w}.${k} Read that path directly next time.]
792
+ `+y.content))}let g=y!==null;return be(n??null,ye(`${i} is a hook-tee file id, not a stash handle`+(g&&w?`, and ${w} is not readable`+(y?.message?` (${y.message})`:"")+". The hook writes these files when it trims a tool output; this one has been swept, or the tee is off. Re-run the command to regenerate its output.":`. Read ${w??"the path in its footer"} directly.`),!0))}let m;try{m=await t.retrieve(i,p?{startLine:l,endLine:d,grep:u}:void 0)}catch(w){m={ok:!1,message:w instanceof Error?w.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(!m.ok)return be(n??null,ye(m.kind==="slice-unsupported"?h:m.message,!0));if(p&&(m.partial===void 0||typeof m.totalLines!="number"))return be(n??null,ye(h,!0));if(m.partial===!0&&typeof m.totalLines=="number"){let w=m.grepMatches!==void 0?`[anyray: partial \u2014 ${m.grepMatches} matching line(s) in lines ${m.startLine}-${m.endLine} of ${m.totalLines}`+(m.grepTruncated?`, windows around the first ${$Y} 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 ${m.startLine}-${m.endLine} of ${m.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return be(n??null,ye(`${w}
793
+ ${m.content}`))}return be(n??null,ye(m.content))}if(a.name===aR.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return be(n??null,ye("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 be(n??null,l.ok?ye(UY(l.matches)):ye(l.message,!0))}if(a.name===sR.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return be(n??null,ye("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(p=>typeof p=="string"):void 0,l=MY(s.maxResults),d=BY(s.resultShape),u;try{u=await t.search(i,c,l)}catch(p){u={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:p instanceof Error?p.message:"search failed"}}return be(n??null,u.ok?ye(_E(i,u,d)):ye(u.message??"search failed",!0))}if(a.name===cR.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 be(n??null,d.ok?ye(Kh(d)):ye(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return be(n??null,ye("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 be(n??null,l.ok?ye(HY(c,l)):ye(l.message??"history search failed",!0))}if(a.name===iR.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return be(n??null,ye("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 be(n??null,l.ok?ye(Kh(l)):ye(l.message??"read failed",!0))}return Qy(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Qy(n??null,-32601,`method not found: ${o}`)}},VY=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),vd);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Vt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},KY=(e,t=!0)=>({retrieve:async(n,r)=>va(await e(),n,r),recall:async(n,r)=>Sd(await e(),n,r),search:(n,r,o)=>Zd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Si(n,r),readTee:async(n,r)=>{if(Iy())return{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"the hook tee is off (ANYRAY_HOOK_TEE=off)"};let o=await Ry(n);return o?{...await Si(o,{cwd:DY.dirname(o),...r}),teePath:o}:{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"not a tee id"}},historySearch:n=>LE(n),historyOpen:n=>NE(n),historyAvailable:async()=>await Ta()>0,advertiseContextTools:t,heartbeat:()=>{e().then(VY).catch(()=>{})}}),uR=async(e="auto",t={})=>{let n=KY(()=>nt(e),e!=="claude"),r=t.stdin??process.stdin,o=t.stdout??process.stdout,a=0,s=t.refreshTick??(()=>{let p=Date.now();p<a||(a=p+6e4,vr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=p=>{try{o.write(JSON.stringify(p)+`
794
+ `)}catch{}},l=async p=>{let f=p.trim();if(!f)return;let m;try{m=JSON.parse(f)}catch{console.error("anyray mcp: dropping unparseable frame");return}let h;try{h=await GY(m,n)}catch(w){console.error("anyray mcp: dispatch error",lR(w)),h=m?.id===void 0?null:Qy(m.id,-32603,"internal error")}h&&c(h),i()};i();let d=setInterval(i,30*6e4);d.unref?.();let u="";try{for await(let p of r){u+=p.toString("utf-8");let f;for(;(f=u.indexOf(`
795
+ `))>=0;){let m=u.slice(0,f);u=u.slice(f+1),await l(m)}}u.trim()&&await l(u)}catch(p){console.error("anyray mcp: stdin error",lR(p))}finally{clearInterval(d)}return 0};import{spawn as jY}from"node:child_process";var ZY=e=>e==="jetbrains"||e==="windsurf"?e:void 0,YY=async(e,t,n,r=1e4)=>{let o=await new Promise(a=>{let s="",i=!1,c=f=>{i||(i=!0,clearTimeout(l),t.off("data",d),t.off("error",u),t.off("end",p),a(f))},l=setTimeout(()=>c(void 0),r),d=f=>{s+=f.toString();let m=s.indexOf(`
768
796
  `);m!==-1?c(s.slice(0,m)):s.length>65536&&c(void 0)},u=()=>c(void 0),p=()=>c(s.length>0?s:void 0);t.on("data",d),t.once("error",u),t.once("end",p)});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}})}
769
- `),!0)}catch{return!1}},IZ={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},EZ=(e,t,n)=>{let r=new Set(IZ[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}},P0=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
770
- `),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!nd(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
771
- `),1;await(n.refreshIfDue??zt)().catch(()=>{});let s=await(n.loadProfile??D)(),i=await(n.readBootstrap??Ar)().catch(()=>{});if(i){let g=await(n.ssoGate??Co)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(g.exitCode===2&&g.stderr)return await SZ(g.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(g.stderr),1;s=await(n.loadProfile??D)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
772
- `),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??fn)():void 0,d=xe({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=vZ(n.clientTool);u&&(d.metadata.tool=u);let p=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",f=(n.hookBinaryIsDurable??ce)(),m=Ov(d,t,{mcpServer:f?Ge("profile"):void 0})[p],h=n.spawn??kZ,w=m.command,y=m.args;if(o==="win32"){if(!m.args.every(g=>g==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(g)))return r.write(`Anyray ACP adapter arguments are invalid.
773
- `),1;w=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${m.command}" ${m.args.join(" ")}`]}return await new Promise(g=>{let b=EZ(e,a,m.env),k=h(w,y,{env:b,stdio:"inherit",windowsHide:!0});k.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
774
- `),g(1)}),k.once("exit",(C,S)=>{g(typeof C=="number"?C:S?1:0)})})};import{randomUUID as xZ}from"node:crypto";import{open as RZ,rm as OZ}from"node:fs/promises";import{join as TZ}from"node:path";import{z as Se}from"zod";var fu=Se.string().min(1).refine(e=>Number.isFinite(Date.parse(e)),"expected an ISO-8601 timestamp"),_Z=Se.enum(["reconcile","refresh","repair","status","offboard"]),Fy=Se.union([Se.literal(0),Se.literal(1),Se.literal(2),Se.literal(3),Se.literal(4)]),PZ=Se.enum(["locked","required","recommended","optional"]),mu=Se.object({schemaVersion:Se.literal(1),generatedAt:fu,connectVersion:Se.string().min(1),fleetManaged:Se.boolean(),enrollment:Se.object({state:Se.enum(["enrolled","degraded","broken","none"]),lastRefreshAt:fu.optional(),lastRefreshOutcome:Se.enum(["ok","failed"]).optional()}).strict(),keyExpiresAt:fu.optional(),tools:Se.array(Se.object({id:Se.string().min(1),tier:PZ,routed:Se.boolean()}).strict()),lastVerb:Se.object({verb:_Z,exitCode:Fy,at:fu}).strict()}).strict(),D0=(e,t)=>{if(!e)return!1;let n=Date.parse(e);return Number.isFinite(n)&&n>t},DZ=(e,t,n=Date.now())=>{if(!!!(e.clientKey||e.enrolledCert||t))return"none";let o=e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt;return!e.gateway||!e.enrolledCert||!t||!D0(o,n)?"broken":!e.clientKey||e.clientKeyExpiresAt&&!D0(e.clientKeyExpiresAt,n)?"degraded":"enrolled"},LZ=e=>{let t=e.lastSuccessAt,n=e.lastAttemptAt;if(t===void 0&&n===void 0)return{};let r=Math.max(t??0,n??0);return!Number.isFinite(r)||r<=0?{}:{lastRefreshAt:new Date(r).toISOString(),lastRefreshOutcome:t!==void 0&&t>=(n??0)?"ok":"failed"}},L0=(e,t)=>e.fleetToolPolicy?.tiers?.[t]??"required",NZ=async(e,t)=>{let n=new Set(e.managedTools??[]),r=new Set(e.revertedTools??[]),o=(e.fleetToolPolicy?.enabled??[]).filter(c=>{let l=L0(e,c);return l==="locked"||l==="required"||l==="recommended"&&!r.has(c)}),a=[...new Set([...n,...o])].sort();if(a.length===0)return[];let s=e.gateway,i=[];for(let c of a){let l=t(c),d=!1;if(l&&s&&l.pointsAt)try{let u=await l.detect();if(!u.installed&&!n.has(c))continue;u.installed&&(d=await l.pointsAt(s))}catch{d=!1}i.push({id:c,tier:L0(e,c),routed:d})}return i},N0=async(e,t={})=>{let n=t.now??Date.now,r=await(t.loadProfile??D)(),o=await(t.loadDevKey??$e)().catch(()=>{}),a=await(t.readRefreshState??It)().catch(()=>({})),s={schemaVersion:1,generatedAt:new Date(n()).toISOString(),connectVersion:Ae,fleetManaged:r.anyrayFleetManaged===!0,enrollment:{state:DZ(r,!!o,n()),...LZ(a)},...r.clientKeyExpiresAt&&Number.isFinite(Date.parse(r.clientKeyExpiresAt))?{keyExpiresAt:r.clientKeyExpiresAt}:{},tools:await NZ(r,t.toolById??mt),lastVerb:e};return mu.parse(s)},$Z=()=>TZ(Q(),"status.json"),$0=async(e,t={})=>{let n=mu.parse(e);await(t.ensureStateDir??tt)();let r=$Z(),o=`${r}.${process.pid}.${xZ()}.tmp`,a;try{a=await RZ(o,"wx",384),await a.writeFile(`${JSON.stringify(n,null,2)}
775
- `,"utf8"),await a.chmod(384),await _r(a),await a.close(),a=void 0,await(t.publish??he)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await OZ(o,{force:!0}).catch(()=>{}),s}},Wy=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var MZ=1e4,Ma=e=>e?.name??"Error",Hy=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(MZ)})}catch(o){console.error(`anyray seat offboard report: ${Ma(o)}`)}},BZ=e=>e==="reverted"||e==="queued",hu=async(e={})=>{let t=e.loadProfile??D,n=e.clearDeviceTokenState??Pd,r=e.reportSeatOffboarded??Hy,o=e.clearEnrollment??Xi,a=e.recordManagedTools??Vn,s=e.markSeatOffboarded??zi,i=e.adapterById??mt,c=e.uninstallScheduler??nr,l=e.unitsPresent??kc,d=e.saveProfile??oe,u=await t(),p=u.managedTools??[];await r(u).catch(()=>{}),await n().catch(()=>{});let f=!1,m=!1;try{f=await o()}catch(C){m=!0,console.error(`anyray offboard: clearing enrollment: ${Ma(C)}`)}let h=[],w=[],y=[];for(let C of p){let S=i(C);if(!S){y.push(C);continue}try{let I=await S.revert({dryRun:!1,fullRevert:!0});h.push({id:C,status:I.status}),BZ(I.status)?w.push(C):y.push(C)}catch(I){console.error(`anyray offboard: reverting ${C}: ${Ma(I)}`),y.push(C)}}let g=!0;try{await a(h,!0,!0)}catch(C){g=!1,console.error(`anyray offboard: recording managed tools: ${Ma(C)}`)}let b=y.length===0&&g,k=!1;if(b)try{await s(),k=!0}catch(C){console.error(`anyray offboard: stamping offboard: ${Ma(C)}`)}try{((await t()).refreshSchedulerEnabled||await l())&&await c(),await d({...await t(),refreshSchedulerEnabled:!1})}catch(C){console.error(`anyray offboard: unit teardown: ${Ma(C)}`)}return{reverted:w,unresolved:y,enrollmentCleared:f,credentialHeld:m,recordPersisted:g,offboardMarked:k,ok:y.length===0&&!m&&g&&k}};var ae={success:0,unexpected:1,usage:2,authBroken:3,partial:4},FZ=`Stable non-interactive runtime commands:
797
+ `),!0)}catch{return!1}},JY={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},XY=(e,t,n)=>{let r=new Set(JY[e].map(s=>s.toUpperCase())),o=new Set(Object.keys(n).map(s=>s.toUpperCase())),a={...t};for(let s of Object.keys(a)){let i=s.toUpperCase();(r.has(i)||o.has(i)||i==="APP_SERVER_LOGS")&&delete a[s]}return{...a,...n}},pR=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
798
+ `),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.
799
+ `),1;await(n.refreshIfDue??zt)().catch(()=>{});let s=await(n.loadProfile??P)(),i=await(n.readBootstrap??Cr)().catch(()=>{});if(i){let g=await(n.ssoGate??Co)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(g.exitCode===2&&g.stderr)return await YY(g.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(g.stderr),1;s=await(n.loadProfile??P)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
800
+ `),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??fn)():void 0,d=xe({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=ZY(n.clientTool);u&&(d.metadata.tool=u);let p=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",f=(n.hookBinaryIsDurable??te)(),m=Pv(d,t,{mcpServer:f?Ge("profile"):void 0})[p],h=n.spawn??jY,w=m.command,y=m.args;if(o==="win32"){if(!m.args.every(g=>g==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(g)))return r.write(`Anyray ACP adapter arguments are invalid.
801
+ `),1;w=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${m.command}" ${m.args.join(" ")}`]}return await new Promise(g=>{let b=XY(e,a,m.env),k=h(w,y,{env:b,stdio:"inherit",windowsHide:!0});k.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
802
+ `),g(1)}),k.once("exit",(C,S)=>{g(typeof C=="number"?C:S?1:0)})})};import{randomUUID as zY}from"node:crypto";import{open as qY,rm as QY}from"node:fs/promises";import{join as eJ}from"node:path";import{z as Se}from"zod";var gu=Se.string().min(1).refine(e=>Number.isFinite(Date.parse(e)),"expected an ISO-8601 timestamp"),tJ=Se.enum(["reconcile","refresh","repair","status","offboard"]),eg=Se.union([Se.literal(0),Se.literal(1),Se.literal(2),Se.literal(3),Se.literal(4)]),nJ=Se.enum(["locked","required","recommended","optional"]),wu=Se.object({schemaVersion:Se.literal(1),generatedAt:gu,connectVersion:Se.string().min(1),fleetManaged:Se.boolean(),enrollment:Se.object({state:Se.enum(["enrolled","degraded","broken","none"]),lastRefreshAt:gu.optional(),lastRefreshOutcome:Se.enum(["ok","failed"]).optional()}).strict(),keyExpiresAt:gu.optional(),tools:Se.array(Se.object({id:Se.string().min(1),tier:nJ,routed:Se.boolean()}).strict()),lastVerb:Se.object({verb:tJ,exitCode:eg,at:gu}).strict()}).strict(),fR=(e,t)=>{if(!e)return!1;let n=Date.parse(e);return Number.isFinite(n)&&n>t},rJ=(e,t,n=Date.now())=>{if(!!!(e.clientKey||e.enrolledCert||t))return"none";let o=e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt;return!e.gateway||!e.enrolledCert||!t||!fR(o,n)?"broken":!e.clientKey||e.clientKeyExpiresAt&&!fR(e.clientKeyExpiresAt,n)?"degraded":"enrolled"},oJ=e=>{let t=e.lastSuccessAt,n=e.lastAttemptAt;if(t===void 0&&n===void 0)return{};let r=Math.max(t??0,n??0);return!Number.isFinite(r)||r<=0?{}:{lastRefreshAt:new Date(r).toISOString(),lastRefreshOutcome:t!==void 0&&t>=(n??0)?"ok":"failed"}},mR=(e,t)=>e.fleetToolPolicy?.tiers?.[t]??"required",aJ=async(e,t)=>{let n=new Set(e.managedTools??[]),r=new Set(e.revertedTools??[]),o=(e.fleetToolPolicy?.enabled??[]).filter(c=>{let l=mR(e,c);return l==="locked"||l==="required"||l==="recommended"&&!r.has(c)}),a=[...new Set([...n,...o])].sort();if(a.length===0)return[];let s=e.gateway,i=[];for(let c of a){let l=t(c),d=!1;if(l&&s&&l.pointsAt)try{let u=await l.detect();if(!u.installed&&!n.has(c))continue;u.installed&&(d=await l.pointsAt(s))}catch{d=!1}i.push({id:c,tier:mR(e,c),routed:d})}return i},hR=async(e,t={})=>{let n=t.now??Date.now,r=await(t.loadProfile??P)(),o=await(t.loadDevKey??$e)().catch(()=>{}),a=await(t.readRefreshState??It)().catch(()=>({})),s={schemaVersion:1,generatedAt:new Date(n()).toISOString(),connectVersion:Ae,fleetManaged:r.anyrayFleetManaged===!0,enrollment:{state:rJ(r,!!o,n()),...oJ(a)},...r.clientKeyExpiresAt&&Number.isFinite(Date.parse(r.clientKeyExpiresAt))?{keyExpiresAt:r.clientKeyExpiresAt}:{},tools:await aJ(r,t.toolById??mt),lastVerb:e};return wu.parse(s)},sJ=()=>eJ(Q(),"status.json"),yR=async(e,t={})=>{let n=wu.parse(e);await(t.ensureStateDir??tt)();let r=sJ(),o=`${r}.${process.pid}.${zY()}.tmp`,a;try{a=await qY(o,"wx",384),await a.writeFile(`${JSON.stringify(n,null,2)}
803
+ `,"utf8"),await a.chmod(384),await Pr(a),await a.close(),a=void 0,await(t.publish??he)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await QY(o,{force:!0}).catch(()=>{}),s}},tg=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var iJ=1e4,Wa=e=>e?.name??"Error",ng=async(e,t=fetch)=>{let n=e.gateway?.replace(/\/+$/,""),r=e.clientKey;if(!(!n||!r))try{await t(`${n}/connect/offboard`,{method:"POST",headers:{"x-anyray-api-key":r},signal:AbortSignal.timeout(iJ)})}catch(o){console.error(`anyray seat offboard report: ${Wa(o)}`)}},cJ=e=>e==="reverted"||e==="queued",bu=async(e={})=>{let t=e.loadProfile??P,n=e.clearDeviceTokenState??Dd,r=e.reportSeatOffboarded??ng,o=e.clearEnrollment??Xi,a=e.recordManagedTools??Kn,s=e.markSeatOffboarded??zi,i=e.adapterById??mt,c=e.uninstallScheduler??rr,l=e.unitsPresent??kc,d=e.saveProfile??ae,u=await t(),p=u.managedTools??[];await r(u).catch(()=>{}),await n().catch(()=>{});let f=!1,m=!1;try{f=await o()}catch(C){m=!0,console.error(`anyray offboard: clearing enrollment: ${Wa(C)}`)}let h=[],w=[],y=[];for(let C of p){let S=i(C);if(!S){y.push(C);continue}try{let I=await S.revert({dryRun:!1,fullRevert:!0});h.push({id:C,status:I.status}),cJ(I.status)?w.push(C):y.push(C)}catch(I){console.error(`anyray offboard: reverting ${C}: ${Wa(I)}`),y.push(C)}}let g=!0;try{await a(h,!0,!0)}catch(C){g=!1,console.error(`anyray offboard: recording managed tools: ${Wa(C)}`)}let b=y.length===0&&g,k=!1;if(b)try{await s(),k=!0}catch(C){console.error(`anyray offboard: stamping offboard: ${Wa(C)}`)}try{((await t()).refreshSchedulerEnabled||await l())&&await c(),await d({...await t(),refreshSchedulerEnabled:!1})}catch(C){console.error(`anyray offboard: unit teardown: ${Wa(C)}`)}return{reverted:w,unresolved:y,enrollmentCleared:f,credentialHeld:m,recordPersisted:g,offboardMarked:k,ok:y.length===0&&!m&&g&&k}};var ie={success:0,unexpected:1,usage:2,authBroken:3,partial:4},lJ=`Stable non-interactive runtime commands:
776
804
  anyray-connect reconcile
777
805
  anyray-connect refresh
778
806
  anyray-connect repair
@@ -788,35 +816,7 @@ Exit codes:
788
816
  1 unexpected error
789
817
  2 usage error (unknown flag or argument)
790
818
  3 authentication broken; re-enrollment required
791
- 4 partial; the command ran but drift remains`,WZ={reconcile:"reconcile",__anyray_reconcile:"reconcile",refresh:"refresh",__anyray_refresh:"refresh",repair:"repair",__anyray_repair:"repair",status:"status",__anyray_status:"status",offboard:"offboard",__anyray_offboard:"offboard"},HZ=e=>e.replaceAll("-","_"),F0=e=>{let t=e[0];if(!t)return;let n=WZ[HZ(t)];if(!n)return;let r=e.slice(1);if(n==="status"&&t==="status"&&!r.includes("--json"))return;if(r.length===1&&(r[0]==="--help"||r[0]==="-h"))return{verb:n,help:!0,usageError:!1};let a=n==="status"?t==="status"?r.length===1&&r[0]==="--json":r.length===0||r.length===1&&r[0]==="--json":r.length===0;return{verb:n,help:!1,usageError:!a}},Uy=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},UZ=async(e=D,t=Date.now())=>{let n=await e(),r=Date.parse(n.enrolledCertExpiry??n.enrolledCert?.payload.expiresAt??""),o=!!n.enrolledCert&&Number.isFinite(r)&&r>t,a=Date.parse(n.clientKeyExpiresAt??""),s=n.clientKeyExpiresAt!==void 0&&(!Number.isFinite(a)||a<=t);if(!n.gateway)return"auth-broken";if(!n.clientKey||s)return o?"credential-degraded":"auth-broken";try{let i=await Aa(n.gateway,n.clientKey);return await Ca(i)}catch(i){if(dh(i))return o?"credential-degraded":"auth-broken";throw i}},GZ=e=>e==="auth-broken"?ae.authBroken:e==="credential-degraded"||e.toolsApplied<e.toolsRequested||e.toolsTombstoned.length>0?ae.partial:ae.success,VZ=e=>e.refresh==="not-enrolled"||e.refresh==="cert-expired"||e.refresh==="cert-rejected"?ae.authBroken:e.refresh==="failed"?ae.unexpected:e.partial||e.refresh==="disabled"||e.refresh==="backoff"||e.refresh==="throttled"||e.refresh==="gateway-incompatible"?ae.partial:ae.success,KZ=e=>!e.enrollment.enrolled||e.enrollment.expired===!0||e.verify?.kind==="enrollment-required",M0=async e=>{let t;return{code:await au({repair:e,quick:!e,silent:!0},{captureReport:r=>t=r}),authBroken:t?KZ(t):!1}},B0=e=>typeof e!="number"&&e.authBroken?ae.authBroken:(typeof e=="number"?e:e.code)===0?ae.success:ae.partial,jZ=(e,t)=>{let n=Wy(t);return n===ae.authBroken?n:e!==0||n===ae.partial?ae.partial:ae.success},ZZ=async(e,t)=>{if(e==="reconcile")return GZ(await(t.reconcile??(()=>UZ(t.loadProfile)))());if(e==="refresh"){if(!t.refresh)throw new Error("refresh runtime is unavailable");return VZ(await t.refresh())}return e==="repair"?B0(await(t.repair??(()=>M0(!0)))()):e==="status"?B0(await(t.status??(()=>M0(!1)))()):(await(t.offboard??hu)()).ok?ae.success:ae.partial},Gy=(e,t)=>mu.parse({...e,lastVerb:{...e.lastVerb,exitCode:t}}),W0=async(e,t={})=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.help)return n(FZ),ae.success;let o=t.now??Date.now,a=new Date(o()).toISOString(),s=t.withProfileLock??Xa,i=t.buildStatus??N0,c=t.writeStatus??$0,l,d=e.usageError?ae.usage:ae.unexpected;e.usageError&&r(`anyray-connect ${e.verb}: UsageError`);try{await s(async()=>{if(!e.usageError)try{d=Fy.parse(await ZZ(e.verb,t))}catch(u){d=dh(u)?ae.authBroken:ae.unexpected,r(`anyray-connect ${e.verb}: ${Uy(u)}`)}if(l=await i({verb:e.verb,exitCode:d,at:a},{now:o}),(e.verb==="repair"||e.verb==="status")&&d!==ae.unexpected&&d!==ae.usage&&d!==ae.authBroken)d=jZ(d===0?0:1,l);else if(e.verb!=="offboard"&&d!==ae.unexpected&&d!==ae.usage){let u=Wy(l);(u===ae.authBroken||d===ae.success)&&(d=u)}l=Gy(l,d);try{await c(l)}catch(u){d=ae.unexpected,l=Gy(l,d),r(`anyray-connect ${e.verb}: ${Uy(u)}`)}})}catch(u){d=ae.unexpected,r(`anyray-connect ${e.verb}: ${Uy(u)}`);try{l=Gy(await i({verb:e.verb,exitCode:d,at:a},{now:o}),d)}catch{l=void 0}}return n(JSON.stringify(l||{schemaVersion:1,generatedAt:a,connectVersion:"unknown",fleetManaged:!1,enrollment:{state:"broken"},tools:[],lastVerb:{verb:e.verb,exitCode:d,at:a}})),d};import{createReadStream as YZ}from"node:fs";import{spawnSync as q0}from"node:child_process";import{createHash as JZ}from"node:crypto";import{access as Q0,chmod as jy,copyFile as XZ,lstat as zZ,mkdir as qZ,mkdtemp as eR,readFile as Au,rename as QZ,rm as Or,stat as eY,writeFile as tY}from"node:fs/promises";import{constants as tR}from"node:fs";import{platform as Wa,tmpdir as nY}from"node:os";import{dirname as rY,isAbsolute as oY,join as gu}from"node:path";import{z as Le}from"zod";var aY="fleetd-installer-v4.89.2",H0=`https://github.com/anyrayHQ/install/releases/download/${aY}`,sY=1e4,iY=1e4,U0=31,cY=1500,nR=20*1024,Vy=20,lY="0.25",dY="/var/tmp",Fa="/Library/LaunchDaemons/com.fleetdm.orbit.plist",wu="/etc/default/orbit",Wi="/opt/orbit/anyray-enroll-secret.txt",rR="/opt/orbit/secret-orbit-node-key.txt",uY="/opt/orbit/bin/orbit/orbit",Hi="C:\\Program Files\\Orbit",pY=`${Hi}\\bin\\orbit`,oR=`${Hi}\\secret-orbit-node-key.txt`,Fi=`${Hi}\\secret.txt`,fY=`${Hi}\\fleet_url.txt`,aR=`${Hi}\\anyray-managed.txt`,bu="Fleet osquery",Zy="C:\\Windows\\System32\\sc.exe",mY="C:\\Windows\\System32\\whoami.exe",yu="C:\\Windows\\System32\\icacls.exe",hY="C:\\Windows\\System32\\msiexec.exe",Yy="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",G0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],yY=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],gY=`anyray-connect endpoint install
792
-
793
- Install Fleet's signed endpoint agent and enroll this machine in Anyray.
794
-
795
- Supported on macOS, Linux and Windows.
796
-
797
- The command uses the current seat's stored gateway key. Administrator access is
798
- required: on macOS and Linux Connect asks through sudo once when /dev/tty is
799
- available; on Windows, run it from a shell started as Administrator.`,zy=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),sR=(e,t=Wa())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),iR=(e,t=Wa(),n=!1)=>(zy(e)||n)&&t!=="win32",se=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},wY=Le.object({kind:Le.enum(["pkg","deb","rpm","msi"]),path:Le.string().min(1).refine(oY),sha256:Le.string().regex(/^[0-9a-f]{64}$/)}).strict(),bY=Le.object({action:Le.literal("restart"),os:Le.enum(["darwin","linux","win32"])}).strict(),AY=Le.object({action:Le.literal("configure"),os:Le.enum(["darwin","linux","win32"]),fleetUrl:Le.string().min(1).max(2048),enrollSecret:Le.string().min(1).max(4096),package:wY.optional()}).strict(),CY=Le.discriminatedUnion("action",[bY,AY]),Ui=(e,t)=>{let n=q0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},qy=async e=>{try{return await Q0(e,tR.F_OK),!0}catch{return!1}},kY=async e=>{try{let t=await eY(e);return t.isFile()&&t.size>0}catch{return!1}},Qy=(e,t)=>{for(let n=0;;){let r=e.indexOf("<key>",n);if(r<0)return null;let o=e.indexOf("</key>",r);if(o<0)return null;if(e.slice(r+5,o).trim()===t)return{start:r,end:o+6};n=o+6}},Ky=(e,t)=>Qy(e,t)!==null,V0=e=>e==="win32"?Fi:Wi,vY=e=>e==="win32"?oR:rR,SY=e=>Ky(e,"ORBIT_FLEET_URL")&&Ky(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Wi}</string>`)&&!Ky(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),IY=e=>{let t=(n,r)=>e.split(`
800
- `).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Wi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Jy=(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()},cR=e=>{let t=e(Zy,["qc",bu,"8192"]);return t.status===0?t.stdout:""},Xy=e=>{let t=e(Yy,yY(bu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},EY=async e=>{try{return e==="win32"?Jy(e,cR(Ui)):Jy(e,await Au(e==="darwin"?Fa:wu,"utf8"))}catch{return}},xY=async e=>{try{if(e==="win32")return await qy(aR)&&Jy(e,cR(Ui))!==void 0;let n=await Au(e==="darwin"?Fa:wu,"utf8");return e==="darwin"?SY(n):IY(n)}catch{return!1}},lR=async(e,t={})=>{let n=t.exists??qy,r=t.command??Ui,o,a="absent";if(e==="win32")a=Xy(r),o=await n(pY)&&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(uY)&&l}let s=await(t.configured??xY)(e),i=await(t.hasNodeKey??(()=>kY(vY(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}},RY=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),dR=(e,t)=>{let n=Qy(e,t);if(!n)return null;let r=n.start;for(;r>0&&(e[r-1]===" "||e[r-1]===" ");)r--;r>0&&e[r-1]===`
801
- `&&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},OY=(e,t)=>{let n=dR(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},K0=(e,t,n)=>{let r=`
802
- <key>${t}</key>
803
- <string>${RY(n)}</string>`,o=dR(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Qy(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new se("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)},TY=(e,t,n=Wi)=>{let r=OY(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=K0(r,"ORBIT_FLEET_URL",t),K0(r,"ORBIT_ENROLL_SECRET_PATH",n)},_Y=(e,t,n=Wi)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
804
- `).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(`
805
- `).trimEnd()}
806
-
807
- # Managed by anyray-connect endpoint install.
808
- # ORBIT_ENROLL_SECRET is deliberately ABSENT: orbit refuses to start when both
809
- # it and ORBIT_ENROLL_SECRET_PATH are set, and the secret belongs in a 0600
810
- # file, never in this world-readable one.
811
- ORBIT_FLEET_URL=${t}
812
- ORBIT_ENROLL_SECRET_PATH=${n}
813
- `},uR=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}},PY=Le.object({code:Le.string().min(1).optional(),message:Le.string().min(1).optional()}).passthrough(),j0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},DY=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=PY.safeParse(t);if(!r.success)return n;let o=j0(r.data.message??""),a=j0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},Z0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??iY),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":Ae},body:"{}",signal:r.signal})}catch{throw new se("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new se("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new se(DY(a.status,c))}let s;try{s=await a.json()}catch{throw new se("The gateway returned malformed endpoint enrollment data.")}let i=Le.object({fleetUrl:Le.string().min(1).max(2048),enrollSecret:Le.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!uR(i.data.fleetUrl))throw new se("The gateway returned invalid endpoint enrollment data.");return i.data},LY=async(e={})=>{let t=e.exists??qy;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 se("Linux endpoint installation requires either dpkg or rpm.")},NY=async e=>e==="darwin"?"pkg":e==="win32"?"msi":LY(),eg=e=>`fleetd.${e}`,$Y=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",MY=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),sY);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},BY=async(e,t={})=>{let n=eg(e),r=t.fetchResponse??fetch,o;try{o=await MY(`${H0}/SHA256SUMS`,r)}catch{throw new se("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new se(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=ny(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await eR(gu(nY(),"anyray-endpoint-")),i=gu(s,n);try{await jy(s,448),await(t.download??ay)(`${H0}/${n}`,i,a)}catch(c){if(await Or(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Ri&&c.status===404)return;throw new se("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Or(s,{recursive:!0,force:!0})}},FY=async(e,t,n)=>{await qZ(rY(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Or(r,{force:!0});try{await tY(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await QZ(r,e)}catch(o){throw await Or(r,{force:!0}).catch(()=>{}),o}},Y0=async e=>{let t=JZ("sha256");for await(let n of YZ(e))t.update(n);return t.digest("hex")},WY=async(e,t={})=>{let n=await zZ(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new se("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await Y0(e.path)!==e.sha256)throw new se("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await eR(gu(dY,"anyray-endpoint-root-")),o=gu(r,eg(e.kind));try{if(await jy(r,448),await XZ(e.path,o),await jy(o,384),await Y0(o)!==e.sha256)throw new se("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Or(r,{recursive:!0,force:!0})}}catch(a){throw await Or(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ba=(e,t)=>{if(e.status!==0)throw new se(t)},J0="com.fleetdm.fleetd.config",HY="com.fleetdm.fleetd.enroll.secret",UY=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",rR],GY=[fY,oR],VY=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(J0))throw new se(`This machine already receives its endpoint configuration from an MDM profile (${J0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},X0=async(e,t,n)=>{let r=n.removeFile??(o=>Or(o,{force:!0}));for(let o of e==="win32"?GY:UY)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",HY,"/Library/Keychains/System.keychain"])},KY=e=>{e(yu,[Fi,"/inheritance:r"]),e(yu,[Fi,"/grant:r","*S-1-5-18:(F)"]),e(yu,[Fi,"/grant:r","*S-1-5-32-544:(F)"]),e(yu,[Fi,"/remove:g","*S-1-5-32-545"])},jY=(e,t,n)=>{if(e.kind==="pkg"){Ba(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ba(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ba(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ba(t(hY,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},ZY=(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",[lY])}throw new se(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(Zy,["stop",bu]);for(let n=0;n<Vy;n++){let r=Xy(t);if(r==="Stopped"||r==="absent")break;t(Yy,G0)}for(let n=0;n<Vy;n++){if(t(Zy,["start",bu]).status===0||Xy(t)==="Running")return;t(Yy,G0)}throw new se("Orbit was configured, but the Windows service could not be started.")}Ba(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ba(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},YY=e=>new Promise(t=>setTimeout(t,e)),pR=async(e,t={})=>{let n=t.command??Ui,r=t.readText??(c=>Au(c,"utf8")),o=t.writeText??FY,a=t.removeSecret??(()=>Or(V0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&VY(n),e.package&&!$Y(e.os,e.package.kind))throw new se("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new se("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await X0(e.os,n,t),e.package){let d=await(t.preparePackage??WY)(e.package);i=d.cleanup,jY(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Fa);await o(Fa,TY(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(wu);await o(wu,_Y(d,e.fleetUrl),420)}else await o(aR,`anyray
814
- `,384);e.os!=="win32"&&await X0(e.os,n,t),await o(V0(e.os),`${e.enrollSecret}
815
- `,384),e.os==="win32"&&KY(n),s=e.os!=="win32"}ZY(e.os,n);let c=t.checkIn??(async d=>{let u=await lR(d);return u.running&&u.checkedIn}),l=t.wait??YY;for(let d=0;d<(t.attempts??U0);d++){if(await c(e.os))return;d+1<(t.attempts??U0)&&await l(cY)}throw new se("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(()=>{})}},JY=async()=>{try{return await Q0("/dev/tty",tR.R_OK),!0}catch{return!1}},XY=12288,zY=e=>{let t=e(mY,["/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>=XY},qY=async(e,t={})=>{if((t.os??Wa())==="win32")return(t.elevated??(()=>zY(t.command??Ui)))()?(await e(),"direct"):((t.print??A)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
816
- anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??JY)()){if(await(t.reexec??(async()=>1))()!==0)throw new se("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??A)(`Administrator access is required. Run:
817
- sudo anyray-connect endpoint install`),"deferred"},QY=async e=>{let t=`${JSON.stringify(e)}
818
- `;if(Buffer.byteLength(t)>nR)throw new se("The privileged endpoint plan is unexpectedly large.");let n=en(["__anyray-endpoint-install"]);return q0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},eJ=async(e,t={})=>(t.withRoot??qY)(()=>(t.apply??pR)(e),{...t.root,reexec:()=>(t.sudo??QY)(e)}),z0=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return D();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return D();let t;try{let s=(await Au("/etc/passwd","utf8")).split(`
819
- `).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Wa()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await D()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},fR=async(e={},t={})=>{let n=t.os??Wa();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new se("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??lR)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??z0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??EY)(r);if(!l||!d||u===void 0)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};let p=await(t.fetchEnrollment??Z0)(l,d);if(u===p.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};$("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new se("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??z0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new se("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??Z0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let p=await(t.packageKind??(()=>NY(r)))();if(i=await(t.stagePackage??BY)(p),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${eg(p)} 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??eJ)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},tg=e=>e instanceof se?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",mR=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return A(gY),0;if(e.length!==1||e[0]!=="install")return O("Usage: anyray-connect endpoint install"),1;try{let t=await fR();return t.message&&(t.outcome==="installed"?M(t.message):$(t.message)),0}catch(t){return O(tg(t)),1}},tJ=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>nR)throw new se("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new se("The privileged endpoint plan is malformed.")}let r=CY.safeParse(n);if(!r.success||r.data.os!==Wa()||r.data.action==="configure"&&!uR(r.data.fleetUrl))throw new se("The privileged endpoint plan is invalid.");return r.data},hR=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 pR(await tJ()),0}catch(t){return O(tg(t)),1}},yR=async(e,t=fR)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?M(n.message):$(n.message)),n.outcome}catch(n){$(`Endpoint agent: ${tg(n)} Tool routing remains configured.`);return}};var nJ=new Set(["not-due","repaired","cert-renewed","heartbeat-refreshed","refreshed"]),gR=async(e,t={})=>await(t.fleetdPresent??Ao)()?nJ.has(e)?{retired:!0,messages:(await(t.uninstallScheduler??nr)()).messages}:{retired:!1,reason:"refresh-unhealthy",messages:[]}:{retired:!1,reason:"no-fleetd",messages:[]};var wR=["reapply_config","remint","revert","revert_tool","update"],rJ=/^[a-z0-9][a-z0-9-]{0,31}$/;var oJ=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"||!wR.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&rJ.test(t.tool):t.tool===void 0},ng=e=>e?.name??"error",bR=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":wR.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!oJ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",ng(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",ng(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:",ng(i))}return a.kind};var AR=e=>e?.name??"Error",CR=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??D,r=t.recordManagedTools??Vn,o=t.adapterById??mt,a=t.isLocked??di,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}: ${AR(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${AR(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as vR}from"node:os";var SR=`${V("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
819
+ 4 partial; the command ran but drift remains`,dJ={reconcile:"reconcile",__anyray_reconcile:"reconcile",refresh:"refresh",__anyray_refresh:"refresh",repair:"repair",__anyray_repair:"repair",status:"status",__anyray_status:"status",offboard:"offboard",__anyray_offboard:"offboard"},uJ=e=>e.replaceAll("-","_"),bR=e=>{let t=e[0];if(!t)return;let n=dJ[uJ(t)];if(!n)return;let r=e.slice(1);if(n==="status"&&t==="status"&&!r.includes("--json"))return;if(r.length===1&&(r[0]==="--help"||r[0]==="-h"))return{verb:n,help:!0,usageError:!1};let a=n==="status"?t==="status"?r.length===1&&r[0]==="--json":r.length===0||r.length===1&&r[0]==="--json":r.length===0;return{verb:n,help:!1,usageError:!a}},rg=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},pJ=async(e=P,t=Date.now())=>{let n=await e(),r=Date.parse(n.enrolledCertExpiry??n.enrolledCert?.payload.expiresAt??""),o=!!n.enrolledCert&&Number.isFinite(r)&&r>t,a=Date.parse(n.clientKeyExpiresAt??""),s=n.clientKeyExpiresAt!==void 0&&(!Number.isFinite(a)||a<=t);if(!n.gateway)return"auth-broken";if(!n.clientKey||s)return o?"credential-degraded":"auth-broken";try{let i=await Aa(n.gateway,n.clientKey);return await Ca(i)}catch(i){if(ch(i))return o?"credential-degraded":"auth-broken";throw i}},fJ=e=>e==="auth-broken"?ie.authBroken:e==="credential-degraded"||e.toolsApplied<e.toolsRequested||e.toolsTombstoned.length>0?ie.partial:ie.success,mJ=e=>e.refresh==="not-enrolled"||e.refresh==="cert-expired"||e.refresh==="cert-rejected"?ie.authBroken:e.refresh==="failed"?ie.unexpected:e.partial||e.refresh==="disabled"||e.refresh==="backoff"||e.refresh==="throttled"||e.refresh==="gateway-incompatible"?ie.partial:ie.success,hJ=e=>!e.enrollment.enrolled||e.enrollment.expired===!0||e.verify?.kind==="enrollment-required",gR=async e=>{let t;return{code:await ou({repair:e,quick:!e,silent:!0},{captureReport:r=>t=r}),authBroken:t?hJ(t):!1}},wR=e=>typeof e!="number"&&e.authBroken?ie.authBroken:(typeof e=="number"?e:e.code)===0?ie.success:ie.partial,yJ=(e,t)=>{let n=tg(t);return n===ie.authBroken?n:e!==0||n===ie.partial?ie.partial:ie.success},gJ=async(e,t)=>{if(e==="reconcile")return fJ(await(t.reconcile??(()=>pJ(t.loadProfile)))());if(e==="refresh"){if(!t.refresh)throw new Error("refresh runtime is unavailable");return mJ(await t.refresh())}return e==="repair"?wR(await(t.repair??(()=>gR(!0)))()):e==="status"?wR(await(t.status??(()=>gR(!1)))()):(await(t.offboard??bu)()).ok?ie.success:ie.partial},og=(e,t)=>wu.parse({...e,lastVerb:{...e.lastVerb,exitCode:t}}),AR=async(e,t={})=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.help)return n(lJ),ie.success;let o=t.now??Date.now,a=new Date(o()).toISOString(),s=t.withProfileLock??Xa,i=t.buildStatus??hR,c=t.writeStatus??yR,l,d=e.usageError?ie.usage:ie.unexpected;e.usageError&&r(`anyray-connect ${e.verb}: UsageError`);try{await s(async()=>{if(!e.usageError)try{d=eg.parse(await gJ(e.verb,t))}catch(u){d=ch(u)?ie.authBroken:ie.unexpected,r(`anyray-connect ${e.verb}: ${rg(u)}`)}if(l=await i({verb:e.verb,exitCode:d,at:a},{now:o}),(e.verb==="repair"||e.verb==="status")&&d!==ie.unexpected&&d!==ie.usage&&d!==ie.authBroken)d=yJ(d===0?0:1,l);else if(e.verb!=="offboard"&&d!==ie.unexpected&&d!==ie.usage){let u=tg(l);(u===ie.authBroken||d===ie.success)&&(d=u)}l=og(l,d);try{await c(l)}catch(u){d=ie.unexpected,l=og(l,d),r(`anyray-connect ${e.verb}: ${rg(u)}`)}})}catch(u){d=ie.unexpected,r(`anyray-connect ${e.verb}: ${rg(u)}`);try{l=og(await i({verb:e.verb,exitCode:d,at:a},{now:o}),d)}catch{l=void 0}}return n(JSON.stringify(l||{schemaVersion:1,generatedAt:a,connectVersion:"unknown",fleetManaged:!1,enrollment:{state:"broken"},tools:[],lastVerb:{verb:e.verb,exitCode:d,at:a}})),d};var wJ=new Set(["not-due","repaired","cert-renewed","heartbeat-refreshed","refreshed"]),CR=async(e,t={})=>await(t.fleetdPresent??Ao)()?wJ.has(e)?{retired:!0,messages:(await(t.uninstallScheduler??rr)()).messages}:{retired:!1,reason:"refresh-unhealthy",messages:[]}:{retired:!1,reason:"no-fleetd",messages:[]};var kR=["reapply_config","remint","revert","revert_tool","update"],bJ=/^[a-z0-9][a-z0-9-]{0,31}$/;var AJ=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||t.id.length===0||typeof t.kind!="string"||!kR.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&bJ.test(t.tool):t.tool===void 0},ag=e=>e?.name??"error",vR=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":kR.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!AJ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",ag(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",ag(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:",ag(i))}return a.kind};var SR=e=>e?.name??"Error",IR=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??P,r=t.recordManagedTools??Kn,o=t.adapterById??mt,a=t.isLocked??di,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}: ${SR(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${SR(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as xR}from"node:os";var RR=`${V("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
820
820
 
821
821
  ${V("Usage")}
822
822
  npx anyray-connect [options]
@@ -861,7 +861,7 @@ ${V("What it does")}
861
861
  key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
862
862
  metadata (user/team) is attached \u2014 never prompt content.
863
863
  ~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
864
- per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,IR=`${V("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
864
+ per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,OR=`${V("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
865
865
 
866
866
  ${V("Usage")}
867
867
  npx anyray-connect <gateway-url> [options]
@@ -1063,22 +1063,22 @@ ${V("What it does")}
1063
1063
  key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
1064
1064
  metadata (user/team) is attached \u2014 never prompt content.
1065
1065
  ~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
1066
- per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,aJ=e=>{let t=e?.trim();return t||Ph()},Cu=(e,t)=>t||e,ER=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"--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},sJ=e=>!e||e.length===0?le:e.map(t=>{let n=mt(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${le.map(r=>r.id).join(", ")}`);return n}),iJ=(e,t)=>{if(U("Gateway target"),A(` Origin: ${et(e.origin)}`),e.byoUpstream)A(` Auth: BYO upstream key ${v(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&A(` Client key: personal gateway key (${Tt(e.clientKey)}) ${v("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=ee(e,"anthropic")?et("your subscription"):"org key",r=ee(e,"openai")?et("your subscription"):"org key";A(` Auth: auto ${v("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&A(` Client key: personal gateway key (${Tt(e.clientKey)})`)}else e.authMode==="subscription"?(A(` Auth: subscription pass-through ${v("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&A(` Client key: personal gateway key (${Tt(e.clientKey)}) ${v("rides x-anyray-api-key")}`)):e.clientKey?A(` Auth: personal gateway key (${Tt(e.clientKey)}) ${v("(replaces the placeholder)")}`):A(` Enrollment: ${v("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&A(` Cursor: ${et("native Team subscription")} ${v("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(ee(e,"anthropic")?(A(` Claude Desktop: ${et("subscription-backed Gateway lane")} ${v("(verified macOS builds; Windows fails closed)")}`),A(` ${v("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(A(` Claude Desktop: ${et("third-party API lane")} ${v("(API-billed; switches the active local inference profile)")}`),A(` ${v("The first-party Claude subscription remains untouched.")}`))),A(` Attribution: ${ue(e.metadata)??v("(none \u2014 pass --user)")}`)},kR=async(e,t)=>{U("Selected tools");for(let n of e){let r=await n.detect();r.installed?A(` ${n.title} ${v(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):$(` ${n.title} ${v(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},cJ=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Ee(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},lJ={loadDevKey:$e,saveDevKey:Ji,clearDevKey:Ja,saveProfile:oe},dJ=async(e,t,n,r=lJ,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}},uJ=async(e,t,n,r,o)=>{let a=0,s=[],i=[],c=[],l=[],d=[];for(let u of e){if(!(await u.detect()).installed&&!r){d.push(u.title);continue}U(`${u.title} ${v(`(${u.id})`)}`);try{let f=r?await u.revert(n):await u.apply(t,{...n,explicit:o?.has(u.id)===!0,reportsToUser:!0});for(let m of f.messages)A(` ${m}`);a+=f.changedFiles?.length??0,l.push({id:u.id,status:f.status}),f.status==="configured"||f.status==="reverted"?M(` ${f.status}`):f.status==="manual"?(s.push(u.title),f.manualAudience==="admin"?(i.push(u.title),c.push(u.id),_(" blocked by machine policy \u2014 your IT team owns this one")):_(" manual step required (see above)")):f.status==="held"?$(" left on its own plan (no change)"):$(` ${f.status}`)}catch(f){l.push({id:u.id,status:"failed"}),O(` failed: ${f instanceof Error?f.message:String(f)}`)}}if(d.length>0&&$(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await ec().catch(()=>[]);u.length&&$(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},pJ=(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},fJ=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>xR(o)&&!r.has(o.id))},mJ=async e=>{let t=gE(e,process.platform,Q());if(t){await we(t.path,t.content);for(let n of wE(t,process.platform))A(` ${n}`)}},hJ=async(e,t,n=vR())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!ib(i,n)||!sb(i,n))continue;let c=ob(i,n);if(!o.has(c)){try{if(!(await a.detect()).installed||!s.isRunning()||await a.pointsAt?.(t)===!0)continue}catch{continue}o.add(c),r.push({id:a.id,title:ab(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},yJ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,gJ=e=>`
1067
- ${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?`}`,wJ=async(e,t={})=>{let n=t.requestQuit??(a=>lb(a)),r=t.waitFor??(a=>db(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),M(` Closed ${a.title}.`);continue}_(` ${a.title} is still open \u2014 leaving it alone.`),$(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},bJ=(e,t={})=>{let n=t.relaunch??(o=>ub(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),M(` Reopened ${o.title}.`)):_(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},xR=e=>e.changesBilling===!0||e.changesOrgManagement===!0,RR=e=>e.changesBilling===!0?"moves inference spend from your subscription to the org API bill":e.changesOrgManagement===!0?"switches the app to third-party mode; claude.ai Enterprise org settings stop applying":void 0,rg=e=>!xR(e),AJ=async(e,t,n={})=>{let r=n.hasEnrollment??Nu,o=n.canMultiSelect??KE,a=n.multiSelect??jE,s=n.prompt??xa,i=n.registry??le;if(A(V("Anyray connect \u2014 guided setup")),A(v("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())A("Stored enrollment will be reused. Run with --revert to clear it.");else if(!e.enroll&&!e.sso&&!e.gateway){U("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{A(" 1. Paste an enrollment link"),A(" 2. Sign in with SSO"),A(" 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||_("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&&ci(d)&&pd(d)){e.enroll=d;break}_("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&&St(d)){e.sso=d;break}_("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&&ci(d)){e.enroll=d,A("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=Qt(d);break}catch{_("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){U("Tools detected");let c=[],l=[];for(let u of i){if(!(await u.detect()).installed){l.push(u);continue}c.push(u)}let d=c.filter(u=>rg(u)).map(u=>u.id);if(c.length>0){for(let u=0;u<3&&!e.tools;u++){let p;if(o()){let f=await a({title:"Tools to configure",items:c.map(m=>({value:m.id,label:`${m.title} (${m.id})`,hint:RR(m),selected:rg(m),requiresExplicitChoice:!rg(m)}))});if(f.kind==="cancelled")throw new yt;p=f.values}else{p=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(w=>w.trim()).filter(Boolean);let m=new Set(c.map(w=>w.id)),h=p.filter(w=>!m.has(w));if(h.length>0){_(`Unknown or unavailable tool id${h.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(p.length===0){_("Choose at least one installed tool.");continue}e.tools=p}if(!e.tools)throw new yt}l.length>0&&$(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},CJ=async(e,t)=>{U("Verifying the connection");let n=await Ei("Checking the gateway\u2026",()=>_i(e,{tools:t}));n.kind==="ok"?M(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?_(` ${n.detail}`):O(` ${n.detail}`);for(let r of n.remedy)A(v(` ${r}`))},kJ=async(e,t={})=>{if(e.dryRun)return;let n=t.install??tr,r=t.uninstall??nr;if(e.want&&e.trayManaged){U("Automatic key refresh"),M(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh.");return}if(e.want){let o=await n();U("Automatic key refresh");for(let a of o.messages)A(` ${a}`);o.ok&&M(" Your gateway key now renews every ~30 min \u2014 no tool will 401 on a stale key mid-session."),o.ok||await oe({...await D(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){U("Automatic key refresh");let o=await r();for(let a of o.messages)A(` ${a}`);await oe({...await D(),refreshSchedulerEnabled:!1}),M(" Removed the automatic key-refresh schedule.")}},vJ=new Set(["login","wizard","status","doctor","sync","device-url"]),SJ=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),IJ=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."}},EJ=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=Vh(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]||!SJ.has(e[0])},og=async(e,t)=>{try{return await _R(e,t)}catch(n){if(n instanceof yt)return console.error(v("Cancelled \u2014 nothing was written.")),130;if(n instanceof Error&&n.message==="connect profile is busy; retry the command")return O("Another Connect update is in progress. Try again."),1;throw n}},OR=12e4,xJ=async(e,t,n,r=Xa)=>e&&!t?r(n,{waitMs:OR}):n(),RJ=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??Ft)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
1068
- ${o} ${n} tool target(s)?`;return await(r.confirm??Ea)(a)?"proceed":"declined"},OJ=async(e=La)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0});switch(t.outcome){case"current":case"updated":case"migrated":case"container":case"unmanaged":return"ok";case"available":case"migration-available":case"migration-deferred":case"disabled":case"platform-unsupported":case"unavailable":case"failed":return"failed";default:return t.outcome}},TJ=async()=>{let e=!1,t=await zt({runAmbientSelfcheck:!0});await cp(),await AI(),await CI()==="retry"&&(e=!0);let n=await D().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await oe(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Ao().catch(()=>!1);if(n&&(await gR(t,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Bt(),i=n.enrolledCert;if(s&&i){let l=await $e().catch(()=>{});l&&await iS(o,a,i,l,s).catch(()=>{})}await bR(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await zt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await CR(d):l==="update"?u=await OJ():u=(await hu()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await La(),{refresh:t,...e?{partial:!0}:{}}},_J=async e=>{if(e[0]==="__anyray-hook"){let r=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return Zx(r)}if(e[0]==="__anyray-codex-hook")return Yx();if(e[0]==="__anyray-prompt-hook")return t0();if(e[0]==="__anyray-shell-pretool")return a0();if(e[0]==="__anyray-shell-run")return o0(e.slice(1));if(e[0]==="__anyray-read-pretool")return f0();if(e[0]==="__anyray-sso-gate")return e0(e.slice(1));if(e[0]==="__anyray-sso-poll")return g0();if(e[0]==="__anyray-managed-enroll")try{return await Xa(()=>h0(y0((r,o)=>_R(r,!1,{managedEnrollmentRevertedTools:o}))),{waitMs:OR})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return v0();if(e[0]==="__anyray-spawn-refresh")return await kr(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return _0(r)}if(e[0]==="__anyray-acp-agent")return P0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return hR(e.slice(1));let t=F0(e);if(t)return W0(t,{refresh:TJ});if(e[0]==="__anyray-persistence")return ww(e.slice(1));if(e[0]==="__anyray-quit-watch")return Uv(e.slice(1));if(e[0]===hr)return YI(e.slice(1));if(e[0]===Vs)return XI(e.slice(1));if(e[0]===Fd){let r=e[1];return r&&await Ud(r),0}if(e[0]==="--version"||e[0]==="-V")return k0();try{let r=await Lg(e);if(r!==void 0)return r}catch(r){return O(`Could not persist anyray-connect for long-lived integrations: ${r instanceof Error?r.message:String(r)}`),1}if(EJ(e)){let r=IJ(await nx());r?.level==="warn"?_(r.message):r&&console.error(r.message)}if(e[0]==="managed")return xS(e.slice(1));if(e[0]==="endpoint")return mR(e.slice(1));if(e[0]==="print-key")return II(e.slice(1));if(e[0]==="models")return xI(e.slice(1));if(e[0]==="copilot-login")return RI(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=Vh(r);return o?og(o,!1):bE(r)}if(e[0]==="retrieve")return CE(e.slice(1));if(e[0]==="recall")return kE(e.slice(1));if(e[0]==="history")return LE(e.slice(1));if(e[0]==="migrate")return $E(e.slice(1));if(e[0]==="login")return b0(e.slice(1));if(e[0]==="update")return C0(e.slice(1));let n=e[0];if(n&&vJ.has(n)){let r=e.slice(1),o;try{o=ER(r)}catch(a){return O(a.message),A("\nRun `npx anyray-connect --help` for usage."),1}return o.help?(A(o.helpAll?IR:SR),0):n==="status"?cx({gateway:o.gateway}):n==="doctor"?au({gateway:o.gateway,json:o.json,verify:o.verify,noVerify:o.noVerify,quick:o.quick,repair:o.repair,securityReview:o.securityReview}):n==="sync"?hx({gateway:o.gateway}):n==="device-url"?DI():og(r,!0)}return og(e,!1)},TR=async e=>{try{return await _J(e)}catch(t){if(t instanceof yt)return console.error(v("Cancelled.")),130;throw t}},_R=async(e,t,n={})=>{let r=n.isInteractive??Ft,o;try{o=ER(e)}catch(T){return O(T.message),A("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return A(o.helpAll?IR:SR),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):jI({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 T;try{T=new URL(o.upstream.trim())}catch{return O(`invalid --upstream URL: "${o.upstream}"`),1}if(T.protocol!=="http:"&&T.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:Ht(o.upstream),key:L}}let s=await D();!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream);let i=!t&&Ft()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??AJ)(o,s),c=!0);let l;try{if(l=sJ(o.tools),n.managedEnrollmentRevertedTools){let T=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];l=m0(l,T)}}catch(T){return O(T.message),1}A(V(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&ci(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,A("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,p,f,m=!1;if(o.enroll){let T=pd(o.enroll);if(T&&(!o.gateway||s.enrolledCert||Ym(T.token)))try{let L=await Ei("Resolving enrollment link\u2026",()=>eS(T)),J=!o.gateway;J&&(o.gateway=L.gatewayUrl),d=L.deploymentId,u=L.email,p=L.provisioningKind,f=L.allowedDomains,m=!0,J&&$(`Enrollment link${L.org?` for ${L.org}`:""}: gateway ${L.gatewayUrl}`),L.seatMode&&!o.subscription&&(o.subscription=!0,$("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(L){if(Ym(T.token))return O(L instanceof Error?L.message:String(L)),1;let J=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(J)$(`Could not resolve the gateway from the enrollment link \u2014 using ${J}.`);else return O(L instanceof Error?L.message:String(L)),1}}let h,w;if(o.claim&&!o.revert)if(o.dryRun)$("dry run: not enrolled (skipped redeeming the enrollment link).");else{let T=pS(o.claim);if(!T)return O("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let L=await Ei("Connecting this machine\u2026",()=>fS({cpOrigin:T.cpOrigin,claim:T.claim,gatewayUrl:o.gateway}));h={cert:L.cert,privateKeyPem:L.privateKeyPem},L.deploymentId&&(d=L.deploymentId),!o.gateway&&L.gatewayUrl&&(o.gateway=L.gatewayUrl),w=L.ssoLink}catch(L){return O(L instanceof Error?L.message:String(L)),1}}if(o.sso&&!h&&!o.revert)if(o.dryRun)$("dry run: not enrolled via SSO (skipped minting a personal key).");else{let T=St(o.sso);if(!T)return O(ci(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 md({cpOrigin:T.cpOrigin,tenantId:T.tenantId,gatewayUrl:o.gateway,log:pe=>$(pe),open:r()?_a:void 0}),J=await Ei("Waiting for SSO sign-in\u2026",()=>hd(L,{gatewayUrl:o.gateway}));h={cert:J.cert,privateKeyPem:J.privateKeyPem},J.deploymentId&&(d=J.deploymentId),!o.gateway&&J.gatewayUrl&&(o.gateway=J.gatewayUrl)}catch(L){return O(L instanceof Error?L.message:String(L)),1}}let y=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;y&&(o.gateway=y);let g;try{g=Qt(o.gateway)}catch(T){return O(T.message),1}let b,k;y&&!o.revert&&$(`Gateway: ${g} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&sg(g)&&_(`${g} 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 C=process.env.ANYRAY_CLIENT_KEY?.trim(),S=C||cJ(s),I,E,R,P,W,q,de=async T=>{await yo();let L=rS(T.token),J=cS(s.enrolledCert,s.enrolledCertExpiry,T.deploymentId,Date.now(),L,s.enrolledTokenHash,T.expectedUser),pe=J?await $e():void 0,ut=Bt()||void 0,j=J&&pe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:pe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,_e=pt=>lS({cpOrigin:T.cpOrigin,token:T.token,gatewayOrigin:g,email:T.email,team:T.team,machineId:T.machineId,deploymentId:T.deploymentId,machineUuid:ut,reuse:pt?j:void 0}),ke=!!j,Xe=await(async()=>{try{return await _e(ke)}catch(pt){if(j&&pt instanceof lt&&pt.policyCode!=="managed_device_required")return $("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),ke=!1,await _e(!1);throw pt}})();S=Xe.clientKey,o.user=Cu(o.user,Xe.user),o.team=Cu(o.team,Xe.team),I=Xe.cert,E=Xe.cert.payload.expiresAt,q=Xe.expiresAt,W=void 0,ke||(R=Xe.privateKeyPem),ke||(P=L),M(`Enrolled${Xe.user?` as ${Xe.user}`:""}${ke?" (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)$("dry run: not enrolled (skipped minting a personal key).");else{let T=pd(o.enroll);if(!T){let L=Qv(o.enroll);return O(L?`that is ${L.what}, not an enrollment link \u2014 re-run with ${L.flag} instead of --enroll.`:St(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?Sd():void 0,J=p==="mdm"&&!u?GE():void 0,pe=p==="mdm"&&!u&&!J?UE(f,Dd()):void 0,ut=J??pe;if(ut){let ke=J?"the email your MDM assigned to this machine":`${ut} (this Mac's login name at the first allowed domain)`;A(o.user?.trim()&&o.user.trim()!==ut?`Ignoring --user: enrolling as ${ke}.`:`Enrolling as ${ke}.`)}let j=u??ut??aJ(o.user);if(!o.machine&&!o.user&&!u&&!ut){let ke=MI();ke.distinct||(_(` Enrolling as "${ke.identity}" \u2014 this may not be unique to you.`),_(ke.reason==="machine_default"?" That looks like a machine or container default, so every developer on":" No personal git email is set, so machines sharing this image can"),_(ke.reason==="machine_default"?" this image would enroll as the same person and their spend would merge.":" enroll under the same name and their spend would merge."),_(" Re-run with `--user you@company.com` (or set `git config --global"),_(" user.email`) so your usage is attributed to you."))}let _e=o.machine?`machine:${L}`:m?j:void 0;await de({cpOrigin:T.cpOrigin,token:T.token,email:j,team:o.team,machineId:L,deploymentId:d,expectedUser:_e})}catch(L){return O(L instanceof Error?L.message:String(L)),L instanceof lt&&L.policyCode!=="managed_device_required"&&$("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."),aS(L)?3:1}}if(h){await yo();try{let T=Bt()||void 0,L=await Xt(g,h.cert,h.privateKeyPem,{machineUuid:T});S=L.key,o.user=Cu(o.user,L.user),o.team=Cu(o.team,L.team),I=h.cert,E=h.cert.payload.expiresAt,R=h.privateKeyPem,q=L.expiresAt;let J=o.sso?St(o.sso):void 0;W=J?`${J.cpOrigin}/sso/${J.tenantId}`:w,M(`Enrolled${L.user?` as ${L.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(T){return O(T instanceof Error?T.message:String(T)),T instanceof lt&&T.policyCode!=="managed_device_required"&&$("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 T=o.yes;b=await FI(o.user,s.name,T),k=await WI(o.team,s.team,T)}if(!o.revert&&!o.dryRun){let T=ax(await ox(g,S),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(T.lane){let L=T.lane==="subscription";o.subscription=L,o.placeholder=!L;let J=L?"your own subscription seat":"the organization's provider account";T.overrodeFlag?$(`Your administrator assigns this machine to ${J}, so that is what was applied (it overrides the lane flag you passed).`):$(`Billing lane set by your administrator: ${J}.`)}}let ie;!o.revert&&!o.subscription&&!o.placeholder&&(ie=await fn(),U("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):ie.anthropic?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${ie.openai?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),!ie.anthropic&&!ie.openai&&!ie.copilot&&Fr()&&(_(" No subscription sign-ins found on this host. Sign-ins do not cross the"),_(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),_(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),_(" and re-run, or everything below routes on the org key instead.")));let K=xe({origin:g,placeholderKey:o.key,clientKey:S,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:ie,user:b,team:k,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),ge=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:ge};if(!o.revert&&K.clientKey&&!Ee(K.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&&!K.clientKey){U("Enrollment required");let T="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(_(` ${T}`),$(" Dry run only \u2014 no placeholder configuration will be written."),await kR(l,"after-enrollment"),$(`
1069
- Dry run complete \u2014 no files were written.`),0):(O(` ${T}`),1)}o.revert||iJ(K,l),c&&!o.revert&&await kR(l,"plan"),o.dryRun&&$(`
1070
- Dry run \u2014 no files will be written.`);let F=await RJ(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(F==="non-interactive")return O(`
1071
- Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(F==="declined")return $(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 T=await Jd(K.origin);if(!T.reachable)return O(`
1066
+ per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,CJ=e=>{let t=e?.trim();return t||Th()},Au=(e,t)=>t||e,TR=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"--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},kJ=e=>!e||e.length===0?le:e.map(t=>{let n=mt(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${le.map(r=>r.id).join(", ")}`);return n}),vJ=(e,t)=>{if(H("Gateway target"),A(` Origin: ${et(e.origin)}`),e.byoUpstream)A(` Auth: BYO upstream key ${v(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&A(` Client key: personal gateway key (${_t(e.clientKey)}) ${v("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=ee(e,"anthropic")?et("your subscription"):"org key",r=ee(e,"openai")?et("your subscription"):"org key";A(` Auth: auto ${v("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&A(` Client key: personal gateway key (${_t(e.clientKey)})`)}else e.authMode==="subscription"?(A(` Auth: subscription pass-through ${v("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&A(` Client key: personal gateway key (${_t(e.clientKey)}) ${v("rides x-anyray-api-key")}`)):e.clientKey?A(` Auth: personal gateway key (${_t(e.clientKey)}) ${v("(replaces the placeholder)")}`):A(` Enrollment: ${v("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&A(` Cursor: ${et("native Team subscription")} ${v("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(ee(e,"anthropic")?(A(` Claude Desktop: ${et("subscription-backed Gateway lane")} ${v("(verified macOS builds; Windows fails closed)")}`),A(` ${v("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(A(` Claude Desktop: ${et("third-party API lane")} ${v("(API-billed; switches the active local inference profile)")}`),A(` ${v("The first-party Claude subscription remains untouched.")}`))),A(` Attribution: ${ue(e.metadata)??v("(none \u2014 pass --user)")}`)},ER=async(e,t)=>{H("Selected tools");for(let n of e){let r=await n.detect();r.installed?A(` ${n.title} ${v(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):$(` ${n.title} ${v(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},SJ=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Ee(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},IJ={loadDevKey:$e,saveDevKey:Ji,clearDevKey:Ja,saveProfile:ae},EJ=async(e,t,n,r=IJ,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}},xJ=async(e,t,n,r,o)=>{let a=0,s=[],i=[],c=[],l=[],d=[];for(let u of e){if(!(await u.detect()).installed&&!r){d.push(u.title);continue}H(`${u.title} ${v(`(${u.id})`)}`);try{let f=r?await u.revert(n):await u.apply(t,{...n,explicit:o?.has(u.id)===!0,reportsToUser:!0});for(let m of f.messages)A(` ${m}`);a+=f.changedFiles?.length??0,l.push({id:u.id,status:f.status}),f.status==="configured"||f.status==="reverted"?B(` ${f.status}`):f.status==="manual"?(s.push(u.title),f.manualAudience==="admin"?(i.push(u.title),c.push(u.id),_(" blocked by machine policy \u2014 your IT team owns this one")):_(" manual step required (see above)")):f.status==="held"?$(" left on its own plan (no change)"):$(` ${f.status}`)}catch(f){l.push({id:u.id,status:"failed"}),O(` failed: ${f instanceof Error?f.message:String(f)}`)}}if(d.length>0&&$(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await ec().catch(()=>[]);u.length&&$(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},RJ=(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},OJ=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>_R(o)&&!r.has(o.id))},TJ=async e=>{let t=AE(e,process.platform,Q());if(t){await we(t.path,t.content);for(let n of CE(t,process.platform))A(` ${n}`)}},_J=async(e,t,n=xR())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!db(i,n)||!lb(i,n))continue;let c=ib(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:cb(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},PJ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,DJ=e=>`
1067
+ ${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?`}`,LJ=async(e,t={})=>{let n=t.requestQuit??(a=>pb(a)),r=t.waitFor??(a=>fb(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),B(` Closed ${a.title}.`);continue}_(` ${a.title} is still open \u2014 leaving it alone.`),$(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},NJ=(e,t={})=>{let n=t.relaunch??(o=>mb(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),B(` Reopened ${o.title}.`)):_(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},_R=e=>e.changesBilling===!0||e.changesOrgManagement===!0,PR=e=>e.changesBilling===!0?"moves inference spend from your subscription to the org API bill":e.changesOrgManagement===!0?"switches the app to third-party mode; claude.ai Enterprise org settings stop applying":void 0,sg=e=>!_R(e),$J=async(e,t,n={})=>{let r=n.hasEnrollment??Lu,o=n.canMultiSelect??JE,a=n.multiSelect??XE,s=n.prompt??xa,i=n.registry??le;if(A(V("Anyray connect \u2014 guided setup")),A(v("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())A("Stored enrollment will be reused. Run with --revert to clear it.");else if(!e.enroll&&!e.sso&&!e.gateway){H("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{A(" 1. Paste an enrollment link"),A(" 2. Sign in with SSO"),A(" 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||_("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&&ci(d)&&fd(d)){e.enroll=d;break}_("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&&St(d)){e.sso=d;break}_("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&&ci(d)){e.enroll=d,A("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=Qt(d);break}catch{_("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){H("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=>sg(u)).map(u=>u.id);if(c.length>0){for(let u=0;u<3&&!e.tools;u++){let p;if(o()){let f=await a({title:"Tools to configure",items:c.map(m=>({value:m.id,label:`${m.title} (${m.id})`,hint:PR(m),selected:sg(m),requiresExplicitChoice:!sg(m)}))});if(f.kind==="cancelled")throw new yt;p=f.values}else{p=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(w=>w.trim()).filter(Boolean);let m=new Set(c.map(w=>w.id)),h=p.filter(w=>!m.has(w));if(h.length>0){_(`Unknown or unavailable tool id${h.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(p.length===0){_("Choose at least one installed tool.");continue}e.tools=p}if(!e.tools)throw new yt}l.length>0&&$(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},MJ=async(e,t)=>{H("Verifying the connection");let n=await Ei("Checking the gateway\u2026",()=>_i(e,{tools:t}));n.kind==="ok"?B(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?_(` ${n.detail}`):O(` ${n.detail}`);for(let r of n.remedy)A(v(` ${r}`))},BJ=async(e,t={})=>{if(e.dryRun)return;let n=t.install??nr,r=t.uninstall??rr;if(e.want&&e.trayManaged){H("Automatic key refresh"),B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh.");return}if(e.want){let o=await n();H("Automatic key refresh");for(let a of o.messages)A(` ${a}`);o.ok&&B(" Your gateway key now renews every ~30 min \u2014 no tool will 401 on a stale key mid-session."),o.ok||await ae({...await P(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){H("Automatic key refresh");let o=await r();for(let a of o.messages)A(` ${a}`);await ae({...await P(),refreshSchedulerEnabled:!1}),B(" Removed the automatic key-refresh schedule.")}},FJ=new Set(["login","wizard","status","doctor","sync","device-url"]),WJ=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),UJ=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."}},HJ=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=Hh(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]||!WJ.has(e[0])},ig=async(e,t)=>{try{return await NR(e,t)}catch(n){if(n instanceof yt)return console.error(v("Cancelled \u2014 nothing was written.")),130;if(n instanceof Error&&n.message==="connect profile is busy; retry the command")return O("Another Connect update is in progress. Try again."),1;throw n}},DR=12e4,GJ=async(e,t,n,r=Xa)=>e&&!t?r(n,{waitMs:DR}):n(),VJ=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??Wt)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
1068
+ ${o} ${n} tool target(s)?`;return await(r.confirm??Ea)(a)?"proceed":"declined"},KJ=async(e=La)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0});switch(t.outcome){case"current":case"updated":case"migrated":case"container":case"unmanaged":return"ok";case"available":case"migration-available":case"migration-deferred":case"disabled":case"platform-unsupported":case"unavailable":case"failed":return"failed";default:return t.outcome}},jJ=async()=>{let e=!1,t=await zt({runAmbientSelfcheck:!0});await ip(),await vI(),await SI()==="retry"&&(e=!0);let n=await P().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await ae(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Ao().catch(()=>!1);if(n&&(await CR(t,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Ft(),i=n.enrolledCert;if(s&&i){let l=await $e().catch(()=>{});l&&await dS(o,a,i,l,s).catch(()=>{})}await vR(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await zt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await IR(d):l==="update"?u=await KJ():u=(await bu()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await La(),{refresh:t,...e?{partial:!0}:{}}},ZJ=async e=>{if(e[0]==="__anyray-hook"){let r=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return zx(r)}if(e[0]==="__anyray-codex-hook")return qx();if(e[0]==="__anyray-prompt-hook")return a0();if(e[0]==="__anyray-shell-pretool")return l0();if(e[0]==="__anyray-shell-run")return c0(e.slice(1));if(e[0]==="__anyray-read-pretool")return g0();if(e[0]==="__anyray-sso-gate")return o0(e.slice(1));if(e[0]==="__anyray-sso-poll")return z0();if(e[0]==="__anyray-managed-enroll")try{return await Xa(()=>J0(X0((r,o)=>NR(r,!1,{managedEnrollmentRevertedTools:o}))),{waitMs:DR})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return rR();if(e[0]==="__anyray-spawn-refresh")return await vr(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return uR(r)}if(e[0]==="__anyray-acp-agent")return pR(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return j0(e.slice(1));let t=bR(e);if(t)return AR(t,{refresh:jJ});if(e[0]==="__anyray-persistence")return Cw(e.slice(1));if(e[0]==="__anyray-quit-watch")return Kv(e.slice(1));if(e[0]===yr)return zI(e.slice(1));if(e[0]===Vs)return QI(e.slice(1));if(e[0]===Wd){let r=e[1];return r&&await Gd(r),0}if(e[0]==="--version"||e[0]==="-V")return nR();try{let r=await Mg(e);if(r!==void 0)return r}catch(r){return O(`Could not persist anyray-connect for long-lived integrations: ${r instanceof Error?r.message:String(r)}`),1}if(HJ(e)){let r=UJ(await sx());r?.level==="warn"?_(r.message):r&&console.error(r.message)}if(e[0]==="managed")return TS(e.slice(1));if(e[0]==="endpoint")return K0(e.slice(1));if(e[0]==="print-key")return RI(e.slice(1));if(e[0]==="models")return TI(e.slice(1));if(e[0]==="copilot-login")return _I(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=Hh(r);return o?ig(o,!1):kE(r)}if(e[0]==="retrieve")return SE(e.slice(1));if(e[0]==="recall")return IE(e.slice(1));if(e[0]==="history")return ME(e.slice(1));if(e[0]==="migrate")return FE(e.slice(1));if(e[0]==="login")return Q0(e.slice(1));if(e[0]==="update")return tR(e.slice(1));let n=e[0];if(n&&FJ.has(n)){let r=e.slice(1),o;try{o=TR(r)}catch(a){return O(a.message),A("\nRun `npx anyray-connect --help` for usage."),1}return o.help?(A(o.helpAll?OR:RR),0):n==="status"?px({gateway:o.gateway}):n==="doctor"?ou({gateway:o.gateway,json:o.json,verify:o.verify,noVerify:o.noVerify,quick:o.quick,repair:o.repair,securityReview:o.securityReview}):n==="sync"?bx({gateway:o.gateway}):n==="device-url"?$I():ig(r,!0)}return ig(e,!1)},LR=async e=>{try{return await ZJ(e)}catch(t){if(t instanceof yt)return console.error(v("Cancelled.")),130;throw t}},NR=async(e,t,n={})=>{let r=n.isInteractive??Wt,o;try{o=TR(e)}catch(T){return O(T.message),A("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return A(o.helpAll?OR:RR),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):JI({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 T;try{T=new URL(o.upstream.trim())}catch{return O(`invalid --upstream URL: "${o.upstream}"`),1}if(T.protocol!=="http:"&&T.protocol!=="https:")return O(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let D=o.upstreamKey.trim();if(!D)return O("--upstream-key must not be empty."),1;a={url:Ht(o.upstream),key:D}}let s=await P();!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream);let i=!t&&Wt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??$J)(o,s),c=!0);let l;try{if(l=kJ(o.tools),n.managedEnrollmentRevertedTools){let T=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];l=Y0(l,T)}}catch(T){return O(T.message),1}A(V(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&ci(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,A("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,p,f,m=!1;if(o.enroll){let T=fd(o.enroll);if(T&&(!o.gateway||s.enrolledCert||jm(T.token)))try{let D=await Ei("Resolving enrollment link\u2026",()=>rS(T)),J=!o.gateway;J&&(o.gateway=D.gatewayUrl),d=D.deploymentId,u=D.email,p=D.provisioningKind,f=D.allowedDomains,m=!0,J&&$(`Enrollment link${D.org?` for ${D.org}`:""}: gateway ${D.gatewayUrl}`),D.seatMode&&!o.subscription&&(o.subscription=!0,$("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(D){if(jm(T.token))return O(D instanceof Error?D.message:String(D)),1;let J=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(J)$(`Could not resolve the gateway from the enrollment link \u2014 using ${J}.`);else return O(D instanceof Error?D.message:String(D)),1}}let h,w;if(o.claim&&!o.revert)if(o.dryRun)$("dry run: not enrolled (skipped redeeming the enrollment link).");else{let T=hS(o.claim);if(!T)return O("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let D=await Ei("Connecting this machine\u2026",()=>yS({cpOrigin:T.cpOrigin,claim:T.claim,gatewayUrl:o.gateway}));h={cert:D.cert,privateKeyPem:D.privateKeyPem},D.deploymentId&&(d=D.deploymentId),!o.gateway&&D.gatewayUrl&&(o.gateway=D.gatewayUrl),w=D.ssoLink}catch(D){return O(D instanceof Error?D.message:String(D)),1}}if(o.sso&&!h&&!o.revert)if(o.dryRun)$("dry run: not enrolled via SSO (skipped minting a personal key).");else{let T=St(o.sso);if(!T)return O(ci(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 D=await hd({cpOrigin:T.cpOrigin,tenantId:T.tenantId,gatewayUrl:o.gateway,log:pe=>$(pe),open:r()?_a:void 0}),J=await Ei("Waiting for SSO sign-in\u2026",()=>yd(D,{gatewayUrl:o.gateway}));h={cert:J.cert,privateKeyPem:J.privateKeyPem},J.deploymentId&&(d=J.deploymentId),!o.gateway&&J.gatewayUrl&&(o.gateway=J.gatewayUrl)}catch(D){return O(D instanceof Error?D.message:String(D)),1}}let y=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;y&&(o.gateway=y);let g;try{g=Qt(o.gateway)}catch(T){return O(T.message),1}let b,k;y&&!o.revert&&$(`Gateway: ${g} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&lg(g)&&_(`${g} 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 C=process.env.ANYRAY_CLIENT_KEY?.trim(),S=C||SJ(s),I,E,R,N,U,q,de=async T=>{await yo();let D=sS(T.token),J=uS(s.enrolledCert,s.enrolledCertExpiry,T.deploymentId,Date.now(),D,s.enrolledTokenHash,T.expectedUser),pe=J?await $e():void 0,ut=Ft()||void 0,j=J&&pe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:pe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,_e=pt=>pS({cpOrigin:T.cpOrigin,token:T.token,gatewayOrigin:g,email:T.email,team:T.team,machineId:T.machineId,deploymentId:T.deploymentId,machineUuid:ut,reuse:pt?j:void 0}),ke=!!j,Xe=await(async()=>{try{return await _e(ke)}catch(pt){if(j&&pt instanceof lt&&pt.policyCode!=="managed_device_required")return $("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),ke=!1,await _e(!1);throw pt}})();S=Xe.clientKey,o.user=Au(o.user,Xe.user),o.team=Au(o.team,Xe.team),I=Xe.cert,E=Xe.cert.payload.expiresAt,q=Xe.expiresAt,U=void 0,ke||(R=Xe.privateKeyPem),ke||(N=D),B(`Enrolled${Xe.user?` as ${Xe.user}`:""}${ke?" (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)$("dry run: not enrolled (skipped minting a personal key).");else{let T=fd(o.enroll);if(!T){let D=nS(o.enroll);return O(D?`that is ${D.what}, not an enrollment link \u2014 re-run with ${D.flag} instead of --enroll.`:St(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 D=o.machine?Id():void 0,J=p==="mdm"&&!u?ZE():void 0,pe=p==="mdm"&&!u&&!J?jE(f,Ld()):void 0,ut=J??pe;if(ut){let ke=J?"the email your MDM assigned to this machine":`${ut} (this Mac's login name at the first allowed domain)`;A(o.user?.trim()&&o.user.trim()!==ut?`Ignoring --user: enrolling as ${ke}.`:`Enrolling as ${ke}.`)}let j=u??ut??CJ(o.user);if(!o.machine&&!o.user&&!u&&!ut){let ke=WI();ke.distinct||(_(` Enrolling as "${ke.identity}" \u2014 this may not be unique to you.`),_(ke.reason==="machine_default"?" That looks like a machine or container default, so every developer on":" No personal git email is set, so machines sharing this image can"),_(ke.reason==="machine_default"?" this image would enroll as the same person and their spend would merge.":" enroll under the same name and their spend would merge."),_(" Re-run with `--user you@company.com` (or set `git config --global"),_(" user.email`) so your usage is attributed to you."))}let _e=o.machine?`machine:${D}`:m?j:void 0;await de({cpOrigin:T.cpOrigin,token:T.token,email:j,team:o.team,machineId:D,deploymentId:d,expectedUser:_e})}catch(D){return O(D instanceof Error?D.message:String(D)),D instanceof lt&&D.policyCode!=="managed_device_required"&&$("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."),cS(D)?3:1}}if(h){await yo();try{let T=Ft()||void 0,D=await Xt(g,h.cert,h.privateKeyPem,{machineUuid:T});S=D.key,o.user=Au(o.user,D.user),o.team=Au(o.team,D.team),I=h.cert,E=h.cert.payload.expiresAt,R=h.privateKeyPem,q=D.expiresAt;let J=o.sso?St(o.sso):void 0;U=J?`${J.cpOrigin}/sso/${J.tenantId}`:w,B(`Enrolled${D.user?` as ${D.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(T){return O(T instanceof Error?T.message:String(T)),T instanceof lt&&T.policyCode!=="managed_device_required"&&$("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 T=o.yes;b=await HI(o.user,s.name,T),k=await GI(o.team,s.team,T)}if(!o.revert&&!o.dryRun){let T=lx(await cx(g,S),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(T.lane){let D=T.lane==="subscription";o.subscription=D,o.placeholder=!D;let J=D?"your own subscription seat":"the organization's provider account";T.overrodeFlag?$(`Your administrator assigns this machine to ${J}, so that is what was applied (it overrides the lane flag you passed).`):$(`Billing lane set by your administrator: ${J}.`)}}let ce;!o.revert&&!o.subscription&&!o.placeholder&&(ce=await fn(),H("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):ce.anthropic?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${ce.openai?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),!ce.anthropic&&!ce.openai&&!ce.copilot&&Fr()&&(_(" No subscription sign-ins found on this host. Sign-ins do not cross the"),_(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),_(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),_(" and re-run, or everything below routes on the org key instead.")));let K=xe({origin:g,placeholderKey:o.key,clientKey:S,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:ce,user:b,team:k,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),ge=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:ge};if(!o.revert&&K.clientKey&&!Ee(K.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&&!K.clientKey){H("Enrollment required");let T="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(_(` ${T}`),$(" Dry run only \u2014 no placeholder configuration will be written."),await ER(l,"after-enrollment"),$(`
1069
+ Dry run complete \u2014 no files were written.`),0):(O(` ${T}`),1)}o.revert||vJ(K,l),c&&!o.revert&&await ER(l,"plan"),o.dryRun&&$(`
1070
+ Dry run \u2014 no files will be written.`);let F=await VJ(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(F==="non-interactive")return O(`
1071
+ Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(F==="declined")return $(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 T=await Xd(K.origin);if(!T.reachable)return O(`
1072
1072
  Gateway ${K.origin} is not reachable (${T.detail}).`),A(v(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
1073
1073
  that would break them until you re-run with --revert.`)),A(`
1074
- Start the gateway and try again, or pass --force to configure anyway.`),1;M(`Gateway reachable (${T.detail}).`)}let Z=o.revert?[]:await hJ(l,K.origin),X=[],Je=()=>{X.length!==0&&(U("Reopening"),bJ(X),X=[])};if(Z.length>0){let T=Z.map(J=>J.title),L=T.length===1?"it":"them";if(U("Open apps"),yJ(o,Ft()))o.quitApps===!0||await Ea(gJ(T))?X=await wJ(Z):$(` Leaving ${L} open \u2014 restart when convenient.`);else{let J=o.noQuitApps===!0?"":" (or pass --quit-apps)";$(o.dryRun?` Would offer to quit ${T.join(", ")} \u2014 dry run, nothing was closed.`:` ${T.join(", ")} ${T.length===1?"is":"are"} open; restart ${L} to pick this up${J}.`)}}let We=async()=>{if(!o.dryRun)try{await tt()}catch{return O("Could not prepare the owner-only Anyray state directory."),1}let T=yI(s,q),L=s.anyrayFleetManaged===!0&&await Ao().catch(()=>!1),J=iR(o,vR(),L),pe=!!(C&&K.clientKey===C&&!I),ut=!pe&&!!(I??s.enrolledCert),j=l.some(Ne=>hI.has(Ne.id)),_e=!o.revert&&o.noKeyRefresh!==!0&&ut&&(T||!j),ke=o.dryRun?await Po(s):await cp(),Xe=ke==="healthy";if(ke==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath),!o.revert&&!o.dryRun){let Ne={...s,managedEnrollmentDisabled:void 0,gateway:K.origin,name:b,team:k,clientKey:K.clientKey??s.clientKey,enrolledCert:pe?void 0:I??s.enrolledCert,enrolledCertExpiry:pe?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:pe?void 0:P??s.enrolledTokenHash,ssoLink:pe?void 0:h?W:I?void 0:s.ssoLink,clientKeyExpiresAt:pe?void 0:q??(K.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:K.authMode,byoUpstream:K.byoUpstream,refreshSchedulerEnabled:_e};try{await dJ(s,Ne,R,void 0,pe)}catch{return O("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}q&&!pe&&await Ia({expiresAt:q})}if(ge)if(o.dryRun)await Nu()&&(U("Enrollment"),A(" would remove the stored gateway credential"));else{await Hy(s),await Pd().catch(()=>{});try{await Xi()&&(U("Enrollment"),M(" Removed the stored gateway credential."),$(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(Ne){U("Enrollment"),_(" Could not remove the stored gateway credential."),_(` Delete ${Q()} by hand, or a credential refresh may restore your tool config.`)}}else o.revert&&!o.dryRun&&(A(`
1075
- Keeping the stored enrollment \u2014 the tools you did not name still need it.`),A("Run --revert with no --tools to remove it."));let pt=l,Tr=fJ(pt,o,s.managedTools);if(Tr.length>0){U("Not configured \u2014 needs your say-so");for(let Ie of Tr)_(` ${Ie.id}: ${RR(Ie)??"changes where inference is billed"}.`),A(` Configure it deliberately with \`npx anyray-connect --tools ${Ie.id}\`.`);let Ne=new Set(Tr.map(Ie=>Ie.id));pt=pt.filter(Ie=>!Ne.has(Ie.id))}if(o.revert&&!ge){let Ne=l.filter(Ie=>di(s,Ie.id));if(Ne.length>0){U("Fleet policy");for(let Ie of Ne)_(` ${Ie.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);pt=l.filter(Ie=>!di(s,Ie.id))}}let{changes:Gi,manual:Ha,manualAdminOnly:Vi,manualAdminOnlyIds:Ua,results:Ga}=await uJ(pt,K,me,o.revert,new Set(o.tools??[])),Va;if(zy(o)){U("Endpoint agent");try{Va=await(n.installEndpointAfterEnrollment??yR)({gateway:g,clientKey:K.clientKey})}catch{$("Endpoint agent setup did not complete. Tool routing remains configured.")}}let ko=J&&sR(Va),Ka=_e&&!ko;if(J&&!ko&&_e&&!o.dryRun&&$(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),ko&&!o.dryRun&&await oe({...await D(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await Vn(Ga,o.revert,ge).catch(()=>{}),ge&&await zi().catch(()=>{})),await kJ({want:Ka,scopedRevert:!!o.revert&&!ge,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!Ka&&await kc(),trayManaged:Xe}),!o.revert&&!o.dryRun&&!pe){let Ne=R??await $e();Ne&&await Eh(await D(),Ne).catch(()=>{})}if(Je(),U("Summary"),o.dryRun)$("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){M(`Reverted (${Gi} file(s) touched).`),$("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let Ne=await KI();Ne.length>0&&(U("This repo carries its own Anyray routing"),_(` Committed here: ${Ne.join(", ")}`),_(" Those are tracked files, so they route every checkout of this"),_(" repo \u2014 this machine included, and your teammates' too. This"),_(" revert only removed THIS machine's own configuration."),A(`
1076
- Remove them from the repo (then commit):`),A(v(" anyray-connect --project --revert")));let Ie=Nc(K);Ie.length>0&&(U("This terminal still points at the gateway"),_(` Still exported here: ${Ie.join(", ")}`),_(" Removing the block from your shell profile cannot reach a shell"),_(" that already ran it. Until these are gone, your tools keep"),_(" reaching the gateway and now fail with 401."),A(`
1074
+ Start the gateway and try again, or pass --force to configure anyway.`),1;B(`Gateway reachable (${T.detail}).`)}let Z=o.revert?[]:await _J(l,K.origin),X=[],Je=()=>{X.length!==0&&(H("Reopening"),NJ(X),X=[])};if(Z.length>0){let T=Z.map(J=>J.title),D=T.length===1?"it":"them";if(H("Open apps"),PJ(o,Wt()))o.quitApps===!0||await Ea(DJ(T))?X=await LJ(Z):$(` Leaving ${D} open \u2014 restart when convenient.`);else{let J=o.noQuitApps===!0?"":" (or pass --quit-apps)";$(o.dryRun?` Would offer to quit ${T.join(", ")} \u2014 dry run, nothing was closed.`:` ${T.join(", ")} ${T.length===1?"is":"are"} open; restart ${D} to pick this up${J}.`)}}let We=async()=>{if(!o.dryRun)try{await tt()}catch{return O("Could not prepare the owner-only Anyray state directory."),1}let T=bI(s,q),D=s.anyrayFleetManaged===!0&&await Ao().catch(()=>!1),J=B0(o,xR(),D),pe=!!(C&&K.clientKey===C&&!I),ut=!pe&&!!(I??s.enrolledCert),j=l.some(Ne=>wI.has(Ne.id)),_e=!o.revert&&o.noKeyRefresh!==!0&&ut&&(T||!j),ke=o.dryRun?await Po(s):await ip(),Xe=ke==="healthy";if(ke==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath),!o.revert&&!o.dryRun){let Ne={...s,managedEnrollmentDisabled:void 0,gateway:K.origin,name:b,team:k,clientKey:K.clientKey??s.clientKey,enrolledCert:pe?void 0:I??s.enrolledCert,enrolledCertExpiry:pe?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:pe?void 0:N??s.enrolledTokenHash,ssoLink:pe?void 0:h?U:I?void 0:s.ssoLink,clientKeyExpiresAt:pe?void 0:q??(K.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:K.authMode,byoUpstream:K.byoUpstream,refreshSchedulerEnabled:_e};try{await EJ(s,Ne,R,void 0,pe)}catch{return O("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}q&&!pe&&await Ia({expiresAt:q})}if(ge)if(o.dryRun)await Lu()&&(H("Enrollment"),A(" would remove the stored gateway credential"));else{await ng(s),await Dd().catch(()=>{});try{await Xi()&&(H("Enrollment"),B(" Removed the stored gateway credential."),$(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(Ne){H("Enrollment"),_(" Could not remove the stored gateway credential."),_(` Delete ${Q()} by hand, or a credential refresh may restore your tool config.`)}}else o.revert&&!o.dryRun&&(A(`
1075
+ Keeping the stored enrollment \u2014 the tools you did not name still need it.`),A("Run --revert with no --tools to remove it."));let pt=l,_r=OJ(pt,o,s.managedTools);if(_r.length>0){H("Not configured \u2014 needs your say-so");for(let Ie of _r)_(` ${Ie.id}: ${PR(Ie)??"changes where inference is billed"}.`),A(` Configure it deliberately with \`npx anyray-connect --tools ${Ie.id}\`.`);let Ne=new Set(_r.map(Ie=>Ie.id));pt=pt.filter(Ie=>!Ne.has(Ie.id))}if(o.revert&&!ge){let Ne=l.filter(Ie=>di(s,Ie.id));if(Ne.length>0){H("Fleet policy");for(let Ie of Ne)_(` ${Ie.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);pt=l.filter(Ie=>!di(s,Ie.id))}}let{changes:Gi,manual:Ua,manualAdminOnly:Vi,manualAdminOnlyIds:Ha,results:Ga}=await xJ(pt,K,me,o.revert,new Set(o.tools??[])),Va;if(Ky(o)){H("Endpoint agent");try{Va=await(n.installEndpointAfterEnrollment??Z0)({gateway:g,clientKey:K.clientKey})}catch{$("Endpoint agent setup did not complete. Tool routing remains configured.")}}let ko=J&&M0(Va),Ka=_e&&!ko;if(J&&!ko&&_e&&!o.dryRun&&$(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),ko&&!o.dryRun&&await ae({...await P(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await Kn(Ga,o.revert,ge).catch(()=>{}),ge&&await zi().catch(()=>{})),await BJ({want:Ka,scopedRevert:!!o.revert&&!ge,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!Ka&&await kc(),trayManaged:Xe}),!o.revert&&!o.dryRun&&!pe){let Ne=R??await $e();Ne&&await Sh(await P(),Ne).catch(()=>{})}if(Je(),H("Summary"),o.dryRun)$("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){B(`Reverted (${Gi} file(s) touched).`),$("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let Ne=await YI();Ne.length>0&&(H("This repo carries its own Anyray routing"),_(` Committed here: ${Ne.join(", ")}`),_(" Those are tracked files, so they route every checkout of this"),_(" repo \u2014 this machine included, and your teammates' too. This"),_(" revert only removed THIS machine's own configuration."),A(`
1076
+ Remove them from the repo (then commit):`),A(v(" anyray-connect --project --revert")));let Ie=Nc(K);Ie.length>0&&(H("This terminal still points at the gateway"),_(` Still exported here: ${Ie.join(", ")}`),_(" Removing the block from your shell profile cannot reach a shell"),_(" that already ran it. Until these are gone, your tools keep"),_(" reaching the gateway and now fail with 401."),A(`
1077
1077
  Fix this terminal:`),A(v(` unset ${Ie.join(" ")}`)),A(`
1078
- Every other open terminal needs the same \u2014 or just open a new one.`),A(" VS Code injects a copy it captured when IT launched, so its"),A(" terminals stay stale even if you open a new one: quit the app"),A(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(M(`Done (${Gi} file(s) written).`),Ha.length>0){let xt=Vi.length===Ha.length;U(xt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let ag of pJ(Ha,Vi,Ua.includes("claude-desktop")?process.platform:void 0))_(ag);if(Ua.includes("claude-desktop")&&!o.dryRun)try{await mJ(K)}catch{_(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}Ft()&&!o.yes&&!xt&&(await Ea("Have you applied the manual settings shown above?")?M("Acknowledged."):_("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?$(`
1079
- Skipped the connection smoke test (--skip-verify).`):await CJ(K,l.map(xt=>xt.id)),U("What's next");let Ne=new Set(Ga.filter(xt=>xt.status==="configured").map(xt=>xt.id)),Ie=l.filter(xt=>Ne.has(xt.id)).map(xt=>xt.title);if(A(Ie.length>0?` Connected: ${Ie.join(", ")}`:" Connected: no tools completed automatic configuration."),A(" Restart any editor that was already running \u2014 it loaded our config at startup."),A(" If something looks wrong: npx anyray-connect doctor"),!o.verbose)return 0;A(`
1078
+ Every other open terminal needs the same \u2014 or just open a new one.`),A(" VS Code injects a copy it captured when IT launched, so its"),A(" terminals stay stale even if you open a new one: quit the app"),A(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(B(`Done (${Gi} file(s) written).`),Ua.length>0){let xt=Vi.length===Ua.length;H(xt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let cg of RJ(Ua,Vi,Ha.includes("claude-desktop")?process.platform:void 0))_(cg);if(Ha.includes("claude-desktop")&&!o.dryRun)try{await TJ(K)}catch{_(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}Wt()&&!o.yes&&!xt&&(await Ea("Have you applied the manual settings shown above?")?B("Acknowledged."):_("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?$(`
1079
+ Skipped the connection smoke test (--skip-verify).`):await MJ(K,l.map(xt=>xt.id)),H("What's next");let Ne=new Set(Ga.filter(xt=>xt.status==="configured").map(xt=>xt.id)),Ie=l.filter(xt=>Ne.has(xt.id)).map(xt=>xt.title);if(A(Ie.length>0?` Connected: ${Ie.join(", ")}`:" Connected: no tools completed automatic configuration."),A(" Restart any editor that was already running \u2014 it loaded our config at startup."),A(" If something looks wrong: npx anyray-connect doctor"),!o.verbose)return 0;A(`
1080
1080
  Re-test by hand any time:`),K.authMode!=="placeholder"&&l.length===1&&l[0]?.id==="cursor"?(A(v(` curl -sS ${K.origin}/connect/savings \\
1081
1081
  -H "x-anyray-api-key: $(anyray-connect print-key)"`)),A(v(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):A(v(` curl -sS ${K.openaiBaseUrl}/chat/completions \\
1082
1082
  -H "Content-Type: application/json" \\
1083
- -H "Authorization: Bearer ${K.clientKey?`<your personal key (${Tt(K.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
1084
- -d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),A(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await xJ(o.revert,o.dryRun,We,n.withProfileLock)}catch(T){if(T instanceof Error&&T.message==="connect profile is busy; retry the command")return O("Another Connect update is in progress. Try again."),1;throw T}finally{Je()}};TR(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
1083
+ -H "Authorization: Bearer ${K.clientKey?`<your personal key (${_t(K.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
1084
+ -d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),A(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await GJ(o.revert,o.dryRun,We,n.withProfileLock)}catch(T){if(T instanceof Error&&T.message==="connect profile is busy; retry the command")return O("Another Connect update is in progress. Try again."),1;throw T}finally{Je()}};LR(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});