anyray-connect 0.11.206 → 0.11.207
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.
- package/dist/index.js +110 -110
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var MT="http://localhost:8787",
|
|
2
|
+
var MT="http://localhost:8787",Zs="anyray-placeholder",vb=/^ark_[A-Za-z0-9_-]{20,512}$/,BT="ark_svc_",FT=/^ark_svc_[A-Za-z0-9_-]{20,512}$/,Pe=e=>{let t=e?.trim();return!!(t&&vb.test(t))};var kn=e=>{let t=e?.trim();if(t){if(FT.test(t))return"service";if(!t.startsWith(BT))return vb.test(t)?"personal":void 0}},ct=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},zp=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,WT=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Sb=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!WT.has(n)}catch{return!1}},cn=e=>{let t=ct(e||process.env.ANYRAY_GATEWAY_URL||MT),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=cn(e.origin),n=e.placeholderKey?.trim()||Zs,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:zp(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:zp(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:zp(e.session,"ANYRAY_METADATA_SESSION")},a=e.subscription?"subscription":e.placeholder?"placeholder":e.seat?"auto":"placeholder";return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:n,clientKey:r,keyKind:kn(r),authMode:a,byoUpstream:e.byoUpstream,seat:a==="auto"?e.seat:void 0,metadata:o}};import{homedir as Dl,platform as Uf}from"node:os";import{join as No}from"node:path";import{mkdir as Bf,readFile as ID,rename as ED,writeFile as _l,rm as Lo}from"node:fs/promises";import{spawnSync as xD}from"node:child_process";import{homedir as Rl}from"node:os";import{join as Ol}from"node:path";import{access as ZT,chmod as JT,mkdir as Qp,open as of,readFile as Pb,rm as ln,stat as xb,utimes as XT}from"node:fs/promises";import{createHash as zT,randomUUID as Db}from"node:crypto";import{dirname as af,join as qT}from"node:path";import{isDeepStrictEqual as Sa}from"node:util";import{randomUUID as UT}from"node:crypto";import{lstat as HT,open as GT,readFile as qp,rename as ol,rm as KT,writeFile as VT}from"node:fs/promises";import{platform as Ib}from"node:os";var Eb=e=>e?.code==="ENOENT",jT=new Set(["EBUSY","EXDEV","ETXTBSY"]),Mr=async(e,t=Ib())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},YT=async(e,t,n={})=>{let r=await qp(e),o;try{o=await qp(t)}catch(s){if(!Eb(s))throw s;await VT(t,r);return}let a=async s=>{let i=await GT(t,"r+");try{await i.write(s,0,s.length,0),await i.truncate(s.length),await Mr(i)}finally{await i.close()}};try{if(await a(r),await n.corruptAfterWrite?.(t),!(await qp(t)).equals(r))throw Object.assign(new Error("in-place publication did not persist"),{code:"EIO"})}catch(s){throw await a(o).catch(()=>{}),s}},Ae=async(e,t,n=Ib(),r={})=>{let o=r.rename??ol;if(n!=="win32"){try{await o(e,t)}catch(i){if(!jT.has(i?.code??""))throw i;await YT(e,t,r)}return}let a=`${t}.anyray-old-${process.pid}-${UT()}`,s=!1;try{let i=await HT(t);if(!i.isFile()&&!i.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await ol(t,a),s=!0}catch(i){if(!Eb(i))throw i}try{await ol(e,t)}catch(i){if(s)try{await ol(a,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${a}`)}throw i}s&&await KT(a,{force:!0})};var Js=e=>`${e}.anyray-bak`,Lb=async e=>{let t;try{t=await of(af(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},Rb=async(e,t)=>{let n,r;try{n=await of(e,"wx",384),await n.writeFile(t,"utf-8"),await Mr(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await ln(e,{force:!0}).catch(()=>{}),r;await Lb(e)},QT=async e=>{let t;try{t=await of(e,"r"),await Mr(t)}finally{await t?.close().catch(()=>{})}await Lb(e)},R=async e=>{try{return await ZT(e),!0}catch{return!1}},F=async e=>{if(!await R(e))return{};let t=await Pb(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},q=async(e,t,n={})=>{await Qp(af(e),{recursive:!0,mode:448});let r=Js(e);if(n.backup!==!1&&!await R(r)){let a=await R(e),s=a?await Pb(e,"utf-8"):`{}
|
|
3
3
|
`;if(a||n.tombstoneAbsent!==!1)try{await Rb(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${Db()}`;try{await Rb(o,`${JSON.stringify(t,null,2)}
|
|
4
|
-
`),await Ae(o,e),await JT(e,384),await QT(e)}finally{await ln(o,{force:!0}).catch(()=>{})}},Nb=1,Ob=3e4,eP=5e3,tP=/^[a-f0-9]{64}$/,$b=e=>`${e}.pending`,nP=e=>`${e}.lock`,ef=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=>ef(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${ef(t[n])}`).join(",")}}`},tf=(e,t)=>({exists:e,sha256:zT("sha256").update(ef(t)).digest("hex")}),nf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_b=e=>nf(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&tP.test(e.sha256),rP=e=>nf(e)&&e.transactionVersion===Nb&&_b(e.before)&&_b(e.after)&&nf(e.journal),rf=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,
|
|
5
|
-
`,{mode:384})}catch(c){throw await
|
|
6
|
-
`,{mode:384}),await uf(r,384);try{await Ae(r,n)}catch(o){throw await
|
|
4
|
+
`),await Ae(o,e),await JT(e,384),await QT(e)}finally{await ln(o,{force:!0}).catch(()=>{})}},Nb=1,Ob=3e4,eP=5e3,tP=/^[a-f0-9]{64}$/,$b=e=>`${e}.pending`,nP=e=>`${e}.lock`,ef=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=>ef(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${ef(t[n])}`).join(",")}}`},tf=(e,t)=>({exists:e,sha256:zT("sha256").update(ef(t)).digest("hex")}),nf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_b=e=>nf(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&tP.test(e.sha256),rP=e=>nf(e)&&e.transactionVersion===Nb&&_b(e.before)&&_b(e.after)&&nf(e.journal),rf=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,Ia=async(e,t)=>{try{return await F(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},oP=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Mb=async e=>{let t=nP(e),n=qT(t,"owner.json");await Qp(af(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=Db();try{await Qp(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await Ia(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 xb(n)).mtimeMs;i=!oP(c.pid)||l>Ob}catch{try{i=Date.now()-(await xb(t)).mtimeMs>Ob}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await ln(t,{recursive:!0,force:!0});continue}try{await q(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await ln(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await Ia(n,"ownership journal")).nonce!==o)return;let i=new Date;await XT(n,i,i)}catch{}})()},eP);return a.unref(),async()=>{clearInterval(a);try{(await Ia(n,"ownership journal")).nonce===o&&await ln(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},Bb=async e=>{let t=await R(e),n={};if(t)try{n=await F(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:tf(t,n)}},Fb=async(e,t)=>{let n=$b(t);if(!await R(n))return;let r=await Ia(n,"prepared ownership transaction");if(!rP(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await Bb(e),a=await R(t),s=await R(Js(e)),i=rf(o.fingerprint,r.before),c=rf(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await q(t,r.journal,{backup:!1}),await ln(n,{force:!0});return}if(i){await ln(n,{force:!0}),a||await pe(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},al=async(e,t,n)=>{let r=await Mb(t);try{return await Fb(e,t),await n()}finally{await r()}},Tb=async(e,t,n,r)=>{if(!await R(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await Ia(e,"ownership journal");if(!(n&&Sa(a,t))){if(!Sa(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await q(e,t,{backup:!1}):await ln(e,{force:!0})}},sl=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await Mb(a);try{await Fb(n,a);let l=await Bb(n),d=tf(i,r),u=await R(a),p=u?await Ia(a,"ownership journal"):void 0,m=p&&typeof p.fileExisted=="boolean"?{...s,fileExisted:p.fileExisted}:s;if(!rf(l.fingerprint,d)){if(Sa(l.value,o)&&p&&Sa(p,m))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&Sa(l.value,o)&&p&&Sa(p,m))return;let f=await R(Js(n));if(p?.fileExisted===!0&&!f)throw new Error("ownership backup is missing; configuration was left unchanged");if(f&&!p)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let h=$b(a),w={transactionVersion:Nb,before:l.fingerprint,after:tf(!0,o),journal:m};await q(h,w,{backup:!1});try{await q(n,o,p?{backup:!1}:{tombstoneAbsent:!1}),await(t.writeJournal??q)(a,m,{backup:!1}),await ln(h,{force:!0})}catch(y){try{await Tb(n,l.value,l.exists,o)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed and config rollback was incomplete")}try{await Tb(a,p??{},u,m),await ln(h,{force:!0}),!f&&!p&&await pe(n)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed after config rollback")}throw y}}finally{await c()}},Ro=async e=>{try{return await F(Js(e))}catch{return{}}},pe=async e=>{await ln(Js(e),{force:!0}).catch(()=>{})};var vn="anyray-org-skills",aP="/connect/claude-desktop/plugins/marketplace.json",Wb=e=>`${e.replace(/\/+$/,"")}${aP}`,Ub=e=>{let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.replace(/^\[|\]$/g,"").toLowerCase();return!(n==="localhost"||n.endsWith(".localhost")||n==="::1"||/^127\./.test(n)||/^169\.254\./.test(n)||n==="metadata.google.internal")},sf=`@${vn}`,Ea=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hb=e=>`${e}${sf}`,Gb=(e,t)=>{let n=!1,r=Ea(e.extraKnownMarketplaces)?e.extraKnownMarketplaces:e.extraKnownMarketplaces===void 0?{}:null;if(r){let a={source:{source:"url",url:t.url}};JSON.stringify(r[vn])!==JSON.stringify(a)&&(r[vn]=a,n=!0),e.extraKnownMarketplaces=r}let o=Ea(e.enabledPlugins)?e.enabledPlugins:e.enabledPlugins===void 0?{}:null;if(o){let a=new Set(t.plugins.map(Hb));for(let s of Object.keys(o))s.endsWith(sf)&&!a.has(s)&&(delete o[s],n=!0);for(let s of a)o[s]!==!0&&(o[s]=!0,n=!0);e.enabledPlugins=o}return n},cf=e=>{let t=!1;if(Ea(e.extraKnownMarketplaces)&&vn in e.extraKnownMarketplaces&&(delete e.extraKnownMarketplaces[vn],Object.keys(e.extraKnownMarketplaces).length===0&&delete e.extraKnownMarketplaces,t=!0),Ea(e.enabledPlugins)){for(let n of Object.keys(e.enabledPlugins))n.endsWith(sf)&&(delete e.enabledPlugins[n],t=!0);Object.keys(e.enabledPlugins).length===0&&delete e.enabledPlugins}return t},sP=e=>Ea(e.extraKnownMarketplaces)&&vn in e.extraKnownMarketplaces,Kb=(e,t)=>{if(!sP(e))return!1;let n=e.enabledPlugins;return Ea(n)?t.plugins.every(r=>n[Hb(r)]===!0):!1};import{access as _P}from"node:fs/promises";import{spawnSync as hP}from"node:child_process";import{readFileSync as yP,realpathSync as Qs,statSync as qb}from"node:fs";import{access as gP,cp as Qb,mkdir as Xb,readdir as wP,readFile as wf,realpath as bP,rename as CP,rm as yf,writeFile as AP}from"node:fs/promises";import{tmpdir as kP}from"node:os";import{basename as Ra,dirname as Xe,join as Be,resolve as vP}from"node:path";import{writeFile as cl,readFile as zs,chmod as uf,stat as pf,mkdir as jb,rm as xa}from"node:fs/promises";import{AsyncLocalStorage as iP}from"node:async_hooks";import{randomUUID as cP}from"node:crypto";import{homedir as Yb}from"node:os";import{join as Oo}from"node:path";var oe=()=>Oo(Yb(),".anyray"),Zb=async()=>{let e=oe();try{if((await pf(e)).isDirectory())return Oo(e,"connect.json")}catch{}return e},ff=()=>Oo(oe(),"dev-key.pem"),lt=async()=>{let e=oe(),t;try{if(!(await pf(e)).isDirectory())t=await zs(e,"utf-8").catch(()=>{}),await xa(e,{force:!0});else return}catch{}if(await jb(e,{recursive:!0,mode:448}),t!==void 0){let n=Oo(e,"connect.json");await cl(n,t,{mode:384}),await uf(n,384)}},ll=async e=>{await lt();let t=ff();await cl(t,e,{mode:384}),await uf(t,384)},Ye=async()=>{try{let e=await zs(ff(),"utf-8");return e.trim()?e:void 0}catch{return}},qs=async()=>{await xa(ff(),{force:!0}).catch(()=>{})},$=async()=>{try{let e=await zs(await Zb(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}},lP=0,dP=3e4,Jb=5e3,uP=25,pP=()=>Oo(Yb(),".anyray-connect-profile.lock"),il=new iP,fP=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},mP=async(e,t)=>{try{let n=JSON.parse(await zs(Oo(e,"owner.json"),"utf-8"));if(typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0)return!fP(n.pid)}catch{}return Date.now()-(await pf(e)).mtimeMs>t},Xs=class extends Error{constructor(t){super(t),this.name="LockBusyError"}},dl=async(e,t={})=>{let n=t.waitMs??Jb,r=t.staleMs??dP,o=Oo(e,"owner.json"),a=Date.now()+n;for(;;){let s=cP();try{await jb(e,{mode:448});try{await cl(o,`${JSON.stringify({pid:process.pid,nonce:s})}
|
|
5
|
+
`,{mode:384})}catch(c){throw await xa(e,{recursive:!0,force:!0}).catch(()=>{}),c}return async()=>{try{JSON.parse(await zs(o,"utf-8")).nonce===s&&await xa(e,{recursive:!0,force:!0})}catch{}}}catch(c){if(c.code!=="EEXIST")throw c}if(!(await mP(e,r).catch(()=>!1)&&await xa(e,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=a)throw new Xs(t.busyMessage??`${e} is busy; retry the command`);await new Promise(c=>setTimeout(c,uP))}}},mf=(e=Jb)=>dl(pP(),{waitMs:e,busyMessage:"connect profile is busy; retry the command"}),Br=async(e,t={})=>{if(il.getStore()===!0)return e();let n=await mf(t.waitMs);try{return await il.run(!0,e)}finally{await n()}},lf=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Zb(),r=`${n}.${process.pid}.${lP++}.tmp`;await cl(r,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,{mode:384}),await uf(r,384);try{await Ae(r,n)}catch(o){throw await xa(r,{force:!0}).catch(()=>{}),o}},de=async e=>{if(il.getStore()===!0){await lf(e);return}let t=await mf();try{await lf(e)}finally{await t()}},ul=async e=>{let t=async()=>{let r=await $(),{next:o,result:a}=e(r);return o&&await lf(o),a};if(il.getStore()===!0)return t();let n=await mf();try{return await t()}finally{await n()}},df=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],Vb="ssoLink",hf=async()=>{let e=await $();return df.some(t=>e[t]!==void 0)?!0:await Ye()!==void 0},pl=async()=>{let e=await $(),t=df.some(a=>e[a]!==void 0),n=e[Vb]!==void 0,r=e.byoUpstream!==void 0,o=await Ye()!==void 0;if(t||n||r||e.managedEnrollmentDisabled!==!0){let a={...e};for(let s of df)delete a[s];delete a[Vb],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,delete a.anyrayFleetManaged,await de(a)}if(await qs(),await Ye())throw new Error(`could not remove the dev key from ${oe()}`);return t||n||r||o},Fr=async(e,t,n=!1)=>{let r=await $(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=new Set(r.blockedTools??[]),i=r.offboardedAt;for(let g of e){let b=g.status==="configured"||g.status==="queued";!t&&b&&(o.add(g.id),a.delete(g.id),s.delete(g.id),i=void 0),!t&&g.refused===!0&&s.add(g.id),t&&(g.status==="reverted"||g.status==="queued")&&(o.delete(g.id),a.add(g.id),s.delete(g.id))}n&&(o.clear(),s.clear());let c=[...o].sort(),l=[...r.managedTools??[]].sort(),d=[...a].sort(),u=[...r.revertedTools??[]].sort(),p=[...s].sort(),m=[...r.blockedTools??[]].sort(),f=(g,b)=>g.length===b.length&&g.every((k,A)=>k===b[A]);if(f(c,l)&&r.revertedTools!=null&&f(d,u)&&f(p,m)&&i===r.offboardedAt)return;let{offboardedAt:w,...y}=r;await de({...y,...i!==void 0?{offboardedAt:i}:{},managedTools:c,revertedTools:d,blockedTools:p})},fl=async(e=new Date().toISOString())=>{await de({...await $(),offboardedAt:e})};var Oa=e=>vP(e).replace(/\\/g,"/").toLowerCase(),gf=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",ei=e=>`${e}.source`,eC=e=>/(^|\/)_npx(\/|$)/.test(Oa(e)),bf=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Oa(e)),Cf=e=>{let t=Oa(e),n=[kP(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Oa);return eC(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},kt=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),ti=e=>/[\\/](node|node\.exe)$/i.test(e),Wr=(e=kt())=>ti(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,zb=e=>{try{let t=qb(e);return t.isFile()?t.size:void 0}catch{return}},Af=e=>{let t=Xe(e);if(Ra(t)==="versions")return t;let n=Xe(t);return Ra(n)==="versions"?n:void 0},hl=(e,t)=>t!==void 0&&(Xe(e)===t||Xe(Xe(e))===t),SP=e=>{let t=Af(e);if(!t)return;let n=Be(Xe(t),"bin",gf());try{let r=Qs(n);return r===Qs(e)||hl(r,Qs(t))?n:void 0}catch{return}},_a=(e=oe(),t=process.platform)=>{let n=Be(e,"bin",gf(t));try{let r=Qs(n),o=Qs(Be(e,"versions"));if(hl(r,o))return n;if(t==="win32"){let a=yP(ei(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=zb(Be(o,a,gf(t)))??zb(Be(o,a));if(s!==void 0&&s===qb(n).size)return n}}catch{return}},Ur=(e=kt())=>{let t=Wr(e),n=bf(t)||vf(t)?_a():void 0;return SP(e.execPath)??n??t},tC=(e=kt())=>Ur(e)!==Wr(e),Sn=(e,t=kt())=>{let n=Ur(t);return ti(t.execPath)&&t.scriptPath!==void 0&&n===Wr(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},yl=(e=kt())=>{let t=Ur(e);return!ti(e.execPath)&&!Cf(t)?Xe(t):Be(oe(),"bin")},ml=async e=>{try{return await gP(e),!0}catch{return!1}},IP=async e=>{let t=await bP(e),n=Xe(t),r=Xe(n),o=Be(r,"package.json"),a=await wf(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 ml(Be(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},EP=async(e,t)=>{let n=t;for(;;){let r=Be(n,"node_modules",e);if(await ml(Be(r,"package.json")))return r;let o=Xe(n);if(o===n)return;n=o}},xP=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await wf(Be(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await EP(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Qb(i,Be(t,s),{recursive:!0}),r.push(i)}}},RP=async(e=kt())=>{let t=_a();if(t)return{command:t,args:[],entryPath:t};if(!ti(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await IP(e.scriptPath);await lt();let r=Be(oe(),"bin",`connect-runtime-${n.version}`),o=Be(r,"dist","index.js");if(!await ml(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await yf(a,{recursive:!0,force:!0}),await Xb(a,{recursive:!0,mode:448});try{await Qb(n.dist,Be(a,"dist"),{recursive:!0}),await AP(Be(a,"package.json"),await wf(n.packageJson),{mode:384}),await xP(n.root,Be(a,"node_modules")),await Xb(Xe(r),{recursive:!0,mode:448});try{await CP(a,r)}catch(s){if(!await ml(o))throw s}}finally{await yf(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},kf=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,OP=e=>{let t=Ra(Xe(Xe(e)));return kf.test(t)?t:void 0},vf=(e,t=oe())=>{let n=Xe(Xe(e));return Oa(Xe(n))===Oa(Be(t,"bin"))&&kf.test(Ra(n))&&Ra(Xe(e))==="dist"&&Ra(e)==="index.js"},nC=(e,t,n)=>{if(t.some(a=>a.status!=="configured"))return!1;let r=new Set(t.map(a=>a.id)),o=new Set(n);return(e??[]).every(a=>r.has(a)||o.has(a))},gl=async(e=kt())=>{let t=Be(oe(),"bin"),n=OP(Wr(e)),r=[];for(let o of await wP(t).catch(()=>[])){if(!kf.test(o)||o===n)continue;let a=Be(t,o);await yf(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},rC=async(e,t=kt())=>{let n=Wr(t);if(!ti(t.execPath)||!eC(n)||_a())return;let r=await RP(t),o=hP(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Sf=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,ni=(e,t)=>[e,...t].map(Sf).join(" "),nr=(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}:{}}]}),Hr=(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))},wl=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!Hr(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},Ta=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!Hr(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)},If=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=>!Hr(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 nt="__anyray-hook",oC="__anyray-codex-hook",Gr="__anyray-prompt-hook",aC="__anyray-shell-pretool",Ef="__anyray-shell-run",sC="__anyray-read-pretool",Kr="__anyray-refresh",_o=(e,t=[])=>{let{command:n,args:r}=Sn([e,...t]);return{command:n,args:r}},Ht=(e,t=[])=>{let n=_o(e,t);return[n.command,...n.args].map(Sf).join(" ")},bl=(e,t,n=[])=>typeof e=="string"&&e.trim()===Ht(t,n),iC=()=>Ht("print-key"),De=()=>Ur(),dt=Cf,te=()=>!dt(De()),In=async()=>{if(!te())return!1;try{return await _P(De()),!0}catch{return!1}},Vr="__anyray-mcp-server",We=e=>_o(Vr,[e]),TP=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),Pa=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=We(t);return n.command===r.command&&TP(n.args,r.args)},vt=(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)===Vr&&r.at(-1)===t};var ae=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,be=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))},jr=e=>e.changesBilling===!0||e.changesOrgManagement===!0;var To=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],cC=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Cl=[...To,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],PP=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
|
|
7
7
|
`)},En=(e,t={})=>{let n=e.byoUpstream,r=!n&&ae(e,"anthropic"),o=be({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1,s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=PP(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 xf}from"zod";var DP=5e3,LP=1e3,NP=1e8,$P=xf.object({modelContext:xf.object({contextTokens:xf.number().int().min(LP).max(NP)}).optional()}),lC=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},dC=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??DP,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=$P.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var MP=1e6,ri="[1m]",BP=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},uC=(e,t)=>!e||t===void 0?{}:BP(e)?{envTokens:t}:t<MP?{}:e.toLowerCase().endsWith(ri)?{}:{model:`${e}${ri}`},pC=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(ri))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(ri))return e.slice(0,-ri.length)};import{platform as FP}from"node:os";var Gt=(e=FP())=>{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 rr=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],Al=e=>typeof e=="string"&&e.trim()!=="",WP=(e,t)=>typeof e[t]=="string"&&!Al(e[t]),fC=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},UP=()=>F(Gt()).catch(()=>({})),mC=async(e={})=>{let t=e.env??process.env,n=fC(e.userSettings??{}),r=fC(await(e.readManaged??UP)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of rr)Al(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Gt()})`,repairable:!1}):Al(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!WP(n,a)&&Al(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Rf=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`,Of=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.",hC=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 HP=rr.map(e=>e.name),GP=Cl.filter(e=>!HP.includes(e)),yC=e=>typeof e=="string"&&e.trim()!=="",gC=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},KP=(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)},VP=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},_f=()=>F(Gt()).catch(()=>({})),wC=_f,jP=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=>Hr(r,nt))},bC=async(e={})=>{let t=await(e.readManaged??wC)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!jP(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},kl=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Gt()}) \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 (${Gt()}), 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",vl=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.",CC=async(e={})=>{let t=gC(e.userSettings??{}),n=gC(await(e.readManaged??wC)().catch(()=>({}))),r=[];for(let o of GP){if(!yC(n[o])||!yC(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(KP(n[o],t[o],a))continue;let s=a?VP(n[o]):void 0;r.push({name:o,source:`managed settings (${Gt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},AC=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`,kC=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 YP}from"node:os";import{join as ZP}from"node:path";import{readFile as JP}from"node:fs/promises";var XP=400,vC=async()=>{try{let e=ZP(YP(),".claude","settings.json"),n=JSON.parse(await JP(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
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}},SC=async()=>{try{let e=await $();return e.gateway?{origin:new URL(e.gateway).origin,metadata:be({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},ut=async(e="auto")=>e==="profile"?SC():e==="claude"?vC():await vC()??await SC(),Sl=async(e={})=>{let t=e.readTarget??ut,n=e.loadProfile??$,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"},dn=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},Il=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),XP);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:dn(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var El="anyray-org",Kt="x-anyray-api-key";var Pf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),IC=e=>{try{return new URL(e).origin}catch{return}},zP=(e,t)=>{if(!Pf(e)||typeof e.url!="string")return!1;try{let n=new URL(e.url);return t.includes(n.origin)&&/\/mcp\/org\/?$/.test(n.pathname)}catch{return!1}},xn=(e,t,n,r)=>{let o=e[t];if(o!==void 0&&!Pf(o))return"conflict";let a=Pf(o)?o:{},s=a[El];return s!==void 0&&!zP(s,n)?"conflict":r===void 0?s===void 0?"unchanged":(delete a[El],Object.keys(a).length===0?delete e[t]:e[t]=a,"changed"):JSON.stringify(s)===JSON.stringify(r)?"unchanged":(a[El]=r,e[t]=a,"changed")},xl="# >>> anyray org mcp >>>",Df="# <<< anyray org mcp <<<",Lf=`[mcp_servers.${El}]`,Tf=e=>JSON.stringify(e),qP=e=>[Lf,`url = ${Tf(e.url)}`,`http_headers = { ${Tf(Kt)} = ${Tf(e.clientKey)} }`],QP=new RegExp(`\\n?${xl.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\s\\S]*?${Df.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\n?`),eD=e=>{let t=e.indexOf(xl);if(t<0||e.indexOf(Df,t+xl.length)>=0)return e;let n=e.slice(t).split(`
|
|
9
9
|
`),r=1,o=!1,a=!1;for(;r<n.length;){let s=n[r].trim();if(s===Lf){if(o)break;o=!0,r+=1;continue}if(s.startsWith("[")||(s.includes(Kt)&&(a=!0),s!==""&&!s.startsWith("#")&&!/^[\w."'-]+\s*=/.test(s)))break;r+=1}return!o||!a?e:e.slice(0,t)+n.slice(r).join(`
|
|
@@ -14,7 +14,7 @@ var MT="http://localhost:8787",Ys="anyray-placeholder",vb=/^ark_[A-Za-z0-9_-]{20
|
|
|
14
14
|
|
|
15
15
|
`:""}${r}
|
|
16
16
|
`:o?`${o}
|
|
17
|
-
`:"";return{text:a,outcome:a===e?"unchanged":"changed"}};import{readFile as tD}from"node:fs/promises";var nD=/ark_[A-Za-z0-9_-]{20,512}/,Vt=async(e,t)=>{if(t.length===0)return null;let n=!1;for(let r of e){let o;try{o=await tD(r,"utf-8")}catch{continue}if(o.includes(t))return!0;nD.test(o)&&(n=!0)}return n?!1:null};var Rn=()=>Ol(Rl(),".claude","settings.json"),oi=()=>Ol(Rl(),".claude.json"),rD=Cl,or="anyray",oD=()=>({type:"stdio",...We("claude"),alwaysLoad:!0}),Yr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),aD=e=>e instanceof Error?e.name:"UnknownError",sD={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},iD=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${or} 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.`}},cD={readJson:F,writeJson:(e,t)=>q(e,t)},lD=async(e,t=cD)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(dD(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=Yr(a)?a[or]:void 0;if(s&&vt(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},dD=e=>{if("mcpServers"in e&&!Yr(e.mcpServers))return"conflict";let t=Yr(e.mcpServers)?{...e.mcpServers}:{},n=t[or];return n!==void 0&&!vt(n,"claude")?"conflict":(t[or]=oD(),e.mcpServers=t,"installed")},xC=e=>{let t=e.mcpServers;return!t||!(or in t)||!vt(t[or],"claude")?!1:(delete t[or],Object.keys(t).length===0&&delete e.mcpServers,!0)},uD=e=>{wl(e,"PostToolUse",nt,nr(Ht(nt),{matcher:"*"})),wl(e,"UserPromptSubmit",Gr,nr(Ht(Gr)))},pD=e=>{wl(e,"SessionStart",Kr,nr(Ht(Kr),{async:!0}))},_C=e=>_a(e,"SessionStart",Kr),RC=e=>{let t=_a(e,"PostToolUse",nt),n=_a(e,"UserPromptSubmit",Gr),r=_C(e);return t||n||r},fD="print-key",mD=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(De()),To=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===fD&&mD(t)},hD=async(e,t)=>{let n=(await Ro(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of rD){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},yD=e=>typeof e.apiKeyHelper=="string"&&!To(e),TC=async e=>{let t=await _f(),n=async()=>t,[r,o,a]=await Promise.all([mC({userSettings:e,readManaged:n}),CC({userSettings:e,readManaged:n}).catch(()=>[]),bC({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},OC=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await TC(e),o=Of(t),a=kC(n);return{routingOverrides:[...t.map(i=>({problem:Rf(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:AC(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},Zr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=Ol(Rl(),".claude"),t=await R(e);return{installed:t,detail:t?Rn():"no ~/.claude directory"}},async apply(e,t){let n=Rn(),r=await F(n),o=lC(r),a=await dC(e.origin,e.clientKey,o),s=uC(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=En(e,{contextWindowTokens:s.envTokens}),{directOverrides:p,hookPolicy:m}=await TC(r),f=p.filter(x=>!x.repairable),h=p.filter(x=>x.repairable),w=[...f.map(x=>`WARNING: ${Rf(x)}.`),...f.length?[Of(f)]:[],...m.state==="fine"?[]:[`WARNING: ${kl(m)}.`,vl(m)],...h.map(x=>hC(x)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let y=r.env??{};r.env={...y,...i};let g=r.env;for(let{name:x}of rr)h.some(_=>_.name===x)?g[x]="":g[x]===""&&(process.env[x]??"").trim()===""&&delete g[x];if(u||delete g.ANTHROPIC_CUSTOM_HEADERS,c&&(y.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete g.ANTHROPIC_AUTH_TOKEN),l)for(let x of cC)delete g[x];let b=!!e.clientKey,k=te(),A=yD(r);!c&&!l&&b&&k&&!A?(r.apiKeyHelper=iC(),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).")):To(r)&&delete r.apiKeyHelper,A&&!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?(pD(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):_C(r),te()?(uD(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.")):(RC(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${De()}). 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 q(n,r);let O=[n],S=oi(),I;if(te()){let x=await lD(S);x.outcome==="registered"?(O.push(S),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(iD(x.failure,S)),I=sD[x.failure])}else try{let x=await F(S);xC(x)&&(await q(S,x),O.push(S))}catch(x){w.push(`Could not clean up a stale Anyray MCP registration in ${S} (${aD(x)}).`)}return{status:"configured",messages:w,changedFiles:O,...I?{errorClass:I}:{}}},skillsDir(){return Ol(Rl(),".claude","skills")},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=oi(),r=await F(n),o=xn(r,"mcpServers",e,t&&{type:"http",url:t.url,headers:{[Kt]:t.clientKey}});return o==="changed"&&await q(n,r,{backup:!1}),{changed:o==="changed"}},async syncOrgMarketplace(e){let t=Rn(),n=await F(t),r=e!==void 0&&Ub(e.url),o=r&&e?Gb(n,e):cf(n);return o&&await q(t,n,{backup:!1}),{changed:o,handlesPluginSkills:r&&e!==void 0?Kb(n,e):!1}},async pointsAt(e){let t=Rn();if(!await R(t))return!1;try{let o=(await F(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async configuredKeyIsCurrent(e){return Vt([Rn()],e)},async runtimeDiagnostics(){let e=await F(Rn()).catch(()=>({}));return OC(e)},async routingOverrides(){let e=await F(Rn()).catch(()=>({}));return(await OC(e)).routingOverrides},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=oi();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await F(e)).mcpServers?.[or];return r?vt(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=Rn();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!Yr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>Hr(c,nt))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>Hr(c,nt)&&Yr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Yr(l)&&bl(l.command,nt))))}}catch{e="unreadable"}let r,o=!0,a=oi();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!Yr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[or];r=i===void 0?"missing":vt(i,"claude")?"owned":"foreign",r==="owned"&&(o=Ta(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await In()?"owned":"missing",beacon_target:await Sl().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await F(Rn()),t=Yr(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=Rn();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await F(t),r=n.env,o=RC(n),a=To(n);a&&delete n.apiKeyHelper;let s=r?await hD(t,r):[],i=pC(typeof n.model=="string"?n.model:void 0,(await Ro(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env;let c=cf(n);(r||o||a||c||i!==void 0)&&await q(t,n,{backup:!1});let l=[`removed Anyray keys from ${t}`];c&&l.push("Removed the Anyray org skills marketplace and its plugins."),i!==void 0&&l.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&l.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&l.push("Removed the Anyray apiKeyHelper."),s.length&&l.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let d=oi();try{let u=await F(d);xC(u)&&(await q(d,u,{backup:!1}),l.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await pe(t),{status:"reverted",messages:l,changedFiles:[t]}}};import{delimiter as gD,dirname as wD}from"node:path";var Jr=e=>{let{command:t,args:n}=Sn([e]);return{command:t,args:n}},Po=()=>Ur(),Ot=(e="",t=process.env.PATH??"",n=yl(),r=Ur())=>{let a=t.split(gD).filter(Boolean).some(s=>s===n)||wD(r)!==n?"anyray-connect":r;return e?`${a} ${e}`:a};import{rm as bD,stat as CD}from"node:fs/promises";import{homedir as PC,platform as AD}from"node:os";import{join as kD}from"node:path";var Nf="Anyray",vD=(e=PC())=>kD(e,"Applications",`${Nf}.app`),$f=async(e={})=>{if((e.os??AD())!=="darwin")return{ok:!0,messages:[]};let n=vD(e.home??PC());try{return await CD(n).then(()=>!0,()=>!1)?(await bD(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed the legacy ${Nf}.app background item from ~/Applications.`]}):{ok:!0,messages:[]}}catch(r){return{ok:!1,messages:[`Could not remove the legacy ${Nf}.app background item (${r?.name??"Error"}).`]}}};import{homedir as DC,userInfo as SD}from"node:os";var LC=()=>{try{return DC()!==SD().homedir}catch{return!1}},Mf=e=>[`Skipped ${e} \u2014 HOME (${DC()}) 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 On=(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,ar=(e=process.env)=>On(e)!==null,sr=e=>e==="codespaces"||e==="devcontainer",Pa=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var NC=()=>Lo(Dl(),".anyray","logs"),Wf=()=>Lo(NC(),"connect-refresh.log"),Pl=1800,Ll="ai.anyray.connect.refresh",ii="anyray-refresh",Hf="\\AnyrayConnectKeyRefresh",Nl=Ll,ci=ii,si=Hf,RD=String(Pl/60),Gf=(e,t)=>{let n=xD(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},Kf=()=>Lo(Dl(),"Library","LaunchAgents",`${Nl}.plist`),Vf=()=>Lo(Dl(),".config","systemd","user"),$C=()=>Lo(Vf(),`${ci}.service`),Tl=()=>Lo(Vf(),`${ci}.timer`),Ff=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),$l=()=>Jr(Kr),OD=(e=$l())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${Ff(o)}</string>`).join(`
|
|
17
|
+
`:"";return{text:a,outcome:a===e?"unchanged":"changed"}};import{readFile as tD}from"node:fs/promises";var nD=/ark_[A-Za-z0-9_-]{20,512}/,Vt=async(e,t)=>{if(t.length===0)return null;let n=!1;for(let r of e){let o;try{o=await tD(r,"utf-8")}catch{continue}if(o.includes(t))return!0;nD.test(o)&&(n=!0)}return n?!1:null};var Rn=()=>Ol(Rl(),".claude","settings.json"),oi=()=>Ol(Rl(),".claude.json"),rD=Cl,or="anyray",oD=()=>({type:"stdio",...We("claude"),alwaysLoad:!0}),Yr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),aD=e=>e instanceof Error?e.name:"UnknownError",sD={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},iD=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${or} 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.`}},cD={readJson:F,writeJson:(e,t)=>q(e,t)},lD=async(e,t=cD)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(dD(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=Yr(a)?a[or]:void 0;if(s&&vt(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},dD=e=>{if("mcpServers"in e&&!Yr(e.mcpServers))return"conflict";let t=Yr(e.mcpServers)?{...e.mcpServers}:{},n=t[or];return n!==void 0&&!vt(n,"claude")?"conflict":(t[or]=oD(),e.mcpServers=t,"installed")},xC=e=>{let t=e.mcpServers;return!t||!(or in t)||!vt(t[or],"claude")?!1:(delete t[or],Object.keys(t).length===0&&delete e.mcpServers,!0)},uD=e=>{wl(e,"PostToolUse",nt,nr(Ht(nt),{matcher:"*"})),wl(e,"UserPromptSubmit",Gr,nr(Ht(Gr)))},pD=e=>{wl(e,"SessionStart",Kr,nr(Ht(Kr),{async:!0}))},_C=e=>Ta(e,"SessionStart",Kr),RC=e=>{let t=Ta(e,"PostToolUse",nt),n=Ta(e,"UserPromptSubmit",Gr),r=_C(e);return t||n||r},fD="print-key",mD=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(De()),Po=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===fD&&mD(t)},hD=async(e,t)=>{let n=(await Ro(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of rD){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},yD=e=>typeof e.apiKeyHelper=="string"&&!Po(e),TC=async e=>{let t=await _f(),n=async()=>t,[r,o,a]=await Promise.all([mC({userSettings:e,readManaged:n}),CC({userSettings:e,readManaged:n}).catch(()=>[]),bC({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},OC=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await TC(e),o=Of(t),a=kC(n);return{routingOverrides:[...t.map(i=>({problem:Rf(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:AC(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},Zr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=Ol(Rl(),".claude"),t=await R(e);return{installed:t,detail:t?Rn():"no ~/.claude directory"}},async apply(e,t){let n=Rn(),r=await F(n),o=lC(r),a=await dC(e.origin,e.clientKey,o),s=uC(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=En(e,{contextWindowTokens:s.envTokens}),{directOverrides:p,hookPolicy:m}=await TC(r),f=p.filter(E=>!E.repairable),h=p.filter(E=>E.repairable),w=[...f.map(E=>`WARNING: ${Rf(E)}.`),...f.length?[Of(f)]:[],...m.state==="fine"?[]:[`WARNING: ${kl(m)}.`,vl(m)],...h.map(E=>hC(E)),`${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:E}of rr)h.some(O=>O.name===E)?g[E]="":g[E]===""&&(process.env[E]??"").trim()===""&&delete g[E];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 E of cC)delete g[E];let b=!!e.clientKey,k=te(),A=yD(r);!c&&!l&&b&&k&&!A?(r.apiKeyHelper=iC(),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).")):Po(r)&&delete r.apiKeyHelper,A&&!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?(pD(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):_C(r),te()?(uD(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.")):(RC(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${De()}). 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 q(n,r);let _=[n],S=oi(),I;if(te()){let E=await lD(S);E.outcome==="registered"?(_.push(S),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(iD(E.failure,S)),I=sD[E.failure])}else try{let E=await F(S);xC(E)&&(await q(S,E),_.push(S))}catch(E){w.push(`Could not clean up a stale Anyray MCP registration in ${S} (${aD(E)}).`)}return{status:"configured",messages:w,changedFiles:_,...I?{errorClass:I}:{}}},skillsDir(){return Ol(Rl(),".claude","skills")},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=oi(),r=await F(n),o=xn(r,"mcpServers",e,t&&{type:"http",url:t.url,headers:{[Kt]:t.clientKey}});return o==="changed"&&await q(n,r,{backup:!1}),{changed:o==="changed"}},async syncOrgMarketplace(e){let t=Rn(),n=await F(t),r=e!==void 0&&Ub(e.url),o=r&&e?Gb(n,e):cf(n);return o&&await q(t,n,{backup:!1}),{changed:o,handlesPluginSkills:r&&e!==void 0?Kb(n,e):!1}},async pointsAt(e){let t=Rn();if(!await R(t))return!1;try{let o=(await F(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async configuredKeyIsCurrent(e){return Vt([Rn()],e)},async runtimeDiagnostics(){let e=await F(Rn()).catch(()=>({}));return OC(e)},async routingOverrides(){let e=await F(Rn()).catch(()=>({}));return(await OC(e)).routingOverrides},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=oi();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await F(e)).mcpServers?.[or];return r?vt(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=Rn();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!Yr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>Hr(c,nt))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>Hr(c,nt)&&Yr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Yr(l)&&bl(l.command,nt))))}}catch{e="unreadable"}let r,o=!0,a=oi();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!Yr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[or];r=i===void 0?"missing":vt(i,"claude")?"owned":"foreign",r==="owned"&&(o=Pa(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await In()?"owned":"missing",beacon_target:await Sl().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await F(Rn()),t=Yr(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=Rn();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await F(t),r=n.env,o=RC(n),a=Po(n);a&&delete n.apiKeyHelper;let s=r?await hD(t,r):[],i=pC(typeof n.model=="string"?n.model:void 0,(await Ro(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env;let c=cf(n);(r||o||a||c||i!==void 0)&&await q(t,n,{backup:!1});let l=[`removed Anyray keys from ${t}`];c&&l.push("Removed the Anyray org skills marketplace and its plugins."),i!==void 0&&l.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&l.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&l.push("Removed the Anyray apiKeyHelper."),s.length&&l.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let d=oi();try{let u=await F(d);xC(u)&&(await q(d,u,{backup:!1}),l.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await pe(t),{status:"reverted",messages:l,changedFiles:[t]}}};import{delimiter as gD,dirname as wD}from"node:path";var Jr=e=>{let{command:t,args:n}=Sn([e]);return{command:t,args:n}},Do=()=>Ur(),Ot=(e="",t=process.env.PATH??"",n=yl(),r=Ur())=>{let a=t.split(gD).filter(Boolean).some(s=>s===n)||wD(r)!==n?"anyray-connect":r;return e?`${a} ${e}`:a};import{rm as bD,stat as CD}from"node:fs/promises";import{homedir as PC,platform as AD}from"node:os";import{join as kD}from"node:path";var Nf="Anyray",vD=(e=PC())=>kD(e,"Applications",`${Nf}.app`),$f=async(e={})=>{if((e.os??AD())!=="darwin")return{ok:!0,messages:[]};let n=vD(e.home??PC());try{return await CD(n).then(()=>!0,()=>!1)?(await bD(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed the legacy ${Nf}.app background item from ~/Applications.`]}):{ok:!0,messages:[]}}catch(r){return{ok:!1,messages:[`Could not remove the legacy ${Nf}.app background item (${r?.name??"Error"}).`]}}};import{homedir as DC,userInfo as SD}from"node:os";var LC=()=>{try{return DC()!==SD().homedir}catch{return!1}},Mf=e=>[`Skipped ${e} \u2014 HOME (${DC()}) 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 On=(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,ar=(e=process.env)=>On(e)!==null,sr=e=>e==="codespaces"||e==="devcontainer",Da=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var NC=()=>No(Dl(),".anyray","logs"),Wf=()=>No(NC(),"connect-refresh.log"),Pl=1800,Ll="ai.anyray.connect.refresh",ii="anyray-refresh",Hf="\\AnyrayConnectKeyRefresh",Nl=Ll,ci=ii,si=Hf,RD=String(Pl/60),Gf=(e,t)=>{let n=xD(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},Kf=()=>No(Dl(),"Library","LaunchAgents",`${Nl}.plist`),Vf=()=>No(Dl(),".config","systemd","user"),$C=()=>No(Vf(),`${ci}.service`),Tl=()=>No(Vf(),`${ci}.timer`),Ff=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),$l=()=>Jr(Kr),OD=(e=$l())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${Ff(o)}</string>`).join(`
|
|
18
18
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
19
19
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
20
20
|
<plist version="1.0">
|
|
@@ -49,30 +49,30 @@ Persistent=true
|
|
|
49
49
|
|
|
50
50
|
[Install]
|
|
51
51
|
WantedBy=timers.target
|
|
52
|
-
`,PD=(e=$l())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),ai=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(" ")}`],MC=e=>!e.run&&LC(),DD=async(e,t)=>await ID(Kf(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Nl]).ok,Xr=async(e={})=>{let t=e.os??Uf(),n=e.invocation??$l(),r=e.run??Gf,o=e.binaryPath??
|
|
53
|
-
${t.stderr??""}`}},UD=async e=>{try{return(await $D(e)).isDirectory()}catch{return!1}},HD=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},jf=async(e,t={})=>{if((t.os??ND())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??UD)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??WD;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?HD(a.output):void 0;return s?BD.has(s)?FD(a.output)!==cr?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},Da=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await jf(n,t)).ok?"healthy":"gone"},Yf=async(e={})=>{try{let t=e.load??$,n=await t(),r=await Da(n,e);if(r!=="gone")return r;let o=e.installScheduler??Xr;return n.refreshSchedulerEnabled&&rt(n)&&await o().catch(()=>{}),await(e.save??de)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var GD={"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."},KD=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},VD=async(e,t)=>{let n=t.stderr??console.error,r=KD(e,"--app-path")??WC,o=await jf(r,t);if(!o.ok)return n(GD[o.reason]),1;let s=await(t.load??$)();return await(t.save??de)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??ir)().catch(()=>{}),0},jD=async e=>{let t=e.load??$,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??Xr;return n.refreshSchedulerEnabled&&rt(n)&&await r().catch(()=>{}),await(e.save??de)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},UC=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await VD(e,t):e.includes("--release-tray")?await jD(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 YD}from"node:fs/promises";import{homedir as Ml,platform as ui}from"node:os";import{join as _t}from"node:path";import{basename as HC,dirname as Zf,join as La}from"node:path";var zr="https://github.com/anyrayHQ/install/releases",No="connect-v",Jf="release-assets.githubusercontent.com",Xf=".anyray",$o="__anyray-refresh-desktop-helpers",qr=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",lr=(e,t=process.platform)=>({launcher:La(e,"bin",qr(t)),binDir:La(e,"bin"),versionsDir:La(e,"versions"),lock:La(e,"update.lock"),state:La(e,"update-state.json")}),di=(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"}},zf=(e,t,n=process.platform)=>HC(e)===qr(n)&&HC(Zf(e))==="bin"?Zf(Zf(e)):La(t,Xf);var qf=(e=ui(),t=Ml())=>e==="darwin"?[{id:cr,mechanism:"launch-agent",filePaths:[_t(t,"Library","LaunchAgents",`${cr}.plist`)]}]:e==="linux"?[{id:cr,mechanism:"xdg-autostart",filePaths:[_t(t,".config","autostart",`${cr}.desktop`)]}]:e==="win32"?[{id:cr,mechanism:"registry-run",filePaths:[],registryValues:[{key:"HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",value:cr},{key:"HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",value:cr}]}]:[],Bl=(e=ui(),t=Ml())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:Ll,paths:[_t(t,"Library","LaunchAgents",`${Ll}.plist`)],dataPaths:[_t(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=_t(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${ii}.timer`,paths:[_t(n,`${ii}.timer`),_t(n,`${ii}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:Hf,paths:[]}]:[]},GC=async e=>{try{return await YD(e),!0}catch{return!1}},Fl=async(e={})=>{let t=e.os??ui(),n=e.exists??GC;for(let r of Bl(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await _n(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},KC=async e=>{let t={suspected:!1,missingPaths:[],kinds:[],removed:!1};if(!e.binaryDurable||!e.schedulerEnabled||e.schedulerInstalled||e.trayManaged===!0)return t;let n=e.exists??GC;for(let r of Bl(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.removed=t.suspected&&e.schedulerInstalledOnce===!0,t},VC=e=>{let t=e.os??ui(),n=e.home??Ml(),r=e.binaryPath??Po(),o=e.arch??process.arch,a=lr(zf(r,n,t),t),s=qr(t);return{schema:"anyray.connect.security-exclusions/v1",connectVersion:e.connectVersion,platform:t,arch:o,binary:{path:r,...e.binarySha256?{sha256:e.binarySha256}:{}},services:Bl(t,n).map(i=>({kind:i.kind,title:i.title,supervisorName:i.supervisorName,unitPaths:i.paths,logPaths:i.dataPaths??[]})),optionalDesktopAutostart:qf(t,n),writePaths:[_t(a.versionsDir,"<version>",s),a.launcher,a.lock,a.state],network:{outboundHosts:[...e.gatewayHost?[e.gatewayHost]:[],"github.com",Jf],inboundListeners:[]},notes:["Match on binary.path and services[].supervisorName. Do not match on binary.sha256: connect self-updates, so a hash-scoped exclusion stops matching at the next release.","The scheduler is unprivileged and runs as the logged-in user. It renews the seat gateway key so a long AI-coding session does not lose access.","A seat whose key cannot lapse between sessions installs no scheduler at all, and connect retires one it no longer needs.","No inbound listener, no proxy, no CA certificate, no DNS change."]}},jC=(e=ui(),t=Ml(),n=Po(),r=process.arch)=>{let o=lr(zf(n,t,e),e),a=qr(e),s=di(e,r),i=s?[` ${zr}/download/${No}<version>/${s}`]:[" (no binary is published for this OS/architecture \u2014 nothing here"," downloads a release asset)"],c=["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 l of Bl(e,t)){c.push(`${l.title} \u2014 supervisor name: ${l.supervisorName}`);for(let d of l.paths)c.push(` ${d}`);l.paths.length===0&&c.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let d of l.dataPaths??[])c.push(` ${d} (captured stdout/stderr \u2014 setup progress and error names, including this seat's enrollment email; never credentials or prompt/response content)`);c.push("")}c.push("Optional signed desktop app autostart (not required or health-checked by","the CLI scheduler):");for(let l of qf(e,t)){c.push(` ${l.id} \u2014 ${l.mechanism}`);for(let d of l.filePaths)c.push(` ${d}`);for(let d of l.registryValues??[])c.push(` ${d.key} :: ${d.value}`)}return qf(e,t).length===0&&c.push(" (not supported on this OS)"),c.push(""),c.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."," - Outbound: github.com, for the self-update below. Asset downloads",` redirect to ${Jf}.`," - No inbound listener, no proxy, no CA certificate, no DNS change.","","Self-update:"," The installed binary keeps itself on the published version, on the same"," tick as key renewal. Every file it downloads is SHA-256 verified against"," the release's published SHA256SUMS before anything is activated; a"," mismatch is deleted and the running version stays.",""," Fetches over HTTPS, unauthenticated, no request body:",` ${zr}/latest`," (the redirect target alone names the published version)",` ${zr}/download/${No}<version>/connect-update.json`,` ${zr}/download/${No}<version>/SHA256SUMS`,...i,""," Writes:",` ${_t(o.versionsDir,"<version>",a)}`," (the downloaded binary; the version it replaces is kept for rollback)",` ${o.launcher}`," (the stable path above, pointed at the new version)",` ${o.lock}`,` ${o.state}`,` ${_t(o.versionsDir,"<version>",`${a}.part-<pid>`)}`,...e==="win32"?[` ${_t(o.binDir,`${a}.old-<pid>`)}`,` ${_t(o.binDir,`${a}.rollback-<pid>`)}`]:[` ${_t(o.binDir,`${a}.new-<pid>`)}`]," (transient: a partial download and the staged swap, removed as the"," swap completes or on the next run)",...e==="win32"?[""," Windows cannot overwrite a running .exe, so activation renames the"," live copy aside, copies the new one into place, and records the",` active version in \`${a}.source\` beside it.`]:[],""," Runs the newly downloaded binary directly, around the swap:"," - `--version`, as a smoke test when it replaces a non-managed runtime;"," a failure puts the previous version back.",` - \`anyray-connect ${$o}\`, which rewrites an`," already-installed Anyray credential-helper script to name the new"," path. It writes nothing where no such helper exists.","","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."),c};import{homedir as dL}from"node:os";import{join as Zl}from"node:path";import{chmod as uL,readFile as $a,rm as eA,copyFile as pL}from"node:fs/promises";import{parse as ZD}from"smol-toml";var dr="# >>> anyray connect >>>",Na="# <<< anyray connect <<<",Qf="# restore: ",YC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ul=e=>{let t=new RegExp(`\\n*${YC(dr)}[\\s\\S]*?${YC(Na)}\\n?`,"g");return JC(e.replace(t,""))},JD="model_provider",XD="anyray",zD=new RegExp(`^\\s*(["'])${XD}\\1\\s*(#.*)?$`),qD=(e,t)=>t===JD&&zD.test(e.slice(e.indexOf("=")+1)),JC=e=>{let t=e.indexOf(dr);if(t<0||e.indexOf(Na,t+dr.length)>=0)return e;let n=e.slice(0,t),r=e.slice(t).split(`
|
|
54
|
-
`),o=
|
|
52
|
+
`,PD=(e=$l())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),ai=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(" ")}`],MC=e=>!e.run&&LC(),DD=async(e,t)=>await ID(Kf(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Nl]).ok,Xr=async(e={})=>{let t=e.os??Uf(),n=e.invocation??$l(),r=e.run??Gf,o=e.binaryPath??Do();if(dt(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(MC(e))return{ok:!1,messages:Mf("auto-refresh scheduling")};let a=On(e.env??(e.run?{}:process.env));if(sr(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${Da(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=Kf(),i=OD(n),c=await $f({os:t});if(await DD(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`,...c.messages]};await Bf(NC(),{recursive:!0,mode:448}),await Bf(No(Dl(),"Library","LaunchAgents"),{recursive:!0});let l=String(process.getuid?.()??""),d=`${s}.new-${process.pid}`;await Lo(d,{force:!0}).catch(()=>{}),await _l(d,i),r("launchctl",["bootout",`gui/${l}`,s]),await Lo(s,{force:!0}).catch(()=>{});try{await ED(d,s)}catch{await _l(s,i),await Lo(d,{force:!0}).catch(()=>{})}return r("launchctl",["bootstrap",`gui/${l}`,s]).ok||r("launchctl",["load","-w",s]).ok?{ok:!0,messages:[`Scheduled auto-refresh via launchd (${s}).`,...c.messages]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...ai(n)]}}if(t==="linux")return await Bf(Vf(),{recursive:!0}),await _l($C(),_D(n)),await _l(Tl(),TD()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${ci}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${Tl()}).`]}:{ok:!1,messages:[`Wrote ${Tl()} but \`systemctl --user enable --now\` failed.`,...ai(n)]};if(t==="win32"){let s=PD(n);return r("schtasks",["/Create","/TN",si,"/TR",s,"/SC","MINUTE","/MO",RD,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",si]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${si}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...ai(n)]}}return{ok:!1,messages:ai(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...ai(n)]}}},ir=async(e={})=>{await Lo(Wf(),{force:!0}).catch(()=>{});let t=e.os??Uf(),n=e.run??Gf,r=[];if(MC(e))return{ok:!0,messages:Mf("scheduler teardown")};try{if(t==="darwin"){let o=Kf(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Lo(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.");let s=await $f({os:t});r.push(...s.messages)}else t==="linux"?(n("systemctl",["--user","disable","--now",`${ci}.timer`]),await Lo(Tl(),{force:!0}),await Lo($C(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",si,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},_n=async(e=Uf(),t=Gf)=>e==="win32"?t("schtasks",["/Query","/TN",si]).ok:e==="darwin"?t("launchctl",["list",Nl]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${ci}.timer`]).ok:!1;import{platform as ND}from"node:os";import{stat as $D}from"node:fs/promises";import{spawnSync as MD}from"node:child_process";var li=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},BC=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),LD=10080*60*1e3,FC=(e,t,n=Date.now())=>{let r=[],o=li(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)<=LD},rt=(e,t={},n=Date.now())=>{if(!e.enrolledCert)return!1;let o=(t.toolIds??e.managedTools??[]).some(a=>BC.has(a));return FC(e,t.keyExpiresAt,n)||!o};var WC="/Applications/Anyray Connect Tray.app",BD=new Set(["V53XMA78UF"]),cr="ai.anyray.connect-tray",FD=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,WD=e=>{let t=MD("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
53
|
+
${t.stderr??""}`}},UD=async e=>{try{return(await $D(e)).isDirectory()}catch{return!1}},HD=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},jf=async(e,t={})=>{if((t.os??ND())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??UD)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??WD;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?HD(a.output):void 0;return s?BD.has(s)?FD(a.output)!==cr?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},La=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await jf(n,t)).ok?"healthy":"gone"},Yf=async(e={})=>{try{let t=e.load??$,n=await t(),r=await La(n,e);if(r!=="gone")return r;let o=e.installScheduler??Xr;return n.refreshSchedulerEnabled&&rt(n)&&await o().catch(()=>{}),await(e.save??de)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var GD={"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."},KD=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},VD=async(e,t)=>{let n=t.stderr??console.error,r=KD(e,"--app-path")??WC,o=await jf(r,t);if(!o.ok)return n(GD[o.reason]),1;let s=await(t.load??$)();return await(t.save??de)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??ir)().catch(()=>{}),0},jD=async e=>{let t=e.load??$,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??Xr;return n.refreshSchedulerEnabled&&rt(n)&&await r().catch(()=>{}),await(e.save??de)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},UC=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await VD(e,t):e.includes("--release-tray")?await jD(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 YD}from"node:fs/promises";import{homedir as Ml,platform as ui}from"node:os";import{join as _t}from"node:path";import{basename as HC,dirname as Zf,join as Na}from"node:path";var zr="https://github.com/anyrayHQ/install/releases",$o="connect-v",Jf="release-assets.githubusercontent.com",Xf=".anyray",Mo="__anyray-refresh-desktop-helpers",qr=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",lr=(e,t=process.platform)=>({launcher:Na(e,"bin",qr(t)),binDir:Na(e,"bin"),versionsDir:Na(e,"versions"),lock:Na(e,"update.lock"),state:Na(e,"update-state.json")}),di=(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"}},zf=(e,t,n=process.platform)=>HC(e)===qr(n)&&HC(Zf(e))==="bin"?Zf(Zf(e)):Na(t,Xf);var qf=(e=ui(),t=Ml())=>e==="darwin"?[{id:cr,mechanism:"launch-agent",filePaths:[_t(t,"Library","LaunchAgents",`${cr}.plist`)]}]:e==="linux"?[{id:cr,mechanism:"xdg-autostart",filePaths:[_t(t,".config","autostart",`${cr}.desktop`)]}]:e==="win32"?[{id:cr,mechanism:"registry-run",filePaths:[],registryValues:[{key:"HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",value:cr},{key:"HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",value:cr}]}]:[],Bl=(e=ui(),t=Ml())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:Ll,paths:[_t(t,"Library","LaunchAgents",`${Ll}.plist`)],dataPaths:[_t(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=_t(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${ii}.timer`,paths:[_t(n,`${ii}.timer`),_t(n,`${ii}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:Hf,paths:[]}]:[]},GC=async e=>{try{return await YD(e),!0}catch{return!1}},Fl=async(e={})=>{let t=e.os??ui(),n=e.exists??GC;for(let r of Bl(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await _n(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},KC=async e=>{let t={suspected:!1,missingPaths:[],kinds:[],removed:!1};if(!e.binaryDurable||!e.schedulerEnabled||e.schedulerInstalled||e.trayManaged===!0)return t;let n=e.exists??GC;for(let r of Bl(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.removed=t.suspected&&e.schedulerInstalledOnce===!0,t},VC=e=>{let t=e.os??ui(),n=e.home??Ml(),r=e.binaryPath??Do(),o=e.arch??process.arch,a=lr(zf(r,n,t),t),s=qr(t);return{schema:"anyray.connect.security-exclusions/v1",connectVersion:e.connectVersion,platform:t,arch:o,binary:{path:r,...e.binarySha256?{sha256:e.binarySha256}:{}},services:Bl(t,n).map(i=>({kind:i.kind,title:i.title,supervisorName:i.supervisorName,unitPaths:i.paths,logPaths:i.dataPaths??[]})),optionalDesktopAutostart:qf(t,n),writePaths:[_t(a.versionsDir,"<version>",s),a.launcher,a.lock,a.state],network:{outboundHosts:[...e.gatewayHost?[e.gatewayHost]:[],"github.com",Jf],inboundListeners:[]},notes:["Match on binary.path and services[].supervisorName. Do not match on binary.sha256: connect self-updates, so a hash-scoped exclusion stops matching at the next release.","The scheduler is unprivileged and runs as the logged-in user. It renews the seat gateway key so a long AI-coding session does not lose access.","A seat whose key cannot lapse between sessions installs no scheduler at all, and connect retires one it no longer needs.","No inbound listener, no proxy, no CA certificate, no DNS change."]}},jC=(e=ui(),t=Ml(),n=Do(),r=process.arch)=>{let o=lr(zf(n,t,e),e),a=qr(e),s=di(e,r),i=s?[` ${zr}/download/${$o}<version>/${s}`]:[" (no binary is published for this OS/architecture \u2014 nothing here"," downloads a release asset)"],c=["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 l of Bl(e,t)){c.push(`${l.title} \u2014 supervisor name: ${l.supervisorName}`);for(let d of l.paths)c.push(` ${d}`);l.paths.length===0&&c.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let d of l.dataPaths??[])c.push(` ${d} (captured stdout/stderr \u2014 setup progress and error names, including this seat's enrollment email; never credentials or prompt/response content)`);c.push("")}c.push("Optional signed desktop app autostart (not required or health-checked by","the CLI scheduler):");for(let l of qf(e,t)){c.push(` ${l.id} \u2014 ${l.mechanism}`);for(let d of l.filePaths)c.push(` ${d}`);for(let d of l.registryValues??[])c.push(` ${d.key} :: ${d.value}`)}return qf(e,t).length===0&&c.push(" (not supported on this OS)"),c.push(""),c.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."," - Outbound: github.com, for the self-update below. Asset downloads",` redirect to ${Jf}.`," - No inbound listener, no proxy, no CA certificate, no DNS change.","","Self-update:"," The installed binary keeps itself on the published version, on the same"," tick as key renewal. Every file it downloads is SHA-256 verified against"," the release's published SHA256SUMS before anything is activated; a"," mismatch is deleted and the running version stays.",""," Fetches over HTTPS, unauthenticated, no request body:",` ${zr}/latest`," (the redirect target alone names the published version)",` ${zr}/download/${$o}<version>/connect-update.json`,` ${zr}/download/${$o}<version>/SHA256SUMS`,...i,""," Writes:",` ${_t(o.versionsDir,"<version>",a)}`," (the downloaded binary; the version it replaces is kept for rollback)",` ${o.launcher}`," (the stable path above, pointed at the new version)",` ${o.lock}`,` ${o.state}`,` ${_t(o.versionsDir,"<version>",`${a}.part-<pid>`)}`,...e==="win32"?[` ${_t(o.binDir,`${a}.old-<pid>`)}`,` ${_t(o.binDir,`${a}.rollback-<pid>`)}`]:[` ${_t(o.binDir,`${a}.new-<pid>`)}`]," (transient: a partial download and the staged swap, removed as the"," swap completes or on the next run)",...e==="win32"?[""," Windows cannot overwrite a running .exe, so activation renames the"," live copy aside, copies the new one into place, and records the",` active version in \`${a}.source\` beside it.`]:[],""," Runs the newly downloaded binary directly, around the swap:"," - `--version`, as a smoke test when it replaces a non-managed runtime;"," a failure puts the previous version back.",` - \`anyray-connect ${Mo}\`, which rewrites an`," already-installed Anyray credential-helper script to name the new"," path. It writes nothing where no such helper exists.","","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."),c};import{homedir as dL}from"node:os";import{join as Zl}from"node:path";import{chmod as uL,readFile as Ma,rm as eA,copyFile as pL}from"node:fs/promises";import{parse as ZD}from"smol-toml";var dr="# >>> anyray connect >>>",$a="# <<< anyray connect <<<",Qf="# restore: ",YC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ul=e=>{let t=new RegExp(`\\n*${YC(dr)}[\\s\\S]*?${YC($a)}\\n?`,"g");return JC(e.replace(t,""))},JD="model_provider",XD="anyray",zD=new RegExp(`^\\s*(["'])${XD}\\1\\s*(#.*)?$`),qD=(e,t)=>t===JD&&zD.test(e.slice(e.indexOf("=")+1)),JC=e=>{let t=e.indexOf(dr);if(t<0||e.indexOf($a,t+dr.length)>=0)return e;let n=e.slice(0,t),r=e.slice(t).split(`
|
|
54
|
+
`),o=Bo(r),a=1;for(;a<r.length;){let s=o[a];if(s.kind==="table"||s.kind==="key"&&!qD(r[a],s.key))break;a+=1}for(;a>1&&r[a-1].trim()==="";)a-=1;return`${n.replace(/\n+$/,`
|
|
55
55
|
`)}${r.slice(a).join(`
|
|
56
|
-
`)}`},em=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},Wl=(e,t)=>e.split(t).length-1,ZC=e=>Wl(e,"[")-Wl(e,"]"),QD=e=>e.replace(/^['"]|['"]$/g,""),
|
|
56
|
+
`)}`},em=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},Wl=(e,t)=>e.split(t).length-1,ZC=e=>Wl(e,"[")-Wl(e,"]"),QD=e=>e.replace(/^['"]|['"]$/g,""),Bo=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Wl(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+ZC(em(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?QD(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=em(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Wl(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+ZC(l)))}return t},tm=e=>e.findIndex(t=>t.kind==="table"),Hl=e=>e.includes(dr),nm=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
57
57
|
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},eL=new Map([["model_providers.anyray",'name = "Anyray Gateway"'],["mcp_servers.anyray","anyray-connect"]]),tL=(e,t)=>{let n=eL.get(t);if(n===void 0)return!1;let r=e.split(`
|
|
58
|
-
`),o=
|
|
59
|
-
`),r=
|
|
58
|
+
`),o=Bo(r),a=!1;for(let s=0;s<r.length;s++){if(o[s].kind==="table"){a=XC(r[s])===t;continue}if(a&&r[s].includes(n))return!0}return!1},Gl=(e,t)=>nm(e,t)?nm(Ul(e),t)?Hl(e)&&!e.includes($a)&&tL(e,t)?"orphaned":"foreign":"managed":"absent",Kl=(e,t)=>{let n=e.split(`
|
|
59
|
+
`),r=Bo(n),o=i=>{let c=XC(i);return c===t||(c?.startsWith(`${t}.`)??!1)},a=[],s=!1;for(let i=0;i<n.length;i++)r[i].kind==="table"&&(s=o(n[i])),s||a.push(n[i]);return a.join(`
|
|
60
60
|
`).replace(/\n{3,}/g,`
|
|
61
61
|
|
|
62
|
-
`)},XC=e=>{let t=e.trim();if(!t.startsWith("[")||t.startsWith("[["))return;let n=t.indexOf("]");if(n<0)return;let r=t.slice(n+1).trimStart();if(!(r!==""&&!r.startsWith("#")))return t.slice(1,n).trim()},rm=e=>{let t=e.indexOf(dr);if(t<0)return;let n=e.indexOf(
|
|
63
|
-
`),o=
|
|
64
|
-
`),s=
|
|
62
|
+
`)},XC=e=>{let t=e.trim();if(!t.startsWith("[")||t.startsWith("[["))return;let n=t.indexOf("]");if(n<0)return;let r=t.slice(n+1).trimStart();if(!(r!==""&&!r.startsWith("#")))return t.slice(1,n).trim()},rm=e=>{let t=e.indexOf(dr);if(t<0)return;let n=e.indexOf($a,t+dr.length);if(n>=0)return e.slice(t,n);let r=e.slice(t);return r.slice(0,r.length-JC(r).length)},zC=(e,t)=>{let n=e.indexOf(dr);if(n<0)return!1;let r=e.indexOf($a,n+dr.length);return r<0?!1:nm(e.slice(n,r),t)},om=(e,t)=>{let r=Ul(e).split(`
|
|
63
|
+
`),o=Bo(r),a=tm(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=em(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}},Vl=(e,t,n)=>{let r=qC(e),a=Ul(e).split(`
|
|
64
|
+
`),s=Bo(a),i=tm(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=Bo(d),m=tm(p),f=(m===-1?d:d.slice(0,m)).join(`
|
|
65
65
|
`),h=m===-1?"":d.slice(m).join(`
|
|
66
|
-
`),w=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${Qf}${b}`),y=[dr,...w,...t
|
|
66
|
+
`),w=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${Qf}${b}`),y=[dr,...w,...t,$a].join(`
|
|
67
67
|
`);return[f.replace(/\s*$/,""),y,h.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
|
|
68
68
|
|
|
69
69
|
`).replace(/\s*$/,"")+`
|
|
70
70
|
`},qC=e=>{let t=new Map,n=rm(e);if(n===void 0)return t;for(let r of n.split(`
|
|
71
|
-
`)){let o=r.trim();if(!o.startsWith(Qf))continue;let a=o.slice(Qf.length).trim(),[s]=
|
|
71
|
+
`)){let o=r.trim();if(!o.startsWith(Qf))continue;let a=o.slice(Qf.length).trim(),[s]=Bo([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},jl=e=>{if(!Hl(e))return null;let t=[...qC(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Ul(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
|
|
72
72
|
`),n].filter(a=>a.length>0).join(`
|
|
73
73
|
|
|
74
74
|
`);return o.length>0?o+`
|
|
75
|
-
`:""},QC=e=>{if(e.trim().length===0)return!0;try{return ZD(e),!0}catch{return!1}};import{randomUUID as nL}from"node:crypto";import{chmod as rL,mkdir as oL,rm as aL,writeFile as sL}from"node:fs/promises";import{dirname as iL}from"node:path";var Se=async(e,t)=>{await oL(iL(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${nL()}`;try{await sL(n,t,{flag:"wx",mode:384}),await Ae(n,e),await rL(e,384)}finally{await aL(n,{force:!0}).catch(()=>{})}};import{homedir as cL}from"node:os";import{join as lL}from"node:path";var jt=()=>lL(cL(),".agents","skills");var fL="codex",mL="Codex app / CLI / IDE",hL="https://chatgpt.com/backend-api/codex",yL="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",gL="x-anyray-client-context-window",wL="x-anyray-client-auto-compact-limit",Jl=()=>process.env.CODEX_HOME?.trim()||Zl(dL(),".codex"),pr=()=>Zl(Jl(),"config.toml"),Yl=()=>`${pr()}.anyray-bak`,am=()=>Zl(Jl(),"hooks.json"),ur=()=>Zl(Jl(),"anyray.config.toml"),tA=e=>_a(e,"PostToolUse",oC),nA=(e,t=!1)=>be({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||fL,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||mL}),pt=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,sm=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,pi=(e,t={})=>{let n=nA(e,t.ignoreEnv),r=ae(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:sm(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${pt(hL)}`,`"x-anyray-forward-headers" = ${pt(yL)}`,...i?[`"x-anyray-api-key" = ${pt(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${pt(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${pt(n)}`),a&&c.push(`"x-anyray-provider" = ${pt(a)}`),t.modelContextWindow&&c.push(`"${gL}" = ${pt(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${wL}" = ${pt(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 = ${pt(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${pt(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${pt(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>pt(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${pt(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(pt).join(", ")}]`]:[]]},bL=["model_providers.anyray","mcp_servers.anyray"],CL=()=>sm()?["model_provider","model"]:["model_provider"],rA={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,skillsDir(){return jt()},async syncOrgMcp({entry:e}){let t=pr(),n=await R(t)?await $a(t,"utf-8"):"",{text:r,outcome:o}=EC(n,e);return o!=="changed"?{changed:!1}:!n&&e===void 0?{changed:!1}:(await Se(t,r),{changed:!0})},async detect(){let e=Jl(),t=await R(e);return{installed:t,detail:t?pr():`no ${e} directory`}},async apply(e,t){let n=pr(),r=am(),o=nA(e),a=ae(e,"openai"),s=sm(),i=te(),c={},l=await R(r);try{l&&(c=await F(r))}catch(I){return{status:"manual",refused:!0,messages:[`Could not inspect the Codex hooks file ${r} (${I instanceof Error?I.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=tA(c),u=[],p=[];d?(t.dryRun||(await q(r,c,{backup:!1}),await pe(r)),u.push(r),p.push(`Removed the retired Anyray Codex PostToolUse hook from ${r}; Codex does not expose a safe pre-transcript replacement seam for side-effecting tools.`)):p.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.");let m=await R(n),f=m?await $a(n,"utf-8"):"";if(!QC(f))return{status:"manual",refused:!0,...u.length>0?{changedFiles:u}:{},messages:[`Could not parse ${n} as TOML, so routing was left unchanged \u2014 writing the Anyray block into it would leave the file just as unreadable to Codex. Repair the file and re-run Connect.`,...p]};let h=Gl(f,"model_providers.anyray");if(h==="foreign")return{status:"manual",refused:!0,...u.length>0?{changedFiles:u}:{},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.`,...p]};let w=Gl(f,"mcp_servers.anyray"),y=w==="foreign",g=om(f,"model_context_window"),b=om(f,"model_auto_compact_token_limit"),k=[`${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.",b?`Context budget: follows model_auto_compact_token_limit=${b}.`:g?`Context budget: follows model_context_window=${g}.`:"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 k.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:k};let A=[...u];k.push(...p),m&&!await R(Yl())&&(await pL(n,Yl()),await uL(Yl(),384),k.push(`Backed up your original config to ${Yl()}.`));let E=i&&!y?We("profile"):void 0;k.push(y?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:E?"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 (${De()}). Re-run via the installer or a global install to enable retrieval.`);let O=f;h==="orphaned"&&(O=Kl(O,"model_providers.anyray"),k.push(`Repaired the Anyray block in ${n}: its end marker was missing and model_providers.anyray had been moved out of it, so routing was re-anchored. Codex rewrites this file itself, which is how the marker goes missing.`)),w==="orphaned"&&(O=Kl(O,"mcp_servers.anyray"));let S=Vl(O,pi(e,{mcpServer:E,modelContextWindow:g,modelAutoCompactTokenLimit:b}),CL());return await Se(n,S),A.push(n),await R(ur())&&(await eA(ur(),{force:!0}),A.push(ur()),k.push(`Removed the old opt-in profile ${ur()} (the default route replaces it).`)),{status:"configured",messages:k,changedFiles:A,...y?{errorClass:"mcp_foreign"}:{}}},async pointsAt(e){let t=pr();if(!await R(t))return!1;try{let n=await $a(t,"utf-8"),r=`base_url = ${pt(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async configuredKeyIsCurrent(e){return Vt([pr()],e)},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=pr();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await $a(e,"utf-8");if(!zC(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 $a(pr(),"utf-8"),t=rm(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=pr(),n=await R(t),r=await R(ur()),o=await R(am());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=am(),c;try{c=await F(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.`]}}tA(c)&&(e.dryRun||(await q(i,c,{backup:!1}),await pe(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=await $a(t,"utf-8"),c=bL.reduce((d,u)=>Gl(d,u)==="orphaned"?Kl(d,u):d,i),l=jl(c)??(c===i?null:c);l!==null&&(e.dryRun||await Se(t,l),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 eA(ur(),{force:!0}),s.push(ur()),a.push(e.dryRun?`would remove the old opt-in profile ${ur()}`:`removed the old opt-in profile ${ur()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await pe(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as RL}from"node:os";import{join as OL}from"node:path";import{readFile as iA,rm as cm}from"node:fs/promises";import{readFile as AL,writeFile as oA,access as kL}from"node:fs/promises";import{homedir as vL}from"node:os";import{join as im}from"node:path";var SL="# >>> anyray connect >>>",IL="# <<< anyray connect <<<",fi=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:SL,end:IL},ft=()=>{let e=vL(),t=process.env.SHELL||"";return t.includes("zsh")?im(e,".zshrc"):t.includes("bash")?im(e,".bashrc"):im(e,".profile")},Xl=async e=>{try{return await kL(e),await AL(e,"utf-8")}catch{return""}},EL=/^export\s+(ANTHROPIC_(BASE_URL|AUTH_TOKEN|API_KEY|MODEL|DEFAULT_[A-Z_]+)|OPENAI_(BASE_URL|API_KEY)|ANYRAY_[A-Z0-9_]+)=/,xL=(e,t,n=[])=>{let{begin:r,end:o}=fi(t),a=e.indexOf(r);if(a===-1)return e;let s=e.indexOf(o,a+r.length),i=e.indexOf(r,a+r.length);i!==-1&&(s===-1||i<s)&&(s=-1);let c=a;for(;c>0&&e[c-1]===`
|
|
75
|
+
`:""},QC=e=>{if(e.trim().length===0)return!0;try{return ZD(e),!0}catch{return!1}};import{randomUUID as nL}from"node:crypto";import{chmod as rL,mkdir as oL,rm as aL,writeFile as sL}from"node:fs/promises";import{dirname as iL}from"node:path";var Se=async(e,t)=>{await oL(iL(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${nL()}`;try{await sL(n,t,{flag:"wx",mode:384}),await Ae(n,e),await rL(e,384)}finally{await aL(n,{force:!0}).catch(()=>{})}};import{homedir as cL}from"node:os";import{join as lL}from"node:path";var jt=()=>lL(cL(),".agents","skills");var fL="codex",mL="Codex app / CLI / IDE",hL="https://chatgpt.com/backend-api/codex",yL="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",gL="x-anyray-client-context-window",wL="x-anyray-client-auto-compact-limit",Jl=()=>process.env.CODEX_HOME?.trim()||Zl(dL(),".codex"),pr=()=>Zl(Jl(),"config.toml"),Yl=()=>`${pr()}.anyray-bak`,am=()=>Zl(Jl(),"hooks.json"),ur=()=>Zl(Jl(),"anyray.config.toml"),tA=e=>Ta(e,"PostToolUse",oC),nA=(e,t=!1)=>be({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||fL,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||mL}),pt=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,sm=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,pi=(e,t={})=>{let n=nA(e,t.ignoreEnv),r=ae(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:sm(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${pt(hL)}`,`"x-anyray-forward-headers" = ${pt(yL)}`,...i?[`"x-anyray-api-key" = ${pt(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${pt(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${pt(n)}`),a&&c.push(`"x-anyray-provider" = ${pt(a)}`),t.modelContextWindow&&c.push(`"${gL}" = ${pt(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${wL}" = ${pt(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 = ${pt(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${pt(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${pt(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>pt(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${pt(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(pt).join(", ")}]`]:[]]},bL=["model_providers.anyray","mcp_servers.anyray"],CL=()=>sm()?["model_provider","model"]:["model_provider"],rA={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,skillsDir(){return jt()},async syncOrgMcp({entry:e}){let t=pr(),n=await R(t)?await Ma(t,"utf-8"):"",{text:r,outcome:o}=EC(n,e);return o!=="changed"?{changed:!1}:!n&&e===void 0?{changed:!1}:(await Se(t,r),{changed:!0})},async detect(){let e=Jl(),t=await R(e);return{installed:t,detail:t?pr():`no ${e} directory`}},async apply(e,t){let n=pr(),r=am(),o=nA(e),a=ae(e,"openai"),s=sm(),i=te(),c={},l=await R(r);try{l&&(c=await F(r))}catch(E){return{status:"manual",refused:!0,messages:[`Could not inspect the Codex hooks file ${r} (${E instanceof Error?E.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=tA(c),u=[],p=[];d?(t.dryRun||(await q(r,c,{backup:!1}),await pe(r)),u.push(r),p.push(`Removed the retired Anyray Codex PostToolUse hook from ${r}; Codex does not expose a safe pre-transcript replacement seam for side-effecting tools.`)):p.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.");let m=await R(n),f=m?await Ma(n,"utf-8"):"";if(!QC(f))return{status:"manual",refused:!0,...u.length>0?{changedFiles:u}:{},messages:[`Could not parse ${n} as TOML, so routing was left unchanged \u2014 writing the Anyray block into it would leave the file just as unreadable to Codex. Repair the file and re-run Connect.`,...p]};let h=Gl(f,"model_providers.anyray");if(h==="foreign")return{status:"manual",refused:!0,...u.length>0?{changedFiles:u}:{},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.`,...p]};let w=Gl(f,"mcp_servers.anyray"),y=w==="foreign",g=om(f,"model_context_window"),b=om(f,"model_auto_compact_token_limit"),k=[`${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.",b?`Context budget: follows model_auto_compact_token_limit=${b}.`:g?`Context budget: follows model_context_window=${g}.`:"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 k.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:k};let A=[...u];k.push(...p),m&&!await R(Yl())&&(await pL(n,Yl()),await uL(Yl(),384),k.push(`Backed up your original config to ${Yl()}.`));let x=i&&!y?We("profile"):void 0,_=i&&e.clientKey?_o("print-key"):void 0;k.push(y?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:x?"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 (${De()}). Re-run via the installer or a global install to enable retrieval.`);let S=f;h==="orphaned"&&(S=Kl(S,"model_providers.anyray"),k.push(`Repaired the Anyray block in ${n}: its end marker was missing and model_providers.anyray had been moved out of it, so routing was re-anchored. Codex rewrites this file itself, which is how the marker goes missing.`)),w==="orphaned"&&(S=Kl(S,"mcp_servers.anyray"));let I=Vl(S,pi(e,{mcpServer:x,modelContextWindow:g,modelAutoCompactTokenLimit:b,..._?{auth:"command",authCommand:_.command,authArgs:_.args}:{}}),CL());return await Se(n,I),A.push(n),await R(ur())&&(await eA(ur(),{force:!0}),A.push(ur()),k.push(`Removed the old opt-in profile ${ur()} (the default route replaces it).`)),{status:"configured",messages:k,changedFiles:A,...y?{errorClass:"mcp_foreign"}:{}}},async pointsAt(e){let t=pr();if(!await R(t))return!1;try{let n=await Ma(t,"utf-8"),r=`base_url = ${pt(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async configuredKeyIsCurrent(e){return Vt([pr()],e)},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=pr();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await Ma(e,"utf-8");if(!zC(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 Ma(pr(),"utf-8"),t=rm(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=pr(),n=await R(t),r=await R(ur()),o=await R(am());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=am(),c;try{c=await F(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.`]}}tA(c)&&(e.dryRun||(await q(i,c,{backup:!1}),await pe(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=await Ma(t,"utf-8"),c=bL.reduce((d,u)=>Gl(d,u)==="orphaned"?Kl(d,u):d,i),l=jl(c)??(c===i?null:c);l!==null&&(e.dryRun||await Se(t,l),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 eA(ur(),{force:!0}),s.push(ur()),a.push(e.dryRun?`would remove the old opt-in profile ${ur()}`:`removed the old opt-in profile ${ur()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await pe(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as RL}from"node:os";import{join as OL}from"node:path";import{readFile as iA,rm as cm}from"node:fs/promises";import{readFile as AL,writeFile as oA,access as kL}from"node:fs/promises";import{homedir as vL}from"node:os";import{join as im}from"node:path";var SL="# >>> anyray connect >>>",IL="# <<< anyray connect <<<",fi=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:SL,end:IL},ft=()=>{let e=vL(),t=process.env.SHELL||"";return t.includes("zsh")?im(e,".zshrc"):t.includes("bash")?im(e,".bashrc"):im(e,".profile")},Xl=async e=>{try{return await kL(e),await AL(e,"utf-8")}catch{return""}},EL=/^export\s+(ANTHROPIC_(BASE_URL|AUTH_TOKEN|API_KEY|MODEL|DEFAULT_[A-Z_]+)|OPENAI_(BASE_URL|API_KEY)|ANYRAY_[A-Z0-9_]+)=/,xL=(e,t,n=[])=>{let{begin:r,end:o}=fi(t),a=e.indexOf(r);if(a===-1)return e;let s=e.indexOf(o,a+r.length),i=e.indexOf(r,a+r.length);i!==-1&&(s===-1||i<s)&&(s=-1);let c=a;for(;c>0&&e[c-1]===`
|
|
76
76
|
`;)c-=1;if(s===-1){let d=new Set(n.map(h=>h.trim())),u=e.slice(c).split(`
|
|
77
77
|
`),p=0;for(;p<u.length;){let h=u[p].trim(),w=h===""||h.startsWith("#")||d.has(h)||EL.test(h);if(p>0&&!w)break;p+=1}let m=e.slice(0,c),f=u.slice(p).join(`
|
|
78
78
|
`);return m.length===0||f.length===0?m+f:`${m}
|
|
@@ -85,17 +85,17 @@ ${i}
|
|
|
85
85
|
`;return await oA(e,c),e},mi=async(e,t)=>{let n=await Xl(e),{begin:r,end:o}=fi(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(`
|
|
86
86
|
`).filter(c=>c.trim().length>0)},sA=async(e,t)=>(await Xl(e)).includes(fi(t).begin),hi=async(e,t)=>{let n=await Xl(e);return n.includes(fi(t).begin)?(await oA(e,aA(n,t).replace(/\s*$/,"")+`
|
|
87
87
|
`),!0):!1};var Yt=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 $e=e=>`'${e.replace(/'/g,"'\\''")}'`,_L=e=>{let t=$e(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},cA=(e,t,n,r)=>[`export OPENAI_BASE_URL=${$e(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${$e(t)}`],`export ANTHROPIC_BASE_URL=${$e(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${$e(t)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]],TL=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],PL=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],lm=()=>OL(RL(),".anyray","shell-env.sh"),uA="# Managed by anyray-connect. Do not source this file anywhere else.",lA=e=>e.split(/\r?\n/,1)[0]===uA,dm=e=>PL.some(t=>e.startsWith(`export ${t}=`)),dA=(e,t)=>{let n=`export ${t}=`,r=e.find(a=>a.startsWith(n));if(!r)return;let o=r.slice(n.length).trim();return o.length>=2&&o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1).replace(/'\\''/g,"'"):o},ql=(e,t=process.env)=>t.ANTHROPIC_BASE_URL===e.anthropicBaseUrl||t.OPENAI_BASE_URL===e.openaiBaseUrl?TL.filter(r=>(t[r]??"")!==""):[],pA={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=ft();return{installed:!0,detail:await R(e)?e:`${e} (will be created)`}},async pointsAt(e){try{let t=await mi(ft());if(!t)return!1;let n=ct(e),r=dA(t,"OPENAI_BASE_URL"),o=dA(t,"ANTHROPIC_BASE_URL");return r!==void 0&&o!==void 0&&ct(r)===n&&ct(o)===n}catch{return!1}},async configuredKeyIsCurrent(e){let t=ft();return t?Vt([t],e):null},async routingExpected(e){return e.includes("shell-env")},async inferenceAuthLanes(){try{let e=await mi(ft());return e?e.some(n=>dm(n)||n.includes(lm()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=ft(),r=ae(e,"openai"),o=ae(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=cA(e,s,r,o),c=i.filter(dm),l=i.filter(b=>!dm(b)),d=lm(),u=yl(),p=[_L(u),...l,...c.length>0?[`[ -r ${$e(d)} ] && . ${$e(d)}`]:[]],m=e.clientKey?cA(e,Yt(e.clientKey),r,o):i,f=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)`,...m.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 ${f} \u2014 your seat-based tool keeps`,"its own sign-in (a placeholder here would override it). Raw SDK/script","calls on a seat need your own key."]:["Note: standard SDK env vars carry no per-user header, so attribution","for these falls back to the gateway default."]],w=await R(d),y=w?await iA(d,"utf8"):void 0,g=y===void 0||lA(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 Se(d,[uA,...c,""].join(`
|
|
88
|
-
`)):w&&g&&await cm(d,{force:!0}),await zl(n,p)}catch(b){try{y!==void 0&&g?await Se(d,y):g&&await cm(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=ft(),n=lm(),r=await R(n),o=r?lA(await iA(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 hi(t);o&&await cm(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 gN}from"node:child_process";import{closeSync as wN,copyFileSync as bN,existsSync as Le,mkdirSync as CN,openSync as AN,readFileSync as ZA,readSync as kN,renameSync as vN,rmSync as Dn,writeFileSync as Im}from"node:fs";import{homedir as JA,platform as SN}from"node:os";import{dirname as XA,join as
|
|
88
|
+
`)):w&&g&&await cm(d,{force:!0}),await zl(n,p)}catch(b){try{y!==void 0&&g?await Se(d,y):g&&await cm(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=ft(),n=lm(),r=await R(n),o=r?lA(await iA(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 hi(t);o&&await cm(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 gN}from"node:child_process";import{closeSync as wN,copyFileSync as bN,existsSync as Le,mkdirSync as CN,openSync as AN,readFileSync as ZA,readSync as kN,renameSync as vN,rmSync as Dn,writeFileSync as Im}from"node:fs";import{homedir as JA,platform as SN}from"node:os";import{dirname as XA,join as Ha,resolve as IN}from"node:path";import{isIP as bm}from"node:net";import{homedir as DL,platform as LL}from"node:os";import{join as Ql}from"node:path";var Ue=e=>{let t=DL();switch(LL()){case"darwin":return Ql(t,"Library","Application Support",e);case"win32":return Ql(process.env.APPDATA??Ql(t,"AppData","Roaming"),e);default:return Ql(t,".config",e)}};import{execFileSync as nd}from"node:child_process";import{mkdtempSync as NL,rmSync as $L,writeFileSync as ML}from"node:fs";import{createRequire as BL}from"node:module";import{tmpdir as FL}from"node:os";import{join as fA}from"node:path";var yi=class extends Error{},gi=e=>e instanceof yi?`: ${e.message}`:"",mA=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new yi("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new yi(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},hA=()=>{try{return nd("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},pm=64*1024*1024,WL=pm*2+64,td=e=>`'${e.replace(/'/g,"''")}'`,UL=(e,t)=>nd("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:WL,stdio:["ignore","pipe","pipe"]}),HL=(e,t)=>nd("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:pm,stdio:["pipe","pipe","pipe"]}),yA=(e,t,n=UL)=>{let r=td(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
|
|
89
89
|
`)?a.slice(0,-2):a.endsWith(`
|
|
90
90
|
`)?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")},gA=(e,t=HL)=>{let r=t(e,`.bail on
|
|
91
91
|
.timeout 5000
|
|
92
92
|
PRAGMA wal_checkpoint(TRUNCATE);
|
|
93
93
|
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");mA(o?.slice(1).map(Number))},GL=(e,t)=>{let n=NL(fA(FL(),"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=${td(a.key)};`;let i=fA(n,`value-${s}`);return ML(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${td(a.key)}, CAST(readfile(${td(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
|
|
94
|
-
`);nd("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:pm,stdio:["pipe","ignore","pipe"]})}finally{try{$L(n,{recursive:!0,force:!0})}catch{}}},KL={kind:"sqlite3-cli",readItem:(e,t)=>yA(e,t),checkpointWal:e=>gA(e),mutateRows:GL},VL=()=>{try{let t=BL(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},um=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},jL=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),YL=e=>({kind:"node-sqlite",readItem:(t,n)=>um(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:jL(o.value)}),checkpointWal:t=>um(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);mA(o)}),mutateRows:(t,n)=>um(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}})}),ed,Qr=()=>{if(ed!==void 0)return ed;let e=VL();return ed=e?YL(e):hA()?KL:null,ed};import{spawn as ZL}from"node:child_process";import{randomUUID as AA}from"node:crypto";import{constants as kA}from"node:fs";import{chmod as JL,copyFile as vA,mkdir as XL,readdir as zL,readFile as qL,rename as QL,rm as wi,writeFile as eN}from"node:fs/promises";import{join as mm}from"node:path";var hm=/^[a-z0-9][a-z0-9-]{0,31}$/,tN=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,SA=/^[a-z0-9][a-z0-9-]{0,31}$/,nN=/^[0-9TZ:.+-]{1,40}$/,ym=()=>mm(oe(),"pending"),
|
|
95
|
-
`,{mode:384}),await Ae(n,t)},xA=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,eo=async(e,t)=>await wm(e,t)==="claimed",wm=async(e,t)=>{let n=
|
|
96
|
-
`),ON=e=>{let t=IN(e);for(;;){if(Le(
|
|
94
|
+
`);nd("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:pm,stdio:["pipe","ignore","pipe"]})}finally{try{$L(n,{recursive:!0,force:!0})}catch{}}},KL={kind:"sqlite3-cli",readItem:(e,t)=>yA(e,t),checkpointWal:e=>gA(e),mutateRows:GL},VL=()=>{try{let t=BL(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},um=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},jL=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),YL=e=>({kind:"node-sqlite",readItem:(t,n)=>um(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:jL(o.value)}),checkpointWal:t=>um(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);mA(o)}),mutateRows:(t,n)=>um(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}})}),ed,Qr=()=>{if(ed!==void 0)return ed;let e=VL();return ed=e?YL(e):hA()?KL:null,ed};import{spawn as ZL}from"node:child_process";import{randomUUID as AA}from"node:crypto";import{constants as kA}from"node:fs";import{chmod as JL,copyFile as vA,mkdir as XL,readdir as zL,readFile as qL,rename as QL,rm as wi,writeFile as eN}from"node:fs/promises";import{join as mm}from"node:path";var hm=/^[a-z0-9][a-z0-9-]{0,31}$/,tN=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,SA=/^[a-z0-9][a-z0-9-]{0,31}$/,nN=/^[0-9TZ:.+-]{1,40}$/,ym=()=>mm(oe(),"pending"),Ba=e=>{if(!hm.test(e)||tN.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return mm(ym(),`${e}.json`)},IA=()=>mm(oe(),"cursor-pending.json"),rN=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),oN=(e,t)=>{if(!rN(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!hm.test(n)||typeof e.op!="string"||!SA.test(e.op)||typeof e.requestedAt!="string"||!nN.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}:{}}},gm=async(e,t)=>{try{return oN(JSON.parse(await qL(e,"utf-8")),t)}catch{return}},EA=async()=>{let e=IA(),t=await gm(e,"cursor");if(!t)return;let n=!1;try{await rd(),await vA(e,Ba("cursor"),kA.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await wi(e,{force:!0})}catch{}return t},Ci=async e=>{let t=await gm(Ba(e),e);return t||(e==="cursor"?EA():void 0)},Pn=async()=>{let e;try{e=await zL(ym())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!hm.test(r))continue;let o=await Ci(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await EA();n&&t.push(n)}return t},rd=async()=>{await lt();let e=ym();await XL(e,{recursive:!0,mode:448});try{await JL(e,448)}catch{}},bi=async e=>{await rd();let t=Ba(e.adapter),n=`${t}.${process.pid}.tmp`;await eN(n,`${JSON.stringify(e)}
|
|
95
|
+
`,{mode:384}),await Ae(n,t)},xA=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,eo=async(e,t)=>await wm(e,t)==="claimed",wm=async(e,t)=>{let n=Ba(e);if(t){let o=`${n}.${process.pid}.${AA()}.claimed`;try{await QL(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await gm(o,e);if(a&&xA(a,t))return await wi(o,{force:!0}),"claimed";let s=!1;try{await vA(o,n,kA.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await wi(o,{force:!0})}return"superseded"}let r=!1;try{await wi(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await wi(IA(),{force:!0})}catch{}return r?"claimed":"absent"},Tn=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},aN=e=>{let{command:t,args:n}=Jr("__anyray-quit-watch");return{exe:t,args:[...n,e]}},sN=e=>{let{exe:t,args:n}=aN(e),r=ZL(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},fm=sN;var RA=async()=>{let e=[],t;try{t=await Pn()}catch{return e}for(let n of t)if(!Tn(n.watcherPid))try{wA&&await wA(n),await iN(n)&&e.push(n.adapter)}catch{}return e},wA;var iN=async e=>{let t=Ba(e.adapter);await rd();let n=await dl(`${t}.lock`,{waitMs:OA,staleMs:_A,busyMessage:`pending operation queue for ${e.adapter} is busy; retry`});try{let r=await Ci(e.adapter);if(!r||!xA(r,e)||Tn(r.watcherPid))return!1;let o=fm(e.adapter);return o?(await bi({...r,watcherPid:o}),!0):!1}finally{await n()}},bA=(e,t)=>{let n=e.indexOf(t);return n===-1?e.length:n},cN=(e,t,n)=>e!==void 0&&(t.op===n||e.includes(t.op)&&bA(e,t.op)<=bA(e,n)),CA;var OA=2e3,_A=1e4,od=async(e,t,n={})=>{if(!SA.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let r=Ba(e);await rd();let o=await dl(`${r}.lock`,{waitMs:OA,staleMs:_A,busyMessage:`pending operation queue for ${e} is busy; retry`});try{return await lN(e,t,n.precedence)}finally{await o()}},lN=async(e,t,n)=>{let r=await Ci(e);if(CA&&await CA({adapter:e,op:t,existing:r}),r&&cN(n,r,t)){if(Tn(r.watcherPid))return{watcherPid:r.watcherPid,alreadyWatching:!0};let i;try{i=fm(e)}catch{i=void 0}return i&&await bi({...r,watcherPid:i}),{watcherPid:i,alreadyWatching:!1}}let o=new Date().toISOString(),a=AA();if(r&&Tn(r.watcherPid))return await bi({...r,adapter:e,op:t,requestedAt:o,generation:a}),{watcherPid:r.watcherPid,alreadyWatching:!0};await bi({version:1,adapter:e,op:t,requestedAt:o,generation:a});let s;try{s=fm(e)}catch{s=void 0}return s&&await bi({version:1,adapter:e,op:t,requestedAt:o,watcherPid:s,generation:a}),{watcherPid:s,alreadyWatching:!1}};import{spawn as dN,spawnSync as PA}from"node:child_process";import{existsSync as ad}from"node:fs";import{homedir as uN,platform as to}from"node:os";import{join as DA,win32 as TA}from"node:path";var LA=(e,t={})=>{let n=t.env??process.env,r=t.exists??ad,o=(t.home??uN)(),a={localAppData:n.LOCALAPPDATA??TA.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=TA.join(i,s.path);if(r(c))return c}},Fo=/^[A-Za-z0-9 ._-]{1,64}$/,pN=/^[A-Za-z0-9.-]{1,128}$/,sd=e=>e.darwinBundleId&&pN.test(e.darwinBundleId)?e.darwinBundleId:void 0,NA=(e,t=to())=>t==="darwin"?sd(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",$A=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",MA=(e,t=to(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return LA(e,r)!==void 0;let o=e.linuxProcess;return!o||!Fo.test(o)?!1:n.split(":").filter(Boolean).some(a=>ad(DA(a,o)))},BA=(e,t=to())=>{if(t==="darwin"&&sd(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Fo.test(n))},FA=1e4,Ai=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=DA(t,"System32",e);return ad(n)?n:e},fN=e=>{let t=`/usr/bin/${e}`;return ad(t)?t:e},mN=(e,t)=>{try{let n=PA(e,t,{encoding:"utf-8",timeout:FA,windowsHide:!0,...to()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:to()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},hN=e=>new Promise(t=>setTimeout(t,e)),WA=(e,t={})=>{let n=t.runtimePlatform??to(),r=t.run??mN;if(n==="darwin"){let a=sd(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||!Fo.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||!Fo.test(a)?!1:r(Ai("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Fo.test(o)?!1:r(fN("pkill"),["-TERM","-o","-x",o])},UA=async(e,t=2e4,n={})=>{let r=n.sleep??hN,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},yN=(e,t,n={})=>{let r=to();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=PA(e,t,{stdio:"ignore",timeout:FA,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=dN(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},HA=(e,t={})=>{let n=t.runtimePlatform??to(),r=t.launch??yN;if(n==="darwin"){let a=sd(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Fo.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=LA(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Fo.test(o)?!1:r(o,[])};var EN={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"}]},xN=e=>e==="apply"||e==="native"||e==="revert",zA=()=>Ue("Cursor"),no=()=>Ha(zA(),"User","globalStorage","state.vscdb"),vi=()=>`${no()}.anyray-bak.json`,Ua=()=>`${no()}.anyray-bak`,ze="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",ht="cursorAuth/openAIKey";var qA="/seat/cursor",Em="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.",ki=Ha(".cursor","rules","anyray.mdc"),QA="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",RN=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",QA,"",Em,""].join(`
|
|
96
|
+
`),ON=e=>{let t=IN(e);for(;;){if(Le(Ha(t,".git")))return t;let n=XA(t);if(n===t)return null;t=n}},_N=e=>e.authMode!=="placeholder",Ln=()=>Ha(JA(),".cursor","hooks.json"),un=()=>Ha(JA(),".cursor","mcp.json"),Zt="anyray",ek="--anyray-owner=cursor-v1",TN="postToolUse",PN="beforeSubmitPrompt",GA="preToolUse",DN="^MCP:",LN="UserPromptSubmit",NN="Shell",$N="^(Read|Grep)$",ud="--anyray-owner=cursor-hook-v1",Wo=[{event:TN,flag:nt,trailingArgs:["cursor"],matcher:DN},{event:PN,flag:Gr,trailingArgs:[],matcher:LN},{event:GA,flag:aC,trailingArgs:[],matcher:NN},{event:GA,flag:sC,trailingArgs:[],matcher:$N}];var KA={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},MN=(e,t,n)=>gN(e,t,n),VA=MN,BN,FN=()=>{let e=BN??SN();if(e==="win32"){let t=VA(Ai("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],KA);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=VA("pgrep",["-x",t],KA);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},WN=FN,ld=()=>WN();var UN=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,ze)??null,openAIKey:e.readItem(n,ht)??null,lastWritten:r};Im(t,`${JSON.stringify(o,null,2)}
|
|
97
97
|
`,{encoding:"utf-8",flag:"wx",mode:384})},tk=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Im(n,`${JSON.stringify(t,null,2)}
|
|
98
|
-
`,{encoding:"utf-8",flag:"wx",mode:384});try{vN(n,e)}catch(r){throw Dn(n,{force:!0}),r}},HN=(e,t)=>{let n=Ba(e);tk(e,{...n,lastWritten:t})},ue=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jA=e=>ue(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Ba=e=>{let t=ZA(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(ue(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||ue(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(!ue(n)||n.version!==1||!ue(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[ze],o=n.rows[ht];if(!jA(r)||!jA(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}},YA=e=>{let t=Buffer.alloc(16),n=AN(e,"r");try{return kN(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{wN(n)}},GN=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return ue(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var nk=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(".")&&bm(t)===0||t==="0.0.0.0")return!0;if(bm(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(bm(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 nk(`${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},rk=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!nk(t.hostname)}catch{return!1}},KN=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${qA}`}catch{}return{...e,openaiBaseUrl:t}},Fa=["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."],Am=()=>{let e=no();if(!Le(e))return"clear";let t=Qr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,ze)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ue(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},VN=(e,t)=>{if(!rk(e))return{routed:!1,problem:"gateway-not-public-https"};let n=no();if(!Le(n))return{routed:!1,problem:"state-db-missing"};let r=Qr();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,ze),a=r.readItem(n,ht)}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(!ue(s))return{routed:!1,problem:"settings-malformed"};let i=`${ct(e)}/v1${qA}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Pe(a)||!Pe(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},jN=()=>{let e=no();if(!Le(e))return"unverifiable";let t=Qr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,ze)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!ue(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},YN=(e,t=[])=>({command:Ht(e,[...t,ud])}),xm=(e,t,n)=>{if(!ue(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Ht(t,[...n,ud])||r===Ht(t,n)||r.endsWith(` ${ud}`)&&r.includes(` ${t} `)},ZN=(e,t)=>ue(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),ok=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(xm(a,t,n)){r=!0;continue}if(!ue(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!ZN(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}},Rm=(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},ak=(e,t,n,r,o)=>ue(e.hooks)&&Rm(e.hooks,t).some(a=>ue(a)&&a.matcher===o&&xm(a,n,r)),JN=(e,t,n,r,o)=>ue(e.hooks)&&Rm(e.hooks,t).some(a=>ue(a)&&a.matcher===o&&xm(a,n,r)&&bl(a.command,n,[...r,ud])),sk=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!ue(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=ue(e.hooks)?{...e.hooks}:{},{entries:s}=ok(Rm(a,t),n,r);return s.push({...YN(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},XN=(e,t,n,r=[])=>{if(!ue(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=ok(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},zN=async()=>{let e=Ln();if(!te()){let t=await ck();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${De()}). 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 F(e);for(let n of Fo)t=sk(t,n.event,n.flag,n.trailingArgs,n.matcher);return await q(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}}},dd=()=>{let e=We("profile");return{command:e.command,args:[...e.args,ek]}},km=e=>ue(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===dd().command&&e.args.length===dd().args.length&&e.args.every((t,n)=>t===dd().args[n]),qN=e=>{if(!ue(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")||dt(e.command))return!1;let t=e.args;if(t.at(-2)!==Vr||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!dt(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},pd=e=>ue(e)&&Array.isArray(e.args)&&e.args.at(-1)===ek||qN(e),QN=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,e$=async()=>{if(!te())return ik();let e=un();try{let t=await F(e);if(t.mcpServers!==void 0&&!ue(t.mcpServers))throw new Error("mcpServers is not an object");let n=ue(t.mcpServers)?{...t.mcpServers}:{},r=n[Zt];return r!==void 0&&!pd(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Zt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Zt]=dd(),await q(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}}},ik=async()=>{let e=un();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e);if(!ue(t.mcpServers)||!(Zt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!pd(t.mcpServers[Zt]))return{changedFiles:[],messages:[`Preserved the foreign ${Zt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Zt];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await q(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}}},ck=async()=>{let e=Ln();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e),n=t;for(let r of Fo)n=XN(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await q(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}}},t$=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=ON(e);if(!n)return t;let r=Ua(n,ki),o=RN();try{if(Le(r)){let a=ZA(r,"utf8");if(a===o)return t;if(!a.includes(QA))return{...t,messages:[`Left ${ki} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Em}"`]}}return CN(XA(r),{recursive:!0}),Im(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${ki} 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 ${ki} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},lk=async()=>{let e=await zN(),t=await e$(),n=await t$();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},vm=async()=>{let e=await ck(),t=await ik();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},dk=async()=>{if(!te()){let e=await vm();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${De()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await F(Ln());for(let r of Fo)e=sk(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await F(un());if(t.mcpServers!==void 0&&!ue(t.mcpServers))throw new Error("mcpServers is not an object");let n=ue(t.mcpServers)?t.mcpServers[Zt]:void 0;return n!==void 0&&!pd(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${un()} already contains a foreign ${Zt} 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 ${Ln()} and ${un()}, then re-run Connect.`],complete:!1}}},n$=async()=>{if(!te())return!1;try{let e=await F(Ln());if(!ue(e.hooks)||!Fo.every(r=>ak(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await F(un()),n=ue(t.mcpServers)?t.mcpServers[Zt]:void 0;return km(n)}catch{return!1}},uk=["openAIBaseUrl","useOpenAIKey"],Si=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!ue(t))throw new Error("Cursor application-user settings are not an object");return t},r$=(e,t,n)=>{let r=Si(e),o=Si(t??void 0),a=n===void 0?void 0:Si(n),s={...r},i=[];for(let c of uk){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:ze}:{key:ze,value:JSON.stringify(s)},conflicts:i}},Cm=(e,t)=>{let n=Si(e),r=Si(t??void 0),o={...n};for(let a of uk)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:ze}:{key:ze,value:JSON.stringify(o)}},id=e=>typeof e=="string"&&e.startsWith("ark_"),cd=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ue(o)&&(n=o)}catch{}let r=id(t)||n!==null&&(id(n.useOpenAIKey)||id(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,id(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}},mt=(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.",...Fa];let n=be(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.",...Fa]},Sm=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 od("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]}},o$=async(e,t)=>{if(!Pe(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 eo("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 dk();if(!n.complete)return{status:"manual",messages:n.messages};let r=Le(vi())||Le(Wa());if(r&&ld())return Sm("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=Am();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 ${Le(Wa())?Wa():vi()}, 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 ${Ln()}, and register the Anyray retrieval MCP server in ${un()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Ii.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 lk(),s=[];if(!t.preservePendingOp)try{await eo("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 -- "${Em}" (connect already writes ${ki} 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."]}},Ii={id:"cursor",title:"Cursor",automatic:!0,skillsDir(){return jt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=un(),r=await F(n),o=xn(r,"mcpServers",e,t&&{url:t.url,headers:{[Kt]:t.clientKey}});return o==="changed"&&await q(n,r,{backup:!1}),{changed:o==="changed"}},quitGated:{isRunning:()=>ld(),quitTarget:EN,needsTarget:e=>e!=="revert",async complete(e,t,n){return xN(e)?e!=="revert"&&t?Ii.apply(t,n):Ii.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=zA(),t=Le(e);return{installed:t,detail:t?no():"Cursor user dir not found"}},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=un();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await F(e),n=ue(t.mcpServers)?t.mcpServers[Zt]:void 0;return km(n)?{registered:!0,command:QN(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=Ln();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!ue(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Fo.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Fo.every(c=>ak(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Fo.every(c=>JN(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=un();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!ue(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Zt];r=i===void 0?"missing":pd(i)?"owned":"foreign",r==="owned"&&(o=km(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await In()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await $();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(_N(e))return o$(e,t);let n=KN(e),r=no(),o=vi(),a=Wa();if(!Pe(e.clientKey))return{status:"manual",messages:mt(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(!rk(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.",...Fa]});let c=await dk();if(!c.complete)return{status:"manual",messages:c.messages};let l=Qr();if(!l)return i({status:"manual",messages:mt(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Le(r))return i({status:"manual",messages:mt(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Le(a)){if(Le(o))return i({status:"manual",messages:mt(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{YA(a)?d="sqlite":(Ba(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:mt(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(Le(o))try{p=Ba(o)}catch{return i({status:"manual",messages:mt(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(ld())return i(await Sm("apply",t,{status:"manual",messages:mt(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Fa,...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}, ${Le(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 ${Ln()}, and register the Anyray retrieval MCP server in ${un()}.`,...Fa]};if(d){try{l.checkpointWal(r)}catch(g){return i({status:"manual",messages:mt(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${gi(g)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=cd(l.readItem(a,ze)??null,l.readItem(a,ht)??null);else{let g=Ba(a);y=cd(g.applicationUser,g.openAIKey)}}catch{return i({status:"manual",messages:mt(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,[Cm(l.readItem(r,ze),y.applicationUser),y.openAIKey===null?{key:ht}:{key:ht,value:y.openAIKey}])}catch{return i({status:"manual",messages:mt(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{Dn(a,{force:!0}),Dn(`${a}-wal`,{force:!0}),Dn(`${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:mt(n,`Couldn't checkpoint Cursor's state DB at ${r}${gi(y)} \u2014 refusing to write; set it by hand:`)})}let m;try{m=l.readItem(r,ze)}catch{return i({status:"manual",messages:mt(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let f=GN(m,n);if(!f)return i({status:"manual",messages:mt(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let h={applicationUser:f.value,openAIKey:e.clientKey};if(Le(o))try{HN(o,h)}catch{return i({status:"manual",messages:mt(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{UN(l,o,r,h)}catch{return i({status:"manual",messages:mt(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:ze,value:f.value},{key:ht,value:e.clientKey}])}catch{let y=!0;if(p)try{tk(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 lk();let w=[];if(!t.preservePendingOp)try{await eo("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,...Fa,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await $().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Le(vi())||Le(Wa())||Am()!=="clear"?!1:n$():VN(e,n).routed},async routingOverrides(){return Am()!=="active"?[]:jN()!=="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=no(),n=vi(),r=Wa(),o=Le(n),a=Le(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 ${Ln()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${Ln()} and unregister its owned retrieval MCP server.`]};if((o||a)&&ld()){if(e.fullRevert){let f=await vm(),h=!0;try{await eo("cursor")}catch{h=!1}return{status:"manual",changedFiles:f.changedFiles,messages:[...f.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 Sm("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Qr(),i=!1,c=!1,l,d=[];if(a)try{if(YA(r))if(Le(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 f=cd(s.readItem(r,ze)??null,s.readItem(r,ht)??null);s.mutateRows(t,[Cm(s.readItem(t,ze),f.applicationUser),f.openAIKey===null?{key:ht}:{key:ht,value:f.openAIKey}]),c=!0}else i=!0,bN(r,t),Dn(`${t}-wal`,{force:!0}),Dn(`${t}-shm`,{force:!0});else{let f=Ba(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Le(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=cd(f.applicationUser,f.openAIKey);s.mutateRows(t,[Cm(s.readItem(t,ze),h.applicationUser),h.openAIKey===null?{key:ht}:{key:ht,value:h.openAIKey}]),c=!0}}catch(f){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${gi(f)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Ba(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(!Le(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 f=r$(s.readItem(t,ze),l.applicationUser,l.lastWritten?.applicationUser);d.push(...f.conflicts);let h=[f.mutation],w=s.readItem(t,ht);l.lastWritten&&w===l.lastWritten.openAIKey?h.push(l.openAIKey===null?{key:ht}:{key:ht,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,h)}catch(f){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${gi(f)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],p=!0;try{Dn(r,{force:!0}),Dn(`${r}-wal`,{force:!0}),Dn(`${r}-shm`,{force:!0}),Dn(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 eo("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let m=await vm();return p=p&&m.complete,{status:p?"reverted":"manual",changedFiles:[...o||a?[t]:[],...m.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(", ")}.`]:[],...m.messages,"Restart Cursor."]}}};import{chmod as iM,mkdir as cM,readFile as Jk,rm as lM,writeFile as dM}from"node:fs/promises";import{randomUUID as uM}from"node:crypto";import{dirname as pM,join as Xk}from"node:path";import{constants as i$,chmod as c$,copyFile as l$,readFile as pk}from"node:fs/promises";import{applyEdits as d$,modify as u$}from"jsonc-parser";var a$=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]!==`
|
|
98
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{vN(n,e)}catch(r){throw Dn(n,{force:!0}),r}},HN=(e,t)=>{let n=Fa(e);tk(e,{...n,lastWritten:t})},ue=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jA=e=>ue(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Fa=e=>{let t=ZA(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(ue(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||ue(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(!ue(n)||n.version!==1||!ue(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[ze],o=n.rows[ht];if(!jA(r)||!jA(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}},YA=e=>{let t=Buffer.alloc(16),n=AN(e,"r");try{return kN(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{wN(n)}},GN=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return ue(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var nk=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(".")&&bm(t)===0||t==="0.0.0.0")return!0;if(bm(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(bm(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 nk(`${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},rk=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!nk(t.hostname)}catch{return!1}},KN=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${qA}`}catch{}return{...e,openaiBaseUrl:t}},Wa=["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."],Am=()=>{let e=no();if(!Le(e))return"clear";let t=Qr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,ze)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ue(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},VN=(e,t)=>{if(!rk(e))return{routed:!1,problem:"gateway-not-public-https"};let n=no();if(!Le(n))return{routed:!1,problem:"state-db-missing"};let r=Qr();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,ze),a=r.readItem(n,ht)}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(!ue(s))return{routed:!1,problem:"settings-malformed"};let i=`${ct(e)}/v1${qA}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Pe(a)||!Pe(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},jN=()=>{let e=no();if(!Le(e))return"unverifiable";let t=Qr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,ze)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!ue(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},YN=(e,t=[])=>({command:Ht(e,[...t,ud])}),xm=(e,t,n)=>{if(!ue(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Ht(t,[...n,ud])||r===Ht(t,n)||r.endsWith(` ${ud}`)&&r.includes(` ${t} `)},ZN=(e,t)=>ue(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),ok=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(xm(a,t,n)){r=!0;continue}if(!ue(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!ZN(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}},Rm=(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},ak=(e,t,n,r,o)=>ue(e.hooks)&&Rm(e.hooks,t).some(a=>ue(a)&&a.matcher===o&&xm(a,n,r)),JN=(e,t,n,r,o)=>ue(e.hooks)&&Rm(e.hooks,t).some(a=>ue(a)&&a.matcher===o&&xm(a,n,r)&&bl(a.command,n,[...r,ud])),sk=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!ue(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=ue(e.hooks)?{...e.hooks}:{},{entries:s}=ok(Rm(a,t),n,r);return s.push({...YN(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},XN=(e,t,n,r=[])=>{if(!ue(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=ok(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},zN=async()=>{let e=Ln();if(!te()){let t=await ck();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${De()}). 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 F(e);for(let n of Wo)t=sk(t,n.event,n.flag,n.trailingArgs,n.matcher);return await q(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}}},dd=()=>{let e=We("profile");return{command:e.command,args:[...e.args,ek]}},km=e=>ue(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===dd().command&&e.args.length===dd().args.length&&e.args.every((t,n)=>t===dd().args[n]),qN=e=>{if(!ue(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")||dt(e.command))return!1;let t=e.args;if(t.at(-2)!==Vr||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!dt(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},pd=e=>ue(e)&&Array.isArray(e.args)&&e.args.at(-1)===ek||qN(e),QN=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,e$=async()=>{if(!te())return ik();let e=un();try{let t=await F(e);if(t.mcpServers!==void 0&&!ue(t.mcpServers))throw new Error("mcpServers is not an object");let n=ue(t.mcpServers)?{...t.mcpServers}:{},r=n[Zt];return r!==void 0&&!pd(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Zt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Zt]=dd(),await q(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}}},ik=async()=>{let e=un();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e);if(!ue(t.mcpServers)||!(Zt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!pd(t.mcpServers[Zt]))return{changedFiles:[],messages:[`Preserved the foreign ${Zt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Zt];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await q(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}}},ck=async()=>{let e=Ln();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e),n=t;for(let r of Wo)n=XN(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await q(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}}},t$=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=ON(e);if(!n)return t;let r=Ha(n,ki),o=RN();try{if(Le(r)){let a=ZA(r,"utf8");if(a===o)return t;if(!a.includes(QA))return{...t,messages:[`Left ${ki} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Em}"`]}}return CN(XA(r),{recursive:!0}),Im(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${ki} 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 ${ki} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},lk=async()=>{let e=await zN(),t=await e$(),n=await t$();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},vm=async()=>{let e=await ck(),t=await ik();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},dk=async()=>{if(!te()){let e=await vm();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${De()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await F(Ln());for(let r of Wo)e=sk(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await F(un());if(t.mcpServers!==void 0&&!ue(t.mcpServers))throw new Error("mcpServers is not an object");let n=ue(t.mcpServers)?t.mcpServers[Zt]:void 0;return n!==void 0&&!pd(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${un()} already contains a foreign ${Zt} 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 ${Ln()} and ${un()}, then re-run Connect.`],complete:!1}}},n$=async()=>{if(!te())return!1;try{let e=await F(Ln());if(!ue(e.hooks)||!Wo.every(r=>ak(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await F(un()),n=ue(t.mcpServers)?t.mcpServers[Zt]:void 0;return km(n)}catch{return!1}},uk=["openAIBaseUrl","useOpenAIKey"],Si=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!ue(t))throw new Error("Cursor application-user settings are not an object");return t},r$=(e,t,n)=>{let r=Si(e),o=Si(t??void 0),a=n===void 0?void 0:Si(n),s={...r},i=[];for(let c of uk){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:ze}:{key:ze,value:JSON.stringify(s)},conflicts:i}},Cm=(e,t)=>{let n=Si(e),r=Si(t??void 0),o={...n};for(let a of uk)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:ze}:{key:ze,value:JSON.stringify(o)}},id=e=>typeof e=="string"&&e.startsWith("ark_"),cd=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ue(o)&&(n=o)}catch{}let r=id(t)||n!==null&&(id(n.useOpenAIKey)||id(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,id(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}},mt=(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.",...Wa];let n=be(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.",...Wa]},Sm=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 od("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]}},o$=async(e,t)=>{if(!Pe(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 eo("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 dk();if(!n.complete)return{status:"manual",messages:n.messages};let r=Le(vi())||Le(Ua());if(r&&ld())return Sm("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=Am();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 ${Le(Ua())?Ua():vi()}, 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 ${Ln()}, and register the Anyray retrieval MCP server in ${un()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Ii.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 lk(),s=[];if(!t.preservePendingOp)try{await eo("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 -- "${Em}" (connect already writes ${ki} 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."]}},Ii={id:"cursor",title:"Cursor",automatic:!0,skillsDir(){return jt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=un(),r=await F(n),o=xn(r,"mcpServers",e,t&&{url:t.url,headers:{[Kt]:t.clientKey}});return o==="changed"&&await q(n,r,{backup:!1}),{changed:o==="changed"}},quitGated:{isRunning:()=>ld(),quitTarget:EN,needsTarget:e=>e!=="revert",async complete(e,t,n){return xN(e)?e!=="revert"&&t?Ii.apply(t,n):Ii.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=zA(),t=Le(e);return{installed:t,detail:t?no():"Cursor user dir not found"}},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=un();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await F(e),n=ue(t.mcpServers)?t.mcpServers[Zt]:void 0;return km(n)?{registered:!0,command:QN(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=Ln();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!ue(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Wo.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Wo.every(c=>ak(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Wo.every(c=>JN(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=un();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!ue(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Zt];r=i===void 0?"missing":pd(i)?"owned":"foreign",r==="owned"&&(o=km(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await In()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await $();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(_N(e))return o$(e,t);let n=KN(e),r=no(),o=vi(),a=Ua();if(!Pe(e.clientKey))return{status:"manual",messages:mt(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(!rk(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.",...Wa]});let c=await dk();if(!c.complete)return{status:"manual",messages:c.messages};let l=Qr();if(!l)return i({status:"manual",messages:mt(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Le(r))return i({status:"manual",messages:mt(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Le(a)){if(Le(o))return i({status:"manual",messages:mt(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{YA(a)?d="sqlite":(Fa(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:mt(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(Le(o))try{p=Fa(o)}catch{return i({status:"manual",messages:mt(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(ld())return i(await Sm("apply",t,{status:"manual",messages:mt(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Wa,...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}, ${Le(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 ${Ln()}, and register the Anyray retrieval MCP server in ${un()}.`,...Wa]};if(d){try{l.checkpointWal(r)}catch(g){return i({status:"manual",messages:mt(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${gi(g)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=cd(l.readItem(a,ze)??null,l.readItem(a,ht)??null);else{let g=Fa(a);y=cd(g.applicationUser,g.openAIKey)}}catch{return i({status:"manual",messages:mt(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,[Cm(l.readItem(r,ze),y.applicationUser),y.openAIKey===null?{key:ht}:{key:ht,value:y.openAIKey}])}catch{return i({status:"manual",messages:mt(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{Dn(a,{force:!0}),Dn(`${a}-wal`,{force:!0}),Dn(`${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:mt(n,`Couldn't checkpoint Cursor's state DB at ${r}${gi(y)} \u2014 refusing to write; set it by hand:`)})}let m;try{m=l.readItem(r,ze)}catch{return i({status:"manual",messages:mt(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let f=GN(m,n);if(!f)return i({status:"manual",messages:mt(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let h={applicationUser:f.value,openAIKey:e.clientKey};if(Le(o))try{HN(o,h)}catch{return i({status:"manual",messages:mt(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{UN(l,o,r,h)}catch{return i({status:"manual",messages:mt(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:ze,value:f.value},{key:ht,value:e.clientKey}])}catch{let y=!0;if(p)try{tk(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 lk();let w=[];if(!t.preservePendingOp)try{await eo("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,...Wa,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await $().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Le(vi())||Le(Ua())||Am()!=="clear"?!1:n$():VN(e,n).routed},async routingOverrides(){return Am()!=="active"?[]:jN()!=="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=no(),n=vi(),r=Ua(),o=Le(n),a=Le(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 ${Ln()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${Ln()} and unregister its owned retrieval MCP server.`]};if((o||a)&&ld()){if(e.fullRevert){let f=await vm(),h=!0;try{await eo("cursor")}catch{h=!1}return{status:"manual",changedFiles:f.changedFiles,messages:[...f.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 Sm("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Qr(),i=!1,c=!1,l,d=[];if(a)try{if(YA(r))if(Le(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 f=cd(s.readItem(r,ze)??null,s.readItem(r,ht)??null);s.mutateRows(t,[Cm(s.readItem(t,ze),f.applicationUser),f.openAIKey===null?{key:ht}:{key:ht,value:f.openAIKey}]),c=!0}else i=!0,bN(r,t),Dn(`${t}-wal`,{force:!0}),Dn(`${t}-shm`,{force:!0});else{let f=Fa(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Le(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=cd(f.applicationUser,f.openAIKey);s.mutateRows(t,[Cm(s.readItem(t,ze),h.applicationUser),h.openAIKey===null?{key:ht}:{key:ht,value:h.openAIKey}]),c=!0}}catch(f){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${gi(f)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Fa(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(!Le(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 f=r$(s.readItem(t,ze),l.applicationUser,l.lastWritten?.applicationUser);d.push(...f.conflicts);let h=[f.mutation],w=s.readItem(t,ht);l.lastWritten&&w===l.lastWritten.openAIKey?h.push(l.openAIKey===null?{key:ht}:{key:ht,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,h)}catch(f){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${gi(f)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],p=!0;try{Dn(r,{force:!0}),Dn(`${r}-wal`,{force:!0}),Dn(`${r}-shm`,{force:!0}),Dn(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 eo("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let m=await vm();return p=p&&m.complete,{status:p?"reverted":"manual",changedFiles:[...o||a?[t]:[],...m.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(", ")}.`]:[],...m.messages,"Restart Cursor."]}}};import{chmod as iM,mkdir as cM,readFile as Jk,rm as lM,writeFile as dM}from"node:fs/promises";import{randomUUID as uM}from"node:crypto";import{dirname as pM,join as Xk}from"node:path";import{constants as i$,chmod as c$,copyFile as l$,readFile as pk}from"node:fs/promises";import{applyEdits as d$,modify as u$}from"jsonc-parser";var a$=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]!==`
|
|
99
99
|
`;)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},s$=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},Tt=e=>JSON.parse(s$(a$(e)));var fd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Me=async e=>{let t=await R(e),n=t?await pk(e,"utf8"):`{}
|
|
100
100
|
`,r=n.trim()?Tt(n):{};if(!fd(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},fk=(e,t,n=[])=>{if(fd(e)&&fd(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...fk(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}]},Jt=async(e,t,n,r)=>{let o=fk(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await l$(e,`${e}.anyray-bak`,i$.COPYFILE_EXCL),await c$(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await Se(`${e}.anyray-bak`,`{}
|
|
101
101
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
@@ -103,18 +103,18 @@ PRAGMA wal_checkpoint(TRUNCATE);
|
|
|
103
103
|
`:`
|
|
104
104
|
`},s=t.raw;for(let i of o)s=d$(s,u$(s,i.path,i.value,{formattingOptions:a}));return await Se(e,s.endsWith(`
|
|
105
105
|
`)?s:`${s}
|
|
106
|
-
`),!0},
|
|
106
|
+
`),!0},Ga=async e=>{try{let t=Tt(await pk(`${e}.anyray-bak`,"utf8"));return fd(t)?t:void 0}catch{return}};import{readFile as J$,writeFile as X$}from"node:fs/promises";import{dirname as z$,join as q$}from"node:path";import{mkdir as Q$}from"node:fs/promises";var mk=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]!==`
|
|
107
107
|
`;)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},f$=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},m$=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},Om=(e,t,n)=>{let r;try{r=Tt(e)}catch{return{ok:!1,reason:"unsupported"}}if(!mk(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=f$(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=m$(e,o)?`
|
|
108
108
|
${a}${s}
|
|
109
109
|
`:`
|
|
110
|
-
${a}${s},`,d=`${i}${l}${c}`;try{let u=Tt(d);if(!mk(u))return{ok:!1,reason:"unsupported"};for(let[p,m]of Object.entries(r))if(JSON.stringify(u[p])!==JSON.stringify(m))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 A$}from"node:child_process";import{readdirSync as k$,statSync as v$}from"node:fs";import{createHash as Ok,randomBytes as S$,randomUUID as _k}from"node:crypto";import{chmod as I$,lstat as Mm,mkdir as Bm,readdir as Tk,readFile as $n,rm as Pk,unlink as gd,writeFile as Fm}from"node:fs/promises";import{homedir as ja,platform as Wm}from"node:os";import{dirname as Lm,join as Pt,posix as Ek,win32 as E$}from"node:path";import{promisify as x$}from"node:util";var Nn="0.1.29";var ro="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",md="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",hk="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfiqg5aldZRjy9SCjdSklpgCSRKo6InP09C+VJqXKL1AaNc0qrT+sjrq253E36jzwDoaCRTuB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os";import{join as fr,posix as h$,win32 as y$}from"node:path";var Uo=["Code","Code - Insiders","VSCodium"],_m="1.121.0",yk=1,g$=121,bk="1.102.0",gk=1,w$=102,b$={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},hd=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},Tm=e=>{let t=hd(e);return t?t.major!==yk?t.major>yk:t.minor>=g$:!1},Ck=e=>{let t=hd(e);return t?t.major!==gk?t.major>gk:t.minor>=w$:!1},C$=async e=>{if(Ga()!=="darwin")return;let t=fr("/Applications",`${b$[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await wk(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},yd=(e,t=Ga(),n=Wo(),r=process.env)=>{switch(t){case"darwin":return fr(n,"Library","Application Support",e);case"win32":return fr(r.APPDATA??fr(n,"AppData","Roaming"),e);default:return fr(n,".config",e)}},Pm=(e,t)=>e?t==="win32"?y$.join:h$.join:fr,Ka=(e,t=!1,n=Ga(),r=Wo(),o=process.env)=>t?Pm(t,n)(r,Ei[e],"data","User"):fr(yd(e,n,r,o),"User"),Ak=async(e,t=!1,n=Ga(),r=Wo(),o=process.env)=>{try{let a=Pm(t,n)(Ka(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await wk(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[]}},kk=async(e,t=Ga(),n=Wo(),r=process.env)=>{let a=(await Ak(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},vk=async(e,t=!1,n=Ga(),r=Wo(),o=process.env)=>{let a=Pm(t,n),s=Ka(e,t,n,r,o),i=await Ak(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Va=async()=>{for(let e of Uo)if(await R(yd(e)))return e},Ei={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Sk=(e,t=Wo())=>fr(t,Ei[e],"extensions"),Dm=async(e=Wo())=>{for(let t of Uo)if(await R(fr(e,Ei[t])))return t},Ik=async e=>{let t=e??await Va();if(!t)return{status:"unknown"};let n=await C$(t);return n?{variant:t,version:n,status:Tm(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var ne="anyray.anyray-vscode",Um="vscode-handoffs",Dk="vscode-receipts",xi=2,R$=x$(A$),mr={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"]}},O$={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"}},_$=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),Lk=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&_$(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ri=e=>{if(Lk(e))try{return new URL(e.trim()).origin}catch{return}},T$=(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)},P$=e=>{try{return k$(e)}catch{return[]}},D$=e=>{try{return v$(e).mtimeMs}catch{return}},L$=(e,t,n,r,o)=>{if(!ar(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=mr[e].commands[0],s=Pt(t,Ei[e]),i=[];for(let{directory:c,suffix:l}of[{directory:Pt(s,"bin"),suffix:["bin","remote-cli"]},{directory:Pt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=Pt(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)},N$=(e,t,n)=>{let{macAppName:r,commands:o}=mr[e],a=o[0],s=[];for(let i of["/Applications",Ek.join(t,"Applications")])for(let c of n(i))T$(c,r)&&s.push(Ek.join(i,c,"Contents/Resources/app/bin",a));return s},$$=(e,t=Wm(),n=ja(),r=process.env,o=P$,a=D$)=>{let s=L$(e,n,r,o,a);if(t==="darwin")return[...new Set([...mr[e].commands,...N$(e,n,o),...s])];if(t!=="win32"){let u=mr[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=O$[e],c=E$.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)),mr[e].commands[0],...s])]},Nk={run:async(e,t)=>({stdout:(await R$(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>S$(24).toString("base64url"),home:"",commandCandidates:e=>$$(e)},Ho=(e,t)=>Pt(e,".anyray",Dk,`${t}.json`),Hm=(e,t)=>Pt(e,".anyray",Dk,`${t}.applied.json`),$k=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&hd(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},Nm=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()===ne.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===Nn}catch{return}},Mk=async(e,t)=>{let n=await $k(e,t);if(n)return Nm(n.command,t)},M$=async(e,t,n)=>{let r=Pt(e,".anyray",Um);for(let o of n){if(!o.endsWith(".json"))continue;let a=Pt(r,o);try{if(!(await Mm(a)).isFile()||JSON.parse(await $n(a,"utf8")).variant!==t)continue;await gd(a)}catch{}}},B$=async(e,t)=>{let n=Pt(e,".anyray",Um),r;try{r=await Tk(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=Pt(n,o);try{if(!(await Mm(a)).isFile()||JSON.parse(await $n(a,"utf8")).variant!==t)continue;await gd(a)}catch{}}},F$=async(e,t)=>{try{let n=JSON.parse(await $n(Ho(e,t),"utf8"));return n.extensionVersion===Nn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==ro}catch{return!1}},Bk=250,W$=9e4,U$=W$/Bk,H$=async(e,t,n,r)=>{for(let o=0;o<U$;o++){try{let a=JSON.parse(await $n(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===xi&&a.action===n?"confirmed":a.extensionVersion!==Nn||a.extensionDistSha256!==ro?"reload-required":a.version===xi&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(Bk)}return"timeout"},G$=200,xk=(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,G$))}return r.join(": ")},K$=async e=>{try{let t=await Mm(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},Rk=e=>Ok("sha256").update(e).digest("hex"),V$=async(e=ja())=>{let t=Buffer.from(hk,"base64");if(t.length<4||t[0]!==80||t[1]!==75||Rk(t)!==md)throw new Error("bundled VS Code extension failed integrity validation");let n=Pt(e,".anyray","vscode-extension"),r=Pt(n,`anyray-vscode-${Nn}-${md.slice(0,12)}.vsix`);try{if(Rk(await $n(r))===md)return r}catch{}await Bm(n,{recursive:!0,mode:448});let o=`${r}.${_k()}.tmp`;try{await Fm(o,t,{mode:384}),await Ae(o,r),Wm()!=="win32"&&await I$(r,384)}finally{await Pk(o,{force:!0})}return r},$m=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=>$m(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${$m(t[n])}`).join(",")}}`},Fk=(e,t,n)=>Ok("sha256").update($m({gatewayUrl:Ri(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:Nn,extensionDistSha256:ro,profiles:[...n].sort()})).digest("hex"),j$=async(e,t,n,r,o,a)=>{let s=JSON.parse(await $n(Hm(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==Fk(t,n,r))return!1;let i=JSON.parse(await $n(Ho(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===Nn&&i.extensionDistSha256===ro&&i.gatewayUrl===Ri(t.origin)?await Mk(e,a)===!0:!1},Y$=async(e,t,n,r)=>{let o=Hm(e,t),a=`${o}.${_k()}.tmp`;try{await Bm(Lm(o),{recursive:!0,mode:448}),await Fm(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
111
|
-
`,{mode:384}),await Ae(a,o)}catch{}finally{await Pk(a,{force:!0})}},Z$=async(e,t)=>{await gd(Hm(e,t)).catch(()=>{})},Wk=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...Nk,...r,home:r.home??
|
|
112
|
-
`,{mode:384}),await M$(a.home,s.slug,w).catch(()=>{});let y={installed:[],failed:[]},g=!1;try{if(n==="configure"){let k=await F$(a.home,s.slug);if(k||await Nm(l,a)!==!0)try{await a.run(l,["--install-extension",p,"--force"])}catch(A){return g=!0,{ok:!1,reason:"install-failed",detail:xk(A,m)}}for(let A of u)try{(k||await Nm(l,a,A)!==!0)&&await a.run(l,["--profile",A,"--install-extension",p,"--force"]),y.installed.push(A)}catch{y.failed.push(A)}}try{await a.run(l,["--open-url",`${s.scheme}://${ne}/configure?nonce=${encodeURIComponent(m)}`])}catch(k){return{ok:!1,reason:"handoff-undeliverable",detail:xk(k,m)}}let b=await H$(h,m,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 Y$(a.home,s.slug,Fk(t,o,u),m);else{await Z$(a.home,s.slug),await B$(a.home,s.slug).catch(()=>{});for(let k of[void 0,...u])try{await a.run(l,[...k?["--profile",k]:[],"--uninstall-extension",ne])}catch{}}return{ok:!0,receipt:h,profiles:y}}catch{return{ok:!1,reason:"failed"}}finally{g&&await gd(f).catch(()=>{})}},wd=async(e,t=
|
|
113
|
-
`,{flag:"wx",mode:384}),await Ae(n,e),await iM(e,384)}finally{await lM(n,{force:!0}).catch(()=>{})}},Km=e=>{if(!Dt(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!==oo||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(!Dt(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!==Qk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!Dt(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}})},Vm=e=>{let t=e.filter(n=>!Km(n));return{next:t,removed:t.length!==e.length}},hM=async(e,t)=>{let n=Ti(e),r=await Ad(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 "${oo}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=Vm(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${oo}" Custom Endpoint from ${n}.`]};try{return await ev(n,o),await pe(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${oo}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${oo}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},yM=async e=>{try{let t=Tt(await Jk(e,"utf-8"));if(Dt(t))return qk(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Pi}.${kd} 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 ${Pi}.${kd} value manually if present.`]}},tv=async(e,t)=>{let n=fM(e),r;try{r=await F(n)}catch{return yM(n)}let{next:o,removed:a}=qk(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 q(n,o,{backup:!1}),await pe(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.`]}}},gM=async(e,t)=>{let n=await hM(e,t),r=await tv(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},nv=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,zk]}},rv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},ov=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),wM=e=>Array.isArray(e.args)&&e.args.at(-1)===zk,av=(e,t)=>{if(!t.hookBinaryIsDurable()||!Dt(e)||!rv(e,["type","command","args"]))return!1;let n=nv(t);return e.type==="stdio"&&e.command===n.command&&ov(e.args,n.args)},bM=(e,t)=>{if(!Dt(e)||!rv(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&&ov(e.args,n.args))return!0;if(dt(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===Vr&&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!dt(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},vd=(e,t)=>av(e,t)?"exact":Dt(e)&&wM(e)||bM(e,t)?"stale-owned":"foreign",jk=e=>`MCP name conflict in ${e}: servers.${Fn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,CM=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 m of a)try{let f=await Me(m),h=f.data;if(i){if("servers"in h&&!Dt(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${m} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let b=Dt(h.servers)?{...h.servers}:{},k=nv(o),A=b[Fn],E=A===void 0?void 0:vd(A,o);if(E==="exact"){d+=1;continue}if(E==="foreign"){u=!0,l.push(jk(m));continue}if(t){d+=1;continue}b[Fn]=k,p.push({path:m,document:f,next:{...h,servers:b},backup:E!=="stale-owned",clearBackupAfter:!1});continue}if(!Dt(h.servers)||!(Fn in h.servers))continue;if(vd(h.servers[Fn],o)==="foreign"){u=!0,l.push(jk(m));continue}if(t)continue;let y={...h.servers};delete y[Fn];let g={...h};Object.keys(y).length===0?delete g.servers:g.servers=y,p.push({path:m,document:f,next:g,backup:!1,clearBackupAfter:!0})}catch(f){u=!0,l.push(`Could not update the Anyray MCP server in ${m} (${f instanceof Error?f.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let m of p)try{await Jt(m.path,m.document,m.next,m.backup),m.clearBackupAfter&&await pe(m.path),c.push(m.path),i&&(d+=1)}catch(f){u=!0,l.push(`Could not update the Anyray MCP server in ${m.path} (${f instanceof Error?f.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 (${bk}+).`),{changedFiles:c,messages:l,manual:u}},AM=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await R(c))try{let l=await Me(c),d=l.data;if(!Dt(d.servers)||!(Fn in d.servers)||vd(d.servers[Fn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[Fn];let p={...d};Object.keys(u).length===0?delete p.servers:p.servers=u,await Jt(c,l,p,!1),await pe(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}},sv=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.`]:[]],iv=()=>`${ne} 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.)`,Yk=e=>[`${ne} 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."],cv=(e,t,n,r)=>({runMcp:o=>CM(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):gM(e,o)}),lv=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${ne} 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 ${ne} 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 ${ne} 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 ${ne} 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 ${_m} 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 ${ne} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${ne} 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.`:`${ne} 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 ${ne} ${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 ${ne} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},kM=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${ne} 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 ${ne} 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 ${ne} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${ne} 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 ${ne} 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 ${ne} 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 ${ne} 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 ${ne} 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 ${ne} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},vM=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=cv(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 f=await c(!0),h=await i(!0);return{status:f.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${ne} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...Yk(t),a?Gm({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,...f.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${ne}; 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:[lv(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),p=await i(!1),m=a?void 0:await Gk(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,...m?.status==="enabled"&&m.changed?[Oi(e)]:[]],messages:[...d.alreadyCurrent?[iv()]:[],...Yk(t),Gm(m??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:sv(d.profiles),...p.messages,...u.messages]}},Zk=e=>[`${ne} 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: ${Li().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."],SM=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=cv(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let m=await c(!0),f=await i(!0);return{status:m.manual||f.manual?"manual":"configured",messages:[`Would install the bundled ${ne} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...Zk(t),...f.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${ne}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Li().map(m=>({id:m,name:Qk(m)}))});if(!d.ok)return{status:"manual",messages:[lv(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?[iv()]:[],...Zk(t),...d.alreadyCurrent?[]:sv(d.profiles),...p.messages,...u.messages]}},IM=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 R(s))return{registered:!1,command:null,reason:"no-config"};try{let{data:i}=await Me(s),c=Dt(i.servers)?i.servers[Fn]:void 0;if(!av(c,n))return{registered:!1,command:null,reason:c===void 0?"absent":vd(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 EM=async(e={installedVariant:Va,remoteServerVariant:Dm,isRemoteDevContext:ar})=>{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}},xM={installedVariant:Va,remoteServerVariant:Dm,detectVscodeLmProviderEligibility:Ik,configureVscodeExtension:Wk,vscodeExtensionPointsAt:Uk,vscodeExtensionAwaitingReload:wd,vscodeExtensionReceiptMode:bd,hookBinaryIsDurable:te,hookBinaryPath:De,mcpServerCommand:We,vscodeUserMcpConfigPaths:vk,isRemoteDevContext:ar},RM=(e={})=>{let t={...xM,...e},n=()=>EM(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,skillsDir(){return jt()},quitGated:{isRunning:_i,quitTarget:Cd},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Ka(r,!0)}`:Ti(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Pe(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 ${_m} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||Ck(i.version);return ae(r,"copilot")?vM(a,r,o,t.configureVscodeExtension,c,s,t):SM(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?IM(r,o,t):{registered:!1,command:null,reason:"no-config"}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ri(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await Ad(Ti(o));if(s.kind==="array"){let c=s.entries.find(Km)?.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 Ad(Ti(r));if(o.kind==="array"&&o.entries.some(Km))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 AM(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await tv(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${ne} 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 ${ne} gateway configuration and secret.`)):(l=!0,u.push(kM(g.reason,o,a,g.detail)))}let p=Ti(o),m=await Ad(p),f=m.kind==="missing"||m.kind==="array"&&!Vm(m.entries).removed,h=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),f)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(m.kind==="unrecognized")return{status:"manual",changedFiles:h.length?h:void 0,messages:[...u,`Couldn't recognize ${p} \u2014 remove the "${oo}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=Vm(m.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${oo} Custom Endpoint from ${p}`]};await ev(p,w);let y=[...u,`Removed the ${oo} Custom Endpoint from ${p}.`];return await pe(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,p],messages:y}}}},dv=RM();import{accessSync as oB,constants as Sv,statSync as aB}from"node:fs";import{readFile as Iv,rm as $i}from"node:fs/promises";import{homedir as nh,platform as Pv}from"node:os";import{delimiter as sB,join as rh,resolve as iB}from"node:path";import{execFile as DM}from"node:child_process";import{readFile as LM}from"node:fs/promises";import{homedir as Zm,platform as NM}from"node:os";import{join as Ni}from"node:path";import{join as OM}from"node:path";var jm="Iv1.b507a08c87ecfe98",_M="https://github.com/login/device/code",TM="https://github.com/login/oauth/access_token",PM="read:user",uv=1e4,Ya=()=>OM(oe(),"copilot-seat-login.json"),pv={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},Ym=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fv=async(e={})=>{let t={...pv,...e};try{let n=await t.fetch(_M,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:jm,scope:PM}),signal:AbortSignal.timeout(uv)});if(!n.ok)return;let r=await n.json();if(!Ym(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}},mv=async(e,t={})=>{let n={...pv,...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(TM,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:jm,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(uv)})).json();if(!Ym(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"}},hv=async(e,t)=>{let n=Ya();return await Se(n,`${JSON.stringify({token:e,clientId:jm,mintedAtIso:t},null,2)}
|
|
114
|
-
`),n},Sd=async()=>{try{let e=await F(
|
|
115
|
-
`))}`]:[],`export ${_d}=${$e(n)}`]},eh=(e,t,n)=>{let r=be({...e.metadata,tool:
|
|
116
|
-
`).map(kB).join(" + [Environment]::NewLine + "),SB=(e={})=>{let t={...AB,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await mi(ft(),Un))?.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&&
|
|
117
|
-
`)):G&&re&&await $i(
|
|
110
|
+
${a}${s},`,d=`${i}${l}${c}`;try{let u=Tt(d);if(!mk(u))return{ok:!1,reason:"unsupported"};for(let[p,m]of Object.entries(r))if(JSON.stringify(u[p])!==JSON.stringify(m))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 A$}from"node:child_process";import{readdirSync as k$,statSync as v$}from"node:fs";import{createHash as Ok,randomBytes as S$,randomUUID as _k}from"node:crypto";import{chmod as I$,lstat as Mm,mkdir as Bm,readdir as Tk,readFile as $n,rm as Pk,unlink as gd,writeFile as Fm}from"node:fs/promises";import{homedir as Ya,platform as Wm}from"node:os";import{dirname as Lm,join as Pt,posix as Ek,win32 as E$}from"node:path";import{promisify as x$}from"node:util";var Nn="0.1.29";var ro="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",md="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",hk="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfiqg5aldZRjy9SCjdSklpgCSRKo6InP09C+VJqXKL1AaNc0qrT+sjrq253E36jzwDoaCRTuBYnv7y4yMaYQEOC+uciG2p0yaQ1G4ErKiiwx9F1/p5yN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owkn0+4KWS6STjnK4+yGAFFSBu9lhYQ0zNLzFhTVL6BUNC3TfGdPQ6m69Du/AO/I+wuHO6Nbzr5cC96Klx7GuFqyAM7vqoWdDCqToad8R6+cIhoDMlwbgDJwWwIyWZlPhXgXLjJY2u+xUZ9HulXS/XCjvQrsvNiYKL9o7GdJRIvwpit/5KLHjNQ4Gnk4icM5e7UEod154b48TrS7Vgu8iMxOLIlc6j1tasslSoUZwug+XxDgEtrsxlOZe1YiOaspCVDvSwESIVjUk8JsJSB4U0Y/6cutVmkl2m0qKc2ofazT8y/8FUEsHCKcyHPQDOQAAI6kAAFBLAQI/AxQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAAAAAAAAAAAC0gQAAAABleHRlbnNpb24udnNpeG1hbmlmZXN0UEsBAj8DFAAACAgAF1oYXVr3VFTSAAAAzgEAABMAAAAAAAAAAAAAALSBaAMAAFtDb250ZW50X1R5cGVzXS54bWxQSwECPwMUAAgICAAKWhhdcQ3Z86YCAAC7BQAAFgAAAAAAAAAAAAAApIFrBAAAZXh0ZW5zaW9uL3BhY2thZ2UuanNvblBLAQI/AxQACAgIAARaGF0wVq3AThEAACgTAAASAAAAAAAAAAAAAACkgVUHAABleHRlbnNpb24vaWNvbi5wbmdQSwECPwMUAAAICAAXWhhdC7fjr0sCAAB9BAAAEwAAAAAAAAAAAAAAtIHjGAAAZXh0ZW5zaW9uL3JlYWRtZS5tZFBLAQI/AxQACAgIAMtZGF2yhnqNeQIAACcEAAAVAAAAAAAAAAAAAACkgV8bAABleHRlbnNpb24vTElDRU5TRS50eHRQSwECPwMUAAgICAAXWhhdpzIc9AM5AAAjqQAAGwAAAAAAAAAAAAAApIEbHgAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAHAAcA1gEAAGdXAAAAAA==";import{readFile as wk}from"node:fs/promises";import{homedir as Uo,platform as Ka}from"node:os";import{join as fr,posix as h$,win32 as y$}from"node:path";var Ho=["Code","Code - Insiders","VSCodium"],_m="1.121.0",yk=1,g$=121,bk="1.102.0",gk=1,w$=102,b$={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},hd=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},Tm=e=>{let t=hd(e);return t?t.major!==yk?t.major>yk:t.minor>=g$:!1},Ck=e=>{let t=hd(e);return t?t.major!==gk?t.major>gk:t.minor>=w$:!1},C$=async e=>{if(Ka()!=="darwin")return;let t=fr("/Applications",`${b$[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await wk(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},yd=(e,t=Ka(),n=Uo(),r=process.env)=>{switch(t){case"darwin":return fr(n,"Library","Application Support",e);case"win32":return fr(r.APPDATA??fr(n,"AppData","Roaming"),e);default:return fr(n,".config",e)}},Pm=(e,t)=>e?t==="win32"?y$.join:h$.join:fr,Va=(e,t=!1,n=Ka(),r=Uo(),o=process.env)=>t?Pm(t,n)(r,Ei[e],"data","User"):fr(yd(e,n,r,o),"User"),Ak=async(e,t=!1,n=Ka(),r=Uo(),o=process.env)=>{try{let a=Pm(t,n)(Va(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await wk(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[]}},kk=async(e,t=Ka(),n=Uo(),r=process.env)=>{let a=(await Ak(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},vk=async(e,t=!1,n=Ka(),r=Uo(),o=process.env)=>{let a=Pm(t,n),s=Va(e,t,n,r,o),i=await Ak(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},ja=async()=>{for(let e of Ho)if(await R(yd(e)))return e},Ei={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Sk=(e,t=Uo())=>fr(t,Ei[e],"extensions"),Dm=async(e=Uo())=>{for(let t of Ho)if(await R(fr(e,Ei[t])))return t},Ik=async e=>{let t=e??await ja();if(!t)return{status:"unknown"};let n=await C$(t);return n?{variant:t,version:n,status:Tm(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var ne="anyray.anyray-vscode",Um="vscode-handoffs",Dk="vscode-receipts",xi=2,R$=x$(A$),mr={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"]}},O$={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"}},_$=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),Lk=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&_$(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ri=e=>{if(Lk(e))try{return new URL(e.trim()).origin}catch{return}},T$=(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)},P$=e=>{try{return k$(e)}catch{return[]}},D$=e=>{try{return v$(e).mtimeMs}catch{return}},L$=(e,t,n,r,o)=>{if(!ar(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=mr[e].commands[0],s=Pt(t,Ei[e]),i=[];for(let{directory:c,suffix:l}of[{directory:Pt(s,"bin"),suffix:["bin","remote-cli"]},{directory:Pt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=Pt(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)},N$=(e,t,n)=>{let{macAppName:r,commands:o}=mr[e],a=o[0],s=[];for(let i of["/Applications",Ek.join(t,"Applications")])for(let c of n(i))T$(c,r)&&s.push(Ek.join(i,c,"Contents/Resources/app/bin",a));return s},$$=(e,t=Wm(),n=Ya(),r=process.env,o=P$,a=D$)=>{let s=L$(e,n,r,o,a);if(t==="darwin")return[...new Set([...mr[e].commands,...N$(e,n,o),...s])];if(t!=="win32"){let u=mr[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=O$[e],c=E$.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)),mr[e].commands[0],...s])]},Nk={run:async(e,t)=>({stdout:(await R$(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>S$(24).toString("base64url"),home:"",commandCandidates:e=>$$(e)},Go=(e,t)=>Pt(e,".anyray",Dk,`${t}.json`),Hm=(e,t)=>Pt(e,".anyray",Dk,`${t}.applied.json`),$k=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&hd(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},Nm=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()===ne.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===Nn}catch{return}},Mk=async(e,t)=>{let n=await $k(e,t);if(n)return Nm(n.command,t)},M$=async(e,t,n)=>{let r=Pt(e,".anyray",Um);for(let o of n){if(!o.endsWith(".json"))continue;let a=Pt(r,o);try{if(!(await Mm(a)).isFile()||JSON.parse(await $n(a,"utf8")).variant!==t)continue;await gd(a)}catch{}}},B$=async(e,t)=>{let n=Pt(e,".anyray",Um),r;try{r=await Tk(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=Pt(n,o);try{if(!(await Mm(a)).isFile()||JSON.parse(await $n(a,"utf8")).variant!==t)continue;await gd(a)}catch{}}},F$=async(e,t)=>{try{let n=JSON.parse(await $n(Go(e,t),"utf8"));return n.extensionVersion===Nn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==ro}catch{return!1}},Bk=250,W$=9e4,U$=W$/Bk,H$=async(e,t,n,r)=>{for(let o=0;o<U$;o++){try{let a=JSON.parse(await $n(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===xi&&a.action===n?"confirmed":a.extensionVersion!==Nn||a.extensionDistSha256!==ro?"reload-required":a.version===xi&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(Bk)}return"timeout"},G$=200,xk=(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,G$))}return r.join(": ")},K$=async e=>{try{let t=await Mm(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},Rk=e=>Ok("sha256").update(e).digest("hex"),V$=async(e=Ya())=>{let t=Buffer.from(hk,"base64");if(t.length<4||t[0]!==80||t[1]!==75||Rk(t)!==md)throw new Error("bundled VS Code extension failed integrity validation");let n=Pt(e,".anyray","vscode-extension"),r=Pt(n,`anyray-vscode-${Nn}-${md.slice(0,12)}.vsix`);try{if(Rk(await $n(r))===md)return r}catch{}await Bm(n,{recursive:!0,mode:448});let o=`${r}.${_k()}.tmp`;try{await Fm(o,t,{mode:384}),await Ae(o,r),Wm()!=="win32"&&await I$(r,384)}finally{await Pk(o,{force:!0})}return r},$m=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=>$m(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${$m(t[n])}`).join(",")}}`},Fk=(e,t,n)=>Ok("sha256").update($m({gatewayUrl:Ri(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:Nn,extensionDistSha256:ro,profiles:[...n].sort()})).digest("hex"),j$=async(e,t,n,r,o,a)=>{let s=JSON.parse(await $n(Hm(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==Fk(t,n,r))return!1;let i=JSON.parse(await $n(Go(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===Nn&&i.extensionDistSha256===ro&&i.gatewayUrl===Ri(t.origin)?await Mk(e,a)===!0:!1},Y$=async(e,t,n,r)=>{let o=Hm(e,t),a=`${o}.${_k()}.tmp`;try{await Bm(Lm(o),{recursive:!0,mode:448}),await Fm(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
111
|
+
`,{mode:384}),await Ae(a,o)}catch{}finally{await Pk(a,{force:!0})}},Z$=async(e,t)=>{await gd(Hm(e,t)).catch(()=>{})},Wk=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...Nk,...r,home:r.home??Ya()},s=mr[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!Lk(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,k,A)=>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)&&A.findIndex(x=>x.id===b.id)===k);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await $k(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!Tm(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>kk(b,Wm(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await j$(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:Go(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let p=a.extensionPath;if(n==="configure"){try{p??=await V$(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await K$(p))return{ok:!1,reason:"extension-missing"}}let m=a.nonce(),f=Pt(a.home,".anyray",Um,`${m}.json`),h=Go(a.home,s.slug);await Bm(Lm(f),{recursive:!0,mode:448});let w=await Tk(Lm(f)).catch(()=>[]);await Fm(f,`${JSON.stringify({version:xi,action:n,nonce:m,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:Nn,expectedExtensionDistSha256:ro})}
|
|
112
|
+
`,{mode:384}),await M$(a.home,s.slug,w).catch(()=>{});let y={installed:[],failed:[]},g=!1;try{if(n==="configure"){let k=await F$(a.home,s.slug);if(k||await Nm(l,a)!==!0)try{await a.run(l,["--install-extension",p,"--force"])}catch(A){return g=!0,{ok:!1,reason:"install-failed",detail:xk(A,m)}}for(let A of u)try{(k||await Nm(l,a,A)!==!0)&&await a.run(l,["--profile",A,"--install-extension",p,"--force"]),y.installed.push(A)}catch{y.failed.push(A)}}try{await a.run(l,["--open-url",`${s.scheme}://${ne}/configure?nonce=${encodeURIComponent(m)}`])}catch(k){return{ok:!1,reason:"handoff-undeliverable",detail:xk(k,m)}}let b=await H$(h,m,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 Y$(a.home,s.slug,Fk(t,o,u),m);else{await Z$(a.home,s.slug),await B$(a.home,s.slug).catch(()=>{});for(let k of[void 0,...u])try{await a.run(l,[...k?["--profile",k]:[],"--uninstall-extension",ne])}catch{}}return{ok:!0,receipt:h,profiles:y}}catch{return{ok:!1,reason:"failed"}}finally{g&&await gd(f).catch(()=>{})}},wd=async(e,t=Ya())=>{try{let n=JSON.parse(await $n(Go(t,mr[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==Nn||n.extensionDistSha256!==ro)}catch{return!1}},bd=async(e,t=Ya())=>{try{let n=JSON.parse(await $n(Go(t,mr[e].slug),"utf8"));return n.version!==xi||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},Uk=async(e,t,n=Ya(),r={})=>{try{let o=Ri(t);if(!o)return!1;let a=JSON.parse(await $n(Go(n,mr[e].slug),"utf8"));if(!(a.version===xi&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===Nn&&a.extensionDistSha256===ro))return!1;let i={...Nk,...r,home:n};return await Mk(e,i)===!0}catch{return!1}};var Mn="extensions.supportAgentsWindow",Bn="chat.agentHost.byokModels.enabled",Oi=e=>q$(Ue(e),"User","settings.json"),Hk=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eM=e=>Hk(e)&&e[ne]===!0,Gk=async(e,t={})=>{let n=Oi(e),r=t.read??(m=>J$(m,"utf-8")),o=t.exists??R,a=t.write??(async(m,f)=>{await Q$(z$(m),{recursive:!0}),await X$(m,f,"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=Tt(s)}catch{return{status:"manual",reason:`${n} is not valid JSON/JSONC, so it was left untouched`}}if(!Hk(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(Mn in i)){let m=Om(c,Mn,{[ne]:!0});if(!m.ok)return{status:"manual",reason:`could not add ${Mn} to ${n} without rewriting it`};c=m.text,l=!0}if(!(Bn in i)){let m=Om(c,Bn,!0);if(!m.ok)return{status:"manual",reason:`could not add ${Bn} to ${n} without rewriting it`};c=m.text,l=!0}l&&await a(n,c);let d=l?Tt(c):i,u=eM(d[Mn]),p=d[Bn]===!0;return!u||!p?{status:"manual",reason:`${n} already sets ${u?Bn:Mn} to something else; left as it is`}:{status:"enabled",changed:l}},Gm=(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 "${Mn}": {"${ne}": true} and "${Bn}": 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 tM}from"node:child_process";import{platform as nM}from"node:os";var Kk={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},rM=(e,t,n)=>tM(e,t,n),Vk=rM,oM,aM=()=>{let e=oM??nM();if(e==="win32"){let n=Vk(Ai("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],Kk);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=Vk("pgrep",[n,r],Kk);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},sM=aM,_i=()=>sM();var Cd={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 oo="Anyray",Fn="anyray",zk="--anyray-owner=vscode-profile-v1",Ti=e=>Xk(Ue(e),"User","chatLanguageModels.json"),fM=e=>Xk(Ue(e),"User","settings.json"),Pi="github.copilot.advanced",kd="debug.overrideCapiUrl",Dt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mM=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}},qk=e=>{let t=e[Pi];if(!Dt(t)||!mM(t[kd]))return{next:e,removed:!1};let n={...t};delete n[kd];let r={...e};return Object.keys(n).length>0?r[Pi]=n:delete r[Pi],{next:r,removed:!0}},Di="anyray-default",Li=()=>{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:[Di]},Qk=e=>e===Di?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),Ad=async e=>{if(!await R(e))return{kind:"missing"};try{let t=await Jk(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"}}},ev=async(e,t)=>{await cM(pM(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${uM()}`;try{await dM(n,`${JSON.stringify(t,null,2)}
|
|
113
|
+
`,{flag:"wx",mode:384}),await Ae(n,e),await iM(e,384)}finally{await lM(n,{force:!0}).catch(()=>{})}},Km=e=>{if(!Dt(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!==oo||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(!Dt(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!==Qk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!Dt(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}})},Vm=e=>{let t=e.filter(n=>!Km(n));return{next:t,removed:t.length!==e.length}},hM=async(e,t)=>{let n=Ti(e),r=await Ad(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 "${oo}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=Vm(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${oo}" Custom Endpoint from ${n}.`]};try{return await ev(n,o),await pe(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${oo}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${oo}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},yM=async e=>{try{let t=Tt(await Jk(e,"utf-8"));if(Dt(t))return qk(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Pi}.${kd} 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 ${Pi}.${kd} value manually if present.`]}},tv=async(e,t)=>{let n=fM(e),r;try{r=await F(n)}catch{return yM(n)}let{next:o,removed:a}=qk(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 q(n,o,{backup:!1}),await pe(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.`]}}},gM=async(e,t)=>{let n=await hM(e,t),r=await tv(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},nv=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,zk]}},rv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},ov=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),wM=e=>Array.isArray(e.args)&&e.args.at(-1)===zk,av=(e,t)=>{if(!t.hookBinaryIsDurable()||!Dt(e)||!rv(e,["type","command","args"]))return!1;let n=nv(t);return e.type==="stdio"&&e.command===n.command&&ov(e.args,n.args)},bM=(e,t)=>{if(!Dt(e)||!rv(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&&ov(e.args,n.args))return!0;if(dt(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===Vr&&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!dt(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},vd=(e,t)=>av(e,t)?"exact":Dt(e)&&wM(e)||bM(e,t)?"stale-owned":"foreign",jk=e=>`MCP name conflict in ${e}: servers.${Fn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,CM=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 m of a)try{let f=await Me(m),h=f.data;if(i){if("servers"in h&&!Dt(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${m} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let b=Dt(h.servers)?{...h.servers}:{},k=nv(o),A=b[Fn],x=A===void 0?void 0:vd(A,o);if(x==="exact"){d+=1;continue}if(x==="foreign"){u=!0,l.push(jk(m));continue}if(t){d+=1;continue}b[Fn]=k,p.push({path:m,document:f,next:{...h,servers:b},backup:x!=="stale-owned",clearBackupAfter:!1});continue}if(!Dt(h.servers)||!(Fn in h.servers))continue;if(vd(h.servers[Fn],o)==="foreign"){u=!0,l.push(jk(m));continue}if(t)continue;let y={...h.servers};delete y[Fn];let g={...h};Object.keys(y).length===0?delete g.servers:g.servers=y,p.push({path:m,document:f,next:g,backup:!1,clearBackupAfter:!0})}catch(f){u=!0,l.push(`Could not update the Anyray MCP server in ${m} (${f instanceof Error?f.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let m of p)try{await Jt(m.path,m.document,m.next,m.backup),m.clearBackupAfter&&await pe(m.path),c.push(m.path),i&&(d+=1)}catch(f){u=!0,l.push(`Could not update the Anyray MCP server in ${m.path} (${f instanceof Error?f.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 (${bk}+).`),{changedFiles:c,messages:l,manual:u}},AM=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await R(c))try{let l=await Me(c),d=l.data;if(!Dt(d.servers)||!(Fn in d.servers)||vd(d.servers[Fn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[Fn];let p={...d};Object.keys(u).length===0?delete p.servers:p.servers=u,await Jt(c,l,p,!1),await pe(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}},sv=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.`]:[]],iv=()=>`${ne} 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.)`,Yk=e=>[`${ne} 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."],cv=(e,t,n,r)=>({runMcp:o=>CM(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):gM(e,o)}),lv=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${ne} 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 ${ne} 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 ${ne} 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 ${ne} 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 ${_m} 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 ${ne} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${ne} 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.`:`${ne} 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 ${ne} ${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 ${ne} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},kM=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${ne} 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 ${ne} 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 ${ne} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${ne} 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 ${ne} 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 ${ne} 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 ${ne} 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 ${ne} 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 ${ne} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},vM=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=cv(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 f=await c(!0),h=await i(!0);return{status:f.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${ne} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...Yk(t),a?Gm({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,...f.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${ne}; 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:[lv(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),p=await i(!1),m=a?void 0:await Gk(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,...m?.status==="enabled"&&m.changed?[Oi(e)]:[]],messages:[...d.alreadyCurrent?[iv()]:[],...Yk(t),Gm(m??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:sv(d.profiles),...p.messages,...u.messages]}},Zk=e=>[`${ne} 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: ${Li().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."],SM=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=cv(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let m=await c(!0),f=await i(!0);return{status:m.manual||f.manual?"manual":"configured",messages:[`Would install the bundled ${ne} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...Zk(t),...f.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${ne}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Li().map(m=>({id:m,name:Qk(m)}))});if(!d.ok)return{status:"manual",messages:[lv(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?[iv()]:[],...Zk(t),...d.alreadyCurrent?[]:sv(d.profiles),...p.messages,...u.messages]}},IM=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 R(s))return{registered:!1,command:null,reason:"no-config"};try{let{data:i}=await Me(s),c=Dt(i.servers)?i.servers[Fn]:void 0;if(!av(c,n))return{registered:!1,command:null,reason:c===void 0?"absent":vd(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 EM=async(e={installedVariant:ja,remoteServerVariant:Dm,isRemoteDevContext:ar})=>{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}},xM={installedVariant:ja,remoteServerVariant:Dm,detectVscodeLmProviderEligibility:Ik,configureVscodeExtension:Wk,vscodeExtensionPointsAt:Uk,vscodeExtensionAwaitingReload:wd,vscodeExtensionReceiptMode:bd,hookBinaryIsDurable:te,hookBinaryPath:De,mcpServerCommand:We,vscodeUserMcpConfigPaths:vk,isRemoteDevContext:ar},RM=(e={})=>{let t={...xM,...e},n=()=>EM(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,skillsDir(){return jt()},quitGated:{isRunning:_i,quitTarget:Cd},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Va(r,!0)}`:Ti(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Pe(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 ${_m} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||Ck(i.version);return ae(r,"copilot")?vM(a,r,o,t.configureVscodeExtension,c,s,t):SM(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?IM(r,o,t):{registered:!1,command:null,reason:"no-config"}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ri(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await Ad(Ti(o));if(s.kind==="array"){let c=s.entries.find(Km)?.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 Ad(Ti(r));if(o.kind==="array"&&o.entries.some(Km))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 AM(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await tv(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${ne} 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 ${ne} gateway configuration and secret.`)):(l=!0,u.push(kM(g.reason,o,a,g.detail)))}let p=Ti(o),m=await Ad(p),f=m.kind==="missing"||m.kind==="array"&&!Vm(m.entries).removed,h=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),f)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(m.kind==="unrecognized")return{status:"manual",changedFiles:h.length?h:void 0,messages:[...u,`Couldn't recognize ${p} \u2014 remove the "${oo}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=Vm(m.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${oo} Custom Endpoint from ${p}`]};await ev(p,w);let y=[...u,`Removed the ${oo} Custom Endpoint from ${p}.`];return await pe(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,p],messages:y}}}},dv=RM();import{accessSync as oB,constants as Sv,statSync as aB}from"node:fs";import{readFile as Iv,rm as $i}from"node:fs/promises";import{homedir as nh,platform as Pv}from"node:os";import{delimiter as sB,join as rh,resolve as iB}from"node:path";import{execFile as DM}from"node:child_process";import{readFile as LM}from"node:fs/promises";import{homedir as Zm,platform as NM}from"node:os";import{join as Ni}from"node:path";import{join as OM}from"node:path";var jm="Iv1.b507a08c87ecfe98",_M="https://github.com/login/device/code",TM="https://github.com/login/oauth/access_token",PM="read:user",uv=1e4,Za=()=>OM(oe(),"copilot-seat-login.json"),pv={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},Ym=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fv=async(e={})=>{let t={...pv,...e};try{let n=await t.fetch(_M,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:jm,scope:PM}),signal:AbortSignal.timeout(uv)});if(!n.ok)return;let r=await n.json();if(!Ym(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}},mv=async(e,t={})=>{let n={...pv,...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(TM,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:jm,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(uv)})).json();if(!Ym(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"}},hv=async(e,t)=>{let n=Za();return await Se(n,`${JSON.stringify({token:e,clientId:jm,mintedAtIso:t},null,2)}
|
|
114
|
+
`),n},Sd=async()=>{try{let e=await F(Za());if(!Ym(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var $M=5e3,Jm=5e3,MM=["copilot-cli","CopilotCLI"],BM="https://api.github.com/copilot_internal/user",gv="~/.copilot/config.json",wv="macOS Keychain (Copilot CLI)",bv=e=>e===gv||e===wv,Ja=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),pn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),FM=()=>process.env.XDG_CONFIG_HOME?.trim()||Ni(Zm(),".config"),WM=()=>process.env.XDG_DATA_HOME?.trim()||Ni(Zm(),".local","share"),UM=async()=>{try{let e=await LM(Ni(Zm(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return Ja(t)?t:void 0}catch{}},HM=async e=>{try{let t=await F(Ni(FM(),"github-copilot",e));if(!pn(t))return;for(let n of Object.values(t))if(pn(n)&&Ja(n.oauth_token))return n.oauth_token}catch{}},GM=async()=>{try{let e=await F(Ni(WM(),"opencode","auth.json")),t=pn(e)?e["github-copilot"]:void 0;if(!pn(t)||t.type!=="oauth")return;if(Ja(t.access))return t.access;if(Ja(t.refresh))return t.refresh}catch{}},KM=(e,t)=>new Promise((n,r)=>{try{DM(e,[...t],{timeout:$M},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),VM=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return Ja(r)?r:void 0}catch{return}},jM=async(e=KM)=>{for(let t of MM){let n=await VM(t,e);if(n)return n}};var Id={env:process.env,platform:NM,tokenFromDeviceLogin:Sd,tokenFromCopilotCliConfig:UM,tokenFromSharedConfig:HM,tokenFromOpenCode:GM,tokenFromKeychain:jM,fetch:(...e)=>fetch(...e)},YM=new Set([401,403,404]),Ed=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Cv=e=>{let t=e?.trim().toLowerCase()??"";return t&&t!=="default"&&Ed.test(t)?t:"default"},ZM=e=>e!=="default"&&Ed.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",JM=e=>{if(typeof e!="string")return"default";let t=e.trim().match(/^https:\/\/api\.([a-z0-9-]{1,63})\.githubcopilot\.com\/?$/)?.[1];return t&&Ed.test(t)?t:"default"},Xm=async(e,t={})=>{let n={...Id,...t},r=new AbortController,o=setTimeout(()=>r.abort(),Jm);try{let a=await n.fetch(BM,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=pn(i)&&pn(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:JM(s)}}return{verdict:YM.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var Xa=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${Ed.test(n)?n:"default"}/header/models`,a=await yv(o,e,r.clientKey,t);if(a.length>0)return a}return yv(`${ZM(n)}/models`,e,void 0,t)},yv=async(e,t,n,r={})=>{let o={...Id,...r},a=new AbortController,s=setTimeout(()=>a.abort(),Jm);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=pn(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!pn(u))continue;let p=u.id;if(typeof p!="string"||p.length===0||u.model_picker_enabled!==!0)continue;let m=u.policy;if(pn(m)&&m.state!=="enabled")continue;let f=u.supported_endpoints,h=Array.isArray(f)?f.filter(x=>typeof x=="string"):[],w=u.capabilities,y=pn(w)?w.limits:void 0,g=x=>{let _=pn(y)?y[x]:void 0;return typeof _=="number"&&Number.isFinite(_)&&_>0?Math.floor(_):void 0},b={id:p,endpoints:h},k=g("max_prompt_tokens"),A=g("max_output_tokens");k!==void 0&&(b.maxPromptTokens=k),A!==void 0&&(b.maxOutputTokens=A),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},xd=async(e,t,n,r={})=>{let o={...Id,...r},a=new AbortController,s=setTimeout(()=>a.abort(),Jm);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)}},Rd=async(e={},t={})=>{let n={...Id,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return Ja(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:wv,read:()=>n.tokenFromKeychain()}]:[],{source:gv,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await Xm(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 Od,platform as kv}from"node:os";import{join as yt}from"node:path";import{execFile as XM}from"node:child_process";import{readFile as zM,readdir as qM}from"node:fs/promises";var QM=3e3,eB="Claude Code-credentials",tB=["copilot-cli","CopilotCLI"],vv=e=>new Promise(t=>{try{XM("security",["find-generic-password","-s",e],{timeout:QM},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),nB=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=yt(Od(),".claude");return!!(await R(yt(e,".oauth_token"))||await R(yt(e,".credentials.json"))||kv()==="darwin"&&await vv(eB))},rB=async()=>{let e=yt(process.env.CODEX_HOME?.trim()||yt(Od(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await zM(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},Av=async e=>{try{return(await qM(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},zm=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of Ho){let n=yt(Ue(t),"User","globalStorage");if(await R(yt(n,"github.copilot-chat"))||await R(yt(n,"github.copilot")))return!0}let e=yt(Od(),".config","github-copilot");if(await R(yt(e,"apps.json"))||await R(yt(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await Av(yt(Od(),t,"extensions")))return!0;for(let t of Ho){if(await Av(Sk(t)))return!0;let n=yt(Va(t,!0),"globalStorage");if(await R(yt(n,"github.copilot-chat"))||await R(yt(n,"github.copilot")))return!0}if(kv()==="darwin"){for(let t of tB)if(await vv(t))return!0}return!1},Wn=async()=>{let[e,t,n]=await Promise.all([nB(),rB(),zm()]);return{anthropic:e,openai:t,copilot:n}};var jo="copilot-cli",Un="copilot-cli",cB=_i,lB=()=>cB()?["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."]:[],Dv=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],oh=()=>Object.fromEntries(Dv.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),qm=()=>rh(nh(),".anyray","copilot-cli.sh"),Lv="# Managed by anyray-connect. Do not source this file anywhere else.",Ev=e=>e.split(/\r?\n/,1)[0]===Lv,dB=["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"],_d="COPILOT_PROVIDER_API_KEY",xv=e=>e.startsWith(`export ${_d}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),hr=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",uB=()=>Li()[0],Mi=(e="default")=>`/copilot/${e}/header`,j7=Mi(),Ko=e=>e.replace(/\/+$/,""),pB=(e,t="default")=>`${Ko(e.openaiBaseUrl)}${Mi(t)}`,Qm=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),th="claude-sonnet-5",fB=()=>{let e=Li()[0];return e===Di?th:e},Nv=e=>e.endpoints.includes(hr(e.id)==="responses"?"/responses":"/chat/completions"),ah=e=>{let t=e.filter(Nv),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)=>Rv(a.version,s.version)?-1:Rv(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var Rv=(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},Ov=(e,t,n,r,o,a="default")=>{let s=be({...e.metadata,tool:jo}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...Dv];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${$e(pB(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${hr(t)}'`,`export COPILOT_MODEL=${$e(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=${$e(i.join(`
|
|
115
|
+
`))}`]:[],`export ${_d}=${$e(n)}`]},eh=(e,t,n)=>{let r=be({...e.metadata,tool:jo});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${$e(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${hr(t)}'`,`export COPILOT_MODEL=${$e(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${$e(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${_d}=${$e(n)}`]:[]]},mB=(e,t)=>t||!ae(e,"copilot"),_v=()=>{let e=dB.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).`]},Tv=(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 ${jo}\`), 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`."],hB=(e=process.env.PATH,t=Pv())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(sB)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=iB(o,n);try{if(!aB(a).isFile())continue;return oB(a,t==="win32"?Sv.F_OK:Sv.X_OK),a}catch{}}},yB=()=>rh(nh(),".copilot","config.json"),fn=()=>rh(nh(),".copilot","mcp-config.json"),Vo="anyray",gB=()=>({type:"local",...We("profile"),tools:["*"]}),ao=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wB=async()=>{let e=fn(),t;try{t=await F(e)}catch{return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because ${e} could not be parsed; it was left unchanged.`,reason:"unreadable"}}if("mcpServers"in t&&!ao(t.mcpServers))return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because mcpServers in ${e} is not an object; it was left unchanged.`,reason:"unreadable"};let r=(ao(t.mcpServers)?t.mcpServers:{})[Vo];return r!==void 0&&!vt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${Vo} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched. Rename that entry, then re-run anyray-connect.`,reason:"foreign"}:{status:"installable",json:t}},bB=async e=>{let t=fn(),n=e.json,r=ao(n.mcpServers)?n.mcpServers:{};r[Vo]=gB(),n.mcpServers=r,await q(t,n)},CB=async()=>{let e=fn(),t;try{let r=await F(e);if(!ao(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!ao(n)||!(Vo in n)||!vt(n[Vo],"profile")?!1:(delete n[Vo],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await $i(e,{force:!0}):await q(e,t,{backup:!1}),await pe(e),!0)},AB={resolveCopilotCommand:hB,platform:Pv,detectCopilotSeat:zm,discoverSeatToken:Rd,readDeviceLoginToken:Sd,fetchSeatModelCatalog:Xa,probeSeatChatModel:xd},kB=e=>`'${e.replace(/'/g,"''")}'`,vB=e=>e.split(`
|
|
116
|
+
`).map(kB).join(" + [Environment]::NewLine + "),SB=(e={})=>{let t={...AB,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await mi(ft(),Un))?.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&&Ko(s)===`${Ko(i)}/v1`,a=(s,i)=>s!==void 0&&Qm(s)&&Ko(s).startsWith(`${Ko(i)}/v1/copilot/`);return{id:jo,title:"GitHub Copilot CLI",automatic:!0,skillsDir(){return jt()},async syncOrgMcp({ownerOrigins:s,entry:i}){let c=fn(),l=await F(c),d=xn(l,"mcpServers",s,i&&{type:"http",url:i.url,headers:{[Kt]:i.clientKey},tools:["*"]});return d==="changed"&&await q(c,l,{backup:!1}),{changed:d==="changed"}},changesBilling:!1,quitGated:{isRunning:_i,quitTarget:Cd},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=yB();return await R(i)?{installed:!0,detail:i}:{installed:!1,detail:"no `copilot` on PATH and no ~/.copilot state"}},async apply(s,i){let c=ft(),l=async(x,_,S)=>{let I=x.filter(xv),E=x.filter(we=>!xv(we)),O=qm(),K=[...E,...I.length>0?[`[ -r ${$e(O)} ] && . ${$e(O)}`]:[]],G=await R(O),X=G?await Iv(O,"utf8"):void 0,re=X===void 0||Ev(X);if(I.length>0&&!re)return{status:"manual",messages:[`Refused to overwrite user-managed ${O}; move or rename that file, then run Connect again.`]};let ke=te(),fe=ke?await wB():void 0,W=fe?.status==="skipped"?fe.reason==="foreign"?"mcp_foreign":"mcp_unreadable":void 0,Q=[`${c} \u2190 managed Anyray block (${Un})`,..._.map(we=>` ${we}`),...I.length>0?[`${O} \u2190 owner-only credential (mode 0600)`]:[],...S,fe?.status==="skipped"?fe.message:ke?`${fn()} \u2190 Anyray retrieval MCP server (anyray_retrieve / anyray_recall)`:`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${De()}). 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.`,...lB()];if(i.dryRun)return{status:"configured",messages:Q,...W?{errorClass:W}:{}};let ye=!1;fe?.status==="installable"&&(await bB(fe),ye=!0);try{I.length>0?await Se(O,[Lv,...I,""].join(`
|
|
117
|
+
`)):G&&re&&await $i(O,{force:!0}),await zl(c,K,Un)}catch(we){try{X!==void 0&&re?await Se(O,X):re&&await $i(O,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw we}return{status:"configured",messages:Q,changedFiles:[c,...I.length>0||G&&re?[O]:[],...ye?[fn()]:[]],...W?{errorClass:W}:{}}},d=await r(),u=d!==void 0&&!Qm(d),p=s.authMode==="placeholder",m=u,f=u&&(!m||!ae(s,"copilot")),h=p?void 0:await t.readDeviceLoginToken().catch(()=>{}),w=p||f&&!h?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),y=w.token,g=w.rejected;if(y){let x=w.capiSegment??"default",_=fB(),S=_!==th||!!process.env.ANYRAY_COPILOT_MODEL,I=await t.fetchSeatModelCatalog(y.token,{},x,{laneOrigin:Ko(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),E=I.find(W=>W.id===_);if(!S){let W=ah(I);if(E=W[0],!i.dryRun&&W.length>0){let Q=Ee=>`${Ko(s.origin)}/v1${Mi(x)}/${hr(Ee)==="responses"?"responses":"chat/completions"}`,ye={...oh(),authorization:`Bearer ${y.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},we=new Set,Y;for(let Ee of W.slice(0,4)){let an=await t.probeSeatChatModel(Q(Ee.id),ye,Ee.id);if(an==="ok"){Y=Ee;break}if(an==="unreachable")break;we.add(Ee.id)}E=Y??W.find(Ee=>!we.has(Ee.id))??W[0]}_=E?.id??th}let O=s.clientKey??s.placeholderKey,K=O&&s.clientKey?Yt(O):O,G=Ov(s,_,y.token,O,E,x),X=Ov(s,_,Yt(y.token),K,E,x),re=hr(_),ke=I.filter(W=>Nv(W)&&hr(W.id)===re).map(W=>W.id).filter(W=>W!==_),fe=[`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: ${_}${S?" (pinned via ANYRAY_COPILOT_MODEL)":I.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...I.length===0&&bv(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."]:[],...ke.length>0?[`Your plan also serves: ${ke.slice(0,8).join(", ")}${ke.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",...X.map(W=>{let Q=W.indexOf("="),ye=W.slice(7,Q),we=W.slice(Q+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${ye}', ${vB(we)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${y.source}, and the gateway key from \`anyray-connect print-key\`.)`,...fe]}:l(G,X,fe)}if(!mB(s,f)){if(m&&!i.dryRun){let x=ft();if(await hi(x,Un))return{status:"reverted",changedFiles:[x],messages:[`removed a stale Anyray ${Un} block from ${x}`,"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:",...Tv(t.platform(),g),..._v()]}}return{status:"held",messages:[...m&&i.dryRun?[`would remove a stale Anyray ${Un} block from ${ft()} (org lane, not chosen)`]:[],...Tv(t.platform(),g)]}}let b=uB(),k=s.clientKey??s.placeholderKey,A=k&&s.clientKey?Yt(k):k;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...eh(s,b,A).map(x=>{let[_,...S]=x.replace(/^export /,"").split("=");return` setx ${_} "${S.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${_d} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(eh(s,b,k),eh(s,b,A),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===Di?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=ft(),c=qm(),l=await R(c),d=l?Ev(await Iv(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${Un} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${fn()} if registered`,...await R(Za())?[`would remove the Copilot sign-in Connect minted (${Za()})`]:[]]};let u=await hi(i,Un);d&&await $i(c,{force:!0});let p=await CB(),m=Za(),f=await R(m);f&&await $i(m,{force:!0});let h=[...u?[i]:[],...d?[c]:[],...p?[fn()]:[],...f?[m]:[]];return{status:h.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${Un} block from ${i}`:`no Anyray ${Un} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...f?[`removed the Copilot sign-in Connect minted (${m})`]:[],...p?[`removed the Anyray MCP server from ${fn()}`]:[],..._v()],changedFiles:h.length>0?h:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async configuredKeyIsCurrent(s){return Vt([qm(),fn()],s)},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let s=fn();if(!await R(s))return{registered:!1,command:null,reason:"no-config"};try{let i=await F(s),c=ao(i)?i.mcpServers:void 0,l=ao(c)?c[Vo]:void 0;return!ao(l)||!vt(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"]:Qm(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(jo)?!0:!await t.detectCopilotSeat()}}},$v=SB();import{homedir as Hv}from"node:os";import{join as io}from"node:path";import{readFile as Gv}from"node:fs/promises";import{readFile as Mv,rm as IB}from"node:fs/promises";var Bv="// Managed by anyray-connect: OpenCode trim carrier v1",EB=5e3,sh=e=>`${Bv}
|
|
118
118
|
import { spawn } from "node:child_process"
|
|
119
119
|
|
|
120
120
|
const hookCommand = ${JSON.stringify([e.command,...e.args])}
|
|
@@ -186,23 +186,23 @@ export const AnyrayTrimPlugin = async () => ({
|
|
|
186
186
|
},
|
|
187
187
|
})
|
|
188
188
|
`,Bi=async e=>await R(e)?(await Mv(e,"utf-8")).startsWith(`${Bv}
|
|
189
|
-
`)?"owned":"foreign":"absent",Fv=async(e,t)=>{let n=sh(t),r=await Bi(e);return r==="foreign"?"foreign":r==="owned"&&await Mv(e,"utf-8")===n?"unchanged":(await Se(e,n),"installed")},ih=async e=>{let t=await Bi(e);return t!=="owned"?t:(await IB(e,{force:!0}),"removed")};var lh="https://opencode.ai/config.json",wr="x-anyray-metadata",Xt="x-anyray-api-key",dh=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],yr="Authorization",so=["anthropic","openai"],br="github-copilot",xB="header",gr="anyray",RB=()=>process.env.XDG_CONFIG_HOME?.trim()||io(Hv(),".config"),OB=()=>process.env.XDG_DATA_HOME?.trim()||io(Hv(),".local","share"),Dd=()=>io(RB(),"opencode"),Td=()=>io(Dd(),"plugins","anyrayTrim.js"),Kv=()=>io(OB(),"opencode"),Vv=async()=>{try{let e=await Gv(io(Kv(),"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}}},Wv=async()=>(await Vv()).chatGptOAuth,_B=["opencode.jsonc","opencode.json","config.json"],jo=async()=>{let e=Dd(),t=[];for(let n of _B){let r=io(e,n);await R(r)&&t.push(r)}return t},ch=async()=>(await jo())[0]??io(Dd(),"opencode.json"),uh=()=>Cv(process.env.ANYRAY_COPILOT_PLAN),ph=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${uh()}/${xB}`,H=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gh=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},TB=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===so[0]||n===so[1]||n===br?[]:H(r)&&H(r.options)&&gh(r.options.baseURL,t)?[n]:[]),fh=/claude/i,wh=["model","small_model"],jv=(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)||!fh.test(o)))return`${so[0]}/${o}`},mh=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)mh(n,t);return t}if(!H(e))return t;for(let[n,r]of Object.entries(e))wh.includes(n)&&typeof r=="string"?t.push(r):mh(r,t);return t},PB=(e,t,n)=>{if(!H(e)||!H(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>fh.test(a)))return!1;let o=`${n}/`;return mh(t).filter(a=>a.startsWith(o)).every(a=>fh.test(a.slice(o.length)))},hh=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>hh(o,t,n));if(!H(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=wh.includes(o)?jv(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=hh(a,t,n)}return r},yh=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>yh(o,t[a],n));if(!H(e)||!H(t))return e;let r={};for(let[o,a]of Object.entries(e))wh.includes(o)&&typeof a=="string"&&jv(t[o],n)===a?r[o]=t[o]:r[o]=yh(a,t[o],n);return r},DB=e=>{if(H(e))for(let t of so){let n=e[t];if(H(n)&&H(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Fi=e=>{if(!H(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&vt({command:t,args:n},"profile")},Pd=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),LB=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return H(t)&&t.tool==="opencode"}catch{return!1}},bh=e=>ae(e,"copilot")&&!!e.clientKey,NB=e=>e.byoUpstream?[]:ae(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".`]:[],$B=(e,t)=>ae(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.`]:[],MB=e=>bh(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."]:[],BB=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=lh);let o;if(n)if("mcp"in r&&!H(r.mcp))o="malformed";else{let g=H(r.mcp)?{...r.mcp}:{},b=g[gr];b!==void 0&&!Fi(b)?o="foreign":(g[gr]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=g)}else if(H(r.mcp)&&Fi(r.mcp[gr])){let g={...r.mcp};delete g[gr],Object.keys(g).length===0?delete r.mcp:r.mcp=g}let a=H(r.provider)?{...r.provider}:{},s=TB(a,t.origin),i=s.every(g=>PB(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=hh(r,i,l)}let d=[],u=[],p=t.openaiBaseUrl,m=t.clientKey??t.placeholderKey,f=be({...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 A=H(k.headers)?{...k.headers}:{},E=!1;for(let[O,S]of[[Xt,m],...f?[[wr,f]]:[]])O in A?(typeof A[O]!="string"||A[O].trim()==="")&&u.push(`${g}.${O}`):(A[O]=S,d.push(`${g}.${O}`),E=!0);E&&(k.headers=A,b.options=k,a[g]=b)}let h=c.length>0?[]:so.filter(g=>g!=="openai"||!ae(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 A=H(k.headers)?{...k.headers}:{};if(g==="anthropic"&&w)k.apiKey=w.key,A[yr]=`Bearer ${w.key}`,A["x-anyray-provider"]="anthropic",A["x-anyray-auth-mode"]="passthrough",A["x-anyray-custom-host"]=w.url;else{k.apiKey=m,"x-anyray-custom-host"in A&&delete A[yr];for(let E of dh)delete A[E]}A[Xt]=m,f&&(A[wr]=f),k.headers=A,b.options=k,a[g]=b}let y=c.length===0&&bh(t);if(y){let g=H(a[br])?{...a[br]}:{},b=H(g.options)?{...g.options}:{};b.baseURL=ph(t);let k=H(b.headers)?{...b.headers}:{};k[Xt]=t.clientKey,f&&(k[wr]=f),b.headers=k,g.options=b,a[br]=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}},FB=["baseURL","apiKey"],Uv=(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?.[Xt],m=Pd(p);if(d&&(delete c.baseURL,l=!0),u&&(d||m)){let f=u,h=H(r)?r.options:void 0,w=H(h)&&H(h.headers)?h.headers:void 0;for(let y of[Xt,wr])w&&y in w?f[y]!==w[y]&&(f[y]=w[y],l=!0):y in f&&(delete f[y],l=!0);Object.keys(f).length===0?delete c.headers:c.headers=f}}else{let d=H(r)?r.options:void 0,u=H(d)?d:{},p=H(c.headers)?c.headers:{},m=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof p[Xt]=="string"||typeof p[wr]=="string"||dh.some(f=>f in p);if(!o&&!m)return!1;for(let f of FB)f in u?c[f]!==u[f]&&(c[f]=u[f],l=!0):f in c&&(delete c[f],l=!0);if(H(c.headers)){let f={...c.headers},h=H(u.headers)?u.headers:{};"x-anyray-custom-host"in f&&yr in f&&(yr in h?f[yr]!==h[yr]&&(f[yr]=h[yr],l=!0):(delete f[yr],l=!0));for(let w of[Xt,wr,...dh])w in h?f[w]!==h[w]&&(f[w]=h[w],l=!0):w in f&&(delete f[w],l=!0);Object.keys(f).length===0?delete c.headers:c.headers=f}}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},WB=(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!(Xt in s)&&Pd(a[Xt])&&(delete a[Xt],i=!0),!(wr in s)&&LB(a[wr])&&(delete a[wr],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},UB=(e,t)=>{let n={...e},r=!1,o=DB(e.provider);if(H(n.mcp)&&Fi(n.mcp[gr])){let c={...n.mcp};delete c[gr],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===lh&&so.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 so)Uv(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...so,br]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;WB(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&H(u)&&H(u.options)&&gh(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=yh(n,t,l))}return Uv(a,br,!0,s[br])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===lh&&(delete n.$schema,r=!0),{next:n,removed:r}},Yv={id:"opencode",title:"OpenCode",automatic:!0,skillsDir(){return jt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=await ch(),r=await Me(n),o=structuredClone(r.data);return xn(o,"mcp",e,t&&{type:"remote",url:t.url,enabled:!0,headers:{[Kt]:t.clientKey}})!=="changed"?{changed:!1}:!r.existed&&t===void 0?{changed:!1}:{changed:await Jt(n,r,o,!1)}},async detect(){let e=Dd(),t=Kv(),n=await R(e)||await R(t),r=n&&await Wv();return{installed:n,detail:n?`${await ch()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await ch(),r=e.openaiBaseUrl,o=be({...e.metadata,tool:"opencode"}),a=bh(e),s=ae(e,"openai"),i=await Wv(),c;try{c=await Me(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(ph(e))}, "headers": { "${Xt}": "<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 In()?We("profile"):void 0,{next:d,customProviders:u,migratedProviders:p,modelRefsRemapped:m,customHeadersAdded:f,customHeaderConflicts:h,mcpConflict:w}=BB(c.data,e,l),y=u.length>0,g=p.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${p.map(I=>`provider.${I}`).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.`,...m.length>0?[`Updated model references: ${m.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(I=>`provider.${I}`).join(", ")}; existing provider values were preserved.`,f.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${f.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)"}`,...NB(e),...$B(e,i),a?`provider.github-copilot options.baseURL \u2192 ${ph(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. ${uh()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${uh()} 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).",...MB(e),"Restart OpenCode (or start a new session) to pick up the change."];w==="foreign"?b.push(`MCP name conflict in ${n}: mcp.${gr} is not owned by Anyray Connect, so it was left untouched. Rename that entry, then re-run anyray-connect to register Anyray retrieval.`):w==="malformed"?b.push(`Could not register the Anyray retrieval MCP server in ${n}: the top-level "mcp" value is not an object, so there is nothing to add a server to. Fix that value (or remove it) and re-run anyray-connect; nothing there was replaced.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let k=h.length>0?"manual":"configured",A=w==="foreign"?"mcp_foreign":w==="malformed"?"mcp_unreadable":void 0;if(t.dryRun)return{status:k,messages:b,...A?{errorClass:A}:{}};let O=await Jt(n,c,d,!0)?[n]:[],S=Td();if(te())try{let I=await Fv(S,ni(nt,["opencode"]));I==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${S} already exists and is not owned by Anyray.`):(I==="installed"&&O.push(S),b.push(`The OpenCode tool.execute.after carrier is active in ${S}; 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 ${S}. Gateway-side optimization remains active.`)}else{try{await ih(S)==="removed"&&O.push(S)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${De()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:k,messages:b,changedFiles:O,...A?{errorClass:A}:{}}},async pointsAt(e){for(let t of await jo())try{let{data:n}=await Me(t);if(!H(n.provider))continue;for(let r of Object.values(n.provider))if(!(!H(r)||!H(r.options))&&gh(r.options.baseURL,e))return!0}catch{}return!1},async configuredKeyIsCurrent(e){return Vt(await jo(),e)},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 Me(r);if(!H(o.mcp))continue;let a=o.mcp[gr];if(!Fi(a)||!H(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 Bi(Td());e=i==="absent"?"missing":i,e==="owned"&&(t=await Gv(Td(),"utf-8")===sh(ni(nt,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await jo()){let c;try{c=await Me(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[gr];if(l!==void 0)if(Fi(l))if(n=!0,!H(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;Ta({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 In()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await Vv(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await jo()){let{data:o}=await Me(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===br&&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===br&&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(Pd(c[Xt])||Pd(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=Td(),r="absent";try{r=await Bi(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 Me(i)}catch{s.push(i);continue}let{next:l,removed:d}=UB(c.data,await Ha(i));d&&(await Jt(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await pe(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 ih(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 Eh}from"node:os";import{join as Hi}from"node:path";import{homedir as HB}from"node:os";import{dirname as GB,join as co}from"node:path";import{mkdir as KB,readdir as VB,readFile as Jv,rm as Xv}from"node:fs/promises";var Ch="ec1085ae001eb632d9ab635be7121f621db3ee3430c4865585e8961171a94532",Zv=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1mYWJsZS01LTEiLAogICAgICAgICAgICAibmFtZSI6ICJDbGF1ZGUgRmFibGUgNS4xIChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDEwMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtb3B1cy01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIE9wdXMgNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiY2xhdWRlLXNvbm5ldC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA1IChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDEwMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBTb25uZXQgNC41IChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDIwMDAwMCwKICAgICAgICAgICAgIm1heFRva2VucyI6IDY0MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiY2xhdWRlLWhhaWt1LTQtNSIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBIYWlrdSA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtb3B1cy00LTgiLAogICAgICAgICAgICAibmFtZSI6ICJDbGF1ZGUgT3B1cyA0LjggKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMTAwMDAwMCwKICAgICAgICAgICAgIm1heFRva2VucyI6IDEyODAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXa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udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMSIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdh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G9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Ah=".anyray-source-sha",Hn=()=>co(HB(),".anyray","openclaw-plugin"),zv=async(e=Hn())=>{try{if((await Jv(co(e,Ah),"utf8")).trim()===Ch)return"current"}catch{}for(let t of Zv){let n=co(e,t.path);await KB(GB(n),{recursive:!0,mode:448}),await Se(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await Se(co(e,Ah),`${Ch}
|
|
190
|
-
`),"installed"},Wi=async(e,t=[])=>{let n=[],r=async a=>{let s=co(a,"plugins","anyray","catalog.json");try{await Xv(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await VB(co(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(co(e,"agents",a,"agent"));return n},Ld=async(e=Hn())=>{try{await Jv(co(e,Ah),"utf8")}catch{return!1}return await Xv(e,{recursive:!0,force:!0}),!0};var vh="x-anyray-metadata",Xa="x-anyray-api-key",Sh=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Zo="Authorization",Jo="anthropic-beta",$d="interleaved-thinking-2025-05-14",Md=["anthropic","openai"],Qv="short",xh="anthropic-messages",Rh=128e3,Bd="anthropic/claude-sonnet-4-5",Oh=["anthropic/claude-haiku-4-5"],_h="anyray/claude-sonnet-4-5",Th=["anyray/claude-haiku-4-5"],jB=[Bd,_h],YB=[Oh,Th],ot="anyray",lo="ANYRAY_API_KEY",mn="anyray",Gi=e=>N(e)&&vt({command:e.command,args:e.args},"profile"),Ui="openclaw",Yo=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Hi(Eh(),".openclaw"),Gn=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Hi(Yo(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qv=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Ih=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},ZB=e=>e==="~"||e.startsWith("~/")?Hi(Eh(),e.slice(1)):e,Nd=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(ZB(o))}return n},JB=(e,t,n,r)=>{let o=t.clientKey??t.placeholderKey,a=be({...t.metadata,tool:Ui}),s=t.byoUpstream,i=[],c=[],l=!1,d={...e},u=[];"models"in d&&!N(d.models)&&u.push("models");let p=N(d.models)?{...d.models}:{};if("providers"in p&&!N(p.providers)&&u.push("models.providers"),u.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:u,pluginConfigured:!1,mcpConfigured:!1,mcpConflict:!1};let m=N(p.providers)?{...p.providers}:{},f=!1;if(n){let S=N(d.plugins)?{...d.plugins}:{},I=N(S.load)?{...S.load}:{},x=N(S.entries)?{...S.entries}:{},_=N(x[ot])?{...x[ot]}:{},K=N(_.config)?{..._.config}:{};if("plugins"in d&&!N(d.plugins)||"load"in S&&!N(S.load)||"paths"in I&&!Array.isArray(I.paths)||"entries"in S&&!N(S.entries)||ot in x&&!N(x[ot])||"config"in _&&!N(_.config)||"env"in d&&!N(d.env))u.push("plugins");else{let G=Array.isArray(I.paths)?[...I.paths]:[];G.includes(n)||G.push(n),I.paths=G,S.load=I,_.enabled=!0,K.gatewayUrl=t.anthropicBaseUrl,K.apiKey=o;let X=t.metadata.user,re=t.metadata.team;X&&(K.user=X),re&&(K.team=re),_.config=K,x[ot]=_,S.entries=x,d.plugins=S;let ke=N(d.env)?{...d.env}:{};ke[lo]=o,d.env=ke,f=!0}}let h=!1,w=!1;if(r)if("mcp"in d&&!N(d.mcp)||N(d.mcp)&&"servers"in d.mcp&&!N(d.mcp.servers))u.push("mcp.servers");else{let S=N(d.mcp)?{...d.mcp}:{},I=N(S.servers)?{...S.servers}:{},x=I[mn];x!==void 0&&!Gi(x)?w=!0:(I[mn]={command:r.command,args:[...r.args],transport:"stdio",enabled:!0},S.servers=I,d.mcp=S,h=!0)}else if(N(d.mcp)&&N(d.mcp.servers)&&Gi(d.mcp.servers[mn])){let S={...d.mcp},I={...S.servers};delete I[mn],Object.keys(I).length===0?delete S.servers:S.servers=I,Object.keys(S).length===0?delete d.mcp:d.mcp=S}let y=Md.filter(S=>S!=="openai"||!ae(t,"openai"));for(let S of y){if(S in m&&!N(m[S])){u.push(`models.providers.${S}`);continue}let I=N(m[S])?{...m[S]}:{};if("headers"in I&&!N(I.headers)){c.push(S);continue}let x=N(I.headers)?{...I.headers}:{};if(I.baseUrl=S==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,S==="anthropic"&&(I.api=xh,(typeof I.maxTokens!="number"||I.maxTokens<=0)&&(I.maxTokens=Rh)),S==="anthropic"&&s)I.apiKey=s.key,x[Zo]=`Bearer ${s.key}`,x["x-anyray-provider"]="anthropic",x["x-anyray-auth-mode"]="passthrough",x["x-anyray-custom-host"]=s.url;else{I.apiKey=o,"x-anyray-custom-host"in x&&delete x[Zo];for(let _ of Sh)delete x[_]}x[Xa]=o,a&&(x[vh]=a),S==="anthropic"&&(Jo in x?l=x[Jo]!==$d:x[Jo]=$d),I.headers=x,m[S]=I,i.push(S)}p.providers=m,d.models=p;let g=!1,b=!1,k=!1,A,E=[],O="agents"in d&&!N(d.agents)||N(d.agents)&&"defaults"in d.agents&&!N(d.agents.defaults)||N(d.agents)&&N(d.agents.defaults)&&("params"in d.agents.defaults&&!N(d.agents.defaults.params)||"model"in d.agents.defaults&&!N(d.agents.defaults.model));if(O&&u.push("agents.defaults"),i.includes("anthropic")&&!O){let S=N(d.agents)?{...d.agents}:{},I=N(S.defaults)?{...S.defaults}:{},x=N(I.params)?{...I.params}:{};"cacheRetention"in x||(x.cacheRetention=Qv,g=!0,I.params=x);let _=N(I.model)?{...I.model}:{},K=f?[...i,ot]:i,G=X=>typeof X=="string"&&K.some(re=>X.startsWith(`${re}/`));typeof _.primary!="string"||_.primary.trim()===""?(_.primary=f?_h:Bd,b=!0,I.model=_,"fallbacks"in _||(_.fallbacks=f?[...Th]:[...Oh],k=!0)):G(_.primary)||(A=_.primary),E=(Array.isArray(_.fallbacks)?_.fallbacks:[]).filter(X=>typeof X=="string"&&!G(X)),(g||b)&&(S.defaults=I,d.agents=S)}return{next:d,routed:i,cacheRetentionSeeded:g,betaPreserved:l,headerConflicts:c,primarySeeded:b,fallbacksSeeded:k,unroutedPrimary:A,unroutedFallbacks:E,structureConflicts:u,pluginConfigured:f,mcpConfigured:h,mcpConflict:w}},XB=["baseUrl","apiKey","api","maxTokens"],kh=(e,t,n=Md,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=Ih(t),l=!1;for(let u of a?n:[]){let p=i[u];if(!N(p))continue;let m={...p},f=N(m.headers)?{...m.headers}:{};if(!(t!==void 0||typeof f[Xa]=="string"||typeof f[vh]=="string"||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_")||Sh.some(A=>A in f)))continue;let w=N(c[u])?c[u]:{},y=N(w.headers)?w.headers:{},g="x-anyray-custom-host"in f,b=A=>A==="api"?m.api===xh:A==="maxTokens"?m.maxTokens===Rh:A==="apiKey"?g||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_"):!0;for(let A of XB)b(A)&&(A in w?m[A]!==w[A]&&(m[A]=w[A],l=!0):A in m&&(delete m[A],l=!0));let k=[Xa,vh,...Sh,..."x-anyray-custom-host"in f?[Zo]:[]];f[Jo]===$d&&k.push(Jo);for(let A of k)A in y?f[A]!==y[A]&&(f[A]=y[A],l=!0):A in f&&(delete f[A],l=!0);Zo in y&&!(Zo in f)&&(f[Zo]=y[Zo],l=!0),Object.keys(f).length===0?delete m.headers:m.headers=f,Object.keys(m).length===0?delete i[u]:i[u]=m}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}:{},m=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=m[ot];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:{};ot in b?JSON.stringify(m[ot])!==JSON.stringify(b[ot])&&(m[ot]=b[ot],l=!0):(delete m[ot],l=!0)}}if(Object.keys(p).length===0?delete u.load:u.load=p,Object.keys(m).length===0?delete u.entries:u.entries=m,Object.keys(u).length===0?delete o.plugins:o.plugins=u,N(o.env)){let w={...o.env},y=w[lo];if(typeof y=="string"&&y.startsWith("ark_")){let g=N(t?.env)?t.env:{};lo in g?w[lo]!==g[lo]&&(w[lo]=g[lo],l=!0):(delete w[lo],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}if(n.includes("anthropic")&&N(o.mcp)&&N(o.mcp.servers)&&Gi(o.mcp.servers[mn])){let u={...o.mcp},p={...u.servers};delete p[mn],Object.keys(p).length===0?delete u.servers:u.servers=p,Object.keys(u).length===0?delete o.mcp:o.mcp=u,l=!0}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}:{},m=N(p.params)?{...p.params}:{},f=N(t.agents)?t.agents:{},h=N(f.defaults)?f.defaults:{},w=N(h.params)?h.params:{};m.cacheRetention===Qv&&("cacheRetention"in w?m.cacheRetention!==w.cacheRetention&&(m.cacheRetention=w.cacheRetention,l=!0):(delete m.cacheRetention,l=!0));let y=N(p.model)?{...p.model}:{},g=N(h.model)?h.model:{};jB.includes(y.primary)&&("primary"in g?y.primary!==g.primary&&(y.primary=g.primary,l=!0):(delete y.primary,l=!0)),YB.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(m).length===0?delete p.params:p.params=m,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}},eS={id:Ui,title:"OpenClaw",automatic:!0,skillsDir(){return process.env.OPENCLAW_STATE_DIR?.trim()?Hi(Yo(),"skills"):jt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=Gn(),r=await Me(n),o=structuredClone(r.data);if(o.mcp!==void 0&&!N(o.mcp))return{changed:!1};let a=N(o.mcp)?o.mcp:{};return xn(a,"servers",e,t&&{url:t.url,transport:"streamable-http",headers:{[Kt]:t.clientKey}})!=="changed"?{changed:!1}:(Object.keys(a).length===0?delete o.mcp:o.mcp=a,!r.existed&&t===void 0?{changed:!1}:{changed:await Jt(n,r,o,!1)})},async detect(){let e=await R(Gn())||await R(Yo());return{installed:e,detail:e?Gn():`no ${Hi(Eh(),".openclaw")} state dir`}},async apply(e,t){let n=Gn();if(!e.byoUpstream&&ae(e,"anthropic")){let x=["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 ${Ui}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],_;try{_=await Me(n)}catch{return{status:"held",messages:x}}let{next:K,removed:G}=kh(_.data,await Ha(n),Md,Hn());return G?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...x]}:(await Jt(n,_,K,!1),await pe(n),await Ld(),await Wi(Yo(),Nd(K)),{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.`,...x]}):(t.dryRun||(await Ld(),await Wi(Yo(),Nd(K))),{status:"held",messages:x})}let r=Hn(),o=!1;if(!t.dryRun)try{await zv(r)}catch{r=void 0,o=!0}let a=await In()?We("profile"):void 0,s;try{s=await Me(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${xh}", "maxTokens": ${Rh}, "apiKey": "<your personal ark_ key>", "headers": { "${Xa}": "<your personal ark_ key>", "${Jo}": "${$d}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${Xa}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Bd}") 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.",...a?[`Under "mcp.servers" add "${mn}": { "command": ${JSON.stringify(a.command)}, "args": ${JSON.stringify(a.args)}, "transport": "stdio", "enabled": true } so optimizer trims stay recoverable.`]:[],"Then run `openclaw config validate`."]}}let{next:i,routed:c,cacheRetentionSeeded:l,betaPreserved:d,headerConflicts:u,primarySeeded:p,fallbacksSeeded:m,unroutedPrimary:f,unroutedFallbacks:h,structureConflicts:w,pluginConfigured:y,mcpConfigured:g,mcpConflict:b}=JB(s.data,e,r,a),k=i,A=!1;if(!c.includes("openai")){let x=kh(k,await Ha(n),["openai"]);x.removed&&(k=x.next,A=!0)}let E=[c.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: ${be({...e.metadata,tool:Ui})??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...l?['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."],...d?[`Kept your existing ${Jo} header value (OpenClaw suppresses its implicit beta headers off-host; yours replaces our default restore).`]:[],...u.length>0?[`Could not add headers on models.providers.${u.join(", ")}: the existing "headers" value is not an object. Fix it manually; nothing there was replaced.`]:[],...p?[`Seeded agents.defaults.model.primary = ${y?_h:Bd} (none was set; routing is inert until the primary resolves to a routed provider).`,...m?[`Seeded agents.defaults.model.fallbacks = [${(y?Th:Oh).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.`]:[],...h.length>0?[`Fallback model(s) ${h.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...A?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...y?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${Hn()}) and registered it under plugins.entries.${ot}: 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).`]:[],...b?[`MCP name conflict in ${n}: mcp.servers.${mn} is not owned by Anyray Connect, so it was left untouched. Rename or remove it to get anyray_retrieve.`]:g?[`Registered the Anyray retrieval MCP server (anyray_retrieve) at mcp.servers.${mn}, so optimizer trims stay recoverable. Restart the OpenClaw gateway, or run \`openclaw mcp reload\`, to connect it.`]:a===void 0?[`Skipped the Anyray retrieval MCP server \u2014 anyray-connect is running from a temporary path (${De()}). Re-run via the installer or a global install so optimizer trims stay recoverable.`]:[],...w.length>0?[`Left ${w.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."],O=u.length>0||w.length>0?"manual":"configured",S=b?"mcp_foreign":void 0;if(t.dryRun)return{status:O,messages:E,...S?{errorClass:S}:{}};let I=await Jt(n,s,k,!0);return y&&await Wi(Yo(),Nd(k)),{status:O,messages:E,changedFiles:I?[n]:[],...S?{errorClass:S}:{}}},async pointsAt(e){try{let{data:t}=await Me(Gn());for(let a of Object.values(Ih(t)))if(N(a)&&qv(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[ot];if(N(o)&&N(o.config)&&qv(o.config.gatewayUrl,e))return!0}catch{}return!1},async configuredKeyIsCurrent(e){return Vt([Gn()],e)},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Gn();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};let t;try{({data:t}=await Me(e))}catch{return{registered:!1,command:null,reason:"unreadable"}}let n=N(t.mcp)?t.mcp:{},o=(N(n.servers)?n.servers:{})[mn];if(o===void 0)return{registered:!1,command:null,reason:"absent"};if(!Gi(o))return{registered:!1,command:null,reason:"foreign"};let a=o.command;return{registered:!0,command:typeof a=="string"?a:null}},async integrationStatus(){let e,t=!0;try{let{data:n}=await Me(Gn()),r=N(n.mcp)?n.mcp.servers:void 0;if(n.mcp!==void 0&&!N(n.mcp)||r!==void 0&&!N(r))e="unreadable";else{let o=N(r)?r[mn]:void 0;if(o===void 0)e="missing";else if(!Gi(o))e="foreign";else{e="owned";let a=o;t=Ta({command:a.command,args:a.args},"profile")}}}catch{e="unreadable"}return{mcp_registration:e,hook_binary:t&&await In()?"owned":"missing"}},async routingExpected(e){return e.includes(Ui)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Me(Gn());for(let a of Object.values(Ih(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[Xa]=="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:{})[ot];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=Gn();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Me(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}=kh(n.data,await Ha(t),Md,Hn()),a=await Ld();return await Wi(Yo(),Nd(r)),o?(await Jt(t,n,r,!1),await pe(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${Hn()}`]:[]],changedFiles:[t]}):(await pe(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${Hn()}`]:[]]})}};import{execFile as UU}from"node:child_process";import{readFile as HU}from"node:fs/promises";import{homedir as cc,platform as mo}from"node:os";import{join as Zn}from"node:path";import{isDeepStrictEqual as Ay,promisify as GU}from"node:util";var Ki=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},Fd=(e,t)=>{let n=Ki(e),r=Ki(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 oU}from"node:crypto";import{promises as pI}from"node:fs";import{platform as fI,tmpdir as aU}from"node:os";import{join as ru}from"node:path";import{execFile as zB}from"node:child_process";import{promises as Vi}from"node:fs";import{homedir as qB,platform as QB}from"node:os";import{delimiter as eF,join as Wd}from"node:path";import{promisify as tF}from"node:util";var nF=tF(zB),rF=15*6e4,oF=64*1024*1024,aF=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],tS=async(e={})=>{let t=(e.home??qB)(),n=e.env??process.env,r=aF(e.runtimePlatform??QB()),o=[Wd(t,".local","bin"),Wd(t,".claude","local"),...(n.PATH??"").split(eF).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Wd(a,`claude${s}`);try{return await Vi.access(i),i}catch{}}return null},sF=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},iF=async e=>{let t=Wd(e,"projects"),n;try{n=(await Vi.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(!dF.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},cF=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 m=a[d];l.push({sessionId:u,transcriptPath:p,title:typeof m=="string"&&m.length>0?m:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:sF(n.projectList)}},lF=async e=>{let t,n;try{let r=await Vi.readFile(e,"utf8");for(let o of r.split(`
|
|
189
|
+
`)?"owned":"foreign":"absent",Fv=async(e,t)=>{let n=sh(t),r=await Bi(e);return r==="foreign"?"foreign":r==="owned"&&await Mv(e,"utf-8")===n?"unchanged":(await Se(e,n),"installed")},ih=async e=>{let t=await Bi(e);return t!=="owned"?t:(await IB(e,{force:!0}),"removed")};var lh="https://opencode.ai/config.json",wr="x-anyray-metadata",Xt="x-anyray-api-key",dh=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],yr="Authorization",so=["anthropic","openai"],br="github-copilot",xB="header",gr="anyray",RB=()=>process.env.XDG_CONFIG_HOME?.trim()||io(Hv(),".config"),OB=()=>process.env.XDG_DATA_HOME?.trim()||io(Hv(),".local","share"),Dd=()=>io(RB(),"opencode"),Td=()=>io(Dd(),"plugins","anyrayTrim.js"),Kv=()=>io(OB(),"opencode"),Vv=async()=>{try{let e=await Gv(io(Kv(),"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}}},Wv=async()=>(await Vv()).chatGptOAuth,_B=["opencode.jsonc","opencode.json","config.json"],Yo=async()=>{let e=Dd(),t=[];for(let n of _B){let r=io(e,n);await R(r)&&t.push(r)}return t},ch=async()=>(await Yo())[0]??io(Dd(),"opencode.json"),uh=()=>Cv(process.env.ANYRAY_COPILOT_PLAN),ph=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${uh()}/${xB}`,H=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gh=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},TB=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===so[0]||n===so[1]||n===br?[]:H(r)&&H(r.options)&&gh(r.options.baseURL,t)?[n]:[]),fh=/claude/i,wh=["model","small_model"],jv=(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)||!fh.test(o)))return`${so[0]}/${o}`},mh=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)mh(n,t);return t}if(!H(e))return t;for(let[n,r]of Object.entries(e))wh.includes(n)&&typeof r=="string"?t.push(r):mh(r,t);return t},PB=(e,t,n)=>{if(!H(e)||!H(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>fh.test(a)))return!1;let o=`${n}/`;return mh(t).filter(a=>a.startsWith(o)).every(a=>fh.test(a.slice(o.length)))},hh=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>hh(o,t,n));if(!H(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=wh.includes(o)?jv(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=hh(a,t,n)}return r},yh=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>yh(o,t[a],n));if(!H(e)||!H(t))return e;let r={};for(let[o,a]of Object.entries(e))wh.includes(o)&&typeof a=="string"&&jv(t[o],n)===a?r[o]=t[o]:r[o]=yh(a,t[o],n);return r},DB=e=>{if(H(e))for(let t of so){let n=e[t];if(H(n)&&H(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Fi=e=>{if(!H(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&vt({command:t,args:n},"profile")},Pd=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),LB=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return H(t)&&t.tool==="opencode"}catch{return!1}},bh=e=>ae(e,"copilot")&&!!e.clientKey,NB=e=>e.byoUpstream?[]:ae(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".`]:[],$B=(e,t)=>ae(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.`]:[],MB=e=>bh(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."]:[],BB=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=lh);let o;if(n)if("mcp"in r&&!H(r.mcp))o="malformed";else{let g=H(r.mcp)?{...r.mcp}:{},b=g[gr];b!==void 0&&!Fi(b)?o="foreign":(g[gr]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=g)}else if(H(r.mcp)&&Fi(r.mcp[gr])){let g={...r.mcp};delete g[gr],Object.keys(g).length===0?delete r.mcp:r.mcp=g}let a=H(r.provider)?{...r.provider}:{},s=TB(a,t.origin),i=s.every(g=>PB(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=hh(r,i,l)}let d=[],u=[],p=t.openaiBaseUrl,m=t.clientKey??t.placeholderKey,f=be({...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 A=H(k.headers)?{...k.headers}:{},x=!1;for(let[_,S]of[[Xt,m],...f?[[wr,f]]:[]])_ in A?(typeof A[_]!="string"||A[_].trim()==="")&&u.push(`${g}.${_}`):(A[_]=S,d.push(`${g}.${_}`),x=!0);x&&(k.headers=A,b.options=k,a[g]=b)}let h=c.length>0?[]:so.filter(g=>g!=="openai"||!ae(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 A=H(k.headers)?{...k.headers}:{};if(g==="anthropic"&&w)k.apiKey=w.key,A[yr]=`Bearer ${w.key}`,A["x-anyray-provider"]="anthropic",A["x-anyray-auth-mode"]="passthrough",A["x-anyray-custom-host"]=w.url;else{k.apiKey=m,"x-anyray-custom-host"in A&&delete A[yr];for(let x of dh)delete A[x]}A[Xt]=m,f&&(A[wr]=f),k.headers=A,b.options=k,a[g]=b}let y=c.length===0&&bh(t);if(y){let g=H(a[br])?{...a[br]}:{},b=H(g.options)?{...g.options}:{};b.baseURL=ph(t);let k=H(b.headers)?{...b.headers}:{};k[Xt]=t.clientKey,f&&(k[wr]=f),b.headers=k,g.options=b,a[br]=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}},FB=["baseURL","apiKey"],Uv=(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?.[Xt],m=Pd(p);if(d&&(delete c.baseURL,l=!0),u&&(d||m)){let f=u,h=H(r)?r.options:void 0,w=H(h)&&H(h.headers)?h.headers:void 0;for(let y of[Xt,wr])w&&y in w?f[y]!==w[y]&&(f[y]=w[y],l=!0):y in f&&(delete f[y],l=!0);Object.keys(f).length===0?delete c.headers:c.headers=f}}else{let d=H(r)?r.options:void 0,u=H(d)?d:{},p=H(c.headers)?c.headers:{},m=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof p[Xt]=="string"||typeof p[wr]=="string"||dh.some(f=>f in p);if(!o&&!m)return!1;for(let f of FB)f in u?c[f]!==u[f]&&(c[f]=u[f],l=!0):f in c&&(delete c[f],l=!0);if(H(c.headers)){let f={...c.headers},h=H(u.headers)?u.headers:{};"x-anyray-custom-host"in f&&yr in f&&(yr in h?f[yr]!==h[yr]&&(f[yr]=h[yr],l=!0):(delete f[yr],l=!0));for(let w of[Xt,wr,...dh])w in h?f[w]!==h[w]&&(f[w]=h[w],l=!0):w in f&&(delete f[w],l=!0);Object.keys(f).length===0?delete c.headers:c.headers=f}}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},WB=(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!(Xt in s)&&Pd(a[Xt])&&(delete a[Xt],i=!0),!(wr in s)&&LB(a[wr])&&(delete a[wr],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},UB=(e,t)=>{let n={...e},r=!1,o=DB(e.provider);if(H(n.mcp)&&Fi(n.mcp[gr])){let c={...n.mcp};delete c[gr],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===lh&&so.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 so)Uv(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...so,br]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;WB(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&H(u)&&H(u.options)&&gh(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=yh(n,t,l))}return Uv(a,br,!0,s[br])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===lh&&(delete n.$schema,r=!0),{next:n,removed:r}},Yv={id:"opencode",title:"OpenCode",automatic:!0,skillsDir(){return jt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=await ch(),r=await Me(n),o=structuredClone(r.data);return xn(o,"mcp",e,t&&{type:"remote",url:t.url,enabled:!0,headers:{[Kt]:t.clientKey}})!=="changed"?{changed:!1}:!r.existed&&t===void 0?{changed:!1}:{changed:await Jt(n,r,o,!1)}},async detect(){let e=Dd(),t=Kv(),n=await R(e)||await R(t),r=n&&await Wv();return{installed:n,detail:n?`${await ch()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await ch(),r=e.openaiBaseUrl,o=be({...e.metadata,tool:"opencode"}),a=bh(e),s=ae(e,"openai"),i=await Wv(),c;try{c=await Me(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(ph(e))}, "headers": { "${Xt}": "<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 In()?We("profile"):void 0,{next:d,customProviders:u,migratedProviders:p,modelRefsRemapped:m,customHeadersAdded:f,customHeaderConflicts:h,mcpConflict:w}=BB(c.data,e,l),y=u.length>0,g=p.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${p.map(I=>`provider.${I}`).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.`,...m.length>0?[`Updated model references: ${m.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(I=>`provider.${I}`).join(", ")}; existing provider values were preserved.`,f.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${f.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)"}`,...NB(e),...$B(e,i),a?`provider.github-copilot options.baseURL \u2192 ${ph(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. ${uh()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${uh()} 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).",...MB(e),"Restart OpenCode (or start a new session) to pick up the change."];w==="foreign"?b.push(`MCP name conflict in ${n}: mcp.${gr} is not owned by Anyray Connect, so it was left untouched. Rename that entry, then re-run anyray-connect to register Anyray retrieval.`):w==="malformed"?b.push(`Could not register the Anyray retrieval MCP server in ${n}: the top-level "mcp" value is not an object, so there is nothing to add a server to. Fix that value (or remove it) and re-run anyray-connect; nothing there was replaced.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let k=h.length>0?"manual":"configured",A=w==="foreign"?"mcp_foreign":w==="malformed"?"mcp_unreadable":void 0;if(t.dryRun)return{status:k,messages:b,...A?{errorClass:A}:{}};let _=await Jt(n,c,d,!0)?[n]:[],S=Td();if(te())try{let I=await Fv(S,_o(nt,["opencode"]));I==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${S} already exists and is not owned by Anyray.`):(I==="installed"&&_.push(S),b.push(`The OpenCode tool.execute.after carrier is active in ${S}; 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 ${S}. Gateway-side optimization remains active.`)}else{try{await ih(S)==="removed"&&_.push(S)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${De()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:k,messages:b,changedFiles:_,...A?{errorClass:A}:{}}},async pointsAt(e){for(let t of await Yo())try{let{data:n}=await Me(t);if(!H(n.provider))continue;for(let r of Object.values(n.provider))if(!(!H(r)||!H(r.options))&&gh(r.options.baseURL,e))return!0}catch{}return!1},async configuredKeyIsCurrent(e){return Vt(await Yo(),e)},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await Yo();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 Me(r);if(!H(o.mcp))continue;let a=o.mcp[gr];if(!Fi(a)||!H(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 Bi(Td());e=i==="absent"?"missing":i,e==="owned"&&(t=await Gv(Td(),"utf-8")===sh(_o(nt,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await Yo()){let c;try{c=await Me(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[gr];if(l!==void 0)if(Fi(l))if(n=!0,!H(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;Pa({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 In()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await Vv(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await Yo()){let{data:o}=await Me(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===br&&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===br&&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(Pd(c[Xt])||Pd(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 Yo(),n=Td(),r="absent";try{r=await Bi(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 Me(i)}catch{s.push(i);continue}let{next:l,removed:d}=UB(c.data,await Ga(i));d&&(await Jt(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await pe(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 ih(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 Eh}from"node:os";import{join as Hi}from"node:path";import{homedir as HB}from"node:os";import{dirname as GB,join as co}from"node:path";import{mkdir as KB,readdir as VB,readFile as Jv,rm as Xv}from"node:fs/promises";var Ch="ec1085ae001eb632d9ab635be7121f621db3ee3430c4865585e8961171a94532",Zv=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1mYWJsZS01LTEiLAogICAgICAgICAgICAibmFtZSI6ICJDbGF1ZGUgRmFibGUgNS4xIChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDEwMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtb3B1cy01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIE9wdXMgNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiY2xhdWRlLXNvbm5ldC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA1IChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDEwMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBTb25uZXQgNC41IChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDIwMDAwMCwKICAgICAgICAgICAgIm1heFRva2VucyI6IDY0MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiY2xhdWRlLWhhaWt1LTQtNSIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBIYWlrdSA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtb3B1cy00LTgiLAogICAgICAgICAgICAibmFtZSI6ICJDbGF1ZGUgT3B1cyA0LjggKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMTAwMDAwMCwKICAgICAgICAgICAgIm1heFRva2VucyI6IDEyODAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMSIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJ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V0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Ah=".anyray-source-sha",Hn=()=>co(HB(),".anyray","openclaw-plugin"),zv=async(e=Hn())=>{try{if((await Jv(co(e,Ah),"utf8")).trim()===Ch)return"current"}catch{}for(let t of Zv){let n=co(e,t.path);await KB(GB(n),{recursive:!0,mode:448}),await Se(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await Se(co(e,Ah),`${Ch}
|
|
190
|
+
`),"installed"},Wi=async(e,t=[])=>{let n=[],r=async a=>{let s=co(a,"plugins","anyray","catalog.json");try{await Xv(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await VB(co(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(co(e,"agents",a,"agent"));return n},Ld=async(e=Hn())=>{try{await Jv(co(e,Ah),"utf8")}catch{return!1}return await Xv(e,{recursive:!0,force:!0}),!0};var vh="x-anyray-metadata",za="x-anyray-api-key",Sh=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Jo="Authorization",Xo="anthropic-beta",$d="interleaved-thinking-2025-05-14",Md=["anthropic","openai"],Qv="short",xh="anthropic-messages",Rh=128e3,Bd="anthropic/claude-sonnet-4-5",Oh=["anthropic/claude-haiku-4-5"],_h="anyray/claude-sonnet-4-5",Th=["anyray/claude-haiku-4-5"],jB=[Bd,_h],YB=[Oh,Th],ot="anyray",lo="ANYRAY_API_KEY",mn="anyray",Gi=e=>N(e)&&vt({command:e.command,args:e.args},"profile"),Ui="openclaw",Zo=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Hi(Eh(),".openclaw"),Gn=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Hi(Zo(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qv=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Ih=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},ZB=e=>e==="~"||e.startsWith("~/")?Hi(Eh(),e.slice(1)):e,Nd=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(ZB(o))}return n},JB=(e,t,n,r)=>{let o=t.clientKey??t.placeholderKey,a=be({...t.metadata,tool:Ui}),s=t.byoUpstream,i=[],c=[],l=!1,d={...e},u=[];"models"in d&&!N(d.models)&&u.push("models");let p=N(d.models)?{...d.models}:{};if("providers"in p&&!N(p.providers)&&u.push("models.providers"),u.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:u,pluginConfigured:!1,mcpConfigured:!1,mcpConflict:!1};let m=N(p.providers)?{...p.providers}:{},f=!1;if(n){let S=N(d.plugins)?{...d.plugins}:{},I=N(S.load)?{...S.load}:{},E=N(S.entries)?{...S.entries}:{},O=N(E[ot])?{...E[ot]}:{},K=N(O.config)?{...O.config}:{};if("plugins"in d&&!N(d.plugins)||"load"in S&&!N(S.load)||"paths"in I&&!Array.isArray(I.paths)||"entries"in S&&!N(S.entries)||ot in E&&!N(E[ot])||"config"in O&&!N(O.config)||"env"in d&&!N(d.env))u.push("plugins");else{let G=Array.isArray(I.paths)?[...I.paths]:[];G.includes(n)||G.push(n),I.paths=G,S.load=I,O.enabled=!0,K.gatewayUrl=t.anthropicBaseUrl,K.apiKey=o;let X=t.metadata.user,re=t.metadata.team;X&&(K.user=X),re&&(K.team=re),O.config=K,E[ot]=O,S.entries=E,d.plugins=S;let ke=N(d.env)?{...d.env}:{};ke[lo]=o,d.env=ke,f=!0}}let h=!1,w=!1;if(r)if("mcp"in d&&!N(d.mcp)||N(d.mcp)&&"servers"in d.mcp&&!N(d.mcp.servers))u.push("mcp.servers");else{let S=N(d.mcp)?{...d.mcp}:{},I=N(S.servers)?{...S.servers}:{},E=I[mn];E!==void 0&&!Gi(E)?w=!0:(I[mn]={command:r.command,args:[...r.args],transport:"stdio",enabled:!0},S.servers=I,d.mcp=S,h=!0)}else if(N(d.mcp)&&N(d.mcp.servers)&&Gi(d.mcp.servers[mn])){let S={...d.mcp},I={...S.servers};delete I[mn],Object.keys(I).length===0?delete S.servers:S.servers=I,Object.keys(S).length===0?delete d.mcp:d.mcp=S}let y=Md.filter(S=>S!=="openai"||!ae(t,"openai"));for(let S of y){if(S in m&&!N(m[S])){u.push(`models.providers.${S}`);continue}let I=N(m[S])?{...m[S]}:{};if("headers"in I&&!N(I.headers)){c.push(S);continue}let E=N(I.headers)?{...I.headers}:{};if(I.baseUrl=S==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,S==="anthropic"&&(I.api=xh,(typeof I.maxTokens!="number"||I.maxTokens<=0)&&(I.maxTokens=Rh)),S==="anthropic"&&s)I.apiKey=s.key,E[Jo]=`Bearer ${s.key}`,E["x-anyray-provider"]="anthropic",E["x-anyray-auth-mode"]="passthrough",E["x-anyray-custom-host"]=s.url;else{I.apiKey=o,"x-anyray-custom-host"in E&&delete E[Jo];for(let O of Sh)delete E[O]}E[za]=o,a&&(E[vh]=a),S==="anthropic"&&(Xo in E?l=E[Xo]!==$d:E[Xo]=$d),I.headers=E,m[S]=I,i.push(S)}p.providers=m,d.models=p;let g=!1,b=!1,k=!1,A,x=[],_="agents"in d&&!N(d.agents)||N(d.agents)&&"defaults"in d.agents&&!N(d.agents.defaults)||N(d.agents)&&N(d.agents.defaults)&&("params"in d.agents.defaults&&!N(d.agents.defaults.params)||"model"in d.agents.defaults&&!N(d.agents.defaults.model));if(_&&u.push("agents.defaults"),i.includes("anthropic")&&!_){let S=N(d.agents)?{...d.agents}:{},I=N(S.defaults)?{...S.defaults}:{},E=N(I.params)?{...I.params}:{};"cacheRetention"in E||(E.cacheRetention=Qv,g=!0,I.params=E);let O=N(I.model)?{...I.model}:{},K=f?[...i,ot]:i,G=X=>typeof X=="string"&&K.some(re=>X.startsWith(`${re}/`));typeof O.primary!="string"||O.primary.trim()===""?(O.primary=f?_h:Bd,b=!0,I.model=O,"fallbacks"in O||(O.fallbacks=f?[...Th]:[...Oh],k=!0)):G(O.primary)||(A=O.primary),x=(Array.isArray(O.fallbacks)?O.fallbacks:[]).filter(X=>typeof X=="string"&&!G(X)),(g||b)&&(S.defaults=I,d.agents=S)}return{next:d,routed:i,cacheRetentionSeeded:g,betaPreserved:l,headerConflicts:c,primarySeeded:b,fallbacksSeeded:k,unroutedPrimary:A,unroutedFallbacks:x,structureConflicts:u,pluginConfigured:f,mcpConfigured:h,mcpConflict:w}},XB=["baseUrl","apiKey","api","maxTokens"],kh=(e,t,n=Md,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=Ih(t),l=!1;for(let u of a?n:[]){let p=i[u];if(!N(p))continue;let m={...p},f=N(m.headers)?{...m.headers}:{};if(!(t!==void 0||typeof f[za]=="string"||typeof f[vh]=="string"||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_")||Sh.some(A=>A in f)))continue;let w=N(c[u])?c[u]:{},y=N(w.headers)?w.headers:{},g="x-anyray-custom-host"in f,b=A=>A==="api"?m.api===xh:A==="maxTokens"?m.maxTokens===Rh:A==="apiKey"?g||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_"):!0;for(let A of XB)b(A)&&(A in w?m[A]!==w[A]&&(m[A]=w[A],l=!0):A in m&&(delete m[A],l=!0));let k=[za,vh,...Sh,..."x-anyray-custom-host"in f?[Jo]:[]];f[Xo]===$d&&k.push(Xo);for(let A of k)A in y?f[A]!==y[A]&&(f[A]=y[A],l=!0):A in f&&(delete f[A],l=!0);Jo in y&&!(Jo in f)&&(f[Jo]=y[Jo],l=!0),Object.keys(f).length===0?delete m.headers:m.headers=f,Object.keys(m).length===0?delete i[u]:i[u]=m}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}:{},m=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=m[ot];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:{};ot in b?JSON.stringify(m[ot])!==JSON.stringify(b[ot])&&(m[ot]=b[ot],l=!0):(delete m[ot],l=!0)}}if(Object.keys(p).length===0?delete u.load:u.load=p,Object.keys(m).length===0?delete u.entries:u.entries=m,Object.keys(u).length===0?delete o.plugins:o.plugins=u,N(o.env)){let w={...o.env},y=w[lo];if(typeof y=="string"&&y.startsWith("ark_")){let g=N(t?.env)?t.env:{};lo in g?w[lo]!==g[lo]&&(w[lo]=g[lo],l=!0):(delete w[lo],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}if(n.includes("anthropic")&&N(o.mcp)&&N(o.mcp.servers)&&Gi(o.mcp.servers[mn])){let u={...o.mcp},p={...u.servers};delete p[mn],Object.keys(p).length===0?delete u.servers:u.servers=p,Object.keys(u).length===0?delete o.mcp:o.mcp=u,l=!0}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}:{},m=N(p.params)?{...p.params}:{},f=N(t.agents)?t.agents:{},h=N(f.defaults)?f.defaults:{},w=N(h.params)?h.params:{};m.cacheRetention===Qv&&("cacheRetention"in w?m.cacheRetention!==w.cacheRetention&&(m.cacheRetention=w.cacheRetention,l=!0):(delete m.cacheRetention,l=!0));let y=N(p.model)?{...p.model}:{},g=N(h.model)?h.model:{};jB.includes(y.primary)&&("primary"in g?y.primary!==g.primary&&(y.primary=g.primary,l=!0):(delete y.primary,l=!0)),YB.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(m).length===0?delete p.params:p.params=m,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}},eS={id:Ui,title:"OpenClaw",automatic:!0,skillsDir(){return process.env.OPENCLAW_STATE_DIR?.trim()?Hi(Zo(),"skills"):jt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=Gn(),r=await Me(n),o=structuredClone(r.data);if(o.mcp!==void 0&&!N(o.mcp))return{changed:!1};let a=N(o.mcp)?o.mcp:{};return xn(a,"servers",e,t&&{url:t.url,transport:"streamable-http",headers:{[Kt]:t.clientKey}})!=="changed"?{changed:!1}:(Object.keys(a).length===0?delete o.mcp:o.mcp=a,!r.existed&&t===void 0?{changed:!1}:{changed:await Jt(n,r,o,!1)})},async detect(){let e=await R(Gn())||await R(Zo());return{installed:e,detail:e?Gn():`no ${Hi(Eh(),".openclaw")} state dir`}},async apply(e,t){let n=Gn();if(!e.byoUpstream&&ae(e,"anthropic")){let E=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${Ui}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],O;try{O=await Me(n)}catch{return{status:"held",messages:E}}let{next:K,removed:G}=kh(O.data,await Ga(n),Md,Hn());return G?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...E]}:(await Jt(n,O,K,!1),await pe(n),await Ld(),await Wi(Zo(),Nd(K)),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...E]}):(t.dryRun||(await Ld(),await Wi(Zo(),Nd(K))),{status:"held",messages:E})}let r=Hn(),o=!1;if(!t.dryRun)try{await zv(r)}catch{r=void 0,o=!0}let a=await In()?We("profile"):void 0,s;try{s=await Me(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${xh}", "maxTokens": ${Rh}, "apiKey": "<your personal ark_ key>", "headers": { "${za}": "<your personal ark_ key>", "${Xo}": "${$d}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${za}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Bd}") 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.",...a?[`Under "mcp.servers" add "${mn}": { "command": ${JSON.stringify(a.command)}, "args": ${JSON.stringify(a.args)}, "transport": "stdio", "enabled": true } so optimizer trims stay recoverable.`]:[],"Then run `openclaw config validate`."]}}let{next:i,routed:c,cacheRetentionSeeded:l,betaPreserved:d,headerConflicts:u,primarySeeded:p,fallbacksSeeded:m,unroutedPrimary:f,unroutedFallbacks:h,structureConflicts:w,pluginConfigured:y,mcpConfigured:g,mcpConflict:b}=JB(s.data,e,r,a),k=i,A=!1;if(!c.includes("openai")){let E=kh(k,await Ga(n),["openai"]);E.removed&&(k=E.next,A=!0)}let x=[c.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: ${be({...e.metadata,tool:Ui})??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...l?['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."],...d?[`Kept your existing ${Xo} header value (OpenClaw suppresses its implicit beta headers off-host; yours replaces our default restore).`]:[],...u.length>0?[`Could not add headers on models.providers.${u.join(", ")}: the existing "headers" value is not an object. Fix it manually; nothing there was replaced.`]:[],...p?[`Seeded agents.defaults.model.primary = ${y?_h:Bd} (none was set; routing is inert until the primary resolves to a routed provider).`,...m?[`Seeded agents.defaults.model.fallbacks = [${(y?Th:Oh).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.`]:[],...h.length>0?[`Fallback model(s) ${h.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...A?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...y?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${Hn()}) and registered it under plugins.entries.${ot}: 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).`]:[],...b?[`MCP name conflict in ${n}: mcp.servers.${mn} is not owned by Anyray Connect, so it was left untouched. Rename or remove it to get anyray_retrieve.`]:g?[`Registered the Anyray retrieval MCP server (anyray_retrieve) at mcp.servers.${mn}, so optimizer trims stay recoverable. Restart the OpenClaw gateway, or run \`openclaw mcp reload\`, to connect it.`]:a===void 0?[`Skipped the Anyray retrieval MCP server \u2014 anyray-connect is running from a temporary path (${De()}). Re-run via the installer or a global install so optimizer trims stay recoverable.`]:[],...w.length>0?[`Left ${w.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."],_=u.length>0||w.length>0?"manual":"configured",S=b?"mcp_foreign":void 0;if(t.dryRun)return{status:_,messages:x,...S?{errorClass:S}:{}};let I=await Jt(n,s,k,!0);return y&&await Wi(Zo(),Nd(k)),{status:_,messages:x,changedFiles:I?[n]:[],...S?{errorClass:S}:{}}},async pointsAt(e){try{let{data:t}=await Me(Gn());for(let a of Object.values(Ih(t)))if(N(a)&&qv(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[ot];if(N(o)&&N(o.config)&&qv(o.config.gatewayUrl,e))return!0}catch{}return!1},async configuredKeyIsCurrent(e){return Vt([Gn()],e)},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Gn();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};let t;try{({data:t}=await Me(e))}catch{return{registered:!1,command:null,reason:"unreadable"}}let n=N(t.mcp)?t.mcp:{},o=(N(n.servers)?n.servers:{})[mn];if(o===void 0)return{registered:!1,command:null,reason:"absent"};if(!Gi(o))return{registered:!1,command:null,reason:"foreign"};let a=o.command;return{registered:!0,command:typeof a=="string"?a:null}},async integrationStatus(){let e,t=!0;try{let{data:n}=await Me(Gn()),r=N(n.mcp)?n.mcp.servers:void 0;if(n.mcp!==void 0&&!N(n.mcp)||r!==void 0&&!N(r))e="unreadable";else{let o=N(r)?r[mn]:void 0;if(o===void 0)e="missing";else if(!Gi(o))e="foreign";else{e="owned";let a=o;t=Pa({command:a.command,args:a.args},"profile")}}}catch{e="unreadable"}return{mcp_registration:e,hook_binary:t&&await In()?"owned":"missing"}},async routingExpected(e){return e.includes(Ui)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Me(Gn());for(let a of Object.values(Ih(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[za]=="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:{})[ot];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=Gn();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Me(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}=kh(n.data,await Ga(t),Md,Hn()),a=await Ld();return await Wi(Zo(),Nd(r)),o?(await Jt(t,n,r,!1),await pe(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${Hn()}`]:[]],changedFiles:[t]}):(await pe(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${Hn()}`]:[]]})}};import{execFile as UU}from"node:child_process";import{readFile as HU}from"node:fs/promises";import{homedir as cc,platform as mo}from"node:os";import{join as Zn}from"node:path";import{isDeepStrictEqual as Ay,promisify as GU}from"node:util";var Ki=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},Fd=(e,t)=>{let n=Ki(e),r=Ki(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 oU}from"node:crypto";import{promises as pI}from"node:fs";import{platform as fI,tmpdir as aU}from"node:os";import{join as ru}from"node:path";import{execFile as zB}from"node:child_process";import{promises as Vi}from"node:fs";import{homedir as qB,platform as QB}from"node:os";import{delimiter as eF,join as Wd}from"node:path";import{promisify as tF}from"node:util";var nF=tF(zB),rF=15*6e4,oF=64*1024*1024,aF=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],tS=async(e={})=>{let t=(e.home??qB)(),n=e.env??process.env,r=aF(e.runtimePlatform??QB()),o=[Wd(t,".local","bin"),Wd(t,".claude","local"),...(n.PATH??"").split(eF).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Wd(a,`claude${s}`);try{return await Vi.access(i),i}catch{}}return null},sF=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},iF=async e=>{let t=Wd(e,"projects"),n;try{n=(await Vi.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(!dF.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},cF=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 m=a[d];l.push({sessionId:u,transcriptPath:p,title:typeof m=="string"&&m.length>0?m:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:sF(n.projectList)}},lF=async e=>{let t,n;try{let r=await Vi.readFile(e,"utf8");for(let o of r.split(`
|
|
191
191
|
`)){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}},dF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,uF=/\.(?:cmd|bat)$/i,pF=(e,t)=>uF.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},nS=async(e,t={})=>{let n=t.exec??nF,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 Vi.mkdir(e.configDir,{recursive:!0,mode:448}),await Vi.mkdir(e.workDir,{recursive:!0,mode:448});let o=pF(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:rF,maxBuffer:oF,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(`
|
|
192
|
-
`).filter(d=>d.trim().length>0),i=cF(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 lF(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await iF(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as fF}from"node:crypto";import{promises as Cr}from"node:fs";import{homedir as mF,platform as hF}from"node:os";import{join as Lt}from"node:path";var rS=448,Ar="local_",yF="local-agent-mode-sessions",Ph="-3p",gF="cowork_account_settings.json",kr=(e={})=>{let t=(e.home??mF)(),n=e.runtimePlatform??hF(),r=e.env??process.env;if(n==="darwin")return Lt(t,"Library","Application Support",`Claude${Ph}`);if(n==="win32"){let o=r.LOCALAPPDATA??Lt(t,"AppData","Local");return Lt(o,`Claude${Ph}`)}return null},Xo=(e={})=>{let t=kr(e);return t?t.slice(0,-Ph.length):null},Dh=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)}`},Ud=async e=>{let t=Lt(e,yF),n;try{n=(await Cr.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 Cr.readdir(Lt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=Lt(t,o,s);try{await Cr.access(Lt(i,gF)),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]}},Lh=async e=>{try{let t=await Cr.readdir(e);return new Set(t.filter(n=>n.startsWith(Ar)&&n.endsWith(".json")).map(n=>n.slice(Ar.length,-5)))}catch{return new Set}},za=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),wF=async(e,t)=>{let n=`${Ar}${t.sessionId}`,r=Lt(e,n),o=Lt(r,"outputs"),a=Lt(r,".claude"),s=Lt(a,"projects",Dh(o));await Cr.mkdir(o,{recursive:!0,mode:rS}),await Cr.mkdir(s,{recursive:!0,mode:rS});let i=Lt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${fF()}`;await Cr.copyFile(t.transcriptPath,c),await Cr.chmod(c,384),await Cr.rename(c,i);let l=t.createdAt??Date.now();await q(Lt(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})},oS=async(e,t)=>{let n=await Lh(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!za(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await wF(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as qa}from"node:fs";import{homedir as bF}from"node:os";import{dirname as CF,join as ji}from"node:path";var AF=448,kF=["Documents","Claude","Projects"],vF="spaces.json",SF=(e={})=>ji((e.home??bF)(),...kF),IF=async e=>{try{let t=JSON.parse(await qa.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}}},EF=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Nh=async e=>{try{return await qa.access(e),!0}catch{return!1}},xF=async(e,t,n)=>{let r=ji(t,EF(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Nh(r)?o:r;return a===o&&await Nh(o)?null:(await qa.mkdir(CF(a),{recursive:!0}),await qa.cp(e,a,{recursive:!0}),a)},RF=async e=>{try{let t=(await qa.readFile(ji(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},aS=async e=>{let t=SF({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=ji(e.storageDir,vF),{spaces:a,readable:s}=await IF(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=ji(e.stagedProjectsDir,l.dirName);try{if(!await Nh(d)){n.failed+=1;continue}let u=await xF(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await RF(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 qa.mkdir(e.storageDir,{recursive:!0,mode:AF}),await q(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as PF}from"node:crypto";import{execFile as DF,spawnSync as yS}from"node:child_process";import{constants as gS}from"node:fs";import{access as Yd,chmod as LF,mkdir as NF,readdir as $F,readFile as Mh,rename as MF,rm as Qa,stat as wS,writeFile as BF}from"node:fs/promises";import{homedir as FF,platform as WF,userInfo as UF}from"node:os";import{basename as HF,dirname as bS,isAbsolute as es,join as zt,resolve as dS}from"node:path";import{isDeepStrictEqual as Zi,promisify as GF}from"node:util";var uo="__anyray-claude-desktop-credential",Yi="__anyray-claude-desktop-bootstrap-headers";var Hd=(e="anyray-connect migrate")=>["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: \`${e} --export <file.zip>\`.`],Gd=["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."],sS=(e="anyray-connect migrate",t="anyray-connect desktop")=>`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 \`${e} --export <file.zip>\`, and \`${t} disconnect\` restores the first-party profile.`;var Kd=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],iS=["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"],OF=new Set(iS),_F=new Set(iS.map(e=>e.toLowerCase())),TF=new Set(Kd.map(e=>e.toLowerCase())),Vd=(e,t=!1)=>(t?_F:OF).has(t?e.toLowerCase():e),cS=(e,t=!1)=>t?TF.has(e.toLowerCase()):Kd.some(n=>n===e),lS=["*"],zo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...lS]}),po=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var Ji=/^[a-f0-9-]{36}$/,CS="Anyray",Bh=4,qi=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],Qi=["deploymentMode","awaitingSignIn"],KF=["inferenceGatewayApiKey","awaitingSignIn"],AS=[...[...qi,...Qi].filter(e=>!KF.includes(e)),"configLibrary","_meta.json"],Kn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),gt=e=>structuredClone(e),Xi=async e=>{try{return await Yd(e),!0}catch{return!1}},VF=async e=>{try{let t=await $F(bS(e)),n=HF(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},jF=async e=>{try{return await Yd(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":VF(e)}},hn=(e={})=>{let t=(e.home??FF)(),n=(e.username??(()=>UF().username))(),r=zt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",zt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:zt(r,"configLibrary"),meta:zt(r,"configLibrary","_meta.json"),appConfig:zt(r,"claude_desktop_config.json"),helper:zt(t,".anyray","bin","claude-desktop-credential-helper"),journal:zt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Fh=()=>{let e=yS("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return e.error?"probe_failed":e.status===0?"running":e.status===1?"not_running":"probe_failed"},Zd=()=>Fh()!=="not_running",kS=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],YF=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...kS(t)]}},Wh=(e="json")=>{let t=Sn(kS(e)),n=dS(t.command),r=dS(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)}},ZF=e=>`'${e.replace(/'/g,`'"'"'`)}'`,Uh=e=>[e.command,...e.args].map(ZF).join(" "),JF=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!es(e.command))throw new Error("the credential helper executable is not absolute")},vS=(e,t)=>{JF(e);let n=Jd(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!es(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},SS=e=>(vS(e,"--json"),`#!/bin/sh
|
|
192
|
+
`).filter(d=>d.trim().length>0),i=cF(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 lF(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await iF(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as fF}from"node:crypto";import{promises as Cr}from"node:fs";import{homedir as mF,platform as hF}from"node:os";import{join as Lt}from"node:path";var rS=448,Ar="local_",yF="local-agent-mode-sessions",Ph="-3p",gF="cowork_account_settings.json",kr=(e={})=>{let t=(e.home??mF)(),n=e.runtimePlatform??hF(),r=e.env??process.env;if(n==="darwin")return Lt(t,"Library","Application Support",`Claude${Ph}`);if(n==="win32"){let o=r.LOCALAPPDATA??Lt(t,"AppData","Local");return Lt(o,`Claude${Ph}`)}return null},zo=(e={})=>{let t=kr(e);return t?t.slice(0,-Ph.length):null},Dh=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)}`},Ud=async e=>{let t=Lt(e,yF),n;try{n=(await Cr.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 Cr.readdir(Lt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=Lt(t,o,s);try{await Cr.access(Lt(i,gF)),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]}},Lh=async e=>{try{let t=await Cr.readdir(e);return new Set(t.filter(n=>n.startsWith(Ar)&&n.endsWith(".json")).map(n=>n.slice(Ar.length,-5)))}catch{return new Set}},qa=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),wF=async(e,t)=>{let n=`${Ar}${t.sessionId}`,r=Lt(e,n),o=Lt(r,"outputs"),a=Lt(r,".claude"),s=Lt(a,"projects",Dh(o));await Cr.mkdir(o,{recursive:!0,mode:rS}),await Cr.mkdir(s,{recursive:!0,mode:rS});let i=Lt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${fF()}`;await Cr.copyFile(t.transcriptPath,c),await Cr.chmod(c,384),await Cr.rename(c,i);let l=t.createdAt??Date.now();await q(Lt(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})},oS=async(e,t)=>{let n=await Lh(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!qa(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await wF(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as Qa}from"node:fs";import{homedir as bF}from"node:os";import{dirname as CF,join as ji}from"node:path";var AF=448,kF=["Documents","Claude","Projects"],vF="spaces.json",SF=(e={})=>ji((e.home??bF)(),...kF),IF=async e=>{try{let t=JSON.parse(await Qa.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}}},EF=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Nh=async e=>{try{return await Qa.access(e),!0}catch{return!1}},xF=async(e,t,n)=>{let r=ji(t,EF(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Nh(r)?o:r;return a===o&&await Nh(o)?null:(await Qa.mkdir(CF(a),{recursive:!0}),await Qa.cp(e,a,{recursive:!0}),a)},RF=async e=>{try{let t=(await Qa.readFile(ji(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},aS=async e=>{let t=SF({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=ji(e.storageDir,vF),{spaces:a,readable:s}=await IF(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=ji(e.stagedProjectsDir,l.dirName);try{if(!await Nh(d)){n.failed+=1;continue}let u=await xF(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await RF(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 Qa.mkdir(e.storageDir,{recursive:!0,mode:AF}),await q(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as PF}from"node:crypto";import{execFile as DF,spawnSync as yS}from"node:child_process";import{constants as gS}from"node:fs";import{access as Yd,chmod as LF,mkdir as NF,readdir as $F,readFile as Mh,rename as MF,rm as es,stat as wS,writeFile as BF}from"node:fs/promises";import{homedir as FF,platform as WF,userInfo as UF}from"node:os";import{basename as HF,dirname as bS,isAbsolute as ts,join as zt,resolve as dS}from"node:path";import{isDeepStrictEqual as Zi,promisify as GF}from"node:util";var uo="__anyray-claude-desktop-credential",Yi="__anyray-claude-desktop-bootstrap-headers";var Hd=(e="anyray-connect migrate")=>["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: \`${e} --export <file.zip>\`.`],Gd=["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."],sS=(e="anyray-connect migrate",t="anyray-connect desktop")=>`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 \`${e} --export <file.zip>\`, and \`${t} disconnect\` restores the first-party profile.`;var Kd=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],iS=["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"],OF=new Set(iS),_F=new Set(iS.map(e=>e.toLowerCase())),TF=new Set(Kd.map(e=>e.toLowerCase())),Vd=(e,t=!1)=>(t?_F:OF).has(t?e.toLowerCase():e),cS=(e,t=!1)=>t?TF.has(e.toLowerCase()):Kd.some(n=>n===e),lS=["*"],qo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...lS]}),po=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var Ji=/^[a-f0-9-]{36}$/,CS="Anyray",Bh=4,qi=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],Qi=["deploymentMode","awaitingSignIn"],KF=["inferenceGatewayApiKey","awaitingSignIn"],AS=[...[...qi,...Qi].filter(e=>!KF.includes(e)),"configLibrary","_meta.json"],Kn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),gt=e=>structuredClone(e),Xi=async e=>{try{return await Yd(e),!0}catch{return!1}},VF=async e=>{try{let t=await $F(bS(e)),n=HF(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},jF=async e=>{try{return await Yd(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":VF(e)}},hn=(e={})=>{let t=(e.home??FF)(),n=(e.username??(()=>UF().username))(),r=zt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",zt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:zt(r,"configLibrary"),meta:zt(r,"configLibrary","_meta.json"),appConfig:zt(r,"claude_desktop_config.json"),helper:zt(t,".anyray","bin","claude-desktop-credential-helper"),journal:zt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Fh=()=>{let e=yS("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return e.error?"probe_failed":e.status===0?"running":e.status===1?"not_running":"probe_failed"},Zd=()=>Fh()!=="not_running",kS=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],YF=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...kS(t)]}},Wh=(e="json")=>{let t=Sn(kS(e)),n=dS(t.command),r=dS(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)}},ZF=e=>`'${e.replace(/'/g,`'"'"'`)}'`,Uh=e=>[e.command,...e.args].map(ZF).join(" "),JF=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ts(e.command))throw new Error("the credential helper executable is not absolute")},vS=(e,t)=>{JF(e);let n=Jd(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!ts(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},SS=e=>(vS(e,"--json"),`#!/bin/sh
|
|
193
193
|
exec ${Uh(e)}
|
|
194
194
|
`),XF=`#!/bin/sh
|
|
195
195
|
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,IS=e=>{vS(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),uo]};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 ${Uh(t)}`,""].join(`
|
|
196
196
|
`)},zF=e=>e.args.at(-1)==="--passthrough-headers"?IS(e):SS(e),Jd=e=>/[\\/](node|node\.exe)$/i.test(e),Hh=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++}},qF=e=>{let t=`#!/bin/sh
|
|
197
197
|
exec `;if(!e.startsWith(t)||!e.endsWith(`
|
|
198
198
|
`))return;let n=e.slice(t.length,-1);if(n.includes(`
|
|
199
|
-
`)||n.includes("\r"))return;let r=Hh(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Jd(o);if(!
|
|
200
|
-
# Anyray subscription pass-through credential helper`,tW=e=>{let t=Jd(e.command);if(!(!
|
|
201
|
-
`)},nW=e=>{if(!e.startsWith(eW))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=Hh(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return tW(a)===e?a:void 0},ES=e=>qF(e)??QF(e)??nW(e),rW=async()=>{let e=yS("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},oW=async e=>{let t=[e.command,...Jd(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>wS(r)))).every(r=>r.isFile())?(await Yd(e.command,gS.X_OK),!0):!1}catch{return!1}},aW=0,Xd=async(e,t,n)=>{await NF(bS(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${aW++}.tmp`;try{await BF(r,t,{mode:n}),await LF(r,n),await MF(r,e)}catch(o){throw await
|
|
199
|
+
`)||n.includes("\r"))return;let r=Hh(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Jd(o);if(!ts(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!ts(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return SS(i)===e?i:void 0}catch{return}},QF=e=>{if(!e.startsWith(XF))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=Hh(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==uo)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return IS(a)===e?a:void 0}catch{return}},eW=`#!/bin/sh
|
|
200
|
+
# Anyray subscription pass-through credential helper`,tW=e=>{let t=Jd(e.command);if(!(!ts(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!ts(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=$(${Uh(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(`
|
|
201
|
+
`)},nW=e=>{if(!e.startsWith(eW))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=Hh(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return tW(a)===e?a:void 0},ES=e=>qF(e)??QF(e)??nW(e),rW=async()=>{let e=yS("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},oW=async e=>{let t=[e.command,...Jd(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>wS(r)))).every(r=>r.isFile())?(await Yd(e.command,gS.X_OK),!0):!1}catch{return!1}},aW=0,Xd=async(e,t,n)=>{await NF(bS(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${aW++}.tmp`;try{await BF(r,t,{mode:n}),await LF(r,n),await MF(r,e)}catch(o){throw await es(r,{force:!0}).catch(()=>{}),o}},vr=async(e,t)=>{await Xd(e,`${JSON.stringify(t,null,2)}
|
|
202
202
|
`,384)},Vn=async e=>{if(!await Xi(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await Mh(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!Kn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},ec=async e=>{if(!await Xi(e))return{present:!1};let t=await wS(e);return{present:!0,content:await Mh(e,"utf-8"),mode:t.mode&511}},xS=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:gt(e[t])}:{present:!1},$h=(e,t,n)=>{n.present?e[t]=gt(n.value):delete e[t]},uS=e=>Kn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),sW=e=>Kn(e)&&uS(e.original)&&uS(e.lastWritten),iW=e=>Kn(e)&&typeof e.present=="boolean"&&(!e.present||typeof e.content=="string"&&typeof e.mode=="number"&&Number.isInteger(e.mode)&&e.mode>=0&&e.mode<=511),pS=(e,t)=>Kn(e)&&t.every(n=>sW(e[n])),cW=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],lW=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],Gh=(e,t,n,r)=>!(!Kn(e)||e.version!==n||typeof e.configId!="string"||!Ji.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!Ji.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!Kn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==CS||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!pS(e.config,r)||r.some(o=>e.config[o].original.present)||!pS(e.deployment,Qi)||!Kn(e.helper)||e.helper.path!==t.helper||!iW(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),dW=(e,t)=>Gh(e,t,Bh,qi),uW=(e,t)=>Gh(e,t,2,cW),pW=(e,t)=>Gh(e,t,3,lW),fW=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),fS=e=>({...e,version:Bh,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),Kh=async e=>{if(!await Xi(e.journal))return;let t;try{t=JSON.parse(await Mh(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(dW(t,e))return t;if(pW(t,e))return fS(t);if(uW(t,e))return fS(fW(t));throw new Error(`${e.journal} is not a valid ownership journal`)},mS=async(e,t)=>{await Xd(e,`${JSON.stringify(t,null,2)}
|
|
203
|
-
`,384)},zi=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!Ji.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!Kn(o)||typeof o.id!="string"||!Ji.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},mW=async(e,t,n)=>{let r=await Vn(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:gt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[gt(t.metaEntry)]}}}let c=zi(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!Zi(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:gt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...gt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=zi(r.value);let c=zt(e.library,`${o}.json`);if(!await Xi(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=gt(r.value.entries)}let s=n();if(!Ji.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await Xi(zt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:CS};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?gt(r.value):{},appliedId:s,entries:[...a,i]}}},hW=(e,t)=>{let n=zo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},RS=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),yW=async(e,t,n,r,o,a,s)=>{let i=RS(),c=Object.fromEntries(qi.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(Qi.map(d=>[d,{original:s?.deployment[d].original??xS(r.value,d),lastWritten:i[d]}]));return{version:Bh,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??gt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await ec(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},jd=e=>({status:"manual",messages:[e]}),gW=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}`)]}},wW=GF(DF),bW=new Set(Kd),CW=async e=>{try{let{stdout:t}=await wW("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return Kn(n)?Object.keys(n):void 0}catch{return}},qo=async(e,t={})=>{let n=t.readManagedPolicyKeys??CW;for(let r of e.managedPolicies){let o=await jF(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=>Vd(i)&&!bW.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},Vh=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.`},jh=e=>(e.platform??WF)()==="darwin",OS=async(e,t,n={})=>{if(!jh(n))return jd("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Zd)()&&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=hn(n),a=await qo(o,n);if(a&&r.push({audience:"admin",message:Vh(a)}),r.length>0)return gW(r);let s=!1,i=!1,c=[o.journal];try{let l=ae(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??rW)())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=YF((n.credentialCommand??(()=>Wh(d)))(),d),p=zF(u),m=await Kh(o),f=await ec(o.helper);if(m&&f.present&&f.content!==m.helper.lastWritten&&f.content!==m.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!m&&f.present&&f.content!==p)throw new Error("the Claude Desktop credential helper path contains a foreign file");let h=await mW(o,m,n.randomUUID??PF),w=zt(o.library,`${h.configId}.json`);c=[o.journal,o.helper,w,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await Vn(w),g=await Vn(o.appConfig),b=hW(e,o.helper),k=await yW(o,h,y,g,p,b,m);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 mS(o.journal,k),i=!0,await Xd(o.helper,p,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await mS(o.journal,k));let A=gt(y.value);for(let S of qi)$h(A,S,b[S]);await vr(w,A),h.metaToWrite&&await vr(o.meta,h.metaToWrite);let E=gt(g.value),O=RS();for(let S of Qi)$h(E,S,O[S]);return await vr(o.appConfig,E),{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.",...Hd(Ot("migrate"))]}}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.`]}:jd(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},hS=(e,t,n,r)=>{let o=gt(e);for(let a of n){let s=t[a];Zi(xS(e,a),s.lastWritten)?$h(o,a,s.original):r.push(a)}return o},_S=async(e,t={})=>{if(!jh(t))return{status:"not-found",messages:[]};if((t.appRunning??Zd)())return jd("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=hn(t);try{let r=await Kh(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=zt(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 Vn(o),i=s.value;s.present&&(i=hS(s.value,r.config,qi,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await Vn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let f=zi(l.value),h=gt(l.value.entries),w=h.findIndex(b=>b.id===r.configId),y=w>=0?h[w]:void 0,g=y!==void 0&&Zi(y,r.metaEntry);if(y!==void 0&&!g&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=gt(l.value),f===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=Zi(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&f!==r.configId?(g&&h.splice(w,1),d={...gt(l.value),entries:h}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await Qa(o,{force:!0}):await vr(o,i)),l.present&&(u?await Qa(n.meta,{force:!0}):Zi(l.value,d)||await vr(n.meta,d));let p=await Vn(n.appConfig);if(p.present){let f=hS(p.value,r.deployment,Qi,a);!r.deploymentFileExisted&&Object.keys(f).length===0?await Qa(n.appConfig,{force:!0}):await vr(n.appConfig,f)}else r.deploymentFileExisted&&a.push("deployment config file");let m=await ec(n.helper);return m.present&&(m.content===r.helper.lastWritten||m.content===r.helper.previousWritten)?r.helper.original.present?await Xd(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await Qa(n.helper,{force:!0}):(m.present||r.helper.original.present)&&a.push("credential helper"),await Qa(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?[]:Gd]}}catch(r){return jd(`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.`)}},Yh=async(e,t={})=>{if(!jh(t))return!1;let n=hn(t);if(await qo(n,t))return!1;try{let r=await Vn(n.meta);if(!r.present)return!1;let o=zi(r.value),a=await Vn(zt(n.library,`${o}.json`)),s=await Vn(n.appConfig);if(!a.present||!s.present)return!1;await Yd(n.helper,gS.X_OK);let i=ct(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}},TS=async(e={})=>{try{let t=hn(e),n=await ec(t.helper);if(!n.present||typeof n.content!="string")return;let r=ES(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},PS=async(e,t={})=>{if(!await Yh(e,t))return!1;let n=hn(t);try{let r=await Kh(n);if(!r)return!1;let o=await Vn(n.meta);if(!o.present||zi(o.value)!==r.configId)return!1;let a=await ec(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=ES(a.content??"");return s?await(t.helperLauncherAvailable??oW)(s):!1}catch{return!1}};import{createHash as ZS,randomUUID as JS}from"node:crypto";import{spawn as AW,spawnSync as kW}from"node:child_process";import{link as ey,mkdir as Zh,open as XS,readFile as Jh,readdir as zS,rename as qS,rm as yn,stat as QS}from"node:fs/promises";import{homedir as ty}from"node:os";import{basename as eI,dirname as nc,join as is,win32 as vW}from"node:path";import{isDeepStrictEqual as ts}from"node:util";var Fe="HKCU\\SOFTWARE\\Policies\\Claude",tc="HKLM\\SOFTWARE\\Policies\\Claude",eu=5,cs="inferenceGatewayApiKey",He=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",cs],DS=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",cs],LS=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",cs],NS=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",cs],tI="Managed by anyray-connect; dynamic credential only.",SW=e=>/^[A-Za-z]:[\\/]/.test(e)&&vW.isAbsolute(e),$S=e=>{if(!SW(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)},nI=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!$S(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&&!$S(e.args[0]))throw new Error("the credential helper does not use print-key --json")},ny=(e={})=>is((e.home??ty)(),".anyray","bin","claude-desktop-credential-helper.cmd"),IW=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},EW=e=>(nI(e),["@echo off",`REM ${tI}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(IW).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
203
|
+
`,384)},zi=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!Ji.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!Kn(o)||typeof o.id!="string"||!Ji.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},mW=async(e,t,n)=>{let r=await Vn(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:gt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[gt(t.metaEntry)]}}}let c=zi(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!Zi(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:gt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...gt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=zi(r.value);let c=zt(e.library,`${o}.json`);if(!await Xi(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=gt(r.value.entries)}let s=n();if(!Ji.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await Xi(zt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:CS};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?gt(r.value):{},appliedId:s,entries:[...a,i]}}},hW=(e,t)=>{let n=qo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},RS=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),yW=async(e,t,n,r,o,a,s)=>{let i=RS(),c=Object.fromEntries(qi.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(Qi.map(d=>[d,{original:s?.deployment[d].original??xS(r.value,d),lastWritten:i[d]}]));return{version:Bh,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??gt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await ec(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},jd=e=>({status:"manual",messages:[e]}),gW=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}`)]}},wW=GF(DF),bW=new Set(Kd),CW=async e=>{try{let{stdout:t}=await wW("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return Kn(n)?Object.keys(n):void 0}catch{return}},Qo=async(e,t={})=>{let n=t.readManagedPolicyKeys??CW;for(let r of e.managedPolicies){let o=await jF(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=>Vd(i)&&!bW.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},Vh=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.`},jh=e=>(e.platform??WF)()==="darwin",OS=async(e,t,n={})=>{if(!jh(n))return jd("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Zd)()&&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=hn(n),a=await Qo(o,n);if(a&&r.push({audience:"admin",message:Vh(a)}),r.length>0)return gW(r);let s=!1,i=!1,c=[o.journal];try{let l=ae(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??rW)())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=YF((n.credentialCommand??(()=>Wh(d)))(),d),p=zF(u),m=await Kh(o),f=await ec(o.helper);if(m&&f.present&&f.content!==m.helper.lastWritten&&f.content!==m.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!m&&f.present&&f.content!==p)throw new Error("the Claude Desktop credential helper path contains a foreign file");let h=await mW(o,m,n.randomUUID??PF),w=zt(o.library,`${h.configId}.json`);c=[o.journal,o.helper,w,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await Vn(w),g=await Vn(o.appConfig),b=hW(e,o.helper),k=await yW(o,h,y,g,p,b,m);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 mS(o.journal,k),i=!0,await Xd(o.helper,p,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await mS(o.journal,k));let A=gt(y.value);for(let S of qi)$h(A,S,b[S]);await vr(w,A),h.metaToWrite&&await vr(o.meta,h.metaToWrite);let x=gt(g.value),_=RS();for(let S of Qi)$h(x,S,_[S]);return await vr(o.appConfig,x),{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.",...Hd(Ot("migrate"))]}}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.`]}:jd(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},hS=(e,t,n,r)=>{let o=gt(e);for(let a of n){let s=t[a];Zi(xS(e,a),s.lastWritten)?$h(o,a,s.original):r.push(a)}return o},_S=async(e,t={})=>{if(!jh(t))return{status:"not-found",messages:[]};if((t.appRunning??Zd)())return jd("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=hn(t);try{let r=await Kh(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=zt(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 Vn(o),i=s.value;s.present&&(i=hS(s.value,r.config,qi,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await Vn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let f=zi(l.value),h=gt(l.value.entries),w=h.findIndex(b=>b.id===r.configId),y=w>=0?h[w]:void 0,g=y!==void 0&&Zi(y,r.metaEntry);if(y!==void 0&&!g&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=gt(l.value),f===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=Zi(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&f!==r.configId?(g&&h.splice(w,1),d={...gt(l.value),entries:h}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await es(o,{force:!0}):await vr(o,i)),l.present&&(u?await es(n.meta,{force:!0}):Zi(l.value,d)||await vr(n.meta,d));let p=await Vn(n.appConfig);if(p.present){let f=hS(p.value,r.deployment,Qi,a);!r.deploymentFileExisted&&Object.keys(f).length===0?await es(n.appConfig,{force:!0}):await vr(n.appConfig,f)}else r.deploymentFileExisted&&a.push("deployment config file");let m=await ec(n.helper);return m.present&&(m.content===r.helper.lastWritten||m.content===r.helper.previousWritten)?r.helper.original.present?await Xd(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await es(n.helper,{force:!0}):(m.present||r.helper.original.present)&&a.push("credential helper"),await es(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?[]:Gd]}}catch(r){return jd(`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.`)}},Yh=async(e,t={})=>{if(!jh(t))return!1;let n=hn(t);if(await Qo(n,t))return!1;try{let r=await Vn(n.meta);if(!r.present)return!1;let o=zi(r.value),a=await Vn(zt(n.library,`${o}.json`)),s=await Vn(n.appConfig);if(!a.present||!s.present)return!1;await Yd(n.helper,gS.X_OK);let i=ct(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}},TS=async(e={})=>{try{let t=hn(e),n=await ec(t.helper);if(!n.present||typeof n.content!="string")return;let r=ES(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},PS=async(e,t={})=>{if(!await Yh(e,t))return!1;let n=hn(t);try{let r=await Kh(n);if(!r)return!1;let o=await Vn(n.meta);if(!o.present||zi(o.value)!==r.configId)return!1;let a=await ec(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=ES(a.content??"");return s?await(t.helperLauncherAvailable??oW)(s):!1}catch{return!1}};import{createHash as ZS,randomUUID as JS}from"node:crypto";import{spawn as AW,spawnSync as kW}from"node:child_process";import{link as ey,mkdir as Zh,open as XS,readFile as Jh,readdir as zS,rename as qS,rm as yn,stat as QS}from"node:fs/promises";import{homedir as ty}from"node:os";import{basename as eI,dirname as nc,join as cs,win32 as vW}from"node:path";import{isDeepStrictEqual as ns}from"node:util";var Fe="HKCU\\SOFTWARE\\Policies\\Claude",tc="HKLM\\SOFTWARE\\Policies\\Claude",eu=5,ls="inferenceGatewayApiKey",He=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ls],DS=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ls],LS=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ls],NS=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ls],tI="Managed by anyray-connect; dynamic credential only.",SW=e=>/^[A-Za-z]:[\\/]/.test(e)&&vW.isAbsolute(e),$S=e=>{if(!SW(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)},nI=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!$S(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&&!$S(e.args[0]))throw new Error("the credential helper does not use print-key --json")},ny=(e={})=>cs((e.home??ty)(),".anyray","bin","claude-desktop-credential-helper.cmd"),IW=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},EW=e=>(nI(e),["@echo off",`REM ${tI}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(IW).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
204
204
|
`)),xW=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},rI=e=>{let t=e.split(`\r
|
|
205
|
-
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${tI}`||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(xW);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return nI(s),s}catch{return}},RW=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>QS(r)))).every(r=>r.isFile())}catch{return!1}},OW=async(e,t)=>{let n=rI(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??RW)(n)}catch{return!1}},Xh=e=>({sha256:
|
|
205
|
+
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${tI}`||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(xW);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return nI(s),s}catch{return}},RW=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>QS(r)))).every(r=>r.isFile())}catch{return!1}},OW=async(e,t)=>{let n=rI(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??RW)(n)}catch{return!1}},Xh=e=>({sha256:ea(e),content:e}),MS=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return qt(t,["sha256","content"])&&MW(t.sha256)&&typeof t.content=="string"&&ea(t.content)===t.sha256&&rI(t.content)!==void 0},ry=()=>{let e=kW("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?"probe_failed":/(?:^|\r?\n)"Claude\.exe",/iu.test(e.stdout??"")?"running":"not_running"},oy=()=>ry()!=="not_running",_W=async(e,t)=>{await Zh(nc(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await XS(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await ey(n,e)}finally{await yn(n,{force:!0}).catch(()=>{})}},TW=e=>`${eI(e)}.anyray-old-`,PW=e=>`${e}.anyray-old-${process.pid}-${JS()}`,oI=async(e,t)=>{try{await ey(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await yn(t,{force:!0}),!0},qd=async(e,t,n,r,o)=>{let a=PW(e),s=n===void 0?void 0:ea(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${JS()}`,c=!1;try{if(i&&n!==void 0){let d=await XS(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 qS(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ss(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await ey(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await is(e)!==s))throw new Error("credential helper publication verification failed");await yn(a,{force:!0}),c=!1}catch(l){throw c&&await oI(e,a).catch(()=>!1),l}finally{i&&await yn(i,{force:!0}).catch(()=>{})}},zh=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,DW=String.raw`
|
|
206
206
|
$ErrorActionPreference = 'Stop'
|
|
207
207
|
try {
|
|
208
208
|
$request = ConvertFrom-Json ([Console]::In.ReadToEnd())
|
|
@@ -271,15 +271,15 @@ try {
|
|
|
271
271
|
exit 5
|
|
272
272
|
} catch {
|
|
273
273
|
exit 6
|
|
274
|
-
}`,Ir=async e=>new Promise((t,n)=>{let r=AW("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",DW],{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(zh(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(zh({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Qt=(e={})=>
|
|
275
|
-
`)}catch(a){if(a.code!=="EEXIST")throw await yn(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await Jh(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!NW(i.pid)}catch{try{s=Date.now()-(await QS(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new
|
|
276
|
-
`;t.writeJournalFile?await t.writeJournalFile(n,r):await Se(n,r)},VW=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,jW=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),YW=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),ZW=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),JW=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===ZW(t).toUpperCase(),jS=(e,t,n,r,o)=>{let a=He.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},XW=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,zW=(e,t)=>{if(!Vd(e,!0))return!1;let n=XW(t);if(YW.has(n))return!1;if(jW.has(n))return n==="REG_EXPAND_SZ"?!0:!cS(e,!0)},qW=(e,t)=>{let n=aI(),r=!1,o=!1,a=!1,s=t.toUpperCase()===tc.toUpperCase(),i=(l,d)=>{if(!s)return;let u=zW(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),jS(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||JW(d,t))continue;let u=VW.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),jS(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Sr=async(e,t=Fe)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:aI(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return qW(n.stdout,t)},fo=async e=>{let t=await Sr(e,tc);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...He.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},ly=e=>e.unparsed?`This machine may have a Claude policy under ${tc} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${tc} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${tc} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var nu=(e,t)=>po(zo(e,t)),sI=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],QW=(e,t)=>{let n=nu(e,t);return Object.fromEntries(He.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},eU=(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}}),tU=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,qh=e=>Object.fromEntries(He.map(t=>[t,$W(t,e[t])])),YS=(e,t,n,r)=>({version:eu,registryKey:Fe,keyExisted:e,lastWritten:qh(t),helper:{path:n,lastWritten:Xh(r)}}),nU=(e,t,n,r,o,a)=>({version:eu,registryKey:Fe,keyExisted:e,lastWritten:qh(t),pending:qh(n),helper:{path:r,...o?{lastWritten:Xh(o)}:{},pending:Xh(a)}}),Qh=(e,t,n)=>ns(n,e.lastWritten[t])||e.pending!==void 0&&ns(n,e.pending[t]),as=async e=>{try{let t=await Jh(e,"utf8");return{content:t,sha256:Qo(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ss=async e=>(await as(e))?.sha256,rs=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Qd=async(e,t)=>{let n=TW(e),r;try{r=await zS(nc(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>is(nc(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([as(e),as(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!rs(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await oI(e,a))throw new Error("credential helper changed during recovery");return}if(t&&rs(t,s.sha256)&&rs(t,i.sha256)){await yn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},dy=async(e,t,n)=>(n.present?await e(sI(Fe,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Fe,"/v",t,"/f"])).code===0,rU=async(e,t,n)=>{let r=!0,o=await Sr(e);for(let a of He)if(!ts(o.values[a],t[a])){if(!ts(o.values[a],n[a])){r=!1;continue}await dy(e,a,t[a])||(r=!1),o=await Sr(e)}return r&&He.every(a=>ts(o.values[a],t[a]))},at=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Qt(n)]}}),iI=async(e,t,n,r={})=>{if(!Pe(t))return at("A valid personal ark_ gateway key is required.",!1,r);let o=ny(r),a;try{a=EW((r.credentialCommand??Wh)())}catch{return at("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=Qo(a),i=r.runReg??Ir,c=Qt(r),l;if(!n.dryRun)try{l=await ay(r)}catch(h){return at(h instanceof os?"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,m,f=!1;try{let h=await fo(i);if(h)return at(ly(h),!1,r);let w=await cy(r,!n.dryRun);n.dryRun||await Qd(o,w);let y=await Sr(i),g=QW(e,o),b=await as(o),k=b?.sha256,A=!1;if(d=w,u=y,p=g,w){let S=He.find(I=>!Qh(w,I,y.values[I]));if(S)return at(`Claude's ${S} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!rs(w,k))return at(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);A=tU(w)}else{if(k!==void 0&&k!==s)return at(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let S=y.foreignState||He.some(_=>y.values[_].present),I=He.every(_=>ts(y.values[_],g[_])),x=He.every(_=>ts(y.values[_],eU(e,t.trim())[_]));if(S&&!I&&!x)return at(`Existing Claude third-party-inference policy values under ${Fe} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(A=x,I&&k===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Fe} into an owner-only journal without rewriting them.`]}:(await zd(YS(y.keyPresent,g,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Fe} into the ownership journal.`]})}if(A){let S=!0;try{S=(r.appRunning??oy)()}catch{}if(S)return at("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=nU(w?.keyExisted??y.keyPresent,y.values,g,o,b?.content,a);if(m=E,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Fe}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await zd(E,r),f=!0;for(let S of He){let I=await Sr(i);if(!ns(I.values[S],E.lastWritten[S])&&!ns(I.values[S],E.pending[S]))throw new Error("registry value changed during apply");if(!ts(I.values[S],g[S])&&!await dy(i,S,g[S]))throw new Error("registry write failed")}let O=await Sr(i);if(!He.every(S=>ns(O.values[S],E.pending[S])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await _W(o,a):await qd(o,k,a,"apply",r)),await ss(o)!==s)throw new Error("credential helper verification failed");return await zd(YS(E.keyExisted,g,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Fe}.`,`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.",...Hd(Ot("migrate"))]}}catch{if(!f||!u||!p||!m)return at("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Qd(o,m);let h=!0,w=await as(o),y=m.helper.pending;if(w?.sha256!==m.helper.lastWritten?.sha256&&(y!==void 0&&w?.sha256===y.sha256?m.helper.lastWritten?(await qd(o,y.sha256,m.helper.lastWritten.content,"rollback",r),h=await ss(o)===m.helper.lastWritten.sha256):await qd(o,y.sha256,void 0,"rollback",r):h=w===void 0&&m.helper.lastWritten===void 0),h&&await rU(i,u.values,p))return d?await zd(d,r):await yn(c,{force:!0}),at("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return at("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?.()}},cI=async(e,t={})=>{let n=t.runReg??Ir,r=Qt(t),o;if(!e.dryRun)try{o=await ay(t)}catch(a){return at(a instanceof os?"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 cy(t,!e.dryRun);a&&!e.dryRun&&await Qd(a.helper.path,a);let s=await Sr(n);if(!a)return He.filter(f=>s.values[f].present).length>0?at(`Claude policy values exist under ${Fe}, 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=He.filter(m=>s.values[m].present&&!Qh(a,m,s.values[m])),c=await ss(a.helper.path),l=c!==void 0&&!rs(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Fe}.`,`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 m of He){let h=(await Sr(n)).values[m];if(h.present){if(!Qh(a,m,h)){u.add(m);continue}await dy(n,m,{present:!1})||(d=!0)}}let p=await ss(a.helper.path);if(p!==void 0)if(rs(a,p))try{await qd(a.helper.path,p,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?at(`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 yn(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Fe}.`,"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?[]:Gd]})}catch{return at(`Could not safely inspect or revert ${Fe}; no unproven value was removed.`,!1,t)}finally{await o?.()}},lI=async(e,t={})=>{let n=t.runReg??Ir;if(!await R(Qt(t)))return;let r;try{r=await ay(t);let o=await cy(t);if(o&&await Qd(o.helper.path,o),!o||o.pending||await fo(n)!==void 0)return;let a=await Sr(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===ct(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&He.every(l=>ns(a.values[l],o.lastWritten[l]))))return;let i=await ss(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 OW(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?.()}},dI=async(e,t={})=>await lI(e,t)!==void 0,uI=async(e,t={})=>await lI(e,t)==="dynamic";var ls=(e=fI())=>e==="win32"?oy:Zd,py=(e=fI())=>e==="win32"?ry:Fh,uy="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",ou=async(e,t={})=>{let n=(t.profileRoot??kr)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:uy};if((t.appRunning??ls(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await pI.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 Ud(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 "+uy}:{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??tS)();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=ru(t.stagingRoot??aU(),`anyray-history-${process.pid}-${oU()}`);try{let s=await(t.runImporter??nS)({binary:o,exportPath:e,configDir:ru(a,"config"),workDir:ru(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. "+uy};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 oS(r.dir,s.conversations),c=await aS({stagedProjectsDir:ru(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 pI.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Nt}from"node:fs";import{homedir as RU}from"node:os";import{join as wn,sep as OU}from"node:path";import{isDeepStrictEqual as cu}from"node:util";import{constants as gI}from"node:fs";import{promises as j}from"node:fs";import{dirname as ds,isAbsolute as my,join as ee,relative as au,resolve as gn,sep as rc}from"node:path";import{randomUUID as lu}from"node:crypto";var jn=448,oc=384,wI=448,sU=4,hy=3e4,bI=5e3,iU=10*6e4,CI={config:["skill","plugin","local-mcp"],session:["code","cowork"]},du=e=>e?["config","session"]:["config"],ac=(e,t)=>(e??["config","session"]).includes(t),AI=["carried","pending","nothing_to_carry","not_routed","unreadable","unsupported","unknown"],kI={carried:"Portable Claude Desktop configuration carried",pending:"Portable Claude Desktop configuration pending",nothing_to_carry:"No portable Claude Desktop configuration to carry",not_routed:"Claude Desktop is not routed through Anyray on this machine, so no configuration carry applies",unreadable:"Portable Claude Desktop configuration could not be read",unsupported:"Portable Claude Desktop configuration is unsupported on this host",unknown:"Portable Claude Desktop configuration state is unknown"},fy=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),Ge=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sc=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),vI=(e,t)=>{let n=au(gn(e),gn(t));return n===""||!n.startsWith(`..${rc}`)&&n!==".."&&!my(n)},Yn=async e=>{try{let t=await j.readFile(e,"utf8"),n=JSON.parse(t);return Ge(n)?{raw:t,value:n}:void 0}catch(t){return St(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},St=e=>e instanceof Error&&"code"in e,cU=e=>{try{return process.kill(e,0),!0}catch(t){return St(t)&&t.code==="EPERM"}},SI=e=>e===0?"owner.json":`owner.${e}.json`,su=async e=>{let t;try{t=await j.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=ee(e,r.name),a,s,i;try{let d=JSON.parse(await j.readFile(o,"utf8"));Ge(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 j.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}},II=e=>{if(e.pid===void 0||!cU(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>hy&&t-e.createdAtMs>iU},lU=async e=>{let t=`${e}.anyray-lock`;await j.mkdir(ds(t),{recursive:!0,mode:jn});let n=lu(),r,o=!1;try{await j.mkdir(t,{mode:jn}),o=!0}catch(i){if(!St(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await su(t);if(d){if(!II(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await j.stat(t).then(p=>Date.now()-p.mtimeMs).catch(()=>0)<=hy)return}let l=ee(t,SI(c));try{await j.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
277
|
-
`,{flag:"wx",mode:oc}),r=l}catch(d){if(St(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await j.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await j.readFile(a,"utf8"));if(!Ge(i)||i.nonce!==n)return;let c=new Date;await j.utimes(a,c,c)}catch{}})()},bI);return s.unref(),async()=>{clearInterval(s);try{(await su(t))?.nonce===n&&await j.rm(t,{recursive:!0,force:!0})}catch{}}},dU=async(e,t,n)=>{await j.mkdir(
|
|
278
|
-
`,{mode:oc,flag:"wx"}),await j.rename(a,e)}catch(s){try{await j.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},uu=async(e,t)=>{for(let n=0;n<sU;n+=1){let r=await Yn(e);if(!r)return"failed";let o=t(r.value);if(!o||cu(o,r.value))return"unchanged";try{if(await dU(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},mI=async e=>{try{return(await j.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},pu=async e=>{let t=[];for(let n of await mI(e))for(let r of await mI(ee(e,n)))t.push(ee(e,n,r));return t},uU=e=>Array.isArray(e.skills)?e.skills.filter(t=>Ge(t)&&sc(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],pU=async e=>{let t=ee(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await pu(t)){let o=await Yn(ee(r,"manifest.json"));if(!o)continue;let a=r.split(rc).at(-1)??"";for(let s of uU(o.value))n.push({account:a,packageDir:r,entry:s})}return n},fU=async e=>{let t=await Yn(ee(e,".claude-plugin","plugin.json"));return!!t&&sc(t.value.name)},mU=(e,t)=>{let n=my(t)?gn(t):gn(e,t);if(!vI(e,n)||n===gn(e))return;let r=au(gn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},hU=async e=>{let t=await pu(ee(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(rc).includes("skills-plugin"))continue;let o=ee(r,"cowork_plugins"),a=await Yn(ee(o,"installed_plugins.json"));if(!a||!Ge(a.value.plugins))continue;let s=r.split(rc).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!sc(i)||!Array.isArray(c)))for(let l of c){if(!Ge(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=mU(o,l.installPath);!d||!await fU(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:ee(r,"cowork_account_settings.json")})}}return n},yU=async e=>{let t=await Yn(ee(e,"claude_desktop_config.json"));return!t||!Ge(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>sc(n)&&n.toLowerCase()!=="anyray"&&Ge(r)))},yy=async e=>{let[t,n,r]=await Promise.all([pU(e),hU(e),yU(e)]);return{skills:t,plugins:n,localMcpServers:r}},gy=async e=>{let t=await yy(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)}},hI=async e=>{try{let n=await j.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())return!1}catch{return!1}let t=async n=>{let r;try{r=await j.readdir(n,{withFileTypes:!0})}catch{return!1}for(let o of r){if(!sc(o.name))return!1;let a=ee(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)},gU=async e=>{let t=async n=>{let r=await j.readdir(n,{withFileTypes:!0});for(let o of r){let a=ee(n,o.name);if(o.isDirectory())await t(a),await j.chmod(a,jn);else if(o.isFile()){let s=await j.stat(a);await j.chmod(a,(s.mode&73)!==0?wI:oc)}}};await t(e),await j.chmod(e,jn)},EI=async(e,t)=>{try{let[n,r]=await Promise.all([j.readFile(e),j.readFile(t)]);return n.equals(r)}catch{return!1}},iu=async(e,t)=>{try{let[n,r]=await Promise.all([j.readdir(e,{withFileTypes:!0}),j.readdir(t,{withFileTypes:!0})]),o=n.map(s=>s.name).sort(),a=r.map(s=>s.name).sort();if(!cu(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 iu(ee(e,s),ee(t,s)))return!1}else if(!i.isFile()||!await EI(ee(e,s),ee(t,s)))return!1}return!0}catch{return!1}},xI=e=>`${e}.anyray-incomplete`,RI=async(e,t)=>{let n=!1;if(t){await j.mkdir(
|
|
279
|
-
`,{flag:"wx",mode:oc}),o=u}catch(p){if(St(p)&&p.code==="EEXIST"){n=!1;continue}n&&await j.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await j.readFile(a,"utf8"));if(!Ge(l)||l.nonce!==r)return;let d=new Date;await j.utimes(a,d,d)}catch{}})()},bI);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await su(e))?.nonce===r&&await j.rm(e,{recursive:!0,force:!0})}catch{}}}},OI=async e=>{let t=await RI(e,!1);t&&await t.complete()},wU=async(e,t,n)=>{let r=xI(t),o=!1;try{let c=await j.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await iu(e,t))return await OI(r),"present"}catch(c){if(!St(c)||c.code!=="ENOENT")return"failed"}if(o)try{let c=await j.lstat(r);if(!c.isDirectory()||c.isSymbolicLink())return"conflict"}catch{return"conflict"}let a=await RI(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await j.mkdir(t,{mode:jn})}catch(c){if(!St(c)||c.code!=="EEXIST")return a.abandon(),"failed";try{let l=await j.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 j.readdir(c,{withFileTypes:!0})}catch{return"failed"}for(let u of d){let p=ee(c,u.name),m=ee(l,u.name);try{if(u.isDirectory()){try{await j.mkdir(m,{mode:jn})}catch(h){if(!St(h)||h.code!=="EEXIST")throw h;let w=await j.lstat(m);if(!w.isDirectory()||w.isSymbolicLink())return"conflict"}let f=await s(p,m);if(f!=="copied")return f}else if(u.isFile())try{await j.copyFile(p,m,gI.COPYFILE_EXCL);let f=await j.stat(p);await j.chmod(m,(f.mode&73)!==0?wI:oc)}catch(f){if(!St(f)||f.code!=="EEXIST")throw f;if(!await EI(p,m))return"conflict"}else return"failed"}catch(f){return St(f)&&f.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await iu(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},_I=async(e,t,n,r)=>{if(!await hI(e))return"invalid";try{let a=await j.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await iu(e,t))return await OI(xI(t)),"present"}catch(a){if(!St(a)||a.code!=="ENOENT")return"failed"}await j.mkdir(ds(t),{recursive:!0,mode:jn});let o=ee(ds(t),`.anyray-stage-${lu()}`);try{return await j.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await hI(o)?(await gU(o),await n?.(t),await wU(o,t,r)):"invalid"}catch{return"failed"}finally{try{await j.rm(o,{recursive:!0,force:!0})}catch{}}},yI=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),TI=async e=>{let t=await pu(ee(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await Yn(ee(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},PI=async e=>{let t=await pu(ee(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(rc).includes("skills-plugin"))try{await j.access(ee(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},bU=async e=>{try{return await j.access(e,gI.R_OK),"readable"}catch(t){return St(t)&&t.code==="ENOENT"?"missing":"unreadable"}},CU=async(e,t)=>{if(e.length===0)return!0;if(!t)return!1;let n=await TI(t);if(n.state!=="found")return!1;let r=await Yn(ee(n.path,"manifest.json"));if(!r)return!1;let o=new Set((Array.isArray(r.value.skills)?r.value.skills:[]).filter(Ge).map(a=>a.name).filter(a=>typeof a=="string").map(a=>a.toLowerCase()));return e.every(a=>o.has(a.entry.name.toLowerCase()))},AU=async(e,t)=>{if(e.length===0)return!0;if(!t)return!1;let n=await PI(t);if(n.state!=="found")return!1;let o=(await Yn(ee(n.path,"cowork_plugins","installed_plugins.json")))?.value.plugins;return Ge(o)?e.every(a=>{let s=o[a.id];return Array.isArray(s)&&s.some(i=>Ge(i)&&i.scope==="user")}):!1},kU=async(e,t)=>{let n=Object.keys(e);if(n.length===0)return!0;if(!t)return!1;let o=(await Yn(ee(t,"claude_desktop_config.json")))?.value.mcpServers;return Ge(o)?n.every(a=>Object.hasOwn(o,a)):!1},DI=async(e,t)=>{if(!e)return"unsupported";let n=await bU(e);if(n==="unreadable")return"unreadable";if(n==="missing")return"nothing_to_carry";let r=await yy(e);if(r.skills.length===0&&r.plugins.length===0&&Object.keys(r.localMcpServers).length===0)return"nothing_to_carry";let[o,a,s]=await Promise.all([CU(r.skills,t),AU(r.plugins,t),kU(r.localMcpServers,t)]);return o&&a&&s?"carried":"pending"},vU=async(e,t,n,r,o)=>{let a=ee(t,"manifest.json");for(let s of e){let i=ee(s.packageDir,"skills",s.entry.name);try{await j.access(ee(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=ee(t,"skills",s.entry.name),l=await _I(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 uu(a,p=>{let m=Array.isArray(p.skills)?p.skills:[];if(m.find(h=>Ge(h)&&typeof h.name=="string"&&h.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...p,skills:[...m,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},LI=(e,t)=>({...e,installPath:t}),SU=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=my(r.installPath)?gn(r.installPath):gn(o,r.installPath),s=LI(e,au(gn(t),gn(n))),i={...r,installPath:au(gn(o),a)};return cu(s,i)},IU=async(e,t,n)=>{let r=await Yn(e);if(!r||!Ge(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":uu(t,a=>{let s=Ge(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},EU=async(e,t,n,r,o)=>{let a=ee(t,"cowork_plugins"),s=ee(a,"installed_plugins.json"),i=ee(t,"cowork_account_settings.json");for(let c of e){let l=ee(a,c.relativeInstallPath);if(!vI(a,l)){n.invalid+=1;continue}let d=await _I(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 uu(s,f=>{let h=Ge(f.plugins)?f.plugins:{},w=h[c.id],y=Array.isArray(w)?w:[],g=y.find(k=>Ge(k)&&k.scope==="user");if(g){u=SU(c.entry,ds(c.settingsFile),c.packageDir,g,t),p=!u;return}let b=LI(c.entry,l);return{...f,version:typeof f.version=="number"?f.version:2,plugins:{...h,[c.id]:[...y,b]}}})==="failed"?n.failed+=1:p?n.conflicts+=1:await IU(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},xU=async(e,t,n)=>{let r=ee(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await uu(r,c=>{let l=Ge(c.mcpServers)?c.mcpServers:{};if(Object.hasOwn(l,o)){s.value=cu(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}},NI=async(e,t,n={})=>{let r=await yy(e),o=fy("skill"),a=fy("plugin"),s=fy("local-mcp"),i=[],c=[],l=[],d=yI(r.skills,n.account,n.allAccounts),u=yI(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let m=new Set(n.allowedAccounts);if([...new Set([...d.map(h=>h.account),...u.map(h=>h.account)])].some(h=>!m.has(h)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,deferred:l,sourceChanged:!0,retryable:[]}}if(d.length>0&&n.appRunning)l.push("skill");else if(d.length>0){let m=await TI(t);m.state==="found"?await vU(d,m.path,o,n.beforeDirectoryPublish,n.afterDirectoryClaim):m.state==="missing"?i.push("skill"):(o.conflicts+=d.length,c.push("skill"))}if(u.length>0&&n.appRunning)l.push("plugin");else if(u.length>0){let m=await PI(t);m.state==="found"?await EU(u,m.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):m.state==="missing"?i.push("plugin"):(a.conflicts+=u.length,c.push("plugin"))}await xU(r.localMcpServers,t,s);let p=[o,a,s];return{outcomes:p,blocked:i,ambiguous:c,deferred:l,sourceChanged:!1,retryable:p.filter(m=>m.failed>0).map(m=>m.kind)}};var _U=async e=>{try{return await Nt.access(e),!0}catch{return!1}},$I=448,TU=384,BI={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},PU=CI.session,Cy=(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.",wy=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),FI=async e=>{let t;try{t=(await Nt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&za(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await Nt.readdir(wn(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&za(a.name)).map(a=>a.name);for(let a of o)n.push(wn(e,r,a))}catch{}return n},DU=async e=>{try{return(await Nt.readdir(e)).filter(t=>t.startsWith(Ar)&&t.endsWith(".json")).map(t=>t.slice(Ar.length,-5)).filter(za)}catch{return[]}},LU=async(e,t)=>{let n=await FI(wn(e,BI[t])),r=[];for(let o of n){let a=await DU(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(OU).slice(-2)[0]})}return r},NU=async(e,t)=>{if(t==="cowork"){let r=await Ud(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await FI(wn(e,BI.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},$U=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await Nt.copyFile(e,n),await Nt.chmod(n,TU),await Nt.rename(n,t)},MU=async(e,t)=>{try{let n=JSON.parse(await Nt.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||!za(o)?!1:(await Nt.access(wn(t,".claude","projects",Dh(r),`${o}.jsonl`)),!0)}catch{return!1}},BU=async(e,t,n,r)=>{let o=wy(e),a=await Lh(n);for(let s of t)await FU(e,s,n,r,a,o);return o},FU=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Ar}${s}.json`,c=wn(t.dir,i);try{if(e==="code"){if(!await MU(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=wn(t.dir,`${Ar}${s}`),d=wn(n,`${Ar}${s}`),u=await Nt.readdir(l);await Nt.mkdir(d,{mode:$I});for(let p of u)await Nt.cp(wn(l,p),wn(d,p),{recursive:!0,force:!1,errorOnExist:!0});await Nt.chmod(d,$I)}await $U(c,wn(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},MI=(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(`
|
|
280
|
-
`)}},by=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),WI=async e=>{let t=[];for(let n of PU)t.push({lane:n,sources:await LU(e,n)});return t},UI=async(e={})=>{let t=(e.firstPartyRoot??(()=>Xo()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let n=ac(e.assetClasses,"session"),[r,o]=await Promise.all([n?WI(t):Promise.resolve([]),gy(t)]),a=r.reduce((i,c)=>i+c.sources.reduce((l,d)=>l+d.ids.length,0),0),s=by(r);for(let i of o.accounts)s.add(i);return{sessions:a,accounts:s.size,userSkills:o.skills,userPlugins:o.plugins,localMcpServers:o.localMcpServers}},ea=async(e={})=>{let t=(e.home??RU)(),n=(e.firstPartyRoot??(()=>Xo()))(),r=(e.thirdPartyRoot??(()=>kr()))();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."};let o=ac(e.assetClasses,"session"),a=(e.appRunning??ls())();if(o&&a)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[s,i]=await Promise.all([o?WI(n):Promise.resolve([]),gy(n)]),c;if(e.account){let h=e.account;for(let g of s)g.sources=g.sources.filter(b=>b.account.startsWith(h));let w=i.accounts.filter(g=>g.startsWith(h));if(s.every(g=>g.sources.length===0)&&w.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${h}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let y=by(s);for(let g of w)y.add(g);if(y.size>1)return MI(s,e.command??"anyray-connect desktop --migrate",`"${h}" matches ${y.size} accounts`,w);c=[...y]}else if(o&&!e.allAccounts){let h=by(s);for(let w of i.accounts)h.add(w);if(h.size>1)return MI(s,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${h.size} accounts`,i.accounts);c=[...h]}let l=e.command??"anyray-connect desktop --migrate",d=!await _U(r),u=await NI(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:c,appRunning:a});if(u.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 \`${l}\` so the account choice is made from a fresh snapshot.`};let p=[],m=[];for(let{lane:h,sources:w}of s){if(w.length===0){p.push(wy(h));continue}let y=await NU(r,h);if("missing"in y){m.push({lane:h,reason:y.missing,waiting:w.reduce((g,b)=>g+b.ids.length,0)}),p.push(wy(h));continue}p.push(await BU(h,w,y.dir,t))}let f=p.some(h=>h.migrated>0||h.alreadyPresent>0)||u.outcomes.some(h=>h.migrated>0||h.alreadyPresent>0||h.conflicts>0);if(!f&&m.length===0&&u.blocked.length===0&&u.deferred.length>0)return{ok:!1,kind:"app-running",reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop; its skill and plugin stores are copied once it is closed."};if(!f&&(m.length>0||u.blocked.length>0)){let h=m[0];return h?{ok:!1,kind:h.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:h.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${h.lane} store`:`Claude Desktop has no ${h.lane} store in its third-party profile yet`,remedy:Cy(h.reason,h.lane,l,d)}:{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:p,portableAssets:u.outcomes,...m.length>0?{blocked:m}:{},...u.blocked.length>0?{blockedAssets:u.blocked}:{},...u.ambiguous.length>0?{ambiguousAssets:u.ambiguous}:{},...u.deferred.length>0?{deferredAssets:u.deferred}:{},...u.retryable.length>0?{retryableAssets:u.retryable}:{}}};var WU=e=>[Ue(e)],HI=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...WU(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await R(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var GI="1.21459.0",KU=GU(UU),VU=async e=>{try{let{stdout:t}=await KU("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},jU=async e=>{try{return await HU(e)}catch{return}},KI="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",YU=["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."],us=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(VI??=jI({}),VI):jI(e),VI,jI=async e=>{let t=(e.home??cc)(),n=["/Applications/Claude.app",Zn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??VU,o=e.readClaudeAppBundle??jU;for(let a of n){let s=await r(Zn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${KI}`}),c=Fd(s,GI);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${GI} or newer.`);let l=await o(Zn(a,"Contents","Resources","app.asar"));return l?AS.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. ${KI}`}},fu="anyray",XI="--anyray-owner=claude-desktop-v1",mu=(e={})=>{let t=(e.platform??mo)(),n=(e.home??cc)();return t==="darwin"?hn(e).appConfig:t==="win32"?Zn(process.env.APPDATA??Zn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):Zn(n,".config","Claude","claude_desktop_config.json")},Sy=(e={})=>Zn((e.home??cc)(),"Library","Application Support","Claude","claude_desktop_config.json"),zI=()=>{let e=We("profile");return{command:e.command,args:[...e.args,XI]}},ta=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qI=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},ZU=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),JU=e=>{if(!ta(e)||!qI(e,["command","args"]))return!1;let t=zI();return e.command===t.command&&ZU(e.args,t.args)},XU=e=>ta(e)&&Array.isArray(e.args)&&e.args.at(-1)===XI,zU=e=>{if(!ta(e)||!qI(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||dt(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===Vr&&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!dt(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},qU=e=>e===void 0?"absent":JU(e)?"exact":XU(e)||zU(e)?"stale-owned":"foreign",Ze=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},na=async e=>{let t=await R(e),n;try{n=await F(e)}catch{throw new Ze(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!ta(n.mcpServers))throw new Ze(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(ta(n.mcpServers)?n.mcpServers:void 0)?.[fu];return{path:e,fileExisted:t,json:n,entry:o,ownership:qU(o)}},hu=e=>{if(e.ownership==="foreign")throw new Ze(`MCP name conflict in ${e.path}: mcpServers.${fu} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},QI=(e,t)=>{let n={...e},r=ta(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[fu]:r[fu]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},ky=async(e,t)=>{if(Ay(e.entry,t))return;let n=await na(e.path);if(!Ay(n.entry,e.entry))throw new Ze(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await vr(e.path,QI(n.json,t)),{reading:e,afterEntry:t}},vy=async e=>{let t=await na(e.reading.path);if(!Ay(t.entry,e.afterEntry))throw new Ze(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=QI(t.json,e.reading.entry);await vr(e.reading.path,n)},QU=async e=>{if(!te())throw new Ze(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${De()} is temporary); no inference setting was changed.`);let t=await na(mu(e));hu(t);let n=Sy(e),r=(e.platform??mo)()==="darwin"&&n!==t.path?await na(n):void 0;return r&&hu(r),{active:t,...r?{legacy:r}:{}}},YI=async e=>{let t=await na(mu(e));hu(t);let n=Sy(e),r=(e.platform??mo)()==="darwin"&&n!==t.path?await na(n):void 0;return r&&hu(r),{active:t,...r?{legacy:r}:{}}},eH=async e=>{let t=[];try{let n=await ky(e.active,zI());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await ky(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await vy(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ze(`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 vy(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Ze(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},tH=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await ky(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await vy(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ze(`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)},ZI=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)."]},nH={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Iy="claude-desktop",Ey="migrate",yu="migrate-config",rH=[Ey,yu],JI=async e=>{await od(Iy,e?Ey:yu,{precedence:rH})},eE=new Set(["app-running","store-missing"]),oH={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},aH={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"}},sH="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",tE=e=>{let t=(e.platform??mo)(),n=e.home??cc;return{home:n,appRunning:e.appRunning??ls(t),firstPartyRoot:()=>Xo({home:n,runtimePlatform:t}),thirdPartyRoot:()=>kr({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},nE=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=oH[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.`:"")},rE=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=aH[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.`:"")},ic=async(e,t)=>{try{let n=du(t.reportsToUser===!0),r=ac(n,"session"),o={...tE(e),assetClasses:n},a=await(e.pendingDesktopMigrationCount??UI)(o),s=a.userSkills+a.userPlugins+a.localMcpServers;if(a.sessions+s===0)return[];if(t.dryRun)return[`Would bring ${[a.sessions>0?`${a.sessions} existing Claude Desktop session${a.sessions===1?"":"s"}`:"",s>0?`${s} portable configuration ${s===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 i=await(e.migrateDesktopProfile??ea)(o);if(i.ok){let d=nE(i.lanes),u=rE(i.portableAssets),p=i.ambiguousAssets??[],m=p.length>0?`Claude Desktop has more than one target ${p.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(i.blocked??[]).filter(A=>A.reason!=="ambiguous"),h=i.blockedAssets??[],w=i.deferredAssets??[],y=i.retryableAssets??[];if(f.length===0&&h.length===0&&w.length===0&&y.length===0)return[d,u,m].filter(A=>!!A);if(t.preservePendingOp)return[d,u,m].filter(A=>!!A);await JI(r);let g=f.reduce((A,E)=>A+E.waiting,0),b=[g>0?`${g} more session${g===1?"":"s"}`:"",h.length>0?`${h.length} extension ${h.length===1?"store":"stores"}`:""].filter(Boolean),k=[...b.length>0?[`Queued: ${b.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...w.length>0?[`Queued: ${w.length} portable configuration ${w.length===1?"store moves":"stores move"} across the next time you fully quit Claude Desktop.`]:[],...y.length>0?[`Queued: ${y.length} portable configuration ${y.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...d?[d]:[],...u?[u]:[],...m?[m]:[],...k]}if(!eE.has(i.kind))return[`Your existing Claude Desktop local data was left where it is: ${i.reason}.
|
|
281
|
-
${i.remedy}`];if(t.preservePendingOp)return[];await JI(r);let c=a.sessions+s,l=`${c} Claude Desktop local ${c===1?"item":"items"}`;return[i.kind==="store-missing"?`Queued: the ${l} 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 ${l} still in your previous profile will move across the next time you fully quit Claude Desktop.`]}catch(n){return n instanceof Js?["Claude Desktop's carry queue was busy; Connect will retry on the next reconcile."]:["Could not check whether Claude Desktop had existing sessions to bring across; run `anyray-connect migrate` if its lists look empty."]}},iH=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await eo(Iy),[]}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."]}},cH=e=>HI({id:Iy,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??mo)(),n=(e.home??cc)();return t==="darwin"?["/Applications/Claude.app",Zn(n,"Applications","Claude.app")]:t==="win32"?[Zn(process.env.LOCALAPPDATA??Zn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>ae(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:",...ZI(t)]:["Claude desktop org/API lane:",...ZI(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`."]}),lH=(e={})=>{let t=cH(e),n=()=>(e.platform??mo)()==="darwin",r=()=>(e.platform??mo)()==="win32",o=(s,i)=>n()?OS(s,i,e):iI(s,s.clientKey??"",i,e),a=s=>n()?_S(s,e):cI(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ls((e.platform??mo)()))(),quitTarget:nH,needsTarget:()=>!1,async complete(s){if(s!==Ey&&s!==yu)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??ea)({...tE(e),assetClasses:s===yu?du(!1):du(!0)});if(i.ok){let c=nE(i.lanes),l=rE(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(w=>w.reason!=="ambiguous"),m=i.blockedAssets??[],f=i.deferredAssets??[],h=i.retryableAssets??[];return p.length>0||m.length>0||f.length>0||h.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...p.length>0||m.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."]:[],...f.length>0?["Claude Desktop came back up; its skill and plugin stores are copied the next time it is fully quit."]:[],...h.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(w=>!!w):["No portable Claude Desktop data was left to bring across."]}}return eE.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?PS(s,e):r()?uI(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let p=hn(e),m=await qo(p,e);if(m)return{status:"manual",manualAudience:"admin",messages:[Vh(m),...await ic(e,i)]}}if(r()){let p;try{p=await fo(e.runReg??Ir)}catch{return{status:"manual",manualAudience:"admin",messages:[sH,...await ic(e,i)]}}if(p)return{status:"manual",manualAudience:"admin",messages:[ly(p),...await ic(e,i)]}}if(r()&&ae(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 us(e);if(!p.supported)return{status:"manual",messages:[p.message??"Claude Desktop version is unsupported."]}}let c;try{c=await QU(e)}catch(p){let m=p instanceof Ze?p.changedFiles:[];return{status:"manual",...m.length>0?{changedFiles:m}:{},messages:[p instanceof Ze?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 ic(e,i)]}}let d;try{d=await eH(c)}catch(p){let m=p instanceof Ze?p.changedFiles:[];return{status:"manual",...m.length>0?{changedFiles:m}:{},messages:[p instanceof Ze?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 ic(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?YU:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=mu(e),c=await iH(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 YI(e)}catch(h){return l({status:"manual",messages:[h instanceof Ze?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()?Qt(e):void 0;if(!(h!==void 0&&p.changedFiles?.includes(h)===!0&&!await R(h)))return l(p)}let m;try{m=await tH(await YI(e))}catch(h){let w=h instanceof Ze?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...p.changedFiles??[],...w])],messages:[...p.messages,h instanceof Ze?h.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await pe(i);let f=Sy(e);return n()&&f!==i&&await pe(f),l({...p,messages:[...p.messages,...m.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...p.changedFiles??[],...m])]})},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await na(mu(e));return s.ownership!=="exact"||!ta(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 us(e)).supported?Yh(s,e):!1:r()?dI(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await us(e)).supported)return["unknown"];let s=await TS(e);return s?[s]:["unknown"]}if(r())return await R(Qt(e))?await fo(e.runReg??Ir)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=hn(e);return!await R(s.journal)||await qo(s,e)?!1:(await us(e)).supported}return r()&&await R(Qt(e))?!await fo(e.runReg??Ir):!1}catch{return!1}}}},oE=lH();import{homedir as MH}from"node:os";import{join as BH}from"node:path";import{rm as Iu}from"node:fs/promises";import{constants as aE,accessSync as dH,statSync as uH}from"node:fs";import{platform as xy}from"node:os";import{delimiter as pH,posix as fH,resolve as mH,win32 as hH}from"node:path";var yH="0.59.0",gH="1.1.4",Er="Anyray \xB7 Claude",xr="Anyray \xB7 Codex",gu="__anyray-acp-agent",sE=(e,t,n)=>{let{command:r,args:o}=Sn([gu,e,t,n]);return{command:r,args:o,env:{}}},wu=(e=xy())=>e==="win32"?"npx.cmd":"npx",bu=(e=process.env.PATH,t=xy())=>{if(!e)return;let n=wu(t);for(let r of e.split(pH)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=mH(o,n);try{if(!uH(a).isFile())continue;return dH(a,t==="win32"?aE.F_OK:aE.X_OK),a}catch{}}},Cu=(e,t=xy())=>{let n=t==="win32"?hH:fH;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==wu(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},wH="https://chatgpt.com/backend-api/codex",bH="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",iE="ANYRAY_ACP_CODEX_AUTHORIZATION",cE="ANYRAY_ACP_CODEX_CLIENT_KEY",lE="ANYRAY_ACP_CODEX_METADATA",dE=e=>be({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),CH=(e,t={})=>{let n=ae(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":wH,"x-anyray-forward-headers":bH}:{},o=n?{...e.clientKey?{"x-anyray-api-key":cE}:{}}:{Authorization:iE};return dE(e)&&(o["x-anyray-metadata"]=lE),{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}}}:{}}},AH=e=>{let t=ae(e,"openai"),n=dE(e);return{...t?e.clientKey?{[cE]:e.clientKey}:{}:{[iE]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[lE]:n}:{}}},uE=(e,t=wu(),n={})=>({[Er]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${yH}`],env:En(e).env},[xr]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${gH}`],env:{CODEX_CONFIG:JSON.stringify(CH(e,n)),...AH(e)}}}),lc=(e=wu(),t="jetbrains")=>({[Er]:sE("claude",e,t),[xr]:sE("codex",e,t)}),ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Au=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as kH}from"node:zlib";import{open as vH,readFile as Py,readdir as Su}from"node:fs/promises";import{dirname as pE,join as Ce}from"node:path";import{homedir as yE,platform as Dy}from"node:os";var ku="2025.3.2",ps="253.30387.147",dc="com.intellij.ml.llm",Ry=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),SH=1e4,IH=256*1024*1024,EH=16*1024*1024,Oy=1024*1024,_y=22,xH=_y+65535,Ty=Fd,RH=()=>{let e=yE(),t=Ce(e,".cache","JetBrains","RemoteDev");switch(Dy()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:Ce(e,"Applications"),layout:"app-bundles"},{path:Ce(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:Ce(process.env.LOCALAPPDATA??Ce(e,"AppData","Local"),"Programs"),layout:"children"},{path:Ce(process.env.LOCALAPPDATA??Ce(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:Ce(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:Ce(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},OH=()=>Dy()==="linux"?Ce(yE(),".local","share","JetBrains"):Ue("JetBrains"),_H=()=>Dy()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),TH=async(e,t=SH)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await Su(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=Ce(r.path,i.name),l=r.layout==="app-bundles"?Ce(c,"Contents","Resources","product-info.json"):Ce(c,"product-info.json");await R(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=Ce(s,"product-info.json"),l=Ce(s,"Contents","Resources","product-info.json");if(await R(c)){n.push(c);return}if(await R(l)){n.push(l);return}let d;try{d=await Su(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let p=Ce(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)]},PH=e=>{let t=pE(e);return t.endsWith(`${Ce("Contents","Resources")}`)?pE(t):t},DH=async e=>{try{let t=JSON.parse(await Py(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Ki(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:PH(e)}}catch{return}},vu=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},LH=async(e,t)=>{let n;try{n=await vH(e,"r");let{size:r}=await n.stat();if(r<_y||r>IH)return;let o=Math.min(r,xH),a=await vu(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-_y;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>EH||c+i>r)return;let l=await vu(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),m=l.readUInt32LE(d+24),f=l.readUInt16LE(d+28),h=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),g=d+46+f+h+w;if(g>l.length)return;let b=l.subarray(d+46,d+46+f).toString("utf8");if(d=g,b!==t)continue;if(p===4294967295||m===4294967295||p>Oy||m>Oy)return;let k=await vu(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let A=k.readUInt16LE(26),E=k.readUInt16LE(28),O=await vu(n,p,y+30+A+E);return O?u===0?O.toString("utf8"):u===8?kH(O,{maxOutputLength:Oy}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},fE=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Ki(n)))return{id:t,version:n}},NH=async(e,t)=>{let n=Ce(e,"META-INF","plugin.xml");if(await R(n))try{let o=fE(await Py(n,"utf8"));return{present:o?.id===dc||t,descriptor:o?.id===dc?o:void 0}}catch{return{present:t}}let r=[];try{r=(await Su(Ce(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=>Ce(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await LH(o,"META-INF/plugin.xml"),s=a?fE(a):void 0;if(s?.id===dc)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},mE=async e=>{let t;try{t=await Su(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Ry.has(o.name.toLowerCase()),i=Ry.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Ry.has(o.name.toLowerCase());if(!a){let i=Ce(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await NH(Ce(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},$H=async e=>{try{return(await Py(Ce(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(dc)}catch{return!1}},hE=e=>e.reduce((t,n)=>t?(Ty(n,t)??-1)>0?n:t:n,void 0),gE=async(e={})=>{let t=e.configRoot??Ue("JetBrains"),n=e.userPluginsRoot??OH(),r=await TH(e.productRoots?e.productRoots.map(f=>({path:f,layout:"recursive"})):RH(),e.scanBudget),o=(await Promise.all(r.map(f=>DH(f)))).filter(f=>f!==void 0),a=o.length>0||await R(t);if(e.wsl??_H())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(f=>(Ty(f.version,ku)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let f of s){let h=Ce(t,f.dataDirectoryName);if(!await R(h)){d=!0;continue}let w=[Ce(h,"plugins"),Ce(n,f.dataDirectoryName),Ce(n,f.dataDirectoryName,"plugins")],y;for(let g of[...new Set(w)]){let b=await mE(g);if(b.present){y=b;break}}if(y??=await mE(Ce(f.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==dc)){if(i.push(y.descriptor.version),await $H(h)){c=!0;continue}if(!((Ty(y.descriptor.version,ps)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${f.version}; AI Assistant ${y.descriptor.version}; ACP supported`,ideVersion:f.version,pluginVersion:y.descriptor.version}}}let u=hE(o.map(f=>f.version)),p=hE(i),m;return a?u?s.length===0?m=`JetBrains IDE ${u} is below the ACP minimum ${ku}; no ACP config was written.`:d?m=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${ku}+ once, enable AI Assistant ${ps}+, then run Connect again. No ACP config was written.`:c?m=`JetBrains AI Assistant is disabled; enable version ${ps}+ and run Connect again. No ACP config was written.`:p?m=`JetBrains AI Assistant ${p} is below the ACP minimum ${ps}; no ACP config was written.`:l?m=`Could not verify the local JetBrains AI Assistant version; require ${ps}+ before running Connect. No ACP config was written.`:m=`JetBrains AI Assistant ${ps}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:m=`Could not prove JetBrains IDE ${ku}+ from local product-info.json; no ACP config was written.`:m="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:m,ideVersion:u,pluginVersion:p}};var FH=[Er,xr],Ly=()=>BH(MH(),".jetbrains","acp.json"),oa=()=>`${Ly()}.anyray-state`,WH=(e,t,n="npx")=>{let r=ra(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,lc(n,"jetbrains")),{...e,agent_servers:r}},UH=(e,t,n)=>{if(!ra(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=ra(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of FH)if(c in r){if(!Au(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}},HH=(e=gE)=>({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=Ly(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=bu();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await R(r),c;try{c=await F(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=lc(a,"jetbrains");return await sl({configPath:r,current:c,next:WH(c,t,a),journalPath:oa(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,oa()]}},async revert(t){let n=Ly(),r=async()=>{if(!await R(n))return t.dryRun||(await pe(n),await Iu(oa(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await F(n)}catch{return t.dryRun||(await pe(n),await Iu(oa(),{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 F(oa());(u.version===1||u.version===2)&&ra(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await R(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await F(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 Ro(n);let l=UH(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 Iu(n,{force:!0}):await q(n,l.next,{backup:!1})),t.dryRun||(await pe(n),await Iu(oa(),{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():al(n,oa(),r)}}),wE=HH();import{homedir as xu}from"node:os";import{join as Ru}from"node:path";import{rm as Ny}from"node:fs/promises";var $y="1.0.0",Ou=["anyray-claude-acp","anyray-codex-acp"],GH=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],My=()=>Ru(xu(),".windsurf","acp","registry.json"),By=()=>Ru(xu(),".windsurf-next","acp","registry.json"),fs=e=>`${e}.anyray-state`,bE=e=>({binary:Object.fromEntries(GH.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),AE=(e="npx")=>{let t=lc(e,"windsurf");return[{id:Ou[0],name:Er,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:bE(t[Er])},{id:Ou[1],name:xr,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:bE(t[xr])}]},Eu=e=>!Array.isArray(e)||e.some(t=>!ra(t)||typeof t.id!="string")?null:e,KH=(e,t="npx")=>{if(e.version!==void 0&&e.version!==$y||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:Eu(e.agents);if(!n)return null;let r=new Set(Ou);return{...e,version:typeof e.version=="string"?e.version:$y,agents:[...n.filter(o=>!r.has(o.id)),...AE(t)],extensions:e.extensions??[]}},VH=(e,t,n)=>{let r=Eu(e.agents);if(!r)return null;let o=Eu(t.agents)??[],a=new Map((Eu(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!Ou.includes(u.id)){l.push(u);continue}if(!Au(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===$y&&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}},CE=async()=>{let e=[];return(await R(By())||await R(Ru(xu(),".windsurf-next")))&&e.push(By()),(await R(My())||await R(Ru(xu(),".windsurf"))||await R(Ue("Devin"))||await R(Ue("Windsurf")))&&e.push(My()),e},kE={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await CE();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await CE();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=bu();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 F(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=KH(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await R(s),d=AE(r);await sl({configPath:s,current:i,next:c,journalPath:fs(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,fs(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=[My(),By()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await pe(a),await Ny(fs(a),{force:!0}).catch(()=>{}));return}let i;try{i=await F(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 m=await F(fs(a));(m.version===1||m.version===2)&&Array.isArray(m.agents)&&(c=m.agents,l=m.version===2&&m.fileExisted===!1,d=m.version===2&&m.fileExisted===!0)}catch{}let u;if(d){let m=`${a}.anyray-bak`;if(!await R(m)){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 F(m)}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 Ro(a);let p=VH(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 Ny(a,{force:!0}):await q(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 pe(a),await Ny(fs(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await al(a,fs(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var se=[Zr,rA,Ii,dv,$v,Yv,eS,wE,oE,kE,pA],qe=e=>se.find(t=>t.id===e);var Je=async(e=$,t=Wn)=>{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 Fy=5e3,vE=3e4,jH=1440*60*1e3,YH=e=>new Promise(t=>setTimeout(t,e)),ZH=async(e=$,t=Wn)=>(await Je(e,t))?.target,JH=e=>qe(e)?.quitGated,SE=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??JH,o=t.readPending??Ci,a=t.clearPending??wm,s=t.targetFromProfile??ZH,i=t.sleep??YH,c=t.now??Date.now,l=t.maxWaitMs??jH;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),p=c(),m=Fy;for(;;){let f=await o(n);if(!f||c()-p>l)return 0;if(d.isRunning()){await i(m),m=Math.min(vE,m*2);continue}let h;if(d.needsTarget?.(f.op)&&(h=await s(),!h)){if(await a(n,f)!=="superseded")return 0;await i(m),m=Fy;continue}if((await u(f.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(m),m=Math.min(vE,m*2);continue}if(await a(n,f)!=="superseded")return 0;await i(m),m=Fy}}catch{return 0}};import{z as pc}from"zod";import{createHash as XH,randomBytes as zH,timingSafeEqual as qH}from"node:crypto";import{createServer as QH}from"node:http";var uc="127.0.0.1",eG=2147483647,tG="/callback",Wy=12,nG="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",Uy=e=>e.length===Wy&&[...e].every(t=>nG.includes(t)),Jn=class extends Error{kind;constructor(t,n){super(n),this.name="ConnectorOauthCallbackError",this.kind=t}},aa=(e,t,n)=>{e.writeHead(t,{"cache-control":"no-store","content-security-policy":"default-src 'none'","content-type":"text/plain; charset=utf-8","referrer-policy":"no-referrer","x-content-type-options":"nosniff"}),e.end(n)},rG=e=>new Promise(t=>{if(e.writableFinished||e.destroyed){t();return}e.once("finish",()=>t()),e.once("close",()=>t())}),IE=async()=>{let e;try{e=zH(32).toString("base64url")}catch{throw new Jn("listen","Could not open a local callback port for the browser.")}let t=Buffer.from(XH("sha256").update(e).digest("base64url")),n=p=>{let m=Buffer.from(p);return m.length===t.length&&qH(m,t)},r,o=()=>{},a=new Promise(p=>{o=p}),s=!1,i=QH((p,m)=>{if(p.socket.remoteAddress!==uc||p.method!=="GET"||p.url===void 0||!p.url.startsWith("/")||p.headers.host!==r){aa(m,404,"Not found.");return}let f;try{f=new URL(p.url,`http://${uc}`)}catch{aa(m,404,"Not found.");return}if(f.pathname!==tG){aa(m,404,"Not found.");return}let h=[...f.searchParams.entries()],w=f.searchParams.getAll("claim"),y=f.searchParams.getAll("nonce"),g=w[0]??"";if(h.length!==2||w.length!==1||y.length!==1||!Uy(g)||!n(y[0]??"")){aa(m,404,"Not found.");return}if(s){aa(m,409,"Callback already received.");return}s=!0,o({status:"claim",claimCode:g,response:m})}),c=()=>new Jn("listen","Could not open a local callback port for the browser.");try{await new Promise((p,m)=>{let f=h=>m(h);i.once("error",f),i.listen({host:uc,port:0},()=>{i.off("error",f),p()})})}catch{throw i.close(),c()}let l=i.address();if(l===null||typeof l=="string"||l.address!==uc||l.port<=0)throw i.close(),c();let d=l.port;r=`${uc}:${d}`;let u=async()=>{i.listening&&await new Promise(p=>{i.close(()=>p()),i.closeAllConnections()})};return i.on("error",()=>{s||(s=!0,o({status:"unavailable"}))}),{port:d,nonce:e,waitForClaim:async(p,m)=>{let f;try{f=await new Promise((h,w)=>{let y=!1,g=A=>{y||(y=!0,clearTimeout(k),m.signal?.removeEventListener("abort",b),A())},b=()=>g(()=>w(new Jn("lost","Connector authorization was cancelled."))),k=setTimeout(()=>g(()=>w(new Jn("timeout","Timed out waiting for the browser."))),Math.min(Math.max(m.timeoutMs,0),eG));if(m.signal?.aborted){b();return}m.signal?.addEventListener("abort",b,{once:!0}),a.then(A=>g(()=>h(A)))})}catch(h){throw await u(),h}if(f.status==="unavailable")throw await u(),new Jn("lost","The local callback port stopped listening.");try{let h=await p(f.claimCode);return aa(f.response,200,"Connected. You can close this window."),h}catch(h){throw aa(f.response,502,"Anyray could not finish connecting. Return to the terminal."),h}finally{await rG(f.response),await u()}},close:u}};import{spawn as oG}from"node:child_process";import{platform as aG}from"node:os";var sG=2e3,Rr=e=>new Promise(t=>{try{let n=new URL(e);if(n.protocol!=="https:"&&n.protocol!=="http:"){t(!1);return}let r=aG(),o=r==="darwin"?"open":r==="win32"?"cmd":"xdg-open",a=r==="win32"?["/c","start",'""',`"${n.href}"`]:[n.href],s=oG(o,a,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:r==="win32"}),i=!1,c=d=>{i||(i=!0,clearTimeout(l),t(d))},l=setTimeout(()=>c(!0),sG);l.unref(),s.on("error",()=>c(!1)),s.on("exit",d=>c(d===0)),s.unref()}catch{t(!1)}});import{fstatSync as mG,openSync as hG,statSync as yG}from"node:fs";import{createInterface as gG}from"node:readline/promises";import{ReadStream as wG}from"node:tty";import{execFileSync as EE}from"node:child_process";import iG from"node:os";var Hy=e=>{try{return EE("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},cG=e=>{try{return EE("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},lG=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"]),Gy=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:lG.has(t):!0},_u=()=>{try{return iG.userInfo().username||void 0}catch{return}},xE=()=>Hy("user.name")??Hy("user.email")??_u()??"unknown",RE=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Hy),global:e.globalGitConfig??(t||cG)}},sa=e=>{try{return e()?.trim()||void 0}catch{return}},Ky=(e={})=>{let t=RE(e),n=sa(e.osUsername??_u),r=sa(()=>t.global("user.email"))??sa(()=>t.local("user.email"));return r||(sa(()=>t.global("user.name"))??sa(()=>t.local("user.name"))??n??"unknown")},OE=(e={})=>{let t=Ky(e);if(Gy(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=RE(e);return!!(sa(()=>n.global("user.email"))??sa(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var ms=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,dG=ms(process.stdout,process.env),Vy=ms(process.stderr,process.env),Tu=!1,hs=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,jy=()=>{Tu=!0},Yy=()=>{Tu=!1},Pu=()=>Tu?Vy:dG,Du=e=>{Tu?console.error(e):console.log(e)},Z=e=>hs("1",e,Pu()),v=e=>hs("2",e,Pu()),uG=e=>hs("32",e,Pu()),pG=e=>hs("33",e,Vy),fG=e=>hs("31",e,Vy),st=e=>hs("36",e,Pu()),C=e=>Du(e),U=e=>Du(`
|
|
282
|
-
${Z(e)}`),M=e=>Du(v(e)),B=e=>Du(`${uG("\u2713")} ${e}`),P=e=>console.error(`${pG("!")} ${e}`),D=e=>console.error(`${fG("\u2717")} ${e}`);var Et=()=>!!process.stdin.isTTY,bG=()=>{try{let e=mG(0);return e.isCharacterDevice()&&e.rdev===yG("/dev/tty").rdev}catch{return!1}},Zy=()=>{if(bG()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new wG(hG(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},It=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},_E=async(e,t)=>{let n=t.input??Zy(),r=t.output??process.stdout,o=gG({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 It))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new It)))})}finally{o.close(),n.close()}},
|
|
274
|
+
}`,Ir=async e=>new Promise((t,n)=>{let r=AW("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",DW],{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(zh(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(zh({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Qt=(e={})=>cs((e.home??ty)(),".anyray","claude-desktop-windows.json"),LW=e=>cs((e.home??ty)(),".anyray","claude-desktop-windows.lock"),as=class extends Error{},NW=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},ay=async e=>{let t=LW(e);await Zh(nc(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=ZS("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=cs(t,"owner.json");try{await Zh(t,{mode:448}),await Se(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
275
|
+
`)}catch(a){if(a.code!=="EEXIST")throw await yn(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await Jh(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!NW(i.pid)}catch{try{s=Date.now()-(await QS(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new as;await yn(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await Jh(o,"utf8")).nonce===r&&await yn(t,{recursive:!0,force:!0})}catch{}}}throw new as},aI=()=>Object.fromEntries(He.map(e=>[e,{present:!1}])),ea=e=>ZS("sha256").update(e).digest("hex"),$W=(e,t)=>t.present?e===ls?{present:!0,type:t.type,sha256:ea(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},rs=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?ea(e.value??"")===t.sha256:e.value===t.value:!0,qt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),tu=(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===ls?qt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:qt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},BS=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&qt(e,He)&&He.every(t=>tu(e[t],t)),FS=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&qt(e,DS)&&DS.every(t=>tu(e[t],t)),MW=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),sy=(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 qt(n,r)&&n.path===ny(t)&&(n.lastWritten===void 0||MS(n.lastWritten))&&(n.pending===void 0||MS(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},BW=(e,t)=>qt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===eu&&e.registryKey===Fe&&typeof e.keyExisted=="boolean"&&BS(e.lastWritten)&&(e.pending===void 0||BS(e.pending))&&sy(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),FW=e=>qt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Fe&&typeof e.keyExisted=="boolean"&&FS(e.lastWritten)&&(e.pending===void 0||FS(e.pending)),WS=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&qt(e,LS)&&LS.every(t=>tu(e[t],t)),WW=(e,t)=>qt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===Fe&&typeof e.keyExisted=="boolean"&&WS(e.lastWritten)&&(e.pending===void 0||WS(e.pending))&&sy(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),US=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&qt(e,NS)&&NS.every(t=>tu(e[t],t)),UW=(e,t)=>qt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===Fe&&typeof e.keyExisted=="boolean"&&US(e.lastWritten)&&(e.pending===void 0||US(e.pending))&&sy(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),HS=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),iy=e=>{let{pending:t,...n}=e;return{...n,version:eu,lastWritten:HS(e.lastWritten),...t?{pending:HS(t)}:{}}},GS=e=>({...e,chatTabEnabled:{present:!1}}),HW=e=>{let{pending:t,...n}=e;return iy({...n,version:4,lastWritten:GS(e.lastWritten),...t?{pending:GS(t)}:{}})},KS=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),GW=(e,t)=>iy({version:4,registryKey:Fe,keyExisted:e.keyExisted,lastWritten:KS(e.lastWritten),...e.pending?{pending:KS(e.pending)}:{},helper:{path:ny(t)}}),cy=async(e,t=!0)=>{let n=Qt(e),r=nc(n),o=`${eI(n)}.anyray-old-`,a=(await zS(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>cs(r,l)),s=n;if(!await R(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await qS(a[0],n):s=a[0]}let i=await F(s),c=FW(i)?GW(i,e):WW(i,e)?HW(i):UW(i,e)?iy(i):BW(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>yn(l,{force:!0}))),c},VS=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),KW=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Fe,keyExisted:e.keyExisted,lastWritten:VS(e.lastWritten),...e.pending?{pending:VS(e.pending)}:{}}:e,zd=async(e,t)=>{let n=Qt(t),r=`${JSON.stringify(KW(e),null,2)}
|
|
276
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await Se(n,r)},VW=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,jW=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),YW=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),ZW=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),JW=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===ZW(t).toUpperCase(),jS=(e,t,n,r,o)=>{let a=He.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},XW=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,zW=(e,t)=>{if(!Vd(e,!0))return!1;let n=XW(t);if(YW.has(n))return!1;if(jW.has(n))return n==="REG_EXPAND_SZ"?!0:!cS(e,!0)},qW=(e,t)=>{let n=aI(),r=!1,o=!1,a=!1,s=t.toUpperCase()===tc.toUpperCase(),i=(l,d)=>{if(!s)return;let u=zW(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),jS(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||JW(d,t))continue;let u=VW.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),jS(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Sr=async(e,t=Fe)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:aI(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return qW(n.stdout,t)},fo=async e=>{let t=await Sr(e,tc);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...He.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},ly=e=>e.unparsed?`This machine may have a Claude policy under ${tc} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${tc} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${tc} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var nu=(e,t)=>po(qo(e,t)),sI=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],QW=(e,t)=>{let n=nu(e,t);return Object.fromEntries(He.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},eU=(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}}),tU=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,qh=e=>Object.fromEntries(He.map(t=>[t,$W(t,e[t])])),YS=(e,t,n,r)=>({version:eu,registryKey:Fe,keyExisted:e,lastWritten:qh(t),helper:{path:n,lastWritten:Xh(r)}}),nU=(e,t,n,r,o,a)=>({version:eu,registryKey:Fe,keyExisted:e,lastWritten:qh(t),pending:qh(n),helper:{path:r,...o?{lastWritten:Xh(o)}:{},pending:Xh(a)}}),Qh=(e,t,n)=>rs(n,e.lastWritten[t])||e.pending!==void 0&&rs(n,e.pending[t]),ss=async e=>{try{let t=await Jh(e,"utf8");return{content:t,sha256:ea(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},is=async e=>(await ss(e))?.sha256,os=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Qd=async(e,t)=>{let n=TW(e),r;try{r=await zS(nc(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>cs(nc(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([ss(e),ss(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!os(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await oI(e,a))throw new Error("credential helper changed during recovery");return}if(t&&os(t,s.sha256)&&os(t,i.sha256)){await yn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},dy=async(e,t,n)=>(n.present?await e(sI(Fe,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Fe,"/v",t,"/f"])).code===0,rU=async(e,t,n)=>{let r=!0,o=await Sr(e);for(let a of He)if(!ns(o.values[a],t[a])){if(!ns(o.values[a],n[a])){r=!1;continue}await dy(e,a,t[a])||(r=!1),o=await Sr(e)}return r&&He.every(a=>ns(o.values[a],t[a]))},at=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Qt(n)]}}),iI=async(e,t,n,r={})=>{if(!Pe(t))return at("A valid personal ark_ gateway key is required.",!1,r);let o=ny(r),a;try{a=EW((r.credentialCommand??Wh)())}catch{return at("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=ea(a),i=r.runReg??Ir,c=Qt(r),l;if(!n.dryRun)try{l=await ay(r)}catch(h){return at(h instanceof as?"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,m,f=!1;try{let h=await fo(i);if(h)return at(ly(h),!1,r);let w=await cy(r,!n.dryRun);n.dryRun||await Qd(o,w);let y=await Sr(i),g=QW(e,o),b=await ss(o),k=b?.sha256,A=!1;if(d=w,u=y,p=g,w){let S=He.find(I=>!Qh(w,I,y.values[I]));if(S)return at(`Claude's ${S} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!os(w,k))return at(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);A=tU(w)}else{if(k!==void 0&&k!==s)return at(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let S=y.foreignState||He.some(O=>y.values[O].present),I=He.every(O=>ns(y.values[O],g[O])),E=He.every(O=>ns(y.values[O],eU(e,t.trim())[O]));if(S&&!I&&!E)return at(`Existing Claude third-party-inference policy values under ${Fe} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(A=E,I&&k===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Fe} into an owner-only journal without rewriting them.`]}:(await zd(YS(y.keyPresent,g,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Fe} into the ownership journal.`]})}if(A){let S=!0;try{S=(r.appRunning??oy)()}catch{}if(S)return at("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let x=nU(w?.keyExisted??y.keyPresent,y.values,g,o,b?.content,a);if(m=x,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Fe}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await zd(x,r),f=!0;for(let S of He){let I=await Sr(i);if(!rs(I.values[S],x.lastWritten[S])&&!rs(I.values[S],x.pending[S]))throw new Error("registry value changed during apply");if(!ns(I.values[S],g[S])&&!await dy(i,S,g[S]))throw new Error("registry write failed")}let _=await Sr(i);if(!He.every(S=>rs(_.values[S],x.pending[S])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await _W(o,a):await qd(o,k,a,"apply",r)),await is(o)!==s)throw new Error("credential helper verification failed");return await zd(YS(x.keyExisted,g,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Fe}.`,`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.",...Hd(Ot("migrate"))]}}catch{if(!f||!u||!p||!m)return at("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Qd(o,m);let h=!0,w=await ss(o),y=m.helper.pending;if(w?.sha256!==m.helper.lastWritten?.sha256&&(y!==void 0&&w?.sha256===y.sha256?m.helper.lastWritten?(await qd(o,y.sha256,m.helper.lastWritten.content,"rollback",r),h=await is(o)===m.helper.lastWritten.sha256):await qd(o,y.sha256,void 0,"rollback",r):h=w===void 0&&m.helper.lastWritten===void 0),h&&await rU(i,u.values,p))return d?await zd(d,r):await yn(c,{force:!0}),at("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return at("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?.()}},cI=async(e,t={})=>{let n=t.runReg??Ir,r=Qt(t),o;if(!e.dryRun)try{o=await ay(t)}catch(a){return at(a instanceof as?"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 cy(t,!e.dryRun);a&&!e.dryRun&&await Qd(a.helper.path,a);let s=await Sr(n);if(!a)return He.filter(f=>s.values[f].present).length>0?at(`Claude policy values exist under ${Fe}, 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=He.filter(m=>s.values[m].present&&!Qh(a,m,s.values[m])),c=await is(a.helper.path),l=c!==void 0&&!os(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Fe}.`,`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 m of He){let h=(await Sr(n)).values[m];if(h.present){if(!Qh(a,m,h)){u.add(m);continue}await dy(n,m,{present:!1})||(d=!0)}}let p=await is(a.helper.path);if(p!==void 0)if(os(a,p))try{await qd(a.helper.path,p,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?at(`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 yn(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Fe}.`,"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?[]:Gd]})}catch{return at(`Could not safely inspect or revert ${Fe}; no unproven value was removed.`,!1,t)}finally{await o?.()}},lI=async(e,t={})=>{let n=t.runReg??Ir;if(!await R(Qt(t)))return;let r;try{r=await ay(t);let o=await cy(t);if(o&&await Qd(o.helper.path,o),!o||o.pending||await fo(n)!==void 0)return;let a=await Sr(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===ct(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&He.every(l=>rs(a.values[l],o.lastWritten[l]))))return;let i=await is(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 OW(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?.()}},dI=async(e,t={})=>await lI(e,t)!==void 0,uI=async(e,t={})=>await lI(e,t)==="dynamic";var ds=(e=fI())=>e==="win32"?oy:Zd,py=(e=fI())=>e==="win32"?ry:Fh,uy="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",ou=async(e,t={})=>{let n=(t.profileRoot??kr)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:uy};if((t.appRunning??ds(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await pI.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 Ud(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 "+uy}:{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??tS)();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=ru(t.stagingRoot??aU(),`anyray-history-${process.pid}-${oU()}`);try{let s=await(t.runImporter??nS)({binary:o,exportPath:e,configDir:ru(a,"config"),workDir:ru(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. "+uy};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 oS(r.dir,s.conversations),c=await aS({stagedProjectsDir:ru(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 pI.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Nt}from"node:fs";import{homedir as RU}from"node:os";import{join as wn,sep as OU}from"node:path";import{isDeepStrictEqual as cu}from"node:util";import{constants as gI}from"node:fs";import{promises as j}from"node:fs";import{dirname as us,isAbsolute as my,join as ee,relative as au,resolve as gn,sep as rc}from"node:path";import{randomUUID as lu}from"node:crypto";var jn=448,oc=384,wI=448,sU=4,hy=3e4,bI=5e3,iU=10*6e4,CI={config:["skill","plugin","local-mcp"],session:["code","cowork"]},du=e=>e?["config","session"]:["config"],ac=(e,t)=>(e??["config","session"]).includes(t),AI=["carried","pending","nothing_to_carry","not_routed","unreadable","unsupported","unknown"],kI={carried:"Portable Claude Desktop configuration carried",pending:"Portable Claude Desktop configuration pending",nothing_to_carry:"No portable Claude Desktop configuration to carry",not_routed:"Claude Desktop is not routed through Anyray on this machine, so no configuration carry applies",unreadable:"Portable Claude Desktop configuration could not be read",unsupported:"Portable Claude Desktop configuration is unsupported on this host",unknown:"Portable Claude Desktop configuration state is unknown"},fy=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),Ge=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sc=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),vI=(e,t)=>{let n=au(gn(e),gn(t));return n===""||!n.startsWith(`..${rc}`)&&n!==".."&&!my(n)},Yn=async e=>{try{let t=await j.readFile(e,"utf8"),n=JSON.parse(t);return Ge(n)?{raw:t,value:n}:void 0}catch(t){return St(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},St=e=>e instanceof Error&&"code"in e,cU=e=>{try{return process.kill(e,0),!0}catch(t){return St(t)&&t.code==="EPERM"}},SI=e=>e===0?"owner.json":`owner.${e}.json`,su=async e=>{let t;try{t=await j.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=ee(e,r.name),a,s,i;try{let d=JSON.parse(await j.readFile(o,"utf8"));Ge(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 j.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}},II=e=>{if(e.pid===void 0||!cU(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>hy&&t-e.createdAtMs>iU},lU=async e=>{let t=`${e}.anyray-lock`;await j.mkdir(us(t),{recursive:!0,mode:jn});let n=lu(),r,o=!1;try{await j.mkdir(t,{mode:jn}),o=!0}catch(i){if(!St(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await su(t);if(d){if(!II(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await j.stat(t).then(p=>Date.now()-p.mtimeMs).catch(()=>0)<=hy)return}let l=ee(t,SI(c));try{await j.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
277
|
+
`,{flag:"wx",mode:oc}),r=l}catch(d){if(St(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await j.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await j.readFile(a,"utf8"));if(!Ge(i)||i.nonce!==n)return;let c=new Date;await j.utimes(a,c,c)}catch{}})()},bI);return s.unref(),async()=>{clearInterval(s);try{(await su(t))?.nonce===n&&await j.rm(t,{recursive:!0,force:!0})}catch{}}},dU=async(e,t,n)=>{await j.mkdir(us(e),{recursive:!0,mode:jn});let r=await lU(e);if(!r)return!1;try{let o;try{o=await j.readFile(e,"utf8")}catch(s){if(!St(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${lu()}`;try{await j.writeFile(a,`${JSON.stringify(n,null,2)}
|
|
278
|
+
`,{mode:oc,flag:"wx"}),await j.rename(a,e)}catch(s){try{await j.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},uu=async(e,t)=>{for(let n=0;n<sU;n+=1){let r=await Yn(e);if(!r)return"failed";let o=t(r.value);if(!o||cu(o,r.value))return"unchanged";try{if(await dU(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},mI=async e=>{try{return(await j.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},pu=async e=>{let t=[];for(let n of await mI(e))for(let r of await mI(ee(e,n)))t.push(ee(e,n,r));return t},uU=e=>Array.isArray(e.skills)?e.skills.filter(t=>Ge(t)&&sc(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],pU=async e=>{let t=ee(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await pu(t)){let o=await Yn(ee(r,"manifest.json"));if(!o)continue;let a=r.split(rc).at(-1)??"";for(let s of uU(o.value))n.push({account:a,packageDir:r,entry:s})}return n},fU=async e=>{let t=await Yn(ee(e,".claude-plugin","plugin.json"));return!!t&&sc(t.value.name)},mU=(e,t)=>{let n=my(t)?gn(t):gn(e,t);if(!vI(e,n)||n===gn(e))return;let r=au(gn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},hU=async e=>{let t=await pu(ee(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(rc).includes("skills-plugin"))continue;let o=ee(r,"cowork_plugins"),a=await Yn(ee(o,"installed_plugins.json"));if(!a||!Ge(a.value.plugins))continue;let s=r.split(rc).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!sc(i)||!Array.isArray(c)))for(let l of c){if(!Ge(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=mU(o,l.installPath);!d||!await fU(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:ee(r,"cowork_account_settings.json")})}}return n},yU=async e=>{let t=await Yn(ee(e,"claude_desktop_config.json"));return!t||!Ge(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>sc(n)&&n.toLowerCase()!=="anyray"&&Ge(r)))},yy=async e=>{let[t,n,r]=await Promise.all([pU(e),hU(e),yU(e)]);return{skills:t,plugins:n,localMcpServers:r}},gy=async e=>{let t=await yy(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)}},hI=async e=>{try{let n=await j.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())return!1}catch{return!1}let t=async n=>{let r;try{r=await j.readdir(n,{withFileTypes:!0})}catch{return!1}for(let o of r){if(!sc(o.name))return!1;let a=ee(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)},gU=async e=>{let t=async n=>{let r=await j.readdir(n,{withFileTypes:!0});for(let o of r){let a=ee(n,o.name);if(o.isDirectory())await t(a),await j.chmod(a,jn);else if(o.isFile()){let s=await j.stat(a);await j.chmod(a,(s.mode&73)!==0?wI:oc)}}};await t(e),await j.chmod(e,jn)},EI=async(e,t)=>{try{let[n,r]=await Promise.all([j.readFile(e),j.readFile(t)]);return n.equals(r)}catch{return!1}},iu=async(e,t)=>{try{let[n,r]=await Promise.all([j.readdir(e,{withFileTypes:!0}),j.readdir(t,{withFileTypes:!0})]),o=n.map(s=>s.name).sort(),a=r.map(s=>s.name).sort();if(!cu(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 iu(ee(e,s),ee(t,s)))return!1}else if(!i.isFile()||!await EI(ee(e,s),ee(t,s)))return!1}return!0}catch{return!1}},xI=e=>`${e}.anyray-incomplete`,RI=async(e,t)=>{let n=!1;if(t){await j.mkdir(us(e),{recursive:!0,mode:jn});try{await j.mkdir(e,{mode:jn}),n=!0}catch(l){if(!St(l)||l.code!=="EEXIST")return}}else try{let l=await j.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=lu(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let p;try{p=await su(e)}catch{return}if(p){if(!II(p)||!Number.isSafeInteger(p.generation+1))return;d=p.generation+1}else if(await j.stat(e).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=hy)return}let u=ee(e,SI(d));try{await j.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
279
|
+
`,{flag:"wx",mode:oc}),o=u}catch(p){if(St(p)&&p.code==="EEXIST"){n=!1;continue}n&&await j.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await j.readFile(a,"utf8"));if(!Ge(l)||l.nonce!==r)return;let d=new Date;await j.utimes(a,d,d)}catch{}})()},bI);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await su(e))?.nonce===r&&await j.rm(e,{recursive:!0,force:!0})}catch{}}}},OI=async e=>{let t=await RI(e,!1);t&&await t.complete()},wU=async(e,t,n)=>{let r=xI(t),o=!1;try{let c=await j.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await iu(e,t))return await OI(r),"present"}catch(c){if(!St(c)||c.code!=="ENOENT")return"failed"}if(o)try{let c=await j.lstat(r);if(!c.isDirectory()||c.isSymbolicLink())return"conflict"}catch{return"conflict"}let a=await RI(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await j.mkdir(t,{mode:jn})}catch(c){if(!St(c)||c.code!=="EEXIST")return a.abandon(),"failed";try{let l=await j.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 j.readdir(c,{withFileTypes:!0})}catch{return"failed"}for(let u of d){let p=ee(c,u.name),m=ee(l,u.name);try{if(u.isDirectory()){try{await j.mkdir(m,{mode:jn})}catch(h){if(!St(h)||h.code!=="EEXIST")throw h;let w=await j.lstat(m);if(!w.isDirectory()||w.isSymbolicLink())return"conflict"}let f=await s(p,m);if(f!=="copied")return f}else if(u.isFile())try{await j.copyFile(p,m,gI.COPYFILE_EXCL);let f=await j.stat(p);await j.chmod(m,(f.mode&73)!==0?wI:oc)}catch(f){if(!St(f)||f.code!=="EEXIST")throw f;if(!await EI(p,m))return"conflict"}else return"failed"}catch(f){return St(f)&&f.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await iu(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},_I=async(e,t,n,r)=>{if(!await hI(e))return"invalid";try{let a=await j.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await iu(e,t))return await OI(xI(t)),"present"}catch(a){if(!St(a)||a.code!=="ENOENT")return"failed"}await j.mkdir(us(t),{recursive:!0,mode:jn});let o=ee(us(t),`.anyray-stage-${lu()}`);try{return await j.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await hI(o)?(await gU(o),await n?.(t),await wU(o,t,r)):"invalid"}catch{return"failed"}finally{try{await j.rm(o,{recursive:!0,force:!0})}catch{}}},yI=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),TI=async e=>{let t=await pu(ee(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await Yn(ee(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},PI=async e=>{let t=await pu(ee(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(rc).includes("skills-plugin"))try{await j.access(ee(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},bU=async e=>{try{return await j.access(e,gI.R_OK),"readable"}catch(t){return St(t)&&t.code==="ENOENT"?"missing":"unreadable"}},CU=async(e,t)=>{if(e.length===0)return!0;if(!t)return!1;let n=await TI(t);if(n.state!=="found")return!1;let r=await Yn(ee(n.path,"manifest.json"));if(!r)return!1;let o=new Set((Array.isArray(r.value.skills)?r.value.skills:[]).filter(Ge).map(a=>a.name).filter(a=>typeof a=="string").map(a=>a.toLowerCase()));return e.every(a=>o.has(a.entry.name.toLowerCase()))},AU=async(e,t)=>{if(e.length===0)return!0;if(!t)return!1;let n=await PI(t);if(n.state!=="found")return!1;let o=(await Yn(ee(n.path,"cowork_plugins","installed_plugins.json")))?.value.plugins;return Ge(o)?e.every(a=>{let s=o[a.id];return Array.isArray(s)&&s.some(i=>Ge(i)&&i.scope==="user")}):!1},kU=async(e,t)=>{let n=Object.keys(e);if(n.length===0)return!0;if(!t)return!1;let o=(await Yn(ee(t,"claude_desktop_config.json")))?.value.mcpServers;return Ge(o)?n.every(a=>Object.hasOwn(o,a)):!1},DI=async(e,t)=>{if(!e)return"unsupported";let n=await bU(e);if(n==="unreadable")return"unreadable";if(n==="missing")return"nothing_to_carry";let r=await yy(e);if(r.skills.length===0&&r.plugins.length===0&&Object.keys(r.localMcpServers).length===0)return"nothing_to_carry";let[o,a,s]=await Promise.all([CU(r.skills,t),AU(r.plugins,t),kU(r.localMcpServers,t)]);return o&&a&&s?"carried":"pending"},vU=async(e,t,n,r,o)=>{let a=ee(t,"manifest.json");for(let s of e){let i=ee(s.packageDir,"skills",s.entry.name);try{await j.access(ee(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=ee(t,"skills",s.entry.name),l=await _I(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 uu(a,p=>{let m=Array.isArray(p.skills)?p.skills:[];if(m.find(h=>Ge(h)&&typeof h.name=="string"&&h.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...p,skills:[...m,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},LI=(e,t)=>({...e,installPath:t}),SU=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=my(r.installPath)?gn(r.installPath):gn(o,r.installPath),s=LI(e,au(gn(t),gn(n))),i={...r,installPath:au(gn(o),a)};return cu(s,i)},IU=async(e,t,n)=>{let r=await Yn(e);if(!r||!Ge(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":uu(t,a=>{let s=Ge(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},EU=async(e,t,n,r,o)=>{let a=ee(t,"cowork_plugins"),s=ee(a,"installed_plugins.json"),i=ee(t,"cowork_account_settings.json");for(let c of e){let l=ee(a,c.relativeInstallPath);if(!vI(a,l)){n.invalid+=1;continue}let d=await _I(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 uu(s,f=>{let h=Ge(f.plugins)?f.plugins:{},w=h[c.id],y=Array.isArray(w)?w:[],g=y.find(k=>Ge(k)&&k.scope==="user");if(g){u=SU(c.entry,us(c.settingsFile),c.packageDir,g,t),p=!u;return}let b=LI(c.entry,l);return{...f,version:typeof f.version=="number"?f.version:2,plugins:{...h,[c.id]:[...y,b]}}})==="failed"?n.failed+=1:p?n.conflicts+=1:await IU(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},xU=async(e,t,n)=>{let r=ee(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await uu(r,c=>{let l=Ge(c.mcpServers)?c.mcpServers:{};if(Object.hasOwn(l,o)){s.value=cu(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}},NI=async(e,t,n={})=>{let r=await yy(e),o=fy("skill"),a=fy("plugin"),s=fy("local-mcp"),i=[],c=[],l=[],d=yI(r.skills,n.account,n.allAccounts),u=yI(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let m=new Set(n.allowedAccounts);if([...new Set([...d.map(h=>h.account),...u.map(h=>h.account)])].some(h=>!m.has(h)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,deferred:l,sourceChanged:!0,retryable:[]}}if(d.length>0&&n.appRunning)l.push("skill");else if(d.length>0){let m=await TI(t);m.state==="found"?await vU(d,m.path,o,n.beforeDirectoryPublish,n.afterDirectoryClaim):m.state==="missing"?i.push("skill"):(o.conflicts+=d.length,c.push("skill"))}if(u.length>0&&n.appRunning)l.push("plugin");else if(u.length>0){let m=await PI(t);m.state==="found"?await EU(u,m.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):m.state==="missing"?i.push("plugin"):(a.conflicts+=u.length,c.push("plugin"))}await xU(r.localMcpServers,t,s);let p=[o,a,s];return{outcomes:p,blocked:i,ambiguous:c,deferred:l,sourceChanged:!1,retryable:p.filter(m=>m.failed>0).map(m=>m.kind)}};var _U=async e=>{try{return await Nt.access(e),!0}catch{return!1}},$I=448,TU=384,BI={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},PU=CI.session,Cy=(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.",wy=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),FI=async e=>{let t;try{t=(await Nt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&qa(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await Nt.readdir(wn(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&qa(a.name)).map(a=>a.name);for(let a of o)n.push(wn(e,r,a))}catch{}return n},DU=async e=>{try{return(await Nt.readdir(e)).filter(t=>t.startsWith(Ar)&&t.endsWith(".json")).map(t=>t.slice(Ar.length,-5)).filter(qa)}catch{return[]}},LU=async(e,t)=>{let n=await FI(wn(e,BI[t])),r=[];for(let o of n){let a=await DU(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(OU).slice(-2)[0]})}return r},NU=async(e,t)=>{if(t==="cowork"){let r=await Ud(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await FI(wn(e,BI.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},$U=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await Nt.copyFile(e,n),await Nt.chmod(n,TU),await Nt.rename(n,t)},MU=async(e,t)=>{try{let n=JSON.parse(await Nt.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||!qa(o)?!1:(await Nt.access(wn(t,".claude","projects",Dh(r),`${o}.jsonl`)),!0)}catch{return!1}},BU=async(e,t,n,r)=>{let o=wy(e),a=await Lh(n);for(let s of t)await FU(e,s,n,r,a,o);return o},FU=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Ar}${s}.json`,c=wn(t.dir,i);try{if(e==="code"){if(!await MU(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=wn(t.dir,`${Ar}${s}`),d=wn(n,`${Ar}${s}`),u=await Nt.readdir(l);await Nt.mkdir(d,{mode:$I});for(let p of u)await Nt.cp(wn(l,p),wn(d,p),{recursive:!0,force:!1,errorOnExist:!0});await Nt.chmod(d,$I)}await $U(c,wn(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},MI=(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(`
|
|
280
|
+
`)}},by=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),WI=async e=>{let t=[];for(let n of PU)t.push({lane:n,sources:await LU(e,n)});return t},UI=async(e={})=>{let t=(e.firstPartyRoot??(()=>zo()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let n=ac(e.assetClasses,"session"),[r,o]=await Promise.all([n?WI(t):Promise.resolve([]),gy(t)]),a=r.reduce((i,c)=>i+c.sources.reduce((l,d)=>l+d.ids.length,0),0),s=by(r);for(let i of o.accounts)s.add(i);return{sessions:a,accounts:s.size,userSkills:o.skills,userPlugins:o.plugins,localMcpServers:o.localMcpServers}},ta=async(e={})=>{let t=(e.home??RU)(),n=(e.firstPartyRoot??(()=>zo()))(),r=(e.thirdPartyRoot??(()=>kr()))();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."};let o=ac(e.assetClasses,"session"),a=(e.appRunning??ds())();if(o&&a)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[s,i]=await Promise.all([o?WI(n):Promise.resolve([]),gy(n)]),c;if(e.account){let h=e.account;for(let g of s)g.sources=g.sources.filter(b=>b.account.startsWith(h));let w=i.accounts.filter(g=>g.startsWith(h));if(s.every(g=>g.sources.length===0)&&w.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${h}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let y=by(s);for(let g of w)y.add(g);if(y.size>1)return MI(s,e.command??"anyray-connect desktop --migrate",`"${h}" matches ${y.size} accounts`,w);c=[...y]}else if(o&&!e.allAccounts){let h=by(s);for(let w of i.accounts)h.add(w);if(h.size>1)return MI(s,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${h.size} accounts`,i.accounts);c=[...h]}let l=e.command??"anyray-connect desktop --migrate",d=!await _U(r),u=await NI(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:c,appRunning:a});if(u.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 \`${l}\` so the account choice is made from a fresh snapshot.`};let p=[],m=[];for(let{lane:h,sources:w}of s){if(w.length===0){p.push(wy(h));continue}let y=await NU(r,h);if("missing"in y){m.push({lane:h,reason:y.missing,waiting:w.reduce((g,b)=>g+b.ids.length,0)}),p.push(wy(h));continue}p.push(await BU(h,w,y.dir,t))}let f=p.some(h=>h.migrated>0||h.alreadyPresent>0)||u.outcomes.some(h=>h.migrated>0||h.alreadyPresent>0||h.conflicts>0);if(!f&&m.length===0&&u.blocked.length===0&&u.deferred.length>0)return{ok:!1,kind:"app-running",reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop; its skill and plugin stores are copied once it is closed."};if(!f&&(m.length>0||u.blocked.length>0)){let h=m[0];return h?{ok:!1,kind:h.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:h.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${h.lane} store`:`Claude Desktop has no ${h.lane} store in its third-party profile yet`,remedy:Cy(h.reason,h.lane,l,d)}:{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:p,portableAssets:u.outcomes,...m.length>0?{blocked:m}:{},...u.blocked.length>0?{blockedAssets:u.blocked}:{},...u.ambiguous.length>0?{ambiguousAssets:u.ambiguous}:{},...u.deferred.length>0?{deferredAssets:u.deferred}:{},...u.retryable.length>0?{retryableAssets:u.retryable}:{}}};var WU=e=>[Ue(e)],HI=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...WU(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await R(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var GI="1.21459.0",KU=GU(UU),VU=async e=>{try{let{stdout:t}=await KU("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},jU=async e=>{try{return await HU(e)}catch{return}},KI="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",YU=["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."],ps=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(VI??=jI({}),VI):jI(e),VI,jI=async e=>{let t=(e.home??cc)(),n=["/Applications/Claude.app",Zn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??VU,o=e.readClaudeAppBundle??jU;for(let a of n){let s=await r(Zn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${KI}`}),c=Fd(s,GI);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${GI} or newer.`);let l=await o(Zn(a,"Contents","Resources","app.asar"));return l?AS.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. ${KI}`}},fu="anyray",XI="--anyray-owner=claude-desktop-v1",mu=(e={})=>{let t=(e.platform??mo)(),n=(e.home??cc)();return t==="darwin"?hn(e).appConfig:t==="win32"?Zn(process.env.APPDATA??Zn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):Zn(n,".config","Claude","claude_desktop_config.json")},Sy=(e={})=>Zn((e.home??cc)(),"Library","Application Support","Claude","claude_desktop_config.json"),zI=()=>{let e=We("profile");return{command:e.command,args:[...e.args,XI]}},na=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qI=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},ZU=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),JU=e=>{if(!na(e)||!qI(e,["command","args"]))return!1;let t=zI();return e.command===t.command&&ZU(e.args,t.args)},XU=e=>na(e)&&Array.isArray(e.args)&&e.args.at(-1)===XI,zU=e=>{if(!na(e)||!qI(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||dt(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===Vr&&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!dt(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},qU=e=>e===void 0?"absent":JU(e)?"exact":XU(e)||zU(e)?"stale-owned":"foreign",Ze=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},ra=async e=>{let t=await R(e),n;try{n=await F(e)}catch{throw new Ze(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!na(n.mcpServers))throw new Ze(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(na(n.mcpServers)?n.mcpServers:void 0)?.[fu];return{path:e,fileExisted:t,json:n,entry:o,ownership:qU(o)}},hu=e=>{if(e.ownership==="foreign")throw new Ze(`MCP name conflict in ${e.path}: mcpServers.${fu} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},QI=(e,t)=>{let n={...e},r=na(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[fu]:r[fu]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},ky=async(e,t)=>{if(Ay(e.entry,t))return;let n=await ra(e.path);if(!Ay(n.entry,e.entry))throw new Ze(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await vr(e.path,QI(n.json,t)),{reading:e,afterEntry:t}},vy=async e=>{let t=await ra(e.reading.path);if(!Ay(t.entry,e.afterEntry))throw new Ze(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=QI(t.json,e.reading.entry);await vr(e.reading.path,n)},QU=async e=>{if(!te())throw new Ze(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${De()} is temporary); no inference setting was changed.`);let t=await ra(mu(e));hu(t);let n=Sy(e),r=(e.platform??mo)()==="darwin"&&n!==t.path?await ra(n):void 0;return r&&hu(r),{active:t,...r?{legacy:r}:{}}},YI=async e=>{let t=await ra(mu(e));hu(t);let n=Sy(e),r=(e.platform??mo)()==="darwin"&&n!==t.path?await ra(n):void 0;return r&&hu(r),{active:t,...r?{legacy:r}:{}}},eH=async e=>{let t=[];try{let n=await ky(e.active,zI());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await ky(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await vy(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ze(`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 vy(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Ze(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},tH=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await ky(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await vy(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ze(`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)},ZI=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)."]},nH={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Iy="claude-desktop",Ey="migrate",yu="migrate-config",rH=[Ey,yu],JI=async e=>{await od(Iy,e?Ey:yu,{precedence:rH})},eE=new Set(["app-running","store-missing"]),oH={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},aH={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"}},sH="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",tE=e=>{let t=(e.platform??mo)(),n=e.home??cc;return{home:n,appRunning:e.appRunning??ds(t),firstPartyRoot:()=>zo({home:n,runtimePlatform:t}),thirdPartyRoot:()=>kr({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},nE=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=oH[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.`:"")},rE=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=aH[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.`:"")},ic=async(e,t)=>{try{let n=du(t.reportsToUser===!0),r=ac(n,"session"),o={...tE(e),assetClasses:n},a=await(e.pendingDesktopMigrationCount??UI)(o),s=a.userSkills+a.userPlugins+a.localMcpServers;if(a.sessions+s===0)return[];if(t.dryRun)return[`Would bring ${[a.sessions>0?`${a.sessions} existing Claude Desktop session${a.sessions===1?"":"s"}`:"",s>0?`${s} portable configuration ${s===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 i=await(e.migrateDesktopProfile??ta)(o);if(i.ok){let d=nE(i.lanes),u=rE(i.portableAssets),p=i.ambiguousAssets??[],m=p.length>0?`Claude Desktop has more than one target ${p.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(i.blocked??[]).filter(A=>A.reason!=="ambiguous"),h=i.blockedAssets??[],w=i.deferredAssets??[],y=i.retryableAssets??[];if(f.length===0&&h.length===0&&w.length===0&&y.length===0)return[d,u,m].filter(A=>!!A);if(t.preservePendingOp)return[d,u,m].filter(A=>!!A);await JI(r);let g=f.reduce((A,x)=>A+x.waiting,0),b=[g>0?`${g} more session${g===1?"":"s"}`:"",h.length>0?`${h.length} extension ${h.length===1?"store":"stores"}`:""].filter(Boolean),k=[...b.length>0?[`Queued: ${b.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...w.length>0?[`Queued: ${w.length} portable configuration ${w.length===1?"store moves":"stores move"} across the next time you fully quit Claude Desktop.`]:[],...y.length>0?[`Queued: ${y.length} portable configuration ${y.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...d?[d]:[],...u?[u]:[],...m?[m]:[],...k]}if(!eE.has(i.kind))return[`Your existing Claude Desktop local data was left where it is: ${i.reason}.
|
|
281
|
+
${i.remedy}`];if(t.preservePendingOp)return[];await JI(r);let c=a.sessions+s,l=`${c} Claude Desktop local ${c===1?"item":"items"}`;return[i.kind==="store-missing"?`Queued: the ${l} 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 ${l} still in your previous profile will move across the next time you fully quit Claude Desktop.`]}catch(n){return n instanceof Xs?["Claude Desktop's carry queue was busy; Connect will retry on the next reconcile."]:["Could not check whether Claude Desktop had existing sessions to bring across; run `anyray-connect migrate` if its lists look empty."]}},iH=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await eo(Iy),[]}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."]}},cH=e=>HI({id:Iy,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??mo)(),n=(e.home??cc)();return t==="darwin"?["/Applications/Claude.app",Zn(n,"Applications","Claude.app")]:t==="win32"?[Zn(process.env.LOCALAPPDATA??Zn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>ae(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:",...ZI(t)]:["Claude desktop org/API lane:",...ZI(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`."]}),lH=(e={})=>{let t=cH(e),n=()=>(e.platform??mo)()==="darwin",r=()=>(e.platform??mo)()==="win32",o=(s,i)=>n()?OS(s,i,e):iI(s,s.clientKey??"",i,e),a=s=>n()?_S(s,e):cI(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ds((e.platform??mo)()))(),quitTarget:nH,needsTarget:()=>!1,async complete(s){if(s!==Ey&&s!==yu)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??ta)({...tE(e),assetClasses:s===yu?du(!1):du(!0)});if(i.ok){let c=nE(i.lanes),l=rE(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(w=>w.reason!=="ambiguous"),m=i.blockedAssets??[],f=i.deferredAssets??[],h=i.retryableAssets??[];return p.length>0||m.length>0||f.length>0||h.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...p.length>0||m.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."]:[],...f.length>0?["Claude Desktop came back up; its skill and plugin stores are copied the next time it is fully quit."]:[],...h.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(w=>!!w):["No portable Claude Desktop data was left to bring across."]}}return eE.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?PS(s,e):r()?uI(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let p=hn(e),m=await Qo(p,e);if(m)return{status:"manual",manualAudience:"admin",messages:[Vh(m),...await ic(e,i)]}}if(r()){let p;try{p=await fo(e.runReg??Ir)}catch{return{status:"manual",manualAudience:"admin",messages:[sH,...await ic(e,i)]}}if(p)return{status:"manual",manualAudience:"admin",messages:[ly(p),...await ic(e,i)]}}if(r()&&ae(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 ps(e);if(!p.supported)return{status:"manual",messages:[p.message??"Claude Desktop version is unsupported."]}}let c;try{c=await QU(e)}catch(p){let m=p instanceof Ze?p.changedFiles:[];return{status:"manual",...m.length>0?{changedFiles:m}:{},messages:[p instanceof Ze?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 ic(e,i)]}}let d;try{d=await eH(c)}catch(p){let m=p instanceof Ze?p.changedFiles:[];return{status:"manual",...m.length>0?{changedFiles:m}:{},messages:[p instanceof Ze?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 ic(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?YU:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=mu(e),c=await iH(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 YI(e)}catch(h){return l({status:"manual",messages:[h instanceof Ze?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()?Qt(e):void 0;if(!(h!==void 0&&p.changedFiles?.includes(h)===!0&&!await R(h)))return l(p)}let m;try{m=await tH(await YI(e))}catch(h){let w=h instanceof Ze?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...p.changedFiles??[],...w])],messages:[...p.messages,h instanceof Ze?h.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await pe(i);let f=Sy(e);return n()&&f!==i&&await pe(f),l({...p,messages:[...p.messages,...m.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...p.changedFiles??[],...m])]})},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await ra(mu(e));return s.ownership!=="exact"||!na(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 ps(e)).supported?Yh(s,e):!1:r()?dI(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await ps(e)).supported)return["unknown"];let s=await TS(e);return s?[s]:["unknown"]}if(r())return await R(Qt(e))?await fo(e.runReg??Ir)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=hn(e);return!await R(s.journal)||await Qo(s,e)?!1:(await ps(e)).supported}return r()&&await R(Qt(e))?!await fo(e.runReg??Ir):!1}catch{return!1}}}},oE=lH();import{homedir as MH}from"node:os";import{join as BH}from"node:path";import{rm as Iu}from"node:fs/promises";import{constants as aE,accessSync as dH,statSync as uH}from"node:fs";import{platform as xy}from"node:os";import{delimiter as pH,posix as fH,resolve as mH,win32 as hH}from"node:path";var yH="0.59.0",gH="1.1.4",Er="Anyray \xB7 Claude",xr="Anyray \xB7 Codex",gu="__anyray-acp-agent",sE=(e,t,n)=>{let{command:r,args:o}=Sn([gu,e,t,n]);return{command:r,args:o,env:{}}},wu=(e=xy())=>e==="win32"?"npx.cmd":"npx",bu=(e=process.env.PATH,t=xy())=>{if(!e)return;let n=wu(t);for(let r of e.split(pH)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=mH(o,n);try{if(!uH(a).isFile())continue;return dH(a,t==="win32"?aE.F_OK:aE.X_OK),a}catch{}}},Cu=(e,t=xy())=>{let n=t==="win32"?hH:fH;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==wu(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},wH="https://chatgpt.com/backend-api/codex",bH="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",iE="ANYRAY_ACP_CODEX_AUTHORIZATION",cE="ANYRAY_ACP_CODEX_CLIENT_KEY",lE="ANYRAY_ACP_CODEX_METADATA",dE=e=>be({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),CH=(e,t={})=>{let n=ae(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":wH,"x-anyray-forward-headers":bH}:{},o=n?{...e.clientKey?{"x-anyray-api-key":cE}:{}}:{Authorization:iE};return dE(e)&&(o["x-anyray-metadata"]=lE),{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}}}:{}}},AH=e=>{let t=ae(e,"openai"),n=dE(e);return{...t?e.clientKey?{[cE]:e.clientKey}:{}:{[iE]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[lE]:n}:{}}},uE=(e,t=wu(),n={})=>({[Er]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${yH}`],env:En(e).env},[xr]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${gH}`],env:{CODEX_CONFIG:JSON.stringify(CH(e,n)),...AH(e)}}}),lc=(e=wu(),t="jetbrains")=>({[Er]:sE("claude",e,t),[xr]:sE("codex",e,t)}),oa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Au=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as kH}from"node:zlib";import{open as vH,readFile as Py,readdir as Su}from"node:fs/promises";import{dirname as pE,join as Ce}from"node:path";import{homedir as yE,platform as Dy}from"node:os";var ku="2025.3.2",fs="253.30387.147",dc="com.intellij.ml.llm",Ry=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),SH=1e4,IH=256*1024*1024,EH=16*1024*1024,Oy=1024*1024,_y=22,xH=_y+65535,Ty=Fd,RH=()=>{let e=yE(),t=Ce(e,".cache","JetBrains","RemoteDev");switch(Dy()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:Ce(e,"Applications"),layout:"app-bundles"},{path:Ce(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:Ce(process.env.LOCALAPPDATA??Ce(e,"AppData","Local"),"Programs"),layout:"children"},{path:Ce(process.env.LOCALAPPDATA??Ce(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:Ce(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:Ce(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},OH=()=>Dy()==="linux"?Ce(yE(),".local","share","JetBrains"):Ue("JetBrains"),_H=()=>Dy()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),TH=async(e,t=SH)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await Su(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=Ce(r.path,i.name),l=r.layout==="app-bundles"?Ce(c,"Contents","Resources","product-info.json"):Ce(c,"product-info.json");await R(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=Ce(s,"product-info.json"),l=Ce(s,"Contents","Resources","product-info.json");if(await R(c)){n.push(c);return}if(await R(l)){n.push(l);return}let d;try{d=await Su(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let p=Ce(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)]},PH=e=>{let t=pE(e);return t.endsWith(`${Ce("Contents","Resources")}`)?pE(t):t},DH=async e=>{try{let t=JSON.parse(await Py(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Ki(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:PH(e)}}catch{return}},vu=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},LH=async(e,t)=>{let n;try{n=await vH(e,"r");let{size:r}=await n.stat();if(r<_y||r>IH)return;let o=Math.min(r,xH),a=await vu(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-_y;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>EH||c+i>r)return;let l=await vu(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),m=l.readUInt32LE(d+24),f=l.readUInt16LE(d+28),h=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),g=d+46+f+h+w;if(g>l.length)return;let b=l.subarray(d+46,d+46+f).toString("utf8");if(d=g,b!==t)continue;if(p===4294967295||m===4294967295||p>Oy||m>Oy)return;let k=await vu(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let A=k.readUInt16LE(26),x=k.readUInt16LE(28),_=await vu(n,p,y+30+A+x);return _?u===0?_.toString("utf8"):u===8?kH(_,{maxOutputLength:Oy}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},fE=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Ki(n)))return{id:t,version:n}},NH=async(e,t)=>{let n=Ce(e,"META-INF","plugin.xml");if(await R(n))try{let o=fE(await Py(n,"utf8"));return{present:o?.id===dc||t,descriptor:o?.id===dc?o:void 0}}catch{return{present:t}}let r=[];try{r=(await Su(Ce(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=>Ce(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await LH(o,"META-INF/plugin.xml"),s=a?fE(a):void 0;if(s?.id===dc)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},mE=async e=>{let t;try{t=await Su(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Ry.has(o.name.toLowerCase()),i=Ry.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Ry.has(o.name.toLowerCase());if(!a){let i=Ce(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await NH(Ce(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},$H=async e=>{try{return(await Py(Ce(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(dc)}catch{return!1}},hE=e=>e.reduce((t,n)=>t?(Ty(n,t)??-1)>0?n:t:n,void 0),gE=async(e={})=>{let t=e.configRoot??Ue("JetBrains"),n=e.userPluginsRoot??OH(),r=await TH(e.productRoots?e.productRoots.map(f=>({path:f,layout:"recursive"})):RH(),e.scanBudget),o=(await Promise.all(r.map(f=>DH(f)))).filter(f=>f!==void 0),a=o.length>0||await R(t);if(e.wsl??_H())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(f=>(Ty(f.version,ku)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let f of s){let h=Ce(t,f.dataDirectoryName);if(!await R(h)){d=!0;continue}let w=[Ce(h,"plugins"),Ce(n,f.dataDirectoryName),Ce(n,f.dataDirectoryName,"plugins")],y;for(let g of[...new Set(w)]){let b=await mE(g);if(b.present){y=b;break}}if(y??=await mE(Ce(f.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==dc)){if(i.push(y.descriptor.version),await $H(h)){c=!0;continue}if(!((Ty(y.descriptor.version,fs)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${f.version}; AI Assistant ${y.descriptor.version}; ACP supported`,ideVersion:f.version,pluginVersion:y.descriptor.version}}}let u=hE(o.map(f=>f.version)),p=hE(i),m;return a?u?s.length===0?m=`JetBrains IDE ${u} is below the ACP minimum ${ku}; no ACP config was written.`:d?m=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${ku}+ once, enable AI Assistant ${fs}+, then run Connect again. No ACP config was written.`:c?m=`JetBrains AI Assistant is disabled; enable version ${fs}+ and run Connect again. No ACP config was written.`:p?m=`JetBrains AI Assistant ${p} is below the ACP minimum ${fs}; no ACP config was written.`:l?m=`Could not verify the local JetBrains AI Assistant version; require ${fs}+ before running Connect. No ACP config was written.`:m=`JetBrains AI Assistant ${fs}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:m=`Could not prove JetBrains IDE ${ku}+ from local product-info.json; no ACP config was written.`:m="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:m,ideVersion:u,pluginVersion:p}};var FH=[Er,xr],Ly=()=>BH(MH(),".jetbrains","acp.json"),aa=()=>`${Ly()}.anyray-state`,WH=(e,t,n="npx")=>{let r=oa(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,lc(n,"jetbrains")),{...e,agent_servers:r}},UH=(e,t,n)=>{if(!oa(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=oa(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of FH)if(c in r){if(!Au(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}},HH=(e=gE)=>({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=Ly(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=bu();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await R(r),c;try{c=await F(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=lc(a,"jetbrains");return await sl({configPath:r,current:c,next:WH(c,t,a),journalPath:aa(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,aa()]}},async revert(t){let n=Ly(),r=async()=>{if(!await R(n))return t.dryRun||(await pe(n),await Iu(aa(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await F(n)}catch{return t.dryRun||(await pe(n),await Iu(aa(),{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 F(aa());(u.version===1||u.version===2)&&oa(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await R(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await F(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 Ro(n);let l=UH(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 Iu(n,{force:!0}):await q(n,l.next,{backup:!1})),t.dryRun||(await pe(n),await Iu(aa(),{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():al(n,aa(),r)}}),wE=HH();import{homedir as xu}from"node:os";import{join as Ru}from"node:path";import{rm as Ny}from"node:fs/promises";var $y="1.0.0",Ou=["anyray-claude-acp","anyray-codex-acp"],GH=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],My=()=>Ru(xu(),".windsurf","acp","registry.json"),By=()=>Ru(xu(),".windsurf-next","acp","registry.json"),ms=e=>`${e}.anyray-state`,bE=e=>({binary:Object.fromEntries(GH.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),AE=(e="npx")=>{let t=lc(e,"windsurf");return[{id:Ou[0],name:Er,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:bE(t[Er])},{id:Ou[1],name:xr,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:bE(t[xr])}]},Eu=e=>!Array.isArray(e)||e.some(t=>!oa(t)||typeof t.id!="string")?null:e,KH=(e,t="npx")=>{if(e.version!==void 0&&e.version!==$y||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:Eu(e.agents);if(!n)return null;let r=new Set(Ou);return{...e,version:typeof e.version=="string"?e.version:$y,agents:[...n.filter(o=>!r.has(o.id)),...AE(t)],extensions:e.extensions??[]}},VH=(e,t,n)=>{let r=Eu(e.agents);if(!r)return null;let o=Eu(t.agents)??[],a=new Map((Eu(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!Ou.includes(u.id)){l.push(u);continue}if(!Au(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===$y&&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}},CE=async()=>{let e=[];return(await R(By())||await R(Ru(xu(),".windsurf-next")))&&e.push(By()),(await R(My())||await R(Ru(xu(),".windsurf"))||await R(Ue("Devin"))||await R(Ue("Windsurf")))&&e.push(My()),e},kE={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await CE();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await CE();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=bu();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 F(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=KH(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await R(s),d=AE(r);await sl({configPath:s,current:i,next:c,journalPath:ms(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,ms(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=[My(),By()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await pe(a),await Ny(ms(a),{force:!0}).catch(()=>{}));return}let i;try{i=await F(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 m=await F(ms(a));(m.version===1||m.version===2)&&Array.isArray(m.agents)&&(c=m.agents,l=m.version===2&&m.fileExisted===!1,d=m.version===2&&m.fileExisted===!0)}catch{}let u;if(d){let m=`${a}.anyray-bak`;if(!await R(m)){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 F(m)}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 Ro(a);let p=VH(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 Ny(a,{force:!0}):await q(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 pe(a),await Ny(ms(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await al(a,ms(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var se=[Zr,rA,Ii,dv,$v,Yv,eS,wE,oE,kE,pA],qe=e=>se.find(t=>t.id===e);var Je=async(e=$,t=Wn)=>{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 Fy=5e3,vE=3e4,jH=1440*60*1e3,YH=e=>new Promise(t=>setTimeout(t,e)),ZH=async(e=$,t=Wn)=>(await Je(e,t))?.target,JH=e=>qe(e)?.quitGated,SE=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??JH,o=t.readPending??Ci,a=t.clearPending??wm,s=t.targetFromProfile??ZH,i=t.sleep??YH,c=t.now??Date.now,l=t.maxWaitMs??jH;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),p=c(),m=Fy;for(;;){let f=await o(n);if(!f||c()-p>l)return 0;if(d.isRunning()){await i(m),m=Math.min(vE,m*2);continue}let h;if(d.needsTarget?.(f.op)&&(h=await s(),!h)){if(await a(n,f)!=="superseded")return 0;await i(m),m=Fy;continue}if((await u(f.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(m),m=Math.min(vE,m*2);continue}if(await a(n,f)!=="superseded")return 0;await i(m),m=Fy}}catch{return 0}};import{z as pc}from"zod";import{createHash as XH,randomBytes as zH,timingSafeEqual as qH}from"node:crypto";import{createServer as QH}from"node:http";var uc="127.0.0.1",eG=2147483647,tG="/callback",Wy=12,nG="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",Uy=e=>e.length===Wy&&[...e].every(t=>nG.includes(t)),Jn=class extends Error{kind;constructor(t,n){super(n),this.name="ConnectorOauthCallbackError",this.kind=t}},sa=(e,t,n)=>{e.writeHead(t,{"cache-control":"no-store","content-security-policy":"default-src 'none'","content-type":"text/plain; charset=utf-8","referrer-policy":"no-referrer","x-content-type-options":"nosniff"}),e.end(n)},rG=e=>new Promise(t=>{if(e.writableFinished||e.destroyed){t();return}e.once("finish",()=>t()),e.once("close",()=>t())}),IE=async()=>{let e;try{e=zH(32).toString("base64url")}catch{throw new Jn("listen","Could not open a local callback port for the browser.")}let t=Buffer.from(XH("sha256").update(e).digest("base64url")),n=p=>{let m=Buffer.from(p);return m.length===t.length&&qH(m,t)},r,o=()=>{},a=new Promise(p=>{o=p}),s=!1,i=QH((p,m)=>{if(p.socket.remoteAddress!==uc||p.method!=="GET"||p.url===void 0||!p.url.startsWith("/")||p.headers.host!==r){sa(m,404,"Not found.");return}let f;try{f=new URL(p.url,`http://${uc}`)}catch{sa(m,404,"Not found.");return}if(f.pathname!==tG){sa(m,404,"Not found.");return}let h=[...f.searchParams.entries()],w=f.searchParams.getAll("claim"),y=f.searchParams.getAll("nonce"),g=w[0]??"";if(h.length!==2||w.length!==1||y.length!==1||!Uy(g)||!n(y[0]??"")){sa(m,404,"Not found.");return}if(s){sa(m,409,"Callback already received.");return}s=!0,o({status:"claim",claimCode:g,response:m})}),c=()=>new Jn("listen","Could not open a local callback port for the browser.");try{await new Promise((p,m)=>{let f=h=>m(h);i.once("error",f),i.listen({host:uc,port:0},()=>{i.off("error",f),p()})})}catch{throw i.close(),c()}let l=i.address();if(l===null||typeof l=="string"||l.address!==uc||l.port<=0)throw i.close(),c();let d=l.port;r=`${uc}:${d}`;let u=async()=>{i.listening&&await new Promise(p=>{i.close(()=>p()),i.closeAllConnections()})};return i.on("error",()=>{s||(s=!0,o({status:"unavailable"}))}),{port:d,nonce:e,waitForClaim:async(p,m)=>{let f;try{f=await new Promise((h,w)=>{let y=!1,g=A=>{y||(y=!0,clearTimeout(k),m.signal?.removeEventListener("abort",b),A())},b=()=>g(()=>w(new Jn("lost","Connector authorization was cancelled."))),k=setTimeout(()=>g(()=>w(new Jn("timeout","Timed out waiting for the browser."))),Math.min(Math.max(m.timeoutMs,0),eG));if(m.signal?.aborted){b();return}m.signal?.addEventListener("abort",b,{once:!0}),a.then(A=>g(()=>h(A)))})}catch(h){throw await u(),h}if(f.status==="unavailable")throw await u(),new Jn("lost","The local callback port stopped listening.");try{let h=await p(f.claimCode);return sa(f.response,200,"Connected. You can close this window."),h}catch(h){throw sa(f.response,502,"Anyray could not finish connecting. Return to the terminal."),h}finally{await rG(f.response),await u()}},close:u}};import{spawn as oG}from"node:child_process";import{platform as aG}from"node:os";var sG=2e3,Rr=e=>new Promise(t=>{try{let n=new URL(e);if(n.protocol!=="https:"&&n.protocol!=="http:"){t(!1);return}let r=aG(),o=r==="darwin"?"open":r==="win32"?"cmd":"xdg-open",a=r==="win32"?["/c","start",'""',`"${n.href}"`]:[n.href],s=oG(o,a,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:r==="win32"}),i=!1,c=d=>{i||(i=!0,clearTimeout(l),t(d))},l=setTimeout(()=>c(!0),sG);l.unref(),s.on("error",()=>c(!1)),s.on("exit",d=>c(d===0)),s.unref()}catch{t(!1)}});import{fstatSync as mG,openSync as hG,statSync as yG}from"node:fs";import{createInterface as gG}from"node:readline/promises";import{ReadStream as wG}from"node:tty";import{execFileSync as EE}from"node:child_process";import iG from"node:os";var Hy=e=>{try{return EE("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},cG=e=>{try{return EE("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},lG=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"]),Gy=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:lG.has(t):!0},_u=()=>{try{return iG.userInfo().username||void 0}catch{return}},xE=()=>Hy("user.name")??Hy("user.email")??_u()??"unknown",RE=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Hy),global:e.globalGitConfig??(t||cG)}},ia=e=>{try{return e()?.trim()||void 0}catch{return}},Ky=(e={})=>{let t=RE(e),n=ia(e.osUsername??_u),r=ia(()=>t.global("user.email"))??ia(()=>t.local("user.email"));return r||(ia(()=>t.global("user.name"))??ia(()=>t.local("user.name"))??n??"unknown")},OE=(e={})=>{let t=Ky(e);if(Gy(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=RE(e);return!!(ia(()=>n.global("user.email"))??ia(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var hs=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,dG=hs(process.stdout,process.env),Vy=hs(process.stderr,process.env),Tu=!1,ys=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,jy=()=>{Tu=!0},Yy=()=>{Tu=!1},Pu=()=>Tu?Vy:dG,Du=e=>{Tu?console.error(e):console.log(e)},Z=e=>ys("1",e,Pu()),v=e=>ys("2",e,Pu()),uG=e=>ys("32",e,Pu()),pG=e=>ys("33",e,Vy),fG=e=>ys("31",e,Vy),st=e=>ys("36",e,Pu()),C=e=>Du(e),U=e=>Du(`
|
|
282
|
+
${Z(e)}`),M=e=>Du(v(e)),B=e=>Du(`${uG("\u2713")} ${e}`),P=e=>console.error(`${pG("!")} ${e}`),D=e=>console.error(`${fG("\u2717")} ${e}`);var Et=()=>!!process.stdin.isTTY,bG=()=>{try{let e=mG(0);return e.isCharacterDevice()&&e.rdev===yG("/dev/tty").rdev}catch{return!1}},Zy=()=>{if(bG()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new wG(hG(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},It=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},_E=async(e,t)=>{let n=t.input??Zy(),r=t.output??process.stdout,o=gG({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 It))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new It)))})}finally{o.close(),n.close()}},ca=async(e,t={})=>{let n=(await _E(`${e} ${v("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},gs=async(e,t,n={})=>{let r=t?` ${v(`[${t}]`)}`:"";return(await _E(`${e}${r}: `,n)).trim()||t},Jy=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return M(`Your name: ${t} ${v("(cached \u2014 pass --user to change)")}`),t;let r=xE();return n||!Et()?(M(`Your name: ${r} ${v("(auto-detected \u2014 pass --user to change)")}`),r):gs("? Your name",r)},Xy=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return M(`Team: ${t} ${v("(cached \u2014 pass --team to change)")}`),t;if(!(n||!Et()))return gs("? Team (optional)")},Xn=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return cn(e??n)},TE=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,ho="claude-desktop",Lu=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await fo(e.runReg??Ir))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Qt({home:e.home});return await R(s)?{authoritative:!0}:n("no-local-record")}if(t!=="darwin")return n("manual-platform");let r={home:e.home,managedPolicyPaths:e.managedPolicyPaths,readManagedPolicyKeys:e.readManagedPolicyKeys},o=hn(r);return await Qo(o,r)?n("managed-policy"):(await ps({home:e.home,readClaudeAppVersion:e.readClaudeAppVersion,readClaudeAppBundle:e.readClaudeAppBundle})).supported?await R(o.journal)?{authoritative:!0}:n("no-local-record"):n("unverified-build")}catch{return n("no-local-record")}},Nu=e=>e.id!==ho||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",CG={"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"},$u=(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=CG[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 AG=`anyray-connect connectors authorize <name> [--claim <code>] [--gateway <origin>]
|
|
283
283
|
|
|
284
284
|
Connect one of your organization's OAuth connectors to your own account.
|
|
285
285
|
<name> is the connector's name in the console (quote it if it has spaces).
|
|
@@ -293,10 +293,10 @@ Options:
|
|
|
293
293
|
--gateway <origin> Gateway origin (default: $ANYRAY_GATEWAY_URL, then the
|
|
294
294
|
~/.anyray cache, then http://localhost:8787).
|
|
295
295
|
--help, -h Show this help.
|
|
296
|
-
`,PE=5*6e4,kG=3e4,Or=class extends Error{},
|
|
296
|
+
`,PE=5*6e4,kG=3e4,Or=class extends Error{},ws=class extends Error{},vG=e=>{let t={help:!1};if(e.length===0)throw new Or("Missing command: authorize.");let[n,...r]=e;if(n==="--help"||n==="-h")return{help:!0};if(n!=="authorize")throw new Or(`Unknown command: ${n}.`);for(let o=0;o<r.length;o++){let a=r[o],s=()=>{let i=r[++o];if(i===void 0||i.startsWith("-"))throw new Or(`${a} needs a value.`);return i};if(a==="--help"||a==="-h")t.help=!0;else if(a==="--claim")t.claim=s();else if(a==="--gateway")t.gateway=s();else{if(a.startsWith("-"))throw new Or(`Unknown option: ${a}.`);if(t.name===void 0)t.name=a;else throw new Or("Give one connector name (quote it if it has spaces).")}}if(t.help)return t;if(!t.name?.trim())throw new Or("Missing connector name.");if(t.name=t.name.trim(),t.claim!==void 0&&(t.claim=t.claim.trim().toUpperCase(),!Uy(t.claim)))throw new Or(`A claim code is ${Wy} characters from A-Z and 2-9.`);return t},zy=e=>e.ssoLink?`Not enrolled. Reconnect with \`npx anyray-connect@latest --sso ${e.ssoLink}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.",$E=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),e.requestTimeoutMs);try{let a=await e.fetch(`${e.origin}${t}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json","x-anyray-api-key":e.clientKey},body:JSON.stringify(n),signal:r.signal}),s;try{s=JSON.parse(await a.text())}catch{s=void 0}return{status:a.status,body:s}}catch{throw new ws(r.signal.aborted?`The gateway at ${e.origin} did not answer within ${Math.round(e.requestTimeoutMs/1e3)} seconds.`:`Could not reach the gateway at ${e.origin}.`)}finally{clearTimeout(o)}},SG=(e,t)=>{switch(e){case 400:return"The gateway rejected the connector name or loopback port.";case 401:return zy(t);case 404:return"This gateway has no connector authorization route. Upgrade the gateway.";case 409:return"This connector is not ready for OAuth yet. Ask an admin to check it under Settings, then Connectors.";case 503:return"Connector authorization is unavailable right now. Try again in a minute.";default:return`Could not start connector authorization (HTTP ${e}).`}},IG=(e,t)=>{switch(e){case 400:return"The gateway rejected the claim code.";case 401:return zy(t);case 404:return"This gateway has no connector authorization route. Upgrade the gateway.";case 409:return"That claim code is no longer valid: it was used, it expired, or it belongs to another connector. Run the command again.";case 429:return"Too many attempts. Wait a minute, then retry.";case 503:return"Connector authorization is unavailable right now. Try again in a minute.";default:return`Could not complete connector authorization (HTTP ${e}).`}},EG=pc.object({authorizationUrl:pc.string().url().refine(e=>new URL(e).protocol==="https:"),loopbackPort:pc.number().int().optional()}),xG=pc.object({user:pc.string().regex(/^[^\p{Cc}]{1,320}$/u).optional()}),RG=e=>xG.safeParse(e).data?.user,DE=async(e,t,n,r)=>{let{status:o,body:a}=await $E(e,"/connect/mcp-oauth/authorize",r?{name:n,loopbackPort:r.port,loopbackNonce:r.nonce}:{name:n}),s=o===200?EG.safeParse(a).data:void 0;if(!s)throw new ws(o===200?"The gateway returned no authorization URL.":SG(o,t));return s},LE=async(e,t,n,r)=>{let{status:o,body:a}=await $E(e,"/connect/mcp-oauth/complete",{name:n,claimCode:r});if(o!==200)throw new ws(IG(o,t));return RG(a)},OG=/^[A-Za-z0-9 ._-]+$/,_G="<connector name>",TG=e=>e.replace(new RegExp("\\p{Cc}","gu"),t=>{let n=t.codePointAt(0)??0;return n<128?JSON.stringify(t).slice(1,-1):`\\u${n.toString(16).padStart(4,"0")}`}),ME=e=>{let t=OG.test(e)?e:_G,n=[` anyray-connect connectors authorize "${t}" --claim <code>`];return t!==e&&n.push(`Connector name: ${TG(e)}`),n},NE=e=>["The page then shows a claim code. Back here, run:",...ME(e)],BE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=d=>{r.write(`${d}
|
|
297
297
|
`)},a;try{a=vG(e)}catch(d){return o(d instanceof Error?d.message:String(d)),o("Run `anyray-connect connectors --help` for usage."),2}if(a.help)return n.write(AG),0;let s=a.name,i=await(t.loadProfile??$)(),c;try{let d=xe({origin:Xn(a.gateway,i),clientKey:i.clientKey});if(!d.clientKey)return o(zy(i)),1;c={origin:d.origin,clientKey:d.clientKey,fetch:t.fetch??fetch,requestTimeoutMs:t.requestTimeoutMs??kG}}catch(d){return o(d instanceof Error?d.message:String(d)),1}let l=d=>(d===void 0?(o("The gateway confirmed the grant but named no account."),n.write(`Connected ${s}.
|
|
298
298
|
`)):n.write(`Connected ${s} as ${d}.
|
|
299
|
-
`),0);try{if(a.claim!==void 0)return l(await LE(c,i,s,a.claim));let d=async()=>{let{authorizationUrl:h}=await DE(c,i,s);o("Open this URL in a browser and consent:"),o(` ${h}`);for(let w of NE(s))o(w)},u=async h=>{await(t.openBrowser??Rr)(h)?o(`Opened your browser to authorize ${s}.`):(o("Could not open a browser on this machine. Open this URL here yourself:"),o(` ${h}`))};if((t.isRemoteSession??ar)())return o("This is a remote session, so the browser cannot come back here."),await d(),1;let p;try{p=await(t.createListener??IE)()}catch(h){return o(h instanceof Jn?h.message:"Could not open a local callback port for the browser."),o("Finishing with a claim code instead."),await d(),1}let m;try{m=await DE(c,i,s,{port:p.port,nonce:p.nonce})}catch(h){throw await p.close(),h}if(m.loopbackPort!==p.port){await p.close(),o("This gateway shows the claim code in the browser instead of finishing here. Upgrade the gateway to skip that step."),await u(m.authorizationUrl);for(let h of NE(s))o(h);return 1}await u(m.authorizationUrl);let f=Math.round((t.timeoutMs??PE)/6e4);o(`Waiting for consent (up to ${f} minute${f===1?"":"s"}).`);try{return l(await p.waitForClaim(h=>LE(c,i,s,h),{timeoutMs:t.timeoutMs??PE}))}catch(h){if(!(h instanceof Jn))throw h;o(h.message),o("If the browser ended on a page that would not load, copy the `claim=` value from its address bar and run:");for(let w of ME(s))o(w);return o("Otherwise run this command again."),1}}catch(d){if(d instanceof
|
|
299
|
+
`),0);try{if(a.claim!==void 0)return l(await LE(c,i,s,a.claim));let d=async()=>{let{authorizationUrl:h}=await DE(c,i,s);o("Open this URL in a browser and consent:"),o(` ${h}`);for(let w of NE(s))o(w)},u=async h=>{await(t.openBrowser??Rr)(h)?o(`Opened your browser to authorize ${s}.`):(o("Could not open a browser on this machine. Open this URL here yourself:"),o(` ${h}`))};if((t.isRemoteSession??ar)())return o("This is a remote session, so the browser cannot come back here."),await d(),1;let p;try{p=await(t.createListener??IE)()}catch(h){return o(h instanceof Jn?h.message:"Could not open a local callback port for the browser."),o("Finishing with a claim code instead."),await d(),1}let m;try{m=await DE(c,i,s,{port:p.port,nonce:p.nonce})}catch(h){throw await p.close(),h}if(m.loopbackPort!==p.port){await p.close(),o("This gateway shows the claim code in the browser instead of finishing here. Upgrade the gateway to skip that step."),await u(m.authorizationUrl);for(let h of NE(s))o(h);return 1}await u(m.authorizationUrl);let f=Math.round((t.timeoutMs??PE)/6e4);o(`Waiting for consent (up to ${f} minute${f===1?"":"s"}).`);try{return l(await p.waitForClaim(h=>LE(c,i,s,h),{timeoutMs:t.timeoutMs??PE}))}catch(h){if(!(h instanceof Jn))throw h;o(h.message),o("If the browser ended on a page that would not load, copy the `claim=` value from its address bar and run:");for(let w of ME(s))o(w);return o("Otherwise run this command again."),1}}catch(d){if(d instanceof ws)return o(d.message),1;throw d}};var PG=`anyray-connect copilot-login
|
|
300
300
|
|
|
301
301
|
Sign Anyray in to GitHub Copilot (device flow) so the Copilot CLI seat lane
|
|
302
302
|
can run your plan's current models. Opens no browser for you: it prints a
|
|
@@ -304,7 +304,7 @@ code to type at github.com/login/device.
|
|
|
304
304
|
|
|
305
305
|
Options:
|
|
306
306
|
--help Show this help.
|
|
307
|
-
`,FE=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(PG),0;C(Z("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??fv)();if(!n)return D("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;C(` 1. Open ${st(n.verificationUri)}`),C(` 2. Enter the code: ${Z(n.userCode)}`),M(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??mv)(n);if(r.status!=="ok")return D(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??hv)(r.token,o);B(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??Xm)(r.token);if(s.verdict==="no-copilot")return D("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??Je)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??
|
|
307
|
+
`,FE=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(PG),0;C(Z("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??fv)();if(!n)return D("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;C(` 1. Open ${st(n.verificationUri)}`),C(` 2. Enter the code: ${Z(n.userCode)}`),M(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??mv)(n);if(r.status!=="ok")return D(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??hv)(r.token,o);B(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??Xm)(r.token);if(s.verdict==="no-copilot")return D("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??Je)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??Xa)(r.token,{},s.capiSegment,c);return l.length===0?P("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}).`),M("Now run: anyray-connect --tools copilot-cli"),0};var WE=`anyray-connect models [<model-id>] [--json]
|
|
308
308
|
|
|
309
309
|
List the Copilot models your seat can run on the Anyray lane, or switch the
|
|
310
310
|
Copilot CLI's startup model. The CLI's own /models cannot list models on a
|
|
@@ -316,8 +316,8 @@ Options:
|
|
|
316
316
|
--json Emit {"origin","current","models":[{"id","wire",...caps}]} instead
|
|
317
317
|
of the table (listing only).
|
|
318
318
|
--help Show this help.
|
|
319
|
-
`,DG=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},LG=e=>{let t=se.find(n=>n.id===
|
|
320
|
-
`),0;C(Z(`Copilot models your seat serves (via ${o.origin})`));for(let f of l){let h=f.id===m?"*":" ",w=NG(f);C(` ${h} ${f.id.padEnd(24)}${w?v(w):""}`)}return M("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),M("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(m=>m.id===n.modelId);if(!d)return D(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??xd)($G(o,i,d.id),{...oh(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return D(`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"?P("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 m=await(t.applyCopilotCli??LG)(o);if(m.status!=="configured"){for(let f of m.messages)C(f);return D("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}`),M("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};import{createReadStream as L1}from"node:fs";import{spawnSync as wx}from"node:child_process";import{createHash as N1}from"node:crypto";import{access as bx,chmod as fg,copyFile as $1,lstat as M1,mkdir as B1,mkdtemp as Cx,readFile as qu,rename as F1,rm as yo,stat as W1,writeFile as U1}from"node:fs/promises";import{constants as Ax}from"node:fs";import{platform as
|
|
319
|
+
`,DG=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},LG=e=>{let t=se.find(n=>n.id===jo);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},NG=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(" / ")},$G=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Mi(t)}/${hr(n)==="responses"?"responses":"chat/completions"}`,UE=async(e=[],t={})=>{let n=DG(e);if(n.help)return process.stdout.write(WE),0;if(n.error)return D(n.error),process.stdout.write(WE),1;let r=await(t.loadTarget??Je)();if(!r)return D("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??Rd)({allowKeychainPrompt:!0});if(!a.token)return D("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??Xa)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=ah(c);if(l.length===0)return D("Could not fetch your seat's model catalog from GitHub (offline, or the sign-in lost its Copilot seat)."),1;if(!n.modelId){let m=process.env.COPILOT_MODEL?.trim();if(n.json)return process.stdout.write(`${JSON.stringify({origin:o.origin,current:m??null,models:l.map(f=>({id:f.id,wire:hr(f.id),...f.maxPromptTokens?{maxPromptTokens:f.maxPromptTokens}:{},...f.maxOutputTokens?{maxOutputTokens:f.maxOutputTokens}:{}}))})}
|
|
320
|
+
`),0;C(Z(`Copilot models your seat serves (via ${o.origin})`));for(let f of l){let h=f.id===m?"*":" ",w=NG(f);C(` ${h} ${f.id.padEnd(24)}${w?v(w):""}`)}return M("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),M("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(m=>m.id===n.modelId);if(!d)return D(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??xd)($G(o,i,d.id),{...oh(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return D(`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"?P("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 m=await(t.applyCopilotCli??LG)(o);if(m.status!=="configured"){for(let f of m.messages)C(f);return D("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}`),M("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};import{createReadStream as L1}from"node:fs";import{spawnSync as wx}from"node:child_process";import{createHash as N1}from"node:crypto";import{access as bx,chmod as fg,copyFile as $1,lstat as M1,mkdir as B1,mkdtemp as Cx,readFile as qu,rename as F1,rm as yo,stat as W1,writeFile as U1}from"node:fs/promises";import{constants as Ax}from"node:fs";import{platform as Is,tmpdir as H1}from"node:os";import{dirname as G1,isAbsolute as K1,join as Ju}from"node:path";import{z as Ke}from"zod";var Ne="0.11.207";import{createWriteStream as o1}from"node:fs";import{spawnSync as tx}from"node:child_process";import{chmod as nx,copyFile as rg,lstat as og,mkdir as ag,readdir as ju,realpath as Vu,rename as Hu,rm as $t,stat as rx,symlink as a1,writeFile as s1}from"node:fs/promises";import{createHash as i1}from"node:crypto";import{basename as Gu,dirname as bn,join as Cs}from"node:path";import{Readable as c1}from"node:stream";import{pipeline as l1}from"node:stream/promises";var MG=["hook_registration","mcp_registration","hook_binary","beacon_target"],la=e=>e.status==="configured"||e.status==="queued",da=async(e,t=se)=>{let n=new Set(e),r=[];for(let o of t)if(n.has(o.id))try{(await o.detect()).installed&&r.push(o)}catch{}return r},bs=async(e,t,n=se)=>{let r=[];for(let o of await da(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},qy=async(e,t=se)=>{let n=[];for(let r of await da(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(MG.map(o=>[o,"unreadable"]))})}return n},HE=e=>e.filter(t=>!t.integrationStatus),BG=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},en=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,...o.errorClass?{errorClass:o.errorClass}:{}})}catch(o){let a=BG(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{constants as GE}from"node:fs";import{access as FG,chmod as WG,lstat as UG,mkdir as HG,open as GG,readFile as KG,realpath as VG,rm as jG,stat as VE,writeFile as YG}from"node:fs/promises";import{randomUUID as ZG}from"node:crypto";import{platform as eg}from"node:os";import{dirname as JG,join as XG,posix as zG,win32 as jE}from"node:path";var hc="/usr/local/bin/anyray-credential-helper",yc="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Mu="/usr/local/bin/anyray-bootstrap-headers-helper",Bu="C:\\Program Files\\Anyray\\anyray-bootstrap-headers-helper.cmd",mc="Managed by anyray-connect desktop helper; do not edit.",qG=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
|
|
321
321
|
|
|
322
322
|
Create the helpers required by Claude Desktop and Codex fleet artifacts: the
|
|
323
323
|
credential helper (inferenceCredentialHelper, also used by Codex) and the
|
|
@@ -367,8 +367,8 @@ Examples:
|
|
|
367
367
|
`),0}if(s!==Qy(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await n1(i,s);for(let d of l){let u=await QE(d.path,d.content,s),p=d.label[0].toUpperCase()+d.label.slice(1);r.write(u==="unchanged"?`${p} already current at ${d.path}.
|
|
368
368
|
`:`${u==="installed"?"Installed":"Updated"} ${d.label} at ${d.path}.
|
|
369
369
|
`)}return 0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
370
|
-
`),1}};var d1=new RegExp(`/releases/tag/${
|
|
371
|
-
`)){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()}},y1=e=>e.mode==="off"?{allow:!1,outcome:"fleet-off"}:e.mode==="directed"&&e.initiator==="tick"?{allow:!1,outcome:"fleet-directed"}:{allow:!0},g1=e=>e==="auto",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&&Cs(e.current,e.minVersion)<0&&Cs(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},w1=e=>Cs(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},b1=(e=process.execPath)=>{let t=Af(e);return t?bn(t):bn(bn(e))},C1=async(e=kt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=lr(b1(e.execPath)).launcher;try{if(await Vu(t)!==await Vu(e.execPath))return}catch{return}return t},ig=async(e=kt(),t=oe())=>{let n=await C1(e);if(n)return{kind:"managed",root:bn(bn(n)),link:n,entryPath:Wr(e)};let r=Wr(e);return vf(r,t)?{kind:"durable",root:t,entryPath:r}:bf(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},Yu=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)}},cg=async(e=Ac)=>{let t=await Yu(`${zr}/latest`,e,{redirect:"manual"});return h1(t.headers.get("location"))},A1=async e=>{try{let t=await Yu(`${e}/connect-update.json`,Ac);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}},Cc=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},lg=async(e,t,n)=>{let r=await Yu(e,p1);if(!r.ok||!r.body)throw new Cc(r.status);let o=i1("sha256"),a=0;if(await l1(c1.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>u1)throw new Error("asset exceeds size cap");o.update(c),yield c}},o1(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},k1=e=>Gu(e)===qr()?Gu(bn(e)):Gu(e),v1=async e=>{let t=await ju(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await $t(bs(e,n),{force:!0}).catch(()=>{})},ax=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await $t(r,{force:!0}).catch(()=>{});let o=!1;try{await Hu(e,r),o=!0}catch{}try{await rg(t,e),await s1(Qs(e),k1(t))}catch(a){throw o&&await Hu(r,e).catch(()=>{}),a}await $t(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await $t(n,{force:!0}),await a1(t,n),await Hu(n,e)},dg=(e,t)=>e===t||Gu(e)===Xf?448:493,bc=async(e,t)=>{let n=(await rx(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await nx(e,n&4095|t).catch(()=>{})},Ku=async(e,t)=>{await ag(e,{recursive:!0,mode:t}),await bc(e,t)},S1=async(e,t,n)=>{let r=dg(e,oe());if(r!==448){let o=lr(e),a=o.versionsDir;await bc(e,r),await bc(bn(o.launcher),r),await bc(a,r);for(let s of await ju(a).catch(()=>[]))await bc(bs(a,s),r)}await(n.refreshDesktopHelpers??Uu)(t)},I1=async(e,t={})=>{let n=lr(e.root),r=bn(n.launcher),{versionsDir:o,launcher:a}=n,s=dg(e.root,(t.privateRoot??oe)());await Ku(r,s),await Ku(o,s);let i=bs(o,e.version),l=(await og(i).catch(()=>{}))?.isFile()?i:bs(i,qr());if(!(await og(l).catch(()=>{}))?.isFile()){let u=await(t.fetchResponse??Yu)(`${e.tagUrl}/SHA256SUMS`,Ac),p=u.ok?sg(await u.text(),e.asset):void 0;if(!p)throw new Error("no published checksum");await Ku(bn(l),s),await v1(bn(l));let m=`${l}.part-${process.pid}`;try{await(t.download??lg)(`${e.tagUrl}/${e.asset}`,m,p),await nx(m,493),await Hu(m,l)}catch(f){throw await $t(m,{force:!0}).catch(()=>{}),f}}return await(t.activate??ax)(a,l),{link:a,target:l,versionsDir:o}},E1=async e=>{tx(e.target,[$o,e.link],{stdio:"ignore",timeout:Ac})},x1=async e=>{if(process.platform==="darwin"){let t=tx("/usr/bin/codesign",["--verify","--strict",e],{stdio:"ignore",timeout:Ac});return!t.error&&t.status===0}return!0},R1=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??la)(n);if(r.length>0){let o=await(t.resolveTarget??Je)(async()=>e);if(!o||!(await(t.repair??en)(r,o.target)).every(ca))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&rt(e)&&!(await(t.installScheduler??Xr)()).ok)},O1=async e=>{let t=await e.install();if(!await(e.smoke??x1)(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},_1=async(e,t)=>{let n=await ju(e).catch(()=>[]);for(let r of n)t.includes(r)||await $t(bs(e,r),{force:!0,recursive:!0}).catch(()=>{})},T1=async e=>{let t=await ju(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await $t(bs(e,n),{force:!0}).catch(()=>{})},P1=async(e,t)=>{let n=async()=>{await $t(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await ag(e,{recursive:!1}),n}catch{}let r=await rx(e).catch(()=>{});if(!(!r||t-r.mtimeMs<m1)){await n();try{return await ag(e,{recursive:!1}),n}catch{return}}},ng=e=>lr(e).state,D1=async e=>{let t=await F(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},As=async(e={})=>{let t=e.now??Date.now,n=Ne;if(sr(On(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??kt(),o=e.root??oe(),a;try{let s=await ig(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??$)().catch(()=>({})),d=l.autoUpdate!==!1,u=l.fleetUpdatePolicy?.mode??"auto",p=y1({mode:u,initiator:e.initiator??"tick"});if(!p.allow)return{outcome:p.outcome,current:n};!i&&s.link&&!e.checkOnly&&(d||c)&&await S1(o,s.link,e).catch(()=>{});let m=di(e.platform??process.platform,e.arch??process.arch);if(!m)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??cg)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let f=a;if(!i&&f===n)return{outcome:"current",current:n,latest:f};if(i&&Cs(f,n)<0)return{outcome:"migration-deferred",current:n,latest:f};let h=await D1(ng(o));if((e.respectFailureBackoff===!0||!c)&&h.failedVersion===f&&h.failedAt!==void 0&&t()-h.failedAt<f1)return{outcome:"failed",current:n,latest:f};let w=`${zr}/download/${No}${f}`,y=d||c||!g1(u)?void 0:await(e.minimumVersion??A1)(w),g={current:n,latest:f,autoUpdate:d,forced:c,minVersion:y},b=i?w1(g):{...ox(g),downgradeBlocked:!1};if(b.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:f};if(!b.apply)return{outcome:"disabled",current:n,latest:f};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:f,mandatory:b.mandatory};o===oe()?await lt():await Ku(o,dg(o,oe()));let k=lr(o),A=await P1(k.lock,t());if(!A)return{outcome:i?"migration-available":"available",current:n,latest:f};let E,O;try{await T1(bn(k.launcher));let S=await Vu(k.versionsDir).catch(()=>{}),I=await Vu(k.launcher).catch(()=>{}),x=I&&hl(I,S)?I:void 0,_=k.launcher;i&&process.platform==="win32"&&(await og(_).catch(()=>{}))?.isFile()&&(O=`${_}.rollback-${process.pid}`,await rg(_,O));let K=()=>(e.installBinary??I1)({root:o,version:f,asset:m,tagUrl:w});i?E=await O1({install:K,smoke:e.smoke,rollback:async({link:G,target:X})=>{O?(await rg(O,G),await $t(Qs(G),{force:!0}).catch(()=>{})):x&&x!==X?await ax(G,x):(await $t(G,{force:!0}),await $t(Qs(G),{force:!0}).catch(()=>{}))},repoint:async G=>e.repoint?e.repoint(l,G):R1(l),prune:async()=>{await(e.pruneDurable??(G=>gl(G)))(r)}}):E=await K(),await _1(E.versionsDir,[f,n]),await(e.refreshHelpersFromInstalled??E1)(E).catch(()=>{}),await $t(ng(o),{force:!0}).catch(()=>{})}finally{O&&await $t(O,{force:!0}).catch(()=>{}),await A()}return{outcome:i?"migrated":"updated",current:n,latest:f,managedPath:E.link,mandatory:b.mandatory}}catch{return a&&await q(ng(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},sx=async(e={})=>{let t=e.context??kt(),n=await ig(t,e.root??oe()),r=Oa(e.root??oe());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Ne,managedPath:n.link??r}:As({initiator:"human",...e,context:t,allowNpmMigration:!0})},da=async(e={})=>{let t=e.context??kt(),n=e.root??oe(),r=await ig(t,n),o=r.kind==="npm"||r.kind==="durable"?Oa(n):void 0,a=await(e.load??$)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!di(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=sr(On(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:Ne,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l,fleetMode:a.fleetUpdatePolicy?.mode??"auto"}};var V1="fleetd-installer-v4.89.2",ix=`https://github.com/anyrayHQ/install/releases/download/${V1}`,j1=1e4,Y1=1e4,cx=31,Z1=1500,kx=20*1024,ug=20,J1="0.25",X1="/var/tmp",vs="/Library/LaunchDaemons/com.fleetdm.orbit.plist",Xu="/etc/default/orbit",vc="/opt/orbit/anyray-enroll-secret.txt",vx="/opt/orbit/secret-orbit-node-key.txt",z1="/opt/orbit/bin/orbit/orbit",Sc="C:\\Program Files\\Orbit",q1=`${Sc}\\bin\\orbit`,Sx=`${Sc}\\secret-orbit-node-key.txt`,kc=`${Sc}\\secret.txt`,Q1=`${Sc}\\fleet_url.txt`,Ix=`${Sc}\\anyray-managed.txt`,zu="Fleet osquery",mg="C:\\Windows\\System32\\sc.exe",wg="C:\\Windows\\System32\\whoami.exe",Zu="C:\\Windows\\System32\\icacls.exe",eK="C:\\Windows\\System32\\msiexec.exe",hg="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",lx=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],tK=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],nK=`anyray-connect endpoint install
|
|
370
|
+
`),1}};var d1=new RegExp(`/releases/tag/${$o}([0-9][0-9A-Za-z.-]*)$`),u1=300*1024*1024,Ac=1e4,p1=5*6e4,f1=360*6e4,m1=30*6e4,As=(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)};var h1=e=>{if(e)return d1.exec(e.trim())?.[1]},sg=(e,t)=>{for(let n of e.split(`
|
|
371
|
+
`)){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()}},y1=e=>e.mode==="off"?{allow:!1,outcome:"fleet-off"}:e.mode==="directed"&&e.initiator==="tick"?{allow:!1,outcome:"fleet-directed"}:{allow:!0},g1=e=>e==="auto",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&&As(e.current,e.minVersion)<0&&As(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},w1=e=>As(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},b1=(e=process.execPath)=>{let t=Af(e);return t?bn(t):bn(bn(e))},C1=async(e=kt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=lr(b1(e.execPath)).launcher;try{if(await Vu(t)!==await Vu(e.execPath))return}catch{return}return t},ig=async(e=kt(),t=oe())=>{let n=await C1(e);if(n)return{kind:"managed",root:bn(bn(n)),link:n,entryPath:Wr(e)};let r=Wr(e);return vf(r,t)?{kind:"durable",root:t,entryPath:r}:bf(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},Yu=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)}},cg=async(e=Ac)=>{let t=await Yu(`${zr}/latest`,e,{redirect:"manual"});return h1(t.headers.get("location"))},A1=async e=>{try{let t=await Yu(`${e}/connect-update.json`,Ac);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}},Cc=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},lg=async(e,t,n)=>{let r=await Yu(e,p1);if(!r.ok||!r.body)throw new Cc(r.status);let o=i1("sha256"),a=0;if(await l1(c1.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>u1)throw new Error("asset exceeds size cap");o.update(c),yield c}},o1(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},k1=e=>Gu(e)===qr()?Gu(bn(e)):Gu(e),v1=async e=>{let t=await ju(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await $t(Cs(e,n),{force:!0}).catch(()=>{})},ax=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await $t(r,{force:!0}).catch(()=>{});let o=!1;try{await Hu(e,r),o=!0}catch{}try{await rg(t,e),await s1(ei(e),k1(t))}catch(a){throw o&&await Hu(r,e).catch(()=>{}),a}await $t(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await $t(n,{force:!0}),await a1(t,n),await Hu(n,e)},dg=(e,t)=>e===t||Gu(e)===Xf?448:493,bc=async(e,t)=>{let n=(await rx(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await nx(e,n&4095|t).catch(()=>{})},Ku=async(e,t)=>{await ag(e,{recursive:!0,mode:t}),await bc(e,t)},S1=async(e,t,n)=>{let r=dg(e,oe());if(r!==448){let o=lr(e),a=o.versionsDir;await bc(e,r),await bc(bn(o.launcher),r),await bc(a,r);for(let s of await ju(a).catch(()=>[]))await bc(Cs(a,s),r)}await(n.refreshDesktopHelpers??Uu)(t)},I1=async(e,t={})=>{let n=lr(e.root),r=bn(n.launcher),{versionsDir:o,launcher:a}=n,s=dg(e.root,(t.privateRoot??oe)());await Ku(r,s),await Ku(o,s);let i=Cs(o,e.version),l=(await og(i).catch(()=>{}))?.isFile()?i:Cs(i,qr());if(!(await og(l).catch(()=>{}))?.isFile()){let u=await(t.fetchResponse??Yu)(`${e.tagUrl}/SHA256SUMS`,Ac),p=u.ok?sg(await u.text(),e.asset):void 0;if(!p)throw new Error("no published checksum");await Ku(bn(l),s),await v1(bn(l));let m=`${l}.part-${process.pid}`;try{await(t.download??lg)(`${e.tagUrl}/${e.asset}`,m,p),await nx(m,493),await Hu(m,l)}catch(f){throw await $t(m,{force:!0}).catch(()=>{}),f}}return await(t.activate??ax)(a,l),{link:a,target:l,versionsDir:o}},E1=async e=>{tx(e.target,[Mo,e.link],{stdio:"ignore",timeout:Ac})},x1=async e=>{if(process.platform==="darwin"){let t=tx("/usr/bin/codesign",["--verify","--strict",e],{stdio:"ignore",timeout:Ac});return!t.error&&t.status===0}return!0},R1=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??da)(n);if(r.length>0){let o=await(t.resolveTarget??Je)(async()=>e);if(!o||!(await(t.repair??en)(r,o.target)).every(la))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&rt(e)&&!(await(t.installScheduler??Xr)()).ok)},O1=async e=>{let t=await e.install();if(!await(e.smoke??x1)(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},_1=async(e,t)=>{let n=await ju(e).catch(()=>[]);for(let r of n)t.includes(r)||await $t(Cs(e,r),{force:!0,recursive:!0}).catch(()=>{})},T1=async e=>{let t=await ju(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await $t(Cs(e,n),{force:!0}).catch(()=>{})},P1=async(e,t)=>{let n=async()=>{await $t(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await ag(e,{recursive:!1}),n}catch{}let r=await rx(e).catch(()=>{});if(!(!r||t-r.mtimeMs<m1)){await n();try{return await ag(e,{recursive:!1}),n}catch{return}}},ng=e=>lr(e).state,D1=async e=>{let t=await F(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},ks=async(e={})=>{let t=e.now??Date.now,n=Ne;if(sr(On(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??kt(),o=e.root??oe(),a;try{let s=await ig(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??$)().catch(()=>({})),d=l.autoUpdate!==!1,u=l.fleetUpdatePolicy?.mode??"auto",p=y1({mode:u,initiator:e.initiator??"tick"});if(!p.allow)return{outcome:p.outcome,current:n};!i&&s.link&&!e.checkOnly&&(d||c)&&await S1(o,s.link,e).catch(()=>{});let m=di(e.platform??process.platform,e.arch??process.arch);if(!m)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??cg)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let f=a;if(!i&&f===n)return{outcome:"current",current:n,latest:f};if(i&&As(f,n)<0)return{outcome:"migration-deferred",current:n,latest:f};let h=await D1(ng(o));if((e.respectFailureBackoff===!0||!c)&&h.failedVersion===f&&h.failedAt!==void 0&&t()-h.failedAt<f1)return{outcome:"failed",current:n,latest:f};let w=`${zr}/download/${$o}${f}`,y=d||c||!g1(u)?void 0:await(e.minimumVersion??A1)(w),g={current:n,latest:f,autoUpdate:d,forced:c,minVersion:y},b=i?w1(g):{...ox(g),downgradeBlocked:!1};if(b.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:f};if(!b.apply)return{outcome:"disabled",current:n,latest:f};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:f,mandatory:b.mandatory};o===oe()?await lt():await Ku(o,dg(o,oe()));let k=lr(o),A=await P1(k.lock,t());if(!A)return{outcome:i?"migration-available":"available",current:n,latest:f};let x,_;try{await T1(bn(k.launcher));let S=await Vu(k.versionsDir).catch(()=>{}),I=await Vu(k.launcher).catch(()=>{}),E=I&&hl(I,S)?I:void 0,O=k.launcher;i&&process.platform==="win32"&&(await og(O).catch(()=>{}))?.isFile()&&(_=`${O}.rollback-${process.pid}`,await rg(O,_));let K=()=>(e.installBinary??I1)({root:o,version:f,asset:m,tagUrl:w});i?x=await O1({install:K,smoke:e.smoke,rollback:async({link:G,target:X})=>{_?(await rg(_,G),await $t(ei(G),{force:!0}).catch(()=>{})):E&&E!==X?await ax(G,E):(await $t(G,{force:!0}),await $t(ei(G),{force:!0}).catch(()=>{}))},repoint:async G=>e.repoint?e.repoint(l,G):R1(l),prune:async()=>{await(e.pruneDurable??(G=>gl(G)))(r)}}):x=await K(),await _1(x.versionsDir,[f,n]),await(e.refreshHelpersFromInstalled??E1)(x).catch(()=>{}),await $t(ng(o),{force:!0}).catch(()=>{})}finally{_&&await $t(_,{force:!0}).catch(()=>{}),await A()}return{outcome:i?"migrated":"updated",current:n,latest:f,managedPath:x.link,mandatory:b.mandatory}}catch{return a&&await q(ng(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},sx=async(e={})=>{let t=e.context??kt(),n=await ig(t,e.root??oe()),r=_a(e.root??oe());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Ne,managedPath:n.link??r}:ks({initiator:"human",...e,context:t,allowNpmMigration:!0})},ua=async(e={})=>{let t=e.context??kt(),n=e.root??oe(),r=await ig(t,n),o=r.kind==="npm"||r.kind==="durable"?_a(n):void 0,a=await(e.load??$)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!di(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=sr(On(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:Ne,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l,fleetMode:a.fleetUpdatePolicy?.mode??"auto"}};var V1="fleetd-installer-v4.89.2",ix=`https://github.com/anyrayHQ/install/releases/download/${V1}`,j1=1e4,Y1=1e4,cx=31,Z1=1500,kx=20*1024,ug=20,J1="0.25",X1="/var/tmp",Ss="/Library/LaunchDaemons/com.fleetdm.orbit.plist",Xu="/etc/default/orbit",vc="/opt/orbit/anyray-enroll-secret.txt",vx="/opt/orbit/secret-orbit-node-key.txt",z1="/opt/orbit/bin/orbit/orbit",Sc="C:\\Program Files\\Orbit",q1=`${Sc}\\bin\\orbit`,Sx=`${Sc}\\secret-orbit-node-key.txt`,kc=`${Sc}\\secret.txt`,Q1=`${Sc}\\fleet_url.txt`,Ix=`${Sc}\\anyray-managed.txt`,zu="Fleet osquery",mg="C:\\Windows\\System32\\sc.exe",wg="C:\\Windows\\System32\\whoami.exe",Zu="C:\\Windows\\System32\\icacls.exe",eK="C:\\Windows\\System32\\msiexec.exe",hg="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",lx=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],tK=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],nK=`anyray-connect endpoint install
|
|
372
372
|
|
|
373
373
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
374
374
|
|
|
@@ -376,8 +376,8 @@ Supported on macOS, Linux and Windows.
|
|
|
376
376
|
|
|
377
377
|
The command uses the current seat's stored gateway key. Administrator access is
|
|
378
378
|
required: on macOS and Linux Connect asks through sudo once when /dev/tty is
|
|
379
|
-
available; on Windows, run it from a shell started as Administrator.`,bg=e=>!!(e.endpoint&&!e.noEndpoint&&(e.signIn||e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),Ex=(e,t=
|
|
380
|
-
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",vc)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},yg=(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(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/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()},Rx=e=>{let t=e(mg,["qc",zu,"8192"]);return t.status===0?t.stdout:""},gg=e=>{let t=e(hg,tK(zu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},uK=async e=>{try{return e==="win32"?yg(e,Rx(Ic)):yg(e,await qu(e==="darwin"?
|
|
379
|
+
available; on Windows, run it from a shell started as Administrator.`,bg=e=>!!(e.endpoint&&!e.noEndpoint&&(e.signIn||e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),Ex=(e,t=Is())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),xx=(e,t=Is(),n=!1)=>(bg(e)||n)&&t!=="win32",me=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},rK=Ke.object({kind:Ke.enum(["pkg","deb","rpm","msi"]),path:Ke.string().min(1).refine(K1),sha256:Ke.string().regex(/^[0-9a-f]{64}$/)}).strict(),oK=Ke.object({action:Ke.literal("restart"),os:Ke.enum(["darwin","linux","win32"])}).strict(),aK=Ke.object({action:Ke.literal("configure"),os:Ke.enum(["darwin","linux","win32"]),fleetUrl:Ke.string().min(1).max(2048),enrollSecret:Ke.string().min(1).max(4096),package:rK.optional()}).strict(),sK=Ke.discriminatedUnion("action",[oK,aK]),Ic=(e,t)=>{let n=wx(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},Cg=async e=>{try{return await bx(e,Ax.F_OK),!0}catch{return!1}},iK=async e=>{try{let t=await W1(e);return t.isFile()&&t.size>0}catch{return!1}},Ag=(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}},pg=(e,t)=>Ag(e,t)!==null,dx=e=>e==="win32"?kc:vc,cK=e=>e==="win32"?Sx:vx,lK=e=>pg(e,"ORBIT_FLEET_URL")&&pg(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${vc}</string>`)&&!pg(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),dK=e=>{let t=(n,r)=>e.split(`
|
|
380
|
+
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",vc)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},yg=(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(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/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()},Rx=e=>{let t=e(mg,["qc",zu,"8192"]);return t.status===0?t.stdout:""},gg=e=>{let t=e(hg,tK(zu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},uK=async e=>{try{return e==="win32"?yg(e,Rx(Ic)):yg(e,await qu(e==="darwin"?Ss:Xu,"utf8"))}catch{return}},pK=async e=>{try{if(e==="win32")return await Cg(Ix)&&yg(e,Rx(Ic))!==void 0;let n=await qu(e==="darwin"?Ss:Xu,"utf8");return e==="darwin"?lK(n):dK(n)}catch{return!1}},Ox=async(e,t={})=>{let n=t.exists??Cg,r=t.command??Ic,o,a="absent";if(e==="win32")a=gg(r),o=await n(q1)&&a!=="absent";else{let l=e==="darwin"?await n(Ss):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(z1)&&l}let s=await(t.configured??pK)(e),i=await(t.hasNodeKey??(()=>iK(cK(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}},fK=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),_x=(e,t)=>{let n=Ag(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]===`
|
|
381
381
|
`&&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},mK=(e,t)=>{let n=_x(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},ux=(e,t,n)=>{let r=`
|
|
382
382
|
<key>${t}</key>
|
|
383
383
|
<string>${fK(n)}</string>`,o=_x(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Ag(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new me("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)},hK=(e,t,n=vc)=>{let r=mK(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=ux(r,"ORBIT_FLEET_URL",t),ux(r,"ORBIT_ENROLL_SECRET_PATH",n)},yK=(e,t,n=vc)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
|
|
@@ -390,13 +390,13 @@ available; on Windows, run it from a shell started as Administrator.`,bg=e=>!!(e
|
|
|
390
390
|
# file, never in this world-readable one.
|
|
391
391
|
ORBIT_FLEET_URL=${t}
|
|
392
392
|
ORBIT_ENROLL_SECRET_PATH=${n}
|
|
393
|
-
`},Tx=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}},gK=Ke.object({code:Ke.string().min(1).optional(),message:Ke.string().min(1).optional()}).passthrough(),px=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},wK=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=gK.safeParse(t);if(!r.success)return n;let o=px(r.data.message??""),a=px(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},fx=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??Y1),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":Ne},body:"{}",signal:r.signal})}catch{throw new me("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new me("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new me(wK(a.status,c))}let s;try{s=await a.json()}catch{throw new me("The gateway returned malformed endpoint enrollment data.")}let i=Ke.object({fleetUrl:Ke.string().min(1).max(2048),enrollSecret:Ke.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!Tx(i.data.fleetUrl))throw new me("The gateway returned invalid endpoint enrollment data.");return i.data},bK=async(e={})=>{let t=e.exists??Cg;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 me("Linux endpoint installation requires either dpkg or rpm.")},CK=async e=>e==="darwin"?"pkg":e==="win32"?"msi":bK(),kg=e=>`fleetd.${e}`,AK=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",kK=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),j1);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},vK=async(e,t={})=>{let n=kg(e),r=t.fetchResponse??fetch,o;try{o=await kK(`${ix}/SHA256SUMS`,r)}catch{throw new me("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new me(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=sg(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await Cx(Ju(H1(),"anyray-endpoint-")),i=Ju(s,n);try{await fg(s,448),await(t.download??lg)(`${ix}/${n}`,i,a)}catch(c){if(await yo(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Cc&&c.status===404)return;throw new me("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>yo(s,{recursive:!0,force:!0})}},SK=async(e,t,n)=>{await B1(G1(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await yo(r,{force:!0});try{await U1(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await F1(r,e)}catch(o){throw await yo(r,{force:!0}).catch(()=>{}),o}},mx=async e=>{let t=N1("sha256");for await(let n of L1(e))t.update(n);return t.digest("hex")},IK=async(e,t={})=>{let n=await M1(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new me("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await mx(e.path)!==e.sha256)throw new me("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await Cx(Ju(X1,"anyray-endpoint-root-")),o=Ju(r,kg(e.kind));try{if(await fg(r,448),await $1(e.path,o),await fg(o,384),await mx(o)!==e.sha256)throw new me("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>yo(r,{recursive:!0,force:!0})}}catch(a){throw await yo(r,{recursive:!0,force:!0}).catch(()=>{}),a}},
|
|
393
|
+
`},Tx=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}},gK=Ke.object({code:Ke.string().min(1).optional(),message:Ke.string().min(1).optional()}).passthrough(),px=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},wK=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=gK.safeParse(t);if(!r.success)return n;let o=px(r.data.message??""),a=px(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},fx=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??Y1),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":Ne},body:"{}",signal:r.signal})}catch{throw new me("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new me("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new me(wK(a.status,c))}let s;try{s=await a.json()}catch{throw new me("The gateway returned malformed endpoint enrollment data.")}let i=Ke.object({fleetUrl:Ke.string().min(1).max(2048),enrollSecret:Ke.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!Tx(i.data.fleetUrl))throw new me("The gateway returned invalid endpoint enrollment data.");return i.data},bK=async(e={})=>{let t=e.exists??Cg;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 me("Linux endpoint installation requires either dpkg or rpm.")},CK=async e=>e==="darwin"?"pkg":e==="win32"?"msi":bK(),kg=e=>`fleetd.${e}`,AK=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",kK=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),j1);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},vK=async(e,t={})=>{let n=kg(e),r=t.fetchResponse??fetch,o;try{o=await kK(`${ix}/SHA256SUMS`,r)}catch{throw new me("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new me(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=sg(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await Cx(Ju(H1(),"anyray-endpoint-")),i=Ju(s,n);try{await fg(s,448),await(t.download??lg)(`${ix}/${n}`,i,a)}catch(c){if(await yo(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Cc&&c.status===404)return;throw new me("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>yo(s,{recursive:!0,force:!0})}},SK=async(e,t,n)=>{await B1(G1(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await yo(r,{force:!0});try{await U1(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await F1(r,e)}catch(o){throw await yo(r,{force:!0}).catch(()=>{}),o}},mx=async e=>{let t=N1("sha256");for await(let n of L1(e))t.update(n);return t.digest("hex")},IK=async(e,t={})=>{let n=await M1(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new me("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await mx(e.path)!==e.sha256)throw new me("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await Cx(Ju(X1,"anyray-endpoint-root-")),o=Ju(r,kg(e.kind));try{if(await fg(r,448),await $1(e.path,o),await fg(o,384),await mx(o)!==e.sha256)throw new me("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>yo(r,{recursive:!0,force:!0})}}catch(a){throw await yo(r,{recursive:!0,force:!0}).catch(()=>{}),a}},vs=(e,t)=>{if(e.status!==0)throw new me(t)},hx="com.fleetdm.fleetd.config",EK="com.fleetdm.fleetd.enroll.secret",xK=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",vx],RK=[Q1,Sx],OK=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(hx))throw new me(`This machine already receives its endpoint configuration from an MDM profile (${hx}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},yx=async(e,t,n)=>{let r=n.removeFile??(o=>yo(o,{force:!0}));for(let o of e==="win32"?RK:xK)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",EK,"/Library/Keychains/System.keychain"])},_K=e=>{e(Zu,[kc,"/inheritance:r"]),e(Zu,[kc,"/grant:r","*S-1-5-18:(F)"]),e(Zu,[kc,"/grant:r","*S-1-5-32-544:(F)"]),e(Zu,[kc,"/remove:g","*S-1-5-32-545"])},TK=(e,t,n)=>{if(e.kind==="pkg"){vs(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){vs(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){vs(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}vs(t(eK,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},PK=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<ug;r++){if(n=t("/bin/launchctl",["bootstrap","system",Ss]),n.status===0)return;t("/bin/sleep",[J1])}throw new me(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(mg,["stop",zu]);for(let n=0;n<ug;n++){let r=gg(t);if(r==="Stopped"||r==="absent")break;t(hg,lx)}for(let n=0;n<ug;n++){if(t(mg,["start",zu]).status===0||gg(t)==="Running")return;t(hg,lx)}throw new me("Orbit was configured, but the Windows service could not be started.")}vs(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),vs(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},DK=e=>new Promise(t=>setTimeout(t,e)),Px=async(e,t={})=>{let n=t.command??Ic,r=t.readText??(c=>qu(c,"utf8")),o=t.writeText??SK,a=t.removeSecret??(()=>yo(dx(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&OK(n),e.package&&!AK(e.os,e.package.kind))throw new me("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new me("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await yx(e.os,n,t),e.package){let d=await(t.preparePackage??IK)(e.package);i=d.cleanup,TK(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Ss);await o(Ss,hK(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(Xu);await o(Xu,yK(d,e.fleetUrl),420)}else await o(Ix,`anyray
|
|
394
394
|
`,384);e.os!=="win32"&&await yx(e.os,n,t),await o(dx(e.os),`${e.enrollSecret}
|
|
395
|
-
`,384),e.os==="win32"&&_K(n),s=e.os!=="win32"}PK(e.os,n);let c=t.checkIn??(async d=>{let u=await Ox(d);return u.running&&u.checkedIn}),l=t.wait??DK;for(let d=0;d<(t.attempts??cx);d++){if(await c(e.os))return;d+1<(t.attempts??cx)&&await l(Z1)}throw new me("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(()=>{})}},LK=async()=>{try{return await bx("/dev/tty",Ax.R_OK),!0}catch{return!1}},NK=12288,$K=e=>{let t=e(wg,["/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>=NK},MK=async(e,t={})=>{if((t.os??
|
|
395
|
+
`,384),e.os==="win32"&&_K(n),s=e.os!=="win32"}PK(e.os,n);let c=t.checkIn??(async d=>{let u=await Ox(d);return u.running&&u.checkedIn}),l=t.wait??DK;for(let d=0;d<(t.attempts??cx);d++){if(await c(e.os))return;d+1<(t.attempts??cx)&&await l(Z1)}throw new me("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(()=>{})}},LK=async()=>{try{return await bx("/dev/tty",Ax.R_OK),!0}catch{return!1}},NK=12288,$K=e=>{let t=e(wg,["/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>=NK},MK=async(e,t={})=>{if((t.os??Is())==="win32")return(t.elevated??(()=>$K(t.command??Ic)))()?(await e(),"direct"):((t.print??C)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
396
396
|
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??LK)()){if(await(t.reexec??(async()=>1))()!==0)throw new me("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??C)(`Administrator access is required. Run:
|
|
397
397
|
sudo anyray-connect endpoint install`),"deferred"},BK=async e=>{let t=`${JSON.stringify(e)}
|
|
398
398
|
`;if(Buffer.byteLength(t)>kx)throw new me("The privileged endpoint plan is unexpectedly large.");let n=Sn(["__anyray-endpoint-install"]);return wx("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},FK=async(e,t={})=>(t.withRoot??MK)(()=>(t.apply??Px)(e),{...t.root,reexec:()=>(t.sudo??BK)(e)}),gx=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return $();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return $();let t;try{let s=(await qu("/etc/passwd","utf8")).split(`
|
|
399
|
-
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=
|
|
399
|
+
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Is()==="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 $()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},Dx=async(e={},t={})=>{let n=t.os??Is();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new me("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??Ox)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??gx)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??uK)(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??fx)(l,d);if(u===p.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};M("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new me("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??gx)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new me("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??fx)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let p=await(t.packageKind??(()=>CK(r)))();if(i=await(t.stagePackage??vK)(p),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${kg(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??FK)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},vg=e=>e instanceof me?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",Lx=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return C(nK),0;if(e.length!==1||e[0]!=="install")return D("Usage: anyray-connect endpoint install"),1;try{let t=await Dx();return t.message&&(t.outcome==="installed"?B(t.message):M(t.message)),0}catch(t){return D(vg(t)),1}},WK=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>kx)throw new me("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new me("The privileged endpoint plan is malformed.")}let r=sK.safeParse(n);if(!r.success||r.data.os!==Is()||r.data.action==="configure"&&!Tx(r.data.fleetUrl))throw new me("The privileged endpoint plan is invalid.");return r.data},Nx=async e=>{if((process.getuid?.()??-1)!==0)return D("The privileged endpoint step must run as root."),1;if(e.length!==0)return D("The privileged endpoint step does not accept arguments."),1;try{return await Px(await WK()),0}catch(t){return D(vg(t)),1}},$x=async(e,t=Dx)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?B(n.message):M(n.message)),n.outcome}catch(n){M(`Endpoint agent: ${vg(n)} Tool routing remains configured.`);return}};import{promises as pV}from"node:fs";var zn=e=>typeof e=="string"?e:"",UK=e=>{let t=zn(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=zn(o.text).trim();a&&r.push(a)}return r.join(`
|
|
400
400
|
|
|
401
401
|
`).trim()},HK=e=>{let t=zn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},GK=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=UK(r);if(!o)continue;let a=zn(r.created_at).trim();t.push({role:HK(r),text:o,...a?{createdAt:a}:{}})}return t},Qu=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=GK(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(zn(s.uuid)||zn(s.id)).trim(),l=(zn(s.name)||zn(s.title)).trim()||"Untitled conversation",d=zn(s.created_at).trim(),u=zn(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 sV}from"node:crypto";import{promises as Rc}from"node:fs";import{homedir as Gx}from"node:os";import{join as tp}from"node:path";import{promises as Mx}from"node:fs";import Sg from"node:path";var KK=4e4,VK=16*1024*1024,Ec=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),xc=async(e,t={})=>{let n=(e??"").trim();if(!n)return Ec("","path is required");let r=t.cwd??process.cwd(),o=Sg.resolve(r,n),a=Sg.relative(r,o);if(a.startsWith("..")||Sg.isAbsolute(a))return Ec(n,"path is outside the workspace");let s=t.maxBytes??KK,i;try{let w=await Mx.stat(o);if(!w.isFile())return Ec(n,"not a regular file");let y=t.maxFileBytes??VK;if(w.size>y)return Ec(n,`file too large to read (${w.size} bytes; limit ${y})`);i=await Mx.readFile(o,"utf8")}catch(w){return Ec(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
|
|
402
402
|
`),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(`
|
|
@@ -405,7 +405,7 @@ ORBIT_ENROLL_SECRET_PATH=${n}
|
|
|
405
405
|
${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}
|
|
406
406
|
${e.content}`};import{spawn as jK}from"node:child_process";import{promises as Eg}from"node:fs";import xg from"node:path";var Rg=400,YK=240,ZK=4e3,JK=4e3,XK=512*1024,zK=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),Fx=(e,t)=>e.length>t?e.slice(0,t):e,qK=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"]),QK=8,eV=2e3,tV=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],nV=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")},Wx=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!qK.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=QK))break}return n},Ux=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},rV=(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)},Bx=(e,t,n)=>{let r=[];for(let o of e.split(`
|
|
407
407
|
`)){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:Fx(l,t)})}return r},oV=(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 f of n)c.push("-g",f);for(let f of tV)c.push("-g",f);if(s?.length){for(let f of s)c.push("-e",f);c.push("--",".")}else c.push("--",e,".");let l;try{l=jK("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,p=f=>{u||(u=!0,clearTimeout(m),i(f))},m=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let f=Bx(d,o,r);p({ok:!0,matches:f,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",f=>{if(d+=f,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",f=>{if(typeof f=="number"&&f>=2){p({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let h=Bx(d,o,r+1),w=h.length>r;p({ok:!0,matches:w?h.slice(0,r):h,truncated:w,engine:"ripgrep"})})}),aV=async(e,t,n,r,o,a,s)=>{let i=Ux(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,m=!1,f=async h=>{if(u.length>=r||Date.now()>a){m=!0;return}let w;try{w=await Eg.readdir(h,{withFileTypes:!0})}catch{return}for(let y of w){if(u.length>=r||Date.now()>a){m=!0;return}let g=xg.join(h,y.name);if(y.isDirectory()){if(zK.has(y.name))continue;await f(g)}else if(y.isFile()){if(p>=JK){m=!0;return}if(d.length&&!d.some(A=>y.name.endsWith(A))||nV(xg.relative(t,g)))continue;p+=1;let b;try{if((await Eg.stat(g)).size>XK)continue;b=await Eg.readFile(g,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let k=b.split(`
|
|
408
|
-
`);for(let A=0;A<k.length;A+=1){let
|
|
408
|
+
`);for(let A=0;A<k.length;A+=1){let x=c(k[A]);if(l.some(_=>x.includes(_))&&(u.push({file:xg.relative(t,g),line:A+1,text:Fx(k[A],o)}),u.length>=r)){m=!0;return}}}}};return await f(t),{ok:!0,matches:u,truncated:m,engine:"walk"}},ep=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??Rg,s=t.maxColumns??YK,i=t.timeoutMs??ZK,c=Date.now()+i,l=Wx(n),d=l.length>1,u=Math.min(a*4,eV),p=(y,g)=>aV(n,r,o,y,s,c,g),m=async y=>{let g=await y(u,l);if(!g.ok)return g;let b=rV(g.matches,l,Ux(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:m((g,b)=>p(g,b))}let f=(y,g)=>oV(n,r,o,y,s,Math.max(0,c-Date.now()),g),h=await f(a);if(h.ok){if(h.matches.length>0||!d)return h;let y=await m((g,b)=>f(g,b));return y.ok?y:m((g,b)=>p(g,b))}let w=await p(a);return w.matches.length>0||!d?w:m((y,g)=>p(y,g))},Hx=(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=Wx(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.
|
|
409
409
|
`:"";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,m])=>`${p} (${m} match${m===1?"":"es"})`);return[`${r}${d.size}${t.truncated?"+":""} file${d.size===1?"":"s"} match "${e}":`,...u].join(`
|
|
410
410
|
`)}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(`
|
|
411
411
|
`):[o,...a.slice(0,Math.max(1,l)),s(a.length-Math.max(1,l))].join(`
|
|
@@ -416,7 +416,7 @@ ${r.text}
|
|
|
416
416
|
`).replace(/\n{3,}/g,`
|
|
417
417
|
|
|
418
418
|
`)+`
|
|
419
|
-
`},np=async e=>{let t=await wo();await Rc.mkdir(t,{recursive:!0,mode:Kx});try{await Rc.chmod(t,Kx)}catch{}let n=0,r=0;for(let o of e)try{await Rc.writeFile(tp(t,lV(o)),uV(o),{mode:iV}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},
|
|
419
|
+
`},np=async e=>{let t=await wo();await Rc.mkdir(t,{recursive:!0,mode:Kx});try{await Rc.chmod(t,Kx)}catch{}let n=0,r=0;for(let o of e)try{await Rc.writeFile(tp(t,lV(o)),uV(o),{mode:iV}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Es=async()=>{try{let e=await wo();return(await Rc.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},Vx=async e=>{let t=await wo();return ep(e,{cwd:t,globs:["*.md"]})},jx=async e=>{let t=await wo();return xc(e,{cwd:t,maxBytes:cV})};var Yx=`anyray-connect history <command>
|
|
420
420
|
|
|
421
421
|
Make past Claude conversations searchable from any Anyray-connected client.
|
|
422
422
|
|
|
@@ -437,11 +437,11 @@ Which one you want:
|
|
|
437
437
|
conversation into the chat when you ask for it. Recall, not a list.
|
|
438
438
|
|
|
439
439
|
Running both is fine, and gets you both.
|
|
440
|
-
`,fV=async e=>{try{return{raw:await pV.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"})`}}},mV=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return D("Usage: anyray-connect history import <conversations.json>"),C(v("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await fV(t);if("error"in n)return D(n.error),1;let r=Qu(n.raw);if(!r.ok)return D(`Could not read that export: ${r.message??"unrecognized format"}`),C(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 D("That export contains no conversations with readable messages."),1;let o;try{o=await np(r.conversations)}catch(a){let s=a?.code;return D(`Could not create the history archive (${s??"write failed"}).`),C(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&&C(v(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&P(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),C(""),C(Z("Your history is now searchable from any Anyray-connected client.")),C(v(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),C(v(" and the assistant can search this archive and pull it up.")),C(v(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),C(v(" for them, they do not reappear as a clickable list in the app.")),0},hV=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return D("Usage: anyray-connect history restore <export.zip>"),C(v("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await ou(t);return n.ok?(B(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&C(v(` ${n.skipped} already present, left untouched.`)),n.failed>0&&P(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),C(""),C(Z("Open Claude Desktop \u2014 they are in the sidebar again.")),C(v(" Anyray stays configured; this changed nothing about your routing.")),C(v(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),C(v(" undocumented. A future Desktop release could stop reading it \u2014 your export")),C(v(" file still works, and `history import` remains a second copy.")),0):(D(`Could not restore into Claude Desktop: ${n.reason}`),C(v(` ${n.remedy}`)),1)},yV=async()=>{let e=await wo(),t=await
|
|
440
|
+
`,fV=async e=>{try{return{raw:await pV.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"})`}}},mV=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return D("Usage: anyray-connect history import <conversations.json>"),C(v("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await fV(t);if("error"in n)return D(n.error),1;let r=Qu(n.raw);if(!r.ok)return D(`Could not read that export: ${r.message??"unrecognized format"}`),C(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 D("That export contains no conversations with readable messages."),1;let o;try{o=await np(r.conversations)}catch(a){let s=a?.code;return D(`Could not create the history archive (${s??"write failed"}).`),C(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&&C(v(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&P(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),C(""),C(Z("Your history is now searchable from any Anyray-connected client.")),C(v(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),C(v(" and the assistant can search this archive and pull it up.")),C(v(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),C(v(" for them, they do not reappear as a clickable list in the app.")),0},hV=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return D("Usage: anyray-connect history restore <export.zip>"),C(v("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await ou(t);return n.ok?(B(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&C(v(` ${n.skipped} already present, left untouched.`)),n.failed>0&&P(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),C(""),C(Z("Open Claude Desktop \u2014 they are in the sidebar again.")),C(v(" Anyray stays configured; this changed nothing about your routing.")),C(v(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),C(v(" undocumented. A future Desktop release could stop reading it \u2014 your export")),C(v(" file still works, and `history import` remains a second copy.")),0):(D(`Could not restore into Claude Desktop: ${n.reason}`),C(v(` ${n.remedy}`)),1)},yV=async()=>{let e=await wo(),t=await Es();return t===0?(C(`No conversations imported yet. Archive would live at ${e}`),C(v(" Import one with: anyray-connect history import <conversations.json>")),0):(B(`${t} conversation${t===1?"":"s"} in ${e}`),0)},Zx=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(Yx),0):t==="import"?mV(e.slice(1)):t==="restore"?hV(e.slice(1)):t==="status"?yV():(D(`Unknown history command: ${t}`),console.log(Yx),1)};var gV=1e4,Og=/^[\w.:-]{1,64}$/,tn=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},_g=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,Jx=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),gV);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 tn("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},wV=e=>{let t=_g(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}},bV=e=>{let t=_g(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Og.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Og.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},CV=e=>{let t=_g(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Pe(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Og.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}}},AV=e=>new Promise(t=>setTimeout(t,e)),kV=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new tn("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}C("Available teams:"),e.forEach((i,c)=>C(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await gs("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 tn("invalid-team","Choose one of the teams shown above.");return s},vV=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??AV,a=t.loadProfile??$,s=t.saveProfile??de,i=t.clearDevKey??qs,c=t.chooseTeam??kV,l=t.apply??(async y=>{await Zr.apply(y,{dryRun:!1})}),d=t.log??M,u=await a(),p=Xn(e.gateway,u),m=await Jx(`${p}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),f=wV(m.body);if(m.status!==200||!f)throw new tn("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${f.browser_url}`),d(`Enter this code in the browser: ${f.user_code}`),(t.openBrowser??Rr)(f.browser_url);let h=r()+f.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<h;){let y=await Jx(`${p}/sso/cli/poll/${encodeURIComponent(f.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":f.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(y.status===202){await o(f.interval*1e3);continue}if(y.status===401)throw new tn("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new tn("expired","SSO login expired before it completed. Run anyray-connect login again.");let g=bV(y.body);if(y.status===200&&g){if(w&&!g.teams.includes(w))throw new tn("invalid-team",`Team ${w} is not available for this account.`);w=await c(g.teams,g.default_team,e.interactive??Et());continue}let b=CV(y.body);if(y.status!==200||!b)throw new tn("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 tn("expired","SSO login expired before it completed. Run anyray-connect login again.")},SV=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
441
441
|
|
|
442
442
|
Start browser SSO, choose a team, mint a personal gateway key, and configure
|
|
443
443
|
the subscription-backed Connect lane. In a non-interactive shell, --team may be
|
|
444
|
-
omitted only when the identity authority supplies a default or sole team.`,Xx=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return C(SV),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return D(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return D(`unknown login option: ${a}`),1}try{let o=await vV({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 It)throw o;return D(o instanceof tn?o.message:"SSO login failed."),1}};import{writeFileSync as d2}from"node:fs";import{chmod as Hg,stat as u2}from"node:fs/promises";import{platform as R0}from"node:os";import{dirname as O0,isAbsolute as p2}from"node:path";var IV="https://app.anyray.ai",EV=new Set(["localhost","::1","[::1]"]),xV=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,RV=e=>EV.has(e)||xV.test(e),Tg=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&RV(t.hostname)},OV=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Cn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!Tg(e)?IV:OV(e)};import{createHash as HV,generateKeyPairSync as GV,randomBytes as Lg}from"node:crypto";import{createPrivateKey as _V,sign as TV}from"node:crypto";var qn=async(e,t)=>{let n=_V(t);return TV(null,new TextEncoder().encode(e),n).toString("base64url")};var PV=["HTTPS_PROXY","https_proxy"],zx=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"]),qx=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Qx=new Set(["ENOTFOUND","EAI_AGAIN"]),e0=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),t0=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),DV=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 LV(e)},LV=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...zx,...qx,...Qx,...e0,...t0])if(t.includes(n))return n}},NV=e=>e?.name==="AbortError"||e?.name==="TimeoutError",$V=e=>PV.filter(t=>(e[t]??"").trim()!==""),MV=(e,t=process.env)=>{let n=DV(e),r=$V(t);return{kind:n&&zx.has(n)?"tls-unknown-issuer":n&&qx.has(n)?"tls-invalid-cert":n&&Qx.has(n)?"dns":NV(e)||n&&t0.has(n)?"timeout":n&&e0.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},BV=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}},xt=(e,t=process.env)=>BV(MV(e,t));var FV="enl_",n0="enp_",r0=e=>e.startsWith(FV)||e.startsWith(n0),Pg=e=>e.startsWith(n0),WV=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],Dg=e=>WV.find(t=>e.startsWith(t.prefix)),o0=/^\/enroll\/([^/]+)\/?$/,a0=/^\/i\/([^/]+)\/?$/,s0=e=>{let t=e.match(o0);if(t)return Dg(t[1])?void 0:t[1];let n=e.match(a0);return n&&r0(n[1])?n[1]:void 0},UV=1e4,rp=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=s0(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!Dg(t))return{cpOrigin:Cn(),token:t}},i0=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(o0)??o.pathname.match(a0);if(!a)return;n=a[1]}catch{}let r=Dg(n);return r?{flag:r.flag,what:r.what}:void 0},_c=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:s0(n.pathname)!==void 0}catch{return r0(t)}},Es=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},Oc=e=>typeof e=="string"&&e.trim()?e.trim():void 0,c0=async(e,t={})=>{let n=t.timeoutMs??UV,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.`:xt(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 Es(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"&&Oc(u.url)!==void 0),d=Oc(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:Oc(l?.deploymentId),org:Oc(i.org),email:Oc(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 Ng=1e4,ua=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ua).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${ua(e[n])}`).join(",")}}`,l0="stable-key-heartbeat-v1",d0="key-heartbeat",KV=["reapply_config","remint","revert"],$g=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var u0=e=>HV("sha256").update(e).digest("hex"),Qe=e=>typeof e=="string"&&e.trim()?e.trim():void 0,VV=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],p0={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"},jV=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${p0[e]}. Ask your IT admin.`,YV=e=>typeof e=="string"&&e in p0,Mg=async e=>{try{let t=await e.json(),n=Qe(t?.message),r=Qe(t?.error),o=YV(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:jV(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},ZV=async e=>(await Mg(e)).message,it=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}},Tc=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="GatewayUnreachableError"}},Pc=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="ControlPlaneUnreachableError"}},Bg=e=>e instanceof Es||e instanceof it&&e.policyCode==="sso_required",xs=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}},Fg=async(e,t,n,r)=>{try{return await r(ua(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Rs=()=>{let{publicKey:e,privateKey:t}=GV("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},An=async(e,t,n,r={})=>{let o=r.timeoutMs??Ng,a=`${e}/connect/verify`,s=Qe(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:Lg(16).toString("hex"),...$g(t,r.machineUuid)},c=await Fg(i,n,"verification",r.signer??qn),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":Ne},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.`:xt(g);throw new Tc(`could not reach the gateway at ${a}.${b}`,g)}finally{clearTimeout(d)}if(!u.ok)throw new it(u.status,await Mg(u));let p;try{p=await u.text()}catch{p=""}let m;try{m=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 f=Qe(m?.key);if(!f)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(f))throw new Error("developer verification failed: the gateway returned a malformed key");let h=Qe(m.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let w=JV(m.directive),y=VV(m.capabilities);return{key:f,user:h,team:Qe(m.team),expiresAt:Qe(m.expiresAt),...y.length>0?{capabilities:y}:{},...w?{directive:w}:{}}},f0=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Ng,s=`${e}/connect/key/heartbeat`,i=Qe(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:Lg(16).toString("hex"),purpose:d0,...$g(n,o.machineUuid)},l=await Fg(c,r,"heartbeat",o.signer??qn),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":Ne},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.`:xt(h);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:h})}finally{clearTimeout(u)}if(!p.ok)throw new xs(p.status,await Mg(p));let m;try{m=await p.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let f=Qe(m.expiresAt);if(!f||!Number.isFinite(Date.parse(f))||m.credentialMode!==l0||m.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:f,credentialMode:l0}},m0=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Ng,i=`${e.replace(/\/$/,"")}/connect/machine`,c=Qe(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Lg(16).toString("hex"),purpose:d0,...$g(n,o)},d=await Fg(l,r,"heartbeat",a.signer??qn),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":Ne},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(m){return console.error("connect machine report skipped:",m instanceof Error?m.name:"error"),!1}finally{clearTimeout(p)}},JV=e=>{if(e===null||typeof e!="object")return null;let t=e,n=Qe(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!KV.includes(r)?null:{id:n,kind:r}},XV=1e4,zV=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!Qe(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!Qe(r.deploymentId)&&!!Qe(r.user)&&!!Qe(r.devPublicKey)&&!!Qe(r.issuedAt)&&!!Qe(r.expiresAt)},qV=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??XV,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.`:xt(u);throw new Pc(`could not reach the control plane at ${s}.${p}`,u)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await ZV(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new Es(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(!zV(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},h0=(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())},y0=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=Rs();return{cert:await qV(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await An(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};var Wg=1e4,QV=900*1e3,w0="tnt_",e2=/^\/sso\/([^/]+)\/?$/,t2=/^\/i\/([^/]+)\/?$/,n2=e=>{let t=e.match(e2);if(t)return t[1];let n=e.match(t2);return n?.[1].startsWith(w0)?n[1]:void 0},Mt=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=n2(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(w0))return{cpOrigin:Cn(),tenantId:t}},wt=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Rt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},r2=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),b0=async e=>{try{let t=await e.json();return r2(t)?t:{}}catch{return{}}},Dc=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});return{status:s.status,json:await b0(s)}}finally{clearTimeout(a)}},C0=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await r(e,{method:"GET",headers:t,redirect:"manual",signal:o.signal});return{status:s.status,json:await b0(s)}}finally{clearTimeout(a)}},o2=e=>new Promise(t=>setTimeout(t,e)),op=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Rs)(),a;try{a=await Dc(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},Wg,n)}catch(f){throw new wt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${xt(f)}`)}if(a.status!==200){let f=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new wt(f?"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 wt("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??QV,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},m=e.log??(()=>{});return m("To finish, sign in with your organization at:"),m(` ${p.verificationUriComplete}`),m(`Confirm this code matches your browser: ${p.userCode}`),a2(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},a2=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ap=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??o2,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 Dc(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},Wg,o)}catch(c){throw new Rt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${xt(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 Rt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Rt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Rt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var g0="sdc_",A0=e=>{let t=e.trim();if(!t)return;if(t.startsWith(g0))return{cpOrigin:Cn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!Tg(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(g0)))return{cpOrigin:n.origin,claim:r}},k0=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Rs)(),o;try{o=await Dc(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},Wg,t)}catch(s){throw new Rt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${xt(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 Rt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Rt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Rt("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 s2}from"node:fs/promises";import{isAbsolute as i2,posix as v0,win32 as Ug}from"node:path";var Lc=(e=process.platform,t=process.env)=>e==="darwin"?v0.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?Ug.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):v0.join("/etc","anyray","bootstrap.json"),c2=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),S0=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(i2(e)||Ug.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),l2=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}},bo=async(e=Lc())=>{try{let t=await s2(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!c2(n)||n.v!==1||typeof n.sso!="string")return;let r=Mt(n.sso);if(!r)return;let o=l2(n.gateway)?n.gateway:void 0,a=S0(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},I0=(e,t,n)=>{let r=Mt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!S0(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&Ug.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)}
|
|
444
|
+
omitted only when the identity authority supplies a default or sole team.`,Xx=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return C(SV),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return D(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return D(`unknown login option: ${a}`),1}try{let o=await vV({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 It)throw o;return D(o instanceof tn?o.message:"SSO login failed."),1}};import{writeFileSync as d2}from"node:fs";import{chmod as Hg,stat as u2}from"node:fs/promises";import{platform as R0}from"node:os";import{dirname as O0,isAbsolute as p2}from"node:path";var IV="https://app.anyray.ai",EV=new Set(["localhost","::1","[::1]"]),xV=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,RV=e=>EV.has(e)||xV.test(e),Tg=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&RV(t.hostname)},OV=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Cn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!Tg(e)?IV:OV(e)};import{createHash as HV,generateKeyPairSync as GV,randomBytes as Lg}from"node:crypto";import{createPrivateKey as _V,sign as TV}from"node:crypto";var qn=async(e,t)=>{let n=_V(t);return TV(null,new TextEncoder().encode(e),n).toString("base64url")};var PV=["HTTPS_PROXY","https_proxy"],zx=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"]),qx=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Qx=new Set(["ENOTFOUND","EAI_AGAIN"]),e0=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),t0=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),DV=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 LV(e)},LV=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...zx,...qx,...Qx,...e0,...t0])if(t.includes(n))return n}},NV=e=>e?.name==="AbortError"||e?.name==="TimeoutError",$V=e=>PV.filter(t=>(e[t]??"").trim()!==""),MV=(e,t=process.env)=>{let n=DV(e),r=$V(t);return{kind:n&&zx.has(n)?"tls-unknown-issuer":n&&qx.has(n)?"tls-invalid-cert":n&&Qx.has(n)?"dns":NV(e)||n&&t0.has(n)?"timeout":n&&e0.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},BV=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}},xt=(e,t=process.env)=>BV(MV(e,t));var FV="enl_",n0="enp_",r0=e=>e.startsWith(FV)||e.startsWith(n0),Pg=e=>e.startsWith(n0),WV=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],Dg=e=>WV.find(t=>e.startsWith(t.prefix)),o0=/^\/enroll\/([^/]+)\/?$/,a0=/^\/i\/([^/]+)\/?$/,s0=e=>{let t=e.match(o0);if(t)return Dg(t[1])?void 0:t[1];let n=e.match(a0);return n&&r0(n[1])?n[1]:void 0},UV=1e4,rp=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=s0(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!Dg(t))return{cpOrigin:Cn(),token:t}},i0=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(o0)??o.pathname.match(a0);if(!a)return;n=a[1]}catch{}let r=Dg(n);return r?{flag:r.flag,what:r.what}:void 0},_c=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:s0(n.pathname)!==void 0}catch{return r0(t)}},xs=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},Oc=e=>typeof e=="string"&&e.trim()?e.trim():void 0,c0=async(e,t={})=>{let n=t.timeoutMs??UV,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.`:xt(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 xs(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"&&Oc(u.url)!==void 0),d=Oc(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:Oc(l?.deploymentId),org:Oc(i.org),email:Oc(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 Ng=1e4,pa=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(pa).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${pa(e[n])}`).join(",")}}`,l0="stable-key-heartbeat-v1",d0="key-heartbeat",KV=["reapply_config","remint","revert"],$g=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var u0=e=>HV("sha256").update(e).digest("hex"),Qe=e=>typeof e=="string"&&e.trim()?e.trim():void 0,VV=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],p0={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"},jV=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${p0[e]}. Ask your IT admin.`,YV=e=>typeof e=="string"&&e in p0,Mg=async e=>{try{let t=await e.json(),n=Qe(t?.message),r=Qe(t?.error),o=YV(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:jV(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},ZV=async e=>(await Mg(e)).message,it=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}},Tc=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="GatewayUnreachableError"}},Pc=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="ControlPlaneUnreachableError"}},Bg=e=>e instanceof xs||e instanceof it&&e.policyCode==="sso_required",Rs=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}},Fg=async(e,t,n,r)=>{try{return await r(pa(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Os=()=>{let{publicKey:e,privateKey:t}=GV("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},An=async(e,t,n,r={})=>{let o=r.timeoutMs??Ng,a=`${e}/connect/verify`,s=Qe(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:Lg(16).toString("hex"),...$g(t,r.machineUuid)},c=await Fg(i,n,"verification",r.signer??qn),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":Ne},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.`:xt(g);throw new Tc(`could not reach the gateway at ${a}.${b}`,g)}finally{clearTimeout(d)}if(!u.ok)throw new it(u.status,await Mg(u));let p;try{p=await u.text()}catch{p=""}let m;try{m=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 f=Qe(m?.key);if(!f)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(f))throw new Error("developer verification failed: the gateway returned a malformed key");let h=Qe(m.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let w=JV(m.directive),y=VV(m.capabilities);return{key:f,user:h,team:Qe(m.team),expiresAt:Qe(m.expiresAt),...y.length>0?{capabilities:y}:{},...w?{directive:w}:{}}},f0=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Ng,s=`${e}/connect/key/heartbeat`,i=Qe(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:Lg(16).toString("hex"),purpose:d0,...$g(n,o.machineUuid)},l=await Fg(c,r,"heartbeat",o.signer??qn),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":Ne},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.`:xt(h);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:h})}finally{clearTimeout(u)}if(!p.ok)throw new Rs(p.status,await Mg(p));let m;try{m=await p.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let f=Qe(m.expiresAt);if(!f||!Number.isFinite(Date.parse(f))||m.credentialMode!==l0||m.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:f,credentialMode:l0}},m0=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Ng,i=`${e.replace(/\/$/,"")}/connect/machine`,c=Qe(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Lg(16).toString("hex"),purpose:d0,...$g(n,o)},d=await Fg(l,r,"heartbeat",a.signer??qn),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":Ne},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(m){return console.error("connect machine report skipped:",m instanceof Error?m.name:"error"),!1}finally{clearTimeout(p)}},JV=e=>{if(e===null||typeof e!="object")return null;let t=e,n=Qe(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!KV.includes(r)?null:{id:n,kind:r}},XV=1e4,zV=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!Qe(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!Qe(r.deploymentId)&&!!Qe(r.user)&&!!Qe(r.devPublicKey)&&!!Qe(r.issuedAt)&&!!Qe(r.expiresAt)},qV=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??XV,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.`:xt(u);throw new Pc(`could not reach the control plane at ${s}.${p}`,u)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await ZV(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new xs(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(!zV(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},h0=(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())},y0=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=Os();return{cert:await qV(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await An(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};var Wg=1e4,QV=900*1e3,w0="tnt_",e2=/^\/sso\/([^/]+)\/?$/,t2=/^\/i\/([^/]+)\/?$/,n2=e=>{let t=e.match(e2);if(t)return t[1];let n=e.match(t2);return n?.[1].startsWith(w0)?n[1]:void 0},Mt=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=n2(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(w0))return{cpOrigin:Cn(),tenantId:t}},wt=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Rt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},r2=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),b0=async e=>{try{let t=await e.json();return r2(t)?t:{}}catch{return{}}},Dc=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});return{status:s.status,json:await b0(s)}}finally{clearTimeout(a)}},C0=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await r(e,{method:"GET",headers:t,redirect:"manual",signal:o.signal});return{status:s.status,json:await b0(s)}}finally{clearTimeout(a)}},o2=e=>new Promise(t=>setTimeout(t,e)),op=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Os)(),a;try{a=await Dc(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},Wg,n)}catch(f){throw new wt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${xt(f)}`)}if(a.status!==200){let f=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new wt(f?"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 wt("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??QV,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},m=e.log??(()=>{});return m("To finish, sign in with your organization at:"),m(` ${p.verificationUriComplete}`),m(`Confirm this code matches your browser: ${p.userCode}`),a2(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},a2=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ap=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??o2,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 Dc(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},Wg,o)}catch(c){throw new Rt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${xt(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 Rt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Rt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Rt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var g0="sdc_",A0=e=>{let t=e.trim();if(!t)return;if(t.startsWith(g0))return{cpOrigin:Cn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!Tg(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(g0)))return{cpOrigin:n.origin,claim:r}},k0=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Os)(),o;try{o=await Dc(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},Wg,t)}catch(s){throw new Rt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${xt(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 Rt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Rt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Rt("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 s2}from"node:fs/promises";import{isAbsolute as i2,posix as v0,win32 as Ug}from"node:path";var Lc=(e=process.platform,t=process.env)=>e==="darwin"?v0.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?Ug.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):v0.join("/etc","anyray","bootstrap.json"),c2=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),S0=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(i2(e)||Ug.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),l2=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}},bo=async(e=Lc())=>{try{let t=await s2(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!c2(n)||n.v!==1||typeof n.sso!="string")return;let r=Mt(n.sso);if(!r)return;let o=l2(n.gateway)?n.gateway:void 0,a=S0(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},I0=(e,t,n)=>{let r=Mt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!S0(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&Ug.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)}
|
|
445
445
|
`};var Gg=`${Z("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
|
|
446
446
|
|
|
447
447
|
Emit or install the OS \`managed-settings.json\` that points a managed fleet's
|
|
@@ -531,7 +531,7 @@ ${Z("Examples")}
|
|
|
531
531
|
anyray-connect managed --print --tool jetbrains --bin /usr/local/bin/anyray-connect --npx /usr/local/bin/npx > acp.json
|
|
532
532
|
|
|
533
533
|
# Shell/SDK fleet snippet (base URLs only; keys stay per-user):
|
|
534
|
-
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,E0=["claude-code","jetbrains","shell","bootstrap"],f2=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"--lock-skills":t.lockSkills=!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(!E0.includes(a))throw new Error(`unknown --tool ${a} (expected ${E0.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&&!Mt(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};var x0=e=>({extraKnownMarketplaces:{[vn]:{source:{source:"url",url:Wb(e)}}},strictPluginOnlyCustomization:{skills:!0}});function sp(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 a=["__anyray-sso-gate","--sso",t.sso,...t.gateway?["--gateway",t.gateway]:[],...t.team?["--team",t.team]:[]];return{hooks:{PostToolUse:[nr(
|
|
534
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,E0=["claude-code","jetbrains","shell","bootstrap"],f2=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"--lock-skills":t.lockSkills=!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(!E0.includes(a))throw new Error(`unknown --tool ${a} (expected ${E0.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&&!Mt(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};var x0=e=>({extraKnownMarketplaces:{[vn]:{source:{source:"url",url:Wb(e)}}},strictPluginOnlyCustomization:{skills:!0}});function sp(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 a=["__anyray-sso-gate","--sso",t.sso,...t.gateway?["--gateway",t.gateway]:[],...t.team?["--team",t.team]:[]];return{hooks:{PostToolUse:[nr(ni(t.binaryPath,[nt]),{matcher:"*"})],UserPromptSubmit:[nr(ni(t.binaryPath,a),{timeout:30}),nr(ni(t.binaryPath,[Gr]))],SessionStart:[nr(ni(t.binaryPath,[...a,"--session-start"]),{async:!0})]},...n.lockSkills?x0(e.origin):{}}}let{env:r}=En(e,{includeAuthToken:!1,includeClientKey:!1}),o=n.lockSkills?x0(e.origin):{};return n.scrubDirectMode?{env:{...Object.fromEntries(rr.map(a=>[a.name,""])),...r},...o}:{env:r,...o}}var m2=(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 To)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,If(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 _0(r),n.extraKnownMarketplaces&&(r.extraKnownMarketplaces={...r.extraKnownMarketplaces??{},...n.extraKnownMarketplaces}),n.strictPluginOnlyCustomization&&(r.strictPluginOnlyCustomization=n.strictPluginOnlyCustomization),r},_0=e=>{let t=!1,n=e.extraKnownMarketplaces;return n&&typeof n=="object"&&vn in n&&(delete n[vn],Object.keys(n).length===0&&delete e.extraKnownMarketplaces,t=!0),JSON.stringify(e.strictPluginOnlyCustomization)===JSON.stringify({skills:!0})&&(delete e.strictPluginOnlyCustomization,t=!0),t},h2=e=>{let t=e.env,n=If(e);if(t){for(let r of To)r in t&&(delete t[r],n=!0);for(let{name:r}of rr)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return _0(e)&&(n=!0),n},T0=async e=>{let t=async n=>{try{return(await u2(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(O0(e))!==void 0}},P0=async(e,t)=>(t.dirExisted||await Hg(O0(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await Hg(e,420),{mode:420,keptRestricted:!1}):(await Hg(e,t.mode),{mode:t.mode,keptRestricted:!0})),D0=(e,t)=>{t.keptRestricted&&(P(`${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.`),C(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.")))},L0=()=>process.getuid?.()===0,et=e=>{process.stderr.write(`${e}
|
|
535
535
|
`)},ip=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}d2(e.out,t,"utf8"),et(v(`# Wrote ${e.out}`))},Kg=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??""}),Vg=e=>p2(e)||/^[A-Za-z]:[\\/]/.test(e),N0=e=>{if(!e.sso)return;let t=Mt(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??De();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(!Vg(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}},$0=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${be(e.metadata)??"(none \u2014 pass --team)"}`],jg=(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{}},y2=(e,t)=>({agent_servers:{[Er]:{command:e,args:[gu,"claude",t,"jetbrains"],env:{}},[xr]:{command:e,args:[gu,"codex",t,"jetbrains"],env:{}}}}),g2=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=${$e(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${$e(e.anthropicBaseUrl)}`,""].join(`
|
|
536
536
|
`),w2=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(!Vg(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(!Cu(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return ip(e,`${JSON.stringify(y2(e.bin,e.npx),null,2)}
|
|
537
537
|
`),et(v("# acp.json for ~/.jetbrains/acp.json (per user).")),et(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),et(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),et(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},b2=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&&!Vg(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return ip(e,I0(e.sso,e.gateway,e.bin)),et(v(`# Fleet bootstrap for ${Lc("linux")}`)),et(v(`# macOS: ${Lc("darwin")}`)),et(v(`# Windows: ${Lc("win32",{ProgramData:"C:\\ProgramData"})}`)),et(v("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},C2=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=Kg(e);return ip(e,g2(t)),et(v("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),jg(t,et),0},A2=e=>{let t=Kg(e),n=N0(e),r=n?sp(t,n,{lockSkills:e.lockSkills}):sp(t,void 0,{scrubDirectMode:e.scrubDirectMode,lockSkills:e.lockSkills});if(ip(e,`${JSON.stringify(r,null,2)}
|
|
@@ -566,8 +566,8 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
|
|
|
566
566
|
Open claude.ai -> Settings -> Privacy -> Export data. Anthropic emails a link.
|
|
567
567
|
Pass the .zip to --export, and the conversations.json inside it to
|
|
568
568
|
--conversations. Both are safe to re-run; they skip what is already there.
|
|
569
|
-
`,E2=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},B0={code:"Claude Code sessions",cowork:"Cowork tasks"},x2=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`${B0[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},R2=async(e,t)=>{C(Z("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??
|
|
570
|
-
`).filter(Boolean))C(` ${s}`);return!1}for(let s of n.lanes)C(` ${x2(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";C(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&P(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&P(` 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&&P(` ${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??[])P(` ${B0[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),C(` ${Cy(s.reason,s.lane,Ot("migrate"))}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&C(v(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},O2=async(e,t)=>{if(C(""),C(Z("2. Your claude.ai chats")),t){C(v(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){C(" These live on your Claude account, not this machine, so they need"),C(" an export. Anyray cannot fetch them: the only credential that could"),C(" is your claude.ai session, which Connect never holds."),C(v(" claude.ai -> Settings -> Privacy -> Export data, then:")),C(v(` ${Ot("migrate --export ~/Downloads/claude-export.zip")}`));return}let n=await ou(e.exportZip);if(!n.ok){D(` ${n.reason}`),C(` ${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`:"")),C(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&&C(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},_2=async e=>{if(C(""),C(Z("3. Searchable from every Anyray client")),!e.conversations){let o=await Is();o>0?C(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(C(v(" Optional. Pass the conversations.json inside the export:")),C(v(` ${Ot("migrate --conversations <path>/conversations.json")}`)));return}let t;try{t=await S2.readFile(e.conversations,"utf8")}catch{D(` could not read ${e.conversations}`);return}let n=Qu(t);if(!n.ok){D(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await np(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`:"")),C(v(` Ask any Anyray-connected client about a past chat. ${await wo()}`))},T2=e=>{C(""),C(Z("Next")),C(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||P(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),C(v(` No Chat tab? Configured before this Connect version: run \`${Ot("desktop")}\`.`))},F0=async(e,t={})=>{let n;try{n=E2(e)}catch(o){return D(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(I2),0;C(Z("Migrating Claude Desktop onto Anyray")),C(v("Claude Desktop must be fully quit.")),C("");let r=await R2(n,t);return await O2(n,!r),await _2(n),r?(T2(n),0):(C(""),P("Fix the item above and re-run to finish the migration."),1)};import{spawn as Xj}from"node:child_process";import{homedir as zj}from"node:os";import{join as IR}from"node:path";import{readFile as qj,writeFile as ER,chmod as Qj,stat as eY,unlink as hR}from"node:fs/promises";import{mkdir as D2,readFile as L2,rm as N2,rmdir as $2,writeFile as M2}from"node:fs/promises";import{join as Nc}from"node:path";import{z as ge}from"zod";var pa="required",P2=e=>e==="subscription"?"subscription":"placeholder",W0=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?P2(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}:{}}},cp=(e,t,n)=>{let r=new Set(t.enabled??[]),o=e.managedTools??[],a=o.filter(u=>r.has(u)||n);if(t.defaulted===!0&&e.toolSelection!=="all")return{candidateIds:a,freshIds:[],tombstonedIds:[]};let s=new Set(e.revertedTools??[]),i=e.revertedTools!=null,c=u=>t.tiers?.[u]??pa,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}},U0=(e,t,n)=>{let r=[],o=[],a=[];if(t===void 0||t.defaulted===!0){for(let c of n)jr(c)?a.push({id:c.id,reason:"consent"}):r.push(c.id);return{applyIds:r,revertIds:o,skipped:a}}let s=new Set(e.managedTools??[]),i=new Set(t.enabled??[]);for(let c of n){let{id:l}=c;if(!i.has(l)){s.has(l)?o.push(l):a.push({id:l,reason:"not_enabled"});continue}if(s.has(l)){r.push(l);continue}let d=t.tiers?.[l]??pa;if(d==="optional"){a.push({id:l,reason:"optional"});continue}if(jr(c)){d==="locked"?r.push(l):a.push({id:l,reason:"consent"});continue}r.push(l)}return{applyIds:r,revertIds:o,skipped:a}};var B2=1e4,F2=1,K0=ge.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),W2=ge.object({id:K0,name:ge.string().min(1),version:ge.string().min(1),body:ge.string(),plugin:ge.boolean().optional()}),U2=ge.object({url:ge.string().url(),plugins:ge.array(K0)}),H2=ge.object({version:ge.literal(F2).optional(),skills:ge.array(W2),skillsIncomplete:ge.boolean().optional(),marketplace:U2.optional(),mcp:ge.object({org:ge.object({url:ge.string().url()})}).optional(),updatedAt:ge.string().min(1).optional(),routing:ge.object({origin:ge.string().min(1)}).optional(),team:ge.string().min(1).optional(),lane:ge.enum(["subscription","org"]).optional().catch(void 0),tools:ge.object({enabled:ge.array(ge.string().min(1)),defaulted:ge.literal(!0).optional().catch(void 0),tiers:ge.record(ge.string().min(1),ge.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional(),updates:ge.object({mode:ge.enum(["auto","directed","off"]).catch("directed")}).optional()}),Os=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},Jg=e=>e instanceof Os&&e.kind==="auth",Yg=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",_s=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",fa=async(e,t,n={})=>{let r=n.timeoutMs??B2,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.`:xt(l);throw new Os("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Os(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 Os("malformed","team policy fetch failed: the gateway returned a malformed response")}return H2.parse(c)},H0=/^[a-z0-9][a-z0-9-]{0,31}$/,G0=64,Xg=e=>{let t=e.tools;if(!t||t.defaulted===!0)return;let n=t.enabled.filter(o=>H0.test(o)).slice(0,G0).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>H0.test(o)).slice(0,G0).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},G2=e=>e.updates?{mode:e.updates.mode}:void 0,$c=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??pa)==="locked":!1},Ts=async(e,t={})=>{let n=t.loadProfile??$,r=t.saveProfile??de,o=t.targetFromProfile??Je,a=t.adapters??se,s=t.repairTools??en,i=t.recordManaged??Fr,c=await n(),l={...c},d=W0(c,{routingOrigin:e.routing?.origin?cn(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:u,teamUpdated:p,laneUpdated:m}=d;(u||p||m)&&(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 f=cp(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers,defaulted:e.tools?.defaulted},u||p||m),{candidateIds:h,freshIds:w}=f,y=0,g=0,b=0;if(h.length>0||w.length>0){let I=await o(async()=>l);if(I){let x;if(u||p||m){let G=new Set(h);x=[];for(let X of a)if(G.has(X.id))try{(await X.detect()).installed&&x.push(X)}catch{}}else x=await ws(h,I.target.origin,a);let _=new Set(w),K=[];for(let G of a)if(_.has(G.id))try{(await G.detect()).installed&&K.push(G)}catch{}if(y=x.length+K.length,y>0){let G=await s([...x,...K],I.target);g=G.filter(ca).length;let X=G.filter(re=>_.has(re.id));if(b=X.filter(ca).length,X.length>0)try{await i(X,!1)}catch{}}}}let k=Xg(e),A=G2(e),E=await n(),O=JSON.stringify(k??null)!==JSON.stringify(E.fleetToolPolicy??null),S=JSON.stringify(A??null)!==JSON.stringify(E.fleetUpdatePolicy??null);if(O||S){let{fleetToolPolicy:I,fleetUpdatePolicy:x,..._}=E;await r({..._,...k?{fleetToolPolicy:k}:{},...A?{fleetUpdatePolicy:A}:{}})}return{routingUpdated:u,teamUpdated:p,laneUpdated:m,toolsRequested:y,toolsApplied:g,toolsEnrolled:b,toolsTombstoned:f.tombstonedIds,profileUpdated:u||p||m,updatesMode:A?.mode??"auto",updatesUpdated:S}},K2=(e,t=se,n=new Set)=>{let r=e.managedTools,o=new Map;for(let a of t){if(r&&!r.includes(a.id))continue;let s=a.skillsDir?.();if(!s)continue;let i=!n.has(a.id),c=o.get(s);o.set(s,{dir:s,includePluginSkills:(c?.includePluginSkills??!1)||i})}return[...o.values()]},V2=e=>e.map(t=>typeof t=="string"?{dir:t,includePluginSkills:!0}:t),Zg=async(e,t)=>{await N2(Nc(e,t,"SKILL.md"),{force:!0}),await $2(Nc(e,t)).catch(()=>{})},j2=e=>{let t=e.body.replace(/\r\n?/g,`
|
|
569
|
+
`,E2=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},B0={code:"Claude Code sessions",cowork:"Cowork tasks"},x2=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`${B0[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},R2=async(e,t)=>{C(Z("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??ta)({account:e.account,allAccounts:e.allAccounts,command:Ot("migrate")});if(!n.ok){D(` ${n.reason}`);for(let s of n.remedy.split(`
|
|
570
|
+
`).filter(Boolean))C(` ${s}`);return!1}for(let s of n.lanes)C(` ${x2(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";C(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&P(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&P(` 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&&P(` ${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??[])P(` ${B0[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),C(` ${Cy(s.reason,s.lane,Ot("migrate"))}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&C(v(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},O2=async(e,t)=>{if(C(""),C(Z("2. Your claude.ai chats")),t){C(v(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){C(" These live on your Claude account, not this machine, so they need"),C(" an export. Anyray cannot fetch them: the only credential that could"),C(" is your claude.ai session, which Connect never holds."),C(v(" claude.ai -> Settings -> Privacy -> Export data, then:")),C(v(` ${Ot("migrate --export ~/Downloads/claude-export.zip")}`));return}let n=await ou(e.exportZip);if(!n.ok){D(` ${n.reason}`),C(` ${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`:"")),C(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&&C(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},_2=async e=>{if(C(""),C(Z("3. Searchable from every Anyray client")),!e.conversations){let o=await Es();o>0?C(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(C(v(" Optional. Pass the conversations.json inside the export:")),C(v(` ${Ot("migrate --conversations <path>/conversations.json")}`)));return}let t;try{t=await S2.readFile(e.conversations,"utf8")}catch{D(` could not read ${e.conversations}`);return}let n=Qu(t);if(!n.ok){D(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await np(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`:"")),C(v(` Ask any Anyray-connected client about a past chat. ${await wo()}`))},T2=e=>{C(""),C(Z("Next")),C(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||P(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),C(v(` No Chat tab? Configured before this Connect version: run \`${Ot("desktop")}\`.`))},F0=async(e,t={})=>{let n;try{n=E2(e)}catch(o){return D(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(I2),0;C(Z("Migrating Claude Desktop onto Anyray")),C(v("Claude Desktop must be fully quit.")),C("");let r=await R2(n,t);return await O2(n,!r),await _2(n),r?(T2(n),0):(C(""),P("Fix the item above and re-run to finish the migration."),1)};import{spawn as Xj}from"node:child_process";import{homedir as zj}from"node:os";import{join as IR}from"node:path";import{readFile as qj,writeFile as ER,chmod as Qj,stat as eY,unlink as hR}from"node:fs/promises";import{mkdir as D2,readFile as L2,rm as N2,rmdir as $2,writeFile as M2}from"node:fs/promises";import{join as Nc}from"node:path";import{z as ge}from"zod";var fa="required",P2=e=>e==="subscription"?"subscription":"placeholder",W0=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?P2(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}:{}}},cp=(e,t,n)=>{let r=new Set(t.enabled??[]),o=e.managedTools??[],a=o.filter(u=>r.has(u)||n);if(t.defaulted===!0&&e.toolSelection!=="all")return{candidateIds:a,freshIds:[],tombstonedIds:[]};let s=new Set(e.revertedTools??[]),i=e.revertedTools!=null,c=u=>t.tiers?.[u]??fa,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}},U0=(e,t,n)=>{let r=[],o=[],a=[];if(t===void 0||t.defaulted===!0){for(let c of n)jr(c)?a.push({id:c.id,reason:"consent"}):r.push(c.id);return{applyIds:r,revertIds:o,skipped:a}}let s=new Set(e.managedTools??[]),i=new Set(t.enabled??[]);for(let c of n){let{id:l}=c;if(!i.has(l)){s.has(l)?o.push(l):a.push({id:l,reason:"not_enabled"});continue}if(s.has(l)){r.push(l);continue}let d=t.tiers?.[l]??fa;if(d==="optional"){a.push({id:l,reason:"optional"});continue}if(jr(c)){d==="locked"?r.push(l):a.push({id:l,reason:"consent"});continue}r.push(l)}return{applyIds:r,revertIds:o,skipped:a}};var B2=1e4,F2=1,K0=ge.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),W2=ge.object({id:K0,name:ge.string().min(1),version:ge.string().min(1),body:ge.string(),plugin:ge.boolean().optional()}),U2=ge.object({url:ge.string().url(),plugins:ge.array(K0)}),H2=ge.object({version:ge.literal(F2).optional(),skills:ge.array(W2),skillsIncomplete:ge.boolean().optional(),marketplace:U2.optional(),mcp:ge.object({org:ge.object({url:ge.string().url()})}).optional(),updatedAt:ge.string().min(1).optional(),routing:ge.object({origin:ge.string().min(1)}).optional(),team:ge.string().min(1).optional(),lane:ge.enum(["subscription","org"]).optional().catch(void 0),tools:ge.object({enabled:ge.array(ge.string().min(1)),defaulted:ge.literal(!0).optional().catch(void 0),tiers:ge.record(ge.string().min(1),ge.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional(),updates:ge.object({mode:ge.enum(["auto","directed","off"]).catch("directed")}).optional()}),_s=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},Jg=e=>e instanceof _s&&e.kind==="auth",Yg=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",Ts=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",ma=async(e,t,n={})=>{let r=n.timeoutMs??B2,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.`:xt(l);throw new _s("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new _s(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 _s("malformed","team policy fetch failed: the gateway returned a malformed response")}return H2.parse(c)},H0=/^[a-z0-9][a-z0-9-]{0,31}$/,G0=64,Xg=e=>{let t=e.tools;if(!t||t.defaulted===!0)return;let n=t.enabled.filter(o=>H0.test(o)).slice(0,G0).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>H0.test(o)).slice(0,G0).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},G2=e=>e.updates?{mode:e.updates.mode}:void 0,$c=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??fa)==="locked":!1},Ps=async(e,t={})=>{let n=t.loadProfile??$,r=t.saveProfile??de,o=t.targetFromProfile??Je,a=t.adapters??se,s=t.repairTools??en,i=t.recordManaged??Fr,c=await n(),l={...c},d=W0(c,{routingOrigin:e.routing?.origin?cn(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:u,teamUpdated:p,laneUpdated:m}=d;(u||p||m)&&(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 f=cp(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers,defaulted:e.tools?.defaulted},u||p||m),{candidateIds:h,freshIds:w}=f,y=0,g=0,b=0;if(h.length>0||w.length>0){let I=await o(async()=>l);if(I){let E;if(u||p||m){let G=new Set(h);E=[];for(let X of a)if(G.has(X.id))try{(await X.detect()).installed&&E.push(X)}catch{}}else E=await bs(h,I.target.origin,a);let O=new Set(w),K=[];for(let G of a)if(O.has(G.id))try{(await G.detect()).installed&&K.push(G)}catch{}if(y=E.length+K.length,y>0){let G=await s([...E,...K],I.target);g=G.filter(la).length;let X=G.filter(re=>O.has(re.id));if(b=X.filter(la).length,X.length>0)try{await i(X,!1)}catch{}}}}let k=Xg(e),A=G2(e),x=await n(),_=JSON.stringify(k??null)!==JSON.stringify(x.fleetToolPolicy??null),S=JSON.stringify(A??null)!==JSON.stringify(x.fleetUpdatePolicy??null);if(_||S){let{fleetToolPolicy:I,fleetUpdatePolicy:E,...O}=x;await r({...O,...k?{fleetToolPolicy:k}:{},...A?{fleetUpdatePolicy:A}:{}})}return{routingUpdated:u,teamUpdated:p,laneUpdated:m,toolsRequested:y,toolsApplied:g,toolsEnrolled:b,toolsTombstoned:f.tombstonedIds,profileUpdated:u||p||m,updatesMode:A?.mode??"auto",updatesUpdated:S}},K2=(e,t=se,n=new Set)=>{let r=e.managedTools,o=new Map;for(let a of t){if(r&&!r.includes(a.id))continue;let s=a.skillsDir?.();if(!s)continue;let i=!n.has(a.id),c=o.get(s);o.set(s,{dir:s,includePluginSkills:(c?.includePluginSkills??!1)||i})}return[...o.values()]},V2=e=>e.map(t=>typeof t=="string"?{dir:t,includePluginSkills:!0}:t),Zg=async(e,t)=>{await N2(Nc(e,t,"SKILL.md"),{force:!0}),await $2(Nc(e,t)).catch(()=>{})},j2=e=>{let t=e.body.replace(/\r\n?/g,`
|
|
571
571
|
`),n=t.startsWith(`---
|
|
572
572
|
`)?t.indexOf(`
|
|
573
573
|
---`,4):-1,r=n+4,o=n>=0&&(r>=t.length||t[r]===`
|
|
@@ -578,7 +578,7 @@ ${u.join(`
|
|
|
578
578
|
---
|
|
579
579
|
${s}`)},lp=e=>/^[ \t]*/.exec(e)?.[0]??"",Y2=/^([ \t]*)(?:"name"|'name'|name)[ \t]*:(.*)$/i,Z2=/^([ \t]*)(?:"description"|'description'|description)[ \t]*:(.*)$/i,J2=async(e,t,n)=>{for(let r of e)try{if(await L2(Nc(r,t,"SKILL.md"),"utf-8")!==n)return!1}catch{return!1}return!0},X2=async(e,t,n,r={})=>{let o=V2(t),a=[],s={},i=new Set,c=0,l=0;for(let p of e.skills){if(!Yg(p.id))continue;i.add(p.id),s[p.id]=p.version;let m=j2(p),f=o.filter(y=>y.includePluginSkills||!p.plugin).map(y=>y.dir);for(let y of o)f.includes(y.dir)||await Zg(y.dir,p.id);if(n[p.id]===p.version&&await J2(f,p.id,m)){l+=1,a.push({id:p.id,name:p.name,version:p.version,written:!1,files:[]});continue}let w=[];for(let y of f){let g=Nc(y,p.id),b=Nc(g,"SKILL.md");await D2(g,{recursive:!0}),await M2(b,m,"utf-8"),w.push(b)}c+=1,a.push({id:p.id,name:p.name,version:p.version,written:!0,files:w})}let d=[];for(let[p,m]of Object.entries(n))if(!(i.has(p)||!Yg(p))){if(e.skillsIncomplete){s[p]=m;continue}for(let f of o)await Zg(f.dir,p);d.push(p)}let u=[];for(let p of r.staleDirs??[])if(!o.some(m=>m.dir===p)){for(let m of new Set([...i,...Object.keys(n)]))Yg(m)&&await Zg(p,m);u.push(p)}return{results:a,changed:c,unchanged:l,removed:d,cleanedDirs:u,versions:s,updatedAt:e.updatedAt}},z2=e=>e.endsWith(`
|
|
580
580
|
`)?e:`${e}
|
|
581
|
-
`,q2=async(e,t,n)=>{let r=new Set,o=!1;for(let a of n){if(!a.syncOrgMarketplace||t&&!t.includes(a.id))continue;let s=await a.syncOrgMarketplace(e).catch(()=>({changed:!1,handlesPluginSkills:!1}));s.changed&&(o=!0),s.handlesPluginSkills&&r.add(a.id)}return{handledBy:r,changed:o}},Q2=(e,t)=>{let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>e[r]===t[r])},zg=async(e,t={})=>{let n=t.loadProfile??$,r=V0(t,n),o=t.adapters??se,a=await n(),s=await q2(e.marketplace,a.managedTools,o),i=K2(a,o,s.handledBy),c=i.map(m=>m.dir),l=a.syncedSkills??{},d=a.syncedSkillDirs??[],u=d.filter(m=>!c.includes(m));if(c.length===0&&u.length===0)return{summary:{results:[],changed:0,unchanged:0,removed:[],cleanedDirs:[],versions:l,updatedAt:e.updatedAt},dirs:c,marketplaceChanged:s.changed};let p=await X2(c.length===0?{...e,skills:[]}:e,i,l,{staleDirs:u});if(p.changed>0||p.removed.length>0||p.cleanedDirs.length>0||!Q2(l,p.versions)||!ej(d,c)){let m=p.updatedAt??new Date().toISOString();try{await r(f=>({next:{...f,syncedSkills:p.versions,syncedSkillDirs:c,syncedAt:m},result:void 0}))}catch{}}return{summary:p,dirs:c,marketplaceChanged:s.changed}},V0=(e,t)=>{if(e.mutateProfile)return e.mutateProfile;let n=e.saveProfile;return n?async r=>{let{next:o,result:a}=r(await t());return o&&await n(o),a}:ul},ej=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),qg=async(e,t={})=>{let n=t.loadProfile??$,r=await n(),o=t.adapters??se,a=e.mcp?.org.url&&r.clientKey?{url:e.mcp.org.url,clientKey:r.clientKey}:void 0,s=a!==void 0,i=[],c=IC(e.mcp?.org.url??e.routing?.origin??r.gateway??"");if(!c)return{changed:i,served:s};let l=r.orgMcpOrigins??[],d=[c,...l.filter(m=>m!==c)],u=r.managedTools??await nj(o,r.gateway),p=!1;for(let m of o){if(!m.syncOrgMcp)continue;let f=u.includes(m.id)&&a!==void 0;(await m.syncOrgMcp({ownerOrigins:d,...f?{entry:a}:{}}).catch(()=>({changed:!1}))).changed&&(i.push(m.id),f&&(p=!0))}if(p&&!l.includes(c))try{await V0(t,n)(m=>{let f=m.orgMcpOrigins??[];return f.includes(c)?{result:void 0}:{next:{...m,orgMcpOrigins:[c,...f.filter(h=>h!==c)].slice(0,tj)},result:void 0}})}catch{}return{changed:i,served:s}},tj=8,dp=async(e,t={})=>{if(!e.gateway||!e.clientKey)return;let n=await(t.fetchTeamPolicy??fa)(e.gateway,e.clientKey),r=await(t.syncSkills??zg)(n).catch(()=>{}),o=await(t.syncOrgMcp??qg)(n).catch(()=>{});return{policy:n,skills:r,mcp:o}},nj=async(e,t)=>{if(!t)return[];let n=[];for(let r of e){if(!r.syncOrgMcp||!r.pointsAt)continue;await r.pointsAt(t).catch(()=>!1)&&n.push(r.id)}return n};import{randomBytes as rj}from"node:crypto";var oj=1e4,aj="machine:",j0=e=>e.startsWith(aj),sj="cert-renew",ij=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)},Y0=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Cn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:rj(16).toString("hex"),purpose:sj},c;try{c=await(n.signer??qn)(ua(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),oj),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 m=(await u.json().catch(()=>null))?.cert;return ij(m)?{ok:!0,cert:m}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var Qg=async(e,t=e.origin,n=se)=>{let r=0,o=0,a=!0;for(let s of n)try{if(!s.pointsAt||!await s.pointsAt(t)||await s.usesDynamicCredential?.(t))continue;r+=1,(await s.apply(e,{dryRun:!1})).status==="configured"?o+=1:a=!1}catch{a=!1}return{matched:r,rewritten:o,complete:a}},ew=async(e,t=e.origin,n=se)=>(await Qg(e,t,n)).complete;var cj=["claude","codex","cursor","opencode"],lj=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],dj=new Set(["missing_key","key_expired"]);var uj=600*1e3,pj=600*1e3,Z0=1440*60*1e3,fj=1440*60*1e3,mj=10080*60*1e3,hj=3600*1e3,yj=720*60*1e3,gj=e=>Math.min(yj,hj*2**Math.max(0,e-1)),Mc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ps=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,J0=e=>typeof e=="string"&&lj.includes(e),Qn=e=>{if(!Mc(e))return{};let t={};if(Ps(e.watchSince)&&(t.watchSince=e.watchSince),Mc(e.invoked)){let n={};for(let r of cj){let o=e.invoked[r];Ps(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return Mc(e.authFailure)&&Ps(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...J0(e.authFailure.code)?{code:e.authFailure.code}:{}}),Mc(e.repair)&&Ps(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,...Ps(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},up=e=>{try{let n=JSON.parse(e);if(Mc(n)&&J0(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"},tw=e=>e!==void 0&&dj.has(e),nw=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=uj},X0=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),rw=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=pj},z0=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),q0=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,Q0=(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},eR=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>Z0||!tw(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<gj(r.failures??1))},pp=e=>{let t=Object.values(e?.invoked??{}).filter(Ps);return t.length>0?Math.max(...t):null},ow=(e,t)=>{if(pp(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=mj},tR=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=fj)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=Z0)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var aw="x-anyray-retrieve-probe",fp=8e3,wj=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",nR=(e,t)=>{let n=dn(e);return t?.probe&&(n[aw]="1"),n},Ds=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(),fp);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:nR(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=wj(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)}},mp=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(),fp);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:nR(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 bj=5e3,Cj=2048,Aj=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}"`))},Ls=async(e={})=>{let t=e.readTarget??ut,n=e.fetch??fetch,r=e.timeoutMs??bj,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=dn(o);i["content-type"]="application/json",i[aw]="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,Cj);if(!Aj(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let p=up(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)}},sw=(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 Sj}from"node:crypto";import{execSync as iw}from"node:child_process";import{hostname as kj}from"node:os";var vj=e=>{try{if(e==="darwin"){let t=iw("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=iw('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 iw("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},hp=(e={platform:process.platform,read:()=>vj(process.platform),hostname:kj})=>e.read().trim()||e.hostname().trim();var nn=(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??(()=>hp());try{return r().trim().toLowerCase()}catch{return""}}return""};var Ij=500,rR=2e3,Ej=2e3,xj=250,oR=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),Ij);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)}},Rj=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},Oj=e=>new Promise(t=>setTimeout(t,e)),_j=async(e,t,n=Oj)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),rR),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=Rj(i)??xj,s>Ej))return!1}finally{clearTimeout(a)}await n(s)}},Tj=async(e,t={})=>{try{let r=(await(t.loadProfile??$)()).enrolledCert,o=await(t.loadDevKey??Ye)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:Sj(16).toString("hex"),events:e},i;try{i=await(t.signer??qn)(ua(s),o)}catch{return!1}return await(t.post??_j)(`${t.origin??Cn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},Pj=async(e,t,n={})=>{try{let o=(await(n.loadProfile??$)()).enrolledCert,a=await(n.loadDevKey??Ye)();if(!o||!a)return;await(n.verify??An)(e,o,a,{timeoutMs:rR,machineUuid:(n.machineUuid??nn)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},aR=async(e,t)=>{if(e.length!==0)try{let n=await ut(),r=n&&await oR(n.origin,dn(n),e,t);if(n&&await Pj(n.origin,e),r)return;await Tj(e)}catch{}},cw=async(e,t,n={readTarget:()=>ut("profile"),post:oR})=>{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 ha=["hook_registration","mcp_registration","hook_binary","beacon_target"];var iR=128,cR=300*1e3,lR=8,Dj=["repaired","repair_failed","flapping","pending"],Lj=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],dR=["rebroke_same_day","repeat_days"],uR=new Set(se.map(e=>e.id)),ma=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fc=(e,t)=>typeof e=="string"&&t.some(n=>n===e),pR=e=>Fc(e,ha),yp=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},Co=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Bc=e=>{if(!(!Array.isArray(e)||!e.every(pR)))return _r(e)},Nj=e=>{if(!ma(e))return;let t=Bc(e.checks);if(!(!Co(e.since)||!Fc(e.reason,dR)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},$j=e=>{if(!ma(e))return;let t={};yp(e.day)&&(t.day=e.day),Co(e.attempts)&&(t.attempts=e.attempts);let n=Bc(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=Bc(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=Bc(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=Bc(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),yp(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Co(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),ma(e.lastRepaired)){let i={};for(let c of ha){let l=e.lastRepaired[c];Co(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=Nj(e.flapping);return s&&(t.flapping=s),t},Mj=e=>{if(!ma(e)||!yp(e.day)||!Co(e.sequence)||e.sequence===0||typeof e.tool!="string"||!uR.has(e.tool)||!pR(e.checkId)||!Fc(e.status,Dj)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!Fc(e.errorClass,Lj))return;t=e.errorClass}else if(e.status==="flapping"){if(!Fc(e.errorClass,dR))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,...Co(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},sR=e=>{if(!ma(e))return{};let t={};if(ma(e.adapters)){let n={};for(let r of uR){let o=$j(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(Mj).filter(n=>n!==void 0).slice(-iR)),Co(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),ma(e.report)&&yp(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Co(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{},...typeof e.report.version=="string"&&e.report.version?{version:e.report.version}:{},...Array.isArray(e.report.deliveredBy)?{deliveredBy:e.report.deliveredBy.filter(n=>typeof n=="string"&&n!=="").slice(-lR)}:{}}),t},Bj=e=>new Date(e).toISOString().slice(0,10),Fj=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,_r=e=>[...new Set(e)],gp=(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}:{}}},Wc=(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(-iR),nextSequence:r}},Wj=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),Uj=async e=>await Je(async()=>e)??null,Hj=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=gp(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)},fR=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:Fj(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:_r([...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:_r([...i?.checks??[],...t])}}:{}},slowFlap:a}},Gj=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=gp(d,n),p=u.awaiting??[],m=a.get(l);if(p.length===0||t.has(l)||!m){c[l]=u;continue}let f=p.filter(g=>m.checks[g]==="owned"),h=p.filter(g=>{let b=m.checks[g];return b==="missing"||b==="foreign"}),w=p.filter(g=>{let b=m.checks[g];return b===void 0||b==="unreadable"}),y=fR(u,f,n,r);c[l]={...y.adapter,awaiting:w.length>0?w:void 0},i=Wc(i,n,[...f.map(g=>({tool:l,checkId:g,status:"repaired"})),...h.map(g=>({tool:l,checkId:g,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?f.map(g=>({tool:l,checkId:g,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},Kj=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=gp(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)),m=p.filter(y=>u.includes(y)),f=l.attempts??0;if(f>=2||p.length===0&&!n){let y=m.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(y.length===0)return{result:void 0};let g=l.flapping;return c[e]={...l,brokenReportedChecks:_r([...l.brokenReportedChecks??[],...y]),flapping:{since:g?.since??a,reason:"rebroke_same_day",checks:_r([...g?.checks??[],...y])}},{next:Wc({...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:f+1,attemptedChecks:_r([...d,...p]),confirmedChecks:u.filter(y=>!p.includes(y)),brokenReportedChecks:_r([...l.brokenReportedChecks??[],...m]),...m.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:_r([...h?.checks??[],...m])}}:{}},{next:Wc({...i,adapters:c},o,m.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:p,fastFlaps:m}}},void 0),Vj=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=gp(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:_r([...l.awaiting??[],...t])},{next:Wc({...i,adapters:c},o,t.map(f=>({tool:e,checkId:f,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(f=>r[f]==="owned"):[],u=n.status==="configured"&&r?t.filter(f=>{let h=r[f];return h==="missing"||h==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],p=fR(l,d,o,a);c[e]=p.adapter;let m=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"apply_unconfirmed";return{next:Wc({...i,adapters:c},o,[...d.map(f=>({tool:e,checkId:f,status:"repaired"})),...u.map(f=>({tool:e,checkId:f,status:"repair_failed",errorClass:m})),...p.slowFlap?d.map(f=>({tool:e,checkId:f,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},jj=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>=cR));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??cw)(o.map(Wj),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)},Yj=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 m=r.adapters?.[u.id];for(let f of ha){let h=p[f];if(!h||h==="unreadable")continue;let w,y;m?.awaiting?.includes(f)&&c.has(u.id)?w="pending":h==="missing"&&m?.flapping?.checks.includes(f)?(w="flapping",y=m.flapping.reason):w=h==="owned"?"ok":h,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:f,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&&rt(e)&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??_n)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??Tn)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=tR(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},Zj=async(e,t,n,r,o,a,s)=>{if(!await s.claimState(u=>{let p=u.report?.day===r?u.report:void 0;return p?.deliveredBy?.includes(a)?{result:!1}:p?.version===a&&p.attemptedAt!==void 0&&p.attemptedAt<=o&&o-p.attemptedAt<cR?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o,version:a,...p?.deliveredBy?{deliveredBy:p.deliveredBy}:{}}},result:!0}},!1))return;let c=await s.readState().catch(()=>({})),l=await Yj(e,t,n,c,o,s);await(s.report??cw)(l,a).catch(()=>!1)&&await s.claimState(u=>u.report?.day===r?{next:{...u,report:{day:r,delivered:!0,version:a,deliveredBy:[...(u.report.deliveredBy??[]).filter(p=>p!==a),a].slice(-lR)}},result:void 0}:{result:void 0},void 0)},mR=async(e,t,n)=>{let r=n.now??Date.now,o=Bj(r()),a=e.managedTools??[],s={...n,readState:async()=>sR(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(sR(l)),c)};try{let i=await(s.findIntegrations??qy)(a);await Hj(i,o,s);let c=await(s.listPending??Pn)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await Gj(i,l,o,r(),s);let d=await(s.resolveTarget??Uj)(e),u=d?await(s.findDrifted??ws)(a,d.target.origin):[],p=new Set(u.map(y=>y.id)),m=new Map(i.map(y=>[y.adapter.id,y]));for(let y of u)m.has(y.id)||m.set(y.id,{adapter:y,checks:{}});let f=!1,h=(s.runtimeDurable??te)();if(d)for(let{adapter:y,checks:g}of m.values()){let b=h?ha.filter(x=>g[x]==="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(ha.map(x=>[x,"unreadable"]))}let A=b.filter(x=>k[x]==="missing"),E=p.has(y.id);if(E&&y.pointsAt&&(E=!await y.pointsAt(d.target.origin).catch(()=>!0)),A.length===0&&!E)continue;let O=await Kj(y.id,A,E,l.has(y.id),o,r(),s);if(!O)continue;let[S]=await(s.repair??en)([y],d.target);if(!S)continue;f=!0;let I;S.status==="configured"&&y.integrationStatus&&(I=await y.integrationStatus().catch(()=>{})),await Vj(y.id,O.checks,S,I,o,r(),s)}await jj(o,r(),t,s),i=await(s.findIntegrations??qy)(a);let w=await(s.listPending??Pn)().catch(()=>[]);return await Zj(e,i,w,o,r(),t,s),f}catch{return!1}};var tY=14,nY=.35,rY=900*1e3,yR=360*60*1e3,oY=.2,aY=1800*1e3,gR=3600*1e3,sY=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),iY=300*1e3,cY=30*1e3,lY=900*1e3,dY=(e=0)=>Math.min(lY,cY*2**Math.max(0,e)),wR=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}},bR=1440*60*1e3,uY=300*1e3,pY=.25,fY=.5,CR=3600*1e3,mY=720*60*60*1e3,hY=360*60*1e3,yY=1440*60*1e3,gY=()=>IR(zj(),".anyray"),lw=()=>IR(gY(),"refresh-state.json"),dw=e=>process.env?.[e],xR=()=>dw("ANYRAY_REFRESH_DISABLE")==="true",uw=()=>{let e=dw("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:tY)*yY},pw=e=>{let t=uw(),n=e?li(e):void 0;if(!n)return t;let r=Math.max(rY,Math.round(n*nY));return Math.min(t,r)},wY=e=>{let t=dw("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(yR,Math.max(aY,Math.round(e*oY))):yR},Bt=async()=>{try{let e=await qj(lw(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},bp=async e=>{try{let t=lw(),n=`${t}.${process.pid}.tmp`;await ER(n,JSON.stringify(e),{mode:384}),await Ae(n,t),await Qj(t,384).catch(()=>{})}catch{}},bY=3e4,CY=()=>`${lw()}.lock`,AR=async e=>{try{return await ER(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},bt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Bt,a=n.writeState??bp,s=CY(),i=!1;try{if(i=await AR(s),!i){if(await eY(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<bY)return t;await hR(s).catch(()=>{}),i=await AR(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await hR(s).catch(()=>{})}},wp=async(e,t={})=>{await bt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Ns=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 bt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},ya=async(e={})=>{let t=e.now??Date.now;await bt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},AY=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(mY,Math.max(CR,Math.round(o*fY))):CR},RR=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,fw=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??de,a=n.loadProfile??$,s=n.loadDevKey??Ye,i=n.renew??Y0,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(j0(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()>AY(e))return{outcome:"not-due",profile:e};if(!await bt(w=>r()-(w.lastCertRenewAt??0)<hY?{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 RR(p,c.sig,t,s))return{outcome:"superseded",profile:p};let m=u.cert.payload.expiresAt,f=Date.parse(m)-r(),h={...p,enrolledCert:u.cert,enrolledCertExpiry:m,...Number.isFinite(f)&&f>0?{enrolledCertLifetimeMs:f}:{}};return await o(h),{outcome:"renewed",profile:h}},kR=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*pY):bR,r=Math.min(bR,n);return Math.min(r,uY*2**Math.max(0,e-1))},kY=()=>{let{command:e,args:t}=Jr(Kr);return{exe:e,args:t}},Ao=async(e={})=>{if(xR())return;let t=e.now??Date.now,n=e.readState??Bt,r=e.writeState??bp,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=kY();Xj(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await bt(s=>t()-(s.lastSpawnAt??0)<wY(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},vY=ew,SY=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Je(async()=>e);if(!r)return!1;let o=await ws(n,r.target.origin),a=t?HE(o):o;return a.length===0?!1:(await en(a,r.target),!0)}catch{return!1}},IY=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=se.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}},EY=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Bt,a=t.writeState??bp;return mR(e,Ne,{now:r,deadWatcherObserved:n,readHookLane:()=>Cp({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>bt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Cp=async(e={})=>{let n=await(e.readState??Bt)().catch(()=>({}));return Qn(n.hookLane)},OR=async(e,t={})=>{try{let n=t.now??Date.now,r=await Cp(t);if(!nw(r,e,n()))return;await bt(o=>{let a=Qn(o.hookLane);return nw(a,e,n())?{next:{...o,hookLane:X0(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},_R=async(e,t={})=>{try{let n=t.now??Date.now,r=await Cp(t);if(!rw(r,n()))return;await bt(o=>{let a=Qn(o.hookLane);return rw(a,n())?{next:{...o,hookLane:z0(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},xY=async(e={})=>{try{let t=e.now??Date.now;if((await Cp(e)).watchSince!==void 0)return;await bt(n=>{let r=Qn(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:q0(r,t())},result:void 0}},void 0,e)}catch{}},vR=async(e,t={})=>{try{let n=t.now??Date.now;await bt(r=>{let o=Qn(r.hookLane),a=Q0(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},TR=async(e={})=>{try{if((await(e.readState??Bt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>bt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??tC)())return await r()?"stamped":"skipped";let o=await(e.load??$)(),s=await(e.findTools??la)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Je(async()=>o);return!i||!await r()?"skipped":(await(e.repair??en)(s,i.target),"repathed")}catch{return"skipped"}},PR=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Bt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>bt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??$)(),i=await(e.findTools??la)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Je(async()=>a);return!c||!await o()?"skipped":(await(e.repair??en)(i,c.target)).some(d=>d.status==="failed")?(await bt(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"}},RY=async e=>{try{let t=await dp(e);if(!t)return!1;let{policy:n,skills:r,mcp:o}=t,a=r!==void 0&&(r.summary.changed>0||r.summary.removed.length>0),s=o!==void 0&&o.changed.length>0,i=await Ts(n);return i.profileUpdated||i.toolsApplied>0||a||s}catch{return!1}},SR=async(e,t,n)=>{let o=await(t.reconcilePolicy??RY)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>SY(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},rn=async(e={})=>{if(xR())return"disabled";let t=e.now??Date.now,n=e.loadProfile??$,r=e.saveProfile??de,o=e.loadDevKey??Ye,a=e.readState??Bt,s=e.writeState??bp,i=e.remint??An,c=e.heartbeat??f0,l=e.detectSeat??Wn,d=e.rewriteTools??vY,u=e.rewriteHookLaneTools??Qg,p=e.probeHookLane??Ls,m=e.classifyBeacon??Sl,f=e.force===!0,h=!1,w=!1,y=!1,g=!1;e.hookLaneRepair===!0&&(f=!0,g=!0);let b=async A=>{if(!g){A==="repaired"&&await vR("none",{now:t,readState:a,writeState:s});return}let E=A;if(A==="repaired"){let O=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));E=O.verdict==="live"?"repaired":O.verdict==="dark"?"repair_failed":"unverified"}await vR(E,{now:t,readState:a,writeState:s})},k=async()=>{if(!e.runAmbientSelfcheck||w||!h)return!1;w=!0;let A;try{A=await n()}catch{return!1}return(e.ambientSelfcheck??(O=>EY(O,{now:t,readState:a,writeState:s},y)))(A).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await Pn().then(W=>W.some(Q=>!Tn(Q.watcherPid))).catch(()=>!1),await xY({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??RA)();let A=await n();if(h=!0,!A.gateway||!A.enrolledCert)return"not-enrolled";let E=A.gateway,O=A.enrolledCertExpiry?Date.parse(A.enrolledCertExpiry):Date.parse(A.enrolledCert.payload.expiresAt);if(!Number.isFinite(O)||O<=t())return"cert-expired";let S=await o();if(!S)return"not-enrolled";let I=(e.resolveMachineUuid??nn)()||void 0,x=await fw(A,S,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});A=x.profile;let _=x.outcome==="renewed",K=A.enrolledCert;if(!K)return"not-enrolled";let G=Date.parse(A.clientKeyExpiresAt??""),X=Number.isFinite(G)?G-t():0,re=await a(),ke=!A.clientKey||X<=pw(A);if(!f&&eR(Qn(re.hookLane),t())&&await m().catch(()=>"unreadable")!=="foreign"&&(f=!0,g=!0),A.clientKey&&(f||ke)){let W=await bt(Q=>{let ye=t()-(Q.lastAttemptAt??0);return ye<gR?{result:"throttled"}:Q.failureCount&&ye<kR(Q.failureCount,Q.keyTtlMs)?{result:"backoff"}:{next:{...Q,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(W!=="ok")return W;try{let Q=await c(E,A.clientKey,K,S,{machineUuid:I}),ye=await n().catch(()=>A);return ye.clientKey!==A.clientKey||ye.enrolledCert?.sig!==K.sig?"failed":(await r({...ye,clientKeyExpiresAt:Q.expiresAt}),await wp(({lastError:we,...Y})=>({...Y,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:li(A)??Y.keyTtlMs}),{now:t,readState:a,writeState:s}),g?await b(await IY(A,E,A.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Q){let ye=wR(Q);return await wp(we=>({...we,lastAttemptAt:t(),failureCount:(we.failureCount??0)+1,lastError:{name:Q instanceof Error?Q.name:"Error",...ye!==void 0?{code:ye}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Q instanceof xs&&Q.policyCode==="managed_device_required"&&console.error(Q.message),Q instanceof xs?Q.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!f&&A.clientKey&&!ke){let W=await SR(A,e,n),Q=await k();return W||Q?"repaired":_?"cert-renewed":"not-due"}let fe=await bt(W=>{let Q=t()-(W.lastAttemptAt??0);if(f)return Q<dY(W.failureCount)?{result:"throttled"}:{next:{...W,lastAttemptAt:t()},result:"ok"};let ye=W.lastError?.code!==void 0&&sY.has(W.lastError.code)?iY:gR;return Q<ye?{result:"throttled"}:W.failureCount&&Q<kR(W.failureCount,W.keyTtlMs)?{result:"backoff"}:{next:{...W,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(fe!=="ok")return fe;try{let W=await i(E,K,S,{machineUuid:I}),Q=await l().catch(()=>{}),ye=xe({origin:E,clientKey:W.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:Q,user:A.name,team:A.team});if(await d(ye,ye.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let Y=await n().catch(()=>A),Ee=null;Y.enrolledCert&&await RR(Y,K.sig,S,o)&&(Ee={...Y,clientKey:W.key,clientKeyExpiresAt:W.expiresAt??Y.clientKeyExpiresAt},await r(Ee));let an=W.expiresAt?Date.parse(W.expiresAt):NaN,Pr=li(A)??(Number.isFinite(an)&&an-t()>0?an-t():void 0);return await wp(({lastError:Dr,...Lr})=>({...Lr,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Pr??Lr.keyTtlMs}),{now:t,readState:a,writeState:s}),Ee&&await SR(Ee,e,n),await b(Ee?"repaired":"repair_failed"),await k(),"refreshed"}catch(W){let Q=wR(W);return await wp(ye=>({...ye,lastAttemptAt:t(),failureCount:(ye.failureCount??0)+1,lastError:{name:W instanceof Error?W.name:"Error",...Q!==void 0?{code:Q}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),W instanceof it&&W.policyCode==="managed_device_required"&&console.error(W.message),W instanceof it?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var OY=`anyray-connect print-key [--json | --passthrough-headers]
|
|
581
|
+
`,q2=async(e,t,n)=>{let r=new Set,o=!1;for(let a of n){if(!a.syncOrgMarketplace||t&&!t.includes(a.id))continue;let s=await a.syncOrgMarketplace(e).catch(()=>({changed:!1,handlesPluginSkills:!1}));s.changed&&(o=!0),s.handlesPluginSkills&&r.add(a.id)}return{handledBy:r,changed:o}},Q2=(e,t)=>{let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>e[r]===t[r])},zg=async(e,t={})=>{let n=t.loadProfile??$,r=V0(t,n),o=t.adapters??se,a=await n(),s=await q2(e.marketplace,a.managedTools,o),i=K2(a,o,s.handledBy),c=i.map(m=>m.dir),l=a.syncedSkills??{},d=a.syncedSkillDirs??[],u=d.filter(m=>!c.includes(m));if(c.length===0&&u.length===0)return{summary:{results:[],changed:0,unchanged:0,removed:[],cleanedDirs:[],versions:l,updatedAt:e.updatedAt},dirs:c,marketplaceChanged:s.changed};let p=await X2(c.length===0?{...e,skills:[]}:e,i,l,{staleDirs:u});if(p.changed>0||p.removed.length>0||p.cleanedDirs.length>0||!Q2(l,p.versions)||!ej(d,c)){let m=p.updatedAt??new Date().toISOString();try{await r(f=>({next:{...f,syncedSkills:p.versions,syncedSkillDirs:c,syncedAt:m},result:void 0}))}catch{}}return{summary:p,dirs:c,marketplaceChanged:s.changed}},V0=(e,t)=>{if(e.mutateProfile)return e.mutateProfile;let n=e.saveProfile;return n?async r=>{let{next:o,result:a}=r(await t());return o&&await n(o),a}:ul},ej=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),qg=async(e,t={})=>{let n=t.loadProfile??$,r=await n(),o=t.adapters??se,a=e.mcp?.org.url&&r.clientKey?{url:e.mcp.org.url,clientKey:r.clientKey}:void 0,s=a!==void 0,i=[],c=IC(e.mcp?.org.url??e.routing?.origin??r.gateway??"");if(!c)return{changed:i,served:s};let l=r.orgMcpOrigins??[],d=[c,...l.filter(m=>m!==c)],u=r.managedTools??await nj(o,r.gateway),p=!1;for(let m of o){if(!m.syncOrgMcp)continue;let f=u.includes(m.id)&&a!==void 0;(await m.syncOrgMcp({ownerOrigins:d,...f?{entry:a}:{}}).catch(()=>({changed:!1}))).changed&&(i.push(m.id),f&&(p=!0))}if(p&&!l.includes(c))try{await V0(t,n)(m=>{let f=m.orgMcpOrigins??[];return f.includes(c)?{result:void 0}:{next:{...m,orgMcpOrigins:[c,...f.filter(h=>h!==c)].slice(0,tj)},result:void 0}})}catch{}return{changed:i,served:s}},tj=8,dp=async(e,t={})=>{if(!e.gateway||!e.clientKey)return;let n=await(t.fetchTeamPolicy??ma)(e.gateway,e.clientKey),r=await(t.syncSkills??zg)(n).catch(()=>{}),o=await(t.syncOrgMcp??qg)(n).catch(()=>{});return{policy:n,skills:r,mcp:o}},nj=async(e,t)=>{if(!t)return[];let n=[];for(let r of e){if(!r.syncOrgMcp||!r.pointsAt)continue;await r.pointsAt(t).catch(()=>!1)&&n.push(r.id)}return n};import{randomBytes as rj}from"node:crypto";var oj=1e4,aj="machine:",j0=e=>e.startsWith(aj),sj="cert-renew",ij=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)},Y0=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Cn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:rj(16).toString("hex"),purpose:sj},c;try{c=await(n.signer??qn)(pa(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),oj),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 m=(await u.json().catch(()=>null))?.cert;return ij(m)?{ok:!0,cert:m}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var Qg=async(e,t=e.origin,n=se)=>{let r=0,o=0,a=!0;for(let s of n)try{if(!s.pointsAt||!await s.pointsAt(t)||await s.usesDynamicCredential?.(t))continue;r+=1,(await s.apply(e,{dryRun:!1})).status==="configured"?o+=1:a=!1}catch{a=!1}return{matched:r,rewritten:o,complete:a}},ew=async(e,t=e.origin,n=se)=>(await Qg(e,t,n)).complete;var cj=["claude","codex","cursor","opencode"],lj=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],dj=new Set(["missing_key","key_expired"]);var uj=600*1e3,pj=600*1e3,Z0=1440*60*1e3,fj=1440*60*1e3,mj=10080*60*1e3,hj=3600*1e3,yj=720*60*1e3,gj=e=>Math.min(yj,hj*2**Math.max(0,e-1)),Mc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ds=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,J0=e=>typeof e=="string"&&lj.includes(e),Qn=e=>{if(!Mc(e))return{};let t={};if(Ds(e.watchSince)&&(t.watchSince=e.watchSince),Mc(e.invoked)){let n={};for(let r of cj){let o=e.invoked[r];Ds(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return Mc(e.authFailure)&&Ds(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...J0(e.authFailure.code)?{code:e.authFailure.code}:{}}),Mc(e.repair)&&Ds(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,...Ds(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},up=e=>{try{let n=JSON.parse(e);if(Mc(n)&&J0(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"},tw=e=>e!==void 0&&dj.has(e),nw=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=uj},X0=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),rw=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=pj},z0=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),q0=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,Q0=(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},eR=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>Z0||!tw(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<gj(r.failures??1))},pp=e=>{let t=Object.values(e?.invoked??{}).filter(Ds);return t.length>0?Math.max(...t):null},ow=(e,t)=>{if(pp(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=mj},tR=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=fj)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=Z0)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var aw="x-anyray-retrieve-probe",fp=8e3,wj=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",nR=(e,t)=>{let n=dn(e);return t?.probe&&(n[aw]="1"),n},Ls=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(),fp);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:nR(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=wj(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)}},mp=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(),fp);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:nR(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 bj=5e3,Cj=2048,Aj=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}"`))},Ns=async(e={})=>{let t=e.readTarget??ut,n=e.fetch??fetch,r=e.timeoutMs??bj,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=dn(o);i["content-type"]="application/json",i[aw]="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,Cj);if(!Aj(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let p=up(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)}},sw=(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 Sj}from"node:crypto";import{execSync as iw}from"node:child_process";import{hostname as kj}from"node:os";var vj=e=>{try{if(e==="darwin"){let t=iw("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=iw('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 iw("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},hp=(e={platform:process.platform,read:()=>vj(process.platform),hostname:kj})=>e.read().trim()||e.hostname().trim();var nn=(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??(()=>hp());try{return r().trim().toLowerCase()}catch{return""}}return""};var Ij=500,rR=2e3,Ej=2e3,xj=250,oR=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),Ij);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)}},Rj=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},Oj=e=>new Promise(t=>setTimeout(t,e)),_j=async(e,t,n=Oj)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),rR),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=Rj(i)??xj,s>Ej))return!1}finally{clearTimeout(a)}await n(s)}},Tj=async(e,t={})=>{try{let r=(await(t.loadProfile??$)()).enrolledCert,o=await(t.loadDevKey??Ye)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:Sj(16).toString("hex"),events:e},i;try{i=await(t.signer??qn)(pa(s),o)}catch{return!1}return await(t.post??_j)(`${t.origin??Cn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},Pj=async(e,t,n={})=>{try{let o=(await(n.loadProfile??$)()).enrolledCert,a=await(n.loadDevKey??Ye)();if(!o||!a)return;await(n.verify??An)(e,o,a,{timeoutMs:rR,machineUuid:(n.machineUuid??nn)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},aR=async(e,t)=>{if(e.length!==0)try{let n=await ut(),r=n&&await oR(n.origin,dn(n),e,t);if(n&&await Pj(n.origin,e),r)return;await Tj(e)}catch{}},cw=async(e,t,n={readTarget:()=>ut("profile"),post:oR})=>{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 ya=["hook_registration","mcp_registration","hook_binary","beacon_target"];var iR=128,cR=300*1e3,lR=8,Dj=["repaired","repair_failed","flapping","pending"],Lj=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],dR=["rebroke_same_day","repeat_days"],uR=new Set(se.map(e=>e.id)),ha=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fc=(e,t)=>typeof e=="string"&&t.some(n=>n===e),pR=e=>Fc(e,ya),yp=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},Co=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Bc=e=>{if(!(!Array.isArray(e)||!e.every(pR)))return _r(e)},Nj=e=>{if(!ha(e))return;let t=Bc(e.checks);if(!(!Co(e.since)||!Fc(e.reason,dR)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},$j=e=>{if(!ha(e))return;let t={};yp(e.day)&&(t.day=e.day),Co(e.attempts)&&(t.attempts=e.attempts);let n=Bc(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=Bc(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=Bc(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=Bc(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),yp(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Co(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),ha(e.lastRepaired)){let i={};for(let c of ya){let l=e.lastRepaired[c];Co(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=Nj(e.flapping);return s&&(t.flapping=s),t},Mj=e=>{if(!ha(e)||!yp(e.day)||!Co(e.sequence)||e.sequence===0||typeof e.tool!="string"||!uR.has(e.tool)||!pR(e.checkId)||!Fc(e.status,Dj)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!Fc(e.errorClass,Lj))return;t=e.errorClass}else if(e.status==="flapping"){if(!Fc(e.errorClass,dR))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,...Co(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},sR=e=>{if(!ha(e))return{};let t={};if(ha(e.adapters)){let n={};for(let r of uR){let o=$j(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(Mj).filter(n=>n!==void 0).slice(-iR)),Co(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),ha(e.report)&&yp(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Co(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{},...typeof e.report.version=="string"&&e.report.version?{version:e.report.version}:{},...Array.isArray(e.report.deliveredBy)?{deliveredBy:e.report.deliveredBy.filter(n=>typeof n=="string"&&n!=="").slice(-lR)}:{}}),t},Bj=e=>new Date(e).toISOString().slice(0,10),Fj=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,_r=e=>[...new Set(e)],gp=(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}:{}}},Wc=(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(-iR),nextSequence:r}},Wj=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),Uj=async e=>await Je(async()=>e)??null,Hj=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=gp(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)},fR=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:Fj(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:_r([...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:_r([...i?.checks??[],...t])}}:{}},slowFlap:a}},Gj=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=gp(d,n),p=u.awaiting??[],m=a.get(l);if(p.length===0||t.has(l)||!m){c[l]=u;continue}let f=p.filter(g=>m.checks[g]==="owned"),h=p.filter(g=>{let b=m.checks[g];return b==="missing"||b==="foreign"}),w=p.filter(g=>{let b=m.checks[g];return b===void 0||b==="unreadable"}),y=fR(u,f,n,r);c[l]={...y.adapter,awaiting:w.length>0?w:void 0},i=Wc(i,n,[...f.map(g=>({tool:l,checkId:g,status:"repaired"})),...h.map(g=>({tool:l,checkId:g,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?f.map(g=>({tool:l,checkId:g,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},Kj=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=gp(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)),m=p.filter(y=>u.includes(y)),f=l.attempts??0;if(f>=2||p.length===0&&!n){let y=m.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(y.length===0)return{result:void 0};let g=l.flapping;return c[e]={...l,brokenReportedChecks:_r([...l.brokenReportedChecks??[],...y]),flapping:{since:g?.since??a,reason:"rebroke_same_day",checks:_r([...g?.checks??[],...y])}},{next:Wc({...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:f+1,attemptedChecks:_r([...d,...p]),confirmedChecks:u.filter(y=>!p.includes(y)),brokenReportedChecks:_r([...l.brokenReportedChecks??[],...m]),...m.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:_r([...h?.checks??[],...m])}}:{}},{next:Wc({...i,adapters:c},o,m.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:p,fastFlaps:m}}},void 0),Vj=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=gp(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:_r([...l.awaiting??[],...t])},{next:Wc({...i,adapters:c},o,t.map(f=>({tool:e,checkId:f,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(f=>r[f]==="owned"):[],u=n.status==="configured"&&r?t.filter(f=>{let h=r[f];return h==="missing"||h==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],p=fR(l,d,o,a);c[e]=p.adapter;let m=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"apply_unconfirmed";return{next:Wc({...i,adapters:c},o,[...d.map(f=>({tool:e,checkId:f,status:"repaired"})),...u.map(f=>({tool:e,checkId:f,status:"repair_failed",errorClass:m})),...p.slowFlap?d.map(f=>({tool:e,checkId:f,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},jj=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>=cR));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??cw)(o.map(Wj),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)},Yj=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 m=r.adapters?.[u.id];for(let f of ya){let h=p[f];if(!h||h==="unreadable")continue;let w,y;m?.awaiting?.includes(f)&&c.has(u.id)?w="pending":h==="missing"&&m?.flapping?.checks.includes(f)?(w="flapping",y=m.flapping.reason):w=h==="owned"?"ok":h,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:f,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&&rt(e)&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??_n)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??Tn)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=tR(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},Zj=async(e,t,n,r,o,a,s)=>{if(!await s.claimState(u=>{let p=u.report?.day===r?u.report:void 0;return p?.deliveredBy?.includes(a)?{result:!1}:p?.version===a&&p.attemptedAt!==void 0&&p.attemptedAt<=o&&o-p.attemptedAt<cR?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o,version:a,...p?.deliveredBy?{deliveredBy:p.deliveredBy}:{}}},result:!0}},!1))return;let c=await s.readState().catch(()=>({})),l=await Yj(e,t,n,c,o,s);await(s.report??cw)(l,a).catch(()=>!1)&&await s.claimState(u=>u.report?.day===r?{next:{...u,report:{day:r,delivered:!0,version:a,deliveredBy:[...(u.report.deliveredBy??[]).filter(p=>p!==a),a].slice(-lR)}},result:void 0}:{result:void 0},void 0)},mR=async(e,t,n)=>{let r=n.now??Date.now,o=Bj(r()),a=e.managedTools??[],s={...n,readState:async()=>sR(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(sR(l)),c)};try{let i=await(s.findIntegrations??qy)(a);await Hj(i,o,s);let c=await(s.listPending??Pn)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await Gj(i,l,o,r(),s);let d=await(s.resolveTarget??Uj)(e),u=d?await(s.findDrifted??bs)(a,d.target.origin):[],p=new Set(u.map(y=>y.id)),m=new Map(i.map(y=>[y.adapter.id,y]));for(let y of u)m.has(y.id)||m.set(y.id,{adapter:y,checks:{}});let f=!1,h=(s.runtimeDurable??te)();if(d)for(let{adapter:y,checks:g}of m.values()){let b=h?ya.filter(E=>g[E]==="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(ya.map(E=>[E,"unreadable"]))}let A=b.filter(E=>k[E]==="missing"),x=p.has(y.id);if(x&&y.pointsAt&&(x=!await y.pointsAt(d.target.origin).catch(()=>!0)),A.length===0&&!x)continue;let _=await Kj(y.id,A,x,l.has(y.id),o,r(),s);if(!_)continue;let[S]=await(s.repair??en)([y],d.target);if(!S)continue;f=!0;let I;S.status==="configured"&&y.integrationStatus&&(I=await y.integrationStatus().catch(()=>{})),await Vj(y.id,_.checks,S,I,o,r(),s)}await jj(o,r(),t,s),i=await(s.findIntegrations??qy)(a);let w=await(s.listPending??Pn)().catch(()=>[]);return await Zj(e,i,w,o,r(),t,s),f}catch{return!1}};var tY=14,nY=.35,rY=900*1e3,yR=360*60*1e3,oY=.2,aY=1800*1e3,gR=3600*1e3,sY=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),iY=300*1e3,cY=30*1e3,lY=900*1e3,dY=(e=0)=>Math.min(lY,cY*2**Math.max(0,e)),wR=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}},bR=1440*60*1e3,uY=300*1e3,pY=.25,fY=.5,CR=3600*1e3,mY=720*60*60*1e3,hY=360*60*1e3,yY=1440*60*1e3,gY=()=>IR(zj(),".anyray"),lw=()=>IR(gY(),"refresh-state.json"),dw=e=>process.env?.[e],xR=()=>dw("ANYRAY_REFRESH_DISABLE")==="true",uw=()=>{let e=dw("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:tY)*yY},pw=e=>{let t=uw(),n=e?li(e):void 0;if(!n)return t;let r=Math.max(rY,Math.round(n*nY));return Math.min(t,r)},wY=e=>{let t=dw("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(yR,Math.max(aY,Math.round(e*oY))):yR},Bt=async()=>{try{let e=await qj(lw(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},bp=async e=>{try{let t=lw(),n=`${t}.${process.pid}.tmp`;await ER(n,JSON.stringify(e),{mode:384}),await Ae(n,t),await Qj(t,384).catch(()=>{})}catch{}},bY=3e4,CY=()=>`${lw()}.lock`,AR=async e=>{try{return await ER(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},bt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Bt,a=n.writeState??bp,s=CY(),i=!1;try{if(i=await AR(s),!i){if(await eY(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<bY)return t;await hR(s).catch(()=>{}),i=await AR(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await hR(s).catch(()=>{})}},wp=async(e,t={})=>{await bt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},$s=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 bt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},ga=async(e={})=>{let t=e.now??Date.now;await bt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},AY=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(mY,Math.max(CR,Math.round(o*fY))):CR},RR=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,fw=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??de,a=n.loadProfile??$,s=n.loadDevKey??Ye,i=n.renew??Y0,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(j0(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()>AY(e))return{outcome:"not-due",profile:e};if(!await bt(w=>r()-(w.lastCertRenewAt??0)<hY?{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 RR(p,c.sig,t,s))return{outcome:"superseded",profile:p};let m=u.cert.payload.expiresAt,f=Date.parse(m)-r(),h={...p,enrolledCert:u.cert,enrolledCertExpiry:m,...Number.isFinite(f)&&f>0?{enrolledCertLifetimeMs:f}:{}};return await o(h),{outcome:"renewed",profile:h}},kR=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*pY):bR,r=Math.min(bR,n);return Math.min(r,uY*2**Math.max(0,e-1))},kY=()=>{let{command:e,args:t}=Jr(Kr);return{exe:e,args:t}},Ao=async(e={})=>{if(xR())return;let t=e.now??Date.now,n=e.readState??Bt,r=e.writeState??bp,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=kY();Xj(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await bt(s=>t()-(s.lastSpawnAt??0)<wY(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},vY=ew,SY=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Je(async()=>e);if(!r)return!1;let o=await bs(n,r.target.origin),a=t?HE(o):o;return a.length===0?!1:(await en(a,r.target),!0)}catch{return!1}},IY=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=se.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}},EY=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Bt,a=t.writeState??bp;return mR(e,Ne,{now:r,deadWatcherObserved:n,readHookLane:()=>Cp({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>bt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Cp=async(e={})=>{let n=await(e.readState??Bt)().catch(()=>({}));return Qn(n.hookLane)},OR=async(e,t={})=>{try{let n=t.now??Date.now,r=await Cp(t);if(!nw(r,e,n()))return;await bt(o=>{let a=Qn(o.hookLane);return nw(a,e,n())?{next:{...o,hookLane:X0(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},_R=async(e,t={})=>{try{let n=t.now??Date.now,r=await Cp(t);if(!rw(r,n()))return;await bt(o=>{let a=Qn(o.hookLane);return rw(a,n())?{next:{...o,hookLane:z0(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},xY=async(e={})=>{try{let t=e.now??Date.now;if((await Cp(e)).watchSince!==void 0)return;await bt(n=>{let r=Qn(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:q0(r,t())},result:void 0}},void 0,e)}catch{}},vR=async(e,t={})=>{try{let n=t.now??Date.now;await bt(r=>{let o=Qn(r.hookLane),a=Q0(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},TR=async(e={})=>{try{if((await(e.readState??Bt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>bt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??tC)())return await r()?"stamped":"skipped";let o=await(e.load??$)(),s=await(e.findTools??da)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Je(async()=>o);return!i||!await r()?"skipped":(await(e.repair??en)(s,i.target),"repathed")}catch{return"skipped"}},PR=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Bt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>bt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??$)(),i=await(e.findTools??da)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Je(async()=>a);return!c||!await o()?"skipped":(await(e.repair??en)(i,c.target)).some(d=>d.status==="failed")?(await bt(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"}},RY=async e=>{try{let t=await dp(e);if(!t)return!1;let{policy:n,skills:r,mcp:o}=t,a=r!==void 0&&(r.summary.changed>0||r.summary.removed.length>0),s=o!==void 0&&o.changed.length>0,i=await Ps(n);return i.profileUpdated||i.toolsApplied>0||a||s}catch{return!1}},SR=async(e,t,n)=>{let o=await(t.reconcilePolicy??RY)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>SY(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},rn=async(e={})=>{if(xR())return"disabled";let t=e.now??Date.now,n=e.loadProfile??$,r=e.saveProfile??de,o=e.loadDevKey??Ye,a=e.readState??Bt,s=e.writeState??bp,i=e.remint??An,c=e.heartbeat??f0,l=e.detectSeat??Wn,d=e.rewriteTools??vY,u=e.rewriteHookLaneTools??Qg,p=e.probeHookLane??Ns,m=e.classifyBeacon??Sl,f=e.force===!0,h=!1,w=!1,y=!1,g=!1;e.hookLaneRepair===!0&&(f=!0,g=!0);let b=async A=>{if(!g){A==="repaired"&&await vR("none",{now:t,readState:a,writeState:s});return}let x=A;if(A==="repaired"){let _=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));x=_.verdict==="live"?"repaired":_.verdict==="dark"?"repair_failed":"unverified"}await vR(x,{now:t,readState:a,writeState:s})},k=async()=>{if(!e.runAmbientSelfcheck||w||!h)return!1;w=!0;let A;try{A=await n()}catch{return!1}return(e.ambientSelfcheck??(_=>EY(_,{now:t,readState:a,writeState:s},y)))(A).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await Pn().then(W=>W.some(Q=>!Tn(Q.watcherPid))).catch(()=>!1),await xY({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??RA)();let A=await n();if(h=!0,!A.gateway||!A.enrolledCert)return"not-enrolled";let x=A.gateway,_=A.enrolledCertExpiry?Date.parse(A.enrolledCertExpiry):Date.parse(A.enrolledCert.payload.expiresAt);if(!Number.isFinite(_)||_<=t())return"cert-expired";let S=await o();if(!S)return"not-enrolled";let I=(e.resolveMachineUuid??nn)()||void 0,E=await fw(A,S,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});A=E.profile;let O=E.outcome==="renewed",K=A.enrolledCert;if(!K)return"not-enrolled";let G=Date.parse(A.clientKeyExpiresAt??""),X=Number.isFinite(G)?G-t():0,re=await a(),ke=!A.clientKey||X<=pw(A);if(!f&&eR(Qn(re.hookLane),t())&&await m().catch(()=>"unreadable")!=="foreign"&&(f=!0,g=!0),A.clientKey&&(f||ke)){let W=await bt(Q=>{let ye=t()-(Q.lastAttemptAt??0);return ye<gR?{result:"throttled"}:Q.failureCount&&ye<kR(Q.failureCount,Q.keyTtlMs)?{result:"backoff"}:{next:{...Q,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(W!=="ok")return W;try{let Q=await c(x,A.clientKey,K,S,{machineUuid:I}),ye=await n().catch(()=>A);return ye.clientKey!==A.clientKey||ye.enrolledCert?.sig!==K.sig?"failed":(await r({...ye,clientKeyExpiresAt:Q.expiresAt}),await wp(({lastError:we,...Y})=>({...Y,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:li(A)??Y.keyTtlMs}),{now:t,readState:a,writeState:s}),g?await b(await IY(A,x,A.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Q){let ye=wR(Q);return await wp(we=>({...we,lastAttemptAt:t(),failureCount:(we.failureCount??0)+1,lastError:{name:Q instanceof Error?Q.name:"Error",...ye!==void 0?{code:ye}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Q instanceof Rs&&Q.policyCode==="managed_device_required"&&console.error(Q.message),Q instanceof Rs?Q.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!f&&A.clientKey&&!ke){let W=await SR(A,e,n),Q=await k();return W||Q?"repaired":O?"cert-renewed":"not-due"}let fe=await bt(W=>{let Q=t()-(W.lastAttemptAt??0);if(f)return Q<dY(W.failureCount)?{result:"throttled"}:{next:{...W,lastAttemptAt:t()},result:"ok"};let ye=W.lastError?.code!==void 0&&sY.has(W.lastError.code)?iY:gR;return Q<ye?{result:"throttled"}:W.failureCount&&Q<kR(W.failureCount,W.keyTtlMs)?{result:"backoff"}:{next:{...W,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(fe!=="ok")return fe;try{let W=await i(x,K,S,{machineUuid:I}),Q=await l().catch(()=>{}),ye=xe({origin:x,clientKey:W.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:Q,user:A.name,team:A.team});if(await d(ye,ye.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let Y=await n().catch(()=>A),Ee=null;Y.enrolledCert&&await RR(Y,K.sig,S,o)&&(Ee={...Y,clientKey:W.key,clientKeyExpiresAt:W.expiresAt??Y.clientKeyExpiresAt},await r(Ee));let an=W.expiresAt?Date.parse(W.expiresAt):NaN,Pr=li(A)??(Number.isFinite(an)&&an-t()>0?an-t():void 0);return await wp(({lastError:Dr,...Lr})=>({...Lr,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Pr??Lr.keyTtlMs}),{now:t,readState:a,writeState:s}),Ee&&await SR(Ee,e,n),await b(Ee?"repaired":"repair_failed"),await k(),"refreshed"}catch(W){let Q=wR(W);return await wp(ye=>({...ye,lastAttemptAt:t(),failureCount:(ye.failureCount??0)+1,lastError:{name:W instanceof Error?W.name:"Error",...Q!==void 0?{code:Q}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),W instanceof it&&W.policyCode==="managed_device_required"&&console.error(W.message),W instanceof it?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var OY=`anyray-connect print-key [--json | --passthrough-headers]
|
|
582
582
|
|
|
583
583
|
Print the current short-lived Anyray client key for a consuming app.
|
|
584
584
|
|
|
@@ -615,7 +615,7 @@ Options:
|
|
|
615
615
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
616
616
|
--help Show this help.
|
|
617
617
|
`,MR=(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},$Y=e=>e.replace(/[\t\r\n]+/g," ").trim(),BR=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=MR(e,!1);if(o.help)return n.write(LY),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
|
|
618
|
-
`),1;let s=await(t.readTarget??ut)(o.source),i=await(t.retrieve??
|
|
618
|
+
`),1;let s=await(t.readTarget??ut)(o.source),i=await(t.retrieve??Ls)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
|
|
619
619
|
`),1)}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
620
620
|
`),1}},FR=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=MR(e,!0);if(o.help)return n.write(NY),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
|
|
621
621
|
`),1;let s=await(t.readTarget??ut)(o.source),i=await(t.recall??mp)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
|
|
@@ -635,13 +635,13 @@ Options:
|
|
|
635
635
|
--json Emit the result as JSON.
|
|
636
636
|
--help Show this help.
|
|
637
637
|
`,MY=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},BY=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"fleet-directed":return"Your organization applies Connect updates centrally. This machine does not update on its own; an administrator pushes new versions.";case"fleet-off":return"Your organization manages Connect updates outside Anyray. This machine does not download binaries; new versions arrive through your own deployment tooling.";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}.`}},UR=async e=>{let t;try{t=MY(e)}catch(o){return D(o.message),process.stderr.write(WR),1}if(t.help)return process.stdout.write(WR),0;if(t.auto!==void 0){let o=await $();if(o.autoUpdate!==!1!==t.auto&&await de({...o,autoUpdate:t.auto}),t.json||(B(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||C("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)}
|
|
638
|
-
`),0}let n=await
|
|
638
|
+
`),0}let n=await ks({checkOnly:t.check,force:!t.check,allowNpmMigration:!0,initiator:"human"});if(t.json){let o=await ua();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state,fleetUpdateMode:o.fleetMode},null,2)}
|
|
639
639
|
`),n.outcome==="failed"?1:0}let r=BY(n);switch(n.outcome){case"updated":case"migrated":B(r);break;case"current":B(r);break;case"available":case"migration-available":C(r),t.check&&C(`Run ${Z("anyray-connect update")} to install it.`);break;case"migration-deferred":P(r),C(v("Use the newer npm runtime until that standalone release is published."));break;case"disabled":P(r),C(`Run ${Z("anyray-connect update")} to install it now, or ${Z("--auto on")} to resume.`);break;case"fleet-directed":case"fleet-off":C(r),C(v("Ask your Anyray administrator if you need a newer version."));break;case"unmanaged":C(r),C(v("A copy your IT team placed is theirs to roll."));break;case"container":C(r);break;case"platform-unsupported":P(r),C(v("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":P(r);break;case"failed":return D(r),1}return 0};var Hc=e=>!e.some(t=>t==="--dry-run"||t==="--revert"||t==="--project"),ko=()=>!1,FY=new Map([["managed",{run:M0,persistsRuntime:e=>e.includes("--write")&&!e.includes("--revert")}],["endpoint",{run:Lx,persistsRuntime:ko}],["print-key",{run:$R,persistsRuntime:ko}],["models",{run:UE,persistsRuntime:e=>Hc(e)&&e.some(t=>!t.startsWith("-"))}],["copilot-login",{run:FE,persistsRuntime:Hc}],["retrieve",{run:BR,persistsRuntime:ko}],["recall",{run:FR,persistsRuntime:ko}],["history",{run:Zx,persistsRuntime:ko}],["migrate",{run:F0,persistsRuntime:ko}],["login",{run:Xx,persistsRuntime:Hc}],["update",{run:UR,persistsRuntime:ko}],["connectors",{run:BE,persistsRuntime:ko}]]),yw=e=>e===void 0?void 0:FY.get(e);import{randomBytes as WY}from"node:crypto";import{chmod as UY,readFile as HY,rm as GR,writeFile as GY}from"node:fs/promises";import{join as KY}from"node:path";var VY=/^[A-Za-z0-9_-]{43}$/,HR=3900,jY=1e4,gw=()=>KY(oe(),"device-token.json"),YY=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&VY.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},KR=async()=>{try{let e=JSON.parse(await HY(gw(),"utf-8"));return YY(e)?e:null}catch{return null}},ZY=0,JY=async e=>{await lt();let t=gw(),n=`${t}.${process.pid}.${ZY++}.tmp`;try{await GY(n,`${JSON.stringify(e)}
|
|
640
640
|
`,{mode:384}),await UY(n,384),await Ae(n,t)}catch(r){throw await GR(n,{force:!0}).catch(()=>{}),r}},kp=async()=>{await GR(gw(),{force:!0}).catch(()=>{})},XY=()=>WY(32).toString("base64url"),zY=e=>e instanceof Error?e.name:"UnknownError",VR=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??$)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=XY(),i=new AbortController,c=setTimeout(()=>i.abort(),jY),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:HR}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await JY({v:1,token:s,expiresAt:t()+HR*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${zY(r)}`),!1}};var jR=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??$)()}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??KR,i=await s();return(!i||i.expiresAt<=r())&&(await(e.rotateToken??VR)(),i=await s()),!i||i.expiresAt<=r()?(n.write(`Could not register a device token \u2014 retry after checking gateway connectivity.
|
|
641
641
|
`),1):(t.write(`${a}/device?dt=${i.token}
|
|
642
|
-
`),0)};import{join as YR,dirname as qY}from"node:path";import{mkdir as QY,readFile as bw,rm as ZR,writeFile as JR}from"node:fs/promises";var ww=["claude-code","codex"],eZ="anyray-connect print-key",Cw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tZ=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:
|
|
642
|
+
`),0)};import{join as YR,dirname as qY}from"node:path";import{mkdir as QY,readFile as bw,rm as ZR,writeFile as JR}from"node:fs/promises";var ww=["claude-code","codex"],eZ="anyray-connect print-key",Cw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tZ=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:Zs,authMode:"placeholder",metadata:{}}),Aw=e=>YR(e,".claude","settings.json"),nZ=async(e,t,n)=>{let r=Aw(e),o=await F(r),{env:a}=En(t,{includeAuthToken:!1,includeClientKey:!1}),s=Cw(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Po(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=eZ,n||await q(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]}},XR=async(e=process.cwd())=>{let t=[],n=Aw(e);try{if(await R(n)){let o=await F(n),a=Cw(o.env)?o.env:{};(To.some(s=>s in a)||Po(o))&&t.push(n)}}catch{}let r=kw(e);try{if(await R(r)){let o=await bw(r,"utf-8");Hl(o)&&t.push(r)}}catch{}return t},rZ=async(e,t)=>{let n=Aw(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await F(n),o=!1;if(Cw(r.env)){let s={...r.env};for(let i of To)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Po(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 ZR(n,{force:!0}):await q(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},kw=e=>YR(e,".codex","config.toml"),oZ=async(e,t,n)=>{let r=kw(e),o=await bw(r,"utf-8").catch(()=>""),a=Vl(o,pi(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await QY(qY(r),{recursive:!0}),await JR(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]}},aZ=async(e,t)=>{let n=kw(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await bw(n,"utf-8"),o=jl(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await ZR(n,{force:!0}):await JR(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},zR=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...ww],r=n.filter(s=>!ww.includes(s));if(r.length>0)return D(`--project supports ${ww.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 $(),i=e.gateway??s.gateway;if(!i)return D("--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 D(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=tZ(ct(i))}if(C(Z(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),U("Project"),C(` Directory: ${t}`),o&&C(` Gateway: ${o.origin}`),C(` Tools: ${n.join(", ")}`),e.revert||(P(`
|
|
643
643
|
A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),M(" Each machine still needs `anyray-connect` on PATH and a one-time enrollment (--sso/--enroll); the files carry no credential and no identity.")),!e.yes&&!e.dryRun){if(!Et())return D(`
|
|
644
|
-
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
|
|
644
|
+
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 ca(`
|
|
645
645
|
${s} ${n.length} tool(s)?`))return M("Aborted. Nothing changed."),0}e.dryRun&&M(`
|
|
646
646
|
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 nZ(t,o,e.dryRun):await oZ(t,o,e.dryRun):s==="claude-code"?await rZ(t,e.dryRun):await aZ(t,e.dryRun);for(let c of i.messages)C(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(U("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)C(` ${s}`);C(v(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as sZ}from"node:child_process";var iZ="/usr/bin/security",cZ=["find-generic-password","-s","Claude Code-credentials","-w"],lZ=1e4,dZ=64*1024,uZ=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,vw="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",pZ=(e,t,n)=>new Promise((r,o)=>{sZ(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),qR=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),fZ=e=>{let t=JSON.parse(e);if(!qR(t)||!qR(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!uZ.test(n))throw new Error("unexpected keychain access token");return n},mZ=async(e,t)=>{let n=hw(e),r=await(t.execSecurity??pZ)(iZ,[...cZ],{encoding:"utf8",timeout:lZ,maxBuffer:dZ,shell:!1});return JSON.stringify({token:fZ(r.stdout),headers:n})},QR=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${vw}
|
|
647
647
|
`),1;let o;try{o=await Uc(t)}catch(i){let c=i instanceof Error&&i.message?i.message:vw;return r.write(`${c}
|
|
@@ -652,7 +652,7 @@ Dry run \u2014 no files will be written.`);let a=[];for(let s of n){U(s==="claud
|
|
|
652
652
|
`),1;try{let o=await Uc(t);return o.warning&&r.write(`${o.warning}
|
|
653
653
|
`),n.write(`${JSON.stringify({Authorization:`Bearer ${o.token}`})}
|
|
654
654
|
`),0}catch{return r.write(`${eO}
|
|
655
|
-
`),1}};import{mkdir as CZ,writeFile as AZ}from"node:fs/promises";import{dirname as kZ}from"node:path";import{Buffer as vZ}from"node:buffer";var hZ=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),yZ=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,gZ=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.")},wZ=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),vp=(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!==""||gZ(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()}
|
|
655
|
+
`),1}};import{mkdir as CZ,writeFile as AZ}from"node:fs/promises";import{dirname as kZ}from"node:path";import{Buffer as vZ}from"node:buffer";var hZ=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),yZ=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,gZ=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.")},wZ=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),vp=(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!==""||gZ(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ms=(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()}},nO=e=>{if(!wZ(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!hZ.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ms(e.clientId,"clientId",!0),r=Ms(e.scopes,"scopes",!0),o=Ms(e.issuer,"issuer",!1),a=Ms(e.authorizationUrl,"authorizationUrl",!1),s=Ms(e.tokenUrl,"tokenUrl",!1),i=Ms(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:vp(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:vp(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:vp(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},rO=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return nO(t)},Sw=e=>e==="windows"?Bu:Mu,bZ=(e,t)=>{let n=new URL(e);return n.searchParams.set("os",t),n.toString()},Sp=(e,t)=>{let n=bZ(vp(e.url,"--bootstrap-url"),t),r=e.oidc?nO(e.oidc):void 0,o;if(e.deploymentOrganizationUuid!==void 0&&(o=e.deploymentOrganizationUuid.trim(),!yZ.test(o)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:n,bootstrapHeadersHelper:Sw(t),...r?{bootstrapOidc:r}:{},...o?{deploymentOrganizationUuid:o}:{}}},oO=(e,t)=>po(Sp(e,t));var SZ=`anyray-connect desktop [disconnect] [options]
|
|
656
656
|
|
|
657
657
|
The minimum Claude Desktop workflow:
|
|
658
658
|
anyray-connect desktop Connect this machine
|
|
@@ -731,12 +731,12 @@ ${s}
|
|
|
731
731
|
<string>${Tr(n)}</string>
|
|
732
732
|
</dict>
|
|
733
733
|
</plist>
|
|
734
|
-
`},Gc={disableDeploymentModeChooser:!0},iO=(e,t)=>Ew("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",po({...
|
|
734
|
+
`},Gc={disableDeploymentModeChooser:!0},iO=(e,t)=>Ew("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",po({...qo(e,t),...Gc})),_Z=(e,t)=>`${JSON.stringify({...qo(e,t),...Gc},null,2)}
|
|
735
735
|
`,TZ=e=>Ew("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",po({...Sp(e,"macos"),...Gc})),PZ=e=>`${JSON.stringify({...Sp(e,"linux"),...Gc},null,2)}
|
|
736
736
|
`,cO=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries({...e,...po(Gc)}).map(([n,r])=>`"${aO(n)}"="${aO(r)}"`),""].join(`
|
|
737
737
|
`),lO=(e,t)=>{let n=nu(e,t);return cO(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},DZ=e=>cO(oO(e,"windows")),dO=(e,t,n)=>{if(t==="darwin"){let r=hc;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:iO(e,r),helperPath:r}}if(t==="win32"){let r=yc;return{path:`${n}\\claude-desktop-anyray.reg`,content:lO(e,r),helperPath:r}}},uO=(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."],LZ=(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=Wu(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${pi(e,o).join(`
|
|
738
738
|
`)}
|
|
739
|
-
`},NZ=e=>Ew("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:vZ.from(e,"utf-8").toString("base64")}),$Z=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},MZ=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=cn(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:
|
|
739
|
+
`},NZ=e=>Ew("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:vZ.from(e,"utf-8").toString("base64")}),$Z=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},MZ=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=cn(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:Zs,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},sO=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??CZ,o=n.writeFile??AZ;await r(kZ(t),{recursive:!0}),await o(t,e)},BZ=(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:
|
|
740
740
|
`),o.write(r==="windows"?` anyray-connect desktop helper --write --platform windows --bin "C:\\Program Files\\Anyray\\anyray-connect.exe" --path "${n}"
|
|
741
741
|
`:` sudo anyray-connect desktop helper --write --platform posix --bin /usr/local/bin/anyray-connect --path '${n.replace(/'/g,`'"'"'`)}'
|
|
742
742
|
`),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.
|
|
@@ -745,7 +745,7 @@ ${s}
|
|
|
745
745
|
`),t.write(`The bootstrap fetch is authenticated by the bootstrap-headers helper at ${Sw(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).
|
|
746
746
|
`),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.
|
|
747
747
|
`),t.write(`Each bootstrap response replaces the allowed managed configuration; omitted keys are unset.
|
|
748
|
-
`)},WZ=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??
|
|
748
|
+
`)},WZ=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??ta)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
|
|
749
749
|
${o.remedy}
|
|
750
750
|
`),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("; ")})`:"")+`
|
|
751
751
|
`)}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)`:"")+`
|
|
@@ -759,7 +759,7 @@ Nothing new to migrate \u2014 no local sessions or portable local data needed co
|
|
|
759
759
|
`);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},pO=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=xZ(e);if(o[0]==="helper")return ex(o.slice(1),t);let a=$Z(o);if(a.help)return n.write(SZ),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 WZ(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:rO(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},p=a.artifact==="reg"?DZ(u):a.artifact==="json"?PZ(u):TZ(u);return await sO(p,a.path,t),FZ(a.artifact==="reg"?"windows":a.artifact==="json"?"linux":"macos",r),a.path&&n.write(`Wrote ${a.path}
|
|
760
760
|
`),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 ${hc} on macOS/Linux or ${yc} 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(!gc(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"&&Wu("windows",i);let l=MZ(a),d;if(a.target==="claude")d=a.artifact==="reg"?lO(l,i):a.artifact==="json"?_Z(l,i):iO(l,i);else{let u=LZ(l,i);d=a.artifact==="mobileconfig"?NZ(u):u}return await sO(d,a.path,t),BZ(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
|
|
761
761
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
762
|
-
`),1}};var UZ=3e3,Ip=async(e,t={})=>{let n=t.timeoutMs??UZ,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`:xt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};import{execFileSync as yO}from"node:child_process";import{lstatSync as gO,readFileSync as HZ}from"node:fs";import GZ from"node:os";import{z as xw}from"zod";var wO="ai.anyray.connect",
|
|
762
|
+
`),1}};var UZ=3e3,Ip=async(e,t={})=>{let n=t.timeoutMs??UZ,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`:xt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};import{execFileSync as yO}from"node:child_process";import{lstatSync as gO,readFileSync as HZ}from"node:fs";import GZ from"node:os";import{z as xw}from"zod";var wO="ai.anyray.connect",wa="EnrollmentEmail",ba="EnrollmentUrl",KZ="HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Anyray\\Connect",fO="/etc/anyray/anyray-enroll.json",VZ=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,jZ=254,YZ=2048,ZZ=64*1024,JZ=e=>e.isFile()&&e.uid===0&&(e.mode&63)===0&&e.size<=ZZ,XZ=()=>`/Library/Managed Preferences/${wO}.plist`,zZ=e=>`/Library/Managed Preferences/${e}/${wO}.plist`;var qZ=xw.record(xw.string(),xw.unknown()),mO=e=>{try{let t=JSON.parse(e),n=qZ.safeParse(t);return n.success?n.data:void 0}catch{return}};var hO=(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}},QZ=(e,t)=>e.split(/\r?\n/u).some(n=>/^\s*(\S+)\s+REG_\S+(?:\s|$)/u.exec(n)?.[1]===t),bO=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(!t||t.length>jZ))return VZ.test(t)?t:void 0},eJ=e=>{if(!e)return;let t=e.trim();if(!(!t||t.length>YZ))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}},tJ={lstat:e=>{gO(e)},convert:e=>yO("plutil",["-convert","json","-o","-",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})},nJ=(e,t=tJ)=>{try{t.lstat(e)}catch(n){return n.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable"}}try{return{kind:"ok",value:t.convert(e)}}catch{return{kind:"unreadable"}}},rJ=()=>{try{return GZ.userInfo().username||void 0}catch{return}},oJ={windowsHide:!0},aJ=`
|
|
763
763
|
$ErrorActionPreference = 'Stop'
|
|
764
764
|
try {
|
|
765
765
|
$item = Get-Item -LiteralPath 'Registry::${KZ}'
|
|
@@ -770,7 +770,7 @@ try {
|
|
|
770
770
|
}
|
|
771
771
|
try {
|
|
772
772
|
$valueNames = $item.GetValueNames()
|
|
773
|
-
foreach ($name in @('${
|
|
773
|
+
foreach ($name in @('${wa}', '${ba}')) {
|
|
774
774
|
if ($valueNames -contains $name) {
|
|
775
775
|
$registryKind = $item.GetValueKind($name)
|
|
776
776
|
# Preserve the administrator-authored value: expanding REG_EXPAND_SZ
|
|
@@ -789,27 +789,27 @@ try {
|
|
|
789
789
|
}
|
|
790
790
|
} catch {
|
|
791
791
|
exit 3
|
|
792
|
-
}`,sJ={query:(e,t)=>yO("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],...t})},iJ=(e=sJ)=>{try{return{kind:"ok",value:e.query(aJ,oJ)}}catch(t){return t.status===2?{kind:"absent"}:{kind:"unreadable"}}},cJ={lstat:e=>gO(e),readFile:e=>HZ(e,"utf8")},lJ=(e=cJ)=>{try{let t=e.lstat(fO);return JZ(t)?{kind:"ok",json:e.readFile(fO)}:{kind:"untrusted"}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable"}}},Ow={platform:process.platform,readMacPlistJson:nJ,username:rJ,readWindowsRegQuery:iJ,readLinuxPolicy:lJ},dJ=e=>{let t=e.map(bO).find(n=>n!==void 0);return t?{email:t}:{}},Rw=e=>typeof e=="string"?{kind:"ok",value:e}:e??{kind:"absent"},uJ=e=>{if(e.kind==="absent")return{status:"absent",enrollment:{}};if(e.kind==="untrusted")return{status:"invalid",reason:"untrusted-file",enrollment:{}};if(e.kind==="unreadable")return{status:"invalid",reason:"unreadable",enrollment:{}};let t=e.documents.find(s=>s.scope==="user"),n=e.documents.find(s=>s.scope==="device"),r=t?mO(t.json):void 0,o=n?mO(n.json):void 0,a=dJ([typeof r?.[
|
|
792
|
+
}`,sJ={query:(e,t)=>yO("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],...t})},iJ=(e=sJ)=>{try{return{kind:"ok",value:e.query(aJ,oJ)}}catch(t){return t.status===2?{kind:"absent"}:{kind:"unreadable"}}},cJ={lstat:e=>gO(e),readFile:e=>HZ(e,"utf8")},lJ=(e=cJ)=>{try{let t=e.lstat(fO);return JZ(t)?{kind:"ok",json:e.readFile(fO)}:{kind:"untrusted"}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable"}}},Ow={platform:process.platform,readMacPlistJson:nJ,username:rJ,readWindowsRegQuery:iJ,readLinuxPolicy:lJ},dJ=e=>{let t=e.map(bO).find(n=>n!==void 0);return t?{email:t}:{}},Rw=e=>typeof e=="string"?{kind:"ok",value:e}:e??{kind:"absent"},uJ=e=>{if(e.kind==="absent")return{status:"absent",enrollment:{}};if(e.kind==="untrusted")return{status:"invalid",reason:"untrusted-file",enrollment:{}};if(e.kind==="unreadable")return{status:"invalid",reason:"unreadable",enrollment:{}};let t=e.documents.find(s=>s.scope==="user"),n=e.documents.find(s=>s.scope==="device"),r=t?mO(t.json):void 0,o=n?mO(n.json):void 0,a=dJ([typeof r?.[wa]=="string"?r[wa]:void 0,typeof o?.[wa]=="string"?o[wa]:void 0]);if(e.failure==="unreadable")return{status:"invalid",reason:"unreadable",enrollment:a};if(n&&!o)return{status:"invalid",reason:"unparsable",enrollment:a};if(t&&!r)return{status:"invalid",reason:"unparsable",enrollment:a};if(o&&ba in o){let s=o[ba],i=typeof s=="string"?eJ(s):void 0;return i?{status:"valid",enrollment:{...a,enrollmentUrl:i}}:{status:"invalid",reason:"malformed-url",enrollment:a}}return r&&ba in r?{status:"invalid",reason:"untrusted-file",enrollment:a}:{status:"absent",enrollment:a}},pJ=e=>{if(e.platform==="darwin"){let t=e.username(),n=Rw(t?e.readMacPlistJson(zZ(t)):{kind:"absent"}),r=Rw(e.readMacPlistJson(XZ())),o=[...n.kind!=="ok"?[]:[{json:n.value,scope:"user"}],...r.kind!=="ok"?[]:[{json:r.value,scope:"device"}]],a=n.kind==="unreadable"||r.kind==="unreadable";return o.length>0?{kind:"document",documents:o,...a?{failure:"unreadable"}:{}}:a?{kind:"unreadable"}:{kind:"absent"}}if(e.platform==="win32"){let t=Rw(e.readWindowsRegQuery());if(t.kind!=="ok")return t;let n=t.value;if(!n)return{kind:"absent"};let r=hO(n,wa),o=hO(n,ba),a=QZ(n,ba);return{kind:"document",documents:[{scope:"device",json:JSON.stringify({...r?{[wa]:r}:{},...a?{[ba]:o??null}:{}})}]}}if(e.platform==="linux"){let t=e.readLinuxPolicy?.()??{kind:"absent"};return t.kind!=="ok"?t:{kind:"document",documents:[{json:t.json,scope:"device"}]}}return{kind:"absent"}},_w=(e=Ow)=>{try{return uJ(pJ(e))}catch{return{status:"invalid",reason:"unreadable",enrollment:{}}}},Kc=(e=Ow)=>_w(e).enrollment,CO=(e,t)=>{if(!e?.length)return;let n=t?.trim().split(/[\\/]/).at(-1)?.toLowerCase();if(n)return bO(`${n}@${e[0]}`)},AO=(e=Ow)=>Kc(e).email;import{z as ie}from"zod";import{createHash as fJ,randomBytes as mJ}from"node:crypto";import{createServer as hJ}from"node:http";var Bs="127.0.0.1",kO=/^[A-Za-z0-9_-]{43}$/,vO=/^[A-Za-z0-9_-]{86}$/,yJ=2147483647,Ft=class extends Error{kind;constructor(t,n){super(n),this.name="DesktopSignInCallbackError",this.kind=t}},Ep=()=>new Ft("denied","Desktop sign-in could not be completed. Try again."),Fs=(e,t,n)=>{e.writeHead(t,{"cache-control":"no-store","content-security-policy":"default-src 'none'","content-type":"text/plain; charset=utf-8","referrer-policy":"no-referrer","x-content-type-options":"nosniff"}),e.end(n)},gJ=(e,t)=>{let n=fJ("sha256").update(t,"utf8").digest().toString("base64url");return`ANYRAY-DESKTOP-SSO-COMPLETION-PROOF-V1
|
|
793
793
|
${e}
|
|
794
794
|
${n}
|
|
795
795
|
POLL
|
|
796
|
-
`},SO=async()=>{let e;try{e=mJ(32).toString("base64url")}catch{throw new Ft("cp-unreachable","Desktop sign-in could not open its local callback. Try again.")}let t,n=()=>{},r=new Promise(l=>{n=l}),o=!1,a=hJ((l,d)=>{if(l.socket.remoteAddress!==
|
|
796
|
+
`},SO=async()=>{let e;try{e=mJ(32).toString("base64url")}catch{throw new Ft("cp-unreachable","Desktop sign-in could not open its local callback. Try again.")}let t,n=()=>{},r=new Promise(l=>{n=l}),o=!1,a=hJ((l,d)=>{if(l.socket.remoteAddress!==Bs||l.method!=="GET"||l.url===void 0||!l.url.startsWith("/")||l.headers.host!==t){Fs(d,404,"Not found.");return}let u;try{u=new URL(l.url,`http://${Bs}`)}catch{Fs(d,404,"Not found.");return}if(u.pathname!==`/${e}`){Fs(d,404,"Not found.");return}if(o){Fs(d,409,"Sign-in callback already received.");return}let p=[...u.searchParams.entries()],m=u.searchParams.getAll("grant_id"),f=u.searchParams.getAll("completion_secret"),h=u.searchParams.getAll("error"),w=p.length!==2||m.length!==1||f.length!==1||h.length!==0||!kO.test(f[0]??"")?void 0:{grantId:m[0]??"",completionSecret:f[0]??""},y=p.length!==2||m.length!==1||f.length!==0||h.length!==1||h[0]!=="access_denied"&&h[0]!=="no_company"?void 0:{grantId:m[0]??"",reason:h[0]};if(w===void 0&&y===void 0){o=!0,n({status:"invalid"}),Fs(d,400,"Invalid sign-in callback.");return}o=!0,n(w!==void 0?{status:"complete",...w}:{status:"rejected",...y}),Fs(d,200,"Sign-in response received. You can return to Anyray.")});try{await new Promise((l,d)=>{let u=()=>d(new Error("listen failed"));a.once("error",u),a.listen({host:Bs,port:0},()=>{a.off("error",u),l()})})}catch{throw a.close(),new Ft("cp-unreachable","Desktop sign-in could not open its local callback. Try again.")}let s=a.address();if(s===null||typeof s=="string"||s.address!==Bs||s.port<=0)throw a.close(),new Ft("cp-unreachable","Desktop sign-in could not open its local callback. Try again.");let i=`http://${Bs}:${s.port}/${e}`;t=`${Bs}:${s.port}`;let c=async()=>{a.listening&&await new Promise(l=>a.close(()=>l()))};return a.on("error",()=>{o||(o=!0,n({status:"unavailable"}))}),{callbackUri:i,waitForCompletion:async(l,d={})=>{let u=d.now??Date.now,p=l.grantExpiresAt-u();if(p<=0)throw await c(),new Ft("expired","Desktop sign-in timed out. Try again.");let m;try{m=await new Promise((h,w)=>{let y=!1,g=A=>{y||(y=!0,clearTimeout(k),d.signal?.removeEventListener("abort",b),A())},b=()=>g(()=>w(Ep())),k=setTimeout(()=>g(()=>w(new Ft("expired","Desktop sign-in timed out. Try again."))),Math.min(p,yJ));if(d.signal?.aborted){b();return}d.signal?.addEventListener("abort",b,{once:!0}),r.then(A=>g(()=>h(A)))})}catch(h){throw await c(),h}if(m.status==="unavailable")throw await c(),new Ft("cp-unreachable","Desktop sign-in lost its local callback. Try again.");if(m.status==="invalid"||m.grantId!==l.id)throw await c(),Ep();if(m.status==="rejected")throw await c(),m.reason==="no_company"?new Ft("no-company","No company found for this email. Ask your admin for a link."):new Ft("denied","Desktop sign-in was denied. Try again.");let f;try{f=await qn(gJ(l.id,m.completionSecret),l.privateKeyPem)}catch{throw await c(),Ep()}if(!vO.test(f)||Buffer.from(f,"base64url").length!==64)throw await c(),Ep();return await c(),{completionSecret:m.completionSecret,keyProof:f}},close:c}},IO=e=>{let t=/^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})\/([A-Za-z0-9_-]{43})(?![\s\S])/.exec(e);return t!==null&&Number.parseInt(t[1]??"0",10)<=65535},EO=e=>e!==void 0&&kO.test(e.completionSecret)&&vO.test(e.keyProof)&&Buffer.from(e.keyProof,"base64url").length===64;var xO=1e4,wJ=/^[BCDFGHJKMNPQRSTVWXYZ23456789]{4}-[BCDFGHJKMNPQRSTVWXYZ23456789]{4}$/,bJ=ie.strictObject({id:ie.string().min(1),browser_url:ie.string().min(1),user_code:ie.string().regex(wJ),poll_secret:ie.string().min(1),interval:ie.number().positive(),expires_in:ie.number().positive()}),CJ=ie.object({payload:ie.object({v:ie.number(),deploymentId:ie.string().min(1),user:ie.string().min(1),team:ie.string().min(1).optional(),source:ie.enum(["sso","provisioning","manual","mdm","device"]).optional(),devPublicKey:ie.string().min(1),devKeyAlg:ie.literal("ES256").optional(),issuedAt:ie.string().min(1),expiresAt:ie.string().min(1),keyTtlSeconds:ie.number().optional()}).passthrough(),alg:ie.literal("Ed25519"),sig:ie.string().min(1)}).passthrough(),AJ=ie.strictObject({status:ie.literal("pending")}),kJ=ie.strictObject({status:ie.literal("complete"),cert:CJ,deploymentId:ie.string().min(1),gatewayUrl:ie.string().min(1).optional()}),vJ=ie.strictObject({status:ie.literal("rejected"),reason:ie.enum(["no_company","denied"])}),SJ=ie.strictObject({status:ie.literal("failure")}),IJ=ie.strictObject({status:ie.literal("failure"),retryable:ie.literal(!0),message:ie.string().min(1).max(256)}),EJ=e=>new Promise(t=>setTimeout(t,e)),xJ=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},RO=async e=>{let t=e.cpOrigin??Cn(),n=e.fetch??fetch,r=e.now??Date.now;if(!IO(e.callbackUri))throw new wt("cp-unreachable","Desktop sign-in could not register its local callback. Try again.");let{publicKeyPem:o,privateKeyPem:a}=(e.generateKeypair??Os)(),s;try{s=await Dc(`${t}/sso/desktop/start`,{devPublicKey:o,callback_uri:e.callbackUri},xO,n)}catch{throw new wt("cp-unreachable","Desktop sign-in could not reach the control plane. Check your network and try again.")}if(s.status!==200){let l=s.status===404||s.status===503;throw new wt(l?"sso-unavailable":"cp-unreachable",l?"Desktop sign-in is not available. Update the app or ask your admin to check the Anyray control plane.":"Desktop sign-in could not be started. Try again.",s.status)}let i=bJ.safeParse(s.json);if(!i.success)throw new wt("cp-unreachable","Desktop sign-in failed: the control plane returned an incomplete response.");if(!xJ(i.data.browser_url,t))throw new wt("cp-unreachable","Desktop sign-in failed: the control plane returned an invalid browser URL.");let c={cpOrigin:t,id:i.data.id,pollSecret:i.data.poll_secret,browserUrl:i.data.browser_url,userCode:i.data.user_code,intervalMs:i.data.interval*1e3,grantExpiresAt:r()+i.data.expires_in*1e3,privateKeyPem:a,publicKeyPem:o};return e.log?.("To finish, sign in with your organization at:"),e.log?.(` ${c.browserUrl}`),e.log?.("On that official page, enter or confirm this code before approval:"),e.log?.(` ${c.userCode}`),e.open?.(c.browserUrl),c},on=class extends Error{kind;constructor(t,n){super(n),this.name="DesktopSignInPollError",this.kind=t}},OO=async(e,t)=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??EJ,a=t.pollIntervalMs??e.intervalMs;if(!EO(t.completion))throw new on("denied","Desktop sign-in was not completed. Try again.");for(;r()<e.grantExpiresAt;){let s;try{s=await C0(`${e.cpOrigin}/sso/desktop/poll/${e.id}`,{"x-anyray-poll-secret":e.pollSecret,"x-anyray-completion-secret":t.completion.completionSecret,"x-anyray-key-proof":t.completion.keyProof},xO,n)}catch{throw new on("cp-unreachable","Desktop sign-in lost contact with the control plane. Check your network and try again.")}if(s.status===202){if(AJ.safeParse(s.json).success){let i=e.grantExpiresAt-r();if(i<=0)break;await o(Math.min(a,i));continue}throw new on("cp-unreachable","Desktop sign-in failed: the control plane returned an unexpected response.")}if(s.status===503&&IJ.safeParse(s.json).success){let i=e.grantExpiresAt-r();if(i<=0)break;await o(Math.min(a,i));continue}if(s.status===200){let i=kJ.safeParse(s.json);if(i.success)return{cert:i.data.cert,privateKeyPem:e.privateKeyPem,gatewayUrl:i.data.gatewayUrl,deploymentId:i.data.deploymentId};let c=vJ.safeParse(s.json);if(c.success&&c.data.reason==="no_company")throw new on("no-company","No company found for this email. Ask your admin for a link.");if(c.success)throw new on("denied","Desktop sign-in was denied. Try again.")}throw s.status===404&&SJ.safeParse(s.json).success?new on("denied","Desktop sign-in was not completed. Try again."):new on("cp-unreachable","Desktop sign-in failed: the control plane returned an unexpected response.")}throw new on("expired","Desktop sign-in timed out. Try again.")};var _O=()=>Zy(),TO=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??_O)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},RJ=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},PO=async(e,t={})=>{let n=(t.openInput??_O)(),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(f=>f.selected===!0&&f.requiresExplicitChoice!==!0),s=0,i=0,c=hs(o,t.env??process.env),l=(f,h)=>c?`\x1B[${f}m${h}\x1B[0m`:h,d=()=>{let f=[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)}`:"";f.push(`${y} ${g} ${w.label}${b}`)}f.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(f.map(h=>`\r\x1B[2K${h}`).join(`
|
|
797
797
|
`)),o.write(`
|
|
798
798
|
`),i=f.length},u=()=>{i!==0&&(o.write(`\x1B[${i}A`),o.write(Array.from({length:i},()=>`\r\x1B[2K
|
|
799
|
-
`).join("")),o.write(`\x1B[${i}A`))},p=!!r.isRaw,m=!1;try{return m=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((f,h)=>{let w=()=>{r.off("data",A),r.off("end",b),r.off("close",b),r.off("error",k)},y=
|
|
800
|
-
`)&&y({kind:"ok",values:[]});continue}if(
|
|
801
|
-
`){y({kind:"ok",values:e.items.filter((S,I)=>a[I]).map(S=>S.value)});return}}}catch(
|
|
799
|
+
`).join("")),o.write(`\x1B[${i}A`))},p=!!r.isRaw,m=!1;try{return m=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((f,h)=>{let w=()=>{r.off("data",A),r.off("end",b),r.off("close",b),r.off("error",k)},y=x=>{w(),f(x)},g=x=>{w(),h(x)},b=()=>y({kind:"cancelled"}),k=x=>g(x),A=x=>{try{for(let _ of RJ(x)){if(_===""||_==="\x1B"||_==="q"){y({kind:"cancelled"});return}if(e.items.length===0){(_==="\r"||_===`
|
|
800
|
+
`)&&y({kind:"ok",values:[]});continue}if(_==="\x1B[A"||_==="k")s=(s-1+e.items.length)%e.items.length,d();else if(_==="\x1B[B"||_==="j")s=(s+1)%e.items.length,d();else if(_===" "){if(e.single){let S=!a[s];a.fill(!1),a[s]=S}else a[s]=!a[s];d()}else if(_==="a"&&!e.single){let S=e.items.map((E,O)=>({item:E,index:O})).filter(({item:E})=>E.requiresExplicitChoice!==!0),I=!S.every(({index:E})=>a[E]);for(let{index:E}of S)a[E]=I;d()}else if(_==="\r"||_===`
|
|
801
|
+
`){y({kind:"ok",values:e.items.filter((S,I)=>a[I]).map(S=>S.value)});return}}}catch(_){g(_)}};r.on("data",A),r.on("end",b),r.on("close",b),r.on("error",k)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),m&&r.setRawMode(p)}catch{}n.close()}};var DO=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],OJ=80,Ws=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&hs(r,n.env??process.env)))return r.write(`${e}
|
|
802
802
|
`),t();let a=0,s=()=>{r.write(`\r${DO[a++%DO.length]} ${e}`)};s();let i=setInterval(s,OJ);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{z as ce}from"zod";var _J=ce.enum(["cp-unreachable","sso-unavailable","no-company","denied","expired","gateway-unreachable","invalid-link","invalid-args","sso-required","yes-required","enroll-rejected","enroll-failed","apply-failed"]),LO=ce.enum(["personal","service"]),TJ=ce.strictObject({event:ce.literal("sso_grant"),verificationUriComplete:ce.string().min(1),userCode:ce.string().min(1).optional(),expiresAt:ce.iso.datetime(),tenantId:ce.string().min(1).optional()}),PJ=ce.strictObject({event:ce.literal("enrolled"),via:ce.enum(["sso","enroll","claim","sign-in"]),user:ce.string().min(1).optional(),team:ce.string().min(1).optional(),authMode:ce.string().min(1),gateway:ce.string().min(1),deploymentId:ce.string().min(1).optional(),certExpiresAt:ce.string().min(1).optional(),keyKind:LO.optional()}),xp=ce.strictObject({id:ce.string().min(1),reason:ce.string()}),DJ=ce.strictObject({event:ce.literal("applied"),connected:ce.array(ce.string().min(1)),queued:ce.array(ce.string().min(1)),held:ce.array(xp),manual:ce.array(xp),failed:ce.array(xp),keyKind:LO.optional(),reverted:ce.array(ce.string().min(1)).optional(),skipped:ce.array(xp).optional()}),LJ=ce.strictObject({event:ce.literal("error"),code:_J,message:ce.string().min(1)}),Ole=ce.discriminatedUnion("event",[TJ,PJ,DJ,LJ]),NO=(e,t,n)=>{let r=e.filter(o=>o.status==="reverted").map(o=>o.id);return{event:"applied",...t?{keyKind:t}:{},connected:e.filter(o=>o.status==="configured").map(o=>o.id),queued:e.filter(o=>o.status==="queued").map(o=>o.id),held:e.filter(o=>o.status==="held").map(o=>({id:o.id,reason:o.reason??"left on its own plan (no change)"})),manual:e.filter(o=>o.status==="manual").map(o=>({id:o.id,reason:o.reason??"manual step required"})),failed:e.filter(o=>o.status==="failed").map(o=>({id:o.id,reason:o.reason??"apply failed"})),...r.length>0?{reverted:r}:{},...n&&n.length>0?{skipped:[...n]}:{}}},er=e=>{process.stdout.write(`${JSON.stringify(e)}
|
|
803
|
-
`)};import{chmod as NJ,readFile as $J,rm as $O,writeFile as MJ}from"node:fs/promises";import{join as BJ}from"node:path";var Tw=()=>BJ(oe(),"sso-gate.json"),FJ=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))},
|
|
804
|
-
`,{mode:384}),await NJ(n,384),await Ae(n,t)}catch(r){throw await $O(n,{force:!0}).catch(()=>{}),r}},Vc=async()=>{await $O(Tw(),{force:!0}).catch(()=>{})},MO=e=>{if(!e||!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}};import{z as BO}from"zod";var UJ=5e3,HJ=BO.object({lane:BO.enum(["subscription","org"]).optional().catch(void 0)}),FO=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??UJ);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=HJ.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},WO=(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 GJ=12e3,KJ="anyray-wiring-probe-not-a-real-token",VJ={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},Dw={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},ba=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},HO=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},Lw=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},UO=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."],jJ=e=>e.includes("no provider key configured for"),Nw=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},$w=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>"]}),jc=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."]}),YJ=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:jJ(t)?{kind:"provider-rejected",providerKeyAbsent:!0,detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${ba(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")?UO([" \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?Nw(t)?$w(e):Lw(t)?jc(e):HO(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${ba(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}): ${ba(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).",...UO([" \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}: ${ba(t)}`,remedy:[]},ZJ=(e,t)=>{if(Lw(t))return jc(e);if(Nw(t))return $w(e);if(HO(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}: ${ba(t)}`,remedy:[]}},JJ=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),XJ=(e,t)=>{if(Lw(t))return jc(e);if(Nw(t))return $w(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:","set it as the gateway upstream (console \u2192 Routing), or for a","caller-supplied host add it to ANYRAY_CUSTOM_HOST_ALLOWLIST."]};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")||JJ(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}: ${ba(t)}`,remedy:[`The probe asks for a fixed model (${Dw.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."]}},Pw=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)}},zJ=async(e,t)=>{if(!e.clientKey)return jc(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?jc(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${ba(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},qJ=(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."]}},QJ=e=>e.providerKeyAbsent===!0?!1:e.kind==="ok"?!0:null,GO=async(e,t={})=>{try{return QJ(await Us(e,t))}catch{return null}},Us=async(e,t={})=>{let n=t.timeoutMs??GJ,r=be(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await zJ(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 Pw(`${e.anthropicBaseUrl}/v1/messages`,l,Dw,n);return XJ(d,u)}if(ae(e,"anthropic")){let l={Authorization:`Bearer ${KJ}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"};r&&(l["x-anyray-metadata"]=r),e.clientKey&&(l["x-anyray-api-key"]=e.clientKey);let{status:d,bodyText:u}=await Pw(`${e.anthropicBaseUrl}/v1/messages`,l,Dw,n);return ZJ(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await Pw(`${e.openaiBaseUrl}/chat/completions`,s,VJ,n);return YJ(i,c,t.tools??[])}catch(o){return qJ(n,o)}};var KO=async(e,t={})=>{let n=await $(),r=!n.enrolledCert&&n.managedEnrollmentDisabled!==!0&&!!(t.managedEnrollment??Kc)().enrollmentUrl,o;try{o=Xn(e.gateway,n)}catch(s){return C(Z("Anyray connect \u2014 status")),M(`Gateway: ${s.message}`),0}C(Z("Anyray connect \u2014 status")),U("Gateway"),C(` Origin: ${st(o)}`),n.gateway?M(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?M(" (from $ANYRAY_GATEWAY_URL)"):r?M(" (default \u2014 enrollment is managed by your organization and re-enrolls on the next refresh)"):e.gateway||M(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),U("Identity"),C(` Name: ${n.name??v("(not set)")}`),C(` Team: ${n.team??v("(not set)")}`);let a=On();a&&(U("Environment"),C(` Remote dev context: ${Pa(a)}`),sr(a)&&M(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),M(" VS Code tools configure the remote server variant backing this window.")),n.enrolledCert&&n.clientKey&&(U("Credential renewal"),B(" Direct gateway routing with a proof-backed key heartbeat."),M(" Renewal extends the same key; tool configuration is not rewritten.")),U("Tools");for(let s of se){if(!(await s.detect()).installed){M(` ${s.title}: not installed`);continue}if(!s.pointsAt){M(` ${s.title}: installed ${v("(status not introspectable)")}`);continue}let c=await s.pointsAt(o);if(c){if(s.id==="cursor"&&(n.authMode==="auto"||n.authMode==="subscription")){B(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),C(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}B(` ${s.title}: pointed at Anyray`)}else{let l=null,d=null;if(s.id===ho&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,p=await Lu();l=Nu({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:p.authoritative}),d={...p.authoritative?{}:{reason:p.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=$u(l,d);P(` ${s.title}: ${u.headline}`);for(let p of u.detail)C(v(` ${p}`))}else M(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as vX}from"node:fs";import{isAbsolute as SX}from"node:path";import{homedir as IX}from"node:os";import{readFile as eX,stat as tX}from"node:fs/promises";import{homedir as nX,platform as rX}from"node:os";var oX=e=>e.replace(/\\(\d{3})/g,(t,n)=>String.fromCharCode(parseInt(n,8))),aX=e=>e.split(`
|
|
805
|
-
`).map(t=>t.split(" ")[4]).filter(t=>!!t).map(oX),sX=async(e,t,n=async r=>(await tX(r)).isFile())=>{let r=t.endsWith("/")?t:`${t}/`,o=[];for(let a of e)a.startsWith(r)&&await n(a).catch(()=>!1)&&o.push(a);return o},Op=async()=>{if(rX()!=="linux")return[];try{let e=await eX("/proc/self/mountinfo","utf-8");return await sX(aX(e),nX())}catch{return[]}};import{access as iX}from"node:fs/promises";import{constants as cX}from"node:fs";import{platform as lX}from"node:os";var dX=async e=>{try{return await iX(e,cX.F_OK),!0}catch{return!1}},uX=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"]:[],
|
|
806
|
-
`)){let o=new RegExp(`${wX}=(\\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"},AX=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",_p=(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 ${Mn} and ${Bn}; 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."}},jO=async(e={})=>{let{installedVariant:t=Va,receiptMode:n=bd,awaitingReload:r=wd,readSettings:o=bX,probeBridge:a=CX,home:s=mX()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:_p("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.":_p("not-applicable","unknown")}}let l=await o(Oi(i)),d=await a(),u=AX({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:_p(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:_p("not-applicable","unknown")}}};var Wt="connect",Tp=e=>e.replace(/-/g,"_"),YO=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Wt,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:Wt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Wt,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:Wt,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.removed&&e.serviceRemoval.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.connect.selfUpdate.updateLane==="fleet_directive"&&t.push({tool:Wt,checkId:"update_lane",status:"fleet_directive"}),e.identity.sharedIdentityRisk&&t.push({tool:Wt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Wt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),t.push({tool:Wt,checkId:"desktop_config_carry",status:e.claudeDesktopConfigCarry}),e.retrieval){let i=Tp(e.retrieval.kind);t.push({tool:Wt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":Tp(e.verify.kind);t.push({tool:Wt,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:Wt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:Tp(e.hookLane.reason)}:{}})}t.push({tool:Wt,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)if(i.installed){if(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.configuredKeyStale?"stale_key":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){let c=!i.mcp.registered&&!i.routingHeld;t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing",...c&&i.mcp.reason?{errorClass:Tp(i.mcp.reason)}:{}})}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:Wt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};var Mw="claude-desktop",kX=async(e,t,n)=>{if(t.some(o=>o.adapter===Mw))return!0;if(e.managedTools!==void 0)return e.managedTools.includes(Mw);let r=n(Mw);return!e.gateway||!r?.pointsAt?!1:r.pointsAt(e.gateway).catch(()=>!1)},Yc=async(e={})=>{let t=(e.firstPartyRoot??Xo)(),n=(e.thirdPartyRoot??kr)();if(!t||!n)return"unsupported";let[r,o]=await Promise.all([(e.loadProfile??$)(),(e.listPendingOps??Pn)()]);return await kX(r,o,e.toolById??qe)?(e.inspect??DI)(t,n):"not_routed"};var EX=e=>{let t=IX();return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e};function ZO(){return Ne}var xX=(e,t)=>e!=="managed"?"package":t?"fleet_directive":"self",RX="ctx_doctor-probe-synthetic",OX=(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: ${Ww(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 _X(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function TX(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Ww(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 JO=e=>Nu({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),Bw=e=>e.tombstoned!==!0&&(e.applyBlocked===!0||e.configuredKeyStale===!0||e.pointedAt===!1&&JO(e)!=="unverifiable"),XO=e=>e.registered&&e.command&&SX(e.command)?vX(e.command):null,PX=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."}},Fw=e=>(Bw(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),DX=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,LX=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},zO=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},NX=(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(ha),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,m=Array.isArray(p?.checks)?p.checks.filter(w=>typeof w=="string"&&a.has(w)):[],f=p?.reason==="rebroke_same_day"||p?.reason==="repeat_days"?p.reason:void 0,h=p&&r(p.since)&&f&&m.length>0?{since:p.since,reason:f,checks:m}:void 0;(u.length>0||h)&&s.push({tool:c,repaired:u,...h?{flapping:h}:{}})}return s},$X=async(e,t,n,r,o,a,s,i=n,c=Us,l=!0,d=Da,u=da,p=Bt,m=Ls,f=()=>Yc({loadProfile:async()=>t,toolById:y=>r.find(g=>g.id===y)}),h=py(),w=_n)=>{let y=l?await Ip(e):null,g=process.env.ANYRAY_CLIENT_KEY?.trim(),b=g?"env":t.clientKey?"profile":null,k=kn(g||t.clientKey)??null,A=J=>J&&Gy(J)?"machine_default":null,E=t.enrolledCert?.payload,O=E?.expiresAt??t.enrolledCertExpiry??null,I=(await a())?.sso??null,x=TX({ssoLink:I,enrolledViaToken:!!t.enrolledTokenHash}),_=s(),K=!E&&t.managedEnrollmentDisabled!==!0&&_.status==="valid",G=ft(),X=await sA(G),re=X?[]:ql(xe({origin:e})),ke=[];for(let J of r){let At=await J.detect(),Eo=null;if(At.installed&&J.mcpStatus)try{let Xp=await J.mcpStatus();Eo={...Xp,commandOk:XO(Xp)}}catch{}let xo=At.installed&&J.id===ho?await o():void 0,Nr=At.installed&&J.pointsAt?await J.pointsAt(e):null,ka=await DX(Nr,J,t.managedTools??[]),nl=Nr===!1&&ka===null,js=ka===!1&&J.routingPendingReload?await J.routingPendingReload().catch(()=>!1):!1,rl=ka===!0&&t.clientKey&&J.configuredKeyIsCurrent?await J.configuredKeyIsCurrent(t.clientKey).catch(()=>null):null,z=At.installed?J.runtimeDiagnostics?await J.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:J.routingOverrides?await J.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:le,claudeCodeHookPolicy:sn}=z,ve=t.fleetToolPolicy,$r=ve?.enabled.includes(J.id)?ve.tiers?.[J.id]??pa:void 0;ke.push({id:J.id,title:J.title,installed:At.installed,...At.detail?{detail:At.detail}:{},pointedAt:ka,...rl===!1?{configuredKeyStale:!0}:{},...nl?{routingHeld:!0}:{},...js?{routingPendingReload:!0}:{},...le.length?{routingOverrides:le}:{},...sn===void 0?{}:{claudeCodeHookPolicy:sn},mcp:Eo,...$r?{policyTier:$r}:{},...t.revertedTools?.includes(J.id)?{tombstoned:!0}:{},...t.blockedTools?.includes(J.id)?{applyBlocked:!0}:{},...J.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...xo===void 0?{}:{inferenceIntrospectable:xo.authoritative,...xo.authoritative?{}:{inferenceUnverifiableReason:xo.reason}}})}let fe=i?await(async()=>{let{kind:J,detail:At,remedy:Eo}=await c(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:At,remedy:Eo}})():null,W=fe?.kind==="provider-rejected"&&await LX(t.managedTools??[],r),Q=fe?{...fe,...W?{notApplicableSubscription:!0}:{}}:null,ye=n?OX(await Ds({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:be({user:t.name,team:t.team})},RX,{probe:!0}),{mode:x,ssoLink:I}):null,we=await p().catch(()=>({})),Y=Qn(we.hookLane),Ee=i?await zO(r):!1,an=Ee?await(async()=>{let J=await m().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...sw(J,{hookRegistered:Ee,neverInvoked:ow(Y,Date.now())}),lastInvokedAt:pp(Y)}})():null,Pr=(await Pn()).map(J=>({adapter:J.adapter,op:J.op,requestedAt:J.requestedAt,watcherAlive:Tn(J.watcherPid)})),Dr=Pr.find(J=>J.adapter==="cursor"),Lr=Dr?{op:Dr.op,requestedAt:Dr.requestedAt,watcherAlive:Dr.watcherAlive}:null,Io=await f().catch(()=>"unknown"),tl=ke.some(J=>J.id===ho&&J.installed),Vs;if(tl&&Io!=="unsupported"){let J;try{J=h()}catch{J="probe_failed"}Vs=J==="probe_failed"?"failed":"answered"}let L=!!t.refreshSchedulerEnabled,T=await w(),V=L&&!T&&!rt(t),_e=await u(),tt=await Ca(),Ut=t.anyrayFleetManaged===!0&&tt,Ct=t.persistenceOwner==="tray",Ve=Ct?await d(t)==="healthy":null,je=await KC({schedulerEnabled:L&&!Ct&&!V,schedulerInstalled:T,binaryDurable:!dt(Po()),schedulerInstalledOnce:t.refreshSchedulerInstalledOnce===!0,trayManaged:Ct}),Te=0;y&&!y.reachable&&(Te+=1),Ct?L&&!Ve&&(Te+=1):L&&!T&&!V&&(Te+=1);for(let J of ke)Te+=Fw(J);Q&&Q.kind!=="ok"&&!Q.notApplicableSubscription&&(Te+=1),ye&&ye.kind!=="ok"&&(Te+=1),an?.verdict==="dark"&&(Te+=1),re.length>0&&(Te+=1),Te+=Pr.filter(J=>!J.watcherAlive).length;let tr=await jO();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:ZO(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:On(),fileBindMounts:await Op(),selfUpdate:{managed:_e.managed,available:_e.available,autoUpdate:_e.autoUpdate,state:_e.state,fleetMode:_e.fleetMode,updateLane:xX(_e.state,Ut)}},gateway:{origin:e,reachable:y?y.reachable:null,detail:y?y.detail:"not probed (--quick)"},refreshScheduler:{enabled:L,installed:T,owner:Ct?"tray":"os",...Ct?{trayHealthy:!!Ve}:{},...V?{retired:!0}:{}},serviceRemoval:je,fleetdPresent:tt,identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:b,keyKind:k,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:A(t.name)},enrollment:{enrolled:!!E,deploymentId:E?.deploymentId??null,issuedAt:E?.issuedAt??null,expiresAt:O,expired:O?Date.parse(O)<Date.now():null,orgMode:x,ssoLink:I,managedPending:K,managedPreference:_.status,managedPreferenceReason:_.reason??null},shell:{profilePath:G,blockPresent:X,staleExports:re},claudeDesktopConfigCarry:Io,...Vs?{claudeDesktopRunningProbe:Vs}:{},tools:ke,...t.fleetToolPolicy?{fleetPlan:cp(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Lr,pendingOps:Pr,ambientRepairs:NX(we,r),verify:Q,retrieval:ye,hookLane:an,agentsWindow:tr,problems:Te}},MX=e=>{if(e.serviceRemoval.suspected){if(!e.serviceRemoval.removed){U("Automatic key refresh"),P(" This seat expects the key-refresh schedule, but no unit is installed and"),P(" Anyray has no record of ever installing one here. Re-run `anyray-connect`"),P(" to install it.");for(let t of e.serviceRemoval.missingPaths)C(v(` expected: ${t}`));return}U("Endpoint security"),P(" Anyray installed these background services, but their files are gone from disk \u2014"),P(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),P(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)C(v(` missing: ${t}`));C(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),C(v(" tools straight at the gateway (your key then needs a periodic re-run).")),C(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),C(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},BX=(e,t)=>{if(C(Z("Anyray connect \u2014 doctor")),e.connect.remoteContext||e.connect.fileBindMounts.length>0){U("Environment"),e.connect.remoteContext&&(C(` Remote dev context: ${Pa(e.connect.remoteContext)}`),sr(e.connect.remoteContext)&&C(v(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule.")));for(let l of e.connect.fileBindMounts)C(` Bind-mounted config file: ${EX(l)}`),C(v(" A file mounted into this container cannot be replaced atomically; connect writes it in place (verified). Mount the parent directory instead to restore atomic writes."))}switch(U("CLI updates"),e.connect.selfUpdate.state){case"managed":B(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.fleetMode==="off"?C(v(" Your organization manages Connect updates; this machine downloads nothing.")):e.connect.selfUpdate.fleetMode==="directed"?C(v(" Your organization applies Connect updates centrally; an administrator pushes new versions.")):e.connect.selfUpdate.autoUpdate||P(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":P(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),C(v(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":P(" Self-update is unavailable on this platform because no standalone binary is published."),C(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":C(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":C(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}if(U("Gateway"),e.gateway.reachable===null?C(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?B(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(D(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),C(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?B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(D(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),C(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."):e.refreshScheduler.retired?B(" Retired \u2014 this key does not expire between sessions, and your tools already trigger renewal. No background schedule is needed."):(D(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||C(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),MX(e),e.identity.keyKind==="service")U("Service key (agent)"),B(e.identity.personalKeySource==="env"?" Service key present ($ANYRAY_CLIENT_KEY).":" Service key present (stored by connect)."),C(v(" Identity and team come from the key. Not a seat: no key refresh here, and no seat health report."));else switch(U("Personal key"),_X(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":P(" Enrolled, but no personal key is cached locally right now."),C(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:if(!t&&e.enrollment.managedPreference==="invalid"){P(` Your organization pushed Anyray enrollment settings to this machine, but they can't be used (reason: ${e.enrollment.managedPreferenceReason}).`),C(v(" Fix: contact your admin. Nothing to run here."));break}if(e.enrollment.managedPending){P(" Enrollment is managed by your organization, but this machine holds no local enrollment state."),C(v(" Fix: none needed \u2014 it re-enrolls unattended on the next refresh; run `anyray-connect refresh` to do it now."));break}P(" Enrollment required \u2014 no personal gateway key is available."),C(v(` Fix: ${Ww(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?P(` 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&&(U("Shell"),D(" This terminal still exports Anyray, but the config is gone."),C(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),C(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),C(v(" Anything you start from this terminal keeps reaching the gateway with")),C(v(" no credential, and fails with 401.")),C(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),C(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),C(v(" reuses the environment it captured at launch, so a new terminal")),C(v(" (or Reload Window) keeps serving the old one.")));let n=e.tools.find(l=>l.installed&&l.claudeCodeHookPolicy!==void 0&&l.claudeCodeHookPolicy!=="fine");if(n?.claudeCodeHookPolicy){let l={state:n.claudeCodeHookPolicy};U("Claude Code hook policy"),D(` ${kl(l)}.`),C(v(` ${vl(l)}`))}if(e.tools.some(l=>l.id===ho&&l.installed)){U("Claude Desktop profile");let l=kI[e.claudeDesktopConfigCarry];switch(e.claudeDesktopConfigCarry){case"carried":B(` ${l}.`);break;case"pending":P(` ${l}.`),C(v(" Connect completes it on the next reconcile, or the next time Claude Desktop is fully quit."));break;case"unreadable":P(` ${l}.`),C(v(" Allow Connect to read the first-party Claude Desktop profile, then run doctor again."));break;case"nothing_to_carry":case"not_routed":case"unsupported":case"unknown":C(v(` ${l}.`));break}e.claudeDesktopRunningProbe==="failed"&&(P(" Could not tell whether Claude Desktop is running: the process probe failed."),C(v(" Queued copies wait until the probe answers; check that pgrep (macOS) or tasklist (Windows) runs from this account.")))}U("Tools");let r=!1,o=!1,a=l=>{for(let d of l.routingOverrides??[])D(` ${l.title}: ${d.problem}.`),C(v(` ${d.fix}`))},s=l=>{l.mcp&&(l.mcp.registered?l.mcp.commandOk===!1?(D(` ${l.title}: retrieval MCP server registered, but its binary is gone (${l.mcp.command}).`),C(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):B(` ${l.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(P(` ${l.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),C(v(` Fix: ${PX(l)}`))))};for(let l of e.tools){if(!l.installed){C(v(` ${l.title}: not installed (skipped)`));continue}if(l.pointedAt===null){C(v(` ${l.title}: installed (config not introspectable)`)),s(l);continue}if(l.pointedAt){if(r=!0,l.id==="cursor"&&l.nativeSubscription){B(` ${l.title}: native Cursor subscription; Anyray hooks/MCP active`),C(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),s(l);continue}B(` ${l.title}: pointed at ${e.gateway.origin}`),a(l),l.id==="claude-code"&&C(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.")),l.id===ho&&C(v(` ${sS(Ot("migrate"),Ot("desktop"))}`)),l.id==="codex"&&C(v(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),s(l)}else{a(l);let d=JO(l);if(d==="not-routed"||d==="unverifiable"){let u=$u(d,{...l.inferenceUnverifiableReason?{reason:l.inferenceUnverifiableReason}:{},mcpRegistered:l.mcp?.registered===!0});P(` ${l.title}: ${u.headline}`);for(let p of u.detail)C(v(` ${p}`));d==="unverifiable"&&(o=!0)}else l.tombstoned?l.policyTier==="required"?(P(` ${l.title}: reverted locally against admin policy (out of compliance)`),C(v(` Re-enroll with \`anyray-connect --tools ${l.id}\`.`))):l.policyTier==="locked"?P(` ${l.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):C(v(` ${l.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${l.id}\``)):l.configuredKeyStale?(D(` ${l.title}: routed, but its stored key is not the current one \u2014 it will stop working when that key expires`),C(v(` Fix: \`anyray-connect --tools ${l.id}\`, then restart ${l.title} so it re-reads the config.`))):l.applyBlocked?(D(` ${l.title}: configured, but the last setup was refused \u2014 this tool is NOT being kept up to date`),C(v(` Its client key is frozen and will stop working when it expires. Fix: re-run \`anyray-connect --tools ${l.id}\` and read the message it prints.`))):l.routingPendingReload?(D(` ${l.title}: configured, but ${l.title} is still running the previous Anyray build`),C(v(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(D(` ${l.title}: installed but not pointed at ${e.gateway.origin}`),C(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let i=(e.repairs?.length??0)>0;if(!r&&!o&&!i&&e.problems===0&&(P(" No tools are pointed at this gateway yet."),C(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){U("Queued operations");for(let l of e.pendingOps){let d=qe(l.adapter)?.title??l.adapter;l.watcherAlive?P(` ${d} ${l.op} queued since ${l.requestedAt} \u2014 completes automatically when ${d} quits.`):(D(` ${d} ${l.op} queued since ${l.requestedAt}, but its watcher is not running.`),C(v(` Fix: quit ${d} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){U("Ambient repairs");let l=d=>d==="hook_registration"?"hook re-installed":d==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let d of e.ambientRepairs){let u=qe(d.tool)?.title??d.tool,p=d.repaired.map(({checkId:f,at:h})=>`${l(f)} ${new Date(h).toISOString().slice(0,10)}`);d.flapping&&p.push(`flapping since ${new Date(d.flapping.since).toISOString().slice(0,10)} (${d.flapping.reason})`);let m=` ${u}: ${p.join("; ")}`;d.flapping?P(m):C(m)}}let c=e.fleetPlan;if(c&&(c.freshIds.length>0||c.tombstonedIds.length>0)){U("Fleet policy");let l=d=>d.map(u=>qe(u)?.title??u).join(", ");c.freshIds.length>0&&C(` Pending enrollment (the next policy sync applies): ${l(c.freshIds)}`),c.tombstonedIds.length>0&&P(` Out of compliance (reverted against required policy): ${l(c.tombstonedIds)}`)}if(e.verify)if(U("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{D(` ${e.verify.kind}: ${e.verify.detail}`);for(let l of e.verify.remedy)C(v(` ${l}`))}if(e.retrieval)if(U("Retrieval loop"),e.retrieval.kind==="ok")B(` ${e.retrieval.detail}`);else{D(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let l of e.retrieval.remedy)C(v(` ${l}`))}if(e.hookLane){if(U("Hook lane"),e.hookLane.verdict==="live")B(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){D(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let l of e.hookLane.remedy)C(v(` ${l}`))}else{P(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let l of e.hookLane.remedy)C(v(` ${l}`))}e.hookLane.lastInvokedAt!==null&&C(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"),P(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(U("VS Code Agents window"),B(` ${e.agentsWindow.detail}`)),U("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)."),C(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):D(` ${e.problems} problem(s) found \u2014 see fixes above.`)},FX=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}),WX=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!tw(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??Ls,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??rn)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=Qn((await(t.readRefreshState??Bt)().catch(()=>({}))).hookLane),l=sw(i,{hookRegistered:await zO(t.adapters??se).catch(()=>!1),neverInvoked:ow(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:pp(c)},note:d}},UX=async(e,t,n={})=>{let r=n.adapters??se,o=n.resolveTarget??Je,a=n.applyTools??en,s=await WX(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&&(Bw(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 ${Ww(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),p=[],m=[...c.notes],f=[];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}f.push(b)}p.length>0&&m.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(f,d.target),w=new Map,y=0;for(let g of h){if(p.push(g),!ca(g))continue;let b=e.tools.find(_=>_.id===g.id);if(!b)continue;let k=r.find(_=>_.id===g.id),A=b.mcp;if(k?.mcpStatus)try{let _=await k.mcpStatus();A={..._,commandOk:XO(_)}}catch{}let E=Bw(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{E=await k.pointsAt(e.gateway.origin)}catch{}let O=b.routingOverrides,S=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let _=await k.runtimeDiagnostics();O=_.routingOverrides.length?_.routingOverrides:void 0,S=_.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let _=await k.routingOverrides();O=_.length?_:void 0}catch{}let I=b.configuredKeyStale;if(k?.configuredKeyIsCurrent&&t.clientKey)try{let _=await k.configuredKeyIsCurrent(t.clientKey);_!==null&&(I=!_)}catch{}let x={...b,pointedAt:E,mcp:A,...I?{configuredKeyStale:!0}:{},...O?{routingOverrides:O}:{},...S===void 0?{}:{claudeCodeHookPolicy:S}};I||delete x.configuredKeyStale,O||delete x.routingOverrides,S===void 0&&delete x.claudeCodeHookPolicy,w.set(g.id,x),y+=Fw(b)-Fw(x)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:m}},HX=e=>{U("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-")?C(v(` ${t.title}: ${t.status}`)):D(` ${t.title}: ${t.status}`);for(let t of e.notes)C(v(` ${t}`))},Pp=async(e,t={})=>{let n=await $();if(e.securityReview){if(e.json){let l;try{l=n.gateway?new URL(n.gateway).hostname:void 0}catch{}return console.log(JSON.stringify(VC({connectVersion:ZO(),...l?{gatewayHost:l}:{}}),null,2)),0}if(!e.silent){C(Z("Anyray connect \u2014 security review"));for(let l of jC())C(l?` ${l}`:"")}return 0}let r;try{r=Xn(e.gateway,n)}catch(l){return e.silent?1:e.json?(console.log(JSON.stringify({error:l.message})),1):(C(Z("Anyray connect \u2014 doctor")),D(` Gateway URL: ${l.message}`),C(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"})):(C(Z("Anyray connect \u2014 doctor")),D(" --quick skips the network probes; it cannot be combined with --verify."))),1;let o=!e.noVerify&&!e.quick,a=await $X(r,n,!!e.verify&&!e.quick,t.adapters??se,t.inferenceIntrospection??Lu,t.fleetBootstrap??bo,t.managedPreference??_w,o,t.verifyAuth??Us,!e.quick,t.checkTray??Da,t.updateStatus??da,t.readRefreshState??Bt,t.probeHookLane??Ls,t.claudeDesktopConfigCarry??(()=>Yc({loadProfile:async()=>n,toolById:l=>(t.adapters??se).find(d=>d.id===l)})),t.claudeDesktopRunningProbe??py(),t.isRefreshSchedulerInstalled??_n),s=e.repair?await UX(a,n,t):void 0,i=s?{...a,tools:a.tools.map(l=>s.refreshedTools.get(l.id)??l),...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(FX(i),null,2)):(BX(i,n.managedEnrollmentDisabled===!0),s&&HX(s)));let c=i.identity.keyKind!=="service";try{!e.quick&&c&&await(t.reportHealth??aR)(YO(i),i.connect.version)}catch{}return i.problems===0?0:1};var qO=async e=>{let t=await $();C(Z("Anyray connect \u2014 sync"));let n;try{n=Xn(e.gateway,t)}catch(i){return D(i.message),1}M(`Gateway: ${n}`);let r=TE(t.clientKey,"anyray-placeholder"),o;try{o=await fa(n,r)}catch(i){return D(`Team policy sync failed: ${_s(i)}`),1}let{summary:a,dirs:s}=await zg(o);if(s.length===0)M("No managed tool exposes a skills directory \u2014 nothing to sync.");else if(o.skills.length===0&&a.removed.length===0)M("No team skills published yet \u2014 nothing to sync.");else{U("Skills");for(let i of a.results)i.written?B(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):M(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);for(let i of a.removed)M(` ${i} \u2014 removed (no longer published)`);o.skillsIncomplete&&M(" The gateway could not read every skills store; nothing was removed this run."),U("Summary"),C(` ${st(String(a.changed))} updated, ${a.unchanged} unchanged, ${a.removed.length} removed, across ${s.length} tool dir(s).`)}try{let i=await qg(o);i.changed.length>0&&C(`Org connectors: ${i.served?"registered":"removed"} the anyray-org MCP entry in ${i.changed.join(", ")}.`)}catch(i){M(`Org connectors sync skipped: ${_s(i)}`)}try{let i=await Ts(o);(i.routingUpdated||i.teamUpdated||i.toolsRequested>0||i.toolsTombstoned.length>0)&&(C(`Fleet policy: routing ${i.routingUpdated?"updated":"unchanged"}, team ${i.teamUpdated?"updated":"unchanged"}, ${i.toolsApplied}/${i.toolsRequested} tool(s) reconciled${i.toolsEnrolled>0?` (${i.toolsEnrolled} newly enrolled)`:""}.`),i.toolsTombstoned.length>0&&M(` Locally reverted against admin policy (out of compliance): ${i.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(i){M(`Fleet policy reconcile skipped: ${_s(i)}`)}return 0};import{gzip as j5}from"node:zlib";import{promisify as Y5}from"node:util";var vo={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Uw=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),QO=e=>`
|
|
803
|
+
`)};import{chmod as NJ,readFile as $J,rm as $O,writeFile as MJ}from"node:fs/promises";import{join as BJ}from"node:path";var Tw=()=>BJ(oe(),"sso-gate.json"),FJ=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))},Us=async()=>{try{let e=JSON.parse(await $J(Tw(),"utf-8"));return FJ(e)?e:null}catch{return null}},WJ=0,Rp=async e=>{await lt();let t=Tw(),n=`${t}.${process.pid}.${WJ++}.tmp`;try{await MJ(n,`${JSON.stringify(e)}
|
|
804
|
+
`,{mode:384}),await NJ(n,384),await Ae(n,t)}catch(r){throw await $O(n,{force:!0}).catch(()=>{}),r}},Vc=async()=>{await $O(Tw(),{force:!0}).catch(()=>{})},MO=e=>{if(!e||!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}};import{z as BO}from"zod";var UJ=5e3,HJ=BO.object({lane:BO.enum(["subscription","org"]).optional().catch(void 0)}),FO=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??UJ);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=HJ.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},WO=(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 GJ=12e3,KJ="anyray-wiring-probe-not-a-real-token",VJ={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},Dw={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},Ca=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},HO=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},Lw=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},UO=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."],jJ=e=>e.includes("no provider key configured for"),Nw=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},$w=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>"]}),jc=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."]}),YJ=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:jJ(t)?{kind:"provider-rejected",providerKeyAbsent:!0,detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Ca(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")?UO([" \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?Nw(t)?$w(e):Lw(t)?jc(e):HO(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Ca(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}): ${Ca(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).",...UO([" \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}: ${Ca(t)}`,remedy:[]},ZJ=(e,t)=>{if(Lw(t))return jc(e);if(Nw(t))return $w(e);if(HO(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}: ${Ca(t)}`,remedy:[]}},JJ=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),XJ=(e,t)=>{if(Lw(t))return jc(e);if(Nw(t))return $w(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:","set it as the gateway upstream (console \u2192 Routing), or for a","caller-supplied host add it to ANYRAY_CUSTOM_HOST_ALLOWLIST."]};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")||JJ(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}: ${Ca(t)}`,remedy:[`The probe asks for a fixed model (${Dw.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."]}},Pw=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)}},zJ=async(e,t)=>{if(!e.clientKey)return jc(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?jc(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Ca(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},qJ=(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."]}},QJ=e=>e.providerKeyAbsent===!0?!1:e.kind==="ok"?!0:null,GO=async(e,t={})=>{try{return QJ(await Hs(e,t))}catch{return null}},Hs=async(e,t={})=>{let n=t.timeoutMs??GJ,r=be(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await zJ(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 Pw(`${e.anthropicBaseUrl}/v1/messages`,l,Dw,n);return XJ(d,u)}if(ae(e,"anthropic")){let l={Authorization:`Bearer ${KJ}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"};r&&(l["x-anyray-metadata"]=r),e.clientKey&&(l["x-anyray-api-key"]=e.clientKey);let{status:d,bodyText:u}=await Pw(`${e.anthropicBaseUrl}/v1/messages`,l,Dw,n);return ZJ(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await Pw(`${e.openaiBaseUrl}/chat/completions`,s,VJ,n);return YJ(i,c,t.tools??[])}catch(o){return qJ(n,o)}};var KO=async(e,t={})=>{let n=await $(),r=!n.enrolledCert&&n.managedEnrollmentDisabled!==!0&&!!(t.managedEnrollment??Kc)().enrollmentUrl,o;try{o=Xn(e.gateway,n)}catch(s){return C(Z("Anyray connect \u2014 status")),M(`Gateway: ${s.message}`),0}C(Z("Anyray connect \u2014 status")),U("Gateway"),C(` Origin: ${st(o)}`),n.gateway?M(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?M(" (from $ANYRAY_GATEWAY_URL)"):r?M(" (default \u2014 enrollment is managed by your organization and re-enrolls on the next refresh)"):e.gateway||M(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),U("Identity"),C(` Name: ${n.name??v("(not set)")}`),C(` Team: ${n.team??v("(not set)")}`);let a=On();a&&(U("Environment"),C(` Remote dev context: ${Da(a)}`),sr(a)&&M(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),M(" VS Code tools configure the remote server variant backing this window.")),n.enrolledCert&&n.clientKey&&(U("Credential renewal"),B(" Direct gateway routing with a proof-backed key heartbeat."),M(" Renewal extends the same key; tool configuration is not rewritten.")),U("Tools");for(let s of se){if(!(await s.detect()).installed){M(` ${s.title}: not installed`);continue}if(!s.pointsAt){M(` ${s.title}: installed ${v("(status not introspectable)")}`);continue}let c=await s.pointsAt(o);if(c){if(s.id==="cursor"&&(n.authMode==="auto"||n.authMode==="subscription")){B(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),C(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}B(` ${s.title}: pointed at Anyray`)}else{let l=null,d=null;if(s.id===ho&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,p=await Lu();l=Nu({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:p.authoritative}),d={...p.authoritative?{}:{reason:p.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=$u(l,d);P(` ${s.title}: ${u.headline}`);for(let p of u.detail)C(v(` ${p}`))}else M(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as vX}from"node:fs";import{isAbsolute as SX}from"node:path";import{homedir as IX}from"node:os";import{readFile as eX,stat as tX}from"node:fs/promises";import{homedir as nX,platform as rX}from"node:os";var oX=e=>e.replace(/\\(\d{3})/g,(t,n)=>String.fromCharCode(parseInt(n,8))),aX=e=>e.split(`
|
|
805
|
+
`).map(t=>t.split(" ")[4]).filter(t=>!!t).map(oX),sX=async(e,t,n=async r=>(await tX(r)).isFile())=>{let r=t.endsWith("/")?t:`${t}/`,o=[];for(let a of e)a.startsWith(r)&&await n(a).catch(()=>!1)&&o.push(a);return o},Op=async()=>{if(rX()!=="linux")return[];try{let e=await eX("/proc/self/mountinfo","utf-8");return await sX(aX(e),nX())}catch{return[]}};import{access as iX}from"node:fs/promises";import{constants as cX}from"node:fs";import{platform as lX}from"node:os";var dX=async e=>{try{return await iX(e,cX.F_OK),!0}catch{return!1}},uX=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"]:[],Aa=async(e={})=>{let t=e.os??lX(),n=e.exists??dX;for(let r of uX(t))if(await n(r))return!0;return!1};import{execFile as pX}from"node:child_process";import{readFile as fX}from"node:fs/promises";import{homedir as mX,platform as hX}from"node:os";import{promisify as yX}from"node:util";var gX=yX(pX),wX="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",VO=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bX=async e=>{let t;try{t=await fX(e,"utf-8")}catch(n){return n?.code==="ENOENT"?{readable:!0}:{readable:!1}}try{if(t.trim()==="")return{readable:!0};let n=Tt(t);if(!VO(n))return{readable:!1};let r=n[Mn],o=n[Bn];return{readable:!0,supportsAnyray:VO(r)?r[ne]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},CX=async(e=async()=>(await gX("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(hX()==="win32")return"unknown";let t;try{t=await e()}catch{return"unknown"}let n=!1;for(let r of t.split(`
|
|
806
|
+
`)){let o=new RegExp(`${wX}=(\\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"},AX=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",_p=(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 ${Mn} and ${Bn}; 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."}},jO=async(e={})=>{let{installedVariant:t=ja,receiptMode:n=bd,awaitingReload:r=wd,readSettings:o=bX,probeBridge:a=CX,home:s=mX()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:_p("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.":_p("not-applicable","unknown")}}let l=await o(Oi(i)),d=await a(),u=AX({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:_p(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:_p("not-applicable","unknown")}}};var Wt="connect",Tp=e=>e.replace(/-/g,"_"),YO=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Wt,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:Wt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Wt,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:Wt,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.removed&&e.serviceRemoval.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.connect.selfUpdate.updateLane==="fleet_directive"&&t.push({tool:Wt,checkId:"update_lane",status:"fleet_directive"}),e.identity.sharedIdentityRisk&&t.push({tool:Wt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Wt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),t.push({tool:Wt,checkId:"desktop_config_carry",status:e.claudeDesktopConfigCarry}),e.retrieval){let i=Tp(e.retrieval.kind);t.push({tool:Wt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":Tp(e.verify.kind);t.push({tool:Wt,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:Wt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:Tp(e.hookLane.reason)}:{}})}t.push({tool:Wt,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)if(i.installed){if(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.configuredKeyStale?"stale_key":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){let c=!i.mcp.registered&&!i.routingHeld;t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing",...c&&i.mcp.reason?{errorClass:Tp(i.mcp.reason)}:{}})}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:Wt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};var Mw="claude-desktop",kX=async(e,t,n)=>{if(t.some(o=>o.adapter===Mw))return!0;if(e.managedTools!==void 0)return e.managedTools.includes(Mw);let r=n(Mw);return!e.gateway||!r?.pointsAt?!1:r.pointsAt(e.gateway).catch(()=>!1)},Yc=async(e={})=>{let t=(e.firstPartyRoot??zo)(),n=(e.thirdPartyRoot??kr)();if(!t||!n)return"unsupported";let[r,o]=await Promise.all([(e.loadProfile??$)(),(e.listPendingOps??Pn)()]);return await kX(r,o,e.toolById??qe)?(e.inspect??DI)(t,n):"not_routed"};var EX=e=>{let t=IX();return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e};function ZO(){return Ne}var xX=(e,t)=>e!=="managed"?"package":t?"fleet_directive":"self",RX="ctx_doctor-probe-synthetic",OX=(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: ${Ww(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 _X(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function TX(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Ww(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 JO=e=>Nu({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),Bw=e=>e.tombstoned!==!0&&(e.applyBlocked===!0||e.configuredKeyStale===!0||e.pointedAt===!1&&JO(e)!=="unverifiable"),XO=e=>e.registered&&e.command&&SX(e.command)?vX(e.command):null,PX=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."}},Fw=e=>(Bw(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),DX=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,LX=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},zO=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},NX=(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(ya),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,m=Array.isArray(p?.checks)?p.checks.filter(w=>typeof w=="string"&&a.has(w)):[],f=p?.reason==="rebroke_same_day"||p?.reason==="repeat_days"?p.reason:void 0,h=p&&r(p.since)&&f&&m.length>0?{since:p.since,reason:f,checks:m}:void 0;(u.length>0||h)&&s.push({tool:c,repaired:u,...h?{flapping:h}:{}})}return s},$X=async(e,t,n,r,o,a,s,i=n,c=Hs,l=!0,d=La,u=ua,p=Bt,m=Ns,f=()=>Yc({loadProfile:async()=>t,toolById:y=>r.find(g=>g.id===y)}),h=py(),w=_n)=>{let y=l?await Ip(e):null,g=process.env.ANYRAY_CLIENT_KEY?.trim(),b=g?"env":t.clientKey?"profile":null,k=kn(g||t.clientKey)??null,A=J=>J&&Gy(J)?"machine_default":null,x=t.enrolledCert?.payload,_=x?.expiresAt??t.enrolledCertExpiry??null,I=(await a())?.sso??null,E=TX({ssoLink:I,enrolledViaToken:!!t.enrolledTokenHash}),O=s(),K=!x&&t.managedEnrollmentDisabled!==!0&&O.status==="valid",G=ft(),X=await sA(G),re=X?[]:ql(xe({origin:e})),ke=[];for(let J of r){let At=await J.detect(),Eo=null;if(At.installed&&J.mcpStatus)try{let Xp=await J.mcpStatus();Eo={...Xp,commandOk:XO(Xp)}}catch{}let xo=At.installed&&J.id===ho?await o():void 0,Nr=At.installed&&J.pointsAt?await J.pointsAt(e):null,va=await DX(Nr,J,t.managedTools??[]),nl=Nr===!1&&va===null,Ys=va===!1&&J.routingPendingReload?await J.routingPendingReload().catch(()=>!1):!1,rl=va===!0&&t.clientKey&&J.configuredKeyIsCurrent?await J.configuredKeyIsCurrent(t.clientKey).catch(()=>null):null,z=At.installed?J.runtimeDiagnostics?await J.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:J.routingOverrides?await J.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:le,claudeCodeHookPolicy:sn}=z,ve=t.fleetToolPolicy,$r=ve?.enabled.includes(J.id)?ve.tiers?.[J.id]??fa:void 0;ke.push({id:J.id,title:J.title,installed:At.installed,...At.detail?{detail:At.detail}:{},pointedAt:va,...rl===!1?{configuredKeyStale:!0}:{},...nl?{routingHeld:!0}:{},...Ys?{routingPendingReload:!0}:{},...le.length?{routingOverrides:le}:{},...sn===void 0?{}:{claudeCodeHookPolicy:sn},mcp:Eo,...$r?{policyTier:$r}:{},...t.revertedTools?.includes(J.id)?{tombstoned:!0}:{},...t.blockedTools?.includes(J.id)?{applyBlocked:!0}:{},...J.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...xo===void 0?{}:{inferenceIntrospectable:xo.authoritative,...xo.authoritative?{}:{inferenceUnverifiableReason:xo.reason}}})}let fe=i?await(async()=>{let{kind:J,detail:At,remedy:Eo}=await c(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:At,remedy:Eo}})():null,W=fe?.kind==="provider-rejected"&&await LX(t.managedTools??[],r),Q=fe?{...fe,...W?{notApplicableSubscription:!0}:{}}:null,ye=n?OX(await Ls({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:be({user:t.name,team:t.team})},RX,{probe:!0}),{mode:E,ssoLink:I}):null,we=await p().catch(()=>({})),Y=Qn(we.hookLane),Ee=i?await zO(r):!1,an=Ee?await(async()=>{let J=await m().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...sw(J,{hookRegistered:Ee,neverInvoked:ow(Y,Date.now())}),lastInvokedAt:pp(Y)}})():null,Pr=(await Pn()).map(J=>({adapter:J.adapter,op:J.op,requestedAt:J.requestedAt,watcherAlive:Tn(J.watcherPid)})),Dr=Pr.find(J=>J.adapter==="cursor"),Lr=Dr?{op:Dr.op,requestedAt:Dr.requestedAt,watcherAlive:Dr.watcherAlive}:null,Io=await f().catch(()=>"unknown"),tl=ke.some(J=>J.id===ho&&J.installed),js;if(tl&&Io!=="unsupported"){let J;try{J=h()}catch{J="probe_failed"}js=J==="probe_failed"?"failed":"answered"}let L=!!t.refreshSchedulerEnabled,T=await w(),V=L&&!T&&!rt(t),_e=await u(),tt=await Aa(),Ut=t.anyrayFleetManaged===!0&&tt,Ct=t.persistenceOwner==="tray",Ve=Ct?await d(t)==="healthy":null,je=await KC({schedulerEnabled:L&&!Ct&&!V,schedulerInstalled:T,binaryDurable:!dt(Do()),schedulerInstalledOnce:t.refreshSchedulerInstalledOnce===!0,trayManaged:Ct}),Te=0;y&&!y.reachable&&(Te+=1),Ct?L&&!Ve&&(Te+=1):L&&!T&&!V&&(Te+=1);for(let J of ke)Te+=Fw(J);Q&&Q.kind!=="ok"&&!Q.notApplicableSubscription&&(Te+=1),ye&&ye.kind!=="ok"&&(Te+=1),an?.verdict==="dark"&&(Te+=1),re.length>0&&(Te+=1),Te+=Pr.filter(J=>!J.watcherAlive).length;let tr=await jO();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:ZO(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:On(),fileBindMounts:await Op(),selfUpdate:{managed:_e.managed,available:_e.available,autoUpdate:_e.autoUpdate,state:_e.state,fleetMode:_e.fleetMode,updateLane:xX(_e.state,Ut)}},gateway:{origin:e,reachable:y?y.reachable:null,detail:y?y.detail:"not probed (--quick)"},refreshScheduler:{enabled:L,installed:T,owner:Ct?"tray":"os",...Ct?{trayHealthy:!!Ve}:{},...V?{retired:!0}:{}},serviceRemoval:je,fleetdPresent:tt,identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:b,keyKind:k,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:A(t.name)},enrollment:{enrolled:!!x,deploymentId:x?.deploymentId??null,issuedAt:x?.issuedAt??null,expiresAt:_,expired:_?Date.parse(_)<Date.now():null,orgMode:E,ssoLink:I,managedPending:K,managedPreference:O.status,managedPreferenceReason:O.reason??null},shell:{profilePath:G,blockPresent:X,staleExports:re},claudeDesktopConfigCarry:Io,...js?{claudeDesktopRunningProbe:js}:{},tools:ke,...t.fleetToolPolicy?{fleetPlan:cp(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Lr,pendingOps:Pr,ambientRepairs:NX(we,r),verify:Q,retrieval:ye,hookLane:an,agentsWindow:tr,problems:Te}},MX=e=>{if(e.serviceRemoval.suspected){if(!e.serviceRemoval.removed){U("Automatic key refresh"),P(" This seat expects the key-refresh schedule, but no unit is installed and"),P(" Anyray has no record of ever installing one here. Re-run `anyray-connect`"),P(" to install it.");for(let t of e.serviceRemoval.missingPaths)C(v(` expected: ${t}`));return}U("Endpoint security"),P(" Anyray installed these background services, but their files are gone from disk \u2014"),P(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),P(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)C(v(` missing: ${t}`));C(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),C(v(" tools straight at the gateway (your key then needs a periodic re-run).")),C(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),C(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},BX=(e,t)=>{if(C(Z("Anyray connect \u2014 doctor")),e.connect.remoteContext||e.connect.fileBindMounts.length>0){U("Environment"),e.connect.remoteContext&&(C(` Remote dev context: ${Da(e.connect.remoteContext)}`),sr(e.connect.remoteContext)&&C(v(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule.")));for(let l of e.connect.fileBindMounts)C(` Bind-mounted config file: ${EX(l)}`),C(v(" A file mounted into this container cannot be replaced atomically; connect writes it in place (verified). Mount the parent directory instead to restore atomic writes."))}switch(U("CLI updates"),e.connect.selfUpdate.state){case"managed":B(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.fleetMode==="off"?C(v(" Your organization manages Connect updates; this machine downloads nothing.")):e.connect.selfUpdate.fleetMode==="directed"?C(v(" Your organization applies Connect updates centrally; an administrator pushes new versions.")):e.connect.selfUpdate.autoUpdate||P(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":P(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),C(v(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":P(" Self-update is unavailable on this platform because no standalone binary is published."),C(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":C(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":C(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}if(U("Gateway"),e.gateway.reachable===null?C(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?B(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(D(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),C(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?B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(D(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),C(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."):e.refreshScheduler.retired?B(" Retired \u2014 this key does not expire between sessions, and your tools already trigger renewal. No background schedule is needed."):(D(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||C(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),MX(e),e.identity.keyKind==="service")U("Service key (agent)"),B(e.identity.personalKeySource==="env"?" Service key present ($ANYRAY_CLIENT_KEY).":" Service key present (stored by connect)."),C(v(" Identity and team come from the key. Not a seat: no key refresh here, and no seat health report."));else switch(U("Personal key"),_X(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":P(" Enrolled, but no personal key is cached locally right now."),C(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:if(!t&&e.enrollment.managedPreference==="invalid"){P(` Your organization pushed Anyray enrollment settings to this machine, but they can't be used (reason: ${e.enrollment.managedPreferenceReason}).`),C(v(" Fix: contact your admin. Nothing to run here."));break}if(e.enrollment.managedPending){P(" Enrollment is managed by your organization, but this machine holds no local enrollment state."),C(v(" Fix: none needed \u2014 it re-enrolls unattended on the next refresh; run `anyray-connect refresh` to do it now."));break}P(" Enrollment required \u2014 no personal gateway key is available."),C(v(` Fix: ${Ww(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?P(` 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&&(U("Shell"),D(" This terminal still exports Anyray, but the config is gone."),C(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),C(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),C(v(" Anything you start from this terminal keeps reaching the gateway with")),C(v(" no credential, and fails with 401.")),C(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),C(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),C(v(" reuses the environment it captured at launch, so a new terminal")),C(v(" (or Reload Window) keeps serving the old one.")));let n=e.tools.find(l=>l.installed&&l.claudeCodeHookPolicy!==void 0&&l.claudeCodeHookPolicy!=="fine");if(n?.claudeCodeHookPolicy){let l={state:n.claudeCodeHookPolicy};U("Claude Code hook policy"),D(` ${kl(l)}.`),C(v(` ${vl(l)}`))}if(e.tools.some(l=>l.id===ho&&l.installed)){U("Claude Desktop profile");let l=kI[e.claudeDesktopConfigCarry];switch(e.claudeDesktopConfigCarry){case"carried":B(` ${l}.`);break;case"pending":P(` ${l}.`),C(v(" Connect completes it on the next reconcile, or the next time Claude Desktop is fully quit."));break;case"unreadable":P(` ${l}.`),C(v(" Allow Connect to read the first-party Claude Desktop profile, then run doctor again."));break;case"nothing_to_carry":case"not_routed":case"unsupported":case"unknown":C(v(` ${l}.`));break}e.claudeDesktopRunningProbe==="failed"&&(P(" Could not tell whether Claude Desktop is running: the process probe failed."),C(v(" Queued copies wait until the probe answers; check that pgrep (macOS) or tasklist (Windows) runs from this account.")))}U("Tools");let r=!1,o=!1,a=l=>{for(let d of l.routingOverrides??[])D(` ${l.title}: ${d.problem}.`),C(v(` ${d.fix}`))},s=l=>{l.mcp&&(l.mcp.registered?l.mcp.commandOk===!1?(D(` ${l.title}: retrieval MCP server registered, but its binary is gone (${l.mcp.command}).`),C(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):B(` ${l.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(P(` ${l.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),C(v(` Fix: ${PX(l)}`))))};for(let l of e.tools){if(!l.installed){C(v(` ${l.title}: not installed (skipped)`));continue}if(l.pointedAt===null){C(v(` ${l.title}: installed (config not introspectable)`)),s(l);continue}if(l.pointedAt){if(r=!0,l.id==="cursor"&&l.nativeSubscription){B(` ${l.title}: native Cursor subscription; Anyray hooks/MCP active`),C(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),s(l);continue}B(` ${l.title}: pointed at ${e.gateway.origin}`),a(l),l.id==="claude-code"&&C(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.")),l.id===ho&&C(v(` ${sS(Ot("migrate"),Ot("desktop"))}`)),l.id==="codex"&&C(v(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),s(l)}else{a(l);let d=JO(l);if(d==="not-routed"||d==="unverifiable"){let u=$u(d,{...l.inferenceUnverifiableReason?{reason:l.inferenceUnverifiableReason}:{},mcpRegistered:l.mcp?.registered===!0});P(` ${l.title}: ${u.headline}`);for(let p of u.detail)C(v(` ${p}`));d==="unverifiable"&&(o=!0)}else l.tombstoned?l.policyTier==="required"?(P(` ${l.title}: reverted locally against admin policy (out of compliance)`),C(v(` Re-enroll with \`anyray-connect --tools ${l.id}\`.`))):l.policyTier==="locked"?P(` ${l.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):C(v(` ${l.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${l.id}\``)):l.configuredKeyStale?(D(` ${l.title}: routed, but its stored key is not the current one \u2014 it will stop working when that key expires`),C(v(` Fix: \`anyray-connect --tools ${l.id}\`, then restart ${l.title} so it re-reads the config.`))):l.applyBlocked?(D(` ${l.title}: configured, but the last setup was refused \u2014 this tool is NOT being kept up to date`),C(v(` Its client key is frozen and will stop working when it expires. Fix: re-run \`anyray-connect --tools ${l.id}\` and read the message it prints.`))):l.routingPendingReload?(D(` ${l.title}: configured, but ${l.title} is still running the previous Anyray build`),C(v(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(D(` ${l.title}: installed but not pointed at ${e.gateway.origin}`),C(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let i=(e.repairs?.length??0)>0;if(!r&&!o&&!i&&e.problems===0&&(P(" No tools are pointed at this gateway yet."),C(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){U("Queued operations");for(let l of e.pendingOps){let d=qe(l.adapter)?.title??l.adapter;l.watcherAlive?P(` ${d} ${l.op} queued since ${l.requestedAt} \u2014 completes automatically when ${d} quits.`):(D(` ${d} ${l.op} queued since ${l.requestedAt}, but its watcher is not running.`),C(v(` Fix: quit ${d} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){U("Ambient repairs");let l=d=>d==="hook_registration"?"hook re-installed":d==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let d of e.ambientRepairs){let u=qe(d.tool)?.title??d.tool,p=d.repaired.map(({checkId:f,at:h})=>`${l(f)} ${new Date(h).toISOString().slice(0,10)}`);d.flapping&&p.push(`flapping since ${new Date(d.flapping.since).toISOString().slice(0,10)} (${d.flapping.reason})`);let m=` ${u}: ${p.join("; ")}`;d.flapping?P(m):C(m)}}let c=e.fleetPlan;if(c&&(c.freshIds.length>0||c.tombstonedIds.length>0)){U("Fleet policy");let l=d=>d.map(u=>qe(u)?.title??u).join(", ");c.freshIds.length>0&&C(` Pending enrollment (the next policy sync applies): ${l(c.freshIds)}`),c.tombstonedIds.length>0&&P(` Out of compliance (reverted against required policy): ${l(c.tombstonedIds)}`)}if(e.verify)if(U("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{D(` ${e.verify.kind}: ${e.verify.detail}`);for(let l of e.verify.remedy)C(v(` ${l}`))}if(e.retrieval)if(U("Retrieval loop"),e.retrieval.kind==="ok")B(` ${e.retrieval.detail}`);else{D(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let l of e.retrieval.remedy)C(v(` ${l}`))}if(e.hookLane){if(U("Hook lane"),e.hookLane.verdict==="live")B(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){D(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let l of e.hookLane.remedy)C(v(` ${l}`))}else{P(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let l of e.hookLane.remedy)C(v(` ${l}`))}e.hookLane.lastInvokedAt!==null&&C(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"),P(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(U("VS Code Agents window"),B(` ${e.agentsWindow.detail}`)),U("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)."),C(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):D(` ${e.problems} problem(s) found \u2014 see fixes above.`)},FX=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}),WX=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!tw(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??Ns,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??rn)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=Qn((await(t.readRefreshState??Bt)().catch(()=>({}))).hookLane),l=sw(i,{hookRegistered:await zO(t.adapters??se).catch(()=>!1),neverInvoked:ow(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:pp(c)},note:d}},UX=async(e,t,n={})=>{let r=n.adapters??se,o=n.resolveTarget??Je,a=n.applyTools??en,s=await WX(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&&(Bw(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 ${Ww(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),p=[],m=[...c.notes],f=[];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}f.push(b)}p.length>0&&m.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(f,d.target),w=new Map,y=0;for(let g of h){if(p.push(g),!la(g))continue;let b=e.tools.find(O=>O.id===g.id);if(!b)continue;let k=r.find(O=>O.id===g.id),A=b.mcp;if(k?.mcpStatus)try{let O=await k.mcpStatus();A={...O,commandOk:XO(O)}}catch{}let x=Bw(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{x=await k.pointsAt(e.gateway.origin)}catch{}let _=b.routingOverrides,S=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let O=await k.runtimeDiagnostics();_=O.routingOverrides.length?O.routingOverrides:void 0,S=O.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let O=await k.routingOverrides();_=O.length?O:void 0}catch{}let I=b.configuredKeyStale;if(k?.configuredKeyIsCurrent&&t.clientKey)try{let O=await k.configuredKeyIsCurrent(t.clientKey);O!==null&&(I=!O)}catch{}let E={...b,pointedAt:x,mcp:A,...I?{configuredKeyStale:!0}:{},..._?{routingOverrides:_}:{},...S===void 0?{}:{claudeCodeHookPolicy:S}};I||delete E.configuredKeyStale,_||delete E.routingOverrides,S===void 0&&delete E.claudeCodeHookPolicy,w.set(g.id,E),y+=Fw(b)-Fw(E)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:m}},HX=e=>{U("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-")?C(v(` ${t.title}: ${t.status}`)):D(` ${t.title}: ${t.status}`);for(let t of e.notes)C(v(` ${t}`))},Pp=async(e,t={})=>{let n=await $();if(e.securityReview){if(e.json){let l;try{l=n.gateway?new URL(n.gateway).hostname:void 0}catch{}return console.log(JSON.stringify(VC({connectVersion:ZO(),...l?{gatewayHost:l}:{}}),null,2)),0}if(!e.silent){C(Z("Anyray connect \u2014 security review"));for(let l of jC())C(l?` ${l}`:"")}return 0}let r;try{r=Xn(e.gateway,n)}catch(l){return e.silent?1:e.json?(console.log(JSON.stringify({error:l.message})),1):(C(Z("Anyray connect \u2014 doctor")),D(` Gateway URL: ${l.message}`),C(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"})):(C(Z("Anyray connect \u2014 doctor")),D(" --quick skips the network probes; it cannot be combined with --verify."))),1;let o=!e.noVerify&&!e.quick,a=await $X(r,n,!!e.verify&&!e.quick,t.adapters??se,t.inferenceIntrospection??Lu,t.fleetBootstrap??bo,t.managedPreference??_w,o,t.verifyAuth??Hs,!e.quick,t.checkTray??La,t.updateStatus??ua,t.readRefreshState??Bt,t.probeHookLane??Ns,t.claudeDesktopConfigCarry??(()=>Yc({loadProfile:async()=>n,toolById:l=>(t.adapters??se).find(d=>d.id===l)})),t.claudeDesktopRunningProbe??py(),t.isRefreshSchedulerInstalled??_n),s=e.repair?await UX(a,n,t):void 0,i=s?{...a,tools:a.tools.map(l=>s.refreshedTools.get(l.id)??l),...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(FX(i),null,2)):(BX(i,n.managedEnrollmentDisabled===!0),s&&HX(s)));let c=i.identity.keyKind!=="service";try{!e.quick&&c&&await(t.reportHealth??aR)(YO(i),i.connect.version)}catch{}return i.problems===0?0:1};var qO=async e=>{let t=await $();C(Z("Anyray connect \u2014 sync"));let n;try{n=Xn(e.gateway,t)}catch(i){return D(i.message),1}M(`Gateway: ${n}`);let r=TE(t.clientKey,"anyray-placeholder"),o;try{o=await ma(n,r)}catch(i){return D(`Team policy sync failed: ${Ts(i)}`),1}let{summary:a,dirs:s}=await zg(o);if(s.length===0)M("No managed tool exposes a skills directory \u2014 nothing to sync.");else if(o.skills.length===0&&a.removed.length===0)M("No team skills published yet \u2014 nothing to sync.");else{U("Skills");for(let i of a.results)i.written?B(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):M(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);for(let i of a.removed)M(` ${i} \u2014 removed (no longer published)`);o.skillsIncomplete&&M(" The gateway could not read every skills store; nothing was removed this run."),U("Summary"),C(` ${st(String(a.changed))} updated, ${a.unchanged} unchanged, ${a.removed.length} removed, across ${s.length} tool dir(s).`)}try{let i=await qg(o);i.changed.length>0&&C(`Org connectors: ${i.served?"registered":"removed"} the anyray-org MCP entry in ${i.changed.join(", ")}.`)}catch(i){M(`Org connectors sync skipped: ${Ts(i)}`)}try{let i=await Ps(o);(i.routingUpdated||i.teamUpdated||i.toolsRequested>0||i.toolsTombstoned.length>0)&&(C(`Fleet policy: routing ${i.routingUpdated?"updated":"unchanged"}, team ${i.teamUpdated?"updated":"unchanged"}, ${i.toolsApplied}/${i.toolsRequested} tool(s) reconciled${i.toolsEnrolled>0?` (${i.toolsEnrolled} newly enrolled)`:""}.`),i.toolsTombstoned.length>0&&M(` Locally reverted against admin policy (out of compliance): ${i.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(i){M(`Fleet policy reconcile skipped: ${Ts(i)}`)}return 0};import{gzip as j5}from"node:zlib";import{promisify as Y5}from"node:util";var vo={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Uw=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),QO=e=>`
|
|
807
807
|
|
|
808
808
|
\u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
|
|
809
809
|
|
|
810
|
-
`,Dp=(e,t={})=>{if(typeof e!="string")return Uw(String(e??""));let n=Math.max(1,t.maxChars??vo.maxChars);if(e.length<=n)return Uw(e);let r=e.length,o=Math.max(0,t.headChars??vo.headChars),a=Math.max(0,t.tailChars??vo.tailChars),s=Math.max(0,t.middleWindows??vo.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),A=Math.min(d,Math.max(l,k)+Math.ceil(g/2)),
|
|
811
|
-
`,
|
|
812
|
-
`,A);S!==-1&&S<d&&(A=S),A>
|
|
810
|
+
`,Dp=(e,t={})=>{if(typeof e!="string")return Uw(String(e??""));let n=Math.max(1,t.maxChars??vo.maxChars);if(e.length<=n)return Uw(e);let r=e.length,o=Math.max(0,t.headChars??vo.headChars),a=Math.max(0,t.tailChars??vo.tailChars),s=Math.max(0,t.middleWindows??vo.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),A=Math.min(d,Math.max(l,k)+Math.ceil(g/2)),x=Math.max(l,A-g),_=e.lastIndexOf(`
|
|
811
|
+
`,x);_>=l&&(x=_+1);let S=e.indexOf(`
|
|
812
|
+
`,A);S!==-1&&S<d&&(A=S),A>x&&u.push([x,A])}}a>0&&u.push([d,r]),u.sort((y,g)=>y[0]-g[0]);let m=[];for(let[y,g]of u){let b=m[m.length-1];b&&y<=b[1]?b[1]=Math.max(b[1],g):m.push([y,g])}let f="",h=0;for(let[y,g]of m)y>h&&(f+=QO(y-h)),f+=e.slice(y,g),h=g;if(r>h&&(f+=QO(r-h)),f.length>=r)return Uw(e);let w=r-f.length;return{text:f,trimmed:!0,originalChars:r,trimmedChars:f.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},GX=["stdout","content","output","text","result"],e_=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} ---
|
|
813
813
|
${d}`);s&&i.push(`--- MCP structuredContent ---
|
|
814
814
|
${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
|
|
815
815
|
|
|
@@ -830,22 +830,22 @@ ${e.slice(-Hw)}`:e;return n5.some(n=>n.test(t))},o5=e=>/^[=~_—-]{4,}$/.test(e)
|
|
|
830
830
|
`).slice(0,E_)};var G5=e=>/(^|[\\/])subagents[\\/]/i.test(e),K5=e=>/\.jsonl$/i.test(e),V5=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),x_=async e=>{let t={intent:"",kind:"unknown"};if(!e||!K5(e))return t;let n;try{let{size:r}=await $5(e),o=Math.max(0,r-B5),a=r-o;if(a<=0)return t;n=await N5(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(`
|
|
831
831
|
`);i=l>=0?i.slice(l+1):""}let c=U5(i.split(`
|
|
832
832
|
`));return V5(c)?{intent:H5(c),kind:G5(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var Z5=3e3,J5=1500,X5=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Z5},z5={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},q5=new Set(["claude","opencode"]),Q5=(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:z5[t]})},e3={cacheGet:async()=>null,cachePut:async()=>{}},t3=(e,t={cacheGet:S_,cachePut:I_,tee:y_})=>e==="claude"?t:e3,n3=1e3,r3=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),Bp=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),o3=e=>{try{let t=JSON.parse(e);if(!Bp(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 Bp(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},a3=e=>{try{let t=JSON.parse(e);return Bp(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},s3=e=>Bp(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
833
|
-
`:"",Qw=e=>Math.round(Math.max(0,e)/4),R_=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",i3=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),c3=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),l3=["tool_output","tool_response","tool_result"],d3=e=>{for(let t of l3)if(t in e)return e[t]},u3=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},p3=120,f3=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??n3))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=Kw(r.stat,null).length+p3;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=Kw(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}}},m3=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let
|
|
834
|
-
${R_(r.tool_input)}`:R_(r.tool_input),y=k_(o,w,u),g=async
|
|
833
|
+
`:"",Qw=e=>Math.round(Math.max(0,e)/4),R_=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",i3=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),c3=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),l3=["tool_output","tool_response","tool_result"],d3=e=>{for(let t of l3)if(t in e)return e[t]},u3=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},p3=120,f3=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??n3))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=Kw(r.stat,null).length+p3;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=Kw(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}}},m3=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let x=JSON.parse(e);if(!x||typeof x!="object")return n;r=x}catch{return n}let o=typeof r.tool_name=="string"?r.tool_name:"unknown";if(i3.has(o)||c3(o))return n;let a=e_(d3(r));if(!a)return n;let s=async x=>{try{await t.beacon(o,x)}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(O_(o)&&l.retrievalContext!=="available")return n;let d=await f3(t,u3(o,r.tool_input),i),u=d?.body??i,p=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!Lp(i,{minChars:J5})))return n;let m=i.length-u.length-p.length,f=async(x,_,S=x.length+p.length)=>{let I=d?.teePath??null;if(!I&&t.tee)try{I=await t.tee(i)}catch{I=null}let E=I?x.replaceAll("; not retrievable in this context]","]"):x,O=I&&!p?c_(I):"",K=E+p+O,G=O.length,X=K;if(t.finalizeOutput)try{let W=t.finalizeOutput(K);W.length<=K.length&&(X=W)}catch{X=K}let re=K.length-X.length,ke=Qw(Math.max(0,m-G))+_+Qw(re);ke>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,S+G-re),estTokensSaved:ke,...d&&{digest:d.decision}});let fe=a.rebuild(X);return{stdout:r3(fe),replacement:fe}},h=async()=>d?f(u,0):n;if(d&&u.length<=t.sizeGate)return f(u,0);let w=l.intent?`${l.intent}
|
|
834
|
+
${R_(r.tool_input)}`:R_(r.tool_input),y=k_(o,w,u),g=async x=>{try{await t.cachePut(y,x)}catch{}},b=null;try{b=await t.cacheGet(y)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?f(b.output,b.tokensSaved):h();let k=null;try{k=C3(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:Qw(u.length-k.output.length)}),f(k.output,0,u.length+p.length)):(await g({optimized:!1}),h());let A;try{A=t.localTrim(u)}catch{return h()}return A.trimmed?f(A.text,A.estTokensSaved):h()},qc=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},h3=()=>{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")}},y3=Y5(j5),g3=async e=>{try{let t=await y3(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},O_=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),w3=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},b3=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),C3=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),A3=2048,k3=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,A3),n=up(t);if(!n)return;await _R({at:Date.now(),status:e.status,code:n})}catch{}},v3=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),X5());try{let c=await g3(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...O_(t)||w3(t)&&a==="available"?{reversible:!0}:{},...b3(t)?{semanticRerank:!0}:{},output:r})),l=dn(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 k3(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)}},__=async(e="claude")=>{let t=await qc();if(e!=="cursor"&&a3(t))return 0;let n=e==="cursor"?o3(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await eb(n,e);if(e==="cursor"){let a=s3(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},eb=async(e,t="claude",n)=>{await Ao(),await OR(t);let r=h3(),o=await ut(),a=o&&{...o,metadata:Q5(o.metadata,t)},s=t3(t);return m3(e,{optimize:(i,c,l,d,u)=>v3(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await x_(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>Dp(i,r),beacon:(i,c)=>Il(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??vo.maxChars,digestCommand:s_,tee:s.tee,mediumBand:q5.has(t),finalizeOutput:n})};var T_=async()=>0;import{spawn as S3}from"node:child_process";import{homedir as I3}from"node:os";import{join as E3}from"node:path";var x3=3e4,R3=5*6e4,O3=30*6e4,_3=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},T3=()=>E3(I3(),".claude","settings.json"),P3=async e=>{try{let n=(await F(T3())).env;if(!n)return!1;let r=En(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}},D3=async e=>{await Zr.apply(e,{dryRun:!1})},L3=()=>{let{command:e,args:t}=Jr("__anyray-sso-poll");return{exe:e,args:t}},N3=()=>{let{exe:e,args:t}=L3(),n=S3(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))}}},$3=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},P_=(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}),Gs=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},D_=e=>`Anyray: one-time sign-in required to use AI tools on this device.
|
|
835
835
|
1. Open ${e.verificationUriComplete}
|
|
836
836
|
2. Confirm code ${e.userCode}
|
|
837
837
|
Your prompt was not sent \u2014 complete sign-in, then resubmit it.
|
|
838
838
|
`,tb=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
|
|
839
839
|
`:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
|
|
840
840
|
`:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
|
|
841
|
-
`,M3=e=>Math.min(R3,x3*2**Math.max(0,e-1)),B3=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?O3:M3(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},
|
|
842
|
-
`))}let re;await h();let ke=(t.resolveMachineUuid??nn)()||void 0;try{re=await d(S,b.enrolledCert,A,{timeoutMs:1e4,machineUuid:ke})}catch(fe){if(!(fe instanceof it))return
|
|
841
|
+
`,M3=e=>Math.min(R3,x3*2**Math.max(0,e-1)),B3=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?O3:M3(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},ka=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??$,o=t.saveProfile??de,a=t.loadDevKey??Ye,s=t.readGateState??Us,i=t.writeGateState??Rp,c=t.isProcessAlive??MO,l=t.startGrant??op,d=t.verify??An,u=t.routingIntact??P3,p=t.applyClaudeCode??D3,m=t.maybeSpawnRefresh??Ao,f=t.recordMint??$s,h=t.reserveMint??ga,w=t.spawnPoller??N3,y=t.openBrowser??Rr;try{let g=Mt(e.sso);if(!g)return{exitCode:0};let b=await r(),k=await s(),A=b.enrolledCert?await a():void 0,x=$3(b),_=!!(b.enrolledCert&&A)&&Number.isFinite(x)&&x>n(),S=e.gateway??b.gateway;if(_&&b.enrolledCert&&A&&S){let G=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(G)&&G>n()&&b.clientKey){let fe=P_(S,b,e.team,b.clientKey);return await u(fe)?(G-n()<=uw()&&await m(),{exitCode:0}):(await p(fe),Gs(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
|
|
842
|
+
`))}let re;await h();let ke=(t.resolveMachineUuid??nn)()||void 0;try{re=await d(S,b.enrolledCert,A,{timeoutMs:1e4,machineUuid:ke})}catch(fe){if(!(fe instanceof it))return Gs(e,tb("gateway-unreachable",g.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(re){let fe={...b,gateway:S,name:re.user,team:e.team??re.team??b.team,clientKey:re.key,clientKeyExpiresAt:re.expiresAt,authMode:"subscription"};return await o(fe),await f({expiresAt:re.expiresAt}),await p(P_(S,fe,e.team,re.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 Gs(e,D_(k))}if(k){let G=B3(k,n());if(G)return Gs(e,tb(G,g.cpOrigin))}let I;try{I=await l({cpOrigin:g.cpOrigin,tenantId:g.tenantId,gatewayUrl:e.gateway,now:n})}catch(G){let X=G instanceof wt?G.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:k?.lastFailure===X?(k.failureCount??0)+1:1,lastFailure:X}),Gs(e,tb(X,g.cpOrigin))}let E={v:1,status:"pending",userCode:I.userCode,verificationUriComplete:I.verificationUriComplete,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,lastAttemptAt:n(),failureCount:0};await i(E);let O=w(),K={...E,pollerPid:O.pid};if(await i(K),O.handoff({deviceCode:I.deviceCode,privateKeyPem:I.privateKeyPem,publicKeyPem:I.publicKeyPem,cpOrigin:I.cpOrigin,tenantId:I.tenantId,intervalMs:I.intervalMs,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,gatewayUrl:I.gatewayUrl,gatewayOverride:e.gateway,team:e.team,priorCertSig:b.enrolledCert?.sig}),e.sessionStart)try{y(I.verificationUriComplete)}catch{}return Gs(e,D_(K))}catch{return{exitCode:0}}},F3=async()=>{try{for await(let e of process.stdin);}catch{}},L_=async e=>{await F3();try{let t=await ka(_3(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var W3=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},U3=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??bo)();if(!r)return;let o=await(t.ssoGate??ka)({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})}
|
|
843
843
|
`}catch{return}},H3=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},G3=()=>{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")}},K3=(e,t)=>{let n=t.minChars??Zc.minChars,r={maxChars:Math.min(vo.maxChars,n)},o=Dp(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},N_=async()=>{let e=await H3(),t=await U3(e);t&&process.stdout.write(t);let n=G3(),r=await ut();return await W3(e,{isPaste:o=>Lp(o,n),measure:o=>K3(o,n),beacon:o=>Il(r,"prompt",o)}),0};import{spawn as V3}from"node:child_process";var $_=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),j3=/[|&;<>`$()\n]/,M_=e=>{if(j3.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},Y3=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!$_(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!$_(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(Ef)||!t.isRecognized(o)||M_(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},Z3=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?M_(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
|
|
844
844
|
`),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
|
|
845
|
-
`),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},J3=16*1024*1024,X3=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=V3(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>J3){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)}}),z3=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await eb(n,"cursor");return typeof r=="string"?r:t},B_=e=>{let t=e[0]==="--b64"?e[1]:void 0;return Z3(t,{exec:X3,trim:z3,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},F_=async()=>{let e=await qc();if(process.platform==="win32")return 0;let t=Y3(e,{isRecognized:n=>Gw(n)!==null||o_(n),wrap:n=>Ht(Ef,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as q3}from"node:crypto";import{homedir as W_}from"node:os";import{extname as Q3,isAbsolute as ez,join as nb,resolve as Qc,sep as U_}from"node:path";import{chmod as tz,readFile as nz,stat as j_,unlink as rz,writeFile as oz}from"node:fs/promises";var ob=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),az=16*1024,H_=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],sz=["pattern","query","regex","search"],iz=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"]),cz=720*60*1e3,lz=512,rb=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},dz=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],G_=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(U_)?n:n+U_)),uz=(e,t,n)=>ez(e)?[Qc(e)]:[...new Set([Qc(t,e),...n.map(r=>Qc(r,e))])],K_=(e,t,n)=>q3("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),V_=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),pz=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!ob(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!ob(o))return"";let a=dz(n.workspace_roots).map(d=>Qc(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=rb(o,sz);if(!d)return"";let u=rb(o,H_);return u&&!G_(Qc(s,u),a)||!await t.remember(K_(i,"Grep",d))?"":V_(`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=rb(o,H_);if(!c||iz.has(Q3(c).toLowerCase()))return"";let l=await t.resolveFile(uz(c,s,a));return!l||l.bytes<az||!G_(l.path,a)||!await t.remember(K_(i,"Read",l.path))?"":V_(`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.`)},fz=async e=>{for(let t of e)try{let n=await j_(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},mz=async()=>{let e=nb(W_(),".anyray");try{if((await j_(e)).isDirectory())return nb(e,"cursor-redirects.json")}catch{}return nb(W_(),".anyray-cursor-redirects.json")},hz=async e=>{let t;try{let n=await mz(),r=Date.now(),o={};try{let s=JSON.parse(await nz(n,"utf-8"));if(s?.v===1&&ob(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=cz&&(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,lz);return t=`${n}.${process.pid}.tmp`,await oz(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await tz(t,384),await Ae(t,n),!0}catch{if(t)try{await rz(t)}catch{}return!1}},Y_=async()=>{let e=await qc(),t="";try{t=await pz(e,{resolveFile:fz,remember:hz})}catch{t=""}return t&&process.stdout.write(t),0};import{execFileSync as yz}from"node:child_process";var J_=new Set(["darwin","win32","linux"]),gz=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),wz=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!gz.has(t)},Fp=async(e,t={})=>{try{if(!J_.has(e.platform)||e.isUserSession?.()===!1||(await e.loadProfile()).managedEnrollmentDisabled===!0)return 0;let r=e.readManagedEnrollment().enrollmentUrl;return r?await e.runApply(["--enroll",r,"--yes",...t.json?["--json"]:[]]):0}catch{return 1}},X_=async(e,t)=>{if(e!=="not-enrolled")return e;try{return!t.readManagedEnrollment().enrollmentUrl||(await t.loadProfile()).managedEnrollmentDisabled===!0||await Fp(t)!==0?e:await t.refresh()}catch{return e}},Z_=async(e,t=se)=>{let n=new Set(e.managedTools??[]),r=[];for(let o of t)if(!n.has(o.id)&&!jr(o))try{(await o.detect()).installed&&r.push(o.id)}catch{}return r},bz=e=>new Date(e).toISOString().slice(0,10),z_=async e=>{try{if(!J_.has(e.platform)||e.isUserSession?.()===!1||!e.readManagedEnrollment().enrollmentUrl)return!1;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return!1;let n=bz((e.now??Date.now)());if(t.managedToolAdoptDay===n)return!1;let r=await Z_(t,e.adapters);if(r.length===0)return!1;let o=e.saveProfile??de;if(await o({...await e.loadProfile(),managedToolAdoptDay:n}),await Fp(e)!==0)return!1;let a=await e.loadProfile(),s=await Z_(a,e.adapters);if(r.some(l=>s.includes(l)))return!0;let{managedToolAdoptDay:i,...c}=a;return await o(c),!0}catch{return!1}},Wp=e=>({platform:process.platform,readManagedEnrollment:Kc,loadProfile:$,isUserSession:()=>{try{if(process.platform==="win32"){let t=yz(wg,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return wz(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var el=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Up=e=>typeof e=="string"&&e.trim()?e.trim():void 0,Cz=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=el(n,"deviceCode"),o=el(n,"privateKeyPem"),a=el(n,"publicKeyPem"),s=el(n,"cpOrigin"),i=el(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=Up(n.gatewayUrl),p=Up(n.gatewayOverride),m=Up(n.team),f=Up(n.priorCertSig);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...p?{gatewayOverride:p}:{},...m?{team:m}:{},...f?{priorCertSig:f}:{}}}catch{return null}},Az=e=>new Promise(t=>setTimeout(t,e)),kz=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})},vz=async(e,t={})=>{let n=t.poll??ap,r=t.verify??An,o=t.loadProfile??$,a=t.saveProfile??de,s=t.saveDevKey??ll,i=t.withProfileLock??Br,c=t.readGateState??Ws,l=t.writeGateState??Rp,d=t.clearGateState??Vc,u=t.sleep??Az,p=t.now??Date.now,m=t.recordMint??Ns,f=t.reserveMint??ya,h=t.applyClaudeCode??(async _=>{await Zr.apply(_,{dryRun:!1})}),w=_=>kz(_,{readGateState:c,writeGateState:l,now:p}),y={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g=async()=>{let _=await c();return _?.status!=="pending"||_.startedAt!==e.startedAt},b;try{b=await n(y,{gatewayUrl:e.gatewayOverride})}catch(_){if(await g())return"superseded";let K=_ instanceof Rt?_.kind:"cp-unreachable";return await w(K),K}if(await g())return"superseded";let k=_=>_.enrolledCert!==void 0&&_.enrolledCert.sig!==b.cert.sig&&_.enrolledCert.sig!==e.priorCertSig,A=e.gatewayOverride??b.gatewayUrl,E=_=>({..._,gateway:A??_.gateway,name:b.cert.payload.user||_.name,team:e.team??b.cert.payload.team??_.team,enrolledCert:b.cert,enrolledCertExpiry:b.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"}),O;try{O=await i(async()=>{let _=await o();if(k(_))return;let K=E(_);return await s(b.privateKeyPem),await a(K),K})}catch{return"failed"}if(!O)return"superseded";if(!A)return await w("gateway-unreachable"),"gateway-unreachable";let S;await f();let I=(t.resolveMachineUuid??nn)()||void 0;for(let _=0;_<3;_++)try{S=await r(A,b.cert,b.privateKeyPem,{timeoutMs:1e4,machineUuid:I});break}catch(K){if(K instanceof it||_===2)break;await u(1e3)}if(!S)return await w("gateway-unreachable"),"gateway-unreachable";let x={...O,gateway:A,name:S.user,team:e.team??S.team??O.team,clientKey:S.key,clientKeyExpiresAt:S.expiresAt,authMode:"subscription"};try{if(!await i(async()=>k(await o())?!1:(await a(x),!0)))return"superseded";await m({expiresAt:S.expiresAt});let K=xe({origin:A,clientKey:S.key,subscription:!0,user:x.name,team:x.team});return await h(K),await d(),"enrolled"}catch{return await w("gateway-unreachable"),"failed"}},Sz=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},q_=async()=>{let e=Cz(await Sz());if(e)try{await vz(e)}catch{}return 0};var Iz=3e3,Q_=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>cg(Iz)),o=e.updateStatus??da;t(`anyray-connect ${Ne}
|
|
846
|
-
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&
|
|
845
|
+
`),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},J3=16*1024*1024,X3=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=V3(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>J3){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)}}),z3=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await eb(n,"cursor");return typeof r=="string"?r:t},B_=e=>{let t=e[0]==="--b64"?e[1]:void 0;return Z3(t,{exec:X3,trim:z3,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},F_=async()=>{let e=await qc();if(process.platform==="win32")return 0;let t=Y3(e,{isRecognized:n=>Gw(n)!==null||o_(n),wrap:n=>Ht(Ef,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as q3}from"node:crypto";import{homedir as W_}from"node:os";import{extname as Q3,isAbsolute as ez,join as nb,resolve as Qc,sep as U_}from"node:path";import{chmod as tz,readFile as nz,stat as j_,unlink as rz,writeFile as oz}from"node:fs/promises";var ob=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),az=16*1024,H_=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],sz=["pattern","query","regex","search"],iz=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"]),cz=720*60*1e3,lz=512,rb=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},dz=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],G_=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(U_)?n:n+U_)),uz=(e,t,n)=>ez(e)?[Qc(e)]:[...new Set([Qc(t,e),...n.map(r=>Qc(r,e))])],K_=(e,t,n)=>q3("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),V_=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),pz=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!ob(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!ob(o))return"";let a=dz(n.workspace_roots).map(d=>Qc(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=rb(o,sz);if(!d)return"";let u=rb(o,H_);return u&&!G_(Qc(s,u),a)||!await t.remember(K_(i,"Grep",d))?"":V_(`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=rb(o,H_);if(!c||iz.has(Q3(c).toLowerCase()))return"";let l=await t.resolveFile(uz(c,s,a));return!l||l.bytes<az||!G_(l.path,a)||!await t.remember(K_(i,"Read",l.path))?"":V_(`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.`)},fz=async e=>{for(let t of e)try{let n=await j_(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},mz=async()=>{let e=nb(W_(),".anyray");try{if((await j_(e)).isDirectory())return nb(e,"cursor-redirects.json")}catch{}return nb(W_(),".anyray-cursor-redirects.json")},hz=async e=>{let t;try{let n=await mz(),r=Date.now(),o={};try{let s=JSON.parse(await nz(n,"utf-8"));if(s?.v===1&&ob(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=cz&&(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,lz);return t=`${n}.${process.pid}.tmp`,await oz(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await tz(t,384),await Ae(t,n),!0}catch{if(t)try{await rz(t)}catch{}return!1}},Y_=async()=>{let e=await qc(),t="";try{t=await pz(e,{resolveFile:fz,remember:hz})}catch{t=""}return t&&process.stdout.write(t),0};import{execFileSync as yz}from"node:child_process";var J_=new Set(["darwin","win32","linux"]),gz=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),wz=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!gz.has(t)},Fp=async(e,t={})=>{try{if(!J_.has(e.platform)||e.isUserSession?.()===!1||(await e.loadProfile()).managedEnrollmentDisabled===!0)return 0;let r=e.readManagedEnrollment().enrollmentUrl;return r?await e.runApply(["--enroll",r,"--yes",...t.json?["--json"]:[]]):0}catch{return 1}},X_=async(e,t)=>{if(e!=="not-enrolled")return e;try{return!t.readManagedEnrollment().enrollmentUrl||(await t.loadProfile()).managedEnrollmentDisabled===!0||await Fp(t)!==0?e:await t.refresh()}catch{return e}},Z_=async(e,t=se)=>{let n=new Set(e.managedTools??[]),r=[];for(let o of t)if(!n.has(o.id)&&!jr(o))try{(await o.detect()).installed&&r.push(o.id)}catch{}return r},bz=e=>new Date(e).toISOString().slice(0,10),z_=async e=>{try{if(!J_.has(e.platform)||e.isUserSession?.()===!1||!e.readManagedEnrollment().enrollmentUrl)return!1;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return!1;let n=bz((e.now??Date.now)());if(t.managedToolAdoptDay===n)return!1;let r=await Z_(t,e.adapters);if(r.length===0)return!1;let o=e.saveProfile??de;if(await o({...await e.loadProfile(),managedToolAdoptDay:n}),await Fp(e)!==0)return!1;let a=await e.loadProfile(),s=await Z_(a,e.adapters);if(r.some(l=>s.includes(l)))return!0;let{managedToolAdoptDay:i,...c}=a;return await o(c),!0}catch{return!1}},Wp=e=>({platform:process.platform,readManagedEnrollment:Kc,loadProfile:$,isUserSession:()=>{try{if(process.platform==="win32"){let t=yz(wg,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return wz(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var el=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Up=e=>typeof e=="string"&&e.trim()?e.trim():void 0,Cz=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=el(n,"deviceCode"),o=el(n,"privateKeyPem"),a=el(n,"publicKeyPem"),s=el(n,"cpOrigin"),i=el(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=Up(n.gatewayUrl),p=Up(n.gatewayOverride),m=Up(n.team),f=Up(n.priorCertSig);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...p?{gatewayOverride:p}:{},...m?{team:m}:{},...f?{priorCertSig:f}:{}}}catch{return null}},Az=e=>new Promise(t=>setTimeout(t,e)),kz=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})},vz=async(e,t={})=>{let n=t.poll??ap,r=t.verify??An,o=t.loadProfile??$,a=t.saveProfile??de,s=t.saveDevKey??ll,i=t.withProfileLock??Br,c=t.readGateState??Us,l=t.writeGateState??Rp,d=t.clearGateState??Vc,u=t.sleep??Az,p=t.now??Date.now,m=t.recordMint??$s,f=t.reserveMint??ga,h=t.applyClaudeCode??(async O=>{await Zr.apply(O,{dryRun:!1})}),w=O=>kz(O,{readGateState:c,writeGateState:l,now:p}),y={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g=async()=>{let O=await c();return O?.status!=="pending"||O.startedAt!==e.startedAt},b;try{b=await n(y,{gatewayUrl:e.gatewayOverride})}catch(O){if(await g())return"superseded";let K=O instanceof Rt?O.kind:"cp-unreachable";return await w(K),K}if(await g())return"superseded";let k=O=>O.enrolledCert!==void 0&&O.enrolledCert.sig!==b.cert.sig&&O.enrolledCert.sig!==e.priorCertSig,A=e.gatewayOverride??b.gatewayUrl,x=O=>({...O,gateway:A??O.gateway,name:b.cert.payload.user||O.name,team:e.team??b.cert.payload.team??O.team,enrolledCert:b.cert,enrolledCertExpiry:b.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"}),_;try{_=await i(async()=>{let O=await o();if(k(O))return;let K=x(O);return await s(b.privateKeyPem),await a(K),K})}catch{return"failed"}if(!_)return"superseded";if(!A)return await w("gateway-unreachable"),"gateway-unreachable";let S;await f();let I=(t.resolveMachineUuid??nn)()||void 0;for(let O=0;O<3;O++)try{S=await r(A,b.cert,b.privateKeyPem,{timeoutMs:1e4,machineUuid:I});break}catch(K){if(K instanceof it||O===2)break;await u(1e3)}if(!S)return await w("gateway-unreachable"),"gateway-unreachable";let E={..._,gateway:A,name:S.user,team:e.team??S.team??_.team,clientKey:S.key,clientKeyExpiresAt:S.expiresAt,authMode:"subscription"};try{if(!await i(async()=>k(await o())?!1:(await a(E),!0)))return"superseded";await m({expiresAt:S.expiresAt});let K=xe({origin:A,clientKey:S.key,subscription:!0,user:E.name,team:E.team});return await h(K),await d(),"enrolled"}catch{return await w("gateway-unreachable"),"failed"}},Sz=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},q_=async()=>{let e=Cz(await Sz());if(e)try{await vz(e)}catch{}return 0};var Iz=3e3,Q_=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>cg(Iz)),o=e.updateStatus??ua;t(`anyray-connect ${Ne}
|
|
846
|
+
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&As(a,Ne)>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: ${Ne} \u2192 ${a}
|
|
847
847
|
${i}
|
|
848
|
-
`)}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 Ez=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},xz=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),Rz=async(e={})=>{try{let t=await(e.readBootstrap??bo)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??rn)().catch(()=>{});let n=await(e.loadProfile??$)();if(Pe(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??
|
|
848
|
+
`)}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 Ez=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},xz=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),Rz=async(e={})=>{try{let t=await(e.readBootstrap??bo)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??rn)().catch(()=>{});let n=await(e.loadProfile??$)();if(Pe(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??ka)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??$)(),Pe(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Us)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!Ez(a)||!xz(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"}}},eT=async(e={})=>{let t=await Rz(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
849
849
|
`),0};import Oz from"node:path";var _z="2025-06-18",Tz={name:"anyray",version:"1"},tT={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,nT={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}},iT=Rg,Dz=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,iT)},Lz=e=>e==="paths"||e==="lines"||e==="full"?e:"full",rT={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-${iT}). 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}},oT={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}},Nz=8,$z=3,aT={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}},Mz=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(`
|
|
850
850
|
`)},Bz=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
851
851
|
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,Nz).map(([a,s])=>{let i=s.slice(0,$z).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
@@ -857,17 +857,17 @@ If the user expected one, their export may predate it, or no export has been imp
|
|
|
857
857
|
[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(`
|
|
858
858
|
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},cT=e=>{try{e.heartbeat?.().catch(()=>{})}catch{}},Fz=async(e,t)=>{let n=e?.id,r=n===void 0,o=typeof e?.method=="string"?e.method:"";switch(o){case"initialize":return cT(t),Re(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:_z,capabilities:{tools:{}},serverInfo:Tz});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Re(n??null,{});case"tools/list":{let a=[tT,nT];t.advertiseContextTools!==!1&&a.push(rT,oT);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(aT),Re(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===tT.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Re(n??null,Ie("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 Re(n??null,Ie("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return Re(n??null,Ie("grep must be non-empty",!0));if(s.grep.length>256)return Re(n??null,Ie("grep is limited to 256 characters",!0));u=s.grep}let p=l!==void 0||d!==void 0||u!==void 0,m=Xw(i);if(m){let w=await zw(m);if(u!==void 0)return Re(n??null,Ie(`${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(m,{startLine:l,endLine:d}).catch(b=>({ok:!1,content:"",path:w??m,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 Re(n??null,Ie(`[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.]
|
|
859
859
|
`+y.content))}let g=y!==null;return Re(n??null,Ie(`${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 f;try{f=await t.retrieve(i,p?{startLine:l,endLine:d,grep:u}:void 0)}catch(w){f={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(!f.ok)return Re(n??null,Ie(f.kind==="slice-unsupported"?h:f.message,!0));if(p&&(f.partial===void 0||typeof f.totalLines!="number"))return Re(n??null,Ie(h,!0));if(f.partial===!0&&typeof f.totalLines=="number"){let w=f.grepMatches!==void 0?`[anyray: partial \u2014 ${f.grepMatches} matching line(s) in lines ${f.startLine}-${f.endLine} of ${f.totalLines}`+(f.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 ${f.startLine}-${f.endLine} of ${f.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return Re(n??null,Ie(`${w}
|
|
860
|
-
${f.content}`))}return Re(n??null,Ie(f.content))}if(a.name===nT.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Re(n??null,Ie("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 Re(n??null,l.ok?Ie(Mz(l.matches)):Ie(l.message,!0))}if(a.name===rT.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Re(n??null,Ie("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(p=>typeof p=="string"):void 0,l=Dz(s.maxResults),d=Lz(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 Re(n??null,u.ok?Ie(Hx(i,u,d)):Ie(u.message??"search failed",!0))}if(a.name===aT.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 Re(n??null,d.ok?Ie(Ig(d)):Ie(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Re(n??null,Ie("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 Re(n??null,l.ok?Ie(Bz(c,l)):Ie(l.message??"history search failed",!0))}if(a.name===oT.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Re(n??null,Ie("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 Re(n??null,l.ok?Ie(Ig(l)):Ie(l.message??"read failed",!0))}return ab(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:ab(n??null,-32601,`method not found: ${o}`)}},Wz=async(e,t=fetch)=>{if(!e)return!1;let n=new AbortController,r=setTimeout(()=>n.abort(),fp);try{return(await t(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:dn(e),signal:n.signal})).ok}catch{return!1}finally{clearTimeout(r)}},Uz=(e,t=!0)=>({retrieve:async(n,r)=>
|
|
860
|
+
${f.content}`))}return Re(n??null,Ie(f.content))}if(a.name===nT.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Re(n??null,Ie("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 Re(n??null,l.ok?Ie(Mz(l.matches)):Ie(l.message,!0))}if(a.name===rT.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Re(n??null,Ie("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(p=>typeof p=="string"):void 0,l=Dz(s.maxResults),d=Lz(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 Re(n??null,u.ok?Ie(Hx(i,u,d)):Ie(u.message??"search failed",!0))}if(a.name===aT.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 Re(n??null,d.ok?Ie(Ig(d)):Ie(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Re(n??null,Ie("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 Re(n??null,l.ok?Ie(Bz(c,l)):Ie(l.message??"history search failed",!0))}if(a.name===oT.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Re(n??null,Ie("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 Re(n??null,l.ok?Ie(Ig(l)):Ie(l.message??"read failed",!0))}return ab(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:ab(n??null,-32601,`method not found: ${o}`)}},Wz=async(e,t=fetch)=>{if(!e)return!1;let n=new AbortController,r=setTimeout(()=>n.abort(),fp);try{return(await t(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:dn(e),signal:n.signal})).ok}catch{return!1}finally{clearTimeout(r)}},Uz=(e,t=!0)=>({retrieve:async(n,r)=>Ls(await e(),n,r),recall:async(n,r)=>mp(await e(),n,r),search:(n,r,o)=>ep(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>xc(n,r),readTee:async(n,r)=>{if(Zw())return{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"the hook tee is off (ANYRAY_HOOK_TEE=off)"};let o=await zw(n);return o?{...await xc(o,{cwd:Oz.dirname(o),...r}),teePath:o}:{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"not a tee id"}},historySearch:n=>Vx(n),historyOpen:n=>jx(n),historyAvailable:async()=>await Es()>0,advertiseContextTools:t,heartbeat:async()=>{try{return await Wz(await e())}catch{return!1}}}),Hz=5*6e4,lT=async(e="auto",t={})=>{let n=Uz(()=>ut(e),e!=="claude");t.heartbeat&&(n.heartbeat=t.heartbeat);let r=t.stdin??process.stdin,o=t.stdout??process.stdout,a=0,s=t.refreshTick??(()=>{let f=Date.now();f<a||(a=f+6e4,Ao().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=f=>{try{return o.write(JSON.stringify(f)+`
|
|
861
861
|
`),!0}catch{return!1}},l,d=()=>{l||!n.heartbeat||(l=setInterval(()=>cT(n),Hz),l.unref())},u=async f=>{let h=f.trim();if(!h)return;let w;try{w=JSON.parse(h)}catch{console.error("anyray mcp: dropping unparseable frame");return}let y;try{y=await Fz(w,n)}catch(b){console.error("anyray mcp: dispatch error",sT(b)),y=w?.id===void 0?null:ab(w.id,-32603,"internal error")}let g=y?c(y):!1;w.method==="initialize"&&y&&!y.error&&g&&d(),i()};i();let p=setInterval(i,30*6e4);p.unref();let m="";try{for await(let f of r){m+=f.toString("utf-8");let h;for(;(h=m.indexOf(`
|
|
862
862
|
`))>=0;){let w=m.slice(0,h);m=m.slice(h+1),await u(w)}}m.trim()&&await u(m)}catch(f){console.error("anyray mcp: stdin error",sT(f))}finally{clearInterval(p),l&&clearInterval(l)}return 0};import{spawn as Gz}from"node:child_process";var Kz=e=>e==="jetbrains"||e==="windsurf"?e:void 0,Vz=async(e,t,n,r=1e4)=>{let o=await new Promise(a=>{let s="",i=!1,c=m=>{i||(i=!0,clearTimeout(l),t.off("data",d),t.off("error",u),t.off("end",p),a(m))},l=setTimeout(()=>c(void 0),r),d=m=>{s+=m.toString();let f=s.indexOf(`
|
|
863
863
|
`);f!==-1?c(s.slice(0,f)):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}})}
|
|
864
864
|
`),!0)}catch{return!1}},jz={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},Yz=(e,t,n)=>{let r=new Set(jz[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}},dT=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
865
865
|
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!Cu(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
866
|
-
`),1;await(n.refreshIfDue??rn)().catch(()=>{});let s=await(n.loadProfile??$)(),i=await(n.readBootstrap??bo)().catch(()=>{});if(i){let g=await(n.ssoGate??
|
|
866
|
+
`),1;await(n.refreshIfDue??rn)().catch(()=>{});let s=await(n.loadProfile??$)(),i=await(n.readBootstrap??bo)().catch(()=>{});if(i){let g=await(n.ssoGate??ka)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(g.exitCode===2&&g.stderr)return await Vz(g.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(g.stderr),1;s=await(n.loadProfile??$)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
|
|
867
867
|
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??Wn)():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=Kz(n.clientTool);u&&(d.metadata.tool=u);let p=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",m=(n.hookBinaryIsDurable??te)(),f=uE(d,t,{mcpServer:m?We("profile"):void 0})[p],h=n.spawn??Gz,w=f.command,y=f.args;if(o==="win32"){if(!f.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.
|
|
868
868
|
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${f.command}" ${f.args.join(" ")}`]}return await new Promise(g=>{let b=Yz(e,a,f.env),k=h(w,y,{env:b,stdio:"inherit",windowsHide:!0});k.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
|
|
869
|
-
`),g(1)}),k.once("exit",(A,
|
|
870
|
-
`,"utf8"),await a.chmod(384),await Mr(a),await a.close(),a=void 0,await(t.publish??Ae)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await Xz(o,{force:!0}).catch(()=>{}),s}},ib=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var o9=1e4,
|
|
869
|
+
`),g(1)}),k.once("exit",(A,x)=>{g(typeof A=="number"?A:x?1:0)})})};import{randomUUID as Zz}from"node:crypto";import{open as Jz,rm as Xz}from"node:fs/promises";import{join as zz}from"node:path";import{z as Oe}from"zod";var Hp=Oe.string().min(1).refine(e=>Number.isFinite(Date.parse(e)),"expected an ISO-8601 timestamp"),qz=Oe.enum(["reconcile","refresh","repair","status","offboard"]),sb=Oe.union([Oe.literal(0),Oe.literal(1),Oe.literal(2),Oe.literal(3),Oe.literal(4)]),Qz=Oe.enum(["locked","required","recommended","optional"]),Gp=Oe.object({schemaVersion:Oe.literal(1),generatedAt:Hp,connectVersion:Oe.string().min(1),fleetManaged:Oe.boolean(),enrollment:Oe.object({state:Oe.enum(["enrolled","degraded","broken","none"]),lastRefreshAt:Hp.optional(),lastRefreshOutcome:Oe.enum(["ok","failed"]).optional()}).strict(),keyExpiresAt:Hp.optional(),keyKind:Oe.enum(["personal","service"]).optional(),claudeDesktopConfigCarry:Oe.enum(AI).default("unknown"),tools:Oe.array(Oe.object({id:Oe.string().min(1),tier:Qz,routed:Oe.boolean()}).strict()),lastVerb:Oe.object({verb:qz,exitCode:sb,at:Hp}).strict()}).strict(),uT=(e,t)=>{if(!e)return!1;let n=Date.parse(e);return Number.isFinite(n)&&n>t},e9=(e,t,n=Date.now())=>{if(!!!(e.clientKey||e.enrolledCert||t))return"none";if(kn(e.clientKey)==="service")return e.gateway?"enrolled":"broken";let o=e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt;return!e.gateway||!e.enrolledCert||!t||!uT(o,n)?"broken":!e.clientKey||e.clientKeyExpiresAt&&!uT(e.clientKeyExpiresAt,n)?"degraded":"enrolled"},t9=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"}},pT=(e,t)=>e.fleetToolPolicy?.tiers?.[t]??"required",n9=async(e,t)=>{let n=new Set(e.managedTools??[]),r=new Set(e.revertedTools??[]),o=(e.fleetToolPolicy?.enabled??[]).filter(c=>{let l=pT(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:pT(e,c),routed:d})}return i},fT=async(e,t={})=>{let n=t.now??Date.now,r=await(t.loadProfile??$)(),o=await(t.loadDevKey??Ye)().catch(()=>{}),a=await(t.readRefreshState??Bt)().catch(()=>({})),s=await(t.claudeDesktopConfigCarry??(()=>Yc({loadProfile:async()=>r,toolById:t.toolById??qe})))().catch(()=>"unknown"),i=kn(r.clientKey),c={schemaVersion:1,generatedAt:new Date(n()).toISOString(),connectVersion:Ne,fleetManaged:r.anyrayFleetManaged===!0,enrollment:{state:e9(r,!!o,n()),...t9(a)},...r.clientKeyExpiresAt&&Number.isFinite(Date.parse(r.clientKeyExpiresAt))?{keyExpiresAt:r.clientKeyExpiresAt}:{},...i?{keyKind:i}:{},claudeDesktopConfigCarry:s,tools:await n9(r,t.toolById??qe),lastVerb:e};return Gp.parse(c)},r9=()=>zz(oe(),"status.json"),mT=async(e,t={})=>{let n=Gp.parse(e);await(t.ensureStateDir??lt)();let r=r9(),o=`${r}.${process.pid}.${Zz()}.tmp`,a;try{a=await Jz(o,"wx",384),await a.writeFile(`${JSON.stringify(n,null,2)}
|
|
870
|
+
`,"utf8"),await a.chmod(384),await Mr(a),await a.close(),a=void 0,await(t.publish??Ae)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await Xz(o,{force:!0}).catch(()=>{}),s}},ib=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var o9=1e4,Ks=e=>e?.name??"Error",cb=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(o9)})}catch(o){console.error(`anyray seat offboard report: ${Ks(o)}`)}},a9=e=>e==="reverted"||e==="queued",Kp=async(e={})=>{let t=e.loadProfile??$,n=e.clearDeviceTokenState??kp,r=e.reportSeatOffboarded??cb,o=e.clearEnrollment??pl,a=e.recordManagedTools??Fr,s=e.markSeatOffboarded??fl,i=e.adapterById??qe,c=e.uninstallScheduler??ir,l=e.unitsPresent??Fl,d=e.saveProfile??de,u=await t(),p=u.managedTools??[];await r(u).catch(()=>{}),await n().catch(()=>{});let m=!1,f=!1;try{m=await o()}catch(A){f=!0,console.error(`anyray offboard: clearing enrollment: ${Ks(A)}`)}let h=[],w=[],y=[];for(let A of p){let x=i(A);if(!x){y.push(A);continue}try{let _=await x.revert({dryRun:!1,fullRevert:!0});h.push({id:A,status:_.status}),a9(_.status)?w.push(A):y.push(A)}catch(_){console.error(`anyray offboard: reverting ${A}: ${Ks(_)}`),y.push(A)}}let g=!0;try{await a(h,!0,!0)}catch(A){g=!1,console.error(`anyray offboard: recording managed tools: ${Ks(A)}`)}let b=y.length===0&&g,k=!1;if(b)try{await s(),k=!0}catch(A){console.error(`anyray offboard: stamping offboard: ${Ks(A)}`)}try{((await t()).refreshSchedulerEnabled||await l())&&await c(),await d({...await t(),refreshSchedulerEnabled:!1})}catch(A){console.error(`anyray offboard: unit teardown: ${Ks(A)}`)}return{reverted:w,unresolved:y,enrollmentCleared:m,credentialHeld:f,recordPersisted:g,offboardMarked:k,ok:y.length===0&&!f&&g&&k}};var he={success:0,unexpected:1,usage:2,authBroken:3,partial:4},s9=`Stable non-interactive runtime commands:
|
|
871
871
|
anyray-connect reconcile
|
|
872
872
|
anyray-connect refresh
|
|
873
873
|
anyray-connect repair
|
|
@@ -883,9 +883,9 @@ Exit codes:
|
|
|
883
883
|
1 unexpected error
|
|
884
884
|
2 usage error (unknown flag or argument)
|
|
885
885
|
3 authentication broken; re-enroll, or rotate a service key in the console
|
|
886
|
-
4 partial; the command ran but drift remains`,i9={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"},c9=e=>e.replaceAll("-","_"),gT=e=>{let t=e[0];if(!t)return;let n=i9[c9(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}},lb=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},l9=async(e=$,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
|
|
886
|
+
4 partial; the command ran but drift remains`,i9={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"},c9=e=>e.replaceAll("-","_"),gT=e=>{let t=e[0];if(!t)return;let n=i9[c9(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}},lb=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},l9=async(e=$,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 ma(n.gateway,n.clientKey);return await Ps(i)}catch(i){if(Jg(i))return o?"credential-degraded":"auth-broken";throw i}},d9=e=>e==="auth-broken"?he.authBroken:e==="credential-degraded"||e.toolsApplied<e.toolsRequested||e.toolsTombstoned.length>0?he.partial:he.success,u9=e=>e.refresh==="not-enrolled"||e.refresh==="cert-expired"||e.refresh==="cert-rejected"?he.authBroken:e.refresh==="failed"?he.unexpected:e.partial||e.refresh==="disabled"||e.refresh==="backoff"||e.refresh==="throttled"||e.refresh==="gateway-incompatible"?he.partial:he.success,wT=e=>e.identity.keyKind==="service"?e.verify?.kind==="key-rejected"||e.verify?.kind==="enrollment-required":!e.enrollment.enrolled||e.enrollment.expired===!0||e.verify?.kind==="enrollment-required",p9=e=>{if(!(e.identity.keyKind!=="service"||!wT(e)))return"the gateway rejected the service key (revoked, expired, or unknown); rotate it in the console and set the new value in ANYRAY_CLIENT_KEY on this host"},hT=async e=>{let t;return{code:await Pp({repair:e,quick:!e,silent:!0},{captureReport:r=>t=r}),authBroken:t?wT(t):!1,authBrokenReason:t?p9(t):void 0}},yT=(e,t,n)=>typeof e!="number"&&e.authBroken?(e.authBrokenReason&&n(`anyray-connect ${t}: ${e.authBrokenReason}`),he.authBroken):(typeof e=="number"?e:e.code)===0?he.success:he.partial,f9=(e,t)=>{let n=ib(t);return n===he.authBroken?n:e!==0||n===he.partial?he.partial:he.success},m9=async(e,t)=>{if(e==="reconcile")return d9(await(t.reconcile??(()=>l9(t.loadProfile)))());if(e==="refresh"){if(!t.refresh)throw new Error("refresh runtime is unavailable");return u9(await t.refresh())}let n=t.stderr??console.error;return e==="repair"?yT(await(t.repair??(()=>hT(!0)))(),e,n):e==="status"?yT(await(t.status??(()=>hT(!1)))(),e,n):(await(t.offboard??Kp)()).ok?he.success:he.partial},db=(e,t)=>Gp.parse({...e,lastVerb:{...e.lastVerb,exitCode:t}}),bT=async(e,t={})=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.help)return n(s9),he.success;let o=t.now??Date.now,a=new Date(o()).toISOString(),s=t.withProfileLock??Br,i=t.buildStatus??fT,c=t.writeStatus??mT,l,d=e.usageError?he.usage:he.unexpected;e.usageError&&r(`anyray-connect ${e.verb}: UsageError`);try{await s(async()=>{if(!e.usageError)try{d=sb.parse(await m9(e.verb,t))}catch(u){d=Jg(u)?he.authBroken:he.unexpected,r(`anyray-connect ${e.verb}: ${lb(u)}`)}if(l=await i({verb:e.verb,exitCode:d,at:a},{now:o}),(e.verb==="repair"||e.verb==="status")&&d!==he.unexpected&&d!==he.usage&&d!==he.authBroken)d=f9(d===0?0:1,l);else if(e.verb!=="offboard"&&d!==he.unexpected&&d!==he.usage){let u=ib(l);(u===he.authBroken||d===he.success)&&(d=u)}l=db(l,d);try{await c(l)}catch(u){d=he.unexpected,l=db(l,d),r(`anyray-connect ${e.verb}: ${lb(u)}`)}})}catch(u){d=he.unexpected,r(`anyray-connect ${e.verb}: ${lb(u)}`);try{l=db(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"},claudeDesktopConfigCarry:"unknown",tools:[],lastVerb:{verb:e.verb,exitCode:d,at:a}})),d};var CT=new Set(["not-due","repaired","cert-renewed","heartbeat-refreshed","refreshed"]),AT=async(e,t={})=>await(t.fleetdPresent??Aa)()?CT.has(e)?{retired:!0,messages:(await(t.uninstallScheduler??ir)()).messages}:{retired:!1,reason:"refresh-unhealthy",messages:[]}:{retired:!1,reason:"no-fleetd",messages:[]},kT=async(e,t={})=>{if(!CT.has(e))return{retired:!1,reason:"refresh-unhealthy",messages:[]};let r=await(t.load??$)().catch(()=>{});if(!r)return{retired:!1,reason:"no-profile",messages:[]};if(!r.refreshSchedulerEnabled||r.persistenceOwner==="tray")return{retired:!1,reason:"not-installed",messages:[]};if(rt(r,{},t.now??Date.now()))return{retired:!1,reason:"still-needed",messages:[]};let o=await(t.uninstallScheduler??ir)();if(!o.ok)return{retired:!1,reason:"uninstall-failed",messages:o.messages};if(await(t.schedulerInstalled??_n)().catch(()=>!0))return{retired:!1,reason:"uninstall-failed",messages:o.messages};let s=t.mutate??ul;return await s(l=>!l.refreshSchedulerEnabled||l.persistenceOwner==="tray"||rt(l,{},t.now??Date.now())?{result:!1}:{next:{...l,refreshSchedulerEnabled:!1,refreshSchedulerInstalledOnce:!1},result:!0}).catch(()=>!1)?await(t.schedulerInstalled??_n)().catch(()=>!1)?(await s(l=>({next:{...l,refreshSchedulerEnabled:!0,refreshSchedulerInstalledOnce:!0},result:void 0})).catch(()=>{}),{retired:!1,reason:"raced-reinstall",messages:o.messages}):{retired:!0,messages:o.messages}:{retired:!1,reason:"clear-failed",messages:o.messages}};var vT=["reapply_config","remint","revert","revert_tool","update"],h9=/^[a-z0-9][a-z0-9-]{0,31}$/;var y9=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"||!vT.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&h9.test(t.tool):t.tool===void 0},ub=e=>e?.name??"error",ST=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":vT.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!y9(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",ub(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",ub(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:",ub(i))}return a.kind};var IT=e=>e?.name??"Error",pb=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??$,r=t.recordManagedTools??Fr,o=t.adapterById??qe,a=t.isLocked??$c,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}: ${IT(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${IT(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{basename as g9}from"node:path";import{join as ET}from"node:path";var w9="history.recentlyOpenedPathsList",b9={"ssh-remote":"ssh","dev-container":"devcontainer","attached-container":"attached-container",wsl:"wsl",codespaces:"codespace",tunnel:"tunnel"},C9=e=>{try{let t=JSON.parse(Buffer.from(e,"hex").toString("utf-8"));if(typeof t.hostPath=="string"&&t.hostPath)return{name:g9(t.hostPath),hostPath:t.hostPath};if(typeof t.containerName=="string"&&t.containerName)return{name:t.containerName.replace(/^\//,"")}}catch{}return{name:"container"}},A9=e=>{let t=/^vscode-remote:\/\/([^/]+)/.exec(e);if(!t)return;let n;try{n=decodeURIComponent(t[1])}catch{return}let r=n.indexOf("+");if(r<=0)return;let o=b9[n.slice(0,r)];if(!o)return;let a=n.slice(r+1);if(a){if(o==="devcontainer"||o==="attached-container"){let s=C9(a);return{kind:o,name:s.name,...o==="devcontainer"&&s.hostPath?{ref:s.hostPath}:{}}}return{kind:o,name:a}}},k9=e=>{let t;try{t=JSON.parse(e).entries}catch{return[]}if(!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){if(typeof o!="object"||o===null)continue;let a=o,s=[a.folderUri,a.fileUri,a.workspace?.configPath].filter(i=>typeof i=="string");for(let i of s){let c=A9(i);if(!c)continue;let l=`${c.kind}|${c.ref??c.name}`;r.has(l)||(r.add(l),n.push(c))}}return n},v9=()=>[...Ho.map(e=>ET(yd(e),"User","globalStorage","state.vscdb")),ET(Ue("Cursor"),"User","globalStorage","state.vscdb")],fb=async(e={})=>{let t=e.readItem??(()=>{let o=Qr();return o?o.readItem.bind(o):void 0})();if(!t)return[];let n=[],r=new Set;for(let o of e.dbPaths??v9()){let a;try{a=t(o,w9)}catch{continue}if(a)for(let s of k9(a)){let i=`${s.kind}|${s.ref??s.name}`;r.has(i)||(r.add(i),n.push(s))}}return n};import{execFile as S9,spawn as I9}from"node:child_process";import{promisify as E9}from"node:util";var x9="https://app.anyray.ai/connect.sh",R9=".anyray/bin/anyray-connect",Vs=e=>`'${e.replaceAll("'",`'"'"'`)}'`,O9=e=>{let n=`${["set -eu","if command -v anyray-connect >/dev/null 2>&1; then"," command -v anyray-connect"," exit 0","fi",`ANYRAY_CONNECT_TAG=${Vs(`connect-v${Ne}`)} \\`,` sh -c ${Vs(`curl -fsSL ${x9} | sh`)} >&2 </dev/null`,`echo "$HOME/${R9}"`].join(`
|
|
887
887
|
`)}
|
|
888
|
-
`;switch(e.kind){case"ssh":return{command:"ssh",args:["-T","--",e.name,"sh","-s"],stdin:n};case"devcontainer":return{command:"docker",args:["exec","-i",e.name,"sh","-s"],stdin:n};case"wsl":return{command:"wsl.exe",args:["-d",e.name,"--","sh","-s"],stdin:n};case"codespace":return{command:"gh",args:["codespace","ssh","-c",e.name,"--","sh -s"],stdin:n}}},_9=(e,t,n)=>{let r=[n,"--yes","--key-stdin","--gateway",t.gateway,...t.user!==void 0?["--user",t.user]:[],...t.team!==void 0?["--team",t.team]:[]],o=[
|
|
888
|
+
`;switch(e.kind){case"ssh":return{command:"ssh",args:["-T","--",e.name,"sh","-s"],stdin:n};case"devcontainer":return{command:"docker",args:["exec","-i",e.name,"sh","-s"],stdin:n};case"wsl":return{command:"wsl.exe",args:["-d",e.name,"--","sh","-s"],stdin:n};case"codespace":return{command:"gh",args:["codespace","ssh","-c",e.name,"--","sh -s"],stdin:n}}},_9=(e,t,n)=>{let r=[n,"--yes","--key-stdin","--gateway",t.gateway,...t.user!==void 0?["--user",t.user]:[],...t.team!==void 0?["--team",t.team]:[]],o=[Vs(n),"--yes","--key-stdin","--gateway",Vs(t.gateway),...t.user!==void 0?["--user",Vs(t.user)]:[],...t.team!==void 0?["--team",Vs(t.team)]:[]].join(" "),a=`${t.clientKey}
|
|
889
889
|
`;switch(e.kind){case"ssh":return{command:"ssh",args:["-T","--",e.name,o],stdin:a};case"devcontainer":return{command:"docker",args:["exec","-i",e.name,...r],stdin:a};case"wsl":return{command:"wsl.exe",args:["-d",e.name,"--",...r],stdin:a};case"codespace":return{command:"gh",args:["codespace","ssh","-c",e.name,"--",o],stdin:a}}},T9=E9(S9),P9=async(e,t)=>(await T9(e,[...t],{encoding:"utf8"})).stdout.toString(),mb=async(e,t={})=>{let n=typeof e=="string"?{name:e}:e,r=n.ref??(/[/\\]/.test(n.name)?n.name:void 0);if(!r)throw new Error("Cannot resolve a dev container by its bare name; use its full host path.");let a=(await(t.exec??P9)("docker",["ps","--filter",`label=devcontainer.local_folder=${r}`,"--format","{{.ID}}"])).split(`
|
|
890
890
|
`).map(s=>s.trim()).filter(Boolean);if(a.length===0)throw new Error("No running dev container matches the discovered workspace.");if(a.length>1)throw new Error(`${a.length} running dev containers match this workspace; stop the stale one (docker ps --filter label=devcontainer.local_folder=...) and re-run.`);return a[0]},xT=(e,t,n)=>new Promise(r=>{let o;try{o=t(e.command,e.args,{stdio:["pipe",n?"pipe":"inherit","inherit"]})}catch{r({code:1,stdout:""});return}let a="",s=!1,i=c=>{s||(s=!0,r({code:c,stdout:a}))};if(o.stdout?.on("data",c=>{a+=c.toString("utf-8")}),o.once("error",()=>i(1)),o.once("close",c=>i(c??1)),!o.stdin){i(1);return}o.stdin.end(e.stdin)}),hb=async(e,t,n={})=>{let r=n.spawn??I9,o=e.kind==="devcontainer"&&e.ref?{...e,name:await mb(e,n)}:e,a=await xT(O9(o),r,!0);if(a.code!==0)return a.code;let s=a.stdout.split(`
|
|
891
891
|
`).map(c=>c.trim()).filter(Boolean).at(-1);return s?(await xT(_9(o,t,s),r,!1)).code:1};import{spawnSync as D9}from"node:child_process";import{platform as Zp}from"node:os";import{basename as L9}from"node:path";import{createInterface as N9}from"node:readline";var _T=`${Z("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
@@ -1162,22 +1162,22 @@ ${Z("What it does")}
|
|
|
1162
1162
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1163
1163
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1164
1164
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1165
|
-
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,$9=e=>{let t=e?.trim();return t||Ky()},TT=(e=process.stdin)=>new Promise((t,n)=>{let r=N9({input:e,crlfDelay:1/0}),o=!1,a=i=>{o||(o=!0,e.removeListener("error",s),r.close(),t(i))},s=i=>{o||(o=!0,r.close(),n(i))};r.once("line",i=>a(i.trim())),r.once("close",()=>a("")),e.once("error",s)}),Vp=(e,t)=>t||e,Jp=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"--key-stdin":t.keyStdin=!0;break;case"--devcontainer":t.devcontainer=o();break;case"--wsl":t.wsl=o();break;case"--codespace":t.codespace=o();break;case"--enroll":t.enroll=o();break;case"--sso":t.sso=o();break;case"--sign-in":t.signIn=!0;break;case"--desktop-app":t.desktopApp=!0;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},M9=e=>!e||e.length===0?se:e.map(t=>{let n=qe(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${se.map(r=>r.id).join(", ")}`);return n}),jp=e=>e.keyKind==="service"?"service key (agent)":"personal gateway key",B9=(e,t)=>{if(U("Gateway target"),C(` Origin: ${st(e.origin)}`),e.byoUpstream)C(` Auth: BYO upstream key ${v(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&C(` Client key: ${jp(e)} (${Yt(e.clientKey)}) ${v("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=ae(e,"anthropic")?st("your subscription"):"org key",r=ae(e,"openai")?st("your subscription"):"org key";C(` Auth: auto ${v("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&C(` Client key: ${jp(e)} (${Yt(e.clientKey)})`)}else e.authMode==="subscription"?(C(` Auth: subscription pass-through ${v("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&C(` Client key: ${jp(e)} (${Yt(e.clientKey)}) ${v("rides x-anyray-api-key")}`)):e.clientKey?C(` Auth: ${jp(e)} (${Yt(e.clientKey)}) ${v("(replaces the placeholder)")}`):C(` Enrollment: ${v("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&C(` Cursor: ${st("native Team subscription")} ${v("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(ae(e,"anthropic")?(C(` Claude Desktop: ${st("subscription-backed Gateway lane")} ${v("(verified macOS builds; Windows fails closed)")}`),C(` ${v("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(C(` Claude Desktop: ${st("third-party API lane")} ${v("(API-billed; switches the active local inference profile)")}`),C(` ${v("The first-party Claude subscription remains untouched.")}`))),C(` Attribution: ${be(e.metadata)??v("(none \u2014 pass --user)")}`)},F9=e=>{switch(e.kind){case"ssh":return`SSH remote \`${e.name}\``;case"devcontainer":return`dev container \`${e.name}\``;case"attached-container":return`attached container \`${e.name}\``;case"wsl":return`WSL distro \`${e.name}\``;case"codespace":return`Codespace \`${e.name}\``;case"tunnel":return`remote tunnel \`${e.name}\``}},W9=async()=>{let[e,t]=await Promise.all([Op().catch(()=>[]),fb().catch(()=>[])]);for(let n of e)C(` Bind-mounted config file: ${n} ${v("(cannot be replaced atomically; connect writes it in place, verified)")}`);if(t.length>0){U("Other environments you work in");for(let n of t)M(` ${F9(n)}`);C(v(" This run configures only this machine. Run `anyray-connect` inside each of these too \u2014 see docs.anyray.ai/get-started/remote-environments."))}},RT=async(e,t)=>{U("Selected tools");for(let n of e){let r=await n.detect();r.installed?C(` ${n.title} ${v(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):M(` ${n.title} ${v(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},wb=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Pe(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},U9={loadDevKey:Ye,saveDevKey:ll,clearDevKey:
|
|
1166
|
-
${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?`}`,X9=async(e,t={})=>{let n=t.requestQuit??(a=>WA(a)),r=t.waitFor??(a=>UA(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),B(` Closed ${a.title}.`);continue}P(` ${a.title} is still open \u2014 leaving it alone.`),M(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},z9=(e,t={})=>{let n=t.relaunch??(o=>HA(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),B(` Reopened ${o.title}.`)):P(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r};var bb=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,q9=(e,t)=>{switch(t){case"optional":return`${e}: skipped, optional tier (a developer enables it with anyray-connect --tools ${e})`;case"not_enabled":return`${e}: skipped, not in the policy's enabled list`;case"consent":return`${e}: skipped, consent-gated; applies only at the locked tier`;default:return t}},yb=e=>!jr(e),Q9=async(e,t,n={})=>{let r=n.hasEnrollment??hf,o=n.canMultiSelect??TO,a=n.multiSelect??PO,s=n.prompt??
|
|
1167
|
-
${o} ${n} tool target(s)?`;return await(r.confirm??ia)(a)?"proceed":"declined"},lq=async(e=As)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0,initiator:"directive"});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";case"fleet-off":return"failed";case"fleet-directed":return"failed";default:return t.outcome}},Cb=e=>NT(e,!1,{managedEnrollmentCarrier:!0}),dq=e=>Fp(Wp(Cb),{json:e}),uq=async()=>{let e=!1,t=await X_(await rn({runAmbientSelfcheck:!0}),{...Wp(Cb),refresh:()=>rn({})});await z_(Wp(Cb)),await Yf(),await TR(),await PR()==="retry"&&(e=!0);let n=await $().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await de(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Ca().catch(()=>!1);if(n&&(await AT(t,{fleetdPresent:async()=>r}).catch(()=>{}),await kT(t).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=nn(),i=n.enrolledCert;if(s&&i){let l=await Ye().catch(()=>{});l&&await m0(o,a,i,l,s).catch(()=>{})}await ST(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await rn({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await pb(d):l==="update"?u=await lq():u=(await Kp()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await As(),{refresh:t,...e?{partial:!0}:{}}},pq=async(e,t={})=>{if(e[0]==="__anyray-hook"){let a=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return __(a)}if(e[0]==="__anyray-codex-hook")return T_();if(e[0]==="__anyray-prompt-hook")return N_();if(e[0]==="__anyray-shell-pretool")return F_();if(e[0]==="__anyray-shell-run")return B_(e.slice(1));if(e[0]==="__anyray-read-pretool")return Y_();if(e[0]==="__anyray-sso-gate")return L_(e.slice(1));if(e[0]==="__anyray-sso-poll")return q_();if(e[0]==="__anyray-managed-enroll")try{return await Br(()=>dq(e.slice(1).includes("--json")),{waitMs:PT})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return eT();if(e[0]==="__anyray-spawn-refresh")return await Ao(),0;if(e[0]==="__anyray-mcp-server"){let a=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return lT(a)}if(e[0]==="__anyray-acp-agent")return dT(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return Nx(e.slice(1));let n=gT(e);if(n)return bT(n,{refresh:uq});if(e[0]==="__anyray-persistence")return UC(e.slice(1));if(e[0]==="__anyray-quit-watch")return SE(e.slice(1));if(e[0]===uo)return QR(e.slice(1));if(e[0]===Yi)return tO(e.slice(1));if(e[0]===$o){let a=e[1];return a&&await Uu(a),0}if(e[0]==="--version"||e[0]==="-V")return Q_();try{let a=await rC(e);if(a!==void 0)return a}catch(a){let s=`Could not persist anyray-connect for long-lived integrations: ${a instanceof Error?a.message:String(a)}`;return D(s),kb(e)&&er({event:"error",code:"enroll-failed",message:s}),1}if(aq(e)){let a=oq(await sx());a?.level==="warn"?P(a.message):a&&console.error(a.message)}let r=yw(e[0]);if(r)return r.run(e.slice(1));if(e[0]==="desktop"){let a=e.slice(1),s=Iw(a);return s?gb(s,!1,t.apply):pO(a)}if(e[0]==="remote")return Aq(e.slice(1));let o=e[0];if(o&&nq.has(o)){let a=e.slice(1),s;try{s=Jp(a)}catch(i){return D(i.message),C("\nRun `npx anyray-connect --help` for usage."),1}return s.help?(C(s.helpAll?Yp:_T),0):o==="status"?KO({gateway:s.gateway}):o==="doctor"?Pp({gateway:s.gateway,json:s.json,verify:s.verify,noVerify:s.noVerify,quick:s.quick,repair:s.repair,securityReview:s.securityReview}):o==="sync"?qO({gateway:s.gateway}):o==="device-url"?jR():gb(a,!0,t.apply)}return gb(e,!1,t.apply)},DT=async(e,t={})=>{Yy();let n=sq(e);if(n?.json&&(jy(),!n.yes)){let r="--json enrollment requires --yes.";return er({event:"error",code:"yes-required",message:r}),D(r),1}try{return await pq(e,t)}catch(r){if(r instanceof It)return console.error(v("Cancelled.")),130;throw r}},fq=e=>{let t=process.platform==="win32"?"where":"which";try{return D9(t,[e],{stdio:"ignore"}).status===0}catch{return!1}},mq=(e,t={})=>{let n=t.which??fq,r=t.platform??Zp;switch(e.kind){case"ssh":return!0;case"devcontainer":return n("docker");case"wsl":return r()==="win32"&&n("wsl.exe");case"codespace":return n("gh")}},hq=e=>{switch(e.kind){case"ssh":case"devcontainer":case"wsl":case"codespace":return{kind:e.kind,name:e.name,...e.kind==="devcontainer"&&e.ref?{ref:e.ref}:{}};case"attached-container":case"tunnel":return}},yq=(e,t)=>{switch(e.kind){case"ssh":return`Configure \`${t}\` over SSH now?`;case"devcontainer":return`Configure \`${t}\` in this dev container now?`;case"wsl":return`Configure \`${t}\` in WSL now?`;case"codespace":return`Configure Codespace \`${t}\` now?`}},gq=e=>e.interactive&&!e.managed&&!e.yes&&!e.revert&&!e.dryRun,wq=async(e,t={})=>{if(!gq(e)||!Pe(e.clientKey))return;let n=t.discoverRemoteEnvironments??fb,r;try{r=await n()}catch{return}let o=t.confirm??ia,a=t.runRemoteApply??hb,s=t.isCarrierAvailable??mq,i=t.resolveDevcontainer??mb;for(let c of r){let l=hq(c);if(!l)continue;let d=l;try{if(!await s(d))continue;d.kind==="devcontainer"&&(d={kind:"devcontainer",name:await i(d)})}catch{continue}if(!await o(yq(d,c.name)))continue;let u=await a(d,{gateway:e.gateway,user:e.user,team:e.team,clientKey:e.clientKey});if(u===0){M(`Remote \`${c.name}\` exited with code 0.`);continue}P(`Remote \`${c.name}\` exited with code ${u}.`),M(LT(d.kind))}},LT=e=>{switch(e){case"ssh":return"Fix: ssh in and run `anyray-connect doctor`.";case"devcontainer":return"Fix: open a shell in the container and run `anyray-connect doctor`.";case"wsl":return"Fix: open the distro and run `anyray-connect doctor`.";case"codespace":return"Fix: `gh codespace ssh` in and run `anyray-connect doctor`."}},bq="usage: anyray-connect remote <ssh-host> [--yes] [--dry-run] | remote --devcontainer <host-path> | --wsl <distro> | --codespace <name> [--yes] [--dry-run]",Cq=e=>{let t=/[/\\]/.test(e);return{kind:"devcontainer",name:t?L9(e.replaceAll("\\","/")):e,...t?{ref:e}:{}}},Aq=async(e,t={})=>{if(e[0]==="--help"||e[0]==="-h")return console.log(Yp),0;let n=e[0]&&!e[0].startsWith("-")?e[0]:void 0,r;try{r=Jp(n?e.slice(1):e)}catch(h){return D(h instanceof Error?h.message:String(h)),1}if(r.help)return console.log(Yp),0;let o=[r.devcontainer,r.wsl,r.codespace].filter(h=>h!==void 0);if(n&&o.length>0||!n&&o.length!==1)return D(bq),1;let a=n?{kind:"ssh",name:n}:r.devcontainer!==void 0?Cq(r.devcontainer):r.wsl!==void 0?{kind:"wsl",name:r.wsl}:{kind:"codespace",name:r.codespace};if(a.kind==="devcontainer"&&!a.ref)return D("Cannot resolve a dev container by its bare name; use its full host path."),1;if(a.kind==="wsl"&&(t.platform??Zp)()!=="win32")return D("--wsl is available only on Windows (win32)."),1;let s=t.isInteractive??Et;if(!r.yes&&!s())return D("remote requires a TTY; pass --yes only when you explicitly intend to configure that target."),1;if(r.revert||r.signIn||r.enroll||r.sso||r.claim||r.desktopApp||r.project||r.upstream||r.upstreamKey)return D("remote supports --gateway, --user, --team, --yes, --dry-run, and --key-stdin only."),1;if(r.dryRun)return M(`Dry run: would configure \`${a.name}\` remotely.`),0;let i;if(r.keyStdin)try{i=await TT()}catch{return D("could not read the personal gateway key from stdin."),1}let c=await(t.loadProfile??$)(),l=!r.gateway&&!process.env.ANYRAY_GATEWAY_URL?c.gateway:void 0,d=cn(r.gateway??l),u=i||process.env.ANYRAY_CLIENT_KEY?.trim()||wb(c);if(!Pe(u))return D("A personal gateway key is required. Enroll locally first or provide ANYRAY_CLIENT_KEY (or --key-stdin)."),1;let p=await Jy(r.user,c.name,r.yes),m=await Xy(r.team,c.team,r.yes),f;try{f=await(t.runRemoteApply??hb)(a,{gateway:d,user:p,team:m,clientKey:u})}catch(h){return D(h instanceof Error?h.message:String(h)),1}return f===0?M(`Remote \`${a.name}\` exited with code 0.`):(P(`Remote \`${a.name}\` exited with code ${f}.`),M(LT(a.kind))),f},NT=async(e,t,n={})=>{Yy();let r=kb(e);r&&jy();let o=(L,T)=>{r&&er({event:"error",code:L,message:T})},a=(L,T)=>(D(T),o(L,T),1),s=n.isInteractive??Et,i;try{i=Jp(e)}catch(L){return a("invalid-args",L.message),C("\nRun `npx anyray-connect --help` for usage."),1}let c=i.signIn?"sign-in":i.claim?"claim":i.sso?"sso":i.enroll?"enroll":void 0;if(r&&!i.yes)return a("yes-required","--json enrollment requires --yes.");if(r&&i.dryRun)return a("invalid-args","--json enrollment cannot be combined with --dry-run.");let l=L=>n.managedEnrollmentCarrier===!0&&Bg(L)?"enroll-rejected":L instanceof wt||L instanceof Rt||L instanceof on||L instanceof Ft?L.kind:L instanceof Tc?"gateway-unreachable":L instanceof Pc?"cp-unreachable":L instanceof it&&L.policyCode==="sso_required"?"sso-required":"enroll-failed";if(i.help)return C(i.helpAll?Yp:_T),0;if(i.desktopApp){if(!i.json)return a("invalid-args","--desktop-app is an internal machine interface and requires --json.");if(i.revert)return a("invalid-args","--desktop-app cannot be combined with --revert.");if(i.sso||i.claim||!i.signIn&&!i.enroll)return a("invalid-args","--desktop-app requires exactly one supported carrier: --sign-in or --enroll.");if(i.devcontainer||i.wsl||i.codespace)return a("invalid-args","--desktop-app configures the local machine and cannot target a remote environment.");if(i.machine)return a("invalid-args","--desktop-app accepts a personal user link, not --machine enrollment.")}if(i.signIn&&(i.sso||i.enroll||i.claim))return a("invalid-args","--sign-in cannot be combined with --sso, --enroll or --claim.");if(i.revert&&(i.signIn||i.sso||i.enroll||i.claim))return a("invalid-args","--revert cannot be combined with --sign-in, --sso, --enroll or --claim. It removes Anyray configuration; re-run without --revert to configure a new CLI.");if(i.project)return i.signIn||i.sso||i.enroll||i.subscription||i.upstream?a("invalid-args","--project cannot be combined with --sign-in/--sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."):(Ab()||kn(wb(await $()))==="service")&&!i.revert?a("invalid-args","--project needs a personal enrollment: the committed config gets its key from `anyray-connect print-key`, which mints from an enrollment cert, and a service key has none."):zR({gateway:i.gateway,tools:i.tools,revert:i.revert,dryRun:i.dryRun,yes:i.yes});if(!!i.upstream!=!!i.upstreamKey)return a("invalid-args","--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there.");if(i.upstream&&(i.subscription||i.placeholder))return a("invalid-args","--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.");let d;if(i.upstream){let L;try{L=new URL(i.upstream.trim())}catch{return a("invalid-args",`invalid --upstream URL: "${i.upstream}"`)}if(L.protocol!=="http:"&&L.protocol!=="https:")return a("invalid-args",`invalid --upstream URL: "${i.upstream}" \u2014 must start with http:// or https://`);let T=i.upstreamKey.trim();if(!T)return a("invalid-args","--upstream-key must not be empty.");d={url:ct(i.upstream),key:T}}let u=await $(),p;if(i.keyStdin)try{p=await TT()}catch{return a("apply-failed","could not read the personal gateway key from stdin.")}!d&&!i.subscription&&!i.placeholder&&!i.revert&&(d=u.byoUpstream);let m=!t&&Et()&&!i.gateway&&!i.revert&&!i.yes&&!i.dryRun&&!i.enroll&&!i.sso&&!i.signIn,f=!1;(t||m)&&s()&&(i=await(n.runWizard??Q9)(i,u),f=!0);let h;try{h=M9(i.tools)}catch(L){return a("apply-failed",L.message)}C(Z(i.revert?"Anyray connect \u2014 revert":"Anyray connect")),i.gateway&&!i.enroll&&_c(i.gateway)&&(i.enroll=i.gateway,i.gateway=void 0,C("That looks like an enrollment link \u2014 treating it as --enroll."));let w,y,g,b,k=!1;if(i.enroll){let L=rp(i.enroll);if(L&&(i.desktopApp||!i.gateway||u.enrolledCert||Pg(L.token)))try{let T=await Fs("Resolving enrollment link\u2026",()=>(n.resolveEnrollLink??c0)(L)),V=!i.gateway;if(V&&(i.gateway=T.gatewayUrl),w=T.deploymentId,y=T.email,g=T.provisioningKind,b=T.allowedDomains,k=!0,i.desktopApp&&!T.email)return a("invalid-link","The desktop app accepts personal links only. Ask your admin for a personal link.");V&&M(`Enrollment link${T.org?` for ${T.org}`:""}: gateway ${T.gatewayUrl}`),T.seatMode&&!i.subscription&&(i.subscription=!0,M("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(T){if(i.desktopApp)return a("enroll-failed","The desktop app could not verify that this is a personal link. Try again or ask your admin for a new personal link.");if(Pg(L.token))return a(l(T),T instanceof Error?T.message:String(T));let V=i.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||u.gateway;if(V)M(`Could not resolve the gateway from the enrollment link \u2014 using ${V}.`);else return a("enroll-failed",T instanceof Error?T.message:String(T))}}let A,E;if(r&&await(n.clearGateState??Vc)(),i.claim&&!i.revert)if(i.dryRun)M("dry run: not enrolled (skipped redeeming the enrollment link).");else{let L=A0(i.claim);if(!L)return a("invalid-link","invalid --claim value: expected the sdc_ code from your organization's Anyray page.");try{let T=await Fs("Connecting this machine\u2026",()=>(n.redeemClaim??k0)({cpOrigin:L.cpOrigin,claim:L.claim,gatewayUrl:i.gateway}));A={cert:T.cert,privateKeyPem:T.privateKeyPem},T.deploymentId&&(w=T.deploymentId),!i.gateway&&T.gatewayUrl&&(i.gateway=T.gatewayUrl),E=T.ssoLink}catch(T){return a(l(T),T instanceof Error?T.message:String(T))}}if(i.sso&&!A&&!i.revert)if(i.dryRun)M("dry run: not enrolled via SSO (skipped minting a personal key).");else{let L=Mt(i.sso);if(!L){let T=_c(i.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.";return a("invalid-link",T)}try{let T=await(n.startDeviceGrant??op)({cpOrigin:L.cpOrigin,tenantId:L.tenantId,gatewayUrl:i.gateway,log:r?void 0:_e=>M(_e),open:!r&&s()?Rr:void 0});r&&er({event:"sso_grant",verificationUriComplete:T.verificationUriComplete,userCode:T.userCode,expiresAt:new Date(T.grantExpiresAt).toISOString(),tenantId:T.tenantId});let V=await Fs("Waiting for SSO sign-in\u2026",()=>(n.pollDeviceGrant??ap)(T,{gatewayUrl:i.gateway}));A={cert:V.cert,privateKeyPem:V.privateKeyPem},V.deploymentId&&(w=V.deploymentId),!i.gateway&&V.gatewayUrl&&(i.gateway=V.gatewayUrl)}catch(T){return a(l(T),T instanceof Error?T.message:String(T))}}if(i.signIn&&!A&&!i.revert)if(i.dryRun)M("dry run: not signed in (skipped minting a personal key).");else{let L;try{let T=await(n.createDesktopSignInCallbackListener??SO)();L=T;let V=await(n.startDesktopSignIn??RO)({callbackUri:T.callbackUri,log:r?void 0:tt=>M(tt),open:!r&&s()?Rr:void 0});r&&er({event:"sso_grant",verificationUriComplete:V.browserUrl,userCode:V.userCode,expiresAt:new Date(V.grantExpiresAt).toISOString()});let _e=await Fs("Waiting for sign-in\u2026",async()=>{let tt=await T.waitForCompletion(V);return(n.pollDesktopSignIn??OO)(V,{completion:tt})});A={cert:_e.cert,privateKeyPem:_e.privateKeyPem},_e.deploymentId&&(w=_e.deploymentId),!i.gateway&&_e.gatewayUrl&&(i.gateway=_e.gatewayUrl)}catch(T){return a(l(T),T instanceof Error?T.message:String(T))}finally{await L?.close()}}let O=!i.gateway&&!process.env.ANYRAY_GATEWAY_URL?u.gateway:void 0;O&&(i.gateway=O);let S;try{S=cn(i.gateway)}catch(L){return a("enroll-failed",L.message)}let I,x;O&&!i.revert&&M(`Gateway: ${S} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!i.revert&&Sb(S)&&P(`${S} 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 _=p??process.env.ANYRAY_CLIENT_KEY?.trim(),K=_||wb(u),G,X,re,ke,fe,W,Q=async L=>{await ya();let T=u0(L.token),V=h0(u.enrolledCert,u.enrolledCertExpiry,L.deploymentId,Date.now(),T,u.enrolledTokenHash,L.expectedUser),_e=V?await Ye():void 0,tt=nn()||void 0,Ut=V&&_e&&u.enrolledCert?{cert:u.enrolledCert,privateKeyPem:_e,publicKeyPem:u.enrolledCert.payload.devPublicKey}:void 0,Ct=Te=>(n.enrollAndVerify??y0)({cpOrigin:L.cpOrigin,token:L.token,gatewayOrigin:S,email:L.email,team:L.team,machineId:L.machineId,deploymentId:L.deploymentId,machineUuid:tt,reuse:Te?Ut:void 0}),Ve=!!Ut,je=await(async()=>{try{return await Ct(Ve)}catch(Te){if(Ut&&Te instanceof it&&Te.policyCode!=="managed_device_required")return M("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),Ve=!1,await Ct(!1);throw Te}})();K=je.clientKey,i.user=Vp(i.user,je.user),i.team=Vp(i.team,je.team),G=je.cert,X=je.cert.payload.expiresAt,W=je.expiresAt,fe=void 0,Ve||(re=je.privateKeyPem),Ve||(ke=T),B(`Enrolled${je.user?` as ${je.user}`:""}${Ve?" (reused your saved cert)":""} \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)};if(i.enroll&&!i.revert)if(i.dryRun)M("dry run: not enrolled (skipped minting a personal key).");else{let L=rp(i.enroll);if(!L){let T=i0(i.enroll),V=T?`that is ${T.what}, not an enrollment link \u2014 re-run with ${T.flag} instead of --enroll.`:Mt(i.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.";return a("invalid-link",V)}try{let T=i.machine?hp():void 0,V=g==="mdm"&&!y?AO():void 0,_e=g==="mdm"&&!y&&!V?CO(b,_u()):void 0,tt=V??_e;if(tt){let Ve=V?"the email your MDM assigned to this machine":`${tt} (this Mac's login name at the first allowed domain)`;C(i.user?.trim()&&i.user.trim()!==tt?`Ignoring --user: enrolling as ${Ve}.`:`Enrolling as ${Ve}.`)}let Ut=y??tt??$9(i.user);if(!i.machine&&!i.user&&!y&&!tt){let Ve=OE();Ve.distinct||(P(` Enrolling as "${Ve.identity}" \u2014 this may not be unique to you.`),P(Ve.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"),P(Ve.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."),P(" Re-run with `--user you@company.com` (or set `git config --global"),P(" user.email`) so your usage is attributed to you."))}let Ct=i.machine?`machine:${T}`:k?Ut:void 0;await Q({cpOrigin:L.cpOrigin,token:L.token,email:Ut,team:i.team,machineId:T,deploymentId:w,expectedUser:Ct})}catch(T){let V=T instanceof Error?T.message:String(T);return D(V),o(l(T),V),T instanceof it&&T.policyCode!=="managed_device_required"&&M("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),Bg(T)?3:1}}if(A){await ya();try{let L=nn()||void 0,T=await(n.verifyWithGateway??An)(S,A.cert,A.privateKeyPem,{machineUuid:L});K=T.key,i.user=Vp(i.user,T.user),i.team=Vp(i.team,T.team),G=A.cert,X=A.cert.payload.expiresAt,re=A.privateKeyPem,W=T.expiresAt;let V=i.sso?Mt(i.sso):void 0;fe=V?`${V.cpOrigin}/sso/${V.tenantId}`:E,B(`Enrolled${T.user?` as ${T.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(L){let T=L instanceof Error?L.message:String(L);return D(T),o(l(L),T),L instanceof it&&L.policyCode!=="managed_device_required"&&M("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}let ye=kn(K);if(!i.revert)if(ye==="service")(i.user!==void 0||i.team!==void 0)&&M("Service key: identity comes from the key; --user/--team ignored.");else{let L=i.yes;I=await Jy(i.user,u.name,L),x=await Xy(i.team,u.team,L)}if(!i.revert&&!i.dryRun){let L=WO(await FO(S,K),{subscription:i.subscription,org:i.placeholder,byoUpstream:!!d});if(L.lane){let T=L.lane==="subscription";i.subscription=T,i.placeholder=!T;let V=T?"your own subscription seat":"the organization's provider account";L.overrodeFlag?M(`Your administrator assigns this machine to ${V}, so that is what was applied (it overrides the lane flag you passed).`):M(`Billing lane set by your administrator: ${V}.`)}}let we;!i.revert&&!i.subscription&&!i.placeholder&&(we=await Wn(),U("Detecting your sign-ins"),C(` Claude (Anthropic): ${d?st("BYO upstream key (passthrough)"):we.anthropic?st("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),C(` Codex (ChatGPT): ${we.openai?st("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),(!we.anthropic||!we.openai)&&K&&await GO(xe({origin:S,placeholderKey:i.key,clientKey:K,subscription:!1,placeholder:!0,byoUpstream:d,user:I,team:x,intent:i.intent}))===!1&&(P(" This gateway holds NO server-side provider key, so the org-key"),P(" fallback above cannot serve a request \u2014 it answers 424, not 401."),we.copilot?(P(" Your Copilot seat DOES work and never touches the org key: prefer"),P(" `github-copilot/...` models in OpenCode and Copilot Chat until an"),P(" admin adds a provider key in the console \u2192 Providers.")):(P(" No subscription seat here works either. Sign in to Copilot or"),P(" Claude, or have an admin add a provider key in console \u2192 Providers."))),!we.anthropic&&!we.openai&&!we.copilot&&ar()&&(P(" No subscription sign-ins found on this host. Sign-ins do not cross the"),P(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),P(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),P(" and re-run, or everything below routes on the org key instead.")));let Y=xe({origin:S,placeholderKey:i.key,clientKey:K,subscription:i.subscription,placeholder:i.placeholder,byoUpstream:d,seat:we,user:I,team:x,intent:i.intent,intentLabel:i.intentLabel,session:i.session}),Ee=i.revert===!0&&(i.tools?.length??0)===0,an={dryRun:i.dryRun,fullRevert:Ee};if(!i.revert&&Y.clientKey&&!Pe(Y.clientKey))return a("enroll-failed","Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key.");if(!i.revert&&!Y.clientKey){U("Enrollment required");let L="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return i.dryRun?(P(` ${L}`),M(" Dry run only \u2014 no placeholder configuration will be written."),await RT(h,"after-enrollment"),M(`
|
|
1165
|
+
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,$9=e=>{let t=e?.trim();return t||Ky()},TT=(e=process.stdin)=>new Promise((t,n)=>{let r=N9({input:e,crlfDelay:1/0}),o=!1,a=i=>{o||(o=!0,e.removeListener("error",s),r.close(),t(i))},s=i=>{o||(o=!0,r.close(),n(i))};r.once("line",i=>a(i.trim())),r.once("close",()=>a("")),e.once("error",s)}),Vp=(e,t)=>t||e,Jp=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"--key-stdin":t.keyStdin=!0;break;case"--devcontainer":t.devcontainer=o();break;case"--wsl":t.wsl=o();break;case"--codespace":t.codespace=o();break;case"--enroll":t.enroll=o();break;case"--sso":t.sso=o();break;case"--sign-in":t.signIn=!0;break;case"--desktop-app":t.desktopApp=!0;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},M9=e=>!e||e.length===0?se:e.map(t=>{let n=qe(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${se.map(r=>r.id).join(", ")}`);return n}),jp=e=>e.keyKind==="service"?"service key (agent)":"personal gateway key",B9=(e,t)=>{if(U("Gateway target"),C(` Origin: ${st(e.origin)}`),e.byoUpstream)C(` Auth: BYO upstream key ${v(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&C(` Client key: ${jp(e)} (${Yt(e.clientKey)}) ${v("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=ae(e,"anthropic")?st("your subscription"):"org key",r=ae(e,"openai")?st("your subscription"):"org key";C(` Auth: auto ${v("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&C(` Client key: ${jp(e)} (${Yt(e.clientKey)})`)}else e.authMode==="subscription"?(C(` Auth: subscription pass-through ${v("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&C(` Client key: ${jp(e)} (${Yt(e.clientKey)}) ${v("rides x-anyray-api-key")}`)):e.clientKey?C(` Auth: ${jp(e)} (${Yt(e.clientKey)}) ${v("(replaces the placeholder)")}`):C(` Enrollment: ${v("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&C(` Cursor: ${st("native Team subscription")} ${v("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(ae(e,"anthropic")?(C(` Claude Desktop: ${st("subscription-backed Gateway lane")} ${v("(verified macOS builds; Windows fails closed)")}`),C(` ${v("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(C(` Claude Desktop: ${st("third-party API lane")} ${v("(API-billed; switches the active local inference profile)")}`),C(` ${v("The first-party Claude subscription remains untouched.")}`))),C(` Attribution: ${be(e.metadata)??v("(none \u2014 pass --user)")}`)},F9=e=>{switch(e.kind){case"ssh":return`SSH remote \`${e.name}\``;case"devcontainer":return`dev container \`${e.name}\``;case"attached-container":return`attached container \`${e.name}\``;case"wsl":return`WSL distro \`${e.name}\``;case"codespace":return`Codespace \`${e.name}\``;case"tunnel":return`remote tunnel \`${e.name}\``}},W9=async()=>{let[e,t]=await Promise.all([Op().catch(()=>[]),fb().catch(()=>[])]);for(let n of e)C(` Bind-mounted config file: ${n} ${v("(cannot be replaced atomically; connect writes it in place, verified)")}`);if(t.length>0){U("Other environments you work in");for(let n of t)M(` ${F9(n)}`);C(v(" This run configures only this machine. Run `anyray-connect` inside each of these too \u2014 see docs.anyray.ai/get-started/remote-environments."))}},RT=async(e,t)=>{U("Selected tools");for(let n of e){let r=await n.detect();r.installed?C(` ${n.title} ${v(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):M(` ${n.title} ${v(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},wb=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Pe(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},U9={loadDevKey:Ye,saveDevKey:ll,clearDevKey:qs,saveProfile:de},H9=async(e,t,n,r=U9,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}},OT="blocked by machine policy \u2014 your IT team owns this one",G9=async(e,t,n,r,o)=>{let a=0,s=[],i=[],c=[],l=[],d=[],u=[];for(let p of e){if(!(await p.detect()).installed&&!r){d.push(p.title),u.push(p.id);continue}U(`${p.title} ${v(`(${p.id})`)}`);try{let f=r?await p.revert(n):await p.apply(t,{...n,explicit:o?.has(p.id)===!0,reportsToUser:!0});for(let y of f.messages)C(` ${y}`);a+=f.changedFiles?.length??0;let h=f.status==="manual"&&f.manualAudience==="admin",w=f.messages.join(" ").trim()||(h?OT:void 0);l.push({id:p.id,status:f.status,...w?{reason:w}:{}}),f.status==="configured"||f.status==="reverted"?B(` ${f.status}`):f.status==="manual"?(s.push(p.title),h?(i.push(p.title),c.push(p.id),P(` ${OT}`)):P(" manual step required (see above)")):f.status==="held"?M(" left on its own plan (no change)"):M(` ${f.status}`)}catch(f){let h=f instanceof Error?f.message:String(f);l.push({id:p.id,status:"failed",reason:h}),D(` failed: ${h}`)}}return d.length>0&&M(`Skipped ${d.length} not installed (${d.join(", ")})`),{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l,skippedIds:u}},K9=(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},V9=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>jr(o)&&!r.has(o.id))},j9=async e=>{let t=dO(e,process.platform,oe());if(t){await Se(t.path,t.content);for(let n of uO(t,process.platform))C(` ${n}`)}},Y9=async(e,t,n=Zp())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!BA(i,n)||!MA(i,n))continue;let c=NA(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:$A(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},Z9=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,J9=e=>`
|
|
1166
|
+
${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?`}`,X9=async(e,t={})=>{let n=t.requestQuit??(a=>WA(a)),r=t.waitFor??(a=>UA(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),B(` Closed ${a.title}.`);continue}P(` ${a.title} is still open \u2014 leaving it alone.`),M(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},z9=(e,t={})=>{let n=t.relaunch??(o=>HA(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),B(` Reopened ${o.title}.`)):P(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r};var bb=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,q9=(e,t)=>{switch(t){case"optional":return`${e}: skipped, optional tier (a developer enables it with anyray-connect --tools ${e})`;case"not_enabled":return`${e}: skipped, not in the policy's enabled list`;case"consent":return`${e}: skipped, consent-gated; applies only at the locked tier`;default:return t}},yb=e=>!jr(e),Q9=async(e,t,n={})=>{let r=n.hasEnrollment??hf,o=n.canMultiSelect??TO,a=n.multiSelect??PO,s=n.prompt??gs,i=n.registry??se;if(C(Z("Anyray connect \u2014 guided setup")),C(v("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())C("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 It;c=d.values[0]}else{C(" 1. Paste an enrollment link"),C(" 2. Sign in with SSO"),C(" 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||P("Choose one of the three connection methods.")}if(!c)throw new It;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&_c(d)&&rp(d)){e.enroll=d;break}P("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&&Mt(d)){e.sso=d;break}P("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&&_c(d)){e.enroll=d,C("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=cn(d);break}catch{P("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new It}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=>yb(u)).map(u=>u.id);if(c.length>0){for(let u=0;u<3&&!e.tools;u++){let p;if(o()){let m=await a({title:"Tools to configure",items:c.map(f=>({value:f.id,label:`${f.title} (${f.id})`,hint:bb(f),selected:yb(f),requiresExplicitChoice:!yb(f)}))});if(m.kind==="cancelled")throw new It;p=m.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 f=new Set(c.map(w=>w.id)),h=p.filter(w=>!f.has(w));if(h.length>0){P(`Unknown or unavailable tool id${h.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(p.length===0){P("Choose at least one installed tool.");continue}e.tools=p}if(!e.tools)throw new It}l.length>0&&M(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},eq=async(e,t)=>{U("Verifying the connection");let n=await Ws("Checking the gateway\u2026",()=>Hs(e,{tools:t}));n.kind==="ok"?B(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?P(` ${n.detail}`):D(` ${n.detail}`);for(let r of n.remedy)C(v(` ${r}`))},tq=async(e,t={})=>{if(e.dryRun)return;let n=t.install??Xr,r=t.uninstall??ir;if(e.want&&e.trayManaged){U("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();U("Automatic key refresh");for(let a of o.messages)C(` ${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 de({...await $(),refreshSchedulerInstalledOnce:!0}):await de({...await $(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){U("Automatic key refresh");let o=await r();for(let a of o.messages)C(` ${a}`);await de({...await $(),refreshSchedulerEnabled:!1,refreshSchedulerInstalledOnce:!1}),B(" Removed the automatic key-refresh schedule.")}},nq=new Set(["wizard","status","doctor","sync","device-url"]),rq=new Set(["device-url","status","remote"]),oq=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==="fleet-off"||e.outcome==="fleet-directed")return{level:"warn",message:"Your organization manages anyray-connect updates, so this run did not download a binary; continuing with the current runtime."};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."}},aq=e=>{if(e.includes("--help")||e.includes("--help-all")||e.includes("-h"))return!1;let t=yw(e[0]);if(t)return t.persistsRuntime(e.slice(1));if(e[0]==="desktop"){let n=Iw(e.slice(1));return!!(n&&!n.includes("--dry-run")&&!n.includes("--revert"))}return Hc(e)?e[0]==="doctor"?e.includes("--repair"):!e[0]||!rq.has(e[0]):!1},Ab=()=>kn(process.env.ANYRAY_CLIENT_KEY)==="service",kb=e=>e.includes("--json")&&(e.includes("--desktop-app")||["--sign-in","--sso","--enroll","--claim"].some(t=>e.includes(t))||Ab()),sq=e=>{let t=e[0]==="wizard"?e.slice(1):e;if(!(t[0]&&!t[0].startsWith("-")))try{let n=Jp(t);return{json:!!(n.json&&(n.desktopApp||n.signIn||n.sso||n.enroll||n.claim||Ab())),yes:!!n.yes}}catch{return}},gb=async(e,t,n={})=>{try{return await NT(e,t,n)}catch(r){let o=kb(e);if(r instanceof It)return console.error(v("Cancelled \u2014 nothing was written.")),130;if(r instanceof Error&&r.message==="connect profile is busy; retry the command"){let a="Another Connect update is in progress. Try again.";return D(a),o&&er({event:"error",code:"apply-failed",message:a}),1}if(o){let a="Connect could not apply the configuration.";return D(`${a} (${r instanceof Error?r.name:"Error"})`),er({event:"error",code:"apply-failed",message:a}),1}throw r}},PT=12e4,iq=async(e,t,n,r=Br)=>e&&!t?r(n,{waitMs:PT}):n(),cq=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??Et)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
|
|
1167
|
+
${o} ${n} tool target(s)?`;return await(r.confirm??ca)(a)?"proceed":"declined"},lq=async(e=ks)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0,initiator:"directive"});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";case"fleet-off":return"failed";case"fleet-directed":return"failed";default:return t.outcome}},Cb=e=>NT(e,!1,{managedEnrollmentCarrier:!0}),dq=e=>Fp(Wp(Cb),{json:e}),uq=async()=>{let e=!1,t=await X_(await rn({runAmbientSelfcheck:!0}),{...Wp(Cb),refresh:()=>rn({})});await z_(Wp(Cb)),await Yf(),await TR(),await PR()==="retry"&&(e=!0);let n=await $().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await de(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Aa().catch(()=>!1);if(n&&(await AT(t,{fleetdPresent:async()=>r}).catch(()=>{}),await kT(t).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=nn(),i=n.enrolledCert;if(s&&i){let l=await Ye().catch(()=>{});l&&await m0(o,a,i,l,s).catch(()=>{})}await ST(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await rn({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await pb(d):l==="update"?u=await lq():u=(await Kp()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await ks(),{refresh:t,...e?{partial:!0}:{}}},pq=async(e,t={})=>{if(e[0]==="__anyray-hook"){let a=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return __(a)}if(e[0]==="__anyray-codex-hook")return T_();if(e[0]==="__anyray-prompt-hook")return N_();if(e[0]==="__anyray-shell-pretool")return F_();if(e[0]==="__anyray-shell-run")return B_(e.slice(1));if(e[0]==="__anyray-read-pretool")return Y_();if(e[0]==="__anyray-sso-gate")return L_(e.slice(1));if(e[0]==="__anyray-sso-poll")return q_();if(e[0]==="__anyray-managed-enroll")try{return await Br(()=>dq(e.slice(1).includes("--json")),{waitMs:PT})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return eT();if(e[0]==="__anyray-spawn-refresh")return await Ao(),0;if(e[0]==="__anyray-mcp-server"){let a=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return lT(a)}if(e[0]==="__anyray-acp-agent")return dT(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return Nx(e.slice(1));let n=gT(e);if(n)return bT(n,{refresh:uq});if(e[0]==="__anyray-persistence")return UC(e.slice(1));if(e[0]==="__anyray-quit-watch")return SE(e.slice(1));if(e[0]===uo)return QR(e.slice(1));if(e[0]===Yi)return tO(e.slice(1));if(e[0]===Mo){let a=e[1];return a&&await Uu(a),0}if(e[0]==="--version"||e[0]==="-V")return Q_();try{let a=await rC(e);if(a!==void 0)return a}catch(a){let s=`Could not persist anyray-connect for long-lived integrations: ${a instanceof Error?a.message:String(a)}`;return D(s),kb(e)&&er({event:"error",code:"enroll-failed",message:s}),1}if(aq(e)){let a=oq(await sx());a?.level==="warn"?P(a.message):a&&console.error(a.message)}let r=yw(e[0]);if(r)return r.run(e.slice(1));if(e[0]==="desktop"){let a=e.slice(1),s=Iw(a);return s?gb(s,!1,t.apply):pO(a)}if(e[0]==="remote")return Aq(e.slice(1));let o=e[0];if(o&&nq.has(o)){let a=e.slice(1),s;try{s=Jp(a)}catch(i){return D(i.message),C("\nRun `npx anyray-connect --help` for usage."),1}return s.help?(C(s.helpAll?Yp:_T),0):o==="status"?KO({gateway:s.gateway}):o==="doctor"?Pp({gateway:s.gateway,json:s.json,verify:s.verify,noVerify:s.noVerify,quick:s.quick,repair:s.repair,securityReview:s.securityReview}):o==="sync"?qO({gateway:s.gateway}):o==="device-url"?jR():gb(a,!0,t.apply)}return gb(e,!1,t.apply)},DT=async(e,t={})=>{Yy();let n=sq(e);if(n?.json&&(jy(),!n.yes)){let r="--json enrollment requires --yes.";return er({event:"error",code:"yes-required",message:r}),D(r),1}try{return await pq(e,t)}catch(r){if(r instanceof It)return console.error(v("Cancelled.")),130;throw r}},fq=e=>{let t=process.platform==="win32"?"where":"which";try{return D9(t,[e],{stdio:"ignore"}).status===0}catch{return!1}},mq=(e,t={})=>{let n=t.which??fq,r=t.platform??Zp;switch(e.kind){case"ssh":return!0;case"devcontainer":return n("docker");case"wsl":return r()==="win32"&&n("wsl.exe");case"codespace":return n("gh")}},hq=e=>{switch(e.kind){case"ssh":case"devcontainer":case"wsl":case"codespace":return{kind:e.kind,name:e.name,...e.kind==="devcontainer"&&e.ref?{ref:e.ref}:{}};case"attached-container":case"tunnel":return}},yq=(e,t)=>{switch(e.kind){case"ssh":return`Configure \`${t}\` over SSH now?`;case"devcontainer":return`Configure \`${t}\` in this dev container now?`;case"wsl":return`Configure \`${t}\` in WSL now?`;case"codespace":return`Configure Codespace \`${t}\` now?`}},gq=e=>e.interactive&&!e.managed&&!e.yes&&!e.revert&&!e.dryRun,wq=async(e,t={})=>{if(!gq(e)||!Pe(e.clientKey))return;let n=t.discoverRemoteEnvironments??fb,r;try{r=await n()}catch{return}let o=t.confirm??ca,a=t.runRemoteApply??hb,s=t.isCarrierAvailable??mq,i=t.resolveDevcontainer??mb;for(let c of r){let l=hq(c);if(!l)continue;let d=l;try{if(!await s(d))continue;d.kind==="devcontainer"&&(d={kind:"devcontainer",name:await i(d)})}catch{continue}if(!await o(yq(d,c.name)))continue;let u=await a(d,{gateway:e.gateway,user:e.user,team:e.team,clientKey:e.clientKey});if(u===0){M(`Remote \`${c.name}\` exited with code 0.`);continue}P(`Remote \`${c.name}\` exited with code ${u}.`),M(LT(d.kind))}},LT=e=>{switch(e){case"ssh":return"Fix: ssh in and run `anyray-connect doctor`.";case"devcontainer":return"Fix: open a shell in the container and run `anyray-connect doctor`.";case"wsl":return"Fix: open the distro and run `anyray-connect doctor`.";case"codespace":return"Fix: `gh codespace ssh` in and run `anyray-connect doctor`."}},bq="usage: anyray-connect remote <ssh-host> [--yes] [--dry-run] | remote --devcontainer <host-path> | --wsl <distro> | --codespace <name> [--yes] [--dry-run]",Cq=e=>{let t=/[/\\]/.test(e);return{kind:"devcontainer",name:t?L9(e.replaceAll("\\","/")):e,...t?{ref:e}:{}}},Aq=async(e,t={})=>{if(e[0]==="--help"||e[0]==="-h")return console.log(Yp),0;let n=e[0]&&!e[0].startsWith("-")?e[0]:void 0,r;try{r=Jp(n?e.slice(1):e)}catch(h){return D(h instanceof Error?h.message:String(h)),1}if(r.help)return console.log(Yp),0;let o=[r.devcontainer,r.wsl,r.codespace].filter(h=>h!==void 0);if(n&&o.length>0||!n&&o.length!==1)return D(bq),1;let a=n?{kind:"ssh",name:n}:r.devcontainer!==void 0?Cq(r.devcontainer):r.wsl!==void 0?{kind:"wsl",name:r.wsl}:{kind:"codespace",name:r.codespace};if(a.kind==="devcontainer"&&!a.ref)return D("Cannot resolve a dev container by its bare name; use its full host path."),1;if(a.kind==="wsl"&&(t.platform??Zp)()!=="win32")return D("--wsl is available only on Windows (win32)."),1;let s=t.isInteractive??Et;if(!r.yes&&!s())return D("remote requires a TTY; pass --yes only when you explicitly intend to configure that target."),1;if(r.revert||r.signIn||r.enroll||r.sso||r.claim||r.desktopApp||r.project||r.upstream||r.upstreamKey)return D("remote supports --gateway, --user, --team, --yes, --dry-run, and --key-stdin only."),1;if(r.dryRun)return M(`Dry run: would configure \`${a.name}\` remotely.`),0;let i;if(r.keyStdin)try{i=await TT()}catch{return D("could not read the personal gateway key from stdin."),1}let c=await(t.loadProfile??$)(),l=!r.gateway&&!process.env.ANYRAY_GATEWAY_URL?c.gateway:void 0,d=cn(r.gateway??l),u=i||process.env.ANYRAY_CLIENT_KEY?.trim()||wb(c);if(!Pe(u))return D("A personal gateway key is required. Enroll locally first or provide ANYRAY_CLIENT_KEY (or --key-stdin)."),1;let p=await Jy(r.user,c.name,r.yes),m=await Xy(r.team,c.team,r.yes),f;try{f=await(t.runRemoteApply??hb)(a,{gateway:d,user:p,team:m,clientKey:u})}catch(h){return D(h instanceof Error?h.message:String(h)),1}return f===0?M(`Remote \`${a.name}\` exited with code 0.`):(P(`Remote \`${a.name}\` exited with code ${f}.`),M(LT(a.kind))),f},NT=async(e,t,n={})=>{Yy();let r=kb(e);r&&jy();let o=(L,T)=>{r&&er({event:"error",code:L,message:T})},a=(L,T)=>(D(T),o(L,T),1),s=n.isInteractive??Et,i;try{i=Jp(e)}catch(L){return a("invalid-args",L.message),C("\nRun `npx anyray-connect --help` for usage."),1}let c=i.signIn?"sign-in":i.claim?"claim":i.sso?"sso":i.enroll?"enroll":void 0;if(r&&!i.yes)return a("yes-required","--json enrollment requires --yes.");if(r&&i.dryRun)return a("invalid-args","--json enrollment cannot be combined with --dry-run.");let l=L=>n.managedEnrollmentCarrier===!0&&Bg(L)?"enroll-rejected":L instanceof wt||L instanceof Rt||L instanceof on||L instanceof Ft?L.kind:L instanceof Tc?"gateway-unreachable":L instanceof Pc?"cp-unreachable":L instanceof it&&L.policyCode==="sso_required"?"sso-required":"enroll-failed";if(i.help)return C(i.helpAll?Yp:_T),0;if(i.desktopApp){if(!i.json)return a("invalid-args","--desktop-app is an internal machine interface and requires --json.");if(i.revert)return a("invalid-args","--desktop-app cannot be combined with --revert.");if(i.sso||i.claim||!i.signIn&&!i.enroll)return a("invalid-args","--desktop-app requires exactly one supported carrier: --sign-in or --enroll.");if(i.devcontainer||i.wsl||i.codespace)return a("invalid-args","--desktop-app configures the local machine and cannot target a remote environment.");if(i.machine)return a("invalid-args","--desktop-app accepts a personal user link, not --machine enrollment.")}if(i.signIn&&(i.sso||i.enroll||i.claim))return a("invalid-args","--sign-in cannot be combined with --sso, --enroll or --claim.");if(i.revert&&(i.signIn||i.sso||i.enroll||i.claim))return a("invalid-args","--revert cannot be combined with --sign-in, --sso, --enroll or --claim. It removes Anyray configuration; re-run without --revert to configure a new CLI.");if(i.project)return i.signIn||i.sso||i.enroll||i.subscription||i.upstream?a("invalid-args","--project cannot be combined with --sign-in/--sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."):(Ab()||kn(wb(await $()))==="service")&&!i.revert?a("invalid-args","--project needs a personal enrollment: the committed config gets its key from `anyray-connect print-key`, which mints from an enrollment cert, and a service key has none."):zR({gateway:i.gateway,tools:i.tools,revert:i.revert,dryRun:i.dryRun,yes:i.yes});if(!!i.upstream!=!!i.upstreamKey)return a("invalid-args","--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there.");if(i.upstream&&(i.subscription||i.placeholder))return a("invalid-args","--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.");let d;if(i.upstream){let L;try{L=new URL(i.upstream.trim())}catch{return a("invalid-args",`invalid --upstream URL: "${i.upstream}"`)}if(L.protocol!=="http:"&&L.protocol!=="https:")return a("invalid-args",`invalid --upstream URL: "${i.upstream}" \u2014 must start with http:// or https://`);let T=i.upstreamKey.trim();if(!T)return a("invalid-args","--upstream-key must not be empty.");d={url:ct(i.upstream),key:T}}let u=await $(),p;if(i.keyStdin)try{p=await TT()}catch{return a("apply-failed","could not read the personal gateway key from stdin.")}!d&&!i.subscription&&!i.placeholder&&!i.revert&&(d=u.byoUpstream);let m=!t&&Et()&&!i.gateway&&!i.revert&&!i.yes&&!i.dryRun&&!i.enroll&&!i.sso&&!i.signIn,f=!1;(t||m)&&s()&&(i=await(n.runWizard??Q9)(i,u),f=!0);let h;try{h=M9(i.tools)}catch(L){return a("apply-failed",L.message)}C(Z(i.revert?"Anyray connect \u2014 revert":"Anyray connect")),i.gateway&&!i.enroll&&_c(i.gateway)&&(i.enroll=i.gateway,i.gateway=void 0,C("That looks like an enrollment link \u2014 treating it as --enroll."));let w,y,g,b,k=!1;if(i.enroll){let L=rp(i.enroll);if(L&&(i.desktopApp||!i.gateway||u.enrolledCert||Pg(L.token)))try{let T=await Ws("Resolving enrollment link\u2026",()=>(n.resolveEnrollLink??c0)(L)),V=!i.gateway;if(V&&(i.gateway=T.gatewayUrl),w=T.deploymentId,y=T.email,g=T.provisioningKind,b=T.allowedDomains,k=!0,i.desktopApp&&!T.email)return a("invalid-link","The desktop app accepts personal links only. Ask your admin for a personal link.");V&&M(`Enrollment link${T.org?` for ${T.org}`:""}: gateway ${T.gatewayUrl}`),T.seatMode&&!i.subscription&&(i.subscription=!0,M("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(T){if(i.desktopApp)return a("enroll-failed","The desktop app could not verify that this is a personal link. Try again or ask your admin for a new personal link.");if(Pg(L.token))return a(l(T),T instanceof Error?T.message:String(T));let V=i.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||u.gateway;if(V)M(`Could not resolve the gateway from the enrollment link \u2014 using ${V}.`);else return a("enroll-failed",T instanceof Error?T.message:String(T))}}let A,x;if(r&&await(n.clearGateState??Vc)(),i.claim&&!i.revert)if(i.dryRun)M("dry run: not enrolled (skipped redeeming the enrollment link).");else{let L=A0(i.claim);if(!L)return a("invalid-link","invalid --claim value: expected the sdc_ code from your organization's Anyray page.");try{let T=await Ws("Connecting this machine\u2026",()=>(n.redeemClaim??k0)({cpOrigin:L.cpOrigin,claim:L.claim,gatewayUrl:i.gateway}));A={cert:T.cert,privateKeyPem:T.privateKeyPem},T.deploymentId&&(w=T.deploymentId),!i.gateway&&T.gatewayUrl&&(i.gateway=T.gatewayUrl),x=T.ssoLink}catch(T){return a(l(T),T instanceof Error?T.message:String(T))}}if(i.sso&&!A&&!i.revert)if(i.dryRun)M("dry run: not enrolled via SSO (skipped minting a personal key).");else{let L=Mt(i.sso);if(!L){let T=_c(i.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.";return a("invalid-link",T)}try{let T=await(n.startDeviceGrant??op)({cpOrigin:L.cpOrigin,tenantId:L.tenantId,gatewayUrl:i.gateway,log:r?void 0:_e=>M(_e),open:!r&&s()?Rr:void 0});r&&er({event:"sso_grant",verificationUriComplete:T.verificationUriComplete,userCode:T.userCode,expiresAt:new Date(T.grantExpiresAt).toISOString(),tenantId:T.tenantId});let V=await Ws("Waiting for SSO sign-in\u2026",()=>(n.pollDeviceGrant??ap)(T,{gatewayUrl:i.gateway}));A={cert:V.cert,privateKeyPem:V.privateKeyPem},V.deploymentId&&(w=V.deploymentId),!i.gateway&&V.gatewayUrl&&(i.gateway=V.gatewayUrl)}catch(T){return a(l(T),T instanceof Error?T.message:String(T))}}if(i.signIn&&!A&&!i.revert)if(i.dryRun)M("dry run: not signed in (skipped minting a personal key).");else{let L;try{let T=await(n.createDesktopSignInCallbackListener??SO)();L=T;let V=await(n.startDesktopSignIn??RO)({callbackUri:T.callbackUri,log:r?void 0:tt=>M(tt),open:!r&&s()?Rr:void 0});r&&er({event:"sso_grant",verificationUriComplete:V.browserUrl,userCode:V.userCode,expiresAt:new Date(V.grantExpiresAt).toISOString()});let _e=await Ws("Waiting for sign-in\u2026",async()=>{let tt=await T.waitForCompletion(V);return(n.pollDesktopSignIn??OO)(V,{completion:tt})});A={cert:_e.cert,privateKeyPem:_e.privateKeyPem},_e.deploymentId&&(w=_e.deploymentId),!i.gateway&&_e.gatewayUrl&&(i.gateway=_e.gatewayUrl)}catch(T){return a(l(T),T instanceof Error?T.message:String(T))}finally{await L?.close()}}let _=!i.gateway&&!process.env.ANYRAY_GATEWAY_URL?u.gateway:void 0;_&&(i.gateway=_);let S;try{S=cn(i.gateway)}catch(L){return a("enroll-failed",L.message)}let I,E;_&&!i.revert&&M(`Gateway: ${S} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!i.revert&&Sb(S)&&P(`${S} 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 O=p??process.env.ANYRAY_CLIENT_KEY?.trim(),K=O||wb(u),G,X,re,ke,fe,W,Q=async L=>{await ga();let T=u0(L.token),V=h0(u.enrolledCert,u.enrolledCertExpiry,L.deploymentId,Date.now(),T,u.enrolledTokenHash,L.expectedUser),_e=V?await Ye():void 0,tt=nn()||void 0,Ut=V&&_e&&u.enrolledCert?{cert:u.enrolledCert,privateKeyPem:_e,publicKeyPem:u.enrolledCert.payload.devPublicKey}:void 0,Ct=Te=>(n.enrollAndVerify??y0)({cpOrigin:L.cpOrigin,token:L.token,gatewayOrigin:S,email:L.email,team:L.team,machineId:L.machineId,deploymentId:L.deploymentId,machineUuid:tt,reuse:Te?Ut:void 0}),Ve=!!Ut,je=await(async()=>{try{return await Ct(Ve)}catch(Te){if(Ut&&Te instanceof it&&Te.policyCode!=="managed_device_required")return M("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),Ve=!1,await Ct(!1);throw Te}})();K=je.clientKey,i.user=Vp(i.user,je.user),i.team=Vp(i.team,je.team),G=je.cert,X=je.cert.payload.expiresAt,W=je.expiresAt,fe=void 0,Ve||(re=je.privateKeyPem),Ve||(ke=T),B(`Enrolled${je.user?` as ${je.user}`:""}${Ve?" (reused your saved cert)":""} \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)};if(i.enroll&&!i.revert)if(i.dryRun)M("dry run: not enrolled (skipped minting a personal key).");else{let L=rp(i.enroll);if(!L){let T=i0(i.enroll),V=T?`that is ${T.what}, not an enrollment link \u2014 re-run with ${T.flag} instead of --enroll.`:Mt(i.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.";return a("invalid-link",V)}try{let T=i.machine?hp():void 0,V=g==="mdm"&&!y?AO():void 0,_e=g==="mdm"&&!y&&!V?CO(b,_u()):void 0,tt=V??_e;if(tt){let Ve=V?"the email your MDM assigned to this machine":`${tt} (this Mac's login name at the first allowed domain)`;C(i.user?.trim()&&i.user.trim()!==tt?`Ignoring --user: enrolling as ${Ve}.`:`Enrolling as ${Ve}.`)}let Ut=y??tt??$9(i.user);if(!i.machine&&!i.user&&!y&&!tt){let Ve=OE();Ve.distinct||(P(` Enrolling as "${Ve.identity}" \u2014 this may not be unique to you.`),P(Ve.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"),P(Ve.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."),P(" Re-run with `--user you@company.com` (or set `git config --global"),P(" user.email`) so your usage is attributed to you."))}let Ct=i.machine?`machine:${T}`:k?Ut:void 0;await Q({cpOrigin:L.cpOrigin,token:L.token,email:Ut,team:i.team,machineId:T,deploymentId:w,expectedUser:Ct})}catch(T){let V=T instanceof Error?T.message:String(T);return D(V),o(l(T),V),T instanceof it&&T.policyCode!=="managed_device_required"&&M("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),Bg(T)?3:1}}if(A){await ga();try{let L=nn()||void 0,T=await(n.verifyWithGateway??An)(S,A.cert,A.privateKeyPem,{machineUuid:L});K=T.key,i.user=Vp(i.user,T.user),i.team=Vp(i.team,T.team),G=A.cert,X=A.cert.payload.expiresAt,re=A.privateKeyPem,W=T.expiresAt;let V=i.sso?Mt(i.sso):void 0;fe=V?`${V.cpOrigin}/sso/${V.tenantId}`:x,B(`Enrolled${T.user?` as ${T.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(L){let T=L instanceof Error?L.message:String(L);return D(T),o(l(L),T),L instanceof it&&L.policyCode!=="managed_device_required"&&M("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}let ye=kn(K);if(!i.revert)if(ye==="service")(i.user!==void 0||i.team!==void 0)&&M("Service key: identity comes from the key; --user/--team ignored.");else{let L=i.yes;I=await Jy(i.user,u.name,L),E=await Xy(i.team,u.team,L)}if(!i.revert&&!i.dryRun){let L=WO(await FO(S,K),{subscription:i.subscription,org:i.placeholder,byoUpstream:!!d});if(L.lane){let T=L.lane==="subscription";i.subscription=T,i.placeholder=!T;let V=T?"your own subscription seat":"the organization's provider account";L.overrodeFlag?M(`Your administrator assigns this machine to ${V}, so that is what was applied (it overrides the lane flag you passed).`):M(`Billing lane set by your administrator: ${V}.`)}}let we;!i.revert&&!i.subscription&&!i.placeholder&&(we=await Wn(),U("Detecting your sign-ins"),C(` Claude (Anthropic): ${d?st("BYO upstream key (passthrough)"):we.anthropic?st("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),C(` Codex (ChatGPT): ${we.openai?st("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),(!we.anthropic||!we.openai)&&K&&await GO(xe({origin:S,placeholderKey:i.key,clientKey:K,subscription:!1,placeholder:!0,byoUpstream:d,user:I,team:E,intent:i.intent}))===!1&&(P(" This gateway holds NO server-side provider key, so the org-key"),P(" fallback above cannot serve a request \u2014 it answers 424, not 401."),we.copilot?(P(" Your Copilot seat DOES work and never touches the org key: prefer"),P(" `github-copilot/...` models in OpenCode and Copilot Chat until an"),P(" admin adds a provider key in the console \u2192 Providers.")):(P(" No subscription seat here works either. Sign in to Copilot or"),P(" Claude, or have an admin add a provider key in console \u2192 Providers."))),!we.anthropic&&!we.openai&&!we.copilot&&ar()&&(P(" No subscription sign-ins found on this host. Sign-ins do not cross the"),P(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),P(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),P(" and re-run, or everything below routes on the org key instead.")));let Y=xe({origin:S,placeholderKey:i.key,clientKey:K,subscription:i.subscription,placeholder:i.placeholder,byoUpstream:d,seat:we,user:I,team:E,intent:i.intent,intentLabel:i.intentLabel,session:i.session}),Ee=i.revert===!0&&(i.tools?.length??0)===0,an={dryRun:i.dryRun,fullRevert:Ee};if(!i.revert&&Y.clientKey&&!Pe(Y.clientKey))return a("enroll-failed","Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key.");if(!i.revert&&!Y.clientKey){U("Enrollment required");let L="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return i.dryRun?(P(` ${L}`),M(" Dry run only \u2014 no placeholder configuration will be written."),await RT(h,"after-enrollment"),M(`
|
|
1168
1168
|
Dry run complete \u2014 no files were written.`),0):a("enroll-failed",` ${L}`)}i.revert||B9(Y,h);let Pr=!i.revert&&!i.yes&&s();(f||Pr)&&!i.revert&&await RT(h,"plan"),Pr&&await W9(),i.dryRun&&M(`
|
|
1169
1169
|
Dry run \u2014 no files will be written.`);let Dr=await cq(i,f,h.length,{isInteractive:s,confirm:n.confirm});if(Dr==="non-interactive")return a("apply-failed",`
|
|
1170
1170
|
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`);if(Dr==="declined")return M(f?"Nothing was written. Re-run `npx anyray-connect wizard` when you're ready.":"Aborted. Nothing changed."),0;if(!i.dryRun&&!i.revert&&!i.force){let L=await Ip(Y.origin);if(!L.reachable){let T=`
|
|
1171
1171
|
Gateway ${Y.origin} is not reachable (${L.detail}).`;return D(T),o("gateway-unreachable",T),C(v(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1172
1172
|
that would break them until you re-run with --revert.`)),C(`
|
|
1173
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1}B(`Gateway reachable (${L.detail}).`)}let Lr=i.revert?[]:await Y9(h,Y.origin),Io=[],tl=()=>{Io.length!==0&&(U("Reopening"),z9(Io),Io=[])};if(Lr.length>0){let L=Lr.map(V=>V.title),T=L.length===1?"it":"them";if(U("Open apps"),Z9(i,Et()))i.quitApps===!0||await
|
|
1174
|
-
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),C("Run --revert with no --tools to remove it."));let je=h,Te=[],tr;if(n.managedEnrollmentCarrier===!0){let z=u.fleetToolPolicy,le=z?"cached admin list (no key to fetch with)":"none (no key to fetch with)";if(Y.clientKey)try{let ve=await(n.fetchTeamPolicy??
|
|
1173
|
+
Start the gateway and try again, or pass --force to configure anyway.`),1}B(`Gateway reachable (${L.detail}).`)}let Lr=i.revert?[]:await Y9(h,Y.origin),Io=[],tl=()=>{Io.length!==0&&(U("Reopening"),z9(Io),Io=[])};if(Lr.length>0){let L=Lr.map(V=>V.title),T=L.length===1?"it":"them";if(U("Open apps"),Z9(i,Et()))i.quitApps===!0||await ca(J9(L))?Io=await X9(Lr):M(` Leaving ${T} open \u2014 restart when convenient.`);else{let V=i.noQuitApps===!0?"":" (or pass --quit-apps)";M(i.dryRun?` Would offer to quit ${L.join(", ")} \u2014 dry run, nothing was closed.`:` ${L.join(", ")} ${L.length===1?"is":"are"} open; restart ${T} to pick this up${V}.`)}}let js=async()=>{if(!i.dryRun)try{await lt()}catch{return a("enroll-failed","Could not prepare the owner-only Anyray state directory.")}let L=u.anyrayFleetManaged===!0&&await Aa().catch(()=>!1),T=xx(i,Zp(),L),V=!!(O&&Y.clientKey===O&&!G),_e=rt({...u,enrolledCert:G??u.enrolledCert},{toolIds:h.map(z=>z.id),keyExpiresAt:W}),tt=Y.keyKind==="service",Ut=!i.revert&&i.noKeyRefresh!==!0&&!V&&!tt&&_e,Ct=i.dryRun?await La(u):await Yf(),Ve=Ct==="healthy";if(Ct==="healed"&&(delete u.persistenceOwner,delete u.trayAppPath),!i.revert&&!i.dryRun){let z={...u,managedEnrollmentDisabled:void 0,gateway:Y.origin,name:I,team:E,clientKey:Y.clientKey??u.clientKey,enrolledCert:V?void 0:G??u.enrolledCert,enrolledCertExpiry:V?void 0:X??u.enrolledCertExpiry,enrolledTokenHash:V?void 0:ke??u.enrolledTokenHash,ssoLink:V?void 0:A?fe:G?void 0:u.ssoLink,clientKeyExpiresAt:V?void 0:W??(Y.clientKey===u.clientKey?.trim()?u.clientKeyExpiresAt:void 0),authMode:Y.authMode,byoUpstream:Y.byoUpstream,refreshSchedulerEnabled:Ut};try{await(n.withProfileLock??Br)(()=>H9(u,z,re,void 0,V))}catch{return a("enroll-failed","Could not save the owner-only Anyray runtime profile. No tool configuration was changed.")}r&&c&&(await(n.clearGateState??Vc)().catch(()=>{}),er({event:"enrolled",via:c,...I?{user:I}:{},...E?{team:E}:{},authMode:Y.authMode,gateway:Y.origin,...w??G?.payload.deploymentId?{deploymentId:w??G?.payload.deploymentId}:{},...X?{certExpiresAt:X}:{},...Y.keyKind?{keyKind:Y.keyKind}:{}})),W&&!V&&await $s({expiresAt:W})}if(Ee)if(i.dryRun)await hf()&&(U("Enrollment"),C(" would remove the stored gateway credential"));else{await cb(u),await kp().catch(()=>{});try{await pl()&&(U("Enrollment"),B(" Removed the stored gateway credential."),M(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(z){U("Enrollment"),P(" Could not remove the stored gateway credential."),P(` Delete ${oe()} by hand, or a credential refresh may restore your tool config.`)}}else i.revert&&!i.dryRun&&(C(`
|
|
1174
|
+
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),C("Run --revert with no --tools to remove it."));let je=h,Te=[],tr;if(n.managedEnrollmentCarrier===!0){let z=u.fleetToolPolicy,le=z?"cached admin list (no key to fetch with)":"none (no key to fetch with)";if(Y.clientKey)try{let ve=await(n.fetchTeamPolicy??ma)(Y.origin,Y.clientKey);z=ve.tools;let $r=Xg(ve),{fleetToolPolicy:Xp,...$T}=await $();await de({...$T,...$r?{fleetToolPolicy:$r}:{}}),le=z?z.defaulted===!0?"gateway default (no tool policy saved)":`admin list from the gateway (${z.enabled?.length??0} enabled)`:"none served by the gateway"}catch{z=u.fleetToolPolicy,le=z?"cached admin list (gateway unreachable this run)":"none (gateway unreachable, nothing cached)"}tr=U0(u,z,se);let sn=new Set(tr.applyIds);je=se.filter(ve=>sn.has(ve.id)),U("Fleet policy"),C(` Policy: ${le}`);for(let ve of tr.skipped)P(` ${q9(ve.id,ve.reason)}`);for(let ve of tr.revertIds)P(` ${ve}: reverting, removed from the policy's enabled list`)}else if(Te=V9(je,i,u.managedTools),Te.length>0){U("Not configured \u2014 needs your say-so");for(let le of Te)P(` ${le.id}: ${bb(le)??"changes where inference is billed"}.`),C(` Configure it deliberately with \`npx anyray-connect --tools ${le.id}\`.`);let z=new Set(Te.map(le=>le.id));je=je.filter(le=>!z.has(le.id))}if(i.revert&&!Ee){let z=h.filter(le=>$c(u,le.id));if(z.length>0){U("Fleet policy");for(let le of z)P(` ${le.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);je=h.filter(le=>!$c(u,le.id))}}let{changes:J,manual:At,manualAdminOnly:Eo,manualAdminOnlyIds:xo,results:Nr,skippedIds:va}=await G9(je,Y,an,i.revert,new Set(i.tools??[]));if(tr)for(let z of tr.revertIds){let le=await pb(z);Nr.push(le==="ok"?{id:z,status:"reverted"}:{id:z,status:"failed",reason:"revert failed"})}r&&er(NO([...Nr,...Te.map(z=>({id:z.id,status:"held",reason:bb(z)??"changes where inference is billed"}))],Y.keyKind,tr?.skipped));let nl;if(bg(i)){U("Endpoint agent");try{nl=await(n.installEndpointAfterEnrollment??$x)({gateway:S,clientKey:Y.clientKey})}catch{M("Endpoint agent setup did not complete. Tool routing remains configured.")}}let Ys=T&&Ex(nl),rl=Ut&&!Ys;if(T&&!Ys&&Ut&&!i.dryRun&&M(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),Ys&&!i.dryRun&&await de({...await $(),refreshSchedulerEnabled:!1}).catch(()=>{}),i.dryRun||(await Fr(Nr,i.revert,Ee).catch(()=>{}),i.revert||await de({...await $(),toolSelection:(i.tools?.length??0)>0?"explicit":"all"}).catch(()=>{}),Ee&&await fl().catch(()=>{})),await tq({want:rl,scopedRevert:!!i.revert&&!Ee,dryRun:!!i.dryRun,wasEnabled:!!u.refreshSchedulerEnabled||!rl&&await Fl(),trayManaged:Ve}),!i.revert&&!i.dryRun)if(nC(u.managedTools,Nr,va)){let z=await gl().catch(()=>[]);z.length&&M(` Removed ${z.length} unused Anyray runtime copies.`)}else M(" Kept older Anyray runtime copies: a managed tool this run did not rewrite may still use one.");if(!i.revert&&!i.dryRun&&!V){let z=re??await Ye();z&&await fw(await $(),z).catch(()=>{})}if(!i.revert&&!i.dryRun){U("Team content");try{let z=await(n.seedTeamContent??dp)(await $());if(!z)M(" Skipped: no enrolled key on this seat.");else{let le=z.skills?.summary;le?le.changed>0||le.removed.length>0?B(` Org skills: ${le.changed} written, ${le.removed.length} removed across ${z.skills?.dirs.length??0} dir(s).`):M(" Org skills: up to date."):M(" Org skills: not written this run; the next pull retries.");let sn=z.mcp;sn?sn.changed.length>0?B(` Org connectors: ${sn.served?"registered":"removed"} the anyray-org MCP entry in ${sn.changed.join(", ")}.`):M(sn.served?" Org connectors: up to date.":" Org connectors: none published."):M(" Org connectors: not written this run; the next pull retries.")}}catch(z){M(` Skipped (${Ts(z)}); the background refresh retries.`)}}if(tl(),U("Summary"),i.dryRun)M("Dry run complete \u2014 re-run without --dry-run to apply.");else if(i.revert){B(`Reverted (${J} file(s) touched).`),M("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let z=await XR();z.length>0&&(U("This repo carries its own Anyray routing"),P(` Committed here: ${z.join(", ")}`),P(" Those are tracked files, so they route every checkout of this"),P(" repo \u2014 this machine included, and your teammates' too. This"),P(" revert only removed THIS machine's own configuration."),C(`
|
|
1175
1175
|
Remove them from the repo (then commit):`),C(v(" anyray-connect --project --revert")));let le=ql(Y);le.length>0&&(U("This terminal still points at the gateway"),P(` Still exported here: ${le.join(", ")}`),P(" Removing the block from your shell profile cannot reach a shell"),P(" that already ran it. Until these are gone, your tools keep"),P(" reaching the gateway and now fail with 401."),C(`
|
|
1176
1176
|
Fix this terminal:`),C(v(` unset ${le.join(" ")}`)),C(`
|
|
1177
|
-
Every other open terminal needs the same \u2014 or just open a new one.`),C(" VS Code injects a copy it captured when IT launched, so its"),C(" terminals stay stale even if you open a new one: quit the app"),C(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(B(`Done (${J} file(s) written).`),At.length>0){let ve=Eo.length===At.length;U(ve?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let $r of K9(At,Eo,xo.includes("claude-desktop")?process.platform:void 0))P($r);if(xo.includes("claude-desktop")&&!i.dryRun)try{await j9(Y)}catch{P(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}Et()&&!i.yes&&!ve&&(await
|
|
1177
|
+
Every other open terminal needs the same \u2014 or just open a new one.`),C(" VS Code injects a copy it captured when IT launched, so its"),C(" terminals stay stale even if you open a new one: quit the app"),C(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(B(`Done (${J} file(s) written).`),At.length>0){let ve=Eo.length===At.length;U(ve?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let $r of K9(At,Eo,xo.includes("claude-desktop")?process.platform:void 0))P($r);if(xo.includes("claude-desktop")&&!i.dryRun)try{await j9(Y)}catch{P(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}Et()&&!i.yes&&!ve&&(await ca("Have you applied the manual settings shown above?")?B("Acknowledged."):P("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}i.skipVerify?M(`
|
|
1178
1178
|
Skipped the connection smoke test (--skip-verify).`):await eq(Y,h.map(ve=>ve.id)),U("What's next");let z=new Set(Nr.filter(ve=>ve.status==="configured").map(ve=>ve.id)),le=h.filter(ve=>z.has(ve.id)).map(ve=>ve.title);if(C(le.length>0?` Connected: ${le.join(", ")}`:" Connected: no tools completed automatic configuration."),C(" Restart any editor that was already running \u2014 it loaded our config at startup."),C(" If something looks wrong: npx anyray-connect doctor"),Y.keyKind==="personal"&&Y.clientKey&&await wq({interactive:Et(),managed:n.managedEnrollmentCarrier===!0,yes:!!i.yes,revert:!!i.revert,dryRun:!!i.dryRun,gateway:Y.origin,user:Y.metadata.user,team:Y.metadata.team,clientKey:Y.clientKey}),!i.verbose)return 0;C(`
|
|
1179
1179
|
Re-test by hand any time:`),Y.authMode!=="placeholder"&&h.length===1&&h[0]?.id==="cursor"?(C(v(` curl -sS ${Y.origin}/connect/savings \\
|
|
1180
1180
|
-H "x-anyray-api-key: $(anyray-connect print-key)"`)),C(v(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):C(v(` curl -sS ${Y.openaiBaseUrl}/chat/completions \\
|
|
1181
1181
|
-H "Content-Type: application/json" \\
|
|
1182
1182
|
-H "Authorization: Bearer ${Y.clientKey?`<your personal key (${Yt(Y.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
|
|
1183
|
-
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),C(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await iq(i.revert,i.dryRun,
|
|
1183
|
+
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),C(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await iq(i.revert,i.dryRun,js,n.withProfileLock)}catch(L){if(L instanceof Error&&L.message==="connect profile is busy; retry the command")return a("apply-failed","Another Connect update is in progress. Try again.");if(r){let T="Connect could not apply the configuration.";return D(`${T} (${L instanceof Error?L.name:"Error"})`),o("apply-failed",T),1}throw L}finally{tl()}};DT(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
|