anyray-connect 0.11.211 → 0.11.212
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 +146 -146
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var JP="http://localhost:8787",pi="anyray-placeholder",lk=/^ark_[A-Za-z0-9_-]{20,512}$/,XP="ark_svc_",zP=/^ark_svc_[A-Za-z0-9_-]{20,512}$/,Pe=e=>{let t=e?.trim();return!!(t&&lk.test(t))};var In=e=>{let t=e?.trim();if(t){if(zP.test(t))return"service";if(!t.startsWith(XP))return lk.test(t)?"personal":void 0}},dt=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},If=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,qP=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),dk=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!qP.has(n)}catch{return!1}},dn=e=>{let t=dt(e||process.env.ANYRAY_GATEWAY_URL||JP),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},Re=(e={})=>{let t=dn(e.origin),n=e.placeholderKey?.trim()||pi,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:If(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:If(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:If(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:In(r),authMode:a,byoUpstream:e.byoUpstream,seat:a==="auto"?e.seat:void 0,metadata:o}};import{homedir as td,platform as ym}from"node:os";import{join as Go}from"node:path";import{mkdir as fm,readFile as
|
|
3
|
-
`,{mode:384})}catch(c){throw await
|
|
4
|
-
`,{mode:384}),await Pf(r,384);try{await ke(r,n)}catch(o){throw await
|
|
2
|
+
var JP="http://localhost:8787",pi="anyray-placeholder",lk=/^ark_[A-Za-z0-9_-]{20,512}$/,XP="ark_svc_",zP=/^ark_svc_[A-Za-z0-9_-]{20,512}$/,Pe=e=>{let t=e?.trim();return!!(t&&lk.test(t))};var In=e=>{let t=e?.trim();if(t){if(zP.test(t))return"service";if(!t.startsWith(XP))return lk.test(t)?"personal":void 0}},dt=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},If=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,qP=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),dk=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!qP.has(n)}catch{return!1}},dn=e=>{let t=dt(e||process.env.ANYRAY_GATEWAY_URL||JP),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},Re=(e={})=>{let t=dn(e.origin),n=e.placeholderKey?.trim()||pi,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:If(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:If(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:If(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:In(r),authMode:a,byoUpstream:e.byoUpstream,seat:a==="auto"?e.seat:void 0,metadata:o}};import{homedir as td,platform as ym}from"node:os";import{join as Go}from"node:path";import{mkdir as fm,readFile as NN,rename as LN,writeFile as ql,rm as Ho}from"node:fs/promises";import{spawnSync as $N}from"node:child_process";import{homedir as Xl}from"node:os";import{join as zl}from"node:path";var Ef=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,xl=(e,t)=>[e,...t].map(Ef).join(" "),cr=(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}:{}}]}),Gr=(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))},Na=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!Gr(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},En=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!Gr(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)},xf=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=>!Gr(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};import{access as RD}from"node:fs/promises";import{spawnSync as fD}from"node:child_process";import{readFileSync as mD,realpathSync as gi,statSync as kk}from"node:fs";import{access as hD,cp as Ck,mkdir as wk,readdir as yD,readFile as Ff,realpath as gD,rename as wD,rm as Mf,writeFile as bD}from"node:fs/promises";import{tmpdir as kD}from"node:os";import{basename as Ma,dirname as ze,join as Be,resolve as CD}from"node:path";import{writeFile as _l,readFile as mi,chmod as Pf,stat as Df,mkdir as mk,rm as La}from"node:fs/promises";import{AsyncLocalStorage as aD}from"node:async_hooks";import{randomUUID as QP}from"node:crypto";import{lstat as Rf,open as eD,readFile as Of,rename as Rl,rm as tD,writeFile as nD}from"node:fs/promises";import{platform as uk}from"node:os";var pk=e=>e?.code==="ENOENT",rD=new Set(["EBUSY","EXDEV","ETXTBSY"]),Kr=async(e,t=uk())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},Do=class extends Error{recoveryCopy;code="ANYRAY_PUBLISH_CONFLICT";constructor(t){super("destination changed before publication"),this.recoveryCopy=t,this.name="PublishConflictError"}},oD=async(e,t,n={})=>{let r=await Of(e),o;try{o=await Of(t)}catch(s){if(!pk(s))throw s;await nD(t,r);return}let a=async s=>{let i=await eD(t,"r+");try{await i.write(s,0,s.length,0),await i.truncate(s.length),await Kr(i)}finally{await i.close()}};try{if(await a(r),await n.corruptAfterWrite?.(t),!(await Of(t)).equals(r))throw Object.assign(new Error("in-place publication did not persist"),{code:"EIO"})}catch(s){throw await a(o).catch(()=>{}),s}},ke=async(e,t,n=uk(),r={})=>{let o=r.rename??Rl;if(n!=="win32"){try{await o(e,t)}catch(i){if(!rD.has(i?.code??""))throw i;await oD(e,t,r)}return}let a=`${t}.anyray-old-${process.pid}-${QP()}`,s=!1;try{let i=await Rf(t);if(!i.isFile()&&!i.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await Rl(t,a),s=!0}catch(i){if(!pk(i))throw i}if(s&&r.verifyDisplaced){let i=!1;try{i=await r.verifyDisplaced(a)}catch{i=!1}if(!i){let c=!1;try{await Rf(t),c=!0}catch{c=!1}if(c)throw new Do(a);try{await o(a,t)}catch(l){let d=l?.code==="EEXIST";if(!d)try{await Rf(t),d=!0}catch{d=!1}throw d?new Do(a):new Error(`destination changed before publication and could not be restored; recovery copy remains at ${a}`,{cause:l})}throw new Do}}try{await Rl(e,t)}catch(i){if(s)try{await Rl(a,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${a}`)}throw i}s&&await tD(a,{force:!0})};import{randomUUID as sD}from"node:crypto";import{homedir as hk}from"node:os";import{join as No}from"node:path";var ee=()=>No(hk(),".anyray"),yk=async()=>{let e=ee();try{if((await Df(e)).isDirectory())return No(e,"connect.json")}catch{}return e},Nf=()=>No(ee(),"dev-key.pem"),Xe=async()=>{let e=ee(),t;try{if(!(await Df(e)).isDirectory())t=await mi(e,"utf-8").catch(()=>{}),await La(e,{force:!0});else return}catch{}if(await mk(e,{recursive:!0,mode:448}),t!==void 0){let n=No(e,"connect.json");await _l(n,t,{mode:384}),await Pf(n,384)}},Tl=async e=>{await Xe();let t=Nf();await _l(t,e,{mode:384}),await Pf(t,384)},Ye=async()=>{try{let e=await mi(Nf(),"utf-8");return e.trim()?e:void 0}catch{return}},hi=async()=>{await La(Nf(),{force:!0}).catch(()=>{})},L=async()=>{try{let e=await mi(await yk(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}},iD=0,cD=3e4,gk=5e3,lD=25,dD=()=>No(hk(),".anyray-connect-profile.lock"),Ol=new aD,uD=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},pD=async(e,t)=>{try{let n=JSON.parse(await mi(No(e,"owner.json"),"utf-8"));if(typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0)return!uD(n.pid)}catch{}return Date.now()-(await Df(e)).mtimeMs>t},fi=class extends Error{constructor(t){super(t),this.name="LockBusyError"}},$a=async(e,t={})=>{let n=t.waitMs??gk,r=t.staleMs??cD,o=No(e,"owner.json"),a=Date.now()+n;for(;;){let s=sD();try{await mk(e,{mode:448});try{await _l(o,`${JSON.stringify({pid:process.pid,nonce:s})}
|
|
3
|
+
`,{mode:384})}catch(c){throw await La(e,{recursive:!0,force:!0}).catch(()=>{}),c}return async()=>{try{JSON.parse(await mi(o,"utf-8")).nonce===s&&await La(e,{recursive:!0,force:!0})}catch{}}}catch(c){if(c.code!=="EEXIST")throw c}if(!(await pD(e,r).catch(()=>!1)&&await La(e,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=a)throw new fi(t.busyMessage??`${e} is busy; retry the command`);await new Promise(c=>setTimeout(c,lD))}}},Lf=(e=gk)=>$a(dD(),{waitMs:e,busyMessage:"connect profile is busy; retry the command"}),xn=async(e,t={})=>{if(Ol.getStore()===!0)return e();let n=await Lf(t.waitMs);try{return await Ol.run(!0,e)}finally{await n()}},_f=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await yk(),r=`${n}.${process.pid}.${iD++}.tmp`;await _l(r,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`,{mode:384}),await Pf(r,384);try{await ke(r,n)}catch(o){throw await La(r,{force:!0}).catch(()=>{}),o}},pe=async e=>{if(Ol.getStore()===!0){await _f(e);return}let t=await Lf();try{await _f(e)}finally{await t()}},yi=async e=>{let t=async()=>{let r=await L(),{next:o,result:a}=e(r);return o&&await _f(o),a};if(Ol.getStore()===!0)return t();let n=await Lf();try{return await t()}finally{await n()}},Tf=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],fk="ssoLink",$f=async()=>{let e=await L();return Tf.some(t=>e[t]!==void 0)?!0:await Ye()!==void 0},Pl=async()=>{let e=await L(),t=Tf.some(a=>e[a]!==void 0),n=e[fk]!==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 Tf)delete a[s];delete a[fk],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,delete a.anyrayFleetManaged,await pe(a)}if(await hi(),await Ye())throw new Error(`could not remove the dev key from ${ee()}`);return t||n||r||o},Vr=async(e,t,n=!1)=>{let r=await L(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=new Set(r.blockedTools??[]),i=r.offboardedAt;for(let w of e){let b=w.status==="configured"||w.status==="queued";!t&&b&&(o.add(w.id),a.delete(w.id),s.delete(w.id),i=void 0),!t&&w.refused===!0&&s.add(w.id),t&&(w.status==="reverted"||w.status==="queued")&&(o.delete(w.id),a.add(w.id),s.delete(w.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=(w,b)=>w.length===b.length&&w.every((A,C)=>A===b[C]);if(f(c,l)&&r.revertedTools!=null&&f(d,u)&&f(p,m)&&i===r.offboardedAt)return;let{offboardedAt:g,...y}=r;await pe({...y,...i!==void 0?{offboardedAt:i}:{},managedTools:c,revertedTools:d,blockedTools:p})},Dl=async(e=new Date().toISOString())=>{await pe({...await L(),offboardedAt:e})};var Ba=e=>CD(e).replace(/\\/g,"/").toLowerCase(),Bf=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",wi=e=>`${e}.source`,Ak=e=>/(^|\/)_npx(\/|$)/.test(Ba(e)),Uf=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Ba(e)),Wf=e=>{let t=Ba(e),n=[kD(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Ba);return Ak(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},vt=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),bi=e=>/[\\/](node|node\.exe)$/i.test(e),jr=(e=vt())=>bi(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,bk=e=>{try{let t=kk(e);return t.isFile()?t.size:void 0}catch{return}},Hf=e=>{let t=ze(e);if(Ma(t)==="versions")return t;let n=ze(t);return Ma(n)==="versions"?n:void 0},Ll=(e,t)=>t!==void 0&&(ze(e)===t||ze(ze(e))===t),AD=e=>{let t=Hf(e);if(!t)return;let n=Be(ze(t),"bin",Bf());try{let r=gi(n);return r===gi(e)||Ll(r,gi(t))?n:void 0}catch{return}},Fa=(e=ee(),t=process.platform)=>{let n=Be(e,"bin",Bf(t));try{let r=gi(n),o=gi(Be(e,"versions"));if(Ll(r,o))return n;if(t==="win32"){let a=mD(wi(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=bk(Be(o,a,Bf(t)))??bk(Be(o,a));if(s!==void 0&&s===kk(n).size)return n}}catch{return}},Yr=(e=vt())=>{let t=jr(e),n=Uf(t)||Kf(t)?Fa():void 0;return AD(e.execPath)??n??t},vk=(e=vt())=>Yr(e)!==jr(e),Rn=(e,t=vt())=>{let n=Yr(t);return bi(t.execPath)&&t.scriptPath!==void 0&&n===jr(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},$l=(e=vt())=>{let t=Yr(e);return!bi(e.execPath)&&!Wf(t)?ze(t):Be(ee(),"bin")},Nl=async e=>{try{return await hD(e),!0}catch{return!1}},vD=async e=>{let t=await gD(e),n=ze(t),r=ze(n),o=Be(r,"package.json"),a=await Ff(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 Nl(Be(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},SD=async(e,t)=>{let n=t;for(;;){let r=Be(n,"node_modules",e);if(await Nl(Be(r,"package.json")))return r;let o=ze(n);if(o===n)return;n=o}},ID=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Ff(Be(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await SD(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Ck(i,Be(t,s),{recursive:!0}),r.push(i)}}},ED=async(e=vt())=>{let t=Fa();if(t)return{command:t,args:[],entryPath:t};if(!bi(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await vD(e.scriptPath);await Xe();let r=Be(ee(),"bin",`connect-runtime-${n.version}`),o=Be(r,"dist","index.js");if(!await Nl(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Mf(a,{recursive:!0,force:!0}),await wk(a,{recursive:!0,mode:448});try{await Ck(n.dist,Be(a,"dist"),{recursive:!0}),await bD(Be(a,"package.json"),await Ff(n.packageJson),{mode:384}),await ID(n.root,Be(a,"node_modules")),await wk(ze(r),{recursive:!0,mode:448});try{await wD(a,r)}catch(s){if(!await Nl(o))throw s}}finally{await Mf(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Gf=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,xD=e=>{let t=Ma(ze(ze(e)));return Gf.test(t)?t:void 0},Kf=(e,t=ee())=>{let n=ze(ze(e));return Ba(ze(n))===Ba(Be(t,"bin"))&&Gf.test(Ma(n))&&Ma(ze(e))==="dist"&&Ma(e)==="index.js"},Sk=(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))},Ml=async(e=vt())=>{let t=Be(ee(),"bin"),n=xD(jr(e)),r=[];for(let o of await yD(t).catch(()=>[])){if(!Gf.test(o)||o===n)continue;let a=Be(t,o);await Mf(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},Ik=async(e,t=vt())=>{let n=jr(t);if(!bi(t.execPath)||!Ak(n)||Fa())return;let r=await ED(t),o=fD(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var rt="__anyray-hook",Ek="__anyray-codex-hook",Lo="__anyray-prompt-hook",$o="__anyray-hook-lifecycle",xk="__anyray-shell-pretool",Vf="__anyray-shell-run",Rk="__anyray-read-pretool",Zr="__anyray-refresh",Mo=(e,t=[])=>{let{command:n,args:r}=Rn([e,...t]);return{command:n,args:r}},un=(e,t=[])=>{let n=Mo(e,t);return[n.command,...n.args].map(Ef).join(" ")},Bl=(e,t,n=[])=>typeof e=="string"&&e.trim()===un(t,n),Ok=()=>un("print-key"),De=()=>Yr(),ut=Wf,ne=()=>!ut(De()),On=async()=>{if(!ne())return!1;try{return await RD(De()),!0}catch{return!1}},Jr="__anyray-mcp-server",Ue=e=>Mo(Jr,[e]),OD=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),Ua=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ue(t);return n.command===r.command&&OD(n.args,r.args)},St=(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)===Jr&&r.at(-1)===t};var Fl=(e,t)=>{for(let n of["PostToolUse","PostToolUseFailure"])Na(e,n,rt,cr(t(rt),{matcher:"*"}));Na(e,"UserPromptSubmit",Lo,cr(t(Lo)));for(let n of["SessionStart","PreCompact","SessionEnd"])Na(e,n,$o,cr(t($o)))};import{access as _D,chmod as TD,mkdir as jf,open as zf,readFile as Mk,rm as pn,stat as _k,utimes as PD}from"node:fs/promises";import{createHash as qf,randomUUID as Bk}from"node:crypto";import{readFileSync as Fk,statSync as Tk}from"node:fs";import{dirname as Qf,join as DD}from"node:path";import{isDeepStrictEqual as Wa}from"node:util";var ki=e=>`${e}.anyray-bak`,Uk=async e=>{let t;try{t=await zf(Qf(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},Pk=async(e,t)=>{let n,r;try{n=await zf(e,"wx",384),await n.writeFile(t,"utf-8"),await Kr(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await pn(e,{force:!0}).catch(()=>{}),r;await Uk(e)},ND=async e=>{let t;try{t=await zf(e,"r"),await Kr(t)}finally{await t?.close().catch(()=>{})}await Uk(e)},R=async e=>{try{return await _D(e),!0}catch{return!1}},F=async e=>{if(!await R(e))return{};let t=await Mk(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},Ga=class extends Error{constructor(){super("repair deferred: configuration changed before publication")}},Dk=e=>`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}:${e.ctimeNs}`,Wk=e=>{try{let t=Dk(Tk(e,{bigint:!0})),n=Fk(e),r=Dk(Tk(e,{bigint:!0}));if(t!==r)throw new Ga;return{raw:n.toString("utf8"),fingerprint:`${r}:${qf("sha256").update(n).digest("hex")}`}}catch(t){if(t.code==="ENOENT")return{raw:"",fingerprint:"missing"};throw t}},Xr=e=>{let{raw:t,fingerprint:n}=Wk(e),r=t.trim()?JSON.parse(t):{};if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("configuration is not a JSON object");return{value:r,fingerprint:n}},Hk=async(e,t,n={})=>{for(let r=0;r<3;r++)try{let o=Xr(e);if(n.requireExisting&&o.fingerprint==="missing")return"unchanged";let a=JSON.stringify(o.value);return t(o.value),JSON.stringify(o.value)===a?"unchanged":(await q(e,o.value,{backup:n.backup,expectedFingerprint:o.fingerprint}),"written")}catch(o){if(!(o instanceof Ga))throw o}return"repair deferred"},q=async(e,t,n={})=>{await jf(Qf(e),{recursive:!0,mode:448});let r=ki(e);if(n.backup!==!1&&!await R(r)){let a=await R(e),s=a?await Mk(e,"utf-8"):`{}
|
|
5
5
|
`;if(a||n.tombstoneAbsent!==!1)try{await Pk(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${Bk()}`;try{if(await Pk(o,`${JSON.stringify(t,null,2)}
|
|
6
|
-
`),n.expectedFingerprint!==void 0){if(Wk(e).fingerprint!==n.expectedFingerprint)throw new Ga;let a=n.expectedFingerprint.slice(n.expectedFingerprint.lastIndexOf(":")+1);try{await ke(o,e,n.runtimePlatform,{verifyDisplaced:async s=>qf("sha256").update(Fk(s)).digest("hex")===a})}catch(s){throw s instanceof Do?new Ga:s}return}await ke(o,e,n.runtimePlatform),await TD(e,384),await
|
|
7
|
-
`)},Tn=(e,t={})=>{let n=e.byoUpstream,r=!n&&se(e,"anthropic"),o=be({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1,s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=HD(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 nm}from"zod";var GD=5e3,KD=1e3,VD=1e8,jD=nm.object({modelContext:nm.object({contextTokens:nm.number().int().min(KD).max(VD)}).optional()}),eC=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},tC=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??GD,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=jD.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var YD=1e6,Ci="[1m]",ZD=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},nC=(e,t)=>!e||t===void 0?{}:ZD(e)?{envTokens:t}:t<YD?{}:e.toLowerCase().endsWith(Ci)?{}:{model:`${e}${Ci}`},rC=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(Ci))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(Ci))return e.slice(0,-Ci.length)};import{platform as JD}from"node:os";var Kt=(e=JD())=>{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 lr=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],Gl=e=>typeof e=="string"&&e.trim()!=="",XD=(e,t)=>typeof e[t]=="string"&&!Gl(e[t]),oC=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},zD=()=>F(Kt()).catch(()=>({})),aC=async(e={})=>{let t=e.env??process.env,n=oC(e.userSettings??{}),r=oC(await(e.readManaged??zD)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of lr)Gl(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Kt()})`,repairable:!1}):Gl(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!XD(n,a)&&Gl(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},rm=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`,om=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.",sC=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 qD=lr.map(e=>e.name),QD=Hl.filter(e=>!qD.includes(e)),iC=e=>typeof e=="string"&&e.trim()!=="",cC=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},
|
|
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}},hC=async()=>{try{let e=await
|
|
6
|
+
`),n.expectedFingerprint!==void 0){if(Wk(e).fingerprint!==n.expectedFingerprint)throw new Ga;let a=n.expectedFingerprint.slice(n.expectedFingerprint.lastIndexOf(":")+1);try{await ke(o,e,n.runtimePlatform,{verifyDisplaced:async s=>qf("sha256").update(Fk(s)).digest("hex")===a})}catch(s){throw s instanceof Do?new Ga:s}return}await ke(o,e,n.runtimePlatform),await TD(e,384),await ND(e)}finally{await pn(o,{force:!0}).catch(()=>{})}},Gk=1,Nk=3e4,LD=5e3,$D=/^[a-f0-9]{64}$/,Kk=e=>`${e}.pending`,MD=e=>`${e}.lock`,Yf=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=>Yf(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Yf(t[n])}`).join(",")}}`},Zf=(e,t)=>({exists:e,sha256:qf("sha256").update(Yf(t)).digest("hex")}),Jf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Lk=e=>Jf(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&$D.test(e.sha256),BD=e=>Jf(e)&&e.transactionVersion===Gk&&Lk(e.before)&&Lk(e.after)&&Jf(e.journal),Xf=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,Ha=async(e,t)=>{try{return await F(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},FD=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Vk=async e=>{let t=MD(e),n=DD(t,"owner.json");await jf(Qf(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=Bk();try{await jf(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await Ha(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 _k(n)).mtimeMs;i=!FD(c.pid)||l>Nk}catch{try{i=Date.now()-(await _k(t)).mtimeMs>Nk}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await pn(t,{recursive:!0,force:!0});continue}try{await q(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await pn(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await Ha(n,"ownership journal")).nonce!==o)return;let i=new Date;await PD(n,i,i)}catch{}})()},LD);return a.unref(),async()=>{clearInterval(a);try{(await Ha(n,"ownership journal")).nonce===o&&await pn(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},jk=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:Zf(t,n)}},Yk=async(e,t)=>{let n=Kk(t);if(!await R(n))return;let r=await Ha(n,"prepared ownership transaction");if(!BD(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await jk(e),a=await R(t),s=await R(ki(e)),i=Xf(o.fingerprint,r.before),c=Xf(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 pn(n,{force:!0});return}if(i){await pn(n,{force:!0}),a||await fe(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},Ul=async(e,t,n)=>{let r=await Vk(t);try{return await Yk(e,t),await n()}finally{await r()}},$k=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 Ha(e,"ownership journal");if(!(n&&Wa(a,t))){if(!Wa(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await q(e,t,{backup:!1}):await pn(e,{force:!0})}},Wl=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await Vk(a);try{await Yk(n,a);let l=await jk(n),d=Zf(i,r),u=await R(a),p=u?await Ha(a,"ownership journal"):void 0,m=p&&typeof p.fileExisted=="boolean"?{...s,fileExisted:p.fileExisted}:s;if(!Xf(l.fingerprint,d)){if(Wa(l.value,o)&&p&&Wa(p,m))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&Wa(l.value,o)&&p&&Wa(p,m))return;let f=await R(ki(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=Kk(a),g={transactionVersion:Gk,before:l.fingerprint,after:Zf(!0,o),journal:m};await q(h,g,{backup:!1});try{await q(n,o,p?{backup:!1}:{tombstoneAbsent:!1}),await(t.writeJournal??q)(a,m,{backup:!1}),await pn(h,{force:!0})}catch(y){try{await $k(n,l.value,l.exists,o)}catch(w){throw new AggregateError([y,w],"ownership journal publication failed and config rollback was incomplete")}try{await $k(a,p??{},u,m),await pn(h,{force:!0}),!f&&!p&&await fe(n)}catch(w){throw new AggregateError([y,w],"ownership journal publication failed after config rollback")}throw y}}finally{await c()}},Bo=async e=>{try{return await F(ki(e))}catch{return{}}},fe=async e=>{await pn(ki(e),{force:!0}).catch(()=>{})};var _n="anyray-org-skills",UD="/connect/claude-desktop/plugins/marketplace.json",Zk=e=>`${e.replace(/\/+$/,"")}${UD}`,Jk=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")},em=`@${_n}`,Ka=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xk=e=>`${e}${em}`,zk=(e,t)=>{let n=!1,r=Ka(e.extraKnownMarketplaces)?e.extraKnownMarketplaces:e.extraKnownMarketplaces===void 0?{}:null;if(r){let a={source:{source:"url",url:t.url}};JSON.stringify(r[_n])!==JSON.stringify(a)&&(r[_n]=a,n=!0),e.extraKnownMarketplaces=r}let o=Ka(e.enabledPlugins)?e.enabledPlugins:e.enabledPlugins===void 0?{}:null;if(o){let a=new Set(t.plugins.map(Xk));for(let s of Object.keys(o))s.endsWith(em)&&!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},tm=e=>{let t=!1;if(Ka(e.extraKnownMarketplaces)&&_n in e.extraKnownMarketplaces&&(delete e.extraKnownMarketplaces[_n],Object.keys(e.extraKnownMarketplaces).length===0&&delete e.extraKnownMarketplaces,t=!0),Ka(e.enabledPlugins)){for(let n of Object.keys(e.enabledPlugins))n.endsWith(em)&&(delete e.enabledPlugins[n],t=!0);Object.keys(e.enabledPlugins).length===0&&delete e.enabledPlugins}return t},WD=e=>Ka(e.extraKnownMarketplaces)&&_n in e.extraKnownMarketplaces,qk=(e,t)=>{if(!WD(e))return!1;let n=e.enabledPlugins;return Ka(n)?t.plugins.every(r=>n[Xk(r)]===!0):!1};var se=(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))},zr=e=>e.changesBilling===!0||e.changesOrgManagement===!0;var Fo=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Qk=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Hl=[...Fo,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],HD=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
|
|
7
|
+
`)},Tn=(e,t={})=>{let n=e.byoUpstream,r=!n&&se(e,"anthropic"),o=be({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1,s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=HD(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 nm}from"zod";var GD=5e3,KD=1e3,VD=1e8,jD=nm.object({modelContext:nm.object({contextTokens:nm.number().int().min(KD).max(VD)}).optional()}),eC=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},tC=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??GD,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=jD.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var YD=1e6,Ci="[1m]",ZD=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},nC=(e,t)=>!e||t===void 0?{}:ZD(e)?{envTokens:t}:t<YD?{}:e.toLowerCase().endsWith(Ci)?{}:{model:`${e}${Ci}`},rC=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(Ci))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(Ci))return e.slice(0,-Ci.length)};import{platform as JD}from"node:os";var Kt=(e=JD())=>{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 lr=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],Gl=e=>typeof e=="string"&&e.trim()!=="",XD=(e,t)=>typeof e[t]=="string"&&!Gl(e[t]),oC=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},zD=()=>F(Kt()).catch(()=>({})),aC=async(e={})=>{let t=e.env??process.env,n=oC(e.userSettings??{}),r=oC(await(e.readManaged??zD)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of lr)Gl(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Kt()})`,repairable:!1}):Gl(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!XD(n,a)&&Gl(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},rm=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`,om=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.",sC=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 qD=lr.map(e=>e.name),QD=Hl.filter(e=>!qD.includes(e)),iC=e=>typeof e=="string"&&e.trim()!=="",cC=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},eN=(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)},tN=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},am=()=>F(Kt()).catch(()=>({})),lC=am,nN=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=>Gr(r,rt))},dC=async(e={})=>{let t=await(e.readManaged??lC)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!nN(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},Kl=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Kt()}) \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 (${Kt()}), 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.",uC=async(e={})=>{let t=cC(e.userSettings??{}),n=cC(await(e.readManaged??lC)().catch(()=>({}))),r=[];for(let o of QD){if(!iC(n[o])||!iC(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(eN(n[o],t[o],a))continue;let s=a?tN(n[o]):void 0;r.push({name:o,source:`managed settings (${Kt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},pC=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`,fC=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 rN}from"node:os";import{join as oN}from"node:path";import{readFile as aN}from"node:fs/promises";var sN=400,mC=async()=>{try{let e=oN(rN(),".claude","settings.json"),n=JSON.parse(await aN(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
|
|
8
|
+
`)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},hC=async()=>{try{let e=await L();return e.gateway?{origin:new URL(e.gateway).origin,metadata:be({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},pt=async(e="auto")=>e==="profile"?hC():e==="claude"?mC():await mC()??await hC(),jl=async(e={})=>{let t=e.readTarget??pt,n=e.loadProfile??L,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a;try{a=new URL(r.gateway).origin}catch{return"unreadable"}return a===o.origin?"owned":"foreign"},fn=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},Yl=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),sN);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:fn(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var Zl="anyray-org",Vt="x-anyray-api-key";var im=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yC=e=>{try{return new URL(e).origin}catch{return}},iN=(e,t)=>{if(!im(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}},Pn=(e,t,n,r)=>{let o=e[t];if(o!==void 0&&!im(o))return"conflict";let a=im(o)?o:{},s=a[Zl];return s!==void 0&&!iN(s,n)?"conflict":r===void 0?s===void 0?"unchanged":(delete a[Zl],Object.keys(a).length===0?delete e[t]:e[t]=a,"changed"):JSON.stringify(s)===JSON.stringify(r)?"unchanged":(a[Zl]=r,e[t]=a,"changed")},Jl="# >>> anyray org mcp >>>",cm="# <<< anyray org mcp <<<",lm=`[mcp_servers.${Zl}]`,sm=e=>JSON.stringify(e),cN=e=>[lm,`url = ${sm(e.url)}`,`http_headers = { ${sm(Vt)} = ${sm(e.clientKey)} }`],lN=new RegExp(`\\n?${Jl.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\s\\S]*?${cm.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\n?`),dN=e=>{let t=e.indexOf(Jl);if(t<0||e.indexOf(cm,t+Jl.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===lm){if(o)break;o=!0,r+=1;continue}if(s.startsWith("[")||(s.includes(Vt)&&(a=!0),s!==""&&!s.startsWith("#")&&!/^[\w."'-]+\s*=/.test(s)))break;r+=1}return!o||!a?e:e.slice(0,t)+n.slice(r).join(`
|
|
10
|
-
`)},gC=(e,t)=>{let n=
|
|
10
|
+
`)},gC=(e,t)=>{let n=dN(e.replace(lN,`
|
|
11
11
|
`));if(n.split(`
|
|
12
|
-
`).some(s=>s.trim()===lm))return{text:e,outcome:"conflict"};let r=t===void 0?"":[Jl,...
|
|
12
|
+
`).some(s=>s.trim()===lm))return{text:e,outcome:"conflict"};let r=t===void 0?"":[Jl,...cN(t),cm].join(`
|
|
13
13
|
`),o=n.replace(/\s*$/,""),a=r?`${o}${o?`
|
|
14
14
|
|
|
15
15
|
`:""}${r}
|
|
16
16
|
`:o?`${o}
|
|
17
|
-
`:"";return{text:a,outcome:a===e?"unchanged":"changed"}};import{readFile as uL}from"node:fs/promises";var pL=/ark_[A-Za-z0-9_-]{20,512}/,jt=async(e,t)=>{if(t.length===0)return null;let n=!1;for(let r of e){let o;try{o=await uL(r,"utf-8")}catch{continue}if(o.includes(t))return!0;pL.test(o)&&(n=!0)}return n?!1:null};var mn=()=>zl(Xl(),".claude","settings.json"),Ai=()=>zl(Xl(),".claude.json"),fL=Hl,dr="anyray",mL=()=>({type:"stdio",...Ue("claude"),alwaysLoad:!0}),qr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hL=e=>e instanceof Error?e.name:"UnknownError",yL={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},gL=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${dr} 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.`}},wL={readJson:F,writeJson:(e,t)=>q(e,t)},bL=async(e,t=wL)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(kL(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=qr(a)?a[dr]:void 0;if(s&&St(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},kL=e=>{if("mcpServers"in e&&!qr(e.mcpServers))return"conflict";let t=qr(e.mcpServers)?{...e.mcpServers}:{},n=t[dr];return n!==void 0&&!St(n,"claude")?"conflict":(t[dr]=mL(),e.mcpServers=t,"installed")},wC=e=>{let t=e.mcpServers;return!t||!(dr in t)||!St(t[dr],"claude")?!1:(delete t[dr],Object.keys(t).length===0&&delete e.mcpServers,!0)},CC=e=>{Fl(e,un)},AC=async()=>{if(!ne())return"unchanged";try{return await Hk(mn(),CC,{backup:!1,requireExisting:!0})}catch{return"repair deferred"}},CL=e=>{La(e,"SessionStart",Zr,cr(un(Zr),{async:!0}))},vC=e=>En(e,"SessionStart",Zr),bC=e=>{let t=En(e,"PostToolUse",rt),n=En(e,"UserPromptSubmit",No),r=vC(e),o=En(e,"PostToolUseFailure",rt),a=En(e,"SessionStart",$o),s=En(e,"PreCompact",$o),i=En(e,"SessionEnd",$o);return a||t||n||r||o||s||i},AL="print-key",vL=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(De()),Uo=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===AL&&vL(t)},SL=async(e,t)=>{let n=(await Bo(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of fL){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},IL=e=>typeof e.apiKeyHelper=="string"&&!Uo(e),SC=async e=>{let t=await am(),n=async()=>t,[r,o,a]=await Promise.all([aC({userSettings:e,readManaged:n}),uC({userSettings:e,readManaged:n}).catch(()=>[]),dC({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},kC=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await SC(e),o=om(t),a=fC(n);return{routingOverrides:[...t.map(i=>({problem:rm(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:pC(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},Dn={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=zl(Xl(),".claude"),t=await R(e);return{installed:t,detail:t?mn():"no ~/.claude directory"}},async apply(e,t){let n=mn(),r=Xr(n),o=r.value,a=eC(o),s=await tC(e.origin,e.clientKey,a),i=nC(a,s),{env:c,subscription:l,byoUpstream:d,meta:u,headers:p}=Tn(e,{contextWindowTokens:i.envTokens}),{directOverrides:m,hookPolicy:f}=await SC(o),h=m.filter(I=>!I.repairable),g=m.filter(I=>I.repairable),y=[...h.map(I=>`WARNING: ${rm(I)}.`),...h.length?[om(h)]:[],...f.state==="fine"?[]:[`WARNING: ${Kl(f)}.`,Vl(f)],...g.map(I=>sC(I)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,d?`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.":""}`:l?`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: ${u??"(none)"}`,...d?[]:["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."],...i.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${i.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...i.model!==void 0?[`Context window: model = ${i.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 ${s} 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:y};i.model!==void 0&&(o.model=i.model);let w=o.env??{};o.env={...w,...c};let b=o.env;for(let{name:I}of lr)g.some(K=>K.name===I)?b[I]="":b[I]===""&&(process.env[I]??"").trim()===""&&delete b[I];if(p||delete b.ANTHROPIC_CUSTOM_HEADERS,l&&(w.ANTHROPIC_AUTH_TOKEN&&y.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete b.ANTHROPIC_AUTH_TOKEN),d)for(let I of Qk)delete b[I];let A=!!e.clientKey,C=ne(),x=IL(o);!l&&!d&&A&&C&&!x?(o.apiKeyHelper=Ok(),b.ANTHROPIC_AUTH_TOKEN="",y.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).")):Uo(o)&&delete o.apiKeyHelper,x&&!l&&!d&&A&&C&&y.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(l||d)&&A&&C?(CL(o),y.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):vC(o),ne()?(CC(o),y.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(bC(o),y.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,o,{expectedFingerprint:r.fingerprint});let S=[n],E=Ai(),T;if(ne()){let I=await bL(E);I.outcome==="registered"?(S.push(E),y.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.")):(y.push(gL(I.failure,E)),T=yL[I.failure])}else try{let I=await F(E);wC(I)&&(await q(E,I),S.push(E))}catch(I){y.push(`Could not clean up a stale Anyray MCP registration in ${E} (${hL(I)}).`)}return{status:"configured",messages:y,changedFiles:S,...T?{errorClass:T}:{}}},skillsDir(){return zl(Xl(),".claude","skills")},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=Ai(),r=await F(n),o=Pn(r,"mcpServers",e,t&&{type:"http",url:t.url,headers:{[Vt]:t.clientKey}});return o==="changed"&&await q(n,r,{backup:!1}),{changed:o==="changed"}},async syncOrgMarketplace(e){let t=mn(),n=Xr(t),r=n.value,o=e!==void 0&&Jk(e.url),a=o&&e?zk(r,e):tm(r);return a&&await q(t,r,{backup:!1,expectedFingerprint:n.fingerprint}),{changed:a,handlesPluginSkills:o&&e!==void 0?qk(r,e):!1}},async pointsAt(e){let t=mn();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 jt([mn()],e)},async runtimeDiagnostics(){let e=await F(mn()).catch(()=>({}));return kC(e)},async routingOverrides(){let e=await F(mn()).catch(()=>({}));return(await kC(e)).routingOverrides},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Ai();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await F(e)).mcpServers?.[dr];return r?St(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=mn();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!qr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>Gr(c,rt))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>Gr(c,rt)&&qr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>qr(l)&&Bl(l.command,rt))))}}catch{e="unreadable"}let r,o=!0,a=Ai();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!qr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[dr];r=i===void 0?"missing":St(i,"claude")?"owned":"foreign",r==="owned"&&(o=Ua(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await On()?"owned":"missing",beacon_target:await jl().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await F(mn()),t=qr(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=mn();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=Xr(t),r=n.value,o=r.env,a=bC(r),s=Uo(r);s&&delete r.apiKeyHelper;let i=o?await SL(t,o):[],c=rC(typeof r.model=="string"?r.model:void 0,(await Bo(t)).model);c!==void 0&&(r.model=c),o&&Object.keys(o).length===0&&delete r.env;let l=tm(r);(o||a||s||l||c!==void 0)&&await q(t,r,{backup:!1,expectedFingerprint:n.fingerprint});let d=[`removed Anyray keys from ${t}`];l&&d.push("Removed the Anyray org skills marketplace and its plugins."),c!==void 0&&d.push(`Put model back to ${c} \u2014 dropped the [1m] alias Anyray added for your context window.`),a&&d.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),s&&d.push("Removed the Anyray apiKeyHelper."),i.length&&d.push(`Put back the ${i.join(" and ")} you had set before Anyray.`);let u=Ai();try{let p=await F(u);wC(p)&&(await q(u,p,{backup:!1}),d.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await fe(t),{status:"reverted",messages:d,changedFiles:[t]}}};import{delimiter as EL,dirname as xL}from"node:path";var Qr=e=>{let{command:t,args:n}=Rn([e]);return{command:t,args:n}},Wo=()=>Yr(),Tt=(e="",t=process.env.PATH??"",n=$l(),r=Yr())=>{let a=t.split(EL).filter(Boolean).some(s=>s===n)||xL(r)!==n?"anyray-connect":r;return e?`${a} ${e}`:a};import{rm as RL,stat as OL}from"node:fs/promises";import{homedir as IC,platform as _L}from"node:os";import{join as TL}from"node:path";var dm="Anyray",PL=(e=IC())=>TL(e,"Applications",`${dm}.app`),um=async(e={})=>{if((e.os??_L())!=="darwin")return{ok:!0,messages:[]};let n=PL(e.home??IC());try{return await OL(n).then(()=>!0,()=>!1)?(await RL(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed the legacy ${dm}.app background item from ~/Applications.`]}):{ok:!0,messages:[]}}catch(r){return{ok:!1,messages:[`Could not remove the legacy ${dm}.app background item (${r?.name??"Error"}).`]}}};import{homedir as EC,userInfo as DL}from"node:os";var xC=()=>{try{return EC()!==DL().homedir}catch{return!1}},pm=e=>[`Skipped ${e} \u2014 HOME (${EC()}) 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 Ln=(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,ur=(e=process.env)=>Ln(e)!==null,pr=e=>e==="codespaces"||e==="devcontainer",Va=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var RC=()=>Go(td(),".anyray","logs"),hm=()=>Go(RC(),"connect-refresh.log"),ed=1800,nd="ai.anyray.connect.refresh",Ii="anyray-refresh",gm="\\AnyrayConnectKeyRefresh",rd=nd,Ei=Ii,Si=gm,ML=String(ed/60),wm=(e,t)=>{let n=$L(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},bm=()=>Go(td(),"Library","LaunchAgents",`${rd}.plist`),km=()=>Go(td(),".config","systemd","user"),OC=()=>Go(km(),`${Ei}.service`),Ql=()=>Go(km(),`${Ei}.timer`),mm=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),od=()=>Qr(Zr),BL=(e=od())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${mm(o)}</string>`).join(`
|
|
17
|
+
`:"";return{text:a,outcome:a===e?"unchanged":"changed"}};import{readFile as uN}from"node:fs/promises";var pN=/ark_[A-Za-z0-9_-]{20,512}/,jt=async(e,t)=>{if(t.length===0)return null;let n=!1;for(let r of e){let o;try{o=await uN(r,"utf-8")}catch{continue}if(o.includes(t))return!0;pN.test(o)&&(n=!0)}return n?!1:null};var mn=()=>zl(Xl(),".claude","settings.json"),Ai=()=>zl(Xl(),".claude.json"),fN=Hl,dr="anyray",mN=()=>({type:"stdio",...Ue("claude"),alwaysLoad:!0}),qr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hN=e=>e instanceof Error?e.name:"UnknownError",yN={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},gN=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${dr} 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.`}},wN={readJson:F,writeJson:(e,t)=>q(e,t)},bN=async(e,t=wN)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(kN(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=qr(a)?a[dr]:void 0;if(s&&St(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},kN=e=>{if("mcpServers"in e&&!qr(e.mcpServers))return"conflict";let t=qr(e.mcpServers)?{...e.mcpServers}:{},n=t[dr];return n!==void 0&&!St(n,"claude")?"conflict":(t[dr]=mN(),e.mcpServers=t,"installed")},wC=e=>{let t=e.mcpServers;return!t||!(dr in t)||!St(t[dr],"claude")?!1:(delete t[dr],Object.keys(t).length===0&&delete e.mcpServers,!0)},CC=e=>{Fl(e,un)},AC=async()=>{if(!ne())return"unchanged";try{return await Hk(mn(),CC,{backup:!1,requireExisting:!0})}catch{return"repair deferred"}},CN=e=>{Na(e,"SessionStart",Zr,cr(un(Zr),{async:!0}))},vC=e=>En(e,"SessionStart",Zr),bC=e=>{let t=En(e,"PostToolUse",rt),n=En(e,"UserPromptSubmit",Lo),r=vC(e),o=En(e,"PostToolUseFailure",rt),a=En(e,"SessionStart",$o),s=En(e,"PreCompact",$o),i=En(e,"SessionEnd",$o);return a||t||n||r||o||s||i},AN="print-key",vN=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(De()),Uo=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===AN&&vN(t)},SN=async(e,t)=>{let n=(await Bo(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of fN){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},IN=e=>typeof e.apiKeyHelper=="string"&&!Uo(e),SC=async e=>{let t=await am(),n=async()=>t,[r,o,a]=await Promise.all([aC({userSettings:e,readManaged:n}),uC({userSettings:e,readManaged:n}).catch(()=>[]),dC({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},kC=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await SC(e),o=om(t),a=fC(n);return{routingOverrides:[...t.map(i=>({problem:rm(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:pC(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},Dn={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=zl(Xl(),".claude"),t=await R(e);return{installed:t,detail:t?mn():"no ~/.claude directory"}},async apply(e,t){let n=mn(),r=Xr(n),o=r.value,a=eC(o),s=await tC(e.origin,e.clientKey,a),i=nC(a,s),{env:c,subscription:l,byoUpstream:d,meta:u,headers:p}=Tn(e,{contextWindowTokens:i.envTokens}),{directOverrides:m,hookPolicy:f}=await SC(o),h=m.filter(I=>!I.repairable),g=m.filter(I=>I.repairable),y=[...h.map(I=>`WARNING: ${rm(I)}.`),...h.length?[om(h)]:[],...f.state==="fine"?[]:[`WARNING: ${Kl(f)}.`,Vl(f)],...g.map(I=>sC(I)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,d?`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.":""}`:l?`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: ${u??"(none)"}`,...d?[]:["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."],...i.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${i.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...i.model!==void 0?[`Context window: model = ${i.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 ${s} 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:y};i.model!==void 0&&(o.model=i.model);let w=o.env??{};o.env={...w,...c};let b=o.env;for(let{name:I}of lr)g.some(K=>K.name===I)?b[I]="":b[I]===""&&(process.env[I]??"").trim()===""&&delete b[I];if(p||delete b.ANTHROPIC_CUSTOM_HEADERS,l&&(w.ANTHROPIC_AUTH_TOKEN&&y.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete b.ANTHROPIC_AUTH_TOKEN),d)for(let I of Qk)delete b[I];let A=!!e.clientKey,C=ne(),x=IN(o);!l&&!d&&A&&C&&!x?(o.apiKeyHelper=Ok(),b.ANTHROPIC_AUTH_TOKEN="",y.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).")):Uo(o)&&delete o.apiKeyHelper,x&&!l&&!d&&A&&C&&y.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(l||d)&&A&&C?(CN(o),y.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):vC(o),ne()?(CC(o),y.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(bC(o),y.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,o,{expectedFingerprint:r.fingerprint});let S=[n],E=Ai(),T;if(ne()){let I=await bN(E);I.outcome==="registered"?(S.push(E),y.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.")):(y.push(gN(I.failure,E)),T=yN[I.failure])}else try{let I=await F(E);wC(I)&&(await q(E,I),S.push(E))}catch(I){y.push(`Could not clean up a stale Anyray MCP registration in ${E} (${hN(I)}).`)}return{status:"configured",messages:y,changedFiles:S,...T?{errorClass:T}:{}}},skillsDir(){return zl(Xl(),".claude","skills")},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=Ai(),r=await F(n),o=Pn(r,"mcpServers",e,t&&{type:"http",url:t.url,headers:{[Vt]:t.clientKey}});return o==="changed"&&await q(n,r,{backup:!1}),{changed:o==="changed"}},async syncOrgMarketplace(e){let t=mn(),n=Xr(t),r=n.value,o=e!==void 0&&Jk(e.url),a=o&&e?zk(r,e):tm(r);return a&&await q(t,r,{backup:!1,expectedFingerprint:n.fingerprint}),{changed:a,handlesPluginSkills:o&&e!==void 0?qk(r,e):!1}},async pointsAt(e){let t=mn();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 jt([mn()],e)},async runtimeDiagnostics(){let e=await F(mn()).catch(()=>({}));return kC(e)},async routingOverrides(){let e=await F(mn()).catch(()=>({}));return(await kC(e)).routingOverrides},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Ai();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await F(e)).mcpServers?.[dr];return r?St(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=mn();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!qr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>Gr(c,rt))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>Gr(c,rt)&&qr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>qr(l)&&Bl(l.command,rt))))}}catch{e="unreadable"}let r,o=!0,a=Ai();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!qr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[dr];r=i===void 0?"missing":St(i,"claude")?"owned":"foreign",r==="owned"&&(o=Ua(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await On()?"owned":"missing",beacon_target:await jl().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await F(mn()),t=qr(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=mn();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=Xr(t),r=n.value,o=r.env,a=bC(r),s=Uo(r);s&&delete r.apiKeyHelper;let i=o?await SN(t,o):[],c=rC(typeof r.model=="string"?r.model:void 0,(await Bo(t)).model);c!==void 0&&(r.model=c),o&&Object.keys(o).length===0&&delete r.env;let l=tm(r);(o||a||s||l||c!==void 0)&&await q(t,r,{backup:!1,expectedFingerprint:n.fingerprint});let d=[`removed Anyray keys from ${t}`];l&&d.push("Removed the Anyray org skills marketplace and its plugins."),c!==void 0&&d.push(`Put model back to ${c} \u2014 dropped the [1m] alias Anyray added for your context window.`),a&&d.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),s&&d.push("Removed the Anyray apiKeyHelper."),i.length&&d.push(`Put back the ${i.join(" and ")} you had set before Anyray.`);let u=Ai();try{let p=await F(u);wC(p)&&(await q(u,p,{backup:!1}),d.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await fe(t),{status:"reverted",messages:d,changedFiles:[t]}}};import{delimiter as EN,dirname as xN}from"node:path";var Qr=e=>{let{command:t,args:n}=Rn([e]);return{command:t,args:n}},Wo=()=>Yr(),Tt=(e="",t=process.env.PATH??"",n=$l(),r=Yr())=>{let a=t.split(EN).filter(Boolean).some(s=>s===n)||xN(r)!==n?"anyray-connect":r;return e?`${a} ${e}`:a};import{rm as RN,stat as ON}from"node:fs/promises";import{homedir as IC,platform as _N}from"node:os";import{join as TN}from"node:path";var dm="Anyray",PN=(e=IC())=>TN(e,"Applications",`${dm}.app`),um=async(e={})=>{if((e.os??_N())!=="darwin")return{ok:!0,messages:[]};let n=PN(e.home??IC());try{return await ON(n).then(()=>!0,()=>!1)?(await RN(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed the legacy ${dm}.app background item from ~/Applications.`]}):{ok:!0,messages:[]}}catch(r){return{ok:!1,messages:[`Could not remove the legacy ${dm}.app background item (${r?.name??"Error"}).`]}}};import{homedir as EC,userInfo as DN}from"node:os";var xC=()=>{try{return EC()!==DN().homedir}catch{return!1}},pm=e=>[`Skipped ${e} \u2014 HOME (${EC()}) 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 Nn=(e=process.env)=>e.CODESPACES==="true"||e.CODESPACE_NAME?"codespaces":e.REMOTE_CONTAINERS==="true"||e.REMOTE_CONTAINERS_IPC||e.DEVCONTAINER?"devcontainer":e.SSH_CONNECTION||e.SSH_TTY?"ssh":null,ur=(e=process.env)=>Nn(e)!==null,pr=e=>e==="codespaces"||e==="devcontainer",Va=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var RC=()=>Go(td(),".anyray","logs"),hm=()=>Go(RC(),"connect-refresh.log"),ed=1800,nd="ai.anyray.connect.refresh",Ii="anyray-refresh",gm="\\AnyrayConnectKeyRefresh",rd=nd,Ei=Ii,Si=gm,MN=String(ed/60),wm=(e,t)=>{let n=$N(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},bm=()=>Go(td(),"Library","LaunchAgents",`${rd}.plist`),km=()=>Go(td(),".config","systemd","user"),OC=()=>Go(km(),`${Ei}.service`),Ql=()=>Go(km(),`${Ei}.timer`),mm=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),od=()=>Qr(Zr),BN=(e=od())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${mm(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">
|
|
@@ -32,14 +32,14 @@ ${r}
|
|
|
32
32
|
<key>StandardErrorPath</key><string>${mm(hm())}</string>
|
|
33
33
|
</dict>
|
|
34
34
|
</plist>
|
|
35
|
-
`},
|
|
35
|
+
`},FN=(e=od())=>{let{command:t,args:n}=e;return`[Unit]
|
|
36
36
|
Description=Anyray connect gateway key refresh
|
|
37
37
|
After=network-online.target
|
|
38
38
|
|
|
39
39
|
[Service]
|
|
40
40
|
Type=oneshot
|
|
41
41
|
ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
|
|
42
|
-
`},
|
|
42
|
+
`},UN=()=>`[Unit]
|
|
43
43
|
Description=Anyray connect gateway key refresh (every ${ed/60}m)
|
|
44
44
|
|
|
45
45
|
[Timer]
|
|
@@ -49,13 +49,13 @@ Persistent=true
|
|
|
49
49
|
|
|
50
50
|
[Install]
|
|
51
51
|
WantedBy=timers.target
|
|
52
|
-
`,
|
|
53
|
-
${t.stderr??""}`}},XL=async e=>{try{return(await VL(e)).isDirectory()}catch{return!1}},zL=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},Ri=async(e,t={})=>{if((t.os??KL())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??XL)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??JL;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?zL(a.output):void 0;return s?YL.has(s)?ZL(a.output)!==mr?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},ja=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await Ri(n,t)).ok?"healthy":"gone"},Cm=async(e={})=>{try{let t=e.load??N,n=await t(),r=await ja(n,e);if(r!=="gone")return r;let o=e.installScheduler??eo;return n.refreshSchedulerEnabled&&ot(n)&&await o().catch(()=>{}),await(e.save??pe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var qL={"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."},QL=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},eN=async(e,t)=>{let n=t.stderr??console.error,r=QL(e,"--app-path")??DC,o=await Ri(r,t);if(!o.ok)return n(qL[o.reason]),1;let s=await(t.load??N)();return await(t.save??pe)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??fr)().catch(()=>{}),0},tN=async e=>{let t=e.load??N,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??eo;return n.refreshSchedulerEnabled&&ot(n)&&await r().catch(()=>{}),await(e.save??pe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},LC=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await eN(e,t):e.includes("--release-tray")?await tN(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 nN}from"node:fs/promises";import{homedir as ad,platform as _i}from"node:os";import{join as Pt}from"node:path";import{basename as NC,dirname as Am,join as Ya}from"node:path";var to="https://github.com/anyrayHQ/install/releases",Ko="connect-v",vm="release-assets.githubusercontent.com",Sm=".anyray",Vo="__anyray-refresh-desktop-helpers",no=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",hr=(e,t=process.platform)=>({launcher:Ya(e,"bin",no(t)),binDir:Ya(e,"bin"),versionsDir:Ya(e,"versions"),lock:Ya(e,"update.lock"),state:Ya(e,"update-state.json")}),Oi=(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"}},Im=(e,t,n=process.platform)=>NC(e)===no(n)&&NC(Am(e))==="bin"?Am(Am(e)):Ya(t,Sm);var Em=(e=_i(),t=ad())=>e==="darwin"?[{id:mr,mechanism:"launch-agent",filePaths:[Pt(t,"Library","LaunchAgents",`${mr}.plist`)]}]:e==="linux"?[{id:mr,mechanism:"xdg-autostart",filePaths:[Pt(t,".config","autostart",`${mr}.desktop`)]}]:e==="win32"?[{id:mr,mechanism:"registry-run",filePaths:[],registryValues:[{key:"HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",value:mr},{key:"HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",value:mr}]}]:[],sd=(e=_i(),t=ad())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:nd,paths:[Pt(t,"Library","LaunchAgents",`${nd}.plist`)],dataPaths:[Pt(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=Pt(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${Ii}.timer`,paths:[Pt(n,`${Ii}.timer`),Pt(n,`${Ii}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:gm,paths:[]}]:[]},$C=async e=>{try{return await nN(e),!0}catch{return!1}},id=async(e={})=>{let t=e.os??_i(),n=e.exists??$C;for(let r of sd(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await Nn(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},MC=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??$C;for(let r of sd(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},BC=e=>{let t=e.os??_i(),n=e.home??ad(),r=e.binaryPath??Wo(),o=e.arch??process.arch,a=hr(Im(r,n,t),t),s=no(t);return{schema:"anyray.connect.security-exclusions/v1",connectVersion:e.connectVersion,platform:t,arch:o,binary:{path:r,...e.binarySha256?{sha256:e.binarySha256}:{}},services:sd(t,n).map(i=>({kind:i.kind,title:i.title,supervisorName:i.supervisorName,unitPaths:i.paths,logPaths:i.dataPaths??[]})),optionalDesktopAutostart:Em(t,n),writePaths:[Pt(a.versionsDir,"<version>",s),a.launcher,a.lock,a.state],network:{outboundHosts:[...e.gatewayHost?[e.gatewayHost]:[],"github.com",vm],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."]}},FC=(e=_i(),t=ad(),n=Wo(),r=process.arch)=>{let o=hr(Im(n,t,e),e),a=no(e),s=Oi(e,r),i=s?[` ${to}/download/${Ko}<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 sd(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 Em(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 Em(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 ${vm}.`," - 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:",` ${to}/latest`," (the redirect target alone names the published version)",` ${to}/download/${Ko}<version>/connect-update.json`,` ${to}/download/${Ko}<version>/SHA256SUMS`,...i,""," Writes:",` ${Pt(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}`,` ${Pt(o.versionsDir,"<version>",`${a}.part-<pid>`)}`,...e==="win32"?[` ${Pt(o.binDir,`${a}.old-<pid>`)}`,` ${Pt(o.binDir,`${a}.rollback-<pid>`)}`]:[` ${Pt(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 ${Vo}\`, 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 bN}from"node:os";import{join as yd}from"node:path";import{chmod as kN,readFile as Ja,rm as YC,copyFile as CN}from"node:fs/promises";import{parse as rN}from"smol-toml";var yr="# >>> anyray connect >>>",Za="# <<< anyray connect <<<",xm="# restore: ",UC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ld=e=>{let t=new RegExp(`\\n*${UC(yr)}[\\s\\S]*?${UC(Za)}\\n?`,"g");return HC(e.replace(t,""))},oN="model_provider",aN="anyray",sN=new RegExp(`^\\s*(["'])${aN}\\1\\s*(#.*)?$`),iN=(e,t)=>t===oN&&sN.test(e.slice(e.indexOf("=")+1)),HC=e=>{let t=e.indexOf(yr);if(t<0||e.indexOf(Za,t+yr.length)>=0)return e;let n=e.slice(0,t),r=e.slice(t).split(`
|
|
54
|
-
`),o=jo(r),a=1;for(;a<r.length;){let s=o[a];if(s.kind==="table"||s.kind==="key"&&!
|
|
52
|
+
`,WN=(e=od())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),vi=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(" ")}`],_C=e=>!e.run&&xC(),HN=async(e,t)=>await NN(bm(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",rd]).ok,eo=async(e={})=>{let t=e.os??ym(),n=e.invocation??od(),r=e.run??wm,o=e.binaryPath??Wo();if(ut(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(_C(e))return{ok:!1,messages:pm("auto-refresh scheduling")};let a=Nn(e.env??(e.run?{}:process.env));if(pr(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${Va(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=bm(),i=BN(n),c=await um({os:t});if(await HN(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`,...c.messages]};await fm(RC(),{recursive:!0,mode:448}),await fm(Go(td(),"Library","LaunchAgents"),{recursive:!0});let l=String(process.getuid?.()??""),d=`${s}.new-${process.pid}`;await Ho(d,{force:!0}).catch(()=>{}),await ql(d,i),r("launchctl",["bootout",`gui/${l}`,s]),await Ho(s,{force:!0}).catch(()=>{});try{await LN(d,s)}catch{await ql(s,i),await Ho(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.`,...vi(n)]}}if(t==="linux")return await fm(km(),{recursive:!0}),await ql(OC(),FN(n)),await ql(Ql(),UN()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${Ei}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${Ql()}).`]}:{ok:!1,messages:[`Wrote ${Ql()} but \`systemctl --user enable --now\` failed.`,...vi(n)]};if(t==="win32"){let s=WN(n);return r("schtasks",["/Create","/TN",Si,"/TR",s,"/SC","MINUTE","/MO",MN,"/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.",...vi(n)]}}return{ok:!1,messages:vi(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...vi(n)]}}},fr=async(e={})=>{await Ho(hm(),{force:!0}).catch(()=>{});let t=e.os??ym(),n=e.run??wm,r=[];if(_C(e))return{ok:!0,messages:pm("scheduler teardown")};try{if(t==="darwin"){let o=bm(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Ho(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.");let s=await um({os:t});r.push(...s.messages)}else t==="linux"?(n("systemctl",["--user","disable","--now",`${Ei}.timer`]),await Ho(Ql(),{force:!0}),await Ho(OC(),{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}},Ln=async(e=ym(),t=wm)=>e==="win32"?t("schtasks",["/Query","/TN",Si]).ok:e==="darwin"?t("launchctl",["list",rd]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${Ei}.timer`]).ok:!1;import{platform as KN}from"node:os";import{stat as VN}from"node:fs/promises";import{spawnSync as jN}from"node:child_process";var xi=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},TC=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),GN=10080*60*1e3,PC=(e,t,n=Date.now())=>{let r=[],o=xi(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)<=GN},ot=(e,t={},n=Date.now())=>{if(!e.enrolledCert)return!1;let o=(t.toolIds??e.managedTools??[]).some(a=>TC.has(a));return PC(e,t.keyExpiresAt,n)||!o};var DC="/Applications/Anyray Connect Tray.app",YN=new Set(["V53XMA78UF"]),mr="ai.anyray.connect-tray",ZN=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,JN=e=>{let t=jN("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
53
|
+
${t.stderr??""}`}},XN=async e=>{try{return(await VN(e)).isDirectory()}catch{return!1}},zN=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},Ri=async(e,t={})=>{if((t.os??KN())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??XN)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??JN;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?zN(a.output):void 0;return s?YN.has(s)?ZN(a.output)!==mr?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},ja=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await Ri(n,t)).ok?"healthy":"gone"},Cm=async(e={})=>{try{let t=e.load??L,n=await t(),r=await ja(n,e);if(r!=="gone")return r;let o=e.installScheduler??eo;return n.refreshSchedulerEnabled&&ot(n)&&await o().catch(()=>{}),await(e.save??pe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var qN={"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."},QN=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},eL=async(e,t)=>{let n=t.stderr??console.error,r=QN(e,"--app-path")??DC,o=await Ri(r,t);if(!o.ok)return n(qN[o.reason]),1;let s=await(t.load??L)();return await(t.save??pe)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??fr)().catch(()=>{}),0},tL=async e=>{let t=e.load??L,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??eo;return n.refreshSchedulerEnabled&&ot(n)&&await r().catch(()=>{}),await(e.save??pe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},NC=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await eL(e,t):e.includes("--release-tray")?await tL(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 nL}from"node:fs/promises";import{homedir as ad,platform as _i}from"node:os";import{join as Pt}from"node:path";import{basename as LC,dirname as Am,join as Ya}from"node:path";var to="https://github.com/anyrayHQ/install/releases",Ko="connect-v",vm="release-assets.githubusercontent.com",Sm=".anyray",Vo="__anyray-refresh-desktop-helpers",no=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",hr=(e,t=process.platform)=>({launcher:Ya(e,"bin",no(t)),binDir:Ya(e,"bin"),versionsDir:Ya(e,"versions"),lock:Ya(e,"update.lock"),state:Ya(e,"update-state.json")}),Oi=(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"}},Im=(e,t,n=process.platform)=>LC(e)===no(n)&&LC(Am(e))==="bin"?Am(Am(e)):Ya(t,Sm);var Em=(e=_i(),t=ad())=>e==="darwin"?[{id:mr,mechanism:"launch-agent",filePaths:[Pt(t,"Library","LaunchAgents",`${mr}.plist`)]}]:e==="linux"?[{id:mr,mechanism:"xdg-autostart",filePaths:[Pt(t,".config","autostart",`${mr}.desktop`)]}]:e==="win32"?[{id:mr,mechanism:"registry-run",filePaths:[],registryValues:[{key:"HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",value:mr},{key:"HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",value:mr}]}]:[],sd=(e=_i(),t=ad())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:nd,paths:[Pt(t,"Library","LaunchAgents",`${nd}.plist`)],dataPaths:[Pt(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=Pt(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${Ii}.timer`,paths:[Pt(n,`${Ii}.timer`),Pt(n,`${Ii}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:gm,paths:[]}]:[]},$C=async e=>{try{return await nL(e),!0}catch{return!1}},id=async(e={})=>{let t=e.os??_i(),n=e.exists??$C;for(let r of sd(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await Ln(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},MC=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??$C;for(let r of sd(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},BC=e=>{let t=e.os??_i(),n=e.home??ad(),r=e.binaryPath??Wo(),o=e.arch??process.arch,a=hr(Im(r,n,t),t),s=no(t);return{schema:"anyray.connect.security-exclusions/v1",connectVersion:e.connectVersion,platform:t,arch:o,binary:{path:r,...e.binarySha256?{sha256:e.binarySha256}:{}},services:sd(t,n).map(i=>({kind:i.kind,title:i.title,supervisorName:i.supervisorName,unitPaths:i.paths,logPaths:i.dataPaths??[]})),optionalDesktopAutostart:Em(t,n),writePaths:[Pt(a.versionsDir,"<version>",s),a.launcher,a.lock,a.state],network:{outboundHosts:[...e.gatewayHost?[e.gatewayHost]:[],"github.com",vm],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."]}},FC=(e=_i(),t=ad(),n=Wo(),r=process.arch)=>{let o=hr(Im(n,t,e),e),a=no(e),s=Oi(e,r),i=s?[` ${to}/download/${Ko}<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 sd(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 Em(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 Em(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 ${vm}.`," - 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:",` ${to}/latest`," (the redirect target alone names the published version)",` ${to}/download/${Ko}<version>/connect-update.json`,` ${to}/download/${Ko}<version>/SHA256SUMS`,...i,""," Writes:",` ${Pt(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}`,` ${Pt(o.versionsDir,"<version>",`${a}.part-<pid>`)}`,...e==="win32"?[` ${Pt(o.binDir,`${a}.old-<pid>`)}`,` ${Pt(o.binDir,`${a}.rollback-<pid>`)}`]:[` ${Pt(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 ${Vo}\`, 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 bL}from"node:os";import{join as yd}from"node:path";import{chmod as kL,readFile as Ja,rm as YC,copyFile as CL}from"node:fs/promises";import{parse as rL}from"smol-toml";var yr="# >>> anyray connect >>>",Za="# <<< anyray connect <<<",xm="# restore: ",UC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ld=e=>{let t=new RegExp(`\\n*${UC(yr)}[\\s\\S]*?${UC(Za)}\\n?`,"g");return HC(e.replace(t,""))},oL="model_provider",aL="anyray",sL=new RegExp(`^\\s*(["'])${aL}\\1\\s*(#.*)?$`),iL=(e,t)=>t===oL&&sL.test(e.slice(e.indexOf("=")+1)),HC=e=>{let t=e.indexOf(yr);if(t<0||e.indexOf(Za,t+yr.length)>=0)return e;let n=e.slice(0,t),r=e.slice(t).split(`
|
|
54
|
+
`),o=jo(r),a=1;for(;a<r.length;){let s=o[a];if(s.kind==="table"||s.kind==="key"&&!iL(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
|
-
`)}`},Rm=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},cd=(e,t)=>e.split(t).length-1,WC=e=>cd(e,"[")-cd(e,"]"),
|
|
57
|
-
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},
|
|
58
|
-
`),o=jo(r),a=!1;for(let s=0;s<r.length;s++){if(o[s].kind==="table"){a=GC(r[s])===t;continue}if(a&&r[s].includes(n))return!0}return!1},ud=(e,t)=>_m(e,t)?_m(ld(e),t)?dd(e)&&!e.includes(Za)&&
|
|
56
|
+
`)}`},Rm=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},cd=(e,t)=>e.split(t).length-1,WC=e=>cd(e,"[")-cd(e,"]"),cL=e=>e.replace(/^['"]|['"]$/g,""),jo=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){cd(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+WC(Rm(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?cL(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=Rm(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])cd(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+WC(l)))}return t},Om=e=>e.findIndex(t=>t.kind==="table"),dd=e=>e.includes(yr),_m=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
57
|
+
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},lL=new Map([["model_providers.anyray",'name = "Anyray Gateway"'],["mcp_servers.anyray","anyray-connect"]]),dL=(e,t)=>{let n=lL.get(t);if(n===void 0)return!1;let r=e.split(`
|
|
58
|
+
`),o=jo(r),a=!1;for(let s=0;s<r.length;s++){if(o[s].kind==="table"){a=GC(r[s])===t;continue}if(a&&r[s].includes(n))return!0}return!1},ud=(e,t)=>_m(e,t)?_m(ld(e),t)?dd(e)&&!e.includes(Za)&&dL(e,t)?"orphaned":"foreign":"managed":"absent",pd=(e,t)=>{let n=e.split(`
|
|
59
59
|
`),r=jo(n),o=i=>{let c=GC(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
|
|
|
@@ -72,53 +72,53 @@ ${t.stderr??""}`}},XL=async e=>{try{return(await VL(e)).isDirectory()}catch{retu
|
|
|
72
72
|
`),n].filter(a=>a.length>0).join(`
|
|
73
73
|
|
|
74
74
|
`);return o.length>0?o+`
|
|
75
|
-
`:""},jC=e=>{if(e.trim().length===0)return!0;try{return rN(e),!0}catch{return!1}};import{randomUUID as uN}from"node:crypto";import{chmod as pN,mkdir as fN,rm as mN,writeFile as hN}from"node:fs/promises";import{dirname as yN}from"node:path";var ve=async(e,t)=>{await fN(yN(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${uN()}`;try{await hN(n,t,{flag:"wx",mode:384}),await ke(n,e),await pN(e,384)}finally{await mN(n,{force:!0}).catch(()=>{})}};import{homedir as gN}from"node:os";import{join as wN}from"node:path";var Yt=()=>wN(gN(),".agents","skills");var AN="codex",vN="Codex app / CLI / IDE",SN="https://chatgpt.com/backend-api/codex",IN="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",EN="x-anyray-client-context-window",xN="x-anyray-client-auto-compact-limit",gd=()=>process.env.CODEX_HOME?.trim()||yd(bN(),".codex"),wr=()=>yd(gd(),"config.toml"),hd=()=>`${wr()}.anyray-bak`,Dm=()=>yd(gd(),"hooks.json"),gr=()=>yd(gd(),"anyray.config.toml"),ZC=e=>En(e,"PostToolUse",Ek),JC=(e,t=!1)=>be({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||AN,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||vN}),ft=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Lm=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,Ti=(e,t={})=>{let n=JC(e,t.ignoreEnv),r=se(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:Lm(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${ft(SN)}`,`"x-anyray-forward-headers" = ${ft(IN)}`,...i?[`"x-anyray-api-key" = ${ft(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${ft(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${ft(n)}`),a&&c.push(`"x-anyray-provider" = ${ft(a)}`),t.modelContextWindow&&c.push(`"${EN}" = ${ft(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${xN}" = ${ft(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 = ${ft(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${ft(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${ft(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>ft(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${ft(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(ft).join(", ")}]`]:[]]},RN=["model_providers.anyray","mcp_servers.anyray"],ON=()=>Lm()?["model_provider","model"]:["model_provider"],XC={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,skillsDir(){return Yt()},async syncOrgMcp({entry:e}){let t=wr(),n=await R(t)?await Ja(t,"utf-8"):"",{text:r,outcome:o}=gC(n,e);return o!=="changed"?{changed:!1}:!n&&e===void 0?{changed:!1}:(await ve(t,r),{changed:!0})},async detect(){let e=gd(),t=await R(e);return{installed:t,detail:t?wr():`no ${e} directory`}},async apply(e,t){let n=wr(),r=Dm(),o=JC(e),a=se(e,"openai"),s=Lm(),i=ne(),c={},l=await R(r);try{l&&(c=await F(r))}catch(T){return{status:"manual",refused:!0,messages:[`Could not inspect the Codex hooks file ${r} (${T instanceof Error?T.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=ZC(c),u=[],p=[];d?(t.dryRun||(await q(r,c,{backup:!1}),await fe(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 Ja(n,"utf-8"):"";if(!jC(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=ud(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 g=ud(f,"mcp_servers.anyray"),y=g==="foreign",w=Pm(f,"model_context_window"),b=Pm(f,"model_auto_compact_token_limit"),A=[`${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}.`:w?`Context budget: follows model_context_window=${w}.`:"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 A.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:A};let C=[...u];A.push(...p),m&&!await R(hd())&&(await CN(n,hd()),await kN(hd(),384),A.push(`Backed up your original config to ${hd()}.`));let x=i&&!y?Ue("profile"):void 0,O=i&&e.clientKey?Mo("print-key"):void 0;A.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=pd(S,"model_providers.anyray"),A.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.`)),g==="orphaned"&&(S=pd(S,"mcp_servers.anyray"));let E=fd(S,Ti(e,{mcpServer:x,modelContextWindow:w,modelAutoCompactTokenLimit:b,...O?{auth:"command",authCommand:O.command,authArgs:O.args}:{}}),ON());return await ve(n,E),C.push(n),await R(gr())&&(await YC(gr(),{force:!0}),C.push(gr()),A.push(`Removed the old opt-in profile ${gr()} (the default route replaces it).`)),{status:"configured",messages:A,changedFiles:C,...y?{errorClass:"mcp_foreign"}:{}}},async pointsAt(e){let t=wr();if(!await R(t))return!1;try{let n=await Ja(t,"utf-8"),r=`base_url = ${ft(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async configuredKeyIsCurrent(e){return jt([wr()],e)},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=wr();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await Ja(e,"utf-8");if(!KC(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 Ja(wr(),"utf-8"),t=Tm(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=wr(),n=await R(t),r=await R(gr()),o=await R(Dm());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=Dm(),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.`]}}ZC(c)&&(e.dryRun||(await q(i,c,{backup:!1}),await fe(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 Ja(t,"utf-8"),c=RN.reduce((d,u)=>ud(d,u)==="orphaned"?pd(d,u):d,i),l=md(c)??(c===i?null:c);l!==null&&(e.dryRun||await ve(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 YC(gr(),{force:!0}),s.push(gr()),a.push(e.dryRun?`would remove the old opt-in profile ${gr()}`:`removed the old opt-in profile ${gr()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await fe(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as MN}from"node:os";import{join as BN}from"node:path";import{readFile as eA,rm as $m}from"node:fs/promises";import{readFile as _N,writeFile as zC,access as TN}from"node:fs/promises";import{homedir as PN}from"node:os";import{join as Nm}from"node:path";var DN="# >>> anyray connect >>>",LN="# <<< anyray connect <<<",Pi=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:DN,end:LN},mt=()=>{let e=PN(),t=process.env.SHELL||"";return t.includes("zsh")?Nm(e,".zshrc"):t.includes("bash")?Nm(e,".bashrc"):Nm(e,".profile")},wd=async e=>{try{return await TN(e),await _N(e,"utf-8")}catch{return""}},NN=/^export\s+(ANTHROPIC_(BASE_URL|AUTH_TOKEN|API_KEY|MODEL|DEFAULT_[A-Z_]+)|OPENAI_(BASE_URL|API_KEY)|ANYRAY_[A-Z0-9_]+)=/,$N=(e,t,n=[])=>{let{begin:r,end:o}=Pi(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
|
+
`:""},jC=e=>{if(e.trim().length===0)return!0;try{return rL(e),!0}catch{return!1}};import{randomUUID as uL}from"node:crypto";import{chmod as pL,mkdir as fL,rm as mL,writeFile as hL}from"node:fs/promises";import{dirname as yL}from"node:path";var ve=async(e,t)=>{await fL(yL(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${uL()}`;try{await hL(n,t,{flag:"wx",mode:384}),await ke(n,e),await pL(e,384)}finally{await mL(n,{force:!0}).catch(()=>{})}};import{homedir as gL}from"node:os";import{join as wL}from"node:path";var Yt=()=>wL(gL(),".agents","skills");var AL="codex",vL="Codex app / CLI / IDE",SL="https://chatgpt.com/backend-api/codex",IL="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",EL="x-anyray-client-context-window",xL="x-anyray-client-auto-compact-limit",gd=()=>process.env.CODEX_HOME?.trim()||yd(bL(),".codex"),wr=()=>yd(gd(),"config.toml"),hd=()=>`${wr()}.anyray-bak`,Dm=()=>yd(gd(),"hooks.json"),gr=()=>yd(gd(),"anyray.config.toml"),ZC=e=>En(e,"PostToolUse",Ek),JC=(e,t=!1)=>be({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||AL,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||vL}),ft=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Nm=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,Ti=(e,t={})=>{let n=JC(e,t.ignoreEnv),r=se(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:Nm(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${ft(SL)}`,`"x-anyray-forward-headers" = ${ft(IL)}`,...i?[`"x-anyray-api-key" = ${ft(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${ft(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${ft(n)}`),a&&c.push(`"x-anyray-provider" = ${ft(a)}`),t.modelContextWindow&&c.push(`"${EL}" = ${ft(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${xL}" = ${ft(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 = ${ft(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${ft(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${ft(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>ft(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${ft(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(ft).join(", ")}]`]:[]]},RL=["model_providers.anyray","mcp_servers.anyray"],OL=()=>Nm()?["model_provider","model"]:["model_provider"],XC={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,skillsDir(){return Yt()},async syncOrgMcp({entry:e}){let t=wr(),n=await R(t)?await Ja(t,"utf-8"):"",{text:r,outcome:o}=gC(n,e);return o!=="changed"?{changed:!1}:!n&&e===void 0?{changed:!1}:(await ve(t,r),{changed:!0})},async detect(){let e=gd(),t=await R(e);return{installed:t,detail:t?wr():`no ${e} directory`}},async apply(e,t){let n=wr(),r=Dm(),o=JC(e),a=se(e,"openai"),s=Nm(),i=ne(),c={},l=await R(r);try{l&&(c=await F(r))}catch(T){return{status:"manual",refused:!0,messages:[`Could not inspect the Codex hooks file ${r} (${T instanceof Error?T.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=ZC(c),u=[],p=[];d?(t.dryRun||(await q(r,c,{backup:!1}),await fe(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 Ja(n,"utf-8"):"";if(!jC(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=ud(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 g=ud(f,"mcp_servers.anyray"),y=g==="foreign",w=Pm(f,"model_context_window"),b=Pm(f,"model_auto_compact_token_limit"),A=[`${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}.`:w?`Context budget: follows model_context_window=${w}.`:"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 A.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:A};let C=[...u];A.push(...p),m&&!await R(hd())&&(await CL(n,hd()),await kL(hd(),384),A.push(`Backed up your original config to ${hd()}.`));let x=i&&!y?Ue("profile"):void 0,O=i&&e.clientKey?Mo("print-key"):void 0;A.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=pd(S,"model_providers.anyray"),A.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.`)),g==="orphaned"&&(S=pd(S,"mcp_servers.anyray"));let E=fd(S,Ti(e,{mcpServer:x,modelContextWindow:w,modelAutoCompactTokenLimit:b,...O?{auth:"command",authCommand:O.command,authArgs:O.args}:{}}),OL());return await ve(n,E),C.push(n),await R(gr())&&(await YC(gr(),{force:!0}),C.push(gr()),A.push(`Removed the old opt-in profile ${gr()} (the default route replaces it).`)),{status:"configured",messages:A,changedFiles:C,...y?{errorClass:"mcp_foreign"}:{}}},async pointsAt(e){let t=wr();if(!await R(t))return!1;try{let n=await Ja(t,"utf-8"),r=`base_url = ${ft(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async configuredKeyIsCurrent(e){return jt([wr()],e)},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=wr();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await Ja(e,"utf-8");if(!KC(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 Ja(wr(),"utf-8"),t=Tm(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=wr(),n=await R(t),r=await R(gr()),o=await R(Dm());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=Dm(),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.`]}}ZC(c)&&(e.dryRun||(await q(i,c,{backup:!1}),await fe(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 Ja(t,"utf-8"),c=RL.reduce((d,u)=>ud(d,u)==="orphaned"?pd(d,u):d,i),l=md(c)??(c===i?null:c);l!==null&&(e.dryRun||await ve(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 YC(gr(),{force:!0}),s.push(gr()),a.push(e.dryRun?`would remove the old opt-in profile ${gr()}`:`removed the old opt-in profile ${gr()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await fe(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as ML}from"node:os";import{join as BL}from"node:path";import{readFile as eA,rm as $m}from"node:fs/promises";import{readFile as _L,writeFile as zC,access as TL}from"node:fs/promises";import{homedir as PL}from"node:os";import{join as Lm}from"node:path";var DL="# >>> anyray connect >>>",NL="# <<< anyray connect <<<",Pi=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:DL,end:NL},mt=()=>{let e=PL(),t=process.env.SHELL||"";return t.includes("zsh")?Lm(e,".zshrc"):t.includes("bash")?Lm(e,".bashrc"):Lm(e,".profile")},wd=async e=>{try{return await TL(e),await _L(e,"utf-8")}catch{return""}},LL=/^export\s+(ANTHROPIC_(BASE_URL|AUTH_TOKEN|API_KEY|MODEL|DEFAULT_[A-Z_]+)|OPENAI_(BASE_URL|API_KEY)|ANYRAY_[A-Z0-9_]+)=/,$L=(e,t,n=[])=>{let{begin:r,end:o}=Pi(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
|
-
`),p=0;for(;p<u.length;){let h=u[p].trim(),g=h===""||h.startsWith("#")||d.has(h)||
|
|
77
|
+
`),p=0;for(;p<u.length;){let h=u[p].trim(),g=h===""||h.startsWith("#")||d.has(h)||LL.test(h);if(p>0&&!g)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}
|
|
79
79
|
${f}`}let l=s+o.length;return e[l]===`
|
|
80
|
-
`&&(l+=1),e.slice(0,c)+e.slice(l)},qC=(e,t,n=[])=>{let r=e;for(;;){let o=$
|
|
80
|
+
`&&(l+=1),e.slice(0,c)+e.slice(l)},qC=(e,t,n=[])=>{let r=e;for(;;){let o=$L(r,t,n);if(o===r)return r;r=o}},bd=async(e,t,n)=>{let r=await wd(e),{begin:o,end:a}=Pi(n),s=qC(r,n,t).replace(/\s*$/,""),i=[o,...t,a].join(`
|
|
81
81
|
`),c=s?`${s}
|
|
82
82
|
|
|
83
83
|
${i}
|
|
84
84
|
`:`${i}
|
|
85
85
|
`;return await zC(e,c),e},Di=async(e,t)=>{let n=await wd(e),{begin:r,end:o}=Pi(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
|
-
`).filter(c=>c.trim().length>0)},QC=async(e,t)=>(await wd(e)).includes(Pi(t).begin),
|
|
87
|
-
`),!0):!1};var Zt=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,"'\\''")}'`,
|
|
88
|
-
`)):g&&w&&await $m(d,{force:!0}),await bd(n,p)}catch(b){try{y!==void 0&&w?await ve(d,y):w&&await $m(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||g&&w?[d]:[]]}},async revert(e){let t=mt(),n=Mm(),r=await R(n),o=r?nA(await eA(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
|
|
86
|
+
`).filter(c=>c.trim().length>0)},QC=async(e,t)=>(await wd(e)).includes(Pi(t).begin),Ni=async(e,t)=>{let n=await wd(e);return n.includes(Pi(t).begin)?(await zC(e,qC(n,t).replace(/\s*$/,"")+`
|
|
87
|
+
`),!0):!1};var Zt=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,"'\\''")}'`,FL=e=>{let t=$e(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},tA=(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'"]],UL=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],WL=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],Mm=()=>BL(ML(),".anyray","shell-env.sh"),oA="# Managed by anyray-connect. Do not source this file anywhere else.",nA=e=>e.split(/\r?\n/,1)[0]===oA,Bm=e=>WL.some(t=>e.startsWith(`export ${t}=`)),rA=(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},kd=(e,t=process.env)=>t.ANTHROPIC_BASE_URL===e.anthropicBaseUrl||t.OPENAI_BASE_URL===e.openaiBaseUrl?UL.filter(r=>(t[r]??"")!==""):[],aA={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=mt();return{installed:!0,detail:await R(e)?e:`${e} (will be created)`}},async pointsAt(e){try{let t=await Di(mt());if(!t)return!1;let n=dt(e),r=rA(t,"OPENAI_BASE_URL"),o=rA(t,"ANTHROPIC_BASE_URL");return r!==void 0&&o!==void 0&&dt(r)===n&&dt(o)===n}catch{return!1}},async configuredKeyIsCurrent(e){let t=mt();return t?jt([t],e):null},async routingExpected(e){return e.includes("shell-env")},async inferenceAuthLanes(){try{let e=await Di(mt());return e?e.some(n=>Bm(n)||n.includes(Mm()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=mt(),r=se(e,"openai"),o=se(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=tA(e,s,r,o),c=i.filter(Bm),l=i.filter(b=>!Bm(b)),d=Mm(),u=$l(),p=[FL(u),...l,...c.length>0?[`[ -r ${$e(d)} ] && . ${$e(d)}`]:[]],m=e.clientKey?tA(e,Zt(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."]],g=await R(d),y=g?await eA(d,"utf8"):void 0,w=y===void 0||nA(y);if(c.length>0&&!w)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(w||h.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:h};try{c.length>0?await ve(d,[oA,...c,""].join(`
|
|
88
|
+
`)):g&&w&&await $m(d,{force:!0}),await bd(n,p)}catch(b){try{y!==void 0&&w?await ve(d,y):w&&await $m(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||g&&w?[d]:[]]}},async revert(e){let t=mt(),n=Mm(),r=await R(n),o=r?nA(await eA(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 Ni(t);o&&await $m(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 E$}from"node:child_process";import{closeSync as x$,copyFileSync as R$,existsSync as Ne,mkdirSync as O$,openSync as _$,readFileSync as WA,readSync as T$,renameSync as P$,rmSync as Bn,writeFileSync as Qm}from"node:fs";import{homedir as HA,platform as D$}from"node:os";import{dirname as GA,join as es,resolve as N$}from"node:path";import{isIP as Ym}from"node:net";import{homedir as HL,platform as GL}from"node:os";import{join as Cd}from"node:path";var We=e=>{let t=HL();switch(GL()){case"darwin":return Cd(t,"Library","Application Support",e);case"win32":return Cd(process.env.APPDATA??Cd(t,"AppData","Roaming"),e);default:return Cd(t,".config",e)}};import{execFileSync as Sd}from"node:child_process";import{mkdtempSync as KL,rmSync as VL,writeFileSync as jL}from"node:fs";import{createRequire as YL}from"node:module";import{tmpdir as ZL}from"node:os";import{join as sA}from"node:path";var Li=class extends Error{},$i=e=>e instanceof Li?`: ${e.message}`:"",iA=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new Li("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new Li(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},cA=()=>{try{return Sd("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Um=64*1024*1024,JL=Um*2+64,vd=e=>`'${e.replace(/'/g,"''")}'`,XL=(e,t)=>Sd("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:JL,stdio:["ignore","pipe","pipe"]}),zL=(e,t)=>Sd("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Um,stdio:["pipe","pipe","pipe"]}),lA=(e,t,n=XL)=>{let r=vd(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
|
-
`)?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")},dA=(e,t=
|
|
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")},dA=(e,t=zL)=>{let r=t(e,`.bail on
|
|
91
91
|
.timeout 5000
|
|
92
92
|
PRAGMA wal_checkpoint(TRUNCATE);
|
|
93
|
-
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");iA(o?.slice(1).map(Number))},
|
|
94
|
-
`);Sd("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Um,stdio:["pipe","ignore","pipe"]})}finally{try{
|
|
95
|
-
`,{mode:384}),await ke(n,t)},kA=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,oo=async(e,t)=>await jm(e,t)==="claimed",jm=async(e,t)=>{let n=Xa(e);if(t){let o=`${n}.${process.pid}.${mA()}.claimed`;try{await c$(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Vm(o,e);if(a&&kA(a,t))return await Mi(o,{force:!0}),"claimed";let s=!1;try{await yA(o,n,hA.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await Mi(o,{force:!0})}return"superseded"}let r=!1;try{await Mi(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await Mi(wA(),{force:!0})}catch{}return r?"claimed":"absent"},$n=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},m$=e=>{let{command:t,args:n}=Qr("__anyray-quit-watch");return{exe:t,args:[...n,e]}},h$=e=>{let{exe:t,args:n}=m$(e),r=r$(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},Wm=h$;var CA=async()=>{let e=[],t;try{t=await Mn()}catch{return e}for(let n of t)if(!$n(n.watcherPid))try{uA&&await uA(n),await y$(n)&&e.push(n.adapter)}catch{}return e},uA;var y$=async e=>{let t=Xa(e.adapter);await Id();let n=await $a(`${t}.lock`,{waitMs:AA,staleMs:vA,busyMessage:`pending operation queue for ${e.adapter} is busy; retry`});try{let r=await Fi(e.adapter);if(!r||!kA(r,e)||$n(r.watcherPid))return!1;let o=Wm(e.adapter);return o?(await Bi({...r,watcherPid:o}),!0):!1}finally{await n()}},pA=(e,t)=>{let n=e.indexOf(t);return n===-1?e.length:n},g$=(e,t,n)=>e!==void 0&&(t.op===n||e.includes(t.op)&&pA(e,t.op)<=pA(e,n)),fA;var AA=2e3,vA=1e4,Ed=async(e,t,n={})=>{if(!gA.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let r=Xa(e);await Id();let o=await $a(`${r}.lock`,{waitMs:AA,staleMs:vA,busyMessage:`pending operation queue for ${e} is busy; retry`});try{return await w$(e,t,n.precedence)}finally{await o()}},w$=async(e,t,n)=>{let r=await Fi(e);if(fA&&await fA({adapter:e,op:t,existing:r}),r&&g$(n,r,t)){if($n(r.watcherPid))return{watcherPid:r.watcherPid,alreadyWatching:!0};let i;try{i=Wm(e)}catch{i=void 0}return i&&await Bi({...r,watcherPid:i}),{watcherPid:i,alreadyWatching:!1}}let o=new Date().toISOString(),a=mA();if(r&&$n(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=Wm(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 b$,spawnSync as IA}from"node:child_process";import{existsSync as xd}from"node:fs";import{homedir as k$,platform as ao}from"node:os";import{join as EA,win32 as SA}from"node:path";var xA=(e,t={})=>{let n=t.env??process.env,r=t.exists??xd,o=(t.home??k$)(),a={localAppData:n.LOCALAPPDATA??SA.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=SA.join(i,s.path);if(r(c))return c}},Yo=/^[A-Za-z0-9 ._-]{1,64}$/,C$=/^[A-Za-z0-9.-]{1,128}$/,Rd=e=>e.darwinBundleId&&C$.test(e.darwinBundleId)?e.darwinBundleId:void 0,RA=(e,t=ao())=>t==="darwin"?Rd(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",OA=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",_A=(e,t=ao(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return xA(e,r)!==void 0;let o=e.linuxProcess;return!o||!Yo.test(o)?!1:n.split(":").filter(Boolean).some(a=>xd(EA(a,o)))},TA=(e,t=ao())=>{if(t==="darwin"&&Rd(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Yo.test(n))},PA=1e4,Ui=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=EA(t,"System32",e);return xd(n)?n:e},A$=e=>{let t=`/usr/bin/${e}`;return xd(t)?t:e},v$=(e,t)=>{try{let n=IA(e,t,{encoding:"utf-8",timeout:PA,windowsHide:!0,...ao()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:ao()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},S$=e=>new Promise(t=>setTimeout(t,e)),DA=(e,t={})=>{let n=t.runtimePlatform??ao(),r=t.run??v$;if(n==="darwin"){let a=Rd(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||!Yo.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||!Yo.test(a)?!1:r(Ui("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Yo.test(o)?!1:r(A$("pkill"),["-TERM","-o","-x",o])},
|
|
96
|
-
`),B$=e=>{let t=
|
|
93
|
+
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");iA(o?.slice(1).map(Number))},qL=(e,t)=>{let n=KL(sA(ZL(),"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=${vd(a.key)};`;let i=sA(n,`value-${s}`);return jL(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${vd(a.key)}, CAST(readfile(${vd(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
|
|
94
|
+
`);Sd("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Um,stdio:["pipe","ignore","pipe"]})}finally{try{VL(n,{recursive:!0,force:!0})}catch{}}},QL={kind:"sqlite3-cli",readItem:(e,t)=>lA(e,t),checkpointWal:e=>dA(e),mutateRows:qL},e$=()=>{try{let t=YL(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Fm=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},t$=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),n$=e=>({kind:"node-sqlite",readItem:(t,n)=>Fm(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:t$(o.value)}),checkpointWal:t=>Fm(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);iA(o)}),mutateRows:(t,n)=>Fm(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}})}),Ad,ro=()=>{if(Ad!==void 0)return Ad;let e=e$();return Ad=e?n$(e):cA()?QL:null,Ad};import{spawn as r$}from"node:child_process";import{randomUUID as mA}from"node:crypto";import{constants as hA}from"node:fs";import{chmod as o$,copyFile as yA,mkdir as a$,readdir as s$,readFile as i$,rename as c$,rm as Mi,writeFile as l$}from"node:fs/promises";import{join as Hm}from"node:path";var Gm=/^[a-z0-9][a-z0-9-]{0,31}$/,d$=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,gA=/^[a-z0-9][a-z0-9-]{0,31}$/,u$=/^[0-9TZ:.+-]{1,40}$/,Km=()=>Hm(ee(),"pending"),Xa=e=>{if(!Gm.test(e)||d$.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Hm(Km(),`${e}.json`)},wA=()=>Hm(ee(),"cursor-pending.json"),p$=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),f$=(e,t)=>{if(!p$(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Gm.test(n)||typeof e.op!="string"||!gA.test(e.op)||typeof e.requestedAt!="string"||!u$.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}:{}}},Vm=async(e,t)=>{try{return f$(JSON.parse(await i$(e,"utf-8")),t)}catch{return}},bA=async()=>{let e=wA(),t=await Vm(e,"cursor");if(!t)return;let n=!1;try{await Id(),await yA(e,Xa("cursor"),hA.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await Mi(e,{force:!0})}catch{}return t},Fi=async e=>{let t=await Vm(Xa(e),e);return t||(e==="cursor"?bA():void 0)},Mn=async()=>{let e;try{e=await s$(Km())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Gm.test(r))continue;let o=await Fi(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await bA();n&&t.push(n)}return t},Id=async()=>{await Xe();let e=Km();await a$(e,{recursive:!0,mode:448});try{await o$(e,448)}catch{}},Bi=async e=>{await Id();let t=Xa(e.adapter),n=`${t}.${process.pid}.tmp`;await l$(n,`${JSON.stringify(e)}
|
|
95
|
+
`,{mode:384}),await ke(n,t)},kA=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,oo=async(e,t)=>await jm(e,t)==="claimed",jm=async(e,t)=>{let n=Xa(e);if(t){let o=`${n}.${process.pid}.${mA()}.claimed`;try{await c$(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Vm(o,e);if(a&&kA(a,t))return await Mi(o,{force:!0}),"claimed";let s=!1;try{await yA(o,n,hA.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await Mi(o,{force:!0})}return"superseded"}let r=!1;try{await Mi(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await Mi(wA(),{force:!0})}catch{}return r?"claimed":"absent"},$n=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},m$=e=>{let{command:t,args:n}=Qr("__anyray-quit-watch");return{exe:t,args:[...n,e]}},h$=e=>{let{exe:t,args:n}=m$(e),r=r$(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},Wm=h$;var CA=async()=>{let e=[],t;try{t=await Mn()}catch{return e}for(let n of t)if(!$n(n.watcherPid))try{uA&&await uA(n),await y$(n)&&e.push(n.adapter)}catch{}return e},uA;var y$=async e=>{let t=Xa(e.adapter);await Id();let n=await $a(`${t}.lock`,{waitMs:AA,staleMs:vA,busyMessage:`pending operation queue for ${e.adapter} is busy; retry`});try{let r=await Fi(e.adapter);if(!r||!kA(r,e)||$n(r.watcherPid))return!1;let o=Wm(e.adapter);return o?(await Bi({...r,watcherPid:o}),!0):!1}finally{await n()}},pA=(e,t)=>{let n=e.indexOf(t);return n===-1?e.length:n},g$=(e,t,n)=>e!==void 0&&(t.op===n||e.includes(t.op)&&pA(e,t.op)<=pA(e,n)),fA;var AA=2e3,vA=1e4,Ed=async(e,t,n={})=>{if(!gA.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let r=Xa(e);await Id();let o=await $a(`${r}.lock`,{waitMs:AA,staleMs:vA,busyMessage:`pending operation queue for ${e} is busy; retry`});try{return await w$(e,t,n.precedence)}finally{await o()}},w$=async(e,t,n)=>{let r=await Fi(e);if(fA&&await fA({adapter:e,op:t,existing:r}),r&&g$(n,r,t)){if($n(r.watcherPid))return{watcherPid:r.watcherPid,alreadyWatching:!0};let i;try{i=Wm(e)}catch{i=void 0}return i&&await Bi({...r,watcherPid:i}),{watcherPid:i,alreadyWatching:!1}}let o=new Date().toISOString(),a=mA();if(r&&$n(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=Wm(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 b$,spawnSync as IA}from"node:child_process";import{existsSync as xd}from"node:fs";import{homedir as k$,platform as ao}from"node:os";import{join as EA,win32 as SA}from"node:path";var xA=(e,t={})=>{let n=t.env??process.env,r=t.exists??xd,o=(t.home??k$)(),a={localAppData:n.LOCALAPPDATA??SA.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=SA.join(i,s.path);if(r(c))return c}},Yo=/^[A-Za-z0-9 ._-]{1,64}$/,C$=/^[A-Za-z0-9.-]{1,128}$/,Rd=e=>e.darwinBundleId&&C$.test(e.darwinBundleId)?e.darwinBundleId:void 0,RA=(e,t=ao())=>t==="darwin"?Rd(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",OA=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",_A=(e,t=ao(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return xA(e,r)!==void 0;let o=e.linuxProcess;return!o||!Yo.test(o)?!1:n.split(":").filter(Boolean).some(a=>xd(EA(a,o)))},TA=(e,t=ao())=>{if(t==="darwin"&&Rd(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Yo.test(n))},PA=1e4,Ui=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=EA(t,"System32",e);return xd(n)?n:e},A$=e=>{let t=`/usr/bin/${e}`;return xd(t)?t:e},v$=(e,t)=>{try{let n=IA(e,t,{encoding:"utf-8",timeout:PA,windowsHide:!0,...ao()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:ao()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},S$=e=>new Promise(t=>setTimeout(t,e)),DA=(e,t={})=>{let n=t.runtimePlatform??ao(),r=t.run??v$;if(n==="darwin"){let a=Rd(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||!Yo.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||!Yo.test(a)?!1:r(Ui("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Yo.test(o)?!1:r(A$("pkill"),["-TERM","-o","-x",o])},NA=async(e,t=2e4,n={})=>{let r=n.sleep??S$,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},I$=(e,t,n={})=>{let r=ao();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=IA(e,t,{stdio:"ignore",timeout:PA,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=b$(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},LA=(e,t={})=>{let n=t.runtimePlatform??ao(),r=t.launch??I$;if(n==="darwin"){let a=Rd(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Yo.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=xA(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Yo.test(o)?!1:r(o,[])};var L$={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"}]},$$=e=>e==="apply"||e==="native"||e==="revert",KA=()=>We("Cursor"),so=()=>es(KA(),"User","globalStorage","state.vscdb"),Hi=()=>`${so()}.anyray-bak.json`,Qa=()=>`${so()}.anyray-bak`,qe="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",yt="cursorAuth/openAIKey";var VA="/seat/cursor",eh="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.",Wi=es(".cursor","rules","anyray.mdc"),jA="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",M$=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",jA,"",eh,""].join(`
|
|
96
|
+
`),B$=e=>{let t=N$(e);for(;;){if(Ne(es(t,".git")))return t;let n=GA(t);if(n===t)return null;t=n}},F$=e=>e.authMode!=="placeholder",Fn=()=>es(HA(),".cursor","hooks.json"),hn=()=>es(HA(),".cursor","mcp.json"),Jt="anyray",YA="--anyray-owner=cursor-v1",U$="postToolUse",W$="beforeSubmitPrompt",$A="preToolUse",H$="^MCP:",G$="UserPromptSubmit",K$="Shell",V$="^(Read|Grep)$",Dd="--anyray-owner=cursor-hook-v1",Zo=[{event:U$,flag:rt,trailingArgs:["cursor"],matcher:H$},{event:W$,flag:Lo,trailingArgs:[],matcher:G$},{event:$A,flag:xk,trailingArgs:[],matcher:K$},{event:$A,flag:Rk,trailingArgs:[],matcher:V$}];var MA={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},j$=(e,t,n)=>E$(e,t,n),BA=j$,Y$,Z$=()=>{let e=Y$??D$();if(e==="win32"){let t=BA(Ui("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],MA);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=BA("pgrep",["-x",t],MA);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},J$=Z$,Td=()=>J$();var X$=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,qe)??null,openAIKey:e.readItem(n,yt)??null,lastWritten:r};Qm(t,`${JSON.stringify(o,null,2)}
|
|
97
97
|
`,{encoding:"utf-8",flag:"wx",mode:384})},ZA=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Qm(n,`${JSON.stringify(t,null,2)}
|
|
98
|
-
`,{encoding:"utf-8",flag:"wx",mode:384});try{P$(n,e)}catch(r){throw Bn(n,{force:!0}),r}},z$=(e,t)=>{let n=za(e);ZA(e,{...n,lastWritten:t})},ue=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),FA=e=>ue(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),za=e=>{let t=WA(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[qe],o=n.rows[yt];if(!FA(r)||!FA(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}},UA=e=>{let t=Buffer.alloc(16),n=_$(e,"r");try{return T$(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{x$(n)}},q$=(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 JA=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(".")&&Ym(t)===0||t==="0.0.0.0")return!0;if(Ym(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(Ym(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 JA(`${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},XA=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!JA(t.hostname)}catch{return!1}},Q$=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${VA}`}catch{}return{...e,openaiBaseUrl:t}},qa=["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."],Jm=()=>{let e=so();if(!Le(e))return"clear";let t=ro();if(!t)return"unverifiable";let n;try{n=t.readItem(e,qe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ue(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},eM=(e,t)=>{if(!XA(e))return{routed:!1,problem:"gateway-not-public-https"};let n=so();if(!Le(n))return{routed:!1,problem:"state-db-missing"};let r=ro();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,qe),a=r.readItem(n,yt)}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=`${dt(e)}/v1${VA}`;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}},tM=()=>{let e=so();if(!Le(e))return"unverifiable";let t=ro();if(!t)return"unverifiable";let n;try{n=t.readItem(e,qe)}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"},nM=(e,t=[])=>({command:un(e,[...t,Dd])}),th=(e,t,n)=>{if(!ue(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===un(t,[...n,Dd])||r===un(t,n)||r.endsWith(` ${Dd}`)&&r.includes(` ${t} `)},rM=(e,t)=>ue(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),zA=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(th(a,t,n)){r=!0;continue}if(!ue(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!rM(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}},nh=(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},qA=(e,t,n,r,o)=>ue(e.hooks)&&nh(e.hooks,t).some(a=>ue(a)&&a.matcher===o&&th(a,n,r)),oM=(e,t,n,r,o)=>ue(e.hooks)&&nh(e.hooks,t).some(a=>ue(a)&&a.matcher===o&&th(a,n,r)&&Bl(a.command,n,[...r,Dd])),QA=(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}=zA(nh(a,t),n,r);return s.push({...nM(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},aM=(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}=zA(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},sM=async()=>{let e=Fn();if(!ne()){let t=await tv();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 Zo)t=QA(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}}},Pd=()=>{let e=Ue("profile");return{command:e.command,args:[...e.args,YA]}},Xm=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===Pd().command&&e.args.length===Pd().args.length&&e.args.every((t,n)=>t===Pd().args[n]),iM=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")||ut(e.command))return!1;let t=e.args;if(t.at(-2)!==Jr||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!ut(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},Ld=e=>ue(e)&&Array.isArray(e.args)&&e.args.at(-1)===YA||iM(e),cM=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,lM=async()=>{if(!ne())return ev();let e=hn();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[Jt];return r!==void 0&&!Ld(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Jt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Jt]=Pd(),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}}},ev=async()=>{let e=hn();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e);if(!ue(t.mcpServers)||!(Jt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!Ld(t.mcpServers[Jt]))return{changedFiles:[],messages:[`Preserved the foreign ${Jt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Jt];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}}},tv=async()=>{let e=Fn();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e),n=t;for(let r of Zo)n=aM(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}}},dM=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=B$(e);if(!n)return t;let r=es(n,Wi),o=M$();try{if(Le(r)){let a=WA(r,"utf8");if(a===o)return t;if(!a.includes(jA))return{...t,messages:[`Left ${Wi} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${eh}"`]}}return O$(GA(r),{recursive:!0}),Qm(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Wi} 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 ${Wi} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},nv=async()=>{let e=await sM(),t=await lM(),n=await dM();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},zm=async()=>{let e=await tv(),t=await ev();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},rv=async()=>{if(!ne()){let e=await zm();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(Fn());for(let r of Zo)e=QA(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await F(hn());if(t.mcpServers!==void 0&&!ue(t.mcpServers))throw new Error("mcpServers is not an object");let n=ue(t.mcpServers)?t.mcpServers[Jt]:void 0;return n!==void 0&&!Ld(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${hn()} already contains a foreign ${Jt} 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 ${Fn()} and ${hn()}, then re-run Connect.`],complete:!1}}},uM=async()=>{if(!ne())return!1;try{let e=await F(Fn());if(!ue(e.hooks)||!Zo.every(r=>qA(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await F(hn()),n=ue(t.mcpServers)?t.mcpServers[Jt]:void 0;return Xm(n)}catch{return!1}},ov=["openAIBaseUrl","useOpenAIKey"],Gi=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},pM=(e,t,n)=>{let r=Gi(e),o=Gi(t??void 0),a=n===void 0?void 0:Gi(n),s={...r},i=[];for(let c of ov){let l=Object.prototype.hasOwnProperty.call(r,c),d=a!==void 0&&Object.prototype.hasOwnProperty.call(a,c);if(a===void 0||l!==d||l&&!Object.is(r[c],a[c])){i.push(c);continue}Object.prototype.hasOwnProperty.call(o,c)?s[c]=o[c]:delete s[c]}return{mutation:Object.keys(s).length===0?{key:qe}:{key:qe,value:JSON.stringify(s)},conflicts:i}},Zm=(e,t)=>{let n=Gi(e),r=Gi(t??void 0),o={...n};for(let a of ov)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:qe}:{key:qe,value:JSON.stringify(o)}},Od=e=>typeof e=="string"&&e.startsWith("ark_"),_d=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ue(o)&&(n=o)}catch{}let r=Od(t)||n!==null&&(Od(n.useOpenAIKey)||Od(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,Od(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}},ht=(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.",...qa];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.",...qa]},qm=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ne())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 Ed("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]}},fM=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 oo("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 rv();if(!n.complete)return{status:"manual",messages:n.messages};let r=Le(Hi())||Le(Qa());if(r&&Td())return qm("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=Jm();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(Qa())?Qa():Hi()}, 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 ${Fn()}, and register the Anyray retrieval MCP server in ${hn()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Ki.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 nv(),s=[];if(!t.preservePendingOp)try{await oo("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 -- "${eh}" (connect already writes ${Wi} 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."]}},Ki={id:"cursor",title:"Cursor",automatic:!0,skillsDir(){return Yt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=hn(),r=await F(n),o=Pn(r,"mcpServers",e,t&&{url:t.url,headers:{[Vt]:t.clientKey}});return o==="changed"&&await q(n,r,{backup:!1}),{changed:o==="changed"}},quitGated:{isRunning:()=>Td(),quitTarget:N$,needsTarget:e=>e!=="revert",async complete(e,t,n){return $$(e)?e!=="revert"&&t?Ki.apply(t,n):Ki.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=KA(),t=Le(e);return{installed:t,detail:t?so():"Cursor user dir not found"}},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=hn();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await F(e),n=ue(t.mcpServers)?t.mcpServers[Jt]:void 0;return Xm(n)?{registered:!0,command:cM(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=Fn();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(Zo.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Zo.every(c=>qA(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Zo.every(c=>oM(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=hn();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[Jt];r=i===void 0?"missing":Ld(i)?"owned":"foreign",r==="owned"&&(o=Xm(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await On()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await N();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(F$(e))return fM(e,t);let n=Q$(e),r=so(),o=Hi(),a=Qa();if(!Pe(e.clientKey))return{status:"manual",messages:ht(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let s={changedFiles:[],messages:[],complete:!0},i=y=>{let w=y.status==="configured"&&!s.complete;return{...y,status:w?"manual":y.status,changedFiles:[...y.changedFiles??[],...s.changedFiles],messages:[...y.messages,...s.messages,...w?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!XA(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.",...qa]});let c=await rv();if(!c.complete)return{status:"manual",messages:c.messages};let l=ro();if(!l)return i({status:"manual",messages:ht(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:ht(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:ht(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{UA(a)?d="sqlite":(za(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:ht(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=za(o)}catch{return i({status:"manual",messages:ht(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(Td())return i(await qm("apply",t,{status:"manual",messages:ht(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...qa,...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 ${Fn()}, and register the Anyray retrieval MCP server in ${hn()}.`,...qa]};if(d){try{l.checkpointWal(r)}catch(w){return i({status:"manual",messages:ht(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${$i(w)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=_d(l.readItem(a,qe)??null,l.readItem(a,yt)??null);else{let w=za(a);y=_d(w.applicationUser,w.openAIKey)}}catch{return i({status:"manual",messages:ht(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,[Zm(l.readItem(r,qe),y.applicationUser),y.openAIKey===null?{key:yt}:{key:yt,value:y.openAIKey}])}catch{return i({status:"manual",messages:ht(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{Bn(a,{force:!0}),Bn(`${a}-wal`,{force:!0}),Bn(`${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:ht(n,`Couldn't checkpoint Cursor's state DB at ${r}${$i(y)} \u2014 refusing to write; set it by hand:`)})}let m;try{m=l.readItem(r,qe)}catch{return i({status:"manual",messages:ht(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let f=q$(m,n);if(!f)return i({status:"manual",messages:ht(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{z$(o,h)}catch{return i({status:"manual",messages:ht(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{X$(l,o,r,h)}catch{return i({status:"manual",messages:ht(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:qe,value:f.value},{key:yt,value:e.clientKey}])}catch{let y=!0;if(p)try{ZA(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 nv();let g=[];if(!t.preservePendingOp)try{await oo("cursor")}catch{g.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).",...g,...qa,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await N().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Le(Hi())||Le(Qa())||Jm()!=="clear"?!1:uM():eM(e,n).routed},async routingOverrides(){return Jm()!=="active"?[]:tM()!=="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=so(),n=Hi(),r=Qa(),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 ${Fn()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${Fn()} and unregister its owned retrieval MCP server.`]};if((o||a)&&Td()){if(e.fullRevert){let f=await zm(),h=!0;try{await oo("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 qm("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=ro(),i=!1,c=!1,l,d=[];if(a)try{if(UA(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=_d(s.readItem(r,qe)??null,s.readItem(r,yt)??null);s.mutateRows(t,[Zm(s.readItem(t,qe),f.applicationUser),f.openAIKey===null?{key:yt}:{key:yt,value:f.openAIKey}]),c=!0}else i=!0,R$(r,t),Bn(`${t}-wal`,{force:!0}),Bn(`${t}-shm`,{force:!0});else{let f=za(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=_d(f.applicationUser,f.openAIKey);s.mutateRows(t,[Zm(s.readItem(t,qe),h.applicationUser),h.openAIKey===null?{key:yt}:{key:yt,value:h.openAIKey}]),c=!0}}catch(f){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${$i(f)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=za(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=pM(s.readItem(t,qe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...f.conflicts);let h=[f.mutation],g=s.readItem(t,yt);l.lastWritten&&g===l.lastWritten.openAIKey?h.push(l.openAIKey===null?{key:yt}:{key:yt,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,h)}catch(f){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${$i(f)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],p=!0;try{Bn(r,{force:!0}),Bn(`${r}-wal`,{force:!0}),Bn(`${r}-shm`,{force:!0}),Bn(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 oo("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let m=await zm();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 yB,mkdir as gB,readFile as Hv,rm as wB,writeFile as bB}from"node:fs/promises";import{randomUUID as kB}from"node:crypto";import{dirname as CB,join as Gv}from"node:path";import{constants as yM,chmod as gM,copyFile as wM,readFile as av}from"node:fs/promises";import{applyEdits as bM,modify as kM}from"jsonc-parser";var mM=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
|
-
`;)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},hM=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},Dt=e=>JSON.parse(hM(mM(e)));var
|
|
100
|
-
`,r=n.trim()?Dt(n):{};if(!
|
|
98
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{P$(n,e)}catch(r){throw Bn(n,{force:!0}),r}},z$=(e,t)=>{let n=za(e);ZA(e,{...n,lastWritten:t})},ue=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),FA=e=>ue(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),za=e=>{let t=WA(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[qe],o=n.rows[yt];if(!FA(r)||!FA(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}},UA=e=>{let t=Buffer.alloc(16),n=_$(e,"r");try{return T$(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{x$(n)}},q$=(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 JA=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(".")&&Ym(t)===0||t==="0.0.0.0")return!0;if(Ym(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(Ym(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 JA(`${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},XA=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!JA(t.hostname)}catch{return!1}},Q$=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${VA}`}catch{}return{...e,openaiBaseUrl:t}},qa=["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."],Jm=()=>{let e=so();if(!Ne(e))return"clear";let t=ro();if(!t)return"unverifiable";let n;try{n=t.readItem(e,qe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ue(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},eM=(e,t)=>{if(!XA(e))return{routed:!1,problem:"gateway-not-public-https"};let n=so();if(!Ne(n))return{routed:!1,problem:"state-db-missing"};let r=ro();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,qe),a=r.readItem(n,yt)}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=`${dt(e)}/v1${VA}`;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}},tM=()=>{let e=so();if(!Ne(e))return"unverifiable";let t=ro();if(!t)return"unverifiable";let n;try{n=t.readItem(e,qe)}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"},nM=(e,t=[])=>({command:un(e,[...t,Dd])}),th=(e,t,n)=>{if(!ue(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===un(t,[...n,Dd])||r===un(t,n)||r.endsWith(` ${Dd}`)&&r.includes(` ${t} `)},rM=(e,t)=>ue(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),zA=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(th(a,t,n)){r=!0;continue}if(!ue(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!rM(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}},nh=(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},qA=(e,t,n,r,o)=>ue(e.hooks)&&nh(e.hooks,t).some(a=>ue(a)&&a.matcher===o&&th(a,n,r)),oM=(e,t,n,r,o)=>ue(e.hooks)&&nh(e.hooks,t).some(a=>ue(a)&&a.matcher===o&&th(a,n,r)&&Bl(a.command,n,[...r,Dd])),QA=(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}=zA(nh(a,t),n,r);return s.push({...nM(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},aM=(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}=zA(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},sM=async()=>{let e=Fn();if(!ne()){let t=await tv();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 Zo)t=QA(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}}},Pd=()=>{let e=Ue("profile");return{command:e.command,args:[...e.args,YA]}},Xm=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===Pd().command&&e.args.length===Pd().args.length&&e.args.every((t,n)=>t===Pd().args[n]),iM=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")||ut(e.command))return!1;let t=e.args;if(t.at(-2)!==Jr||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!ut(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},Nd=e=>ue(e)&&Array.isArray(e.args)&&e.args.at(-1)===YA||iM(e),cM=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,lM=async()=>{if(!ne())return ev();let e=hn();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[Jt];return r!==void 0&&!Nd(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Jt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Jt]=Pd(),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}}},ev=async()=>{let e=hn();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e);if(!ue(t.mcpServers)||!(Jt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!Nd(t.mcpServers[Jt]))return{changedFiles:[],messages:[`Preserved the foreign ${Jt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Jt];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}}},tv=async()=>{let e=Fn();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e),n=t;for(let r of Zo)n=aM(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}}},dM=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=B$(e);if(!n)return t;let r=es(n,Wi),o=M$();try{if(Ne(r)){let a=WA(r,"utf8");if(a===o)return t;if(!a.includes(jA))return{...t,messages:[`Left ${Wi} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${eh}"`]}}return O$(GA(r),{recursive:!0}),Qm(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Wi} 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 ${Wi} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},nv=async()=>{let e=await sM(),t=await lM(),n=await dM();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},zm=async()=>{let e=await tv(),t=await ev();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},rv=async()=>{if(!ne()){let e=await zm();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(Fn());for(let r of Zo)e=QA(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await F(hn());if(t.mcpServers!==void 0&&!ue(t.mcpServers))throw new Error("mcpServers is not an object");let n=ue(t.mcpServers)?t.mcpServers[Jt]:void 0;return n!==void 0&&!Nd(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${hn()} already contains a foreign ${Jt} 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 ${Fn()} and ${hn()}, then re-run Connect.`],complete:!1}}},uM=async()=>{if(!ne())return!1;try{let e=await F(Fn());if(!ue(e.hooks)||!Zo.every(r=>qA(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await F(hn()),n=ue(t.mcpServers)?t.mcpServers[Jt]:void 0;return Xm(n)}catch{return!1}},ov=["openAIBaseUrl","useOpenAIKey"],Gi=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},pM=(e,t,n)=>{let r=Gi(e),o=Gi(t??void 0),a=n===void 0?void 0:Gi(n),s={...r},i=[];for(let c of ov){let l=Object.prototype.hasOwnProperty.call(r,c),d=a!==void 0&&Object.prototype.hasOwnProperty.call(a,c);if(a===void 0||l!==d||l&&!Object.is(r[c],a[c])){i.push(c);continue}Object.prototype.hasOwnProperty.call(o,c)?s[c]=o[c]:delete s[c]}return{mutation:Object.keys(s).length===0?{key:qe}:{key:qe,value:JSON.stringify(s)},conflicts:i}},Zm=(e,t)=>{let n=Gi(e),r=Gi(t??void 0),o={...n};for(let a of ov)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:qe}:{key:qe,value:JSON.stringify(o)}},Od=e=>typeof e=="string"&&e.startsWith("ark_"),_d=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ue(o)&&(n=o)}catch{}let r=Od(t)||n!==null&&(Od(n.useOpenAIKey)||Od(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,Od(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}},ht=(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.",...qa];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.",...qa]},qm=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ne())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 Ed("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]}},fM=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 oo("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 rv();if(!n.complete)return{status:"manual",messages:n.messages};let r=Ne(Hi())||Ne(Qa());if(r&&Td())return qm("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=Jm();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 ${Ne(Qa())?Qa():Hi()}, 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 ${Fn()}, and register the Anyray retrieval MCP server in ${hn()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Ki.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 nv(),s=[];if(!t.preservePendingOp)try{await oo("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 -- "${eh}" (connect already writes ${Wi} 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."]}},Ki={id:"cursor",title:"Cursor",automatic:!0,skillsDir(){return Yt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=hn(),r=await F(n),o=Pn(r,"mcpServers",e,t&&{url:t.url,headers:{[Vt]:t.clientKey}});return o==="changed"&&await q(n,r,{backup:!1}),{changed:o==="changed"}},quitGated:{isRunning:()=>Td(),quitTarget:L$,needsTarget:e=>e!=="revert",async complete(e,t,n){return $$(e)?e!=="revert"&&t?Ki.apply(t,n):Ki.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=KA(),t=Ne(e);return{installed:t,detail:t?so():"Cursor user dir not found"}},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=hn();if(!await R(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await F(e),n=ue(t.mcpServers)?t.mcpServers[Jt]:void 0;return Xm(n)?{registered:!0,command:cM(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=Fn();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(Zo.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Zo.every(c=>qA(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Zo.every(c=>oM(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=hn();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[Jt];r=i===void 0?"missing":Nd(i)?"owned":"foreign",r==="owned"&&(o=Xm(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await On()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await L();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(F$(e))return fM(e,t);let n=Q$(e),r=so(),o=Hi(),a=Qa();if(!Pe(e.clientKey))return{status:"manual",messages:ht(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let s={changedFiles:[],messages:[],complete:!0},i=y=>{let w=y.status==="configured"&&!s.complete;return{...y,status:w?"manual":y.status,changedFiles:[...y.changedFiles??[],...s.changedFiles],messages:[...y.messages,...s.messages,...w?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!XA(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.",...qa]});let c=await rv();if(!c.complete)return{status:"manual",messages:c.messages};let l=ro();if(!l)return i({status:"manual",messages:ht(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Ne(r))return i({status:"manual",messages:ht(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Ne(a)){if(Ne(o))return i({status:"manual",messages:ht(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{UA(a)?d="sqlite":(za(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:ht(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(Ne(o))try{p=za(o)}catch{return i({status:"manual",messages:ht(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(Td())return i(await qm("apply",t,{status:"manual",messages:ht(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...qa,...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}, ${Ne(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 ${Fn()}, and register the Anyray retrieval MCP server in ${hn()}.`,...qa]};if(d){try{l.checkpointWal(r)}catch(w){return i({status:"manual",messages:ht(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${$i(w)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=_d(l.readItem(a,qe)??null,l.readItem(a,yt)??null);else{let w=za(a);y=_d(w.applicationUser,w.openAIKey)}}catch{return i({status:"manual",messages:ht(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,[Zm(l.readItem(r,qe),y.applicationUser),y.openAIKey===null?{key:yt}:{key:yt,value:y.openAIKey}])}catch{return i({status:"manual",messages:ht(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{Bn(a,{force:!0}),Bn(`${a}-wal`,{force:!0}),Bn(`${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:ht(n,`Couldn't checkpoint Cursor's state DB at ${r}${$i(y)} \u2014 refusing to write; set it by hand:`)})}let m;try{m=l.readItem(r,qe)}catch{return i({status:"manual",messages:ht(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let f=q$(m,n);if(!f)return i({status:"manual",messages:ht(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(Ne(o))try{z$(o,h)}catch{return i({status:"manual",messages:ht(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{X$(l,o,r,h)}catch{return i({status:"manual",messages:ht(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:qe,value:f.value},{key:yt,value:e.clientKey}])}catch{let y=!0;if(p)try{ZA(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 nv();let g=[];if(!t.preservePendingOp)try{await oo("cursor")}catch{g.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).",...g,...qa,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await L().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Ne(Hi())||Ne(Qa())||Jm()!=="clear"?!1:uM():eM(e,n).routed},async routingOverrides(){return Jm()!=="active"?[]:tM()!=="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=so(),n=Hi(),r=Qa(),o=Ne(n),a=Ne(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 ${Fn()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${Fn()} and unregister its owned retrieval MCP server.`]};if((o||a)&&Td()){if(e.fullRevert){let f=await zm(),h=!0;try{await oo("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 qm("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=ro(),i=!1,c=!1,l,d=[];if(a)try{if(UA(r))if(Ne(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=_d(s.readItem(r,qe)??null,s.readItem(r,yt)??null);s.mutateRows(t,[Zm(s.readItem(t,qe),f.applicationUser),f.openAIKey===null?{key:yt}:{key:yt,value:f.openAIKey}]),c=!0}else i=!0,R$(r,t),Bn(`${t}-wal`,{force:!0}),Bn(`${t}-shm`,{force:!0});else{let f=za(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ne(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=_d(f.applicationUser,f.openAIKey);s.mutateRows(t,[Zm(s.readItem(t,qe),h.applicationUser),h.openAIKey===null?{key:yt}:{key:yt,value:h.openAIKey}]),c=!0}}catch(f){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${$i(f)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=za(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(!Ne(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=pM(s.readItem(t,qe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...f.conflicts);let h=[f.mutation],g=s.readItem(t,yt);l.lastWritten&&g===l.lastWritten.openAIKey?h.push(l.openAIKey===null?{key:yt}:{key:yt,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,h)}catch(f){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${$i(f)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],p=!0;try{Bn(r,{force:!0}),Bn(`${r}-wal`,{force:!0}),Bn(`${r}-shm`,{force:!0}),Bn(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 oo("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let m=await zm();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 yB,mkdir as gB,readFile as Hv,rm as wB,writeFile as bB}from"node:fs/promises";import{randomUUID as kB}from"node:crypto";import{dirname as CB,join as Gv}from"node:path";import{constants as yM,chmod as gM,copyFile as wM,readFile as av}from"node:fs/promises";import{applyEdits as bM,modify as kM}from"jsonc-parser";var mM=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
|
+
`;)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},hM=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},Dt=e=>JSON.parse(hM(mM(e)));var Ld=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Me=async e=>{let t=await R(e),n=t?await av(e,"utf8"):`{}
|
|
100
|
+
`,r=n.trim()?Dt(n):{};if(!Ld(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},sv=(e,t,n=[])=>{if(Ld(e)&&Ld(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...sv(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}]},Xt=async(e,t,n,r)=>{let o=sv(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await wM(e,`${e}.anyray-bak`,yM.COPYFILE_EXCL),await gM(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await ve(`${e}.anyray-bak`,`{}
|
|
101
101
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
102
102
|
`)?`\r
|
|
103
103
|
`:`
|
|
104
104
|
`},s=t.raw;for(let i of o)s=bM(s,kM(s,i.path,i.value,{formattingOptions:a}));return await ve(e,s.endsWith(`
|
|
105
105
|
`)?s:`${s}
|
|
106
|
-
`),!0},ts=async e=>{try{let t=Dt(await av(`${e}.anyray-bak`,"utf8"));return
|
|
106
|
+
`),!0},ts=async e=>{try{let t=Dt(await av(`${e}.anyray-bak`,"utf8"));return Ld(t)?t:void 0}catch{return}};import{readFile as oB,writeFile as aB}from"node:fs/promises";import{dirname as sB,join as iB}from"node:path";import{mkdir as cB}from"node:fs/promises";var iv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),CM=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},AM=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},vM=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},rh=(e,t,n)=>{let r;try{r=Dt(e)}catch{return{ok:!1,reason:"unsupported"}}if(!iv(r))return{ok:!1,reason:"unsupported"};if(t in r)return{ok:!1,reason:"key-present"};let o=CM(e);if(o===-1)return{ok:!1,reason:"unsupported"};let a=AM(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=vM(e,o)?`
|
|
108
108
|
${a}${s}
|
|
109
109
|
`:`
|
|
110
|
-
${a}${s},`,d=`${i}${l}${c}`;try{let u=Dt(d);if(!iv(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 _M}from"node:child_process";import{readdirSync as TM,statSync as PM}from"node:fs";import{createHash as Av,randomBytes as DM,randomUUID as vv}from"node:crypto";import{chmod as LM,lstat as uh,mkdir as ph,readdir as Sv,readFile as Wn,rm as Iv,unlink as Fd,writeFile as fh}from"node:fs/promises";import{homedir as as,platform as mh}from"node:os";import{dirname as ch,join as Lt,posix as bv,win32 as NM}from"node:path";import{promisify as $M}from"node:util";var Un="0.1.29";var io="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",$d="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",cv="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfiqg5aldZRjy9SCjdSklpgCSRKo6InP09C+VJqXKL1AaNc0qrT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homedir as Jo,platform as ns}from"node:os";import{join as br,posix as SM,win32 as IM}from"node:path";var Xo=["Code","Code - Insiders","VSCodium"],oh="1.121.0",lv=1,EM=121,pv="1.102.0",dv=1,xM=102,RM={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Md=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},ah=e=>{let t=Md(e);return t?t.major!==lv?t.major>lv:t.minor>=EM:!1},fv=e=>{let t=Md(e);return t?t.major!==dv?t.major>dv:t.minor>=xM:!1},OM=async e=>{if(ns()!=="darwin")return;let t=br("/Applications",`${RM[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await uv(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Bd=(e,t=ns(),n=Jo(),r=process.env)=>{switch(t){case"darwin":return br(n,"Library","Application Support",e);case"win32":return br(r.APPDATA??br(n,"AppData","Roaming"),e);default:return br(n,".config",e)}},sh=(e,t)=>e?t==="win32"?IM.join:SM.join:br,rs=(e,t=!1,n=ns(),r=Jo(),o=process.env)=>t?sh(t,n)(r,Vi[e],"data","User"):br(Bd(e,n,r,o),"User"),mv=async(e,t=!1,n=ns(),r=Jo(),o=process.env)=>{try{let a=sh(t,n)(rs(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await uv(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[]}},hv=async(e,t=ns(),n=Jo(),r=process.env)=>{let a=(await mv(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},yv=async(e,t=!1,n=ns(),r=Jo(),o=process.env)=>{let a=sh(t,n),s=rs(e,t,n,r,o),i=await mv(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},os=async()=>{for(let e of Xo)if(await R(Bd(e)))return e},Vi={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},gv=(e,t=Jo())=>br(t,Vi[e],"extensions"),ih=async(e=Jo())=>{for(let t of Xo)if(await R(br(e,Vi[t])))return t},wv=async e=>{let t=e??await os();if(!t)return{status:"unknown"};let n=await OM(t);return n?{variant:t,version:n,status:ah(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var oe="anyray.anyray-vscode",hh="vscode-handoffs",Ev="vscode-receipts",ji=2,MM=$M(_M),kr={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"]}},BM={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"}},FM=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),xv=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&FM(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Yi=e=>{if(xv(e))try{return new URL(e.trim()).origin}catch{return}},UM=(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)},WM=e=>{try{return TM(e)}catch{return[]}},HM=e=>{try{return PM(e).mtimeMs}catch{return}},GM=(e,t,n,r,o)=>{if(!ur(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=kr[e].commands[0],s=Lt(t,Vi[e]),i=[];for(let{directory:c,suffix:l}of[{directory:Lt(s,"bin"),suffix:["bin","remote-cli"]},{directory:Lt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=Lt(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)},KM=(e,t,n)=>{let{macAppName:r,commands:o}=kr[e],a=o[0],s=[];for(let i of["/Applications",bv.join(t,"Applications")])for(let c of n(i))UM(c,r)&&s.push(bv.join(i,c,"Contents/Resources/app/bin",a));return s},VM=(e,t=mh(),n=as(),r=process.env,o=WM,a=HM)=>{let s=GM(e,n,r,o,a);if(t==="darwin")return[...new Set([...kr[e].commands,...KM(e,n,o),...s])];if(t!=="win32"){let u=kr[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=BM[e],c=NM.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)),kr[e].commands[0],...s])]},Rv={run:async(e,t)=>({stdout:(await MM(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>DM(24).toString("base64url"),home:"",commandCandidates:e=>VM(e)},zo=(e,t)=>Lt(e,".anyray",Ev,`${t}.json`),yh=(e,t)=>Lt(e,".anyray",Ev,`${t}.applied.json`),Ov=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Md(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},lh=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()===oe.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===Un}catch{return}},_v=async(e,t)=>{let n=await Ov(e,t);if(n)return lh(n.command,t)},jM=async(e,t,n)=>{let r=Lt(e,".anyray",hh);for(let o of n){if(!o.endsWith(".json"))continue;let a=Lt(r,o);try{if(!(await uh(a)).isFile()||JSON.parse(await Wn(a,"utf8")).variant!==t)continue;await Fd(a)}catch{}}},YM=async(e,t)=>{let n=Lt(e,".anyray",hh),r;try{r=await Sv(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=Lt(n,o);try{if(!(await uh(a)).isFile()||JSON.parse(await Wn(a,"utf8")).variant!==t)continue;await Fd(a)}catch{}}},ZM=async(e,t)=>{try{let n=JSON.parse(await Wn(zo(e,t),"utf8"));return n.extensionVersion===Un&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==io}catch{return!1}},Tv=250,JM=9e4,XM=JM/Tv,zM=async(e,t,n,r)=>{for(let o=0;o<XM;o++){try{let a=JSON.parse(await Wn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===ji&&a.action===n?"confirmed":a.extensionVersion!==Un||a.extensionDistSha256!==io?"reload-required":a.version===ji&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(Tv)}return"timeout"},qM=200,kv=(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,qM))}return r.join(": ")},QM=async e=>{try{let t=await uh(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},Cv=e=>Av("sha256").update(e).digest("hex"),eB=async(e=as())=>{let t=Buffer.from(cv,"base64");if(t.length<4||t[0]!==80||t[1]!==75||Cv(t)!==$d)throw new Error("bundled VS Code extension failed integrity validation");let n=Lt(e,".anyray","vscode-extension"),r=Lt(n,`anyray-vscode-${Un}-${$d.slice(0,12)}.vsix`);try{if(Cv(await Wn(r))===$d)return r}catch{}await ph(n,{recursive:!0,mode:448});let o=`${r}.${vv()}.tmp`;try{await fh(o,t,{mode:384}),await ke(o,r),mh()!=="win32"&&await LM(r,384)}finally{await Iv(o,{force:!0})}return r},dh=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=>dh(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${dh(t[n])}`).join(",")}}`},Pv=(e,t,n)=>Av("sha256").update(dh({gatewayUrl:Yi(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:Un,extensionDistSha256:io,profiles:[...n].sort()})).digest("hex"),tB=async(e,t,n,r,o,a)=>{let s=JSON.parse(await Wn(yh(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==Pv(t,n,r))return!1;let i=JSON.parse(await Wn(zo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===Un&&i.extensionDistSha256===io&&i.gatewayUrl===Yi(t.origin)?await _v(e,a)===!0:!1},nB=async(e,t,n,r)=>{let o=yh(e,t),a=`${o}.${vv()}.tmp`;try{await ph(ch(o),{recursive:!0,mode:448}),await fh(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
111
|
-
`,{mode:384}),await ke(a,o)}catch{}finally{await Iv(a,{force:!0})}},rB=async(e,t)=>{await Fd(yh(e,t)).catch(()=>{})},Dv=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...Rv,...r,home:r.home??as()},s=kr[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!xv(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,A,C)=>typeof b.id=="string"&&b.id.length>0&&b.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.id)&&typeof b.name=="string"&&b.name.length>0&&b.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.name)&&C.findIndex(x=>x.id===b.id)===A);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await Ov(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!ah(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>hv(b,mh(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await tB(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:zo(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let p=a.extensionPath;if(n==="configure"){try{p??=await eB(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await QM(p))return{ok:!1,reason:"extension-missing"}}let m=a.nonce(),f=
|
|
112
|
-
`,{mode:384}),await jM(a.home,s.slug,g).catch(()=>{});let y={installed:[],failed:[]},w=!1;try{if(n==="configure"){let A=await ZM(a.home,s.slug);if(A||await lh(l,a)!==!0)try{await a.run(l,["--install-extension",p,"--force"])}catch(C){return w=!0,{ok:!1,reason:"install-failed",detail:kv(C,m)}}for(let C of u)try{(A||await lh(l,a,C)!==!0)&&await a.run(l,["--profile",C,"--install-extension",p,"--force"]),y.installed.push(C)}catch{y.failed.push(C)}}try{await a.run(l,["--open-url",`${s.scheme}://${oe}/configure?nonce=${encodeURIComponent(m)}`])}catch(A){return{ok:!1,reason:"handoff-undeliverable",detail:kv(A,m)}}let b=await zM(h,m,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(w=!0,n==="configure")y.failed.length===0&&await nB(a.home,s.slug,Pv(t,o,u),m);else{await rB(a.home,s.slug),await YM(a.home,s.slug).catch(()=>{});for(let A of[void 0,...u])try{await a.run(l,[...A?["--profile",A]:[],"--uninstall-extension",oe])}catch{}}return{ok:!0,receipt:h,profiles:y}}catch{return{ok:!1,reason:"failed"}}finally{w&&await Fd(f).catch(()=>{})}},Ud=async(e,t=as())=>{try{let n=JSON.parse(await Wn(zo(t,kr[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==Un||n.extensionDistSha256!==io)}catch{return!1}},Wd=async(e,t=as())=>{try{let n=JSON.parse(await Wn(zo(t,kr[e].slug),"utf8"));return n.version!==ji||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},
|
|
113
|
-
`,{flag:"wx",mode:384}),await ke(n,e),await yB(e,384)}finally{await wB(n,{force:!0}).catch(()=>{})}},wh=e=>{if(!Nt(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!==co||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(!Nt(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!==jv(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!Nt(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}})},bh=e=>{let t=e.filter(n=>!wh(n));return{next:t,removed:t.length!==e.length}},SB=async(e,t)=>{let n=Xi(e),r=await Gd(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 "${co}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=bh(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${co}" Custom Endpoint from ${n}.`]};try{return await Yv(n,o),await fe(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${co}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${co}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},IB=async e=>{try{let t=Dt(await Hv(e,"utf-8"));if(Nt(t))return Vv(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${zi}.${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 ${zi}.${Kd} value manually if present.`]}},Zv=async(e,t)=>{let n=AB(e),r;try{r=await F(n)}catch{return IB(n)}let{next:o,removed:a}=Vv(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 fe(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.`]}}},EB=async(e,t)=>{let n=await SB(e,t),r=await Zv(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},Jv=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,Kv]}},Xv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},zv=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),xB=e=>Array.isArray(e.args)&&e.args.at(-1)===Kv,qv=(e,t)=>{if(!t.hookBinaryIsDurable()||!Nt(e)||!Xv(e,["type","command","args"]))return!1;let n=Jv(t);return e.type==="stdio"&&e.command===n.command&&zv(e.args,n.args)},RB=(e,t)=>{if(!Nt(e)||!Xv(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&&zv(e.args,n.args))return!0;if(ut(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===Jr&&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!ut(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)=>qv(e,t)?"exact":Nt(e)&&xB(e)||RB(e,t)?"stale-owned":"foreign",Fv=e=>`MCP name conflict in ${e}: servers.${Kn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,OB=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&&!Nt(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=Nt(h.servers)?{...h.servers}:{},A=Jv(o),C=b[Kn],x=C===void 0?void 0:Vd(C,o);if(x==="exact"){d+=1;continue}if(x==="foreign"){u=!0,l.push(Fv(m));continue}if(t){d+=1;continue}b[Kn]=A,p.push({path:m,document:f,next:{...h,servers:b},backup:x!=="stale-owned",clearBackupAfter:!1});continue}if(!Nt(h.servers)||!(Kn in h.servers))continue;if(Vd(h.servers[Kn],o)==="foreign"){u=!0,l.push(Fv(m));continue}if(t)continue;let y={...h.servers};delete y[Kn];let w={...h};Object.keys(y).length===0?delete w.servers:w.servers=y,p.push({path:m,document:f,next:w,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 Xt(m.path,m.document,m.next,m.backup),m.clearBackupAfter&&await fe(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 (${pv}+).`),{changedFiles:c,messages:l,manual:u}},_B=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(!Nt(d.servers)||!(Kn in d.servers)||Vd(d.servers[Kn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[Kn];let p={...d};Object.keys(u).length===0?delete p.servers:p.servers=u,await Xt(c,l,p,!1),await fe(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}},Qv=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.`]:[]],eS=()=>`${oe} 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.)`,Uv=e=>[`${oe} 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."],tS=(e,t,n,r)=>({runMcp:o=>OB(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):EB(e,o)}),nS=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${oe} 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 ${oe} 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 ${oe} 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 ${oe} 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 ${oh} 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 ${oe} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${oe} 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.`:`${oe} 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 ${oe} ${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 ${oe} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},TB=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${oe} 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 ${oe} 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 ${oe} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${oe} 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 ${oe} 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 ${oe} 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 ${oe} 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 ${oe} 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 ${oe} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},PB=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=tS(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 ${oe} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...Uv(t),a?gh({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 ${oe}; 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:[nS(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),p=await i(!1),m=a?void 0:await $v(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?[Zi(e)]:[]],messages:[...d.alreadyCurrent?[eS()]:[],...Uv(t),gh(m??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:Qv(d.profiles),...p.messages,...u.messages]}},Wv=e=>[`${oe} 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: ${Qi().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."],DB=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=tS(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 ${oe} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...Wv(t),...f.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${oe}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Qi().map(m=>({id:m,name:jv(m)}))});if(!d.ok)return{status:"manual",messages:[nS(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?[eS()]:[],...Wv(t),...d.alreadyCurrent?[]:Qv(d.profiles),...p.messages,...u.messages]}},LB=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=Nt(i.servers)?i.servers[Kn]:void 0;if(!qv(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 NB=async(e={installedVariant:os,remoteServerVariant:ih,isRemoteDevContext:ur})=>{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}},$B={installedVariant:os,remoteServerVariant:ih,detectVscodeLmProviderEligibility:wv,configureVscodeExtension:Dv,vscodeExtensionPointsAt:Lv,vscodeExtensionAwaitingReload:Ud,vscodeExtensionReceiptMode:Wd,hookBinaryIsDurable:ne,hookBinaryPath:De,mcpServerCommand:Ue,vscodeUserMcpConfigPaths:yv,isRemoteDevContext:ur},MB=(e={})=>{let t={...$B,...e},n=()=>NB(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,skillsDir(){return Yt()},quitGated:{isRunning:Ji,quitTarget:Hd},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${rs(r,!0)}`:Xi(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 ${oh} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||fv(i.version);return se(r,"copilot")?PB(a,r,o,t.configureVscodeExtension,c,s,t):DB(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?LB(r,o,t):{registered:!1,command:null,reason:"no-config"}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Yi(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await Gd(Xi(o));if(s.kind==="array"){let c=s.entries.find(wh)?.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 Gd(Xi(r));if(o.kind==="array"&&o.entries.some(wh))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 _B(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await Zv(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${oe} to clear its global configuration and SecretStorage key`);else{let w=await t.configureVscodeExtension(o,void 0,"reset");w.ok?(c=!0,d=w.receipt,u.push(`Cleared ${oe} gateway configuration and secret.`)):(l=!0,u.push(TB(w.reason,o,a,w.detail)))}let p=Xi(o),m=await Gd(p),f=m.kind==="missing"||m.kind==="array"&&!bh(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 "${co}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:g}=bh(m.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${co} Custom Endpoint from ${p}`]};await Yv(p,g);let y=[...u,`Removed the ${co} Custom Endpoint from ${p}.`];return await fe(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,p],messages:y}}}},rS=MB();import{accessSync as fF,constants as gS,statSync as mF}from"node:fs";import{readFile as wS,rm as tc}from"node:fs/promises";import{homedir as _h,platform as IS}from"node:os";import{delimiter as hF,join as Th,resolve as yF}from"node:path";import{execFile as HB}from"node:child_process";import{readFile as GB}from"node:fs/promises";import{homedir as Ah,platform as KB}from"node:os";import{join as ec}from"node:path";import{join as BB}from"node:path";var kh="Iv1.b507a08c87ecfe98",FB="https://github.com/login/device/code",UB="https://github.com/login/oauth/access_token",WB="read:user",oS=1e4,ss=()=>BB(ee(),"copilot-seat-login.json"),aS={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},Ch=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sS=async(e={})=>{let t={...aS,...e};try{let n=await t.fetch(FB,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:kh,scope:WB}),signal:AbortSignal.timeout(oS)});if(!n.ok)return;let r=await n.json();if(!Ch(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}},iS=async(e,t={})=>{let n={...aS,...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(UB,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:kh,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(oS)})).json();if(!Ch(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"}},cS=async(e,t)=>{let n=ss();return await ve(n,`${JSON.stringify({token:e,clientId:kh,mintedAtIso:t},null,2)}
|
|
110
|
+
${a}${s},`,d=`${i}${l}${c}`;try{let u=Dt(d);if(!iv(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 _M}from"node:child_process";import{readdirSync as TM,statSync as PM}from"node:fs";import{createHash as Av,randomBytes as DM,randomUUID as vv}from"node:crypto";import{chmod as NM,lstat as uh,mkdir as ph,readdir as Sv,readFile as Wn,rm as Iv,unlink as Fd,writeFile as fh}from"node:fs/promises";import{homedir as as,platform as mh}from"node:os";import{dirname as ch,join as Nt,posix as bv,win32 as LM}from"node:path";import{promisify as $M}from"node:util";var Un="0.1.30";var io="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",$d="7d721304ee023fc9314e5f426e42fd9f871f146a2847999860fbdd7bc682ba8c",cv="UEsDBBQAAAgIAF1LJ128vVu+NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WW28aORR+Tn6F5ZX2qdiQfVllBypEkhYtVFRk81jpYB8Gbzy25eMh0F9fzQy30PQCqfo243PO9/lc/NnZ21Vh2RIjGe+6vCPanKFTXhuXd3mZ5q2/+dve5UU2AfUIOY7BmTlSYg/bkCvRroJWhXXU5YuUwrWUpBZYAInCqOjJz5NQvpAal2h9wCiXtGo1PvKq3elswq/1GQAtjWRy1+D0Li8usjEm0JCg+rnIhhpdMmnNRuDyEnLscnSt/6acDXWXg1tHWLeWpLxGvs+qLTrirzZnk3JmDS0wbl05kw3ujaFgYf0BCuz1axOb+8gepmzgNWby0N4EIKloQjLeVeleUwCFXR4iEsYl8l5fa4arYI0yiW0gc0j4BGtWeI2WmI8bQ+spQgio2cAHY31iVM728BvvtIi+zBfbPf0JwdM/xPx8bpQBy+ymIq3an4Xol0ZjZP3JUGTyYL9NAveQU+95DGWyXq3tA0iY+2iQev3hmzGohXHIRgjRGZdn8sBe+78DazGu72yFUBdaZfLZYuVWu05i1fW0Dd0trOsmjndD8mCoBDtNpTZeVDmLW5cbV3UWbIld/qkjOlf1lMuTkVYJXTUdNxjQaXTKIO2AXwNYna1fAvSvcXoH9OTjYz1jb0pzBujIK7DmM+rtuXldrg5mFnU/mCrEE9gX4E5OG1WZkAbN0W3AUizxDMApxqVRSGJk3COJqS+j2oNWokTXUuYmLcpZLUWNGrz/KAvvfMTgRW7SaYU54nyHiRLEhPo385r0vpz9Xs5pGYKP6SRSaYjKagpfwVuL0Umsf0QEXRyN1Bn8TZX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29uUEsBAj8DFAAICAgASUsnXTBWrcBOEQAAKBMAABIAAAAAAAAAAAAAAKSBUQcAAGV4dGVuc2lvbi9pY29uLnBuZ1BLAQI/AxQAAAgIAF1LJ10Lt+OvSwIAAH0EAAATAAAAAAAAAAAAAAC0gd8YAABleHRlbnNpb24vcmVhZG1lLm1kUEsBAj8DFAAICAgASUsnXbKGeo15AgAAJwQAABUAAAAAAAAAAAAAAKSBWxsAAGV4dGVuc2lvbi9MSUNFTlNFLnR4dFBLAQI/AxQACAgIAF1LJ12nMhz0AzkAACOpAAAbAAAAAAAAAAAAAACkgRceAABleHRlbnNpb24vZGlzdC9leHRlbnNpb24uanNQSwUGAAAAAAcABwDWAQAAY1cAAAAA";import{readFile as uv}from"node:fs/promises";import{homedir as Jo,platform as ns}from"node:os";import{join as br,posix as SM,win32 as IM}from"node:path";var Xo=["Code","Code - Insiders","VSCodium"],oh="1.121.0",lv=1,EM=121,pv="1.102.0",dv=1,xM=102,RM={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Md=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},ah=e=>{let t=Md(e);return t?t.major!==lv?t.major>lv:t.minor>=EM:!1},fv=e=>{let t=Md(e);return t?t.major!==dv?t.major>dv:t.minor>=xM:!1},OM=async e=>{if(ns()!=="darwin")return;let t=br("/Applications",`${RM[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await uv(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Bd=(e,t=ns(),n=Jo(),r=process.env)=>{switch(t){case"darwin":return br(n,"Library","Application Support",e);case"win32":return br(r.APPDATA??br(n,"AppData","Roaming"),e);default:return br(n,".config",e)}},sh=(e,t)=>e?t==="win32"?IM.join:SM.join:br,rs=(e,t=!1,n=ns(),r=Jo(),o=process.env)=>t?sh(t,n)(r,Vi[e],"data","User"):br(Bd(e,n,r,o),"User"),mv=async(e,t=!1,n=ns(),r=Jo(),o=process.env)=>{try{let a=sh(t,n)(rs(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await uv(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[]}},hv=async(e,t=ns(),n=Jo(),r=process.env)=>{let a=(await mv(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},yv=async(e,t=!1,n=ns(),r=Jo(),o=process.env)=>{let a=sh(t,n),s=rs(e,t,n,r,o),i=await mv(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},os=async()=>{for(let e of Xo)if(await R(Bd(e)))return e},Vi={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},gv=(e,t=Jo())=>br(t,Vi[e],"extensions"),ih=async(e=Jo())=>{for(let t of Xo)if(await R(br(e,Vi[t])))return t},wv=async e=>{let t=e??await os();if(!t)return{status:"unknown"};let n=await OM(t);return n?{variant:t,version:n,status:ah(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var oe="anyray.anyray-vscode",hh="vscode-handoffs",Ev="vscode-receipts",ji=2,MM=$M(_M),kr={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"]}},BM={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"}},FM=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),xv=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&FM(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Yi=e=>{if(xv(e))try{return new URL(e.trim()).origin}catch{return}},UM=(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)},WM=e=>{try{return TM(e)}catch{return[]}},HM=e=>{try{return PM(e).mtimeMs}catch{return}},GM=(e,t,n,r,o)=>{if(!ur(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=kr[e].commands[0],s=Nt(t,Vi[e]),i=[];for(let{directory:c,suffix:l}of[{directory:Nt(s,"bin"),suffix:["bin","remote-cli"]},{directory:Nt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=Nt(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)},KM=(e,t,n)=>{let{macAppName:r,commands:o}=kr[e],a=o[0],s=[];for(let i of["/Applications",bv.join(t,"Applications")])for(let c of n(i))UM(c,r)&&s.push(bv.join(i,c,"Contents/Resources/app/bin",a));return s},VM=(e,t=mh(),n=as(),r=process.env,o=WM,a=HM)=>{let s=GM(e,n,r,o,a);if(t==="darwin")return[...new Set([...kr[e].commands,...KM(e,n,o),...s])];if(t!=="win32"){let u=kr[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=BM[e],c=LM.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)),kr[e].commands[0],...s])]},Rv={run:async(e,t)=>({stdout:(await MM(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>DM(24).toString("base64url"),home:"",commandCandidates:e=>VM(e)},zo=(e,t)=>Nt(e,".anyray",Ev,`${t}.json`),yh=(e,t)=>Nt(e,".anyray",Ev,`${t}.applied.json`),Ov=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Md(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},lh=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()===oe.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===Un}catch{return}},_v=async(e,t)=>{let n=await Ov(e,t);if(n)return lh(n.command,t)},jM=async(e,t,n)=>{let r=Nt(e,".anyray",hh);for(let o of n){if(!o.endsWith(".json"))continue;let a=Nt(r,o);try{if(!(await uh(a)).isFile()||JSON.parse(await Wn(a,"utf8")).variant!==t)continue;await Fd(a)}catch{}}},YM=async(e,t)=>{let n=Nt(e,".anyray",hh),r;try{r=await Sv(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=Nt(n,o);try{if(!(await uh(a)).isFile()||JSON.parse(await Wn(a,"utf8")).variant!==t)continue;await Fd(a)}catch{}}},ZM=async(e,t)=>{try{let n=JSON.parse(await Wn(zo(e,t),"utf8"));return n.extensionVersion===Un&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==io}catch{return!1}},Tv=250,JM=9e4,XM=JM/Tv,zM=async(e,t,n,r)=>{for(let o=0;o<XM;o++){try{let a=JSON.parse(await Wn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===ji&&a.action===n?"confirmed":a.extensionVersion!==Un||a.extensionDistSha256!==io?"reload-required":a.version===ji&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(Tv)}return"timeout"},qM=200,kv=(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,qM))}return r.join(": ")},QM=async e=>{try{let t=await uh(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},Cv=e=>Av("sha256").update(e).digest("hex"),eB=async(e=as())=>{let t=Buffer.from(cv,"base64");if(t.length<4||t[0]!==80||t[1]!==75||Cv(t)!==$d)throw new Error("bundled VS Code extension failed integrity validation");let n=Nt(e,".anyray","vscode-extension"),r=Nt(n,`anyray-vscode-${Un}-${$d.slice(0,12)}.vsix`);try{if(Cv(await Wn(r))===$d)return r}catch{}await ph(n,{recursive:!0,mode:448});let o=`${r}.${vv()}.tmp`;try{await fh(o,t,{mode:384}),await ke(o,r),mh()!=="win32"&&await NM(r,384)}finally{await Iv(o,{force:!0})}return r},dh=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=>dh(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${dh(t[n])}`).join(",")}}`},Pv=(e,t,n)=>Av("sha256").update(dh({gatewayUrl:Yi(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:Un,extensionDistSha256:io,profiles:[...n].sort()})).digest("hex"),tB=async(e,t,n,r,o,a)=>{let s=JSON.parse(await Wn(yh(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==Pv(t,n,r))return!1;let i=JSON.parse(await Wn(zo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===Un&&i.extensionDistSha256===io&&i.gatewayUrl===Yi(t.origin)?await _v(e,a)===!0:!1},nB=async(e,t,n,r)=>{let o=yh(e,t),a=`${o}.${vv()}.tmp`;try{await ph(ch(o),{recursive:!0,mode:448}),await fh(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
111
|
+
`,{mode:384}),await ke(a,o)}catch{}finally{await Iv(a,{force:!0})}},rB=async(e,t)=>{await Fd(yh(e,t)).catch(()=>{})},Dv=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...Rv,...r,home:r.home??as()},s=kr[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!xv(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,A,C)=>typeof b.id=="string"&&b.id.length>0&&b.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.id)&&typeof b.name=="string"&&b.name.length>0&&b.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.name)&&C.findIndex(x=>x.id===b.id)===A);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await Ov(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!ah(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>hv(b,mh(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await tB(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:zo(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let p=a.extensionPath;if(n==="configure"){try{p??=await eB(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await QM(p))return{ok:!1,reason:"extension-missing"}}let m=a.nonce(),f=Nt(a.home,".anyray",hh,`${m}.json`),h=zo(a.home,s.slug);await ph(ch(f),{recursive:!0,mode:448});let g=await Sv(ch(f)).catch(()=>[]);await fh(f,`${JSON.stringify({version:ji,action:n,nonce:m,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:Un,expectedExtensionDistSha256:io})}
|
|
112
|
+
`,{mode:384}),await jM(a.home,s.slug,g).catch(()=>{});let y={installed:[],failed:[]},w=!1;try{if(n==="configure"){let A=await ZM(a.home,s.slug);if(A||await lh(l,a)!==!0)try{await a.run(l,["--install-extension",p,"--force"])}catch(C){return w=!0,{ok:!1,reason:"install-failed",detail:kv(C,m)}}for(let C of u)try{(A||await lh(l,a,C)!==!0)&&await a.run(l,["--profile",C,"--install-extension",p,"--force"]),y.installed.push(C)}catch{y.failed.push(C)}}try{await a.run(l,["--open-url",`${s.scheme}://${oe}/configure?nonce=${encodeURIComponent(m)}`])}catch(A){return{ok:!1,reason:"handoff-undeliverable",detail:kv(A,m)}}let b=await zM(h,m,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(w=!0,n==="configure")y.failed.length===0&&await nB(a.home,s.slug,Pv(t,o,u),m);else{await rB(a.home,s.slug),await YM(a.home,s.slug).catch(()=>{});for(let A of[void 0,...u])try{await a.run(l,[...A?["--profile",A]:[],"--uninstall-extension",oe])}catch{}}return{ok:!0,receipt:h,profiles:y}}catch{return{ok:!1,reason:"failed"}}finally{w&&await Fd(f).catch(()=>{})}},Ud=async(e,t=as())=>{try{let n=JSON.parse(await Wn(zo(t,kr[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==Un||n.extensionDistSha256!==io)}catch{return!1}},Wd=async(e,t=as())=>{try{let n=JSON.parse(await Wn(zo(t,kr[e].slug),"utf8"));return n.version!==ji||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},Nv=async(e,t,n=as(),r={})=>{try{let o=Yi(t);if(!o)return!1;let a=JSON.parse(await Wn(zo(n,kr[e].slug),"utf8"));if(!(a.version===ji&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===Un&&a.extensionDistSha256===io))return!1;let i={...Rv,...r,home:n};return await _v(e,i)===!0}catch{return!1}};var Hn="extensions.supportAgentsWindow",Gn="chat.agentHost.byokModels.enabled",Zi=e=>iB(We(e),"User","settings.json"),Lv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lB=e=>Lv(e)&&e[oe]===!0,$v=async(e,t={})=>{let n=Zi(e),r=t.read??(m=>oB(m,"utf-8")),o=t.exists??R,a=t.write??(async(m,f)=>{await cB(sB(m),{recursive:!0}),await aB(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=Dt(s)}catch{return{status:"manual",reason:`${n} is not valid JSON/JSONC, so it was left untouched`}}if(!Lv(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(Hn in i)){let m=rh(c,Hn,{[oe]:!0});if(!m.ok)return{status:"manual",reason:`could not add ${Hn} to ${n} without rewriting it`};c=m.text,l=!0}if(!(Gn in i)){let m=rh(c,Gn,!0);if(!m.ok)return{status:"manual",reason:`could not add ${Gn} to ${n} without rewriting it`};c=m.text,l=!0}l&&await a(n,c);let d=l?Dt(c):i,u=lB(d[Hn]),p=d[Gn]===!0;return!u||!p?{status:"manual",reason:`${n} already sets ${u?Gn:Hn} to something else; left as it is`}:{status:"enabled",changed:l}},gh=(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 "${Hn}": {"${oe}": true} and "${Gn}": 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 dB}from"node:child_process";import{platform as uB}from"node:os";var Mv={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},pB=(e,t,n)=>dB(e,t,n),Bv=pB,fB,mB=()=>{let e=fB??uB();if(e==="win32"){let n=Bv(Ui("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],Mv);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=Bv("pgrep",[n,r],Mv);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},hB=mB,Ji=()=>hB();var Hd={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 co="Anyray",Kn="anyray",Kv="--anyray-owner=vscode-profile-v1",Xi=e=>Gv(We(e),"User","chatLanguageModels.json"),AB=e=>Gv(We(e),"User","settings.json"),zi="github.copilot.advanced",Kd="debug.overrideCapiUrl",Lt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vB=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}},Vv=e=>{let t=e[zi];if(!Lt(t)||!vB(t[Kd]))return{next:e,removed:!1};let n={...t};delete n[Kd];let r={...e};return Object.keys(n).length>0?r[zi]=n:delete r[zi],{next:r,removed:!0}},qi="anyray-default",Qi=()=>{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:[qi]},jv=e=>e===qi?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),Gd=async e=>{if(!await R(e))return{kind:"missing"};try{let t=await Hv(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"}}},Yv=async(e,t)=>{await gB(CB(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${kB()}`;try{await bB(n,`${JSON.stringify(t,null,2)}
|
|
113
|
+
`,{flag:"wx",mode:384}),await ke(n,e),await yB(e,384)}finally{await wB(n,{force:!0}).catch(()=>{})}},wh=e=>{if(!Lt(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!==co||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(!Lt(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!==jv(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!Lt(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}})},bh=e=>{let t=e.filter(n=>!wh(n));return{next:t,removed:t.length!==e.length}},SB=async(e,t)=>{let n=Xi(e),r=await Gd(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 "${co}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=bh(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${co}" Custom Endpoint from ${n}.`]};try{return await Yv(n,o),await fe(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${co}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${co}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},IB=async e=>{try{let t=Dt(await Hv(e,"utf-8"));if(Lt(t))return Vv(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${zi}.${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 ${zi}.${Kd} value manually if present.`]}},Zv=async(e,t)=>{let n=AB(e),r;try{r=await F(n)}catch{return IB(n)}let{next:o,removed:a}=Vv(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 fe(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.`]}}},EB=async(e,t)=>{let n=await SB(e,t),r=await Zv(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},Jv=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,Kv]}},Xv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},zv=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),xB=e=>Array.isArray(e.args)&&e.args.at(-1)===Kv,qv=(e,t)=>{if(!t.hookBinaryIsDurable()||!Lt(e)||!Xv(e,["type","command","args"]))return!1;let n=Jv(t);return e.type==="stdio"&&e.command===n.command&&zv(e.args,n.args)},RB=(e,t)=>{if(!Lt(e)||!Xv(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&&zv(e.args,n.args))return!0;if(ut(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===Jr&&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!ut(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)=>qv(e,t)?"exact":Lt(e)&&xB(e)||RB(e,t)?"stale-owned":"foreign",Fv=e=>`MCP name conflict in ${e}: servers.${Kn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,OB=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&&!Lt(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=Lt(h.servers)?{...h.servers}:{},A=Jv(o),C=b[Kn],x=C===void 0?void 0:Vd(C,o);if(x==="exact"){d+=1;continue}if(x==="foreign"){u=!0,l.push(Fv(m));continue}if(t){d+=1;continue}b[Kn]=A,p.push({path:m,document:f,next:{...h,servers:b},backup:x!=="stale-owned",clearBackupAfter:!1});continue}if(!Lt(h.servers)||!(Kn in h.servers))continue;if(Vd(h.servers[Kn],o)==="foreign"){u=!0,l.push(Fv(m));continue}if(t)continue;let y={...h.servers};delete y[Kn];let w={...h};Object.keys(y).length===0?delete w.servers:w.servers=y,p.push({path:m,document:f,next:w,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 Xt(m.path,m.document,m.next,m.backup),m.clearBackupAfter&&await fe(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 (${pv}+).`),{changedFiles:c,messages:l,manual:u}},_B=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(!Lt(d.servers)||!(Kn in d.servers)||Vd(d.servers[Kn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[Kn];let p={...d};Object.keys(u).length===0?delete p.servers:p.servers=u,await Xt(c,l,p,!1),await fe(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}},Qv=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.`]:[]],eS=()=>`${oe} 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.)`,Uv=e=>[`${oe} 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."],tS=(e,t,n,r)=>({runMcp:o=>OB(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):EB(e,o)}),nS=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${oe} 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 ${oe} 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 ${oe} 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 ${oe} 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 ${oh} 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 ${oe} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${oe} 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.`:`${oe} 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 ${oe} ${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 ${oe} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},TB=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${oe} 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 ${oe} 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 ${oe} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${oe} 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 ${oe} 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 ${oe} 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 ${oe} 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 ${oe} 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 ${oe} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},PB=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=tS(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 ${oe} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...Uv(t),a?gh({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 ${oe}; 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:[nS(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),p=await i(!1),m=a?void 0:await $v(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?[Zi(e)]:[]],messages:[...d.alreadyCurrent?[eS()]:[],...Uv(t),gh(m??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:Qv(d.profiles),...p.messages,...u.messages]}},Wv=e=>[`${oe} 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: ${Qi().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."],DB=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=tS(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 ${oe} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...Wv(t),...f.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${oe}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Qi().map(m=>({id:m,name:jv(m)}))});if(!d.ok)return{status:"manual",messages:[nS(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?[eS()]:[],...Wv(t),...d.alreadyCurrent?[]:Qv(d.profiles),...p.messages,...u.messages]}},NB=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=Lt(i.servers)?i.servers[Kn]:void 0;if(!qv(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 LB=async(e={installedVariant:os,remoteServerVariant:ih,isRemoteDevContext:ur})=>{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}},$B={installedVariant:os,remoteServerVariant:ih,detectVscodeLmProviderEligibility:wv,configureVscodeExtension:Dv,vscodeExtensionPointsAt:Nv,vscodeExtensionAwaitingReload:Ud,vscodeExtensionReceiptMode:Wd,hookBinaryIsDurable:ne,hookBinaryPath:De,mcpServerCommand:Ue,vscodeUserMcpConfigPaths:yv,isRemoteDevContext:ur},MB=(e={})=>{let t={...$B,...e},n=()=>LB(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,skillsDir(){return Yt()},quitGated:{isRunning:Ji,quitTarget:Hd},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${rs(r,!0)}`:Xi(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 ${oh} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||fv(i.version);return se(r,"copilot")?PB(a,r,o,t.configureVscodeExtension,c,s,t):DB(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?NB(r,o,t):{registered:!1,command:null,reason:"no-config"}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Yi(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await Gd(Xi(o));if(s.kind==="array"){let c=s.entries.find(wh)?.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 Gd(Xi(r));if(o.kind==="array"&&o.entries.some(wh))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 _B(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await Zv(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${oe} to clear its global configuration and SecretStorage key`);else{let w=await t.configureVscodeExtension(o,void 0,"reset");w.ok?(c=!0,d=w.receipt,u.push(`Cleared ${oe} gateway configuration and secret.`)):(l=!0,u.push(TB(w.reason,o,a,w.detail)))}let p=Xi(o),m=await Gd(p),f=m.kind==="missing"||m.kind==="array"&&!bh(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 "${co}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:g}=bh(m.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${co} Custom Endpoint from ${p}`]};await Yv(p,g);let y=[...u,`Removed the ${co} Custom Endpoint from ${p}.`];return await fe(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,p],messages:y}}}},rS=MB();import{accessSync as fF,constants as gS,statSync as mF}from"node:fs";import{readFile as wS,rm as tc}from"node:fs/promises";import{homedir as _h,platform as IS}from"node:os";import{delimiter as hF,join as Th,resolve as yF}from"node:path";import{execFile as HB}from"node:child_process";import{readFile as GB}from"node:fs/promises";import{homedir as Ah,platform as KB}from"node:os";import{join as ec}from"node:path";import{join as BB}from"node:path";var kh="Iv1.b507a08c87ecfe98",FB="https://github.com/login/device/code",UB="https://github.com/login/oauth/access_token",WB="read:user",oS=1e4,ss=()=>BB(ee(),"copilot-seat-login.json"),aS={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},Ch=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sS=async(e={})=>{let t={...aS,...e};try{let n=await t.fetch(FB,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:kh,scope:WB}),signal:AbortSignal.timeout(oS)});if(!n.ok)return;let r=await n.json();if(!Ch(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}},iS=async(e,t={})=>{let n={...aS,...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(UB,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:kh,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(oS)})).json();if(!Ch(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"}},cS=async(e,t)=>{let n=ss();return await ve(n,`${JSON.stringify({token:e,clientId:kh,mintedAtIso:t},null,2)}
|
|
114
114
|
`),n},jd=async()=>{try{let e=await F(ss());if(!Ch(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var VB=5e3,vh=5e3,jB=["copilot-cli","CopilotCLI"],YB="https://api.github.com/copilot_internal/user",dS="~/.copilot/config.json",uS="macOS Keychain (Copilot CLI)",pS=e=>e===dS||e===uS,is=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),yn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ZB=()=>process.env.XDG_CONFIG_HOME?.trim()||ec(Ah(),".config"),JB=()=>process.env.XDG_DATA_HOME?.trim()||ec(Ah(),".local","share"),XB=async()=>{try{let e=await GB(ec(Ah(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return is(t)?t:void 0}catch{}},zB=async e=>{try{let t=await F(ec(ZB(),"github-copilot",e));if(!yn(t))return;for(let n of Object.values(t))if(yn(n)&&is(n.oauth_token))return n.oauth_token}catch{}},qB=async()=>{try{let e=await F(ec(JB(),"opencode","auth.json")),t=yn(e)?e["github-copilot"]:void 0;if(!yn(t)||t.type!=="oauth")return;if(is(t.access))return t.access;if(is(t.refresh))return t.refresh}catch{}},QB=(e,t)=>new Promise((n,r)=>{try{HB(e,[...t],{timeout:VB},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),eF=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return is(r)?r:void 0}catch{return}},tF=async(e=QB)=>{for(let t of jB){let n=await eF(t,e);if(n)return n}};var Yd={env:process.env,platform:KB,tokenFromDeviceLogin:jd,tokenFromCopilotCliConfig:XB,tokenFromSharedConfig:zB,tokenFromOpenCode:qB,tokenFromKeychain:tF,fetch:(...e)=>fetch(...e)},nF=new Set([401,403,404]),Zd=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,fS=e=>{let t=e?.trim().toLowerCase()??"";return t&&t!=="default"&&Zd.test(t)?t:"default"},rF=e=>e!=="default"&&Zd.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",oF=e=>{if(typeof e!="string")return"default";let t=e.trim().match(/^https:\/\/api\.([a-z0-9-]{1,63})\.githubcopilot\.com\/?$/)?.[1];return t&&Zd.test(t)?t:"default"},Sh=async(e,t={})=>{let n={...Yd,...t},r=new AbortController,o=setTimeout(()=>r.abort(),vh);try{let a=await n.fetch(YB,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=yn(i)&&yn(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:oF(s)}}return{verdict:nF.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var cs=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${Zd.test(n)?n:"default"}/header/models`,a=await lS(o,e,r.clientKey,t);if(a.length>0)return a}return lS(`${rF(n)}/models`,e,void 0,t)},lS=async(e,t,n,r={})=>{let o={...Yd,...r},a=new AbortController,s=setTimeout(()=>a.abort(),vh);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=yn(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!yn(u))continue;let p=u.id;if(typeof p!="string"||p.length===0||u.model_picker_enabled!==!0)continue;let m=u.policy;if(yn(m)&&m.state!=="enabled")continue;let f=u.supported_endpoints,h=Array.isArray(f)?f.filter(x=>typeof x=="string"):[],g=u.capabilities,y=yn(g)?g.limits:void 0,w=x=>{let O=yn(y)?y[x]:void 0;return typeof O=="number"&&Number.isFinite(O)&&O>0?Math.floor(O):void 0},b={id:p,endpoints:h},A=w("max_prompt_tokens"),C=w("max_output_tokens");A!==void 0&&(b.maxPromptTokens=A),C!==void 0&&(b.maxOutputTokens=C),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},Jd=async(e,t,n,r={})=>{let o={...Yd,...r},a=new AbortController,s=setTimeout(()=>a.abort(),vh);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)}},Xd=async(e={},t={})=>{let n={...Yd,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return is(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:uS,read:()=>n.tokenFromKeychain()}]:[],{source:dS,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await Sh(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 zd,platform as hS}from"node:os";import{join as gt}from"node:path";import{execFile as aF}from"node:child_process";import{readFile as sF,readdir as iF}from"node:fs/promises";var cF=3e3,lF="Claude Code-credentials",dF=["copilot-cli","CopilotCLI"],yS=e=>new Promise(t=>{try{aF("security",["find-generic-password","-s",e],{timeout:cF},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),uF=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=gt(zd(),".claude");return!!(await R(gt(e,".oauth_token"))||await R(gt(e,".credentials.json"))||hS()==="darwin"&&await yS(lF))},pF=async()=>{let e=gt(process.env.CODEX_HOME?.trim()||gt(zd(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await sF(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},mS=async e=>{try{return(await iF(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},Ih=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of Xo){let n=gt(We(t),"User","globalStorage");if(await R(gt(n,"github.copilot-chat"))||await R(gt(n,"github.copilot")))return!0}let e=gt(zd(),".config","github-copilot");if(await R(gt(e,"apps.json"))||await R(gt(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await mS(gt(zd(),t,"extensions")))return!0;for(let t of Xo){if(await mS(gv(t)))return!0;let n=gt(rs(t,!0),"globalStorage");if(await R(gt(n,"github.copilot-chat"))||await R(gt(n,"github.copilot")))return!0}if(hS()==="darwin"){for(let t of dF)if(await yS(t))return!0}return!1},Vn=async()=>{let[e,t,n]=await Promise.all([uF(),pF(),Ih()]);return{anthropic:e,openai:t,copilot:n}};var ea="copilot-cli",jn="copilot-cli",gF=Ji,wF=()=>gF()?["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."]:[],ES=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],Ph=()=>Object.fromEntries(ES.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),Eh=()=>Th(_h(),".anyray","copilot-cli.sh"),xS="# Managed by anyray-connect. Do not source this file anywhere else.",bS=e=>e.split(/\r?\n/,1)[0]===xS,bF=["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"],qd="COPILOT_PROVIDER_API_KEY",kS=e=>e.startsWith(`export ${qd}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Cr=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",kF=()=>Qi()[0],nc=(e="default")=>`/copilot/${e}/header`,zte=nc(),qo=e=>e.replace(/\/+$/,""),CF=(e,t="default")=>`${qo(e.openaiBaseUrl)}${nc(t)}`,xh=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),Oh="claude-sonnet-5",AF=()=>{let e=Qi()[0];return e===qi?Oh:e},RS=e=>e.endpoints.includes(Cr(e.id)==="responses"?"/responses":"/chat/completions"),Dh=e=>{let t=e.filter(RS),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)=>CS(a.version,s.version)?-1:CS(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var CS=(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},AS=(e,t,n,r,o,a="default")=>{let s=be({...e.metadata,tool:ea}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...ES];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${$e(CF(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Cr(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
115
|
`))}`]:[],`export ${qd}=${$e(n)}`]},Rh=(e,t,n)=>{let r=be({...e.metadata,tool:ea});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${$e(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Cr(t)}'`,`export COPILOT_MODEL=${$e(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${$e(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${qd}=${$e(n)}`]:[]]},vF=(e,t)=>t||!se(e,"copilot"),vS=()=>{let e=bF.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).`]},SS=(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 ${ea}\`), 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`."],SF=(e=process.env.PATH,t=IS())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(hF)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=yF(o,n);try{if(!mF(a).isFile())continue;return fF(a,t==="win32"?gS.F_OK:gS.X_OK),a}catch{}}},IF=()=>Th(_h(),".copilot","config.json"),gn=()=>Th(_h(),".copilot","mcp-config.json"),Qo="anyray",EF=()=>({type:"local",...Ue("profile"),tools:["*"]}),lo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xF=async()=>{let e=gn(),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&&!lo(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=(lo(t.mcpServers)?t.mcpServers:{})[Qo];return r!==void 0&&!St(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${Qo} 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}},RF=async e=>{let t=gn(),n=e.json,r=lo(n.mcpServers)?n.mcpServers:{};r[Qo]=EF(),n.mcpServers=r,await q(t,n)},OF=async()=>{let e=gn(),t;try{let r=await F(e);if(!lo(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!lo(n)||!(Qo in n)||!St(n[Qo],"profile")?!1:(delete n[Qo],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await tc(e,{force:!0}):await q(e,t,{backup:!1}),await fe(e),!0)},_F={resolveCopilotCommand:SF,platform:IS,detectCopilotSeat:Ih,discoverSeatToken:Xd,readDeviceLoginToken:jd,fetchSeatModelCatalog:cs,probeSeatChatModel:Jd},TF=e=>`'${e.replace(/'/g,"''")}'`,PF=e=>e.split(`
|
|
116
116
|
`).map(TF).join(" + [Environment]::NewLine + "),DF=(e={})=>{let t={..._F,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Di(mt(),jn))?.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&&qo(s)===`${qo(i)}/v1`,a=(s,i)=>s!==void 0&&xh(s)&&qo(s).startsWith(`${qo(i)}/v1/copilot/`);return{id:ea,title:"GitHub Copilot CLI",automatic:!0,skillsDir(){return Yt()},async syncOrgMcp({ownerOrigins:s,entry:i}){let c=gn(),l=await F(c),d=Pn(l,"mcpServers",s,i&&{type:"http",url:i.url,headers:{[Vt]:i.clientKey},tools:["*"]});return d==="changed"&&await q(c,l,{backup:!1}),{changed:d==="changed"}},changesBilling:!1,quitGated:{isRunning:Ji,quitTarget:Hd},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=IF();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=mt(),l=async(x,O,S)=>{let E=x.filter(kS),T=x.filter(we=>!kS(we)),I=Eh(),K=[...T,...E.length>0?[`[ -r ${$e(I)} ] && . ${$e(I)}`]:[]],G=await R(I),X=G?await wS(I,"utf8"):void 0,ae=X===void 0||bS(X);if(E.length>0&&!ae)return{status:"manual",messages:[`Refused to overwrite user-managed ${I}; move or rename that file, then run Connect again.`]};let Ae=ne(),me=Ae?await xF():void 0,U=me?.status==="skipped"?me.reason==="foreign"?"mcp_foreign":"mcp_unreadable":void 0,Q=[`${c} \u2190 managed Anyray block (${jn})`,...O.map(we=>` ${we}`),...E.length>0?[`${I} \u2190 owner-only credential (mode 0600)`]:[],...S,me?.status==="skipped"?me.message:Ae?`${gn()} \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.`,...wF()];if(i.dryRun)return{status:"configured",messages:Q,...U?{errorClass:U}:{}};let ye=!1;me?.status==="installable"&&(await RF(me),ye=!0);try{E.length>0?await ve(I,[xS,...E,""].join(`
|
|
117
|
-
`)):G&&ae&&await tc(I,{force:!0}),await bd(c,K,jn)}catch(we){try{X!==void 0&&ae?await ve(I,X):ae&&await tc(I,{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,...E.length>0||G&&ae?[I]:[],...ye?[gn()]:[]],...U?{errorClass:U}:{}}},d=await r(),u=d!==void 0&&!xh(d),p=s.authMode==="placeholder",m=u,f=u&&(!m||!se(s,"copilot")),h=p?void 0:await t.readDeviceLoginToken().catch(()=>{}),g=p||f&&!h?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),y=g.token,w=g.rejected;if(y){let x=g.capiSegment??"default",O=AF(),S=O!==Oh||!!process.env.ANYRAY_COPILOT_MODEL,E=await t.fetchSeatModelCatalog(y.token,{},x,{laneOrigin:qo(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),T=E.find(U=>U.id===O);if(!S){let U=Dh(E);if(T=U[0],!i.dryRun&&U.length>0){let Q=Ie=>`${qo(s.origin)}/v1${nc(x)}/${Cr(Ie)==="responses"?"responses":"chat/completions"}`,ye={...Ph(),authorization:`Bearer ${y.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},we=new Set,Y;for(let Ie of U.slice(0,4)){let cn=await t.probeSeatChatModel(Q(Ie.id),ye,Ie.id);if(cn==="ok"){Y=Ie;break}if(cn==="unreachable")break;we.add(Ie.id)}T=Y??U.find(Ie=>!we.has(Ie.id))??U[0]}O=T?.id??Oh}let I=s.clientKey??s.placeholderKey,K=I&&s.clientKey?Zt(I):I,G=AS(s,O,y.token,I,T,x),X=AS(s,O,Zt(y.token),K,T,x),ae=Cr(O),Ae=E.filter(U=>RS(U)&&Cr(U.id)===ae).map(U=>U.id).filter(U=>U!==O),me=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${y.source}).`,`Model: ${O}${S?" (pinned via ANYRAY_COPILOT_MODEL)":E.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...E.length===0&&pS(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."]:[],...Ae.length>0?[`Your plan also serves: ${Ae.slice(0,8).join(", ")}${Ae.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(U=>{let Q=U.indexOf("="),ye=U.slice(7,Q),we=U.slice(Q+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${ye}', ${PF(we)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${y.source}, and the gateway key from \`anyray-connect print-key\`.)`,...me]}:l(G,X,me)}if(!vF(s,f)){if(m&&!i.dryRun){let x=mt();if(await
|
|
117
|
+
`)):G&&ae&&await tc(I,{force:!0}),await bd(c,K,jn)}catch(we){try{X!==void 0&&ae?await ve(I,X):ae&&await tc(I,{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,...E.length>0||G&&ae?[I]:[],...ye?[gn()]:[]],...U?{errorClass:U}:{}}},d=await r(),u=d!==void 0&&!xh(d),p=s.authMode==="placeholder",m=u,f=u&&(!m||!se(s,"copilot")),h=p?void 0:await t.readDeviceLoginToken().catch(()=>{}),g=p||f&&!h?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),y=g.token,w=g.rejected;if(y){let x=g.capiSegment??"default",O=AF(),S=O!==Oh||!!process.env.ANYRAY_COPILOT_MODEL,E=await t.fetchSeatModelCatalog(y.token,{},x,{laneOrigin:qo(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),T=E.find(U=>U.id===O);if(!S){let U=Dh(E);if(T=U[0],!i.dryRun&&U.length>0){let Q=Ie=>`${qo(s.origin)}/v1${nc(x)}/${Cr(Ie)==="responses"?"responses":"chat/completions"}`,ye={...Ph(),authorization:`Bearer ${y.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},we=new Set,Y;for(let Ie of U.slice(0,4)){let cn=await t.probeSeatChatModel(Q(Ie.id),ye,Ie.id);if(cn==="ok"){Y=Ie;break}if(cn==="unreachable")break;we.add(Ie.id)}T=Y??U.find(Ie=>!we.has(Ie.id))??U[0]}O=T?.id??Oh}let I=s.clientKey??s.placeholderKey,K=I&&s.clientKey?Zt(I):I,G=AS(s,O,y.token,I,T,x),X=AS(s,O,Zt(y.token),K,T,x),ae=Cr(O),Ae=E.filter(U=>RS(U)&&Cr(U.id)===ae).map(U=>U.id).filter(U=>U!==O),me=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${y.source}).`,`Model: ${O}${S?" (pinned via ANYRAY_COPILOT_MODEL)":E.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...E.length===0&&pS(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."]:[],...Ae.length>0?[`Your plan also serves: ${Ae.slice(0,8).join(", ")}${Ae.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(U=>{let Q=U.indexOf("="),ye=U.slice(7,Q),we=U.slice(Q+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${ye}', ${PF(we)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${y.source}, and the gateway key from \`anyray-connect print-key\`.)`,...me]}:l(G,X,me)}if(!vF(s,f)){if(m&&!i.dryRun){let x=mt();if(await Ni(x,jn))return{status:"reverted",changedFiles:[x],messages:[`removed a stale Anyray ${jn} 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:",...SS(t.platform(),w),...vS()]}}return{status:"held",messages:[...m&&i.dryRun?[`would remove a stale Anyray ${jn} block from ${mt()} (org lane, not chosen)`]:[],...SS(t.platform(),w)]}}let b=kF(),A=s.clientKey??s.placeholderKey,C=A&&s.clientKey?Zt(A):A;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...Rh(s,b,C).map(x=>{let[O,...S]=x.replace(/^export /,"").split("=");return` setx ${O} "${S.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${qd} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(Rh(s,b,A),Rh(s,b,C),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===qi?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=mt(),c=Eh(),l=await R(c),d=l?bS(await wS(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${jn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${gn()} if registered`,...await R(ss())?[`would remove the Copilot sign-in Connect minted (${ss()})`]:[]]};let u=await Ni(i,jn);d&&await tc(c,{force:!0});let p=await OF(),m=ss(),f=await R(m);f&&await tc(m,{force:!0});let h=[...u?[i]:[],...d?[c]:[],...p?[gn()]:[],...f?[m]:[]];return{status:h.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${jn} block from ${i}`:`no Anyray ${jn} 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 ${gn()}`]:[],...vS()],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 jt([Eh(),gn()],s)},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let s=gn();if(!await R(s))return{registered:!1,command:null,reason:"no-config"};try{let i=await F(s),c=lo(i)?i.mcpServers:void 0,l=lo(c)?c[Qo]:void 0;return!lo(l)||!St(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"]:xh(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(ea)?!0:!await t.detectCopilotSeat()}}},OS=DF();import{homedir as LS}from"node:os";import{join as po}from"node:path";import{readFile as $S}from"node:fs/promises";import{readFile as _S,rm as NF}from"node:fs/promises";var TS="// Managed by anyray-connect: OpenCode trim carrier v1",LF=5e3,Nh=e=>`${TS}
|
|
118
118
|
import { spawn } from "node:child_process"
|
|
119
119
|
|
|
120
120
|
const hookCommand = ${JSON.stringify([e.command,...e.args])}
|
|
121
|
-
const hookTimeoutMs = ${
|
|
121
|
+
const hookTimeoutMs = ${LF}
|
|
122
122
|
|
|
123
123
|
const invokeHook = (payload) =>
|
|
124
124
|
new Promise((resolve) => {
|
|
@@ -186,10 +186,10 @@ export const AnyrayTrimPlugin = async () => ({
|
|
|
186
186
|
},
|
|
187
187
|
})
|
|
188
188
|
`,rc=async e=>await R(e)?(await _S(e,"utf-8")).startsWith(`${TS}
|
|
189
|
-
`)?"owned":"foreign":"absent",PS=async(e,t)=>{let n=Lh(t),r=await rc(e);return r==="foreign"?"foreign":r==="owned"&&await _S(e,"utf-8")===n?"unchanged":(await ve(e,n),"installed")},Nh=async e=>{let t=await rc(e);return t!=="owned"?t:(await LF(e,{force:!0}),"removed")};var Mh="https://opencode.ai/config.json",Sr="x-anyray-metadata",zt="x-anyray-api-key",Bh=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Ar="Authorization",uo=["anthropic","openai"],Ir="github-copilot",$F="header",vr="anyray",MF=()=>process.env.XDG_CONFIG_HOME?.trim()||po(NS(),".config"),BF=()=>process.env.XDG_DATA_HOME?.trim()||po(NS(),".local","share"),tu=()=>po(MF(),"opencode"),Qd=()=>po(tu(),"plugins","anyrayTrim.js"),MS=()=>po(BF(),"opencode"),BS=async()=>{try{let e=await $S(po(MS(),"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}}},DS=async()=>(await BS()).chatGptOAuth,FF=["opencode.jsonc","opencode.json","config.json"],ta=async()=>{let e=tu(),t=[];for(let n of FF){let r=po(e,n);await R(r)&&t.push(r)}return t},$h=async()=>(await ta())[0]??po(tu(),"opencode.json"),Fh=()=>fS(process.env.ANYRAY_COPILOT_PLAN),Uh=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Fh()}/${$F}`,H=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vh=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},UF=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===uo[0]||n===uo[1]||n===Ir?[]:H(r)&&H(r.options)&&Vh(r.options.baseURL,t)?[n]:[]),Wh=/claude/i,jh=["model","small_model"],FS=(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)||!Wh.test(o)))return`${uo[0]}/${o}`},Hh=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Hh(n,t);return t}if(!H(e))return t;for(let[n,r]of Object.entries(e))jh.includes(n)&&typeof r=="string"?t.push(r):Hh(r,t);return t},WF=(e,t,n)=>{if(!H(e)||!H(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Wh.test(a)))return!1;let o=`${n}/`;return Hh(t).filter(a=>a.startsWith(o)).every(a=>Wh.test(a.slice(o.length)))},Gh=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Gh(o,t,n));if(!H(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=jh.includes(o)?FS(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Gh(a,t,n)}return r},Kh=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Kh(o,t[a],n));if(!H(e)||!H(t))return e;let r={};for(let[o,a]of Object.entries(e))jh.includes(o)&&typeof a=="string"&&FS(t[o],n)===a?r[o]=t[o]:r[o]=Kh(a,t[o],n);return r},HF=e=>{if(H(e))for(let t of uo){let n=e[t];if(H(n)&&H(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},oc=e=>{if(!H(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&St({command:t,args:n},"profile")},eu=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),GF=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return H(t)&&t.tool==="opencode"}catch{return!1}},Yh=e=>se(e,"copilot")&&!!e.clientKey,KF=e=>e.byoUpstream?[]:se(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".`]:[],VF=(e,t)=>se(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.`]:[],jF=e=>Yh(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."]:[],YF=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Mh);let o;if(n)if("mcp"in r&&!H(r.mcp))o="malformed";else{let w=H(r.mcp)?{...r.mcp}:{},b=w[vr];b!==void 0&&!oc(b)?o="foreign":(w[vr]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=w)}else if(H(r.mcp)&&oc(r.mcp[vr])){let w={...r.mcp};delete w[vr],Object.keys(w).length===0?delete r.mcp:r.mcp=w}let a=H(r.provider)?{...r.provider}:{},s=UF(a,t.origin),i=s.every(w=>WF(a[w],e,w))?s:[],c=s.filter(w=>!i.includes(w)),l=[];if(i.length>0){for(let w of i)delete a[w];r=Gh(r,i,l)}let d=[],u=[],p=t.openaiBaseUrl,m=t.clientKey??t.placeholderKey,f=be({...t.metadata,tool:"opencode"});for(let w of c){let b={...a[w]},A={...b.options};if("headers"in A&&!H(A.headers)){u.push(w);continue}let C=H(A.headers)?{...A.headers}:{},x=!1;for(let[O,S]of[[zt,m],...f?[[Sr,f]]:[]])O in C?(typeof C[O]!="string"||C[O].trim()==="")&&u.push(`${w}.${O}`):(C[O]=S,d.push(`${w}.${O}`),x=!0);x&&(A.headers=C,b.options=A,a[w]=b)}let h=c.length>0?[]:uo.filter(w=>w!=="openai"||!se(t,"openai")),g=t.byoUpstream;for(let w of h){let b=H(a[w])?{...a[w]}:{},A=H(b.options)?{...b.options}:{};A.baseURL=p;let C=H(A.headers)?{...A.headers}:{};if(w==="anthropic"&&g)A.apiKey=g.key,C[Ar]=`Bearer ${g.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=g.url;else{A.apiKey=m,"x-anyray-custom-host"in C&&delete C[Ar];for(let x of Bh)delete C[x]}C[zt]=m,f&&(C[Sr]=f),A.headers=C,b.options=A,a[w]=b}let y=c.length===0&&Yh(t);if(y){let w=H(a[Ir])?{...a[Ir]}:{},b=H(w.options)?{...w.options}:{};b.baseURL=Uh(t);let A=H(b.headers)?{...b.headers}:{};A[zt]=t.clientKey,f&&(A[Sr]=f),b.headers=A,w.options=b,a[Ir]=w}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}},ZF=["baseURL","apiKey"],LS=(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?.[zt],m=eu(p);if(d&&(delete c.baseURL,l=!0),u&&(d||m)){let f=u,h=H(r)?r.options:void 0,g=H(h)&&H(h.headers)?h.headers:void 0;for(let y of[zt,Sr])g&&y in g?f[y]!==g[y]&&(f[y]=g[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[zt]=="string"||typeof p[Sr]=="string"||Bh.some(f=>f in p);if(!o&&!m)return!1;for(let f of ZF)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&&Ar in f&&(Ar in h?f[Ar]!==h[Ar]&&(f[Ar]=h[Ar],l=!0):(delete f[Ar],l=!0));for(let g of[zt,Sr,...Bh])g in h?f[g]!==h[g]&&(f[g]=h[g],l=!0):g in f&&(delete f[g],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},JF=(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!(zt in s)&&eu(a[zt])&&(delete a[zt],i=!0),!(Sr in s)&&GF(a[Sr])&&(delete a[Sr],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},XF=(e,t)=>{let n={...e},r=!1,o=HF(e.provider);if(H(n.mcp)&&oc(n.mcp[vr])){let c={...n.mcp};delete c[vr],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===Mh&&uo.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 uo)LS(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...uo,Ir]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;JF(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&H(u)&&H(u.options)&&Vh(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Kh(n,t,l))}return LS(a,Ir,!0,s[Ir])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Mh&&(delete n.$schema,r=!0),{next:n,removed:r}},US={id:"opencode",title:"OpenCode",automatic:!0,skillsDir(){return Yt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=await $h(),r=await Me(n),o=structuredClone(r.data);return Pn(o,"mcp",e,t&&{type:"remote",url:t.url,enabled:!0,headers:{[Vt]:t.clientKey}})!=="changed"?{changed:!1}:!r.existed&&t===void 0?{changed:!1}:{changed:await Xt(n,r,o,!1)}},async detect(){let e=tu(),t=MS(),n=await R(e)||await R(t),r=n&&await DS();return{installed:n,detail:n?`${await $h()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await $h(),r=e.openaiBaseUrl,o=be({...e.metadata,tool:"opencode"}),a=Yh(e),s=se(e,"openai"),i=await DS(),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(Uh(e))}, "headers": { "${zt}": "<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 On()?Ue("profile"):void 0,{next:d,customProviders:u,migratedProviders:p,modelRefsRemapped:m,customHeadersAdded:f,customHeaderConflicts:h,mcpConflict:g}=YF(c.data,e,l),y=u.length>0,w=p.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${p.map(E=>`provider.${E}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...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(E=>`provider.${E}`).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."]:[...w,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)"}`,...KF(e),...VF(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Uh(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. ${Fh()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Fh()} 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).",...jF(e),"Restart OpenCode (or start a new session) to pick up the change."];g==="foreign"?b.push(`MCP name conflict in ${n}: mcp.${vr} is not owned by Anyray Connect, so it was left untouched. Rename that entry, then re-run anyray-connect to register Anyray retrieval.`):g==="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 A=h.length>0?"manual":"configured",C=g==="foreign"?"mcp_foreign":g==="malformed"?"mcp_unreadable":void 0;if(t.dryRun)return{status:A,messages:b,...C?{errorClass:C}:{}};let O=await Xt(n,c,d,!0)?[n]:[],S=Qd();if(ne())try{let E=await PS(S,Mo(rt,["opencode"]));E==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${S} already exists and is not owned by Anyray.`):(E==="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 Nh(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:A,messages:b,changedFiles:O,...C?{errorClass:C}:{}}},async pointsAt(e){for(let t of await ta())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))&&Vh(r.options.baseURL,e))return!0}catch{}return!1},async configuredKeyIsCurrent(e){return jt(await ta(),e)},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await ta();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[vr];if(!oc(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 rc(Qd());e=i==="absent"?"missing":i,e==="owned"&&(t=await $S(Qd(),"utf-8")===Lh(Mo(rt,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await ta()){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[vr];if(l!==void 0)if(oc(l))if(n=!0,!H(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;Ua({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 On()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await BS(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await ta()){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===Ir&&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===Ir&&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(eu(c[zt])||eu(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 ta(),n=Qd(),r="absent";try{r=await rc(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}=XF(c.data,await ts(i));d&&(await Xt(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await fe(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 Nh(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 ey}from"node:os";import{join as ic}from"node:path";import{homedir as zF}from"node:os";import{dirname as qF,join as fo}from"node:path";import{mkdir as QF,readdir as eU,readFile as HS,rm as GS}from"node:fs/promises";var Zh="ec1085ae001eb632d9ab635be7121f621db3ee3430c4865585e8961171a94532",WS=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1mYWJsZS01LTEiLAogICAgICAgICAgICAibmFtZSI6ICJDbGF1ZGUgRmFibGUgNS4xIChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDEwMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtb3B1cy01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIE9wdXMgNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiY2xhdWRlLXNvbm5ldC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA1IChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDEwMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBTb25uZXQgNC41IChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDIwMDAwMCwKICAgICAgICAgICAgIm1heFRva2VucyI6IDY0MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiY2xhdWRlLWhhaWt1LTQtNSIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBIYWlrdSA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtb3B1cy00LTgiLAogICAgICAgICAgICAibmFtZSI6ICJDbGF1ZGUgT3B1cyA0LjggKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMTAwMDAwMCwKICAgICAgICAgICAgIm1heFRva2VucyI6IDEyODAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleH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oY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMSIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pb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F5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Jh=".anyray-source-sha",Yn=()=>fo(zF(),".anyray","openclaw-plugin"),KS=async(e=Yn())=>{try{if((await HS(fo(e,Jh),"utf8")).trim()===Zh)return"current"}catch{}for(let t of WS){let n=fo(e,t.path);await QF(qF(n),{recursive:!0,mode:448}),await ve(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await ve(fo(e,Jh),`${Zh}
|
|
189
|
+
`)?"owned":"foreign":"absent",PS=async(e,t)=>{let n=Nh(t),r=await rc(e);return r==="foreign"?"foreign":r==="owned"&&await _S(e,"utf-8")===n?"unchanged":(await ve(e,n),"installed")},Lh=async e=>{let t=await rc(e);return t!=="owned"?t:(await NF(e,{force:!0}),"removed")};var Mh="https://opencode.ai/config.json",Sr="x-anyray-metadata",zt="x-anyray-api-key",Bh=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Ar="Authorization",uo=["anthropic","openai"],Ir="github-copilot",$F="header",vr="anyray",MF=()=>process.env.XDG_CONFIG_HOME?.trim()||po(LS(),".config"),BF=()=>process.env.XDG_DATA_HOME?.trim()||po(LS(),".local","share"),tu=()=>po(MF(),"opencode"),Qd=()=>po(tu(),"plugins","anyrayTrim.js"),MS=()=>po(BF(),"opencode"),BS=async()=>{try{let e=await $S(po(MS(),"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}}},DS=async()=>(await BS()).chatGptOAuth,FF=["opencode.jsonc","opencode.json","config.json"],ta=async()=>{let e=tu(),t=[];for(let n of FF){let r=po(e,n);await R(r)&&t.push(r)}return t},$h=async()=>(await ta())[0]??po(tu(),"opencode.json"),Fh=()=>fS(process.env.ANYRAY_COPILOT_PLAN),Uh=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Fh()}/${$F}`,H=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vh=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},UF=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===uo[0]||n===uo[1]||n===Ir?[]:H(r)&&H(r.options)&&Vh(r.options.baseURL,t)?[n]:[]),Wh=/claude/i,jh=["model","small_model"],FS=(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)||!Wh.test(o)))return`${uo[0]}/${o}`},Hh=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Hh(n,t);return t}if(!H(e))return t;for(let[n,r]of Object.entries(e))jh.includes(n)&&typeof r=="string"?t.push(r):Hh(r,t);return t},WF=(e,t,n)=>{if(!H(e)||!H(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Wh.test(a)))return!1;let o=`${n}/`;return Hh(t).filter(a=>a.startsWith(o)).every(a=>Wh.test(a.slice(o.length)))},Gh=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Gh(o,t,n));if(!H(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=jh.includes(o)?FS(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Gh(a,t,n)}return r},Kh=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Kh(o,t[a],n));if(!H(e)||!H(t))return e;let r={};for(let[o,a]of Object.entries(e))jh.includes(o)&&typeof a=="string"&&FS(t[o],n)===a?r[o]=t[o]:r[o]=Kh(a,t[o],n);return r},HF=e=>{if(H(e))for(let t of uo){let n=e[t];if(H(n)&&H(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},oc=e=>{if(!H(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&St({command:t,args:n},"profile")},eu=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),GF=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return H(t)&&t.tool==="opencode"}catch{return!1}},Yh=e=>se(e,"copilot")&&!!e.clientKey,KF=e=>e.byoUpstream?[]:se(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".`]:[],VF=(e,t)=>se(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.`]:[],jF=e=>Yh(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."]:[],YF=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Mh);let o;if(n)if("mcp"in r&&!H(r.mcp))o="malformed";else{let w=H(r.mcp)?{...r.mcp}:{},b=w[vr];b!==void 0&&!oc(b)?o="foreign":(w[vr]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=w)}else if(H(r.mcp)&&oc(r.mcp[vr])){let w={...r.mcp};delete w[vr],Object.keys(w).length===0?delete r.mcp:r.mcp=w}let a=H(r.provider)?{...r.provider}:{},s=UF(a,t.origin),i=s.every(w=>WF(a[w],e,w))?s:[],c=s.filter(w=>!i.includes(w)),l=[];if(i.length>0){for(let w of i)delete a[w];r=Gh(r,i,l)}let d=[],u=[],p=t.openaiBaseUrl,m=t.clientKey??t.placeholderKey,f=be({...t.metadata,tool:"opencode"});for(let w of c){let b={...a[w]},A={...b.options};if("headers"in A&&!H(A.headers)){u.push(w);continue}let C=H(A.headers)?{...A.headers}:{},x=!1;for(let[O,S]of[[zt,m],...f?[[Sr,f]]:[]])O in C?(typeof C[O]!="string"||C[O].trim()==="")&&u.push(`${w}.${O}`):(C[O]=S,d.push(`${w}.${O}`),x=!0);x&&(A.headers=C,b.options=A,a[w]=b)}let h=c.length>0?[]:uo.filter(w=>w!=="openai"||!se(t,"openai")),g=t.byoUpstream;for(let w of h){let b=H(a[w])?{...a[w]}:{},A=H(b.options)?{...b.options}:{};A.baseURL=p;let C=H(A.headers)?{...A.headers}:{};if(w==="anthropic"&&g)A.apiKey=g.key,C[Ar]=`Bearer ${g.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=g.url;else{A.apiKey=m,"x-anyray-custom-host"in C&&delete C[Ar];for(let x of Bh)delete C[x]}C[zt]=m,f&&(C[Sr]=f),A.headers=C,b.options=A,a[w]=b}let y=c.length===0&&Yh(t);if(y){let w=H(a[Ir])?{...a[Ir]}:{},b=H(w.options)?{...w.options}:{};b.baseURL=Uh(t);let A=H(b.headers)?{...b.headers}:{};A[zt]=t.clientKey,f&&(A[Sr]=f),b.headers=A,w.options=b,a[Ir]=w}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}},ZF=["baseURL","apiKey"],NS=(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?.[zt],m=eu(p);if(d&&(delete c.baseURL,l=!0),u&&(d||m)){let f=u,h=H(r)?r.options:void 0,g=H(h)&&H(h.headers)?h.headers:void 0;for(let y of[zt,Sr])g&&y in g?f[y]!==g[y]&&(f[y]=g[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[zt]=="string"||typeof p[Sr]=="string"||Bh.some(f=>f in p);if(!o&&!m)return!1;for(let f of ZF)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&&Ar in f&&(Ar in h?f[Ar]!==h[Ar]&&(f[Ar]=h[Ar],l=!0):(delete f[Ar],l=!0));for(let g of[zt,Sr,...Bh])g in h?f[g]!==h[g]&&(f[g]=h[g],l=!0):g in f&&(delete f[g],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},JF=(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!(zt in s)&&eu(a[zt])&&(delete a[zt],i=!0),!(Sr in s)&&GF(a[Sr])&&(delete a[Sr],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},XF=(e,t)=>{let n={...e},r=!1,o=HF(e.provider);if(H(n.mcp)&&oc(n.mcp[vr])){let c={...n.mcp};delete c[vr],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===Mh&&uo.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 uo)NS(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...uo,Ir]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;JF(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&H(u)&&H(u.options)&&Vh(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Kh(n,t,l))}return NS(a,Ir,!0,s[Ir])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Mh&&(delete n.$schema,r=!0),{next:n,removed:r}},US={id:"opencode",title:"OpenCode",automatic:!0,skillsDir(){return Yt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=await $h(),r=await Me(n),o=structuredClone(r.data);return Pn(o,"mcp",e,t&&{type:"remote",url:t.url,enabled:!0,headers:{[Vt]:t.clientKey}})!=="changed"?{changed:!1}:!r.existed&&t===void 0?{changed:!1}:{changed:await Xt(n,r,o,!1)}},async detect(){let e=tu(),t=MS(),n=await R(e)||await R(t),r=n&&await DS();return{installed:n,detail:n?`${await $h()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await $h(),r=e.openaiBaseUrl,o=be({...e.metadata,tool:"opencode"}),a=Yh(e),s=se(e,"openai"),i=await DS(),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(Uh(e))}, "headers": { "${zt}": "<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 On()?Ue("profile"):void 0,{next:d,customProviders:u,migratedProviders:p,modelRefsRemapped:m,customHeadersAdded:f,customHeaderConflicts:h,mcpConflict:g}=YF(c.data,e,l),y=u.length>0,w=p.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${p.map(E=>`provider.${E}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...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(E=>`provider.${E}`).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."]:[...w,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)"}`,...KF(e),...VF(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Uh(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. ${Fh()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Fh()} 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).",...jF(e),"Restart OpenCode (or start a new session) to pick up the change."];g==="foreign"?b.push(`MCP name conflict in ${n}: mcp.${vr} is not owned by Anyray Connect, so it was left untouched. Rename that entry, then re-run anyray-connect to register Anyray retrieval.`):g==="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 A=h.length>0?"manual":"configured",C=g==="foreign"?"mcp_foreign":g==="malformed"?"mcp_unreadable":void 0;if(t.dryRun)return{status:A,messages:b,...C?{errorClass:C}:{}};let O=await Xt(n,c,d,!0)?[n]:[],S=Qd();if(ne())try{let E=await PS(S,Mo(rt,["opencode"]));E==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${S} already exists and is not owned by Anyray.`):(E==="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 Lh(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:A,messages:b,changedFiles:O,...C?{errorClass:C}:{}}},async pointsAt(e){for(let t of await ta())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))&&Vh(r.options.baseURL,e))return!0}catch{}return!1},async configuredKeyIsCurrent(e){return jt(await ta(),e)},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await ta();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[vr];if(!oc(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 rc(Qd());e=i==="absent"?"missing":i,e==="owned"&&(t=await $S(Qd(),"utf-8")===Nh(Mo(rt,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await ta()){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[vr];if(l!==void 0)if(oc(l))if(n=!0,!H(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;Ua({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 On()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await BS(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await ta()){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===Ir&&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===Ir&&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(eu(c[zt])||eu(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 ta(),n=Qd(),r="absent";try{r=await rc(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}=XF(c.data,await ts(i));d&&(await Xt(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await fe(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 Lh(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 ey}from"node:os";import{join as ic}from"node:path";import{homedir as zF}from"node:os";import{dirname as qF,join as fo}from"node:path";import{mkdir as QF,readdir as eU,readFile as HS,rm as GS}from"node:fs/promises";var Zh="d2c7371f202aedd785b6e69ee928434138f53a79dca502c912f2f19deea03a48",WS=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1mYWJsZS01LTEiLAogICAgICAgICAgICAibmFtZSI6ICJDbGF1ZGUgRmFibGUgNS4xIChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDEwMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtb3B1cy01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIE9wdXMgNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiY2xhdWRlLXNvbm5ldC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA1IChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDEwMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBTb25uZXQgNC41IChBbnlyYXkpIiwKICAgICAgICAgICAgInJlYXNvbmluZyI6IHRydWUsCiAgICAgICAgICAgICJpbnB1dCI6IFsidGV4dCIsICJpbWFnZSJdLAogICAgICAgICAgICAiY29udGV4dFdpbmRvdyI6IDIwMDAwMCwKICAgICAgICAgICAgIm1heFRva2VucyI6IDY0MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiY2xhdWRlLWhhaWt1LTQtNSIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBIYWlrdSA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtb3B1cy00LTgiLAogICAgICAgICAgICAibmFtZSI6ICJDbGF1ZGUgT3B1cyA0LjggKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMTAwMDAwMCwKICAgICAgICAgICAgIm1heFRva2VucyI6IDEyODAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMSIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJEZXBlbmRlbmNpZXMiOiB7CiAgICAib3BlbmNsYXciOiAiPj0yMDI2LjcuMSIKICB9LAogICJkZXZEZXBlbmRlbmNpZXMiOiB7CiAgICAidHN4IjogIl40LjIzLjEzIiwKICAgICJ0eXBlc2NyaXB0IjogIl41LjYuMyIKICB9Cn0K"},{path:"src/index.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ld2F5UHJvdmlkZXJGb3JNb2RlbChtb2RlbC5pZCkKICAgICAgOiB1bmRlZmluZWQ7CiAgICBpZiAoZ2F0ZXdheVByb3ZpZGVyICYmIGhlYWRlcnNbJ3gtYW55cmF5LXByb3ZpZGVyJ10gPT09IHVuZGVmaW5lZCkgewogICAgICBoZWFkZXJzWyd4LWFueXJheS1wcm92aWRlciddID0gZ2F0ZXdheVByb3ZpZGVyOwogICAgfQogICAgb3B0cy5oZWFkZXJzID0gaGVhZGVyczsKICAgIGNvbnN0IHNlc3Npb25JZCA9CiAgICAgIHR5cGVvZiBvcHRzLnNlc3Npb25JZCA9PT0gJ3N0cmluZycgPyBvcHRzLnNlc3Npb25JZCA6IHVuZGVmaW5lZDsKICAgIGNvbnN0IGNhbGxlck9uUGF5bG9hZCA9IG9wdHMub25QYXlsb2FkOwogICAgb3B0cy5vblBheWxvYWQgPSBhc3luYyAocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA9PiB7CiAgICAgIGlmIChwYXlsb2FkICYmIHR5cGVvZiBwYXlsb2FkID09PSAnb2JqZWN0JyAmJiAhQXJyYXkuaXNBcnJheShwYXlsb2FkKSkgewogICAgICAgIHBhdGNoUGF5bG9hZFNlc3Npb25JZGVudGl0eSgKICAgICAgICAgIHBheWxvYWQgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4sCiAgICAgICAgICBzZXNzaW9uSWQKICAgICAgICApOwogICAgICB9CiAgICAgIHJldHVybiBjYWxsZXJPblBheWxvYWQgPyBjYWxsZXJPblBheWxvYWQocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Jh=".anyray-source-sha",Yn=()=>fo(zF(),".anyray","openclaw-plugin"),KS=async(e=Yn())=>{try{if((await HS(fo(e,Jh),"utf8")).trim()===Zh)return"current"}catch{}for(let t of WS){let n=fo(e,t.path);await QF(qF(n),{recursive:!0,mode:448}),await ve(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await ve(fo(e,Jh),`${Zh}
|
|
190
190
|
`),"installed"},ac=async(e,t=[])=>{let n=[],r=async a=>{let s=fo(a,"plugins","anyray","catalog.json");try{await GS(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await eU(fo(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(fo(e,"agents",a,"agent"));return n},nu=async(e=Yn())=>{try{await HS(fo(e,Jh),"utf8")}catch{return!1}return await GS(e,{recursive:!0,force:!0}),!0};var zh="x-anyray-metadata",ls="x-anyray-api-key",qh=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],ra="Authorization",oa="anthropic-beta",ou="interleaved-thinking-2025-05-14",au=["anthropic","openai"],jS="short",ty="anthropic-messages",ny=128e3,su="anthropic/claude-sonnet-4-5",ry=["anthropic/claude-haiku-4-5"],oy="anyray/claude-sonnet-4-5",ay=["anyray/claude-haiku-4-5"],tU=[su,oy],nU=[ry,ay],at="anyray",mo="ANYRAY_API_KEY",wn="anyray",cc=e=>$(e)&&St({command:e.command,args:e.args},"profile"),sc="openclaw",na=()=>process.env.OPENCLAW_STATE_DIR?.trim()||ic(ey(),".openclaw"),Zn=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||ic(na(),"openclaw.json"),$=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),VS=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Qh=e=>{if(!$(e))return{};let t=e.models;return!$(t)||!$(t.providers)?{}:t.providers},rU=e=>e==="~"||e.startsWith("~/")?ic(ey(),e.slice(1)):e,ru=e=>{if(!$(e))return[];let t=e.agents;if(!$(t)||!Array.isArray(t.list))return[];let n=[];for(let r of t.list){if(!$(r))continue;let o=typeof r.agentDir=="string"?r.agentDir.trim():"";o&&n.push(rU(o))}return n},oU=(e,t,n,r)=>{let o=t.clientKey??t.placeholderKey,a=be({...t.metadata,tool:sc}),s=t.byoUpstream,i=[],c=[],l=!1,d={...e},u=[];"models"in d&&!$(d.models)&&u.push("models");let p=$(d.models)?{...d.models}:{};if("providers"in p&&!$(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=$(p.providers)?{...p.providers}:{},f=!1;if(n){let S=$(d.plugins)?{...d.plugins}:{},E=$(S.load)?{...S.load}:{},T=$(S.entries)?{...S.entries}:{},I=$(T[at])?{...T[at]}:{},K=$(I.config)?{...I.config}:{};if("plugins"in d&&!$(d.plugins)||"load"in S&&!$(S.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in S&&!$(S.entries)||at in T&&!$(T[at])||"config"in I&&!$(I.config)||"env"in d&&!$(d.env))u.push("plugins");else{let G=Array.isArray(E.paths)?[...E.paths]:[];G.includes(n)||G.push(n),E.paths=G,S.load=E,I.enabled=!0,K.gatewayUrl=t.anthropicBaseUrl,K.apiKey=o;let X=t.metadata.user,ae=t.metadata.team;X&&(K.user=X),ae&&(K.team=ae),I.config=K,T[at]=I,S.entries=T,d.plugins=S;let Ae=$(d.env)?{...d.env}:{};Ae[mo]=o,d.env=Ae,f=!0}}let h=!1,g=!1;if(r)if("mcp"in d&&!$(d.mcp)||$(d.mcp)&&"servers"in d.mcp&&!$(d.mcp.servers))u.push("mcp.servers");else{let S=$(d.mcp)?{...d.mcp}:{},E=$(S.servers)?{...S.servers}:{},T=E[wn];T!==void 0&&!cc(T)?g=!0:(E[wn]={command:r.command,args:[...r.args],transport:"stdio",enabled:!0},S.servers=E,d.mcp=S,h=!0)}else if($(d.mcp)&&$(d.mcp.servers)&&cc(d.mcp.servers[wn])){let S={...d.mcp},E={...S.servers};delete E[wn],Object.keys(E).length===0?delete S.servers:S.servers=E,Object.keys(S).length===0?delete d.mcp:d.mcp=S}let y=au.filter(S=>S!=="openai"||!se(t,"openai"));for(let S of y){if(S in m&&!$(m[S])){u.push(`models.providers.${S}`);continue}let E=$(m[S])?{...m[S]}:{};if("headers"in E&&!$(E.headers)){c.push(S);continue}let T=$(E.headers)?{...E.headers}:{};if(E.baseUrl=S==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,S==="anthropic"&&(E.api=ty,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=ny)),S==="anthropic"&&s)E.apiKey=s.key,T[ra]=`Bearer ${s.key}`,T["x-anyray-provider"]="anthropic",T["x-anyray-auth-mode"]="passthrough",T["x-anyray-custom-host"]=s.url;else{E.apiKey=o,"x-anyray-custom-host"in T&&delete T[ra];for(let I of qh)delete T[I]}T[ls]=o,a&&(T[zh]=a),S==="anthropic"&&(oa in T?l=T[oa]!==ou:T[oa]=ou),E.headers=T,m[S]=E,i.push(S)}p.providers=m,d.models=p;let w=!1,b=!1,A=!1,C,x=[],O="agents"in d&&!$(d.agents)||$(d.agents)&&"defaults"in d.agents&&!$(d.agents.defaults)||$(d.agents)&&$(d.agents.defaults)&&("params"in d.agents.defaults&&!$(d.agents.defaults.params)||"model"in d.agents.defaults&&!$(d.agents.defaults.model));if(O&&u.push("agents.defaults"),i.includes("anthropic")&&!O){let S=$(d.agents)?{...d.agents}:{},E=$(S.defaults)?{...S.defaults}:{},T=$(E.params)?{...E.params}:{};"cacheRetention"in T||(T.cacheRetention=jS,w=!0,E.params=T);let I=$(E.model)?{...E.model}:{},K=f?[...i,at]:i,G=X=>typeof X=="string"&&K.some(ae=>X.startsWith(`${ae}/`));typeof I.primary!="string"||I.primary.trim()===""?(I.primary=f?oy:su,b=!0,E.model=I,"fallbacks"in I||(I.fallbacks=f?[...ay]:[...ry],A=!0)):G(I.primary)||(C=I.primary),x=(Array.isArray(I.fallbacks)?I.fallbacks:[]).filter(X=>typeof X=="string"&&!G(X)),(w||b)&&(S.defaults=E,d.agents=S)}return{next:d,routed:i,cacheRetentionSeeded:w,betaPreserved:l,headerConflicts:c,primarySeeded:b,fallbacksSeeded:A,unroutedPrimary:C,unroutedFallbacks:x,structureConflicts:u,pluginConfigured:f,mcpConfigured:h,mcpConflict:g}},aU=["baseUrl","apiKey","api","maxTokens"],Xh=(e,t,n=au,r)=>{let o={...e},a=!("models"in o)||$(o.models)&&(!("providers"in o.models)||$(o.models.providers)),s=$(o.models)?{...o.models}:{},i=$(s.providers)?{...s.providers}:{},c=Qh(t),l=!1;for(let u of a?n:[]){let p=i[u];if(!$(p))continue;let m={...p},f=$(m.headers)?{...m.headers}:{};if(!(t!==void 0||typeof f[ls]=="string"||typeof f[zh]=="string"||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_")||qh.some(C=>C in f)))continue;let g=$(c[u])?c[u]:{},y=$(g.headers)?g.headers:{},w="x-anyray-custom-host"in f,b=C=>C==="api"?m.api===ty:C==="maxTokens"?m.maxTokens===ny:C==="apiKey"?w||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_"):!0;for(let C of aU)b(C)&&(C in g?m[C]!==g[C]&&(m[C]=g[C],l=!0):C in m&&(delete m[C],l=!0));let A=[ls,zh,...qh,..."x-anyray-custom-host"in f?[ra]:[]];f[oa]===ou&&A.push(oa);for(let C of A)C in y?f[C]!==y[C]&&(f[C]=y[C],l=!0):C in f&&(delete f[C],l=!0);ra in y&&!(ra in f)&&(f[ra]=y[ra],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=$(o.plugins)?{...o.plugins}:{},p=$(u.load)?{...u.load}:{},m=$(u.entries)?{...u.entries}:{};if((!("plugins"in o)||$(o.plugins))&&(!("load"in u)||$(u.load))&&(!("paths"in p)||Array.isArray(p.paths))&&(!("entries"in u)||$(u.entries))){if(Array.isArray(p.paths)&&p.paths.includes(r)){let g=p.paths.filter(y=>y!==r);g.length===0?delete p.paths:p.paths=g,l=!0}let h=m[at];if($(h)){let g=$(h.config)?h.config:{};if(t!==void 0||typeof g.apiKey=="string"&&g.apiKey.startsWith("ark_")){let w=$(t?.plugins)?t.plugins:{},b=$(w.entries)?w.entries:{};at in b?JSON.stringify(m[at])!==JSON.stringify(b[at])&&(m[at]=b[at],l=!0):(delete m[at],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,$(o.env)){let g={...o.env},y=g[mo];if(typeof y=="string"&&y.startsWith("ark_")){let w=$(t?.env)?t.env:{};mo in w?g[mo]!==w[mo]&&(g[mo]=w[mo],l=!0):(delete g[mo],l=!0),Object.keys(g).length===0?delete o.env:o.env=g}}}}if(n.includes("anthropic")&&$(o.mcp)&&$(o.mcp.servers)&&cc(o.mcp.servers[wn])){let u={...o.mcp},p={...u.servers};delete p[wn],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)||$(o.agents)&&(!("defaults"in o.agents)||$(o.agents.defaults)&&(!("params"in o.agents.defaults)||$(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||$(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=$(o.agents)?{...o.agents}:{},p=$(u.defaults)?{...u.defaults}:{},m=$(p.params)?{...p.params}:{},f=$(t.agents)?t.agents:{},h=$(f.defaults)?f.defaults:{},g=$(h.params)?h.params:{};m.cacheRetention===jS&&("cacheRetention"in g?m.cacheRetention!==g.cacheRetention&&(m.cacheRetention=g.cacheRetention,l=!0):(delete m.cacheRetention,l=!0));let y=$(p.model)?{...p.model}:{},w=$(h.model)?h.model:{};tU.includes(y.primary)&&("primary"in w?y.primary!==w.primary&&(y.primary=w.primary,l=!0):(delete y.primary,l=!0)),nU.some(b=>JSON.stringify(y.fallbacks)===JSON.stringify(b))&&("fallbacks"in w?JSON.stringify(y.fallbacks)!==JSON.stringify(w.fallbacks)&&(y.fallbacks=w.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}},YS={id:sc,title:"OpenClaw",automatic:!0,skillsDir(){return process.env.OPENCLAW_STATE_DIR?.trim()?ic(na(),"skills"):Yt()},async syncOrgMcp({ownerOrigins:e,entry:t}){let n=Zn(),r=await Me(n),o=structuredClone(r.data);if(o.mcp!==void 0&&!$(o.mcp))return{changed:!1};let a=$(o.mcp)?o.mcp:{};return Pn(a,"servers",e,t&&{url:t.url,transport:"streamable-http",headers:{[Vt]: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 Xt(n,r,o,!1)})},async detect(){let e=await R(Zn())||await R(na());return{installed:e,detail:e?Zn():`no ${ic(ey(),".openclaw")} state dir`}},async apply(e,t){let n=Zn();if(!e.byoUpstream&&se(e,"anthropic")){let T=["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 ${sc}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],I;try{I=await Me(n)}catch{return{status:"held",messages:T}}let{next:K,removed:G}=Xh(I.data,await ts(n),au,Yn());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)`,...T]}:(await Xt(n,I,K,!1),await fe(n),await nu(),await ac(na(),ru(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.`,...T]}):(t.dryRun||(await nu(),await ac(na(),ru(K))),{status:"held",messages:T})}let r=Yn(),o=!1;if(!t.dryRun)try{await KS(r)}catch{r=void 0,o=!0}let a=await On()?Ue("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": "${ty}", "maxTokens": ${ny}, "apiKey": "<your personal ark_ key>", "headers": { "${ls}": "<your personal ark_ key>", "${oa}": "${ou}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${ls}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${su}") 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 "${wn}": { "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:g,pluginConfigured:y,mcpConfigured:w,mcpConflict:b}=oU(s.data,e,r,a),A=i,C=!1;if(!c.includes("openai")){let T=Xh(A,await ts(n),["openai"]);T.removed&&(A=T.next,C=!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:sc})??"(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 ${oa} 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?oy:su} (none was set; routing is inert until the primary resolves to a routed provider).`,...m?[`Seeded agents.defaults.model.fallbacks = [${(y?ay:ry).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.`]:[],...C?["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 (${Yn()}) and registered it under plugins.entries.${at}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${Yn()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...b?[`MCP name conflict in ${n}: mcp.servers.${wn} is not owned by Anyray Connect, so it was left untouched. Rename or remove it to get anyray_retrieve.`]:w?[`Registered the Anyray retrieval MCP server (anyray_retrieve) at mcp.servers.${wn}, 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.`]:[],...g.length>0?[`Left ${g.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||g.length>0?"manual":"configured",S=b?"mcp_foreign":void 0;if(t.dryRun)return{status:O,messages:x,...S?{errorClass:S}:{}};let E=await Xt(n,s,A,!0);return y&&await ac(na(),ru(A)),{status:O,messages:x,changedFiles:E?[n]:[],...S?{errorClass:S}:{}}},async pointsAt(e){try{let{data:t}=await Me(Zn());for(let a of Object.values(Qh(t)))if($(a)&&VS(a.baseUrl,e))return!0;let n=$(t.plugins)?t.plugins:{},o=($(n.entries)?n.entries:{})[at];if($(o)&&$(o.config)&&VS(o.config.gatewayUrl,e))return!0}catch{}return!1},async configuredKeyIsCurrent(e){return jt([Zn()],e)},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Zn();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=$(t.mcp)?t.mcp:{},o=($(n.servers)?n.servers:{})[wn];if(o===void 0)return{registered:!1,command:null,reason:"absent"};if(!cc(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(Zn()),r=$(n.mcp)?n.mcp.servers:void 0;if(n.mcp!==void 0&&!$(n.mcp)||r!==void 0&&!$(r))e="unreadable";else{let o=$(r)?r[wn]:void 0;if(o===void 0)e="missing";else if(!cc(o))e="foreign";else{e="owned";let a=o;t=Ua({command:a.command,args:a.args},"profile")}}}catch{e="unreadable"}return{mcp_registration:e,hook_binary:t&&await On()?"owned":"missing"}},async routingExpected(e){return e.includes(sc)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Me(Zn());for(let a of Object.values(Qh(t))){if(!$(a))continue;let s=$(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[ls]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=$(t.plugins)?t.plugins:{},o=($(n.entries)?n.entries:{})[at];if($(o)&&$(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=Zn();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}=Xh(n.data,await ts(t),au,Yn()),a=await nu();return await ac(na(),ru(r)),o?(await Xt(t,n,r,!1),await fe(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${Yn()}`]:[]],changedFiles:[t]}):(await fe(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${Yn()}`]:[]]})}};import{execFile as XH}from"node:child_process";import{readFile as zH}from"node:fs/promises";import{homedir as xc,platform as wo}from"node:os";import{join as Qn}from"node:path";import{isDeepStrictEqual as Jy,promisify as qH}from"node:util";var lc=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},iu=(e,t)=>{let n=lc(e),r=lc(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 fH}from"node:crypto";import{promises as aE}from"node:fs";import{platform as sE,tmpdir as mH}from"node:os";import{join as Iu}from"node:path";import{execFile as sU}from"node:child_process";import{promises as dc}from"node:fs";import{homedir as iU,platform as cU}from"node:os";import{delimiter as lU,join as cu}from"node:path";import{promisify as dU}from"node:util";var uU=dU(sU),pU=15*6e4,fU=64*1024*1024,mU=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],ZS=async(e={})=>{let t=(e.home??iU)(),n=e.env??process.env,r=mU(e.runtimePlatform??cU()),o=[cu(t,".local","bin"),cu(t,".claude","local"),...(n.PATH??"").split(lU).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=cu(a,`claude${s}`);try{return await dc.access(i),i}catch{}}return null},hU=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},yU=async e=>{let t=cu(e,"projects"),n;try{n=(await dc.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(!bU.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},gU=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:hU(n.projectList)}},wU=async e=>{let t,n;try{let r=await dc.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}},bU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,kU=/\.(?:cmd|bat)$/i,CU=(e,t)=>kU.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},JS=async(e,t={})=>{let n=t.exec??uU,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 dc.mkdir(e.configDir,{recursive:!0,mode:448}),await dc.mkdir(e.workDir,{recursive:!0,mode:448});let o=CU(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:pU,maxBuffer:fU,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=gU(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 wU(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await yU(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as AU}from"node:crypto";import{promises as Er}from"node:fs";import{homedir as vU,platform as SU}from"node:os";import{join as $t}from"node:path";var XS=448,xr="local_",IU="local-agent-mode-sessions",sy="-3p",EU="cowork_account_settings.json",Rr=(e={})=>{let t=(e.home??vU)(),n=e.runtimePlatform??SU(),r=e.env??process.env;if(n==="darwin")return $t(t,"Library","Application Support",`Claude${sy}`);if(n==="win32"){let o=r.LOCALAPPDATA??$t(t,"AppData","Local");return $t(o,`Claude${sy}`)}return null},aa=(e={})=>{let t=Rr(e);return t?t.slice(0,-sy.length):null},iy=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)}`},lu=async e=>{let t=$t(e,IU),n;try{n=(await Er.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 Er.readdir($t(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=$t(t,o,s);try{await Er.access($t(i,EU)),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]}},cy=async e=>{try{let t=await Er.readdir(e);return new Set(t.filter(n=>n.startsWith(xr)&&n.endsWith(".json")).map(n=>n.slice(xr.length,-5)))}catch{return new Set}},ds=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),xU=async(e,t)=>{let n=`${xr}${t.sessionId}`,r=$t(e,n),o=$t(r,"outputs"),a=$t(r,".claude"),s=$t(a,"projects",iy(o));await Er.mkdir(o,{recursive:!0,mode:XS}),await Er.mkdir(s,{recursive:!0,mode:XS});let i=$t(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${AU()}`;await Er.copyFile(t.transcriptPath,c),await Er.chmod(c,384),await Er.rename(c,i);let l=t.createdAt??Date.now();await q($t(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})},zS=async(e,t)=>{let n=await cy(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!ds(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await xU(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as us}from"node:fs";import{homedir as RU}from"node:os";import{dirname as OU,join as uc}from"node:path";var _U=448,TU=["Documents","Claude","Projects"],PU="spaces.json",DU=(e={})=>uc((e.home??RU)(),...TU),LU=async e=>{try{let t=JSON.parse(await us.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}}},NU=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},ly=async e=>{try{return await us.access(e),!0}catch{return!1}},$U=async(e,t,n)=>{let r=uc(t,NU(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await ly(r)?o:r;return a===o&&await ly(o)?null:(await us.mkdir(OU(a),{recursive:!0}),await us.cp(e,a,{recursive:!0}),a)},MU=async e=>{try{let t=(await us.readFile(uc(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},qS=async e=>{let t=DU({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=uc(e.storageDir,PU),{spaces:a,readable:s}=await LU(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=uc(e.stagedProjectsDir,l.dirName);try{if(!await ly(d)){n.failed+=1;continue}let u=await $U(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await MU(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 us.mkdir(e.storageDir,{recursive:!0,mode:_U}),await q(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as WU}from"node:crypto";import{execFile as HU,spawnSync as lI}from"node:child_process";import{constants as dI}from"node:fs";import{access as hu,chmod as GU,mkdir as KU,readdir as VU,readFile as uy,rename as jU,rm as ps,stat as uI,writeFile as YU}from"node:fs/promises";import{homedir as ZU,platform as JU,userInfo as XU}from"node:os";import{basename as zU,dirname as pI,isAbsolute as fs,join as qt,resolve as rI}from"node:path";import{isDeepStrictEqual as fc,promisify as qU}from"node:util";var ho="__anyray-claude-desktop-credential",pc="__anyray-claude-desktop-bootstrap-headers";var du=(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>\`.`],uu=["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."],QS=(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 pu=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],eI=["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"],BU=new Set(eI),FU=new Set(eI.map(e=>e.toLowerCase())),UU=new Set(pu.map(e=>e.toLowerCase())),fu=(e,t=!1)=>(t?FU:BU).has(t?e.toLowerCase():e),tI=(e,t=!1)=>t?UU.has(e.toLowerCase()):pu.some(n=>n===e),nI=["*"],sa=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...nI]}),yo=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var mc=/^[a-f0-9-]{36}$/,fI="Anyray",py=4,gc=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],wc=["deploymentMode","awaitingSignIn"],QU=["inferenceGatewayApiKey","awaitingSignIn"],mI=[...[...gc,...wc].filter(e=>!QU.includes(e)),"configLibrary","_meta.json"],Jn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wt=e=>structuredClone(e),hc=async e=>{try{return await hu(e),!0}catch{return!1}},eW=async e=>{try{let t=await VU(pI(e)),n=zU(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},tW=async e=>{try{return await hu(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":eW(e)}},bn=(e={})=>{let t=(e.home??ZU)(),n=(e.username??(()=>XU().username))(),r=qt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",qt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:qt(r,"configLibrary"),meta:qt(r,"configLibrary","_meta.json"),appConfig:qt(r,"claude_desktop_config.json"),helper:qt(t,".anyray","bin","claude-desktop-credential-helper"),journal:qt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},fy=()=>{let e=lI("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"},yu=()=>fy()!=="not_running",hI=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],nW=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...hI(t)]}},my=(e="json")=>{let t=Rn(hI(e)),n=rI(t.command),r=rI(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ne()&&(!o||r!==n)}},rW=e=>`'${e.replace(/'/g,`'"'"'`)}'`,hy=e=>[e.command,...e.args].map(rW).join(" "),oW=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!fs(e.command))throw new Error("the credential helper executable is not absolute")},yI=(e,t)=>{oW(e);let n=gu(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!fs(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},gI=e=>(yI(e,"--json"),`#!/bin/sh
|
|
192
|
+
`).filter(d=>d.trim().length>0),i=gU(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 wU(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await yU(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as AU}from"node:crypto";import{promises as Er}from"node:fs";import{homedir as vU,platform as SU}from"node:os";import{join as $t}from"node:path";var XS=448,xr="local_",IU="local-agent-mode-sessions",sy="-3p",EU="cowork_account_settings.json",Rr=(e={})=>{let t=(e.home??vU)(),n=e.runtimePlatform??SU(),r=e.env??process.env;if(n==="darwin")return $t(t,"Library","Application Support",`Claude${sy}`);if(n==="win32"){let o=r.LOCALAPPDATA??$t(t,"AppData","Local");return $t(o,`Claude${sy}`)}return null},aa=(e={})=>{let t=Rr(e);return t?t.slice(0,-sy.length):null},iy=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)}`},lu=async e=>{let t=$t(e,IU),n;try{n=(await Er.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 Er.readdir($t(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=$t(t,o,s);try{await Er.access($t(i,EU)),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]}},cy=async e=>{try{let t=await Er.readdir(e);return new Set(t.filter(n=>n.startsWith(xr)&&n.endsWith(".json")).map(n=>n.slice(xr.length,-5)))}catch{return new Set}},ds=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),xU=async(e,t)=>{let n=`${xr}${t.sessionId}`,r=$t(e,n),o=$t(r,"outputs"),a=$t(r,".claude"),s=$t(a,"projects",iy(o));await Er.mkdir(o,{recursive:!0,mode:XS}),await Er.mkdir(s,{recursive:!0,mode:XS});let i=$t(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${AU()}`;await Er.copyFile(t.transcriptPath,c),await Er.chmod(c,384),await Er.rename(c,i);let l=t.createdAt??Date.now();await q($t(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})},zS=async(e,t)=>{let n=await cy(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!ds(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await xU(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as us}from"node:fs";import{homedir as RU}from"node:os";import{dirname as OU,join as uc}from"node:path";var _U=448,TU=["Documents","Claude","Projects"],PU="spaces.json",DU=(e={})=>uc((e.home??RU)(),...TU),NU=async e=>{try{let t=JSON.parse(await us.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}}},LU=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},ly=async e=>{try{return await us.access(e),!0}catch{return!1}},$U=async(e,t,n)=>{let r=uc(t,LU(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await ly(r)?o:r;return a===o&&await ly(o)?null:(await us.mkdir(OU(a),{recursive:!0}),await us.cp(e,a,{recursive:!0}),a)},MU=async e=>{try{let t=(await us.readFile(uc(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},qS=async e=>{let t=DU({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=uc(e.storageDir,PU),{spaces:a,readable:s}=await NU(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=uc(e.stagedProjectsDir,l.dirName);try{if(!await ly(d)){n.failed+=1;continue}let u=await $U(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await MU(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 us.mkdir(e.storageDir,{recursive:!0,mode:_U}),await q(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as WU}from"node:crypto";import{execFile as HU,spawnSync as lI}from"node:child_process";import{constants as dI}from"node:fs";import{access as hu,chmod as GU,mkdir as KU,readdir as VU,readFile as uy,rename as jU,rm as ps,stat as uI,writeFile as YU}from"node:fs/promises";import{homedir as ZU,platform as JU,userInfo as XU}from"node:os";import{basename as zU,dirname as pI,isAbsolute as fs,join as qt,resolve as rI}from"node:path";import{isDeepStrictEqual as fc,promisify as qU}from"node:util";var ho="__anyray-claude-desktop-credential",pc="__anyray-claude-desktop-bootstrap-headers";var du=(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>\`.`],uu=["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."],QS=(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 pu=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],eI=["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"],BU=new Set(eI),FU=new Set(eI.map(e=>e.toLowerCase())),UU=new Set(pu.map(e=>e.toLowerCase())),fu=(e,t=!1)=>(t?FU:BU).has(t?e.toLowerCase():e),tI=(e,t=!1)=>t?UU.has(e.toLowerCase()):pu.some(n=>n===e),nI=["*"],sa=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...nI]}),yo=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var mc=/^[a-f0-9-]{36}$/,fI="Anyray",py=4,gc=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],wc=["deploymentMode","awaitingSignIn"],QU=["inferenceGatewayApiKey","awaitingSignIn"],mI=[...[...gc,...wc].filter(e=>!QU.includes(e)),"configLibrary","_meta.json"],Jn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wt=e=>structuredClone(e),hc=async e=>{try{return await hu(e),!0}catch{return!1}},eW=async e=>{try{let t=await VU(pI(e)),n=zU(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},tW=async e=>{try{return await hu(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":eW(e)}},bn=(e={})=>{let t=(e.home??ZU)(),n=(e.username??(()=>XU().username))(),r=qt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",qt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:qt(r,"configLibrary"),meta:qt(r,"configLibrary","_meta.json"),appConfig:qt(r,"claude_desktop_config.json"),helper:qt(t,".anyray","bin","claude-desktop-credential-helper"),journal:qt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},fy=()=>{let e=lI("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"},yu=()=>fy()!=="not_running",hI=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],nW=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...hI(t)]}},my=(e="json")=>{let t=Rn(hI(e)),n=rI(t.command),r=rI(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ne()&&(!o||r!==n)}},rW=e=>`'${e.replace(/'/g,`'"'"'`)}'`,hy=e=>[e.command,...e.args].map(rW).join(" "),oW=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!fs(e.command))throw new Error("the credential helper executable is not absolute")},yI=(e,t)=>{oW(e);let n=gu(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!fs(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},gI=e=>(yI(e,"--json"),`#!/bin/sh
|
|
193
193
|
exec ${hy(e)}
|
|
194
194
|
`),aW=`#!/bin/sh
|
|
195
195
|
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,wI=e=>{yI(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),ho]};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 ${hy(t)}`,""].join(`
|
|
@@ -200,7 +200,7 @@ exec `;if(!e.startsWith(t)||!e.endsWith(`
|
|
|
200
200
|
# Anyray subscription pass-through credential helper`,dW=e=>{let t=gu(e.command);if(!(!fs(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!fs(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=$(${hy(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
201
|
`)},uW=e=>{if(!e.startsWith(lW))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=yy(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return dW(a)===e?a:void 0},bI=e=>iW(e)??cW(e)??uW(e),pW=async()=>{let e=lI("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},fW=async e=>{let t=[e.command,...gu(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>uI(r)))).every(r=>r.isFile())?(await hu(e.command,dI.X_OK),!0):!1}catch{return!1}},mW=0,wu=async(e,t,n)=>{await KU(pI(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${mW++}.tmp`;try{await YU(r,t,{mode:n}),await GU(r,n),await jU(r,e)}catch(o){throw await ps(r,{force:!0}).catch(()=>{}),o}},Or=async(e,t)=>{await wu(e,`${JSON.stringify(t,null,2)}
|
|
202
202
|
`,384)},Xn=async e=>{if(!await hc(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await uy(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!Jn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},bc=async e=>{if(!await hc(e))return{present:!1};let t=await uI(e);return{present:!0,content:await uy(e,"utf-8"),mode:t.mode&511}},kI=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:wt(e[t])}:{present:!1},dy=(e,t,n)=>{n.present?e[t]=wt(n.value):delete e[t]},oI=e=>Jn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),hW=e=>Jn(e)&&oI(e.original)&&oI(e.lastWritten),yW=e=>Jn(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),aI=(e,t)=>Jn(e)&&t.every(n=>hW(e[n])),gW=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],wW=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],gy=(e,t,n,r)=>!(!Jn(e)||e.version!==n||typeof e.configId!="string"||!mc.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!mc.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!Jn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==fI||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!aI(e.config,r)||r.some(o=>e.config[o].original.present)||!aI(e.deployment,wc)||!Jn(e.helper)||e.helper.path!==t.helper||!yW(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),bW=(e,t)=>gy(e,t,py,gc),kW=(e,t)=>gy(e,t,2,gW),CW=(e,t)=>gy(e,t,3,wW),AW=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),sI=e=>({...e,version:py,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),wy=async e=>{if(!await hc(e.journal))return;let t;try{t=JSON.parse(await uy(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(bW(t,e))return t;if(CW(t,e))return sI(t);if(kW(t,e))return sI(AW(t));throw new Error(`${e.journal} is not a valid ownership journal`)},iI=async(e,t)=>{await wu(e,`${JSON.stringify(t,null,2)}
|
|
203
|
-
`,384)},yc=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!mc.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(!Jn(o)||typeof o.id!="string"||!mc.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},vW=async(e,t,n)=>{let r=await Xn(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:wt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[wt(t.metaEntry)]}}}let c=yc(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!fc(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:wt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...wt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=yc(r.value);let c=qt(e.library,`${o}.json`);if(!await hc(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=wt(r.value.entries)}let s=n();if(!mc.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await hc(qt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:fI};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?wt(r.value):{},appliedId:s,entries:[...a,i]}}},SW=(e,t)=>{let n=sa(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},CI=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),IW=async(e,t,n,r,o,a,s)=>{let i=CI(),c=Object.fromEntries(gc.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(wc.map(d=>[d,{original:s?.deployment[d].original??kI(r.value,d),lastWritten:i[d]}]));return{version:py,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??wt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await bc(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},mu=e=>({status:"manual",messages:[e]}),EW=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}`)]}},xW=qU(HU),RW=new Set(pu),OW=async e=>{try{let{stdout:t}=await xW("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return Jn(n)?Object.keys(n):void 0}catch{return}},ia=async(e,t={})=>{let n=t.readManagedPolicyKeys??OW;for(let r of e.managedPolicies){let o=await tW(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=>fu(i)&&!RW.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},by=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.`},ky=e=>(e.platform??JU)()==="darwin",AI=async(e,t,n={})=>{if(!ky(n))return mu("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??yu)()&&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=bn(n),a=await ia(o,n);if(a&&r.push({audience:"admin",message:by(a)}),r.length>0)return EW(r);let s=!1,i=!1,c=[o.journal];try{let l=se(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??pW)())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=nW((n.credentialCommand??(()=>my(d)))(),d),p=sW(u),m=await wy(o),f=await bc(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 vW(o,m,n.randomUUID??WU),g=qt(o.library,`${h.configId}.json`);c=[o.journal,o.helper,g,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await Xn(g),w=await Xn(o.appConfig),b=SW(e,o.helper),A=await IW(o,h,y,w,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 iI(o.journal,A),i=!0,await wu(o.helper,p,448),A.helper.previousWritten!==void 0&&(delete A.helper.previousWritten,await iI(o.journal,A));let C=wt(y.value);for(let S of gc)dy(C,S,b[S]);await Or(g,C),h.metaToWrite&&await Or(o.meta,h.metaToWrite);let x=wt(w.value),O=CI();for(let S of wc)dy(x,S,O[S]);return await Or(o.appConfig,x),{status:"configured",changedFiles:[o.journal,o.helper,g,...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.",...du(Tt("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.`]}:mu(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},cI=(e,t,n,r)=>{let o=wt(e);for(let a of n){let s=t[a];fc(kI(e,a),s.lastWritten)?dy(o,a,s.original):r.push(a)}return o},vI=async(e,t={})=>{if(!ky(t))return{status:"not-found",messages:[]};if((t.appRunning??yu)())return mu("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=bn(t);try{let r=await wy(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=qt(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 Xn(o),i=s.value;s.present&&(i=cI(s.value,r.config,gc,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await Xn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let f=yc(l.value),h=wt(l.value.entries),g=h.findIndex(b=>b.id===r.configId),y=g>=0?h[g]:void 0,w=y!==void 0&&fc(y,r.metaEntry);if(y!==void 0&&!w&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=wt(l.value),f===r.configId){let b=r.originalAppliedId;b&&h.some(A=>A.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&w?(h.splice(g,1),d.entries=h):c&&y===void 0&&(d.entries=h)}else{let b=fc(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&f!==r.configId?(w&&h.splice(g,1),d={...wt(l.value),entries:h}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await ps(o,{force:!0}):await Or(o,i)),l.present&&(u?await ps(n.meta,{force:!0}):fc(l.value,d)||await Or(n.meta,d));let p=await Xn(n.appConfig);if(p.present){let f=cI(p.value,r.deployment,wc,a);!r.deploymentFileExisted&&Object.keys(f).length===0?await ps(n.appConfig,{force:!0}):await Or(n.appConfig,f)}else r.deploymentFileExisted&&a.push("deployment config file");let m=await bc(n.helper);return m.present&&(m.content===r.helper.lastWritten||m.content===r.helper.previousWritten)?r.helper.original.present?await wu(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await ps(n.helper,{force:!0}):(m.present||r.helper.original.present)&&a.push("credential helper"),await ps(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?[]:uu]}}catch(r){return mu(`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.`)}},Cy=async(e,t={})=>{if(!ky(t))return!1;let n=bn(t);if(await ia(n,t))return!1;try{let r=await Xn(n.meta);if(!r.present)return!1;let o=yc(r.value),a=await Xn(qt(n.library,`${o}.json`)),s=await Xn(n.appConfig);if(!a.present||!s.present)return!1;await hu(n.helper,dI.X_OK);let i=dt(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}},SI=async(e={})=>{try{let t=bn(e),n=await bc(t.helper);if(!n.present||typeof n.content!="string")return;let r=bI(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},II=async(e,t={})=>{if(!await Cy(e,t))return!1;let n=bn(t);try{let r=await wy(n);if(!r)return!1;let o=await Xn(n.meta);if(!o.present||yc(o.value)!==r.configId)return!1;let a=await bc(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=bI(a.content??"");return s?await(t.helperLauncherAvailable??fW)(s):!1}catch{return!1}};import{createHash as WI,randomUUID as HI}from"node:crypto";import{spawn as _W,spawnSync as TW}from"node:child_process";import{link as Ry,mkdir as Ay,open as GI,readFile as vy,readdir as KI,rename as VI,rm as kn,stat as jI}from"node:fs/promises";import{homedir as Oy}from"node:os";import{basename as YI,dirname as Cc,join as ks,win32 as PW}from"node:path";import{isDeepStrictEqual as ms}from"node:util";var Fe="HKCU\\SOFTWARE\\Policies\\Claude",kc="HKLM\\SOFTWARE\\Policies\\Claude",Au=5,Cs="inferenceGatewayApiKey",He=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",Cs],EI=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",Cs],xI=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",Cs],RI=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",Cs],ZI="Managed by anyray-connect; dynamic credential only.",DW=e=>/^[A-Za-z]:[\\/]/.test(e)&&PW.isAbsolute(e),OI=e=>{if(!DW(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)},JI=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!OI(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&&!OI(e.args[0]))throw new Error("the credential helper does not use print-key --json")},_y=(e={})=>ks((e.home??Oy)(),".anyray","bin","claude-desktop-credential-helper.cmd"),LW=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},NW=e=>(JI(e),["@echo off",`REM ${ZI}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(LW).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
203
|
+
`,384)},yc=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!mc.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(!Jn(o)||typeof o.id!="string"||!mc.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},vW=async(e,t,n)=>{let r=await Xn(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:wt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[wt(t.metaEntry)]}}}let c=yc(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!fc(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:wt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...wt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=yc(r.value);let c=qt(e.library,`${o}.json`);if(!await hc(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=wt(r.value.entries)}let s=n();if(!mc.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await hc(qt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:fI};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?wt(r.value):{},appliedId:s,entries:[...a,i]}}},SW=(e,t)=>{let n=sa(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},CI=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),IW=async(e,t,n,r,o,a,s)=>{let i=CI(),c=Object.fromEntries(gc.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(wc.map(d=>[d,{original:s?.deployment[d].original??kI(r.value,d),lastWritten:i[d]}]));return{version:py,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??wt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await bc(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},mu=e=>({status:"manual",messages:[e]}),EW=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}`)]}},xW=qU(HU),RW=new Set(pu),OW=async e=>{try{let{stdout:t}=await xW("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return Jn(n)?Object.keys(n):void 0}catch{return}},ia=async(e,t={})=>{let n=t.readManagedPolicyKeys??OW;for(let r of e.managedPolicies){let o=await tW(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=>fu(i)&&!RW.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},by=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.`},ky=e=>(e.platform??JU)()==="darwin",AI=async(e,t,n={})=>{if(!ky(n))return mu("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??yu)()&&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=bn(n),a=await ia(o,n);if(a&&r.push({audience:"admin",message:by(a)}),r.length>0)return EW(r);let s=!1,i=!1,c=[o.journal];try{let l=se(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??pW)())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=nW((n.credentialCommand??(()=>my(d)))(),d),p=sW(u),m=await wy(o),f=await bc(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 vW(o,m,n.randomUUID??WU),g=qt(o.library,`${h.configId}.json`);c=[o.journal,o.helper,g,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await Xn(g),w=await Xn(o.appConfig),b=SW(e,o.helper),A=await IW(o,h,y,w,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 iI(o.journal,A),i=!0,await wu(o.helper,p,448),A.helper.previousWritten!==void 0&&(delete A.helper.previousWritten,await iI(o.journal,A));let C=wt(y.value);for(let S of gc)dy(C,S,b[S]);await Or(g,C),h.metaToWrite&&await Or(o.meta,h.metaToWrite);let x=wt(w.value),O=CI();for(let S of wc)dy(x,S,O[S]);return await Or(o.appConfig,x),{status:"configured",changedFiles:[o.journal,o.helper,g,...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.",...du(Tt("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.`]}:mu(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},cI=(e,t,n,r)=>{let o=wt(e);for(let a of n){let s=t[a];fc(kI(e,a),s.lastWritten)?dy(o,a,s.original):r.push(a)}return o},vI=async(e,t={})=>{if(!ky(t))return{status:"not-found",messages:[]};if((t.appRunning??yu)())return mu("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=bn(t);try{let r=await wy(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=qt(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 Xn(o),i=s.value;s.present&&(i=cI(s.value,r.config,gc,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await Xn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let f=yc(l.value),h=wt(l.value.entries),g=h.findIndex(b=>b.id===r.configId),y=g>=0?h[g]:void 0,w=y!==void 0&&fc(y,r.metaEntry);if(y!==void 0&&!w&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=wt(l.value),f===r.configId){let b=r.originalAppliedId;b&&h.some(A=>A.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&w?(h.splice(g,1),d.entries=h):c&&y===void 0&&(d.entries=h)}else{let b=fc(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&f!==r.configId?(w&&h.splice(g,1),d={...wt(l.value),entries:h}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await ps(o,{force:!0}):await Or(o,i)),l.present&&(u?await ps(n.meta,{force:!0}):fc(l.value,d)||await Or(n.meta,d));let p=await Xn(n.appConfig);if(p.present){let f=cI(p.value,r.deployment,wc,a);!r.deploymentFileExisted&&Object.keys(f).length===0?await ps(n.appConfig,{force:!0}):await Or(n.appConfig,f)}else r.deploymentFileExisted&&a.push("deployment config file");let m=await bc(n.helper);return m.present&&(m.content===r.helper.lastWritten||m.content===r.helper.previousWritten)?r.helper.original.present?await wu(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await ps(n.helper,{force:!0}):(m.present||r.helper.original.present)&&a.push("credential helper"),await ps(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?[]:uu]}}catch(r){return mu(`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.`)}},Cy=async(e,t={})=>{if(!ky(t))return!1;let n=bn(t);if(await ia(n,t))return!1;try{let r=await Xn(n.meta);if(!r.present)return!1;let o=yc(r.value),a=await Xn(qt(n.library,`${o}.json`)),s=await Xn(n.appConfig);if(!a.present||!s.present)return!1;await hu(n.helper,dI.X_OK);let i=dt(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}},SI=async(e={})=>{try{let t=bn(e),n=await bc(t.helper);if(!n.present||typeof n.content!="string")return;let r=bI(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},II=async(e,t={})=>{if(!await Cy(e,t))return!1;let n=bn(t);try{let r=await wy(n);if(!r)return!1;let o=await Xn(n.meta);if(!o.present||yc(o.value)!==r.configId)return!1;let a=await bc(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=bI(a.content??"");return s?await(t.helperLauncherAvailable??fW)(s):!1}catch{return!1}};import{createHash as WI,randomUUID as HI}from"node:crypto";import{spawn as _W,spawnSync as TW}from"node:child_process";import{link as Ry,mkdir as Ay,open as GI,readFile as vy,readdir as KI,rename as VI,rm as kn,stat as jI}from"node:fs/promises";import{homedir as Oy}from"node:os";import{basename as YI,dirname as Cc,join as ks,win32 as PW}from"node:path";import{isDeepStrictEqual as ms}from"node:util";var Fe="HKCU\\SOFTWARE\\Policies\\Claude",kc="HKLM\\SOFTWARE\\Policies\\Claude",Au=5,Cs="inferenceGatewayApiKey",He=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",Cs],EI=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",Cs],xI=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",Cs],RI=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",Cs],ZI="Managed by anyray-connect; dynamic credential only.",DW=e=>/^[A-Za-z]:[\\/]/.test(e)&&PW.isAbsolute(e),OI=e=>{if(!DW(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)},JI=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!OI(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&&!OI(e.args[0]))throw new Error("the credential helper does not use print-key --json")},_y=(e={})=>ks((e.home??Oy)(),".anyray","bin","claude-desktop-credential-helper.cmd"),NW=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},LW=e=>(JI(e),["@echo off",`REM ${ZI}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(NW).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
204
204
|
`)),$W=e=>{let t="";for(let n=0;n<e.length;n++){if(e[n]!=="%"){t+=e[n];continue}if(e[n+1]!=="%")return;t+="%",n++}return t},XI=e=>{let t=e.split(`\r
|
|
205
205
|
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${ZI}`||t[2]!=="setlocal DisableDelayedExpansion"||t[4]!=="exit /b %ERRORLEVEL%"||t[5]!==""||!t[3].startsWith('"')||!t[3].endsWith('"'))return;let r=t[3].slice(1,-1).split('" "').map($W);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return JI(s),s}catch{return}},MW=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>jI(r)))).every(r=>r.isFile())}catch{return!1}},BW=async(e,t)=>{let n=XI(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??MW)(n)}catch{return!1}},Sy=e=>({sha256:ca(e),content:e}),_I=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Qt(t,["sha256","content"])&&jW(t.sha256)&&typeof t.content=="string"&&ca(t.content)===t.sha256&&XI(t.content)!==void 0},Ty=()=>{let e=TW("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"},Py=()=>Ty()!=="not_running",FW=async(e,t)=>{await Ay(Cc(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await GI(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await Ry(n,e)}finally{await kn(n,{force:!0}).catch(()=>{})}},UW=e=>`${YI(e)}.anyray-old-`,WW=e=>`${e}.anyray-old-${process.pid}-${HI()}`,zI=async(e,t)=>{try{await Ry(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await kn(t,{force:!0}),!0},ku=async(e,t,n,r,o)=>{let a=WW(e),s=n===void 0?void 0:ca(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${HI()}`,c=!1;try{if(i&&n!==void 0){let d=await GI(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 VI(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ws(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await Ry(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await bs(e)!==s))throw new Error("credential helper publication verification failed");await kn(a,{force:!0}),c=!1}catch(l){throw c&&await zI(e,a).catch(()=>!1),l}finally{i&&await kn(i,{force:!0}).catch(()=>{})}},Iy=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,HW=String.raw`
|
|
206
206
|
$ErrorActionPreference = 'Stop'
|
|
@@ -272,14 +272,14 @@ try {
|
|
|
272
272
|
} catch {
|
|
273
273
|
exit 6
|
|
274
274
|
}`,Tr=async e=>new Promise((t,n)=>{let r=_W("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",HW],{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(Iy(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(Iy({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),en=(e={})=>ks((e.home??Oy)(),".anyray","claude-desktop-windows.json"),GW=e=>ks((e.home??Oy)(),".anyray","claude-desktop-windows.lock"),gs=class extends Error{},KW=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Dy=async e=>{let t=GW(e);await Ay(Cc(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=WI("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=ks(t,"owner.json");try{await Ay(t,{mode:448}),await ve(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
275
|
-
`)}catch(a){if(a.code!=="EEXIST")throw await kn(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await vy(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!KW(i.pid)}catch{try{s=Date.now()-(await jI(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new gs;await kn(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await vy(o,"utf8")).nonce===r&&await kn(t,{recursive:!0,force:!0})}catch{}}}throw new gs},qI=()=>Object.fromEntries(He.map(e=>[e,{present:!1}])),ca=e=>WI("sha256").update(e).digest("hex"),VW=(e,t)=>t.present?e===Cs?{present:!0,type:t.type,sha256:ca(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},hs=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?ca(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)),vu=(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===Cs?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},TI=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Qt(e,He)&&He.every(t=>vu(e[t],t)),PI=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Qt(e,EI)&&EI.every(t=>vu(e[t],t)),jW=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),
|
|
276
|
-
`;t.writeJournalFile?await t.writeJournalFile(n,r):await ve(n,r)},eH=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,tH=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),nH=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),rH=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),oH=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===rH(t).toUpperCase(),FI=(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},aH=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,sH=(e,t)=>{if(!fu(e,!0))return!1;let n=aH(t);if(nH.has(n))return!1;if(tH.has(n))return n==="REG_EXPAND_SZ"?!0:!tI(e,!0)},iH=(e,t)=>{let n=qI(),r=!1,o=!1,a=!1,s=t.toUpperCase()===kc.toUpperCase(),i=(l,d)=>{if(!s)return;let u=sH(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),FI(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||oH(d,t))continue;let u=eH.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),FI(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},_r=async(e,t=Fe)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:qI(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return iH(n.stdout,t)},go=async e=>{let t=await _r(e,kc);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...He.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},My=e=>e.unparsed?`This machine may have a Claude policy under ${kc} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${kc} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${kc} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Su=(e,t)=>yo(sa(e,t)),QI=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],cH=(e,t)=>{let n=Su(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}]}))},lH=(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}}),dH=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,Ey=e=>Object.fromEntries(He.map(t=>[t,VW(t,e[t])])),UI=(e,t,n,r)=>({version:Au,registryKey:Fe,keyExisted:e,lastWritten:Ey(t),helper:{path:n,lastWritten:Sy(r)}}),uH=(e,t,n,r,o,a)=>({version:Au,registryKey:Fe,keyExisted:e,lastWritten:Ey(t),pending:Ey(n),helper:{path:r,...o?{lastWritten:Sy(o)}:{},pending:Sy(a)}}),xy=(e,t,n)=>hs(n,e.lastWritten[t])||e.pending!==void 0&&hs(n,e.pending[t]),ws=async e=>{try{let t=await vy(e,"utf8");return{content:t,sha256:ca(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},bs=async e=>(await ws(e))?.sha256,ys=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Cu=async(e,t)=>{let n=UW(e),r;try{r=await KI(Cc(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>ks(Cc(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([ws(e),ws(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ys(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await zI(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ys(t,s.sha256)&&ys(t,i.sha256)){await kn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},By=async(e,t,n)=>(n.present?await e(QI(Fe,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Fe,"/v",t,"/f"])).code===0,pH=async(e,t,n)=>{let r=!0,o=await _r(e);for(let a of He)if(!ms(o.values[a],t[a])){if(!ms(o.values[a],n[a])){r=!1;continue}await By(e,a,t[a])||(r=!1),o=await _r(e)}return r&&He.every(a=>ms(o.values[a],t[a]))},st=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[en(n)]}}),eE=async(e,t,n,r={})=>{if(!Pe(t))return st("A valid personal ark_ gateway key is required.",!1,r);let o=_y(r),a;try{a=NW((r.credentialCommand??my)())}catch{return st("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=ca(a),i=r.runReg??Tr,c=en(r),l;if(!n.dryRun)try{l=await Dy(r)}catch(h){return st(h instanceof gs?"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 go(i);if(h)return st(My(h),!1,r);let g=await $y(r,!n.dryRun);n.dryRun||await Cu(o,g);let y=await _r(i),w=cH(e,o),b=await ws(o),A=b?.sha256,C=!1;if(d=g,u=y,p=w,g){let S=He.find(E=>!xy(g,E,y.values[E]));if(S)return st(`Claude's ${S} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(A!==void 0&&!ys(g,A))return st(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=dH(g)}else{if(A!==void 0&&A!==s)return st(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let S=y.foreignState||He.some(I=>y.values[I].present),E=He.every(I=>ms(y.values[I],w[I])),T=He.every(I=>ms(y.values[I],lH(e,t.trim())[I]));if(S&&!E&&!T)return st(`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(C=T,E&&A===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 bu(UI(y.keyPresent,w,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Fe} into the ownership journal.`]})}if(C){let S=!0;try{S=(r.appRunning??Py)()}catch{}if(S)return st("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let x=uH(g?.keyExisted??y.keyPresent,y.values,w,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 bu(x,r),f=!0;for(let S of He){let E=await _r(i);if(!hs(E.values[S],x.lastWritten[S])&&!hs(E.values[S],x.pending[S]))throw new Error("registry value changed during apply");if(!ms(E.values[S],w[S])&&!await By(i,S,w[S]))throw new Error("registry write failed")}let O=await _r(i);if(!He.every(S=>hs(O.values[S],x.pending[S])))throw new Error("registry verification failed");if(A!==s&&(A===void 0?await FW(o,a):await ku(o,A,a,"apply",r)),await bs(o)!==s)throw new Error("credential helper verification failed");return await bu(UI(x.keyExisted,w,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.",...du(Tt("migrate"))]}}catch{if(!f||!u||!p||!m)return st("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Cu(o,m);let h=!0,g=await ws(o),y=m.helper.pending;if(g?.sha256!==m.helper.lastWritten?.sha256&&(y!==void 0&&g?.sha256===y.sha256?m.helper.lastWritten?(await ku(o,y.sha256,m.helper.lastWritten.content,"rollback",r),h=await bs(o)===m.helper.lastWritten.sha256):await ku(o,y.sha256,void 0,"rollback",r):h=g===void 0&&m.helper.lastWritten===void 0),h&&await pH(i,u.values,p))return d?await bu(d,r):await kn(c,{force:!0}),st("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return st("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?.()}},tE=async(e,t={})=>{let n=t.runReg??Tr,r=en(t),o;if(!e.dryRun)try{o=await Dy(t)}catch(a){return st(a instanceof gs?"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 $y(t,!e.dryRun);a&&!e.dryRun&&await Cu(a.helper.path,a);let s=await _r(n);if(!a)return He.filter(f=>s.values[f].present).length>0?st(`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&&!xy(a,m,s.values[m])),c=await bs(a.helper.path),l=c!==void 0&&!ys(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 _r(n)).values[m];if(h.present){if(!xy(a,m,h)){u.add(m);continue}await By(n,m,{present:!1})||(d=!0)}}let p=await bs(a.helper.path);if(p!==void 0)if(ys(a,p))try{await ku(a.helper.path,p,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?st(`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 kn(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?[]:uu]})}catch{return st(`Could not safely inspect or revert ${Fe}; no unproven value was removed.`,!1,t)}finally{await o?.()}},nE=async(e,t={})=>{let n=t.runReg??Tr;if(!await R(en(t)))return;let r;try{r=await Dy(t);let o=await $y(t);if(o&&await Cu(o.helper.path,o),!o||o.pending||await go(n)!==void 0)return;let a=await _r(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===dt(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&He.every(l=>hs(a.values[l],o.lastWritten[l]))))return;let i=await bs(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 BW(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?.()}},rE=async(e,t={})=>await nE(e,t)!==void 0,oE=async(e,t={})=>await nE(e,t)==="dynamic";var As=(e=sE())=>e==="win32"?Py:yu,Uy=(e=sE())=>e==="win32"?Ty:fy,Fy="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Eu=async(e,t={})=>{let n=(t.profileRoot??Rr)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Fy};if((t.appRunning??As(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await aE.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 lu(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 "+Fy}:{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??ZS)();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=Iu(t.stagingRoot??mH(),`anyray-history-${process.pid}-${fH()}`);try{let s=await(t.runImporter??JS)({binary:o,exportPath:e,configDir:Iu(a,"config"),workDir:Iu(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. "+Fy};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 zS(r.dir,s.conversations),c=await qS({stagedProjectsDir:Iu(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 aE.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Mt}from"node:fs";import{homedir as MH}from"node:os";import{join as An,sep as BH}from"node:path";import{isDeepStrictEqual as _u}from"node:util";import{constants as dE}from"node:fs";import{promises as j}from"node:fs";import{dirname as vs,isAbsolute as Hy,join as re,relative as xu,resolve as Cn,sep as Ac}from"node:path";import{randomUUID as Tu}from"node:crypto";var zn=448,vc=384,uE=448,hH=4,Gy=3e4,pE=5e3,yH=10*6e4,fE={config:["skill","plugin","local-mcp"],session:["code","cowork"]},Pu=e=>e?["config","session"]:["config"],Sc=(e,t)=>(e??["config","session"]).includes(t),mE=["carried","pending","nothing_to_carry","not_routed","unreadable","unsupported","unknown"],hE={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"},Wy=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),Ge=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ic=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),yE=(e,t)=>{let n=xu(Cn(e),Cn(t));return n===""||!n.startsWith(`..${Ac}`)&&n!==".."&&!Hy(n)},qn=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 It(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},It=e=>e instanceof Error&&"code"in e,gH=e=>{try{return process.kill(e,0),!0}catch(t){return It(t)&&t.code==="EPERM"}},gE=e=>e===0?"owner.json":`owner.${e}.json`,Ru=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=re(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}},wE=e=>{if(e.pid===void 0||!gH(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Gy&&t-e.createdAtMs>yH},wH=async e=>{let t=`${e}.anyray-lock`;await j.mkdir(vs(t),{recursive:!0,mode:zn});let n=Tu(),r,o=!1;try{await j.mkdir(t,{mode:zn}),o=!0}catch(i){if(!It(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Ru(t);if(d){if(!wE(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)<=Gy)return}let l=re(t,gE(c));try{await j.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
275
|
+
`)}catch(a){if(a.code!=="EEXIST")throw await kn(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await vy(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!KW(i.pid)}catch{try{s=Date.now()-(await jI(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new gs;await kn(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await vy(o,"utf8")).nonce===r&&await kn(t,{recursive:!0,force:!0})}catch{}}}throw new gs},qI=()=>Object.fromEntries(He.map(e=>[e,{present:!1}])),ca=e=>WI("sha256").update(e).digest("hex"),VW=(e,t)=>t.present?e===Cs?{present:!0,type:t.type,sha256:ca(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},hs=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?ca(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)),vu=(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===Cs?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},TI=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Qt(e,He)&&He.every(t=>vu(e[t],t)),PI=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Qt(e,EI)&&EI.every(t=>vu(e[t],t)),jW=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),Ny=(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===_y(t)&&(n.lastWritten===void 0||_I(n.lastWritten))&&(n.pending===void 0||_I(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},YW=(e,t)=>Qt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Au&&e.registryKey===Fe&&typeof e.keyExisted=="boolean"&&TI(e.lastWritten)&&(e.pending===void 0||TI(e.pending))&&Ny(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),ZW=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"&&PI(e.lastWritten)&&(e.pending===void 0||PI(e.pending)),DI=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Qt(e,xI)&&xI.every(t=>vu(e[t],t)),JW=(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"&&DI(e.lastWritten)&&(e.pending===void 0||DI(e.pending))&&Ny(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),NI=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Qt(e,RI)&&RI.every(t=>vu(e[t],t)),XW=(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"&&NI(e.lastWritten)&&(e.pending===void 0||NI(e.pending))&&Ny(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),LI=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),Ly=e=>{let{pending:t,...n}=e;return{...n,version:Au,lastWritten:LI(e.lastWritten),...t?{pending:LI(t)}:{}}},$I=e=>({...e,chatTabEnabled:{present:!1}}),zW=e=>{let{pending:t,...n}=e;return Ly({...n,version:4,lastWritten:$I(e.lastWritten),...t?{pending:$I(t)}:{}})},MI=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),qW=(e,t)=>Ly({version:4,registryKey:Fe,keyExisted:e.keyExisted,lastWritten:MI(e.lastWritten),...e.pending?{pending:MI(e.pending)}:{},helper:{path:_y(t)}}),$y=async(e,t=!0)=>{let n=en(e),r=Cc(n),o=`${YI(n)}.anyray-old-`,a=(await KI(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>ks(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 VI(a[0],n):s=a[0]}let i=await F(s),c=ZW(i)?qW(i,e):JW(i,e)?zW(i):XW(i,e)?Ly(i):YW(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>kn(l,{force:!0}))),c},BI=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),QW=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Fe,keyExisted:e.keyExisted,lastWritten:BI(e.lastWritten),...e.pending?{pending:BI(e.pending)}:{}}:e,bu=async(e,t)=>{let n=en(t),r=`${JSON.stringify(QW(e),null,2)}
|
|
276
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await ve(n,r)},eH=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,tH=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),nH=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),rH=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),oH=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===rH(t).toUpperCase(),FI=(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},aH=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,sH=(e,t)=>{if(!fu(e,!0))return!1;let n=aH(t);if(nH.has(n))return!1;if(tH.has(n))return n==="REG_EXPAND_SZ"?!0:!tI(e,!0)},iH=(e,t)=>{let n=qI(),r=!1,o=!1,a=!1,s=t.toUpperCase()===kc.toUpperCase(),i=(l,d)=>{if(!s)return;let u=sH(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),FI(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||oH(d,t))continue;let u=eH.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),FI(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},_r=async(e,t=Fe)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:qI(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return iH(n.stdout,t)},go=async e=>{let t=await _r(e,kc);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...He.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},My=e=>e.unparsed?`This machine may have a Claude policy under ${kc} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${kc} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${kc} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Su=(e,t)=>yo(sa(e,t)),QI=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],cH=(e,t)=>{let n=Su(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}]}))},lH=(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}}),dH=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,Ey=e=>Object.fromEntries(He.map(t=>[t,VW(t,e[t])])),UI=(e,t,n,r)=>({version:Au,registryKey:Fe,keyExisted:e,lastWritten:Ey(t),helper:{path:n,lastWritten:Sy(r)}}),uH=(e,t,n,r,o,a)=>({version:Au,registryKey:Fe,keyExisted:e,lastWritten:Ey(t),pending:Ey(n),helper:{path:r,...o?{lastWritten:Sy(o)}:{},pending:Sy(a)}}),xy=(e,t,n)=>hs(n,e.lastWritten[t])||e.pending!==void 0&&hs(n,e.pending[t]),ws=async e=>{try{let t=await vy(e,"utf8");return{content:t,sha256:ca(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},bs=async e=>(await ws(e))?.sha256,ys=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Cu=async(e,t)=>{let n=UW(e),r;try{r=await KI(Cc(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>ks(Cc(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([ws(e),ws(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ys(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await zI(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ys(t,s.sha256)&&ys(t,i.sha256)){await kn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},By=async(e,t,n)=>(n.present?await e(QI(Fe,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Fe,"/v",t,"/f"])).code===0,pH=async(e,t,n)=>{let r=!0,o=await _r(e);for(let a of He)if(!ms(o.values[a],t[a])){if(!ms(o.values[a],n[a])){r=!1;continue}await By(e,a,t[a])||(r=!1),o=await _r(e)}return r&&He.every(a=>ms(o.values[a],t[a]))},st=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[en(n)]}}),eE=async(e,t,n,r={})=>{if(!Pe(t))return st("A valid personal ark_ gateway key is required.",!1,r);let o=_y(r),a;try{a=LW((r.credentialCommand??my)())}catch{return st("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=ca(a),i=r.runReg??Tr,c=en(r),l;if(!n.dryRun)try{l=await Dy(r)}catch(h){return st(h instanceof gs?"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 go(i);if(h)return st(My(h),!1,r);let g=await $y(r,!n.dryRun);n.dryRun||await Cu(o,g);let y=await _r(i),w=cH(e,o),b=await ws(o),A=b?.sha256,C=!1;if(d=g,u=y,p=w,g){let S=He.find(E=>!xy(g,E,y.values[E]));if(S)return st(`Claude's ${S} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(A!==void 0&&!ys(g,A))return st(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=dH(g)}else{if(A!==void 0&&A!==s)return st(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let S=y.foreignState||He.some(I=>y.values[I].present),E=He.every(I=>ms(y.values[I],w[I])),T=He.every(I=>ms(y.values[I],lH(e,t.trim())[I]));if(S&&!E&&!T)return st(`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(C=T,E&&A===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 bu(UI(y.keyPresent,w,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Fe} into the ownership journal.`]})}if(C){let S=!0;try{S=(r.appRunning??Py)()}catch{}if(S)return st("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let x=uH(g?.keyExisted??y.keyPresent,y.values,w,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 bu(x,r),f=!0;for(let S of He){let E=await _r(i);if(!hs(E.values[S],x.lastWritten[S])&&!hs(E.values[S],x.pending[S]))throw new Error("registry value changed during apply");if(!ms(E.values[S],w[S])&&!await By(i,S,w[S]))throw new Error("registry write failed")}let O=await _r(i);if(!He.every(S=>hs(O.values[S],x.pending[S])))throw new Error("registry verification failed");if(A!==s&&(A===void 0?await FW(o,a):await ku(o,A,a,"apply",r)),await bs(o)!==s)throw new Error("credential helper verification failed");return await bu(UI(x.keyExisted,w,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.",...du(Tt("migrate"))]}}catch{if(!f||!u||!p||!m)return st("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Cu(o,m);let h=!0,g=await ws(o),y=m.helper.pending;if(g?.sha256!==m.helper.lastWritten?.sha256&&(y!==void 0&&g?.sha256===y.sha256?m.helper.lastWritten?(await ku(o,y.sha256,m.helper.lastWritten.content,"rollback",r),h=await bs(o)===m.helper.lastWritten.sha256):await ku(o,y.sha256,void 0,"rollback",r):h=g===void 0&&m.helper.lastWritten===void 0),h&&await pH(i,u.values,p))return d?await bu(d,r):await kn(c,{force:!0}),st("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return st("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?.()}},tE=async(e,t={})=>{let n=t.runReg??Tr,r=en(t),o;if(!e.dryRun)try{o=await Dy(t)}catch(a){return st(a instanceof gs?"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 $y(t,!e.dryRun);a&&!e.dryRun&&await Cu(a.helper.path,a);let s=await _r(n);if(!a)return He.filter(f=>s.values[f].present).length>0?st(`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&&!xy(a,m,s.values[m])),c=await bs(a.helper.path),l=c!==void 0&&!ys(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 _r(n)).values[m];if(h.present){if(!xy(a,m,h)){u.add(m);continue}await By(n,m,{present:!1})||(d=!0)}}let p=await bs(a.helper.path);if(p!==void 0)if(ys(a,p))try{await ku(a.helper.path,p,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?st(`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 kn(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?[]:uu]})}catch{return st(`Could not safely inspect or revert ${Fe}; no unproven value was removed.`,!1,t)}finally{await o?.()}},nE=async(e,t={})=>{let n=t.runReg??Tr;if(!await R(en(t)))return;let r;try{r=await Dy(t);let o=await $y(t);if(o&&await Cu(o.helper.path,o),!o||o.pending||await go(n)!==void 0)return;let a=await _r(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===dt(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&He.every(l=>hs(a.values[l],o.lastWritten[l]))))return;let i=await bs(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 BW(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?.()}},rE=async(e,t={})=>await nE(e,t)!==void 0,oE=async(e,t={})=>await nE(e,t)==="dynamic";var As=(e=sE())=>e==="win32"?Py:yu,Uy=(e=sE())=>e==="win32"?Ty:fy,Fy="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Eu=async(e,t={})=>{let n=(t.profileRoot??Rr)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Fy};if((t.appRunning??As(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await aE.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 lu(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 "+Fy}:{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??ZS)();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=Iu(t.stagingRoot??mH(),`anyray-history-${process.pid}-${fH()}`);try{let s=await(t.runImporter??JS)({binary:o,exportPath:e,configDir:Iu(a,"config"),workDir:Iu(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. "+Fy};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 zS(r.dir,s.conversations),c=await qS({stagedProjectsDir:Iu(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 aE.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Mt}from"node:fs";import{homedir as MH}from"node:os";import{join as An,sep as BH}from"node:path";import{isDeepStrictEqual as _u}from"node:util";import{constants as dE}from"node:fs";import{promises as j}from"node:fs";import{dirname as vs,isAbsolute as Hy,join as re,relative as xu,resolve as Cn,sep as Ac}from"node:path";import{randomUUID as Tu}from"node:crypto";var zn=448,vc=384,uE=448,hH=4,Gy=3e4,pE=5e3,yH=10*6e4,fE={config:["skill","plugin","local-mcp"],session:["code","cowork"]},Pu=e=>e?["config","session"]:["config"],Sc=(e,t)=>(e??["config","session"]).includes(t),mE=["carried","pending","nothing_to_carry","not_routed","unreadable","unsupported","unknown"],hE={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"},Wy=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),Ge=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ic=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),yE=(e,t)=>{let n=xu(Cn(e),Cn(t));return n===""||!n.startsWith(`..${Ac}`)&&n!==".."&&!Hy(n)},qn=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 It(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},It=e=>e instanceof Error&&"code"in e,gH=e=>{try{return process.kill(e,0),!0}catch(t){return It(t)&&t.code==="EPERM"}},gE=e=>e===0?"owner.json":`owner.${e}.json`,Ru=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=re(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}},wE=e=>{if(e.pid===void 0||!gH(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Gy&&t-e.createdAtMs>yH},wH=async e=>{let t=`${e}.anyray-lock`;await j.mkdir(vs(t),{recursive:!0,mode:zn});let n=Tu(),r,o=!1;try{await j.mkdir(t,{mode:zn}),o=!0}catch(i){if(!It(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Ru(t);if(d){if(!wE(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)<=Gy)return}let l=re(t,gE(c));try{await j.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
277
277
|
`,{flag:"wx",mode:vc}),r=l}catch(d){if(It(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{}})()},pE);return s.unref(),async()=>{clearInterval(s);try{(await Ru(t))?.nonce===n&&await j.rm(t,{recursive:!0,force:!0})}catch{}}},bH=async(e,t,n)=>{await j.mkdir(vs(e),{recursive:!0,mode:zn});let r=await wH(e);if(!r)return!1;try{let o;try{o=await j.readFile(e,"utf8")}catch(s){if(!It(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${Tu()}`;try{await j.writeFile(a,`${JSON.stringify(n,null,2)}
|
|
278
|
-
`,{mode:vc,flag:"wx"}),await j.rename(a,e)}catch(s){try{await j.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},Du=async(e,t)=>{for(let n=0;n<hH;n+=1){let r=await qn(e);if(!r)return"failed";let o=t(r.value);if(!o||_u(o,r.value))return"unchanged";try{if(await bH(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},iE=async e=>{try{return(await j.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},
|
|
279
|
-
`,{flag:"wx",mode:vc}),o=u}catch(p){if(It(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{}})()},pE);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Ru(e))?.nonce===r&&await j.rm(e,{recursive:!0,force:!0})}catch{}}}},AE=async e=>{let t=await CE(e,!1);t&&await t.complete()},xH=async(e,t,n)=>{let r=kE(t),o=!1;try{let c=await j.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Ou(e,t))return await AE(r),"present"}catch(c){if(!It(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 CE(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await j.mkdir(t,{mode:zn})}catch(c){if(!It(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=re(c,u.name),m=re(l,u.name);try{if(u.isDirectory()){try{await j.mkdir(m,{mode:zn})}catch(h){if(!It(h)||h.code!=="EEXIST")throw h;let g=await j.lstat(m);if(!g.isDirectory()||g.isSymbolicLink())return"conflict"}let f=await s(p,m);if(f!=="copied")return f}else if(u.isFile())try{await j.copyFile(p,m,dE.COPYFILE_EXCL);let f=await j.stat(p);await j.chmod(m,(f.mode&73)!==0?uE:vc)}catch(f){if(!It(f)||f.code!=="EEXIST")throw f;if(!await bE(p,m))return"conflict"}else return"failed"}catch(f){return It(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 Ou(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},vE=async(e,t,n,r)=>{if(!await cE(e))return"invalid";try{let a=await j.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Ou(e,t))return await AE(kE(t)),"present"}catch(a){if(!It(a)||a.code!=="ENOENT")return"failed"}await j.mkdir(vs(t),{recursive:!0,mode:zn});let o=re(vs(t),`.anyray-stage-${Tu()}`);try{return await j.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await cE(o)?(await EH(o),await n?.(t),await xH(o,t,r)):"invalid"}catch{return"failed"}finally{try{await j.rm(o,{recursive:!0,force:!0})}catch{}}},lE=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),SE=async e=>{let t=await Lu(re(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await qn(re(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},IE=async e=>{let t=await Lu(re(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(Ac).includes("skills-plugin"))try{await j.access(re(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},RH=async e=>{try{return await j.access(e,dE.R_OK),"readable"}catch(t){return It(t)&&t.code==="ENOENT"?"missing":"unreadable"}},OH=async(e,t)=>{if(e.length===0)return!0;if(!t)return!1;let n=await SE(t);if(n.state!=="found")return!1;let r=await qn(re(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()))},_H=async(e,t)=>{if(e.length===0)return!0;if(!t)return!1;let n=await IE(t);if(n.state!=="found")return!1;let o=(await qn(re(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},TH=async(e,t)=>{let n=Object.keys(e);if(n.length===0)return!0;if(!t)return!1;let o=(await qn(re(t,"claude_desktop_config.json")))?.value.mcpServers;return Ge(o)?n.every(a=>Object.hasOwn(o,a)):!1},EE=async(e,t)=>{if(!e)return"unsupported";let n=await RH(e);if(n==="unreadable")return"unreadable";if(n==="missing")return"nothing_to_carry";let r=await Ky(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([OH(r.skills,t),_H(r.plugins,t),TH(r.localMcpServers,t)]);return o&&a&&s?"carried":"pending"},PH=async(e,t,n,r,o)=>{let a=re(t,"manifest.json");for(let s of e){let i=re(s.packageDir,"skills",s.entry.name);try{await j.access(re(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=re(t,"skills",s.entry.name),l=await vE(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 Du(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}},xE=(e,t)=>({...e,installPath:t}),DH=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=Hy(r.installPath)?Cn(r.installPath):Cn(o,r.installPath),s=xE(e,xu(Cn(t),Cn(n))),i={...r,installPath:xu(Cn(o),a)};return _u(s,i)},LH=async(e,t,n)=>{let r=await qn(e);if(!r||!Ge(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":Du(t,a=>{let s=Ge(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},NH=async(e,t,n,r,o)=>{let a=re(t,"cowork_plugins"),s=re(a,"installed_plugins.json"),i=re(t,"cowork_account_settings.json");for(let c of e){let l=re(a,c.relativeInstallPath);if(!yE(a,l)){n.invalid+=1;continue}let d=await vE(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 Du(s,f=>{let h=Ge(f.plugins)?f.plugins:{},g=h[c.id],y=Array.isArray(g)?g:[],w=y.find(A=>Ge(A)&&A.scope==="user");if(w){u=DH(c.entry,vs(c.settingsFile),c.packageDir,w,t),p=!u;return}let b=xE(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 LH(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},$H=async(e,t,n)=>{let r=re(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await Du(r,c=>{let l=Ge(c.mcpServers)?c.mcpServers:{};if(Object.hasOwn(l,o)){s.value=_u(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}},RE=async(e,t,n={})=>{let r=await Ky(e),o=Wy("skill"),a=Wy("plugin"),s=Wy("local-mcp"),i=[],c=[],l=[],d=lE(r.skills,n.account,n.allAccounts),u=lE(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 SE(t);m.state==="found"?await PH(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 IE(t);m.state==="found"?await NH(u,m.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):m.state==="missing"?i.push("plugin"):(a.conflicts+=u.length,c.push("plugin"))}await $H(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 FH=async e=>{try{return await Mt.access(e),!0}catch{return!1}},OE=448,UH=384,TE={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},WH=fE.session,Zy=(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.",jy=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),PE=async e=>{let t;try{t=(await Mt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&ds(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await Mt.readdir(An(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&ds(a.name)).map(a=>a.name);for(let a of o)n.push(An(e,r,a))}catch{}return n},HH=async e=>{try{return(await Mt.readdir(e)).filter(t=>t.startsWith(xr)&&t.endsWith(".json")).map(t=>t.slice(xr.length,-5)).filter(ds)}catch{return[]}},GH=async(e,t)=>{let n=await PE(An(e,TE[t])),r=[];for(let o of n){let a=await HH(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(BH).slice(-2)[0]})}return r},KH=async(e,t)=>{if(t==="cowork"){let r=await lu(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await PE(An(e,TE.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},VH=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await Mt.copyFile(e,n),await Mt.chmod(n,UH),await Mt.rename(n,t)},jH=async(e,t)=>{try{let n=JSON.parse(await Mt.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||!ds(o)?!1:(await Mt.access(An(t,".claude","projects",iy(r),`${o}.jsonl`)),!0)}catch{return!1}},YH=async(e,t,n,r)=>{let o=jy(e),a=await cy(n);for(let s of t)await ZH(e,s,n,r,a,o);return o},ZH=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${xr}${s}.json`,c=An(t.dir,i);try{if(e==="code"){if(!await jH(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=An(t.dir,`${xr}${s}`),d=An(n,`${xr}${s}`),u=await Mt.readdir(l);await Mt.mkdir(d,{mode:OE});for(let p of u)await Mt.cp(An(l,p),An(d,p),{recursive:!0,force:!1,errorOnExist:!0});await Mt.chmod(d,OE)}await VH(c,An(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},_E=(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
|
-
`)}},Yy=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),DE=async e=>{let t=[];for(let n of WH)t.push({lane:n,sources:await GH(e,n)});return t},LE=async(e={})=>{let t=(e.firstPartyRoot??(()=>aa()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let n=Sc(e.assetClasses,"session"),[r,o]=await Promise.all([n?DE(t):Promise.resolve([]),Vy(t)]),a=r.reduce((i,c)=>i+c.sources.reduce((l,d)=>l+d.ids.length,0),0),s=Yy(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}},la=async(e={})=>{let t=(e.home??MH)(),n=(e.firstPartyRoot??(()=>aa()))(),r=(e.thirdPartyRoot??(()=>Rr()))();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=Sc(e.assetClasses,"session"),a=(e.appRunning??As())();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?DE(n):Promise.resolve([]),Vy(n)]),c;if(e.account){let h=e.account;for(let w of s)w.sources=w.sources.filter(b=>b.account.startsWith(h));let g=i.accounts.filter(w=>w.startsWith(h));if(s.every(w=>w.sources.length===0)&&g.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=Yy(s);for(let w of g)y.add(w);if(y.size>1)return _E(s,e.command??"anyray-connect desktop --migrate",`"${h}" matches ${y.size} accounts`,g);c=[...y]}else if(o&&!e.allAccounts){let h=Yy(s);for(let g of i.accounts)h.add(g);if(h.size>1)return _E(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 FH(r),u=await RE(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:g}of s){if(g.length===0){p.push(jy(h));continue}let y=await KH(r,h);if("missing"in y){m.push({lane:h,reason:y.missing,waiting:g.reduce((w,b)=>w+b.ids.length,0)}),p.push(jy(h));continue}p.push(await YH(h,g,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:Zy(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 JH=e=>[We(e)],NE=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...JH(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 $E="1.21459.0",QH=qH(XH),eG=async e=>{try{let{stdout:t}=await QH("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},tG=async e=>{try{return await zH(e)}catch{return}},ME="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",nG=["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."],Ss=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(BE??=FE({}),BE):FE(e),BE,FE=async e=>{let t=(e.home??xc)(),n=["/Applications/Claude.app",Qn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??eG,o=e.readClaudeAppBundle??tG;for(let a of n){let s=await r(Qn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${ME}`}),c=iu(s,$E);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${$E} or newer.`);let l=await o(Qn(a,"Contents","Resources","app.asar"));return l?mI.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. ${ME}`}},Nu="anyray",GE="--anyray-owner=claude-desktop-v1",$u=(e={})=>{let t=(e.platform??wo)(),n=(e.home??xc)();return t==="darwin"?bn(e).appConfig:t==="win32"?Qn(process.env.APPDATA??Qn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):Qn(n,".config","Claude","claude_desktop_config.json")},qy=(e={})=>Qn((e.home??xc)(),"Library","Application Support","Claude","claude_desktop_config.json"),KE=()=>{let e=Ue("profile");return{command:e.command,args:[...e.args,GE]}},da=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),VE=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},rG=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),oG=e=>{if(!da(e)||!VE(e,["command","args"]))return!1;let t=KE();return e.command===t.command&&rG(e.args,t.args)},aG=e=>da(e)&&Array.isArray(e.args)&&e.args.at(-1)===GE,sG=e=>{if(!da(e)||!VE(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||ut(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===Jr&&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!ut(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},iG=e=>e===void 0?"absent":oG(e)?"exact":aG(e)||sG(e)?"stale-owned":"foreign",Ze=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},ua=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&&!da(n.mcpServers))throw new Ze(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(da(n.mcpServers)?n.mcpServers:void 0)?.[Nu];return{path:e,fileExisted:t,json:n,entry:o,ownership:iG(o)}},Mu=e=>{if(e.ownership==="foreign")throw new Ze(`MCP name conflict in ${e.path}: mcpServers.${Nu} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},jE=(e,t)=>{let n={...e},r=da(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[Nu]:r[Nu]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Xy=async(e,t)=>{if(Jy(e.entry,t))return;let n=await ua(e.path);if(!Jy(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 Or(e.path,jE(n.json,t)),{reading:e,afterEntry:t}},zy=async e=>{let t=await ua(e.reading.path);if(!Jy(t.entry,e.afterEntry))throw new Ze(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=jE(t.json,e.reading.entry);await Or(e.reading.path,n)},cG=async e=>{if(!ne())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 ua($u(e));Mu(t);let n=qy(e),r=(e.platform??wo)()==="darwin"&&n!==t.path?await ua(n):void 0;return r&&Mu(r),{active:t,...r?{legacy:r}:{}}},UE=async e=>{let t=await ua($u(e));Mu(t);let n=qy(e),r=(e.platform??wo)()==="darwin"&&n!==t.path?await ua(n):void 0;return r&&Mu(r),{active:t,...r?{legacy:r}:{}}},lG=async e=>{let t=[];try{let n=await Xy(e.active,KE());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Xy(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await zy(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 zy(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)}}},dG=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Xy(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await zy(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)},WE=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)."]},uG={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Qy="claude-desktop",eg="migrate",Bu="migrate-config",pG=[eg,Bu],HE=async e=>{await Ed(Qy,e?eg:Bu,{precedence:pG})},YE=new Set(["app-running","store-missing"]),fG={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},mG={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"}},hG="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",ZE=e=>{let t=(e.platform??wo)(),n=e.home??xc;return{home:n,appRunning:e.appRunning??As(t),firstPartyRoot:()=>aa({home:n,runtimePlatform:t}),thirdPartyRoot:()=>Rr({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},JE=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=fG[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.`:"")},XE=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=mG[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.`:"")},Ec=async(e,t)=>{try{let n=Pu(t.reportsToUser===!0),r=Sc(n,"session"),o={...ZE(e),assetClasses:n},a=await(e.pendingDesktopMigrationCount??LE)(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??la)(o);if(i.ok){let d=JE(i.lanes),u=XE(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(C=>C.reason!=="ambiguous"),h=i.blockedAssets??[],g=i.deferredAssets??[],y=i.retryableAssets??[];if(f.length===0&&h.length===0&&g.length===0&&y.length===0)return[d,u,m].filter(C=>!!C);if(t.preservePendingOp)return[d,u,m].filter(C=>!!C);await HE(r);let w=f.reduce((C,x)=>C+x.waiting,0),b=[w>0?`${w} more session${w===1?"":"s"}`:"",h.length>0?`${h.length} extension ${h.length===1?"store":"stores"}`:""].filter(Boolean),A=[...b.length>0?[`Queued: ${b.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...g.length>0?[`Queued: ${g.length} portable configuration ${g.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]:[],...A]}if(!YE.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 HE(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 fi?["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."]}},yG=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await oo(Qy),[]}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."]}},gG=e=>NE({id:Qy,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??wo)(),n=(e.home??xc)();return t==="darwin"?["/Applications/Claude.app",Qn(n,"Applications","Claude.app")]:t==="win32"?[Qn(process.env.LOCALAPPDATA??Qn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>se(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:",...WE(t)]:["Claude desktop org/API lane:",...WE(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`."]}),wG=(e={})=>{let t=gG(e),n=()=>(e.platform??wo)()==="darwin",r=()=>(e.platform??wo)()==="win32",o=(s,i)=>n()?AI(s,i,e):eE(s,s.clientKey??"",i,e),a=s=>n()?vI(s,e):tE(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??As((e.platform??wo)()))(),quitTarget:uG,needsTarget:()=>!1,async complete(s){if(s!==eg&&s!==Bu)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??la)({...ZE(e),assetClasses:s===Bu?Pu(!1):Pu(!0)});if(i.ok){let c=JE(i.lanes),l=XE(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(g=>g.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(g=>!!g):["No portable Claude Desktop data was left to bring across."]}}return YE.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?II(s,e):r()?oE(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let p=bn(e),m=await ia(p,e);if(m)return{status:"manual",manualAudience:"admin",messages:[by(m),...await Ec(e,i)]}}if(r()){let p;try{p=await go(e.runReg??Tr)}catch{return{status:"manual",manualAudience:"admin",messages:[hG,...await Ec(e,i)]}}if(p)return{status:"manual",manualAudience:"admin",messages:[My(p),...await Ec(e,i)]}}if(r()&&se(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 Ss(e);if(!p.supported)return{status:"manual",messages:[p.message??"Claude Desktop version is unsupported."]}}let c;try{c=await cG(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 Ec(e,i)]}}let d;try{d=await lG(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 Ec(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?nG:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=$u(e),c=await yG(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 UE(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()?en(e):void 0;if(!(h!==void 0&&p.changedFiles?.includes(h)===!0&&!await R(h)))return l(p)}let m;try{m=await dG(await UE(e))}catch(h){let g=h instanceof Ze?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...p.changedFiles??[],...g])],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 fe(i);let f=qy(e);return n()&&f!==i&&await fe(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(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await ua($u(e));return s.ownership!=="exact"||!da(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 Ss(e)).supported?Cy(s,e):!1:r()?rE(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await Ss(e)).supported)return["unknown"];let s=await SI(e);return s?[s]:["unknown"]}if(r())return await R(en(e))?await go(e.runReg??Tr)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=bn(e);return!await R(s.journal)||await ia(s,e)?!1:(await Ss(e)).supported}return r()&&await R(en(e))?!await go(e.runReg??Tr):!1}catch{return!1}}}},zE=wG();import{homedir as jG}from"node:os";import{join as YG}from"node:path";import{rm as Yu}from"node:fs/promises";import{constants as qE,accessSync as bG,statSync as kG}from"node:fs";import{platform as tg}from"node:os";import{delimiter as CG,posix as AG,resolve as vG,win32 as SG}from"node:path";var IG="0.59.0",EG="1.1.4",Pr="Anyray \xB7 Claude",Dr="Anyray \xB7 Codex",Fu="__anyray-acp-agent",QE=(e,t,n)=>{let{command:r,args:o}=Rn([Fu,e,t,n]);return{command:r,args:o,env:{}}},Uu=(e=tg())=>e==="win32"?"npx.cmd":"npx",Wu=(e=process.env.PATH,t=tg())=>{if(!e)return;let n=Uu(t);for(let r of e.split(CG)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=vG(o,n);try{if(!kG(a).isFile())continue;return bG(a,t==="win32"?qE.F_OK:qE.X_OK),a}catch{}}},Hu=(e,t=tg())=>{let n=t==="win32"?SG:AG;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==Uu(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},xG="https://chatgpt.com/backend-api/codex",RG="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",ex="ANYRAY_ACP_CODEX_AUTHORIZATION",tx="ANYRAY_ACP_CODEX_CLIENT_KEY",nx="ANYRAY_ACP_CODEX_METADATA",rx=e=>be({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),OG=(e,t={})=>{let n=se(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":xG,"x-anyray-forward-headers":RG}:{},o=n?{...e.clientKey?{"x-anyray-api-key":tx}:{}}:{Authorization:ex};return rx(e)&&(o["x-anyray-metadata"]=nx),{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}}}:{}}},_G=e=>{let t=se(e,"openai"),n=rx(e);return{...t?e.clientKey?{[tx]:e.clientKey}:{}:{[ex]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[nx]:n}:{}}},ox=(e,t=Uu(),n={})=>({[Pr]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${IG}`],env:Tn(e).env},[Dr]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${EG}`],env:{CODEX_CONFIG:JSON.stringify(OG(e,n)),..._G(e)}}}),Rc=(e=Uu(),t="jetbrains")=>({[Pr]:QE("claude",e,t),[Dr]:QE("codex",e,t)}),pa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gu=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as TG}from"node:zlib";import{open as PG,readFile as sg,readdir as ju}from"node:fs/promises";import{dirname as ax,join as Ce}from"node:path";import{homedir as lx,platform as ig}from"node:os";var Ku="2025.3.2",Is="253.30387.147",Oc="com.intellij.ml.llm",ng=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),DG=1e4,LG=256*1024*1024,NG=16*1024*1024,rg=1024*1024,og=22,$G=og+65535,ag=iu,MG=()=>{let e=lx(),t=Ce(e,".cache","JetBrains","RemoteDev");switch(ig()){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"}]}},BG=()=>ig()==="linux"?Ce(lx(),".local","share","JetBrains"):We("JetBrains"),FG=()=>ig()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),UG=async(e,t=DG)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await ju(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 ju(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)]},WG=e=>{let t=ax(e);return t.endsWith(`${Ce("Contents","Resources")}`)?ax(t):t},HG=async e=>{try{let t=JSON.parse(await sg(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!lc(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:WG(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},GG=async(e,t)=>{let n;try{n=await PG(e,"r");let{size:r}=await n.stat();if(r<og||r>LG)return;let o=Math.min(r,$G),a=await Vu(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-og;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>NG||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),g=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),w=d+46+f+h+g;if(w>l.length)return;let b=l.subarray(d+46,d+46+f).toString("utf8");if(d=w,b!==t)continue;if(p===4294967295||m===4294967295||p>rg||m>rg)return;let A=await Vu(n,30,y);if(!A||A.readUInt32LE(0)!==67324752)return;let C=A.readUInt16LE(26),x=A.readUInt16LE(28),O=await Vu(n,p,y+30+C+x);return O?u===0?O.toString("utf8"):u===8?TG(O,{maxOutputLength:rg}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},sx=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!lc(n)))return{id:t,version:n}},KG=async(e,t)=>{let n=Ce(e,"META-INF","plugin.xml");if(await R(n))try{let o=sx(await sg(n,"utf8"));return{present:o?.id===Oc||t,descriptor:o?.id===Oc?o:void 0}}catch{return{present:t}}let r=[];try{r=(await ju(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 GG(o,"META-INF/plugin.xml"),s=a?sx(a):void 0;if(s?.id===Oc)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},ix=async e=>{let t;try{t=await ju(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=ng.has(o.name.toLowerCase()),i=ng.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=ng.has(o.name.toLowerCase());if(!a){let i=Ce(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await KG(Ce(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},VG=async e=>{try{return(await sg(Ce(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(Oc)}catch{return!1}},cx=e=>e.reduce((t,n)=>t?(ag(n,t)??-1)>0?n:t:n,void 0),dx=async(e={})=>{let t=e.configRoot??We("JetBrains"),n=e.userPluginsRoot??BG(),r=await UG(e.productRoots?e.productRoots.map(f=>({path:f,layout:"recursive"})):MG(),e.scanBudget),o=(await Promise.all(r.map(f=>HG(f)))).filter(f=>f!==void 0),a=o.length>0||await R(t);if(e.wsl??FG())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=>(ag(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 g=[Ce(h,"plugins"),Ce(n,f.dataDirectoryName),Ce(n,f.dataDirectoryName,"plugins")],y;for(let w of[...new Set(g)]){let b=await ix(w);if(b.present){y=b;break}}if(y??=await ix(Ce(f.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==Oc)){if(i.push(y.descriptor.version),await VG(h)){c=!0;continue}if(!((ag(y.descriptor.version,Is)??-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=cx(o.map(f=>f.version)),p=cx(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 ${Is}+, then run Connect again. No ACP config was written.`:c?m=`JetBrains AI Assistant is disabled; enable version ${Is}+ and run Connect again. No ACP config was written.`:p?m=`JetBrains AI Assistant ${p} is below the ACP minimum ${Is}; no ACP config was written.`:l?m=`Could not verify the local JetBrains AI Assistant version; require ${Is}+ before running Connect. No ACP config was written.`:m=`JetBrains AI Assistant ${Is}+ 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 ZG=[Pr,Dr],cg=()=>YG(jG(),".jetbrains","acp.json"),fa=()=>`${cg()}.anyray-state`,JG=(e,t,n="npx")=>{let r=pa(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,Rc(n,"jetbrains")),{...e,agent_servers:r}},XG=(e,t,n)=>{if(!pa(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=pa(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of ZG)if(c in r){if(!Gu(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}},zG=(e=dx)=>({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=cg(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=Wu();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=Rc(a,"jetbrains");return await Wl({configPath:r,current:c,next:JG(c,t,a),journalPath:fa(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,fa()]}},async revert(t){let n=cg(),r=async()=>{if(!await R(n))return t.dryRun||(await fe(n),await Yu(fa(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await F(n)}catch{return t.dryRun||(await fe(n),await Yu(fa(),{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(fa());(u.version===1||u.version===2)&&pa(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 Bo(n);let l=XG(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 Yu(n,{force:!0}):await q(n,l.next,{backup:!1})),t.dryRun||(await fe(n),await Yu(fa(),{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():Ul(n,fa(),r)}}),ux=zG();import{homedir as Ju}from"node:os";import{join as Xu}from"node:path";import{rm as lg}from"node:fs/promises";var dg="1.0.0",zu=["anyray-claude-acp","anyray-codex-acp"],qG=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],ug=()=>Xu(Ju(),".windsurf","acp","registry.json"),pg=()=>Xu(Ju(),".windsurf-next","acp","registry.json"),Es=e=>`${e}.anyray-state`,px=e=>({binary:Object.fromEntries(qG.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),mx=(e="npx")=>{let t=Rc(e,"windsurf");return[{id:zu[0],name:Pr,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:px(t[Pr])},{id:zu[1],name:Dr,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:px(t[Dr])}]},Zu=e=>!Array.isArray(e)||e.some(t=>!pa(t)||typeof t.id!="string")?null:e,QG=(e,t="npx")=>{if(e.version!==void 0&&e.version!==dg||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:Zu(e.agents);if(!n)return null;let r=new Set(zu);return{...e,version:typeof e.version=="string"?e.version:dg,agents:[...n.filter(o=>!r.has(o.id)),...mx(t)],extensions:e.extensions??[]}},e1=(e,t,n)=>{let r=Zu(e.agents);if(!r)return null;let o=Zu(t.agents)??[],a=new Map((Zu(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!zu.includes(u.id)){l.push(u);continue}if(!Gu(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===dg&&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}},fx=async()=>{let e=[];return(await R(pg())||await R(Xu(Ju(),".windsurf-next")))&&e.push(pg()),(await R(ug())||await R(Xu(Ju(),".windsurf"))||await R(We("Devin"))||await R(We("Windsurf")))&&e.push(ug()),e},hx={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await fx();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await fx();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=Wu();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=QG(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=mx(r);await Wl({configPath:s,current:i,next:c,journalPath:Es(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Es(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=[ug(),pg()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await fe(a),await lg(Es(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(Es(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 Bo(a);let p=e1(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 lg(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 fe(a),await lg(Es(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await Ul(a,Es(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var ie=[Dn,XC,Ki,rS,OS,US,YS,ux,zE,hx,aA],Qe=e=>ie.find(t=>t.id===e);var Je=async(e=N,t=Vn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:Re({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 fg=5e3,yx=3e4,t1=1440*60*1e3,n1=e=>new Promise(t=>setTimeout(t,e)),r1=async(e=N,t=Vn)=>(await Je(e,t))?.target,o1=e=>Qe(e)?.quitGated,gx=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??o1,o=t.readPending??Fi,a=t.clearPending??jm,s=t.targetFromProfile??r1,i=t.sleep??n1,c=t.now??Date.now,l=t.maxWaitMs??t1;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),p=c(),m=fg;for(;;){let f=await o(n);if(!f||c()-p>l)return 0;if(d.isRunning()){await i(m),m=Math.min(yx,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=fg;continue}if((await u(f.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(m),m=Math.min(yx,m*2);continue}if(await a(n,f)!=="superseded")return 0;await i(m),m=fg}}catch{return 0}};import{z as Tc}from"zod";import{createHash as a1,randomBytes as s1,timingSafeEqual as i1}from"node:crypto";import{createServer as c1}from"node:http";var _c="127.0.0.1",l1=2147483647,d1="/callback",mg=12,u1="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",hg=e=>e.length===mg&&[...e].every(t=>u1.includes(t)),er=class extends Error{kind;constructor(t,n){super(n),this.name="ConnectorOauthCallbackError",this.kind=t}},ma=(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)},p1=e=>new Promise(t=>{if(e.writableFinished||e.destroyed){t();return}e.once("finish",()=>t()),e.once("close",()=>t())}),wx=async()=>{let e;try{e=s1(32).toString("base64url")}catch{throw new er("listen","Could not open a local callback port for the browser.")}let t=Buffer.from(a1("sha256").update(e).digest("base64url")),n=p=>{let m=Buffer.from(p);return m.length===t.length&&i1(m,t)},r,o=()=>{},a=new Promise(p=>{o=p}),s=!1,i=c1((p,m)=>{if(p.socket.remoteAddress!==_c||p.method!=="GET"||p.url===void 0||!p.url.startsWith("/")||p.headers.host!==r){ma(m,404,"Not found.");return}let f;try{f=new URL(p.url,`http://${_c}`)}catch{ma(m,404,"Not found.");return}if(f.pathname!==d1){ma(m,404,"Not found.");return}let h=[...f.searchParams.entries()],g=f.searchParams.getAll("claim"),y=f.searchParams.getAll("nonce"),w=g[0]??"";if(h.length!==2||g.length!==1||y.length!==1||!hg(w)||!n(y[0]??"")){ma(m,404,"Not found.");return}if(s){ma(m,409,"Callback already received.");return}s=!0,o({status:"claim",claimCode:w,response:m})}),c=()=>new er("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:_c,port:0},()=>{i.off("error",f),p()})})}catch{throw i.close(),c()}let l=i.address();if(l===null||typeof l=="string"||l.address!==_c||l.port<=0)throw i.close(),c();let d=l.port;r=`${_c}:${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,g)=>{let y=!1,w=C=>{y||(y=!0,clearTimeout(A),m.signal?.removeEventListener("abort",b),C())},b=()=>w(()=>g(new er("lost","Connector authorization was cancelled."))),A=setTimeout(()=>w(()=>g(new er("timeout","Timed out waiting for the browser."))),Math.min(Math.max(m.timeoutMs,0),l1));if(m.signal?.aborted){b();return}m.signal?.addEventListener("abort",b,{once:!0}),a.then(C=>w(()=>h(C)))})}catch(h){throw await u(),h}if(f.status==="unavailable")throw await u(),new er("lost","The local callback port stopped listening.");try{let h=await p(f.claimCode);return ma(f.response,200,"Connected. You can close this window."),h}catch(h){throw ma(f.response,502,"Anyray could not finish connecting. Return to the terminal."),h}finally{await p1(f.response),await u()}},close:u}};import{spawn as f1}from"node:child_process";import{platform as m1}from"node:os";var h1=2e3,Lr=e=>new Promise(t=>{try{let n=new URL(e);if(n.protocol!=="https:"&&n.protocol!=="http:"){t(!1);return}let r=m1(),o=r==="darwin"?"open":r==="win32"?"cmd":"xdg-open",a=r==="win32"?["/c","start",'""',`"${n.href}"`]:[n.href],s=f1(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),h1);l.unref(),s.on("error",()=>c(!1)),s.on("exit",d=>c(d===0)),s.unref()}catch{t(!1)}});import{fstatSync as v1,openSync as S1,statSync as I1}from"node:fs";import{createInterface as E1}from"node:readline/promises";import{ReadStream as x1}from"node:tty";import{execFileSync as bx}from"node:child_process";import y1 from"node:os";var yg=e=>{try{return bx("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},g1=e=>{try{return bx("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},w1=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"]),gg=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:w1.has(t):!0},qu=()=>{try{return y1.userInfo().username||void 0}catch{return}},kx=()=>yg("user.name")??yg("user.email")??qu()??"unknown",Cx=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||yg),global:e.globalGitConfig??(t||g1)}},ha=e=>{try{return e()?.trim()||void 0}catch{return}},wg=(e={})=>{let t=Cx(e),n=ha(e.osUsername??qu),r=ha(()=>t.global("user.email"))??ha(()=>t.local("user.email"));return r||(ha(()=>t.global("user.name"))??ha(()=>t.local("user.name"))??n??"unknown")},Ax=(e={})=>{let t=wg(e);if(gg(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=Cx(e);return!!(ha(()=>n.global("user.email"))??ha(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var xs=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,b1=xs(process.stdout,process.env),bg=xs(process.stderr,process.env),Qu=!1,Rs=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,kg=()=>{Qu=!0},Cg=()=>{Qu=!1},ep=()=>Qu?bg:b1,tp=e=>{Qu?console.error(e):console.log(e)},Z=e=>Rs("1",e,ep()),v=e=>Rs("2",e,ep()),k1=e=>Rs("32",e,ep()),C1=e=>Rs("33",e,bg),A1=e=>Rs("31",e,bg),it=e=>Rs("36",e,ep()),k=e=>tp(e),W=e=>tp(`
|
|
282
|
-
${Z(e)}`),M=e=>tp(v(e)),B=e=>tp(`${
|
|
278
|
+
`,{mode:vc,flag:"wx"}),await j.rename(a,e)}catch(s){try{await j.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},Du=async(e,t)=>{for(let n=0;n<hH;n+=1){let r=await qn(e);if(!r)return"failed";let o=t(r.value);if(!o||_u(o,r.value))return"unchanged";try{if(await bH(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},iE=async e=>{try{return(await j.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},Nu=async e=>{let t=[];for(let n of await iE(e))for(let r of await iE(re(e,n)))t.push(re(e,n,r));return t},kH=e=>Array.isArray(e.skills)?e.skills.filter(t=>Ge(t)&&Ic(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],CH=async e=>{let t=re(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await Nu(t)){let o=await qn(re(r,"manifest.json"));if(!o)continue;let a=r.split(Ac).at(-1)??"";for(let s of kH(o.value))n.push({account:a,packageDir:r,entry:s})}return n},AH=async e=>{let t=await qn(re(e,".claude-plugin","plugin.json"));return!!t&&Ic(t.value.name)},vH=(e,t)=>{let n=Hy(t)?Cn(t):Cn(e,t);if(!yE(e,n)||n===Cn(e))return;let r=xu(Cn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},SH=async e=>{let t=await Nu(re(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(Ac).includes("skills-plugin"))continue;let o=re(r,"cowork_plugins"),a=await qn(re(o,"installed_plugins.json"));if(!a||!Ge(a.value.plugins))continue;let s=r.split(Ac).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!Ic(i)||!Array.isArray(c)))for(let l of c){if(!Ge(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=vH(o,l.installPath);!d||!await AH(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:re(r,"cowork_account_settings.json")})}}return n},IH=async e=>{let t=await qn(re(e,"claude_desktop_config.json"));return!t||!Ge(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>Ic(n)&&n.toLowerCase()!=="anyray"&&Ge(r)))},Ky=async e=>{let[t,n,r]=await Promise.all([CH(e),SH(e),IH(e)]);return{skills:t,plugins:n,localMcpServers:r}},Vy=async e=>{let t=await Ky(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)}},cE=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(!Ic(o.name))return!1;let a=re(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)},EH=async e=>{let t=async n=>{let r=await j.readdir(n,{withFileTypes:!0});for(let o of r){let a=re(n,o.name);if(o.isDirectory())await t(a),await j.chmod(a,zn);else if(o.isFile()){let s=await j.stat(a);await j.chmod(a,(s.mode&73)!==0?uE:vc)}}};await t(e),await j.chmod(e,zn)},bE=async(e,t)=>{try{let[n,r]=await Promise.all([j.readFile(e),j.readFile(t)]);return n.equals(r)}catch{return!1}},Ou=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(!_u(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 Ou(re(e,s),re(t,s)))return!1}else if(!i.isFile()||!await bE(re(e,s),re(t,s)))return!1}return!0}catch{return!1}},kE=e=>`${e}.anyray-incomplete`,CE=async(e,t)=>{let n=!1;if(t){await j.mkdir(vs(e),{recursive:!0,mode:zn});try{await j.mkdir(e,{mode:zn}),n=!0}catch(l){if(!It(l)||l.code!=="EEXIST")return}}else try{let l=await j.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=Tu(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let p;try{p=await Ru(e)}catch{return}if(p){if(!wE(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)<=Gy)return}let u=re(e,gE(d));try{await j.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
279
|
+
`,{flag:"wx",mode:vc}),o=u}catch(p){if(It(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{}})()},pE);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Ru(e))?.nonce===r&&await j.rm(e,{recursive:!0,force:!0})}catch{}}}},AE=async e=>{let t=await CE(e,!1);t&&await t.complete()},xH=async(e,t,n)=>{let r=kE(t),o=!1;try{let c=await j.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Ou(e,t))return await AE(r),"present"}catch(c){if(!It(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 CE(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await j.mkdir(t,{mode:zn})}catch(c){if(!It(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=re(c,u.name),m=re(l,u.name);try{if(u.isDirectory()){try{await j.mkdir(m,{mode:zn})}catch(h){if(!It(h)||h.code!=="EEXIST")throw h;let g=await j.lstat(m);if(!g.isDirectory()||g.isSymbolicLink())return"conflict"}let f=await s(p,m);if(f!=="copied")return f}else if(u.isFile())try{await j.copyFile(p,m,dE.COPYFILE_EXCL);let f=await j.stat(p);await j.chmod(m,(f.mode&73)!==0?uE:vc)}catch(f){if(!It(f)||f.code!=="EEXIST")throw f;if(!await bE(p,m))return"conflict"}else return"failed"}catch(f){return It(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 Ou(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},vE=async(e,t,n,r)=>{if(!await cE(e))return"invalid";try{let a=await j.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Ou(e,t))return await AE(kE(t)),"present"}catch(a){if(!It(a)||a.code!=="ENOENT")return"failed"}await j.mkdir(vs(t),{recursive:!0,mode:zn});let o=re(vs(t),`.anyray-stage-${Tu()}`);try{return await j.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await cE(o)?(await EH(o),await n?.(t),await xH(o,t,r)):"invalid"}catch{return"failed"}finally{try{await j.rm(o,{recursive:!0,force:!0})}catch{}}},lE=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),SE=async e=>{let t=await Nu(re(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await qn(re(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},IE=async e=>{let t=await Nu(re(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(Ac).includes("skills-plugin"))try{await j.access(re(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},RH=async e=>{try{return await j.access(e,dE.R_OK),"readable"}catch(t){return It(t)&&t.code==="ENOENT"?"missing":"unreadable"}},OH=async(e,t)=>{if(e.length===0)return!0;if(!t)return!1;let n=await SE(t);if(n.state!=="found")return!1;let r=await qn(re(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()))},_H=async(e,t)=>{if(e.length===0)return!0;if(!t)return!1;let n=await IE(t);if(n.state!=="found")return!1;let o=(await qn(re(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},TH=async(e,t)=>{let n=Object.keys(e);if(n.length===0)return!0;if(!t)return!1;let o=(await qn(re(t,"claude_desktop_config.json")))?.value.mcpServers;return Ge(o)?n.every(a=>Object.hasOwn(o,a)):!1},EE=async(e,t)=>{if(!e)return"unsupported";let n=await RH(e);if(n==="unreadable")return"unreadable";if(n==="missing")return"nothing_to_carry";let r=await Ky(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([OH(r.skills,t),_H(r.plugins,t),TH(r.localMcpServers,t)]);return o&&a&&s?"carried":"pending"},PH=async(e,t,n,r,o)=>{let a=re(t,"manifest.json");for(let s of e){let i=re(s.packageDir,"skills",s.entry.name);try{await j.access(re(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=re(t,"skills",s.entry.name),l=await vE(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 Du(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}},xE=(e,t)=>({...e,installPath:t}),DH=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=Hy(r.installPath)?Cn(r.installPath):Cn(o,r.installPath),s=xE(e,xu(Cn(t),Cn(n))),i={...r,installPath:xu(Cn(o),a)};return _u(s,i)},NH=async(e,t,n)=>{let r=await qn(e);if(!r||!Ge(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":Du(t,a=>{let s=Ge(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},LH=async(e,t,n,r,o)=>{let a=re(t,"cowork_plugins"),s=re(a,"installed_plugins.json"),i=re(t,"cowork_account_settings.json");for(let c of e){let l=re(a,c.relativeInstallPath);if(!yE(a,l)){n.invalid+=1;continue}let d=await vE(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 Du(s,f=>{let h=Ge(f.plugins)?f.plugins:{},g=h[c.id],y=Array.isArray(g)?g:[],w=y.find(A=>Ge(A)&&A.scope==="user");if(w){u=DH(c.entry,vs(c.settingsFile),c.packageDir,w,t),p=!u;return}let b=xE(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 NH(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},$H=async(e,t,n)=>{let r=re(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await Du(r,c=>{let l=Ge(c.mcpServers)?c.mcpServers:{};if(Object.hasOwn(l,o)){s.value=_u(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}},RE=async(e,t,n={})=>{let r=await Ky(e),o=Wy("skill"),a=Wy("plugin"),s=Wy("local-mcp"),i=[],c=[],l=[],d=lE(r.skills,n.account,n.allAccounts),u=lE(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 SE(t);m.state==="found"?await PH(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 IE(t);m.state==="found"?await LH(u,m.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):m.state==="missing"?i.push("plugin"):(a.conflicts+=u.length,c.push("plugin"))}await $H(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 FH=async e=>{try{return await Mt.access(e),!0}catch{return!1}},OE=448,UH=384,TE={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},WH=fE.session,Zy=(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.",jy=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),PE=async e=>{let t;try{t=(await Mt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&ds(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await Mt.readdir(An(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&ds(a.name)).map(a=>a.name);for(let a of o)n.push(An(e,r,a))}catch{}return n},HH=async e=>{try{return(await Mt.readdir(e)).filter(t=>t.startsWith(xr)&&t.endsWith(".json")).map(t=>t.slice(xr.length,-5)).filter(ds)}catch{return[]}},GH=async(e,t)=>{let n=await PE(An(e,TE[t])),r=[];for(let o of n){let a=await HH(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(BH).slice(-2)[0]})}return r},KH=async(e,t)=>{if(t==="cowork"){let r=await lu(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await PE(An(e,TE.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},VH=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await Mt.copyFile(e,n),await Mt.chmod(n,UH),await Mt.rename(n,t)},jH=async(e,t)=>{try{let n=JSON.parse(await Mt.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||!ds(o)?!1:(await Mt.access(An(t,".claude","projects",iy(r),`${o}.jsonl`)),!0)}catch{return!1}},YH=async(e,t,n,r)=>{let o=jy(e),a=await cy(n);for(let s of t)await ZH(e,s,n,r,a,o);return o},ZH=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${xr}${s}.json`,c=An(t.dir,i);try{if(e==="code"){if(!await jH(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=An(t.dir,`${xr}${s}`),d=An(n,`${xr}${s}`),u=await Mt.readdir(l);await Mt.mkdir(d,{mode:OE});for(let p of u)await Mt.cp(An(l,p),An(d,p),{recursive:!0,force:!1,errorOnExist:!0});await Mt.chmod(d,OE)}await VH(c,An(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},_E=(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
|
+
`)}},Yy=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),DE=async e=>{let t=[];for(let n of WH)t.push({lane:n,sources:await GH(e,n)});return t},NE=async(e={})=>{let t=(e.firstPartyRoot??(()=>aa()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let n=Sc(e.assetClasses,"session"),[r,o]=await Promise.all([n?DE(t):Promise.resolve([]),Vy(t)]),a=r.reduce((i,c)=>i+c.sources.reduce((l,d)=>l+d.ids.length,0),0),s=Yy(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}},la=async(e={})=>{let t=(e.home??MH)(),n=(e.firstPartyRoot??(()=>aa()))(),r=(e.thirdPartyRoot??(()=>Rr()))();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=Sc(e.assetClasses,"session"),a=(e.appRunning??As())();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?DE(n):Promise.resolve([]),Vy(n)]),c;if(e.account){let h=e.account;for(let w of s)w.sources=w.sources.filter(b=>b.account.startsWith(h));let g=i.accounts.filter(w=>w.startsWith(h));if(s.every(w=>w.sources.length===0)&&g.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=Yy(s);for(let w of g)y.add(w);if(y.size>1)return _E(s,e.command??"anyray-connect desktop --migrate",`"${h}" matches ${y.size} accounts`,g);c=[...y]}else if(o&&!e.allAccounts){let h=Yy(s);for(let g of i.accounts)h.add(g);if(h.size>1)return _E(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 FH(r),u=await RE(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:g}of s){if(g.length===0){p.push(jy(h));continue}let y=await KH(r,h);if("missing"in y){m.push({lane:h,reason:y.missing,waiting:g.reduce((w,b)=>w+b.ids.length,0)}),p.push(jy(h));continue}p.push(await YH(h,g,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:Zy(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 JH=e=>[We(e)],LE=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...JH(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 $E="1.21459.0",QH=qH(XH),e1=async e=>{try{let{stdout:t}=await QH("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},t1=async e=>{try{return await zH(e)}catch{return}},ME="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",n1=["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."],Ss=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(BE??=FE({}),BE):FE(e),BE,FE=async e=>{let t=(e.home??xc)(),n=["/Applications/Claude.app",Qn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??e1,o=e.readClaudeAppBundle??t1;for(let a of n){let s=await r(Qn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${ME}`}),c=iu(s,$E);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${$E} or newer.`);let l=await o(Qn(a,"Contents","Resources","app.asar"));return l?mI.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. ${ME}`}},Lu="anyray",GE="--anyray-owner=claude-desktop-v1",$u=(e={})=>{let t=(e.platform??wo)(),n=(e.home??xc)();return t==="darwin"?bn(e).appConfig:t==="win32"?Qn(process.env.APPDATA??Qn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):Qn(n,".config","Claude","claude_desktop_config.json")},qy=(e={})=>Qn((e.home??xc)(),"Library","Application Support","Claude","claude_desktop_config.json"),KE=()=>{let e=Ue("profile");return{command:e.command,args:[...e.args,GE]}},da=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),VE=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},r1=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),o1=e=>{if(!da(e)||!VE(e,["command","args"]))return!1;let t=KE();return e.command===t.command&&r1(e.args,t.args)},a1=e=>da(e)&&Array.isArray(e.args)&&e.args.at(-1)===GE,s1=e=>{if(!da(e)||!VE(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||ut(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===Jr&&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!ut(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},i1=e=>e===void 0?"absent":o1(e)?"exact":a1(e)||s1(e)?"stale-owned":"foreign",Ze=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},ua=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&&!da(n.mcpServers))throw new Ze(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(da(n.mcpServers)?n.mcpServers:void 0)?.[Lu];return{path:e,fileExisted:t,json:n,entry:o,ownership:i1(o)}},Mu=e=>{if(e.ownership==="foreign")throw new Ze(`MCP name conflict in ${e.path}: mcpServers.${Lu} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},jE=(e,t)=>{let n={...e},r=da(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[Lu]:r[Lu]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Xy=async(e,t)=>{if(Jy(e.entry,t))return;let n=await ua(e.path);if(!Jy(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 Or(e.path,jE(n.json,t)),{reading:e,afterEntry:t}},zy=async e=>{let t=await ua(e.reading.path);if(!Jy(t.entry,e.afterEntry))throw new Ze(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=jE(t.json,e.reading.entry);await Or(e.reading.path,n)},c1=async e=>{if(!ne())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 ua($u(e));Mu(t);let n=qy(e),r=(e.platform??wo)()==="darwin"&&n!==t.path?await ua(n):void 0;return r&&Mu(r),{active:t,...r?{legacy:r}:{}}},UE=async e=>{let t=await ua($u(e));Mu(t);let n=qy(e),r=(e.platform??wo)()==="darwin"&&n!==t.path?await ua(n):void 0;return r&&Mu(r),{active:t,...r?{legacy:r}:{}}},l1=async e=>{let t=[];try{let n=await Xy(e.active,KE());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Xy(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await zy(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 zy(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)}}},d1=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Xy(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await zy(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)},WE=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)."]},u1={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Qy="claude-desktop",eg="migrate",Bu="migrate-config",p1=[eg,Bu],HE=async e=>{await Ed(Qy,e?eg:Bu,{precedence:p1})},YE=new Set(["app-running","store-missing"]),f1={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},m1={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"}},h1="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",ZE=e=>{let t=(e.platform??wo)(),n=e.home??xc;return{home:n,appRunning:e.appRunning??As(t),firstPartyRoot:()=>aa({home:n,runtimePlatform:t}),thirdPartyRoot:()=>Rr({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},JE=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=f1[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.`:"")},XE=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=m1[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.`:"")},Ec=async(e,t)=>{try{let n=Pu(t.reportsToUser===!0),r=Sc(n,"session"),o={...ZE(e),assetClasses:n},a=await(e.pendingDesktopMigrationCount??NE)(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??la)(o);if(i.ok){let d=JE(i.lanes),u=XE(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(C=>C.reason!=="ambiguous"),h=i.blockedAssets??[],g=i.deferredAssets??[],y=i.retryableAssets??[];if(f.length===0&&h.length===0&&g.length===0&&y.length===0)return[d,u,m].filter(C=>!!C);if(t.preservePendingOp)return[d,u,m].filter(C=>!!C);await HE(r);let w=f.reduce((C,x)=>C+x.waiting,0),b=[w>0?`${w} more session${w===1?"":"s"}`:"",h.length>0?`${h.length} extension ${h.length===1?"store":"stores"}`:""].filter(Boolean),A=[...b.length>0?[`Queued: ${b.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...g.length>0?[`Queued: ${g.length} portable configuration ${g.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]:[],...A]}if(!YE.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 HE(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 fi?["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."]}},y1=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await oo(Qy),[]}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."]}},g1=e=>LE({id:Qy,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??wo)(),n=(e.home??xc)();return t==="darwin"?["/Applications/Claude.app",Qn(n,"Applications","Claude.app")]:t==="win32"?[Qn(process.env.LOCALAPPDATA??Qn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>se(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:",...WE(t)]:["Claude desktop org/API lane:",...WE(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`."]}),w1=(e={})=>{let t=g1(e),n=()=>(e.platform??wo)()==="darwin",r=()=>(e.platform??wo)()==="win32",o=(s,i)=>n()?AI(s,i,e):eE(s,s.clientKey??"",i,e),a=s=>n()?vI(s,e):tE(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??As((e.platform??wo)()))(),quitTarget:u1,needsTarget:()=>!1,async complete(s){if(s!==eg&&s!==Bu)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??la)({...ZE(e),assetClasses:s===Bu?Pu(!1):Pu(!0)});if(i.ok){let c=JE(i.lanes),l=XE(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(g=>g.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(g=>!!g):["No portable Claude Desktop data was left to bring across."]}}return YE.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?II(s,e):r()?oE(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let p=bn(e),m=await ia(p,e);if(m)return{status:"manual",manualAudience:"admin",messages:[by(m),...await Ec(e,i)]}}if(r()){let p;try{p=await go(e.runReg??Tr)}catch{return{status:"manual",manualAudience:"admin",messages:[h1,...await Ec(e,i)]}}if(p)return{status:"manual",manualAudience:"admin",messages:[My(p),...await Ec(e,i)]}}if(r()&&se(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 Ss(e);if(!p.supported)return{status:"manual",messages:[p.message??"Claude Desktop version is unsupported."]}}let c;try{c=await c1(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 Ec(e,i)]}}let d;try{d=await l1(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 Ec(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?n1:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=$u(e),c=await y1(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 UE(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()?en(e):void 0;if(!(h!==void 0&&p.changedFiles?.includes(h)===!0&&!await R(h)))return l(p)}let m;try{m=await d1(await UE(e))}catch(h){let g=h instanceof Ze?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...p.changedFiles??[],...g])],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 fe(i);let f=qy(e);return n()&&f!==i&&await fe(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(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await ua($u(e));return s.ownership!=="exact"||!da(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 Ss(e)).supported?Cy(s,e):!1:r()?rE(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await Ss(e)).supported)return["unknown"];let s=await SI(e);return s?[s]:["unknown"]}if(r())return await R(en(e))?await go(e.runReg??Tr)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=bn(e);return!await R(s.journal)||await ia(s,e)?!1:(await Ss(e)).supported}return r()&&await R(en(e))?!await go(e.runReg??Tr):!1}catch{return!1}}}},zE=w1();import{homedir as j1}from"node:os";import{join as Y1}from"node:path";import{rm as Yu}from"node:fs/promises";import{constants as qE,accessSync as b1,statSync as k1}from"node:fs";import{platform as tg}from"node:os";import{delimiter as C1,posix as A1,resolve as v1,win32 as S1}from"node:path";var I1="0.59.0",E1="1.1.4",Pr="Anyray \xB7 Claude",Dr="Anyray \xB7 Codex",Fu="__anyray-acp-agent",QE=(e,t,n)=>{let{command:r,args:o}=Rn([Fu,e,t,n]);return{command:r,args:o,env:{}}},Uu=(e=tg())=>e==="win32"?"npx.cmd":"npx",Wu=(e=process.env.PATH,t=tg())=>{if(!e)return;let n=Uu(t);for(let r of e.split(C1)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=v1(o,n);try{if(!k1(a).isFile())continue;return b1(a,t==="win32"?qE.F_OK:qE.X_OK),a}catch{}}},Hu=(e,t=tg())=>{let n=t==="win32"?S1:A1;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==Uu(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},x1="https://chatgpt.com/backend-api/codex",R1="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",ex="ANYRAY_ACP_CODEX_AUTHORIZATION",tx="ANYRAY_ACP_CODEX_CLIENT_KEY",nx="ANYRAY_ACP_CODEX_METADATA",rx=e=>be({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),O1=(e,t={})=>{let n=se(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":x1,"x-anyray-forward-headers":R1}:{},o=n?{...e.clientKey?{"x-anyray-api-key":tx}:{}}:{Authorization:ex};return rx(e)&&(o["x-anyray-metadata"]=nx),{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}}}:{}}},_1=e=>{let t=se(e,"openai"),n=rx(e);return{...t?e.clientKey?{[tx]:e.clientKey}:{}:{[ex]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[nx]:n}:{}}},ox=(e,t=Uu(),n={})=>({[Pr]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${I1}`],env:Tn(e).env},[Dr]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${E1}`],env:{CODEX_CONFIG:JSON.stringify(O1(e,n)),..._1(e)}}}),Rc=(e=Uu(),t="jetbrains")=>({[Pr]:QE("claude",e,t),[Dr]:QE("codex",e,t)}),pa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gu=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as T1}from"node:zlib";import{open as P1,readFile as sg,readdir as ju}from"node:fs/promises";import{dirname as ax,join as Ce}from"node:path";import{homedir as lx,platform as ig}from"node:os";var Ku="2025.3.2",Is="253.30387.147",Oc="com.intellij.ml.llm",ng=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),D1=1e4,N1=256*1024*1024,L1=16*1024*1024,rg=1024*1024,og=22,$1=og+65535,ag=iu,M1=()=>{let e=lx(),t=Ce(e,".cache","JetBrains","RemoteDev");switch(ig()){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"}]}},B1=()=>ig()==="linux"?Ce(lx(),".local","share","JetBrains"):We("JetBrains"),F1=()=>ig()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),U1=async(e,t=D1)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await ju(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 ju(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)]},W1=e=>{let t=ax(e);return t.endsWith(`${Ce("Contents","Resources")}`)?ax(t):t},H1=async e=>{try{let t=JSON.parse(await sg(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!lc(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:W1(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},G1=async(e,t)=>{let n;try{n=await P1(e,"r");let{size:r}=await n.stat();if(r<og||r>N1)return;let o=Math.min(r,$1),a=await Vu(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-og;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>L1||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),g=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),w=d+46+f+h+g;if(w>l.length)return;let b=l.subarray(d+46,d+46+f).toString("utf8");if(d=w,b!==t)continue;if(p===4294967295||m===4294967295||p>rg||m>rg)return;let A=await Vu(n,30,y);if(!A||A.readUInt32LE(0)!==67324752)return;let C=A.readUInt16LE(26),x=A.readUInt16LE(28),O=await Vu(n,p,y+30+C+x);return O?u===0?O.toString("utf8"):u===8?T1(O,{maxOutputLength:rg}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},sx=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!lc(n)))return{id:t,version:n}},K1=async(e,t)=>{let n=Ce(e,"META-INF","plugin.xml");if(await R(n))try{let o=sx(await sg(n,"utf8"));return{present:o?.id===Oc||t,descriptor:o?.id===Oc?o:void 0}}catch{return{present:t}}let r=[];try{r=(await ju(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 G1(o,"META-INF/plugin.xml"),s=a?sx(a):void 0;if(s?.id===Oc)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},ix=async e=>{let t;try{t=await ju(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=ng.has(o.name.toLowerCase()),i=ng.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=ng.has(o.name.toLowerCase());if(!a){let i=Ce(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await K1(Ce(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},V1=async e=>{try{return(await sg(Ce(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(Oc)}catch{return!1}},cx=e=>e.reduce((t,n)=>t?(ag(n,t)??-1)>0?n:t:n,void 0),dx=async(e={})=>{let t=e.configRoot??We("JetBrains"),n=e.userPluginsRoot??B1(),r=await U1(e.productRoots?e.productRoots.map(f=>({path:f,layout:"recursive"})):M1(),e.scanBudget),o=(await Promise.all(r.map(f=>H1(f)))).filter(f=>f!==void 0),a=o.length>0||await R(t);if(e.wsl??F1())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=>(ag(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 g=[Ce(h,"plugins"),Ce(n,f.dataDirectoryName),Ce(n,f.dataDirectoryName,"plugins")],y;for(let w of[...new Set(g)]){let b=await ix(w);if(b.present){y=b;break}}if(y??=await ix(Ce(f.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==Oc)){if(i.push(y.descriptor.version),await V1(h)){c=!0;continue}if(!((ag(y.descriptor.version,Is)??-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=cx(o.map(f=>f.version)),p=cx(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 ${Is}+, then run Connect again. No ACP config was written.`:c?m=`JetBrains AI Assistant is disabled; enable version ${Is}+ and run Connect again. No ACP config was written.`:p?m=`JetBrains AI Assistant ${p} is below the ACP minimum ${Is}; no ACP config was written.`:l?m=`Could not verify the local JetBrains AI Assistant version; require ${Is}+ before running Connect. No ACP config was written.`:m=`JetBrains AI Assistant ${Is}+ 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 Z1=[Pr,Dr],cg=()=>Y1(j1(),".jetbrains","acp.json"),fa=()=>`${cg()}.anyray-state`,J1=(e,t,n="npx")=>{let r=pa(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,Rc(n,"jetbrains")),{...e,agent_servers:r}},X1=(e,t,n)=>{if(!pa(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=pa(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of Z1)if(c in r){if(!Gu(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}},z1=(e=dx)=>({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=cg(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=Wu();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=Rc(a,"jetbrains");return await Wl({configPath:r,current:c,next:J1(c,t,a),journalPath:fa(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,fa()]}},async revert(t){let n=cg(),r=async()=>{if(!await R(n))return t.dryRun||(await fe(n),await Yu(fa(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await F(n)}catch{return t.dryRun||(await fe(n),await Yu(fa(),{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(fa());(u.version===1||u.version===2)&&pa(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 Bo(n);let l=X1(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 Yu(n,{force:!0}):await q(n,l.next,{backup:!1})),t.dryRun||(await fe(n),await Yu(fa(),{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():Ul(n,fa(),r)}}),ux=z1();import{homedir as Ju}from"node:os";import{join as Xu}from"node:path";import{rm as lg}from"node:fs/promises";var dg="1.0.0",zu=["anyray-claude-acp","anyray-codex-acp"],q1=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],ug=()=>Xu(Ju(),".windsurf","acp","registry.json"),pg=()=>Xu(Ju(),".windsurf-next","acp","registry.json"),Es=e=>`${e}.anyray-state`,px=e=>({binary:Object.fromEntries(q1.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),mx=(e="npx")=>{let t=Rc(e,"windsurf");return[{id:zu[0],name:Pr,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:px(t[Pr])},{id:zu[1],name:Dr,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:px(t[Dr])}]},Zu=e=>!Array.isArray(e)||e.some(t=>!pa(t)||typeof t.id!="string")?null:e,Q1=(e,t="npx")=>{if(e.version!==void 0&&e.version!==dg||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:Zu(e.agents);if(!n)return null;let r=new Set(zu);return{...e,version:typeof e.version=="string"?e.version:dg,agents:[...n.filter(o=>!r.has(o.id)),...mx(t)],extensions:e.extensions??[]}},eG=(e,t,n)=>{let r=Zu(e.agents);if(!r)return null;let o=Zu(t.agents)??[],a=new Map((Zu(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!zu.includes(u.id)){l.push(u);continue}if(!Gu(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===dg&&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}},fx=async()=>{let e=[];return(await R(pg())||await R(Xu(Ju(),".windsurf-next")))&&e.push(pg()),(await R(ug())||await R(Xu(Ju(),".windsurf"))||await R(We("Devin"))||await R(We("Windsurf")))&&e.push(ug()),e},hx={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await fx();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await fx();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=Wu();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=Q1(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=mx(r);await Wl({configPath:s,current:i,next:c,journalPath:Es(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Es(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=[ug(),pg()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await fe(a),await lg(Es(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(Es(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 Bo(a);let p=eG(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 lg(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 fe(a),await lg(Es(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await Ul(a,Es(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var ie=[Dn,XC,Ki,rS,OS,US,YS,ux,zE,hx,aA],Qe=e=>ie.find(t=>t.id===e);var Je=async(e=L,t=Vn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:Re({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 fg=5e3,yx=3e4,tG=1440*60*1e3,nG=e=>new Promise(t=>setTimeout(t,e)),rG=async(e=L,t=Vn)=>(await Je(e,t))?.target,oG=e=>Qe(e)?.quitGated,gx=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??oG,o=t.readPending??Fi,a=t.clearPending??jm,s=t.targetFromProfile??rG,i=t.sleep??nG,c=t.now??Date.now,l=t.maxWaitMs??tG;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),p=c(),m=fg;for(;;){let f=await o(n);if(!f||c()-p>l)return 0;if(d.isRunning()){await i(m),m=Math.min(yx,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=fg;continue}if((await u(f.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(m),m=Math.min(yx,m*2);continue}if(await a(n,f)!=="superseded")return 0;await i(m),m=fg}}catch{return 0}};import{z as Tc}from"zod";import{createHash as aG,randomBytes as sG,timingSafeEqual as iG}from"node:crypto";import{createServer as cG}from"node:http";var _c="127.0.0.1",lG=2147483647,dG="/callback",mg=12,uG="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",hg=e=>e.length===mg&&[...e].every(t=>uG.includes(t)),er=class extends Error{kind;constructor(t,n){super(n),this.name="ConnectorOauthCallbackError",this.kind=t}},ma=(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)},pG=e=>new Promise(t=>{if(e.writableFinished||e.destroyed){t();return}e.once("finish",()=>t()),e.once("close",()=>t())}),wx=async()=>{let e;try{e=sG(32).toString("base64url")}catch{throw new er("listen","Could not open a local callback port for the browser.")}let t=Buffer.from(aG("sha256").update(e).digest("base64url")),n=p=>{let m=Buffer.from(p);return m.length===t.length&&iG(m,t)},r,o=()=>{},a=new Promise(p=>{o=p}),s=!1,i=cG((p,m)=>{if(p.socket.remoteAddress!==_c||p.method!=="GET"||p.url===void 0||!p.url.startsWith("/")||p.headers.host!==r){ma(m,404,"Not found.");return}let f;try{f=new URL(p.url,`http://${_c}`)}catch{ma(m,404,"Not found.");return}if(f.pathname!==dG){ma(m,404,"Not found.");return}let h=[...f.searchParams.entries()],g=f.searchParams.getAll("claim"),y=f.searchParams.getAll("nonce"),w=g[0]??"";if(h.length!==2||g.length!==1||y.length!==1||!hg(w)||!n(y[0]??"")){ma(m,404,"Not found.");return}if(s){ma(m,409,"Callback already received.");return}s=!0,o({status:"claim",claimCode:w,response:m})}),c=()=>new er("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:_c,port:0},()=>{i.off("error",f),p()})})}catch{throw i.close(),c()}let l=i.address();if(l===null||typeof l=="string"||l.address!==_c||l.port<=0)throw i.close(),c();let d=l.port;r=`${_c}:${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,g)=>{let y=!1,w=C=>{y||(y=!0,clearTimeout(A),m.signal?.removeEventListener("abort",b),C())},b=()=>w(()=>g(new er("lost","Connector authorization was cancelled."))),A=setTimeout(()=>w(()=>g(new er("timeout","Timed out waiting for the browser."))),Math.min(Math.max(m.timeoutMs,0),lG));if(m.signal?.aborted){b();return}m.signal?.addEventListener("abort",b,{once:!0}),a.then(C=>w(()=>h(C)))})}catch(h){throw await u(),h}if(f.status==="unavailable")throw await u(),new er("lost","The local callback port stopped listening.");try{let h=await p(f.claimCode);return ma(f.response,200,"Connected. You can close this window."),h}catch(h){throw ma(f.response,502,"Anyray could not finish connecting. Return to the terminal."),h}finally{await pG(f.response),await u()}},close:u}};import{spawn as fG}from"node:child_process";import{platform as mG}from"node:os";var hG=2e3,Nr=e=>new Promise(t=>{try{let n=new URL(e);if(n.protocol!=="https:"&&n.protocol!=="http:"){t(!1);return}let r=mG(),o=r==="darwin"?"open":r==="win32"?"cmd":"xdg-open",a=r==="win32"?["/c","start",'""',`"${n.href}"`]:[n.href],s=fG(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),hG);l.unref(),s.on("error",()=>c(!1)),s.on("exit",d=>c(d===0)),s.unref()}catch{t(!1)}});import{fstatSync as vG,openSync as SG,statSync as IG}from"node:fs";import{createInterface as EG}from"node:readline/promises";import{ReadStream as xG}from"node:tty";import{execFileSync as bx}from"node:child_process";import yG from"node:os";var yg=e=>{try{return bx("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},gG=e=>{try{return bx("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},wG=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"]),gg=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:wG.has(t):!0},qu=()=>{try{return yG.userInfo().username||void 0}catch{return}},kx=()=>yg("user.name")??yg("user.email")??qu()??"unknown",Cx=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||yg),global:e.globalGitConfig??(t||gG)}},ha=e=>{try{return e()?.trim()||void 0}catch{return}},wg=(e={})=>{let t=Cx(e),n=ha(e.osUsername??qu),r=ha(()=>t.global("user.email"))??ha(()=>t.local("user.email"));return r||(ha(()=>t.global("user.name"))??ha(()=>t.local("user.name"))??n??"unknown")},Ax=(e={})=>{let t=wg(e);if(gg(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=Cx(e);return!!(ha(()=>n.global("user.email"))??ha(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var xs=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,bG=xs(process.stdout,process.env),bg=xs(process.stderr,process.env),Qu=!1,Rs=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,kg=()=>{Qu=!0},Cg=()=>{Qu=!1},ep=()=>Qu?bg:bG,tp=e=>{Qu?console.error(e):console.log(e)},Z=e=>Rs("1",e,ep()),v=e=>Rs("2",e,ep()),kG=e=>Rs("32",e,ep()),CG=e=>Rs("33",e,bg),AG=e=>Rs("31",e,bg),it=e=>Rs("36",e,ep()),k=e=>tp(e),W=e=>tp(`
|
|
282
|
+
${Z(e)}`),M=e=>tp(v(e)),B=e=>tp(`${kG("\u2713")} ${e}`),P=e=>console.error(`${CG("!")} ${e}`),D=e=>console.error(`${AG("\u2717")} ${e}`);var xt=()=>!!process.stdin.isTTY,RG=()=>{try{let e=vG(0);return e.isCharacterDevice()&&e.rdev===IG("/dev/tty").rdev}catch{return!1}},Ag=()=>{if(RG()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new xG(SG(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},Et=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},vx=async(e,t)=>{let n=t.input??Ag(),r=t.output??process.stdout,o=EG({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 Et))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new Et)))})}finally{o.close(),n.close()}},ya=async(e,t={})=>{let n=(await vx(`${e} ${v("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Os=async(e,t,n={})=>{let r=t?` ${v(`[${t}]`)}`:"";return(await vx(`${e}${r}: `,n)).trim()||t},vg=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=kx();return n||!xt()?(M(`Your name: ${r} ${v("(auto-detected \u2014 pass --user to change)")}`),r):Os("? Your name",r)},Sg=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||!xt()))return Os("? Team (optional)")},tr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return dn(e??n)},Sx=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,bo="claude-desktop",np=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await go(e.runReg??Tr))return n("managed-policy")}catch{return n("policy-unreadable")}let s=en({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=bn(r);return await ia(o,r)?n("managed-policy"):(await Ss({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")}},rp=e=>e.id!==bo||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",OG={"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"},op=(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=OG[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 _G=`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
|
-
`,Ix=5*6e4,
|
|
297
|
-
`)},a;try{a=
|
|
296
|
+
`,Ix=5*6e4,TG=3e4,Lr=class extends Error{},_s=class extends Error{},PG=e=>{let t={help:!1};if(e.length===0)throw new Lr("Missing command: authorize.");let[n,...r]=e;if(n==="--help"||n==="-h")return{help:!0};if(n!=="authorize")throw new Lr(`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 Lr(`${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 Lr(`Unknown option: ${a}.`);if(t.name===void 0)t.name=a;else throw new Lr("Give one connector name (quote it if it has spaces).")}}if(t.help)return t;if(!t.name?.trim())throw new Lr("Missing connector name.");if(t.name=t.name.trim(),t.claim!==void 0&&(t.claim=t.claim.trim().toUpperCase(),!hg(t.claim)))throw new Lr(`A claim code is ${mg} characters from A-Z and 2-9.`);return t},Ig=e=>e.ssoLink?`Not enrolled. Reconnect with \`npx anyray-connect@latest --sso ${e.ssoLink}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.",Ox=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 _s(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)}},DG=(e,t)=>{switch(e){case 400:return"The gateway rejected the connector name or loopback port.";case 401:return Ig(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}).`}},NG=(e,t)=>{switch(e){case 400:return"The gateway rejected the claim code.";case 401:return Ig(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}).`}},LG=Tc.object({authorizationUrl:Tc.string().url().refine(e=>new URL(e).protocol==="https:"),loopbackPort:Tc.number().int().optional()}),$G=Tc.object({user:Tc.string().regex(/^[^\p{Cc}]{1,320}$/u).optional()}),MG=e=>$G.safeParse(e).data?.user,Ex=async(e,t,n,r)=>{let{status:o,body:a}=await Ox(e,"/connect/mcp-oauth/authorize",r?{name:n,loopbackPort:r.port,loopbackNonce:r.nonce}:{name:n}),s=o===200?LG.safeParse(a).data:void 0;if(!s)throw new _s(o===200?"The gateway returned no authorization URL.":DG(o,t));return s},xx=async(e,t,n,r)=>{let{status:o,body:a}=await Ox(e,"/connect/mcp-oauth/complete",{name:n,claimCode:r});if(o!==200)throw new _s(NG(o,t));return MG(a)},BG=/^[A-Za-z0-9 ._-]+$/,FG="<connector name>",UG=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")}`}),_x=e=>{let t=BG.test(e)?e:FG,n=[` anyray-connect connectors authorize "${t}" --claim <code>`];return t!==e&&n.push(`Connector name: ${UG(e)}`),n},Rx=e=>["The page then shows a claim code. Back here, run:",..._x(e)],Tx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=d=>{r.write(`${d}
|
|
297
|
+
`)},a;try{a=PG(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(_G),0;let s=a.name,i=await(t.loadProfile??L)(),c;try{let d=Re({origin:tr(a.gateway,i),clientKey:i.clientKey});if(!d.clientKey)return o(Ig(i)),1;c={origin:d.origin,clientKey:d.clientKey,fetch:t.fetch??fetch,requestTimeoutMs:t.requestTimeoutMs??TG}}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 xx(c,i,s,a.claim));let d=async()=>{let{authorizationUrl:h}=await Ex(c,i,s);o("Open this URL in a browser and consent:"),o(` ${h}`);for(let g of Rx(s))o(g)},u=async h=>{await(t.openBrowser??
|
|
299
|
+
`),0);try{if(a.claim!==void 0)return l(await xx(c,i,s,a.claim));let d=async()=>{let{authorizationUrl:h}=await Ex(c,i,s);o("Open this URL in a browser and consent:"),o(` ${h}`);for(let g of Rx(s))o(g)},u=async h=>{await(t.openBrowser??Nr)(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??ur)())return o("This is a remote session, so the browser cannot come back here."),await d(),1;let p;try{p=await(t.createListener??wx)()}catch(h){return o(h instanceof er?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 Ex(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 Rx(s))o(h);return 1}await u(m.authorizationUrl);let f=Math.round((t.timeoutMs??Ix)/6e4);o(`Waiting for consent (up to ${f} minute${f===1?"":"s"}).`);try{return l(await p.waitForClaim(h=>xx(c,i,s,h),{timeoutMs:t.timeoutMs??Ix}))}catch(h){if(!(h instanceof er))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 g of _x(s))o(g);return o("Otherwise run this command again."),1}}catch(d){if(d instanceof _s)return o(d.message),1;throw d}};var WG=`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
|
-
`,Px=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(
|
|
307
|
+
`,Px=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(WG),0;k(Z("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??sS)();if(!n)return D("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;k(` 1. Open ${it(n.verificationUri)}`),k(` 2. Enter the code: ${Z(n.userCode)}`),M(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??iS)(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??cS)(r.token,o);B(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??Sh)(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??cs)(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 Dx=`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
|
-
`,
|
|
320
|
-
`),0;k(Z(`Copilot models your seat serves (via ${o.origin})`));for(let f of l){let h=f.id===m?"*":" ",g=
|
|
319
|
+
`,HG=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},GG=e=>{let t=ie.find(n=>n.id===ea);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},KG=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(" / ")},VG=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${nc(t)}/${Cr(n)==="responses"?"responses":"chat/completions"}`,Nx=async(e=[],t={})=>{let n=HG(e);if(n.help)return process.stdout.write(Dx),0;if(n.error)return D(n.error),process.stdout.write(Dx),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??Xd)({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??cs)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=Dh(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:Cr(f.id),...f.maxPromptTokens?{maxPromptTokens:f.maxPromptTokens}:{},...f.maxOutputTokens?{maxOutputTokens:f.maxOutputTokens}:{}}))})}
|
|
320
|
+
`),0;k(Z(`Copilot models your seat serves (via ${o.origin})`));for(let f of l){let h=f.id===m?"*":" ",g=KG(f);k(` ${h} ${f.id.padEnd(24)}${g?v(g):""}`)}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??Jd)(VG(o,i,d.id),{...Ph(),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??GG)(o);if(m.status!=="configured"){for(let f of m.messages)k(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 KK}from"node:fs";import{spawnSync as d0}from"node:child_process";import{createHash as VK}from"node:crypto";import{access as u0,chmod as Wg,copyFile as jK,lstat as YK,mkdir as ZK,mkdtemp as p0,readFile as kp,rename as JK,rm as Co,stat as XK,writeFile as zK}from"node:fs/promises";import{constants as f0}from"node:fs";import{platform as Ls,tmpdir as qK}from"node:os";import{dirname as QK,isAbsolute as e2,join as gp}from"node:path";import{z as Ke}from"zod";var Le="0.11.212";import{createWriteStream as fK}from"node:fs";import{spawnSync as Zx}from"node:child_process";import{chmod as Jx,copyFile as Tg,lstat as Pg,mkdir as Dg,readdir as mp,realpath as fp,rename as dp,rm as Bt,stat as Ng,symlink as mK,writeFile as hK}from"node:fs/promises";import{createHash as yK}from"node:crypto";import{basename as up,dirname as nn,join as ba}from"node:path";import{Readable as gK}from"node:stream";import{pipeline as wK}from"node:stream/promises";var jG=["hook_registration","mcp_registration","hook_binary","beacon_target"],ga=e=>e.status==="configured"||e.status==="queued",wa=async(e,t=ie)=>{let n=new Set(e),r=[];for(let o of t)if(n.has(o.id))try{(await o.detect()).installed&&r.push(o)}catch{}return r},Ts=async(e,t,n=ie)=>{let r=[];for(let o of await wa(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},Eg=async(e,t=ie)=>{let n=[];for(let r of await wa(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(jG.map(o=>[o,"unreadable"]))})}return n},Lx=e=>e.filter(t=>!t.integrationStatus),YG=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},tn=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=YG(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 $x}from"node:fs";import{access as ZG,chmod as JG,lstat as XG,mkdir as zG,open as qG,readFile as QG,realpath as eK,rm as tK,stat as Bx,writeFile as nK}from"node:fs/promises";import{randomUUID as rK}from"node:crypto";import{platform as Rg}from"node:os";import{dirname as oK,join as aK,posix as sK,win32 as Fx}from"node:path";var Nc="/usr/local/bin/anyray-credential-helper",Lc="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",ap="/usr/local/bin/anyray-bootstrap-headers-helper",sp="C:\\Program Files\\Anyray\\anyray-bootstrap-headers-helper.cmd",Dc="Managed by anyray-connect desktop helper; do not edit.",iK=`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
|
|
@@ -338,8 +338,8 @@ Options:
|
|
|
338
338
|
--platform <target> posix or windows (default: current host).
|
|
339
339
|
--wrapper <kind> credential or bootstrap-headers (--print only).
|
|
340
340
|
--path <absolute> Credential helper destination. Defaults by target:
|
|
341
|
-
${Lc}
|
|
342
341
|
${Nc}
|
|
342
|
+
${Lc}
|
|
343
343
|
--bootstrap-headers-path <absolute>
|
|
344
344
|
Bootstrap-headers helper destination. Defaults:
|
|
345
345
|
${ap}
|
|
@@ -359,16 +359,16 @@ Examples:
|
|
|
359
359
|
anyray-connect desktop helper --print --wrapper bootstrap-headers \\
|
|
360
360
|
--platform posix --bin /usr/local/bin/anyray-connect \\
|
|
361
361
|
> anyray-bootstrap-headers-helper
|
|
362
|
-
`,xg=(e=Rg())=>e==="win32"?"windows":"posix",Ux=e=>e==="windows"?Nc
|
|
362
|
+
`,xg=(e=Rg())=>e==="win32"?"windows":"posix",Ux=e=>e==="windows"?Lc:Nc,Wx=e=>e==="windows"?sp:ap,Mx=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},cK=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--write":Mx(t,"write");break;case"--print":Mx(t,"print");break;case"--bin":t.binaryPath=o();break;case"--path":t.helperPath=o();break;case"--bootstrap-headers-path":t.bootstrapHeadersHelperPath=o();break;case"--wrapper":{let a=o();if(a!=="credential"&&a!=="bootstrap-headers")throw new Error("--wrapper must be credential or bootstrap-headers");t.wrapper=a;break}case"--platform":{let a=o();if(a!=="posix"&&a!=="windows")throw new Error("--platform must be posix or windows");t.targetPlatform=a;break}case"--help":case"-h":t.help=!0;break;default:throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r}`)}}return t},lK=e=>/[\0\r\n]/.test(e),dK=e=>/^[A-Za-z]:[\\/]/.test(e)&&Fx.isAbsolute(e),$c=(e,t)=>!lK(e)&&(t==="windows"?dK(e):sK.isAbsolute(e)),Pc=e=>e.replace(/\\/g,"/").toLowerCase(),ip=(e,t)=>{if(!$c(e,t))return!1;let n=Pc(e);return!(/(^|\/)_npx(\/|$)/.test(n)||n==="/tmp"||n.startsWith("/tmp/")||n==="/private/tmp"||n.startsWith("/private/tmp/")||n==="/var/tmp"||n.startsWith("/var/tmp/")||n.startsWith("/var/folders/")||n.startsWith("/private/var/folders/")||/\/appdata\/local\/temp(\/|$)/.test(n)||t==="windows"&&(/[%!^&|<>()"]/.test(e)||!/\.exe$/i.test(e)))},Mc=(e,t)=>t==="windows"?Fx.normalize(e):e,Og=e=>`'${e.replace(/'/g,`'"'"'`)}'`,Hx=(e,t)=>{if(!ip(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Mc(t,e);if(e==="windows")return["@echo off",`REM ${Dc}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" ${ho}`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
363
363
|
`);let r=Og(n);return["#!/bin/sh",`# ${Dc}`,'if [ "$#" -eq 0 ]; then',` exec ${r} ${ho}`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
|
|
364
364
|
`)},Gx=(e,t)=>{if(!ip(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Mc(t,e);return e==="windows"?["@echo off",`REM ${Dc}`,'if not "%~1"=="" exit /b 64',`"${n}" ${pc}`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
365
365
|
`):["#!/bin/sh",`# ${Dc}`,'if [ "$#" -eq 0 ]; then',` exec ${Og(n)} ${pc}`,"fi","exit 64",""].join(`
|
|
366
|
-
`)},cp=(e,t)=>{if(!$c(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Mc(t,e);if(e==="windows"){if(/[%!^&|<>()"]/.test(n)||!/\.cmd$/i.test(n))throw new Error("Windows --helper-path must be a safe absolute .cmd path without batch metacharacters");return{command:"C:\\Windows\\System32\\cmd.exe",args:["/d","/s","/c",`call "${n}" --token`]}}return{command:n,args:["--token"]}},Kx=async e=>{try{return await
|
|
366
|
+
`)},cp=(e,t)=>{if(!$c(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Mc(t,e);if(e==="windows"){if(/[%!^&|<>()"]/.test(n)||!/\.cmd$/i.test(n))throw new Error("Windows --helper-path must be a safe absolute .cmd path without batch metacharacters");return{command:"C:\\Windows\\System32\\cmd.exe",args:["/d","/s","/c",`call "${n}" --token`]}}return{command:n,args:["--token"]}},Kx=async e=>{try{return await QG(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},uK=async(e,t)=>{try{let n=await eK(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!ip(r,t))throw new Error;if(!(await Bx(n)).isFile())throw new Error;await ZG(n,t==="posix"?$x.X_OK:$x.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},Vx=e=>e.slice(0,300).includes(Dc),jx=async(e,t,n)=>{let r=await Kx(e);if(r!==void 0&&r!==t&&!Vx(r))throw new Error(`refusing to replace non-Anyray file at ${e}; choose another --path`);if(r===t){if(n==="windows")return"unchanged";try{if(((await Bx(e)).mode&511)===493)return"unchanged"}catch{}}let o=oK(e);try{await zG(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=aK(o,`.anyray-helper.${process.pid}.${rK()}.tmp`),s=!1;try{await nK(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await JG(a,493);let i=await qG(a,"r");try{await Kr(i)}finally{await i.close()}await ke(a,e),s=!0}catch{throw new Error(`could not install helper at ${e}`)}finally{s||await tK(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},pK=(e,t,n)=>{let r=n==="windows"?`"${Mc(t,n)}" `:` exec ${Og(t)} `;return e.split(/\r?\n/).some(o=>o.startsWith(r)&&o.length>r.length)},lp=async(e,t={})=>{let n=xg((t.platform??Rg)());if(!ip(e,n))return;let r=[{path:t.helperPath??Ux(n),content:Hx(n,e)},{path:t.bootstrapHeadersHelperPath??Wx(n),content:Gx(n,e)}];for(let o of r)try{if((await XG(o.path).catch(()=>{}))?.isSymbolicLink())continue;let a=await Kx(o.path);if(a===void 0||a===o.content||!Vx(a)||!pK(a,e,n))continue;await jx(o.path,o.content,n)}catch{}},Yx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=cK(e);if(o.help)return n.write(iK),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");if(o.wrapper&&o.mode!=="print")throw new Error("--wrapper applies to --print only; --write installs both helpers");let a=(t.platform??Rg)(),s=o.targetPlatform??xg(a),i=o.binaryPath,c=(d,u,p)=>{let m=Mc(u??p,s);if(!$c(m,s))throw new Error(`${d} must be an absolute ${s} path`);if(s==="windows"&&cp("windows",m),Pc(m)===Pc(i))throw new Error(`${d} must differ from --bin (the helper cannot invoke itself)`);return m},l=[{kind:"credential",label:"credential helper",path:c("--path",o.helperPath,Ux(s)),content:Hx(s,i)},{kind:"bootstrap-headers",label:"bootstrap-headers helper",path:c("--bootstrap-headers-path",o.bootstrapHeadersHelperPath,Wx(s)),content:Gx(s,i)}];if(Pc(l[0].path)===Pc(l[1].path))throw new Error("--path and --bootstrap-headers-path must differ");if(o.mode==="print"){let d=o.wrapper??"credential",u=l.find(p=>p.kind===d);return n.write(u.content),r.write(`Deploy this wrapper at ${u.path} after deploying the binary at ${i}.
|
|
367
367
|
`),0}if(s!==xg(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await uK(i,s);for(let d of l){let u=await jx(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 bK=new RegExp(`/releases/tag/${Ko}([0-9][0-9A-Za-z.-]*)$`),kK=300*1024*1024,Fc=1e4,CK=5*6e4,AK=360*6e4,vK=30*6e4,ko=(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 SK=e=>{if(e)return bK.exec(e.trim())?.[1]},
|
|
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()}},$g=e=>e.mode==="off"?{allow:!1,outcome:"fleet-off"}:e.mode==="directed"&&e.initiator==="tick"?{allow:!1,outcome:"fleet-directed"}:{allow:!0},IK=e=>e==="auto",Xx=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&&ko(e.current,e.minVersion)<0&&ko(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},EK=e=>ko(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}:{...Xx(e),downgradeBlocked:!1},xK=(e=process.execPath)=>{let t=Hf(e);return t?nn(t):nn(nn(e))},RK=async(e=vt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=hr(xK(e.execPath)).launcher;try{if(await fp(t)!==await fp(e.execPath))return}catch{return}return t},OK=["connect-tray","connect-tray.exe"],_K=async e=>{let t=nn(e);for(let n of OK)try{let r=await Lg(ba(t,n)),o=process.platform==="win32"||(r.mode&73)!==0;if(r.isFile()&&o)return!0}catch{}return!1},Uc=async(e=vt(),t=ee())=>{let n=await RK(e);if(n)return{kind:"managed",root:nn(nn(n)),link:n,entryPath:jr(e)};let r=jr(e);return Kf(r,t)?{kind:"durable",root:t,entryPath:r}:Uf(r)?{kind:"npm",root:t,entryPath:r}:await _K(r)?{kind:"sidecar",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},hp=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)}},Mg=async(e=Fc)=>{let t=await hp(`${to}/latest`,e,{redirect:"manual"});return SK(t.headers.get("location"))},TK=async e=>{try{let t=await hp(`${e}/connect-update.json`,Fc);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}},ka=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},Wc=async(e,t,n)=>{let r=await hp(e,CK);if(!r.ok||!r.body)throw new ka(r.status);let o=yK("sha256"),a=0;if(await wK(gK.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>kK)throw new Error("asset exceeds size cap");o.update(c),yield c}},fK(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},PK=e=>up(e)===no()?up(nn(e)):up(e),DK=async e=>{let t=await mp(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Bt(ba(e,n),{force:!0}).catch(()=>{})},zx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Bt(r,{force:!0}).catch(()=>{});let o=!1;try{await dp(e,r),o=!0}catch{}try{await Tg(t,e),await hK(wi(e),PK(t))}catch(a){throw o&&await dp(r,e).catch(()=>{}),a}await Bt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Bt(n,{force:!0}),await mK(t,n),await dp(n,e)},Bg=(e,t)=>e===t||up(e)===Sm?448:493,Bc=async(e,t)=>{let n=(await Lg(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await Jx(e,n&4095|t).catch(()=>{})},pp=async(e,t)=>{await Dg(e,{recursive:!0,mode:t}),await Bc(e,t)},LK=async(e,t,n)=>{let r=Bg(e,ee());if(r!==448){let o=hr(e),a=o.versionsDir;await Bc(e,r),await Bc(nn(o.launcher),r),await Bc(a,r);for(let s of await mp(a).catch(()=>[]))await Bc(ba(a,s),r)}await(n.refreshDesktopHelpers??lp)(t)},NK=async(e,t={})=>{let n=hr(e.root),r=nn(n.launcher),{versionsDir:o,launcher:a}=n,s=Bg(e.root,(t.privateRoot??ee)());await pp(r,s),await pp(o,s);let i=ba(o,e.version),l=(await Pg(i).catch(()=>{}))?.isFile()?i:ba(i,no());if(!(await Pg(l).catch(()=>{}))?.isFile()){let u=await(t.fetchResponse??hp)(`${e.tagUrl}/SHA256SUMS`,Fc),p=u.ok?Ng(await u.text(),e.asset):void 0;if(!p)throw new Error("no published checksum");await pp(nn(l),s),await DK(nn(l));let m=`${l}.part-${process.pid}`;try{await(t.download??Wc)(`${e.tagUrl}/${e.asset}`,m,p),await Jx(m,493),await dp(m,l)}catch(f){throw await Bt(m,{force:!0}).catch(()=>{}),f}}return await(t.activate??zx)(a,l),{link:a,target:l,versionsDir:o}},$K=async e=>{Zx(e.target,[Vo,e.link],{stdio:"ignore",timeout:Fc})},MK=async e=>{if(process.platform==="darwin"){let t=Zx("/usr/bin/codesign",["--verify","--strict",e],{stdio:"ignore",timeout:Fc});return!t.error&&t.status===0}return!0},BK=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??wa)(n);if(r.length>0){let o=await(t.resolveTarget??Je)(async()=>e);if(!o||!(await(t.repair??tn)(r,o.target)).every(ga))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&ot(e)&&!(await(t.installScheduler??eo)()).ok)},FK=async e=>{let t=await e.install();if(!await(e.smoke??MK)(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},UK=async(e,t)=>{let n=await mp(e).catch(()=>[]);for(let r of n)t.includes(r)||await Bt(ba(e,r),{force:!0,recursive:!0}).catch(()=>{})},WK=async e=>{let t=await mp(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Bt(ba(e,n),{force:!0}).catch(()=>{})},HK=async(e,t)=>{let n=async()=>{await Bt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Dg(e,{recursive:!1}),n}catch{}let r=await Lg(e).catch(()=>{});if(!(!r||t-r.mtimeMs<vK)){await n();try{return await Dg(e,{recursive:!1}),n}catch{return}}},_g=e=>hr(e).state,GK=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}},Ps=async(e={})=>{let t=e.now??Date.now,n=Ne;if(pr(Ln(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??vt(),o=e.root??ee(),a;try{let s=await Uc(r,o);if(o=s.root,s.kind==="sidecar")return{outcome:"sidecar",current:n};if(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??N)().catch(()=>({})),d=l.autoUpdate!==!1,u=l.fleetUpdatePolicy?.mode??"auto",p=$g({mode:u,initiator:e.initiator??"tick"});if(!p.allow)return{outcome:p.outcome,current:n};!i&&s.link&&!e.checkOnly&&(d||c)&&await LK(o,s.link,e).catch(()=>{});let m=Oi(e.platform??process.platform,e.arch??process.arch);if(!m)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Mg)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let f=a;if(!i&&f===n)return{outcome:"current",current:n,latest:f};if(i&&ko(f,n)<0)return{outcome:"migration-deferred",current:n,latest:f};let h=await GK(_g(o));if((e.respectFailureBackoff===!0||!c)&&h.failedVersion===f&&h.failedAt!==void 0&&t()-h.failedAt<AK)return{outcome:"failed",current:n,latest:f};let g=`${to}/download/${Ko}${f}`,y=d||c||!IK(u)?void 0:await(e.minimumVersion??TK)(g),w={current:n,latest:f,autoUpdate:d,forced:c,minVersion:y},b=i?EK(w):{...Xx(w),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===ee()?await Xe():await pp(o,Bg(o,ee()));let A=hr(o),C=await HK(A.lock,t());if(!C)return{outcome:i?"migration-available":"available",current:n,latest:f};let x,O;try{await WK(nn(A.launcher));let S=await fp(A.versionsDir).catch(()=>{}),E=await fp(A.launcher).catch(()=>{}),T=E&&Nl(E,S)?E:void 0,I=A.launcher;i&&process.platform==="win32"&&(await Pg(I).catch(()=>{}))?.isFile()&&(O=`${I}.rollback-${process.pid}`,await Tg(I,O));let K=()=>(e.installBinary??NK)({root:o,version:f,asset:m,tagUrl:g});i?x=await FK({install:K,smoke:e.smoke,rollback:async({link:G,target:X})=>{O?(await Tg(O,G),await Bt(wi(G),{force:!0}).catch(()=>{})):T&&T!==X?await zx(G,T):(await Bt(G,{force:!0}),await Bt(wi(G),{force:!0}).catch(()=>{}))},repoint:async G=>e.repoint?e.repoint(l,G):BK(l),prune:async()=>{await(e.pruneDurable??(G=>Ml(G)))(r)}}):x=await K(),await UK(x.versionsDir,[f,n]),await(e.refreshHelpersFromInstalled??$K)(x).catch(()=>{}),await Bt(_g(o),{force:!0}).catch(()=>{})}finally{O&&await Bt(O,{force:!0}).catch(()=>{}),await C()}return{outcome:i?"migrated":"updated",current:n,latest:f,managedPath:x.link,mandatory:b.mandatory}}catch{return a&&await q(_g(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},qx=async(e={})=>{let t=e.context??vt(),n=await Uc(t,e.root??ee()),r=Fa(e.root??ee());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Ne,managedPath:n.link??r}:Ps({initiator:"human",...e,context:t,allowNpmMigration:!0})},Ca=async(e={})=>{let t=e.context??vt(),n=e.root??ee(),r=await Uc(t,n),o=r.kind==="npm"||r.kind==="durable"?Fa(n):void 0,a=await(e.load??N)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!Oi(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=pr(Ln(e.env??process.env))?"container":r.kind==="sidecar"?"sidecar":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 tV="fleetd-installer-v4.89.2",Qx=`https://github.com/anyrayHQ/install/releases/download/${tV}`,nV=1e4,rV=1e4,e0=31,oV=1500,m0=20*1024,Fg=20,aV="0.25",sV="/var/tmp",Ls="/Library/LaunchDaemons/com.fleetdm.orbit.plist",wp="/etc/default/orbit",Gc="/opt/orbit/anyray-enroll-secret.txt",h0="/opt/orbit/secret-orbit-node-key.txt",iV="/opt/orbit/bin/orbit/orbit",Kc="C:\\Program Files\\Orbit",cV=`${Kc}\\bin\\orbit`,y0=`${Kc}\\secret-orbit-node-key.txt`,Hc=`${Kc}\\secret.txt`,lV=`${Kc}\\fleet_url.txt`,g0=`${Kc}\\anyray-managed.txt`,bp="Fleet osquery",Hg="C:\\Windows\\System32\\sc.exe",jg="C:\\Windows\\System32\\whoami.exe",yp="C:\\Windows\\System32\\icacls.exe",dV="C:\\Windows\\System32\\msiexec.exe",Gg="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",t0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],uV=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],pV=`anyray-connect endpoint install
|
|
370
|
+
`),1}};var bK=new RegExp(`/releases/tag/${Ko}([0-9][0-9A-Za-z.-]*)$`),kK=300*1024*1024,Fc=1e4,CK=5*6e4,AK=360*6e4,vK=30*6e4,ko=(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 SK=e=>{if(e)return bK.exec(e.trim())?.[1]},Lg=(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()}},$g=e=>e.mode==="off"?{allow:!1,outcome:"fleet-off"}:e.mode==="directed"&&e.initiator==="tick"?{allow:!1,outcome:"fleet-directed"}:{allow:!0},IK=e=>e==="auto",Xx=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&&ko(e.current,e.minVersion)<0&&ko(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},EK=e=>ko(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}:{...Xx(e),downgradeBlocked:!1},xK=(e=process.execPath)=>{let t=Hf(e);return t?nn(t):nn(nn(e))},RK=async(e=vt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=hr(xK(e.execPath)).launcher;try{if(await fp(t)!==await fp(e.execPath))return}catch{return}return t},OK=["connect-tray","connect-tray.exe"],_K=async e=>{let t=nn(e);for(let n of OK)try{let r=await Ng(ba(t,n)),o=process.platform==="win32"||(r.mode&73)!==0;if(r.isFile()&&o)return!0}catch{}return!1},Uc=async(e=vt(),t=ee())=>{let n=await RK(e);if(n)return{kind:"managed",root:nn(nn(n)),link:n,entryPath:jr(e)};let r=jr(e);return Kf(r,t)?{kind:"durable",root:t,entryPath:r}:Uf(r)?{kind:"npm",root:t,entryPath:r}:await _K(r)?{kind:"sidecar",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},hp=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)}},Mg=async(e=Fc)=>{let t=await hp(`${to}/latest`,e,{redirect:"manual"});return SK(t.headers.get("location"))},TK=async e=>{try{let t=await hp(`${e}/connect-update.json`,Fc);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}},ka=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},Wc=async(e,t,n)=>{let r=await hp(e,CK);if(!r.ok||!r.body)throw new ka(r.status);let o=yK("sha256"),a=0;if(await wK(gK.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>kK)throw new Error("asset exceeds size cap");o.update(c),yield c}},fK(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},PK=e=>up(e)===no()?up(nn(e)):up(e),DK=async e=>{let t=await mp(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Bt(ba(e,n),{force:!0}).catch(()=>{})},zx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Bt(r,{force:!0}).catch(()=>{});let o=!1;try{await dp(e,r),o=!0}catch{}try{await Tg(t,e),await hK(wi(e),PK(t))}catch(a){throw o&&await dp(r,e).catch(()=>{}),a}await Bt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Bt(n,{force:!0}),await mK(t,n),await dp(n,e)},Bg=(e,t)=>e===t||up(e)===Sm?448:493,Bc=async(e,t)=>{let n=(await Ng(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await Jx(e,n&4095|t).catch(()=>{})},pp=async(e,t)=>{await Dg(e,{recursive:!0,mode:t}),await Bc(e,t)},NK=async(e,t,n)=>{let r=Bg(e,ee());if(r!==448){let o=hr(e),a=o.versionsDir;await Bc(e,r),await Bc(nn(o.launcher),r),await Bc(a,r);for(let s of await mp(a).catch(()=>[]))await Bc(ba(a,s),r)}await(n.refreshDesktopHelpers??lp)(t)},LK=async(e,t={})=>{let n=hr(e.root),r=nn(n.launcher),{versionsDir:o,launcher:a}=n,s=Bg(e.root,(t.privateRoot??ee)());await pp(r,s),await pp(o,s);let i=ba(o,e.version),l=(await Pg(i).catch(()=>{}))?.isFile()?i:ba(i,no());if(!(await Pg(l).catch(()=>{}))?.isFile()){let u=await(t.fetchResponse??hp)(`${e.tagUrl}/SHA256SUMS`,Fc),p=u.ok?Lg(await u.text(),e.asset):void 0;if(!p)throw new Error("no published checksum");await pp(nn(l),s),await DK(nn(l));let m=`${l}.part-${process.pid}`;try{await(t.download??Wc)(`${e.tagUrl}/${e.asset}`,m,p),await Jx(m,493),await dp(m,l)}catch(f){throw await Bt(m,{force:!0}).catch(()=>{}),f}}return await(t.activate??zx)(a,l),{link:a,target:l,versionsDir:o}},$K=async e=>{Zx(e.target,[Vo,e.link],{stdio:"ignore",timeout:Fc})},MK=async e=>{if(process.platform==="darwin"){let t=Zx("/usr/bin/codesign",["--verify","--strict",e],{stdio:"ignore",timeout:Fc});return!t.error&&t.status===0}return!0},BK=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??wa)(n);if(r.length>0){let o=await(t.resolveTarget??Je)(async()=>e);if(!o||!(await(t.repair??tn)(r,o.target)).every(ga))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&ot(e)&&!(await(t.installScheduler??eo)()).ok)},FK=async e=>{let t=await e.install();if(!await(e.smoke??MK)(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},UK=async(e,t)=>{let n=await mp(e).catch(()=>[]);for(let r of n)t.includes(r)||await Bt(ba(e,r),{force:!0,recursive:!0}).catch(()=>{})},WK=async e=>{let t=await mp(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Bt(ba(e,n),{force:!0}).catch(()=>{})},HK=async(e,t)=>{let n=async()=>{await Bt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Dg(e,{recursive:!1}),n}catch{}let r=await Ng(e).catch(()=>{});if(!(!r||t-r.mtimeMs<vK)){await n();try{return await Dg(e,{recursive:!1}),n}catch{return}}},_g=e=>hr(e).state,GK=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}},Ps=async(e={})=>{let t=e.now??Date.now,n=Le;if(pr(Nn(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??vt(),o=e.root??ee(),a;try{let s=await Uc(r,o);if(o=s.root,s.kind==="sidecar")return{outcome:"sidecar",current:n};if(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??L)().catch(()=>({})),d=l.autoUpdate!==!1,u=l.fleetUpdatePolicy?.mode??"auto",p=$g({mode:u,initiator:e.initiator??"tick"});if(!p.allow)return{outcome:p.outcome,current:n};!i&&s.link&&!e.checkOnly&&(d||c)&&await NK(o,s.link,e).catch(()=>{});let m=Oi(e.platform??process.platform,e.arch??process.arch);if(!m)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Mg)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let f=a;if(!i&&f===n)return{outcome:"current",current:n,latest:f};if(i&&ko(f,n)<0)return{outcome:"migration-deferred",current:n,latest:f};let h=await GK(_g(o));if((e.respectFailureBackoff===!0||!c)&&h.failedVersion===f&&h.failedAt!==void 0&&t()-h.failedAt<AK)return{outcome:"failed",current:n,latest:f};let g=`${to}/download/${Ko}${f}`,y=d||c||!IK(u)?void 0:await(e.minimumVersion??TK)(g),w={current:n,latest:f,autoUpdate:d,forced:c,minVersion:y},b=i?EK(w):{...Xx(w),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===ee()?await Xe():await pp(o,Bg(o,ee()));let A=hr(o),C=await HK(A.lock,t());if(!C)return{outcome:i?"migration-available":"available",current:n,latest:f};let x,O;try{await WK(nn(A.launcher));let S=await fp(A.versionsDir).catch(()=>{}),E=await fp(A.launcher).catch(()=>{}),T=E&&Ll(E,S)?E:void 0,I=A.launcher;i&&process.platform==="win32"&&(await Pg(I).catch(()=>{}))?.isFile()&&(O=`${I}.rollback-${process.pid}`,await Tg(I,O));let K=()=>(e.installBinary??LK)({root:o,version:f,asset:m,tagUrl:g});i?x=await FK({install:K,smoke:e.smoke,rollback:async({link:G,target:X})=>{O?(await Tg(O,G),await Bt(wi(G),{force:!0}).catch(()=>{})):T&&T!==X?await zx(G,T):(await Bt(G,{force:!0}),await Bt(wi(G),{force:!0}).catch(()=>{}))},repoint:async G=>e.repoint?e.repoint(l,G):BK(l),prune:async()=>{await(e.pruneDurable??(G=>Ml(G)))(r)}}):x=await K(),await UK(x.versionsDir,[f,n]),await(e.refreshHelpersFromInstalled??$K)(x).catch(()=>{}),await Bt(_g(o),{force:!0}).catch(()=>{})}finally{O&&await Bt(O,{force:!0}).catch(()=>{}),await C()}return{outcome:i?"migrated":"updated",current:n,latest:f,managedPath:x.link,mandatory:b.mandatory}}catch{return a&&await q(_g(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},qx=async(e={})=>{let t=e.context??vt(),n=await Uc(t,e.root??ee()),r=Fa(e.root??ee());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Le,managedPath:n.link??r}:Ps({initiator:"human",...e,context:t,allowNpmMigration:!0})},Ca=async(e={})=>{let t=e.context??vt(),n=e.root??ee(),r=await Uc(t,n),o=r.kind==="npm"||r.kind==="durable"?Fa(n):void 0,a=await(e.load??L)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!Oi(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=pr(Nn(e.env??process.env))?"container":r.kind==="sidecar"?"sidecar":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:Le,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l,fleetMode:a.fleetUpdatePolicy?.mode??"auto"}};var t2="fleetd-installer-v4.89.2",Qx=`https://github.com/anyrayHQ/install/releases/download/${t2}`,n2=1e4,r2=1e4,e0=31,o2=1500,m0=20*1024,Fg=20,a2="0.25",s2="/var/tmp",Ns="/Library/LaunchDaemons/com.fleetdm.orbit.plist",wp="/etc/default/orbit",Gc="/opt/orbit/anyray-enroll-secret.txt",h0="/opt/orbit/secret-orbit-node-key.txt",i2="/opt/orbit/bin/orbit/orbit",Kc="C:\\Program Files\\Orbit",c2=`${Kc}\\bin\\orbit`,y0=`${Kc}\\secret-orbit-node-key.txt`,Hc=`${Kc}\\secret.txt`,l2=`${Kc}\\fleet_url.txt`,g0=`${Kc}\\anyray-managed.txt`,bp="Fleet osquery",Hg="C:\\Windows\\System32\\sc.exe",jg="C:\\Windows\\System32\\whoami.exe",yp="C:\\Windows\\System32\\icacls.exe",d2="C:\\Windows\\System32\\msiexec.exe",Gg="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",t0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],u2=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],p2=`anyray-connect endpoint install
|
|
372
372
|
|
|
373
373
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
374
374
|
|
|
@@ -376,11 +376,11 @@ 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.`,Yg=e=>!!(e.endpoint&&!e.noEndpoint&&(e.signIn||e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),w0=(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",Gc)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Kg=(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()},k0=e=>{let t=e(Hg,["qc",bp,"8192"]);return t.status===0?t.stdout:""},Vg=e=>{let t=e(Gg,
|
|
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},
|
|
379
|
+
available; on Windows, run it from a shell started as Administrator.`,Yg=e=>!!(e.endpoint&&!e.noEndpoint&&(e.signIn||e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),w0=(e,t=Ls())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),b0=(e,t=Ls(),n=!1)=>(Yg(e)||n)&&t!=="win32",he=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},f2=Ke.object({kind:Ke.enum(["pkg","deb","rpm","msi"]),path:Ke.string().min(1).refine(e2),sha256:Ke.string().regex(/^[0-9a-f]{64}$/)}).strict(),m2=Ke.object({action:Ke.literal("restart"),os:Ke.enum(["darwin","linux","win32"])}).strict(),h2=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:f2.optional()}).strict(),y2=Ke.discriminatedUnion("action",[m2,h2]),Vc=(e,t)=>{let n=d0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},Zg=async e=>{try{return await u0(e,f0.F_OK),!0}catch{return!1}},g2=async e=>{try{let t=await XK(e);return t.isFile()&&t.size>0}catch{return!1}},Jg=(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}},Ug=(e,t)=>Jg(e,t)!==null,n0=e=>e==="win32"?Hc:Gc,w2=e=>e==="win32"?y0:h0,b2=e=>Ug(e,"ORBIT_FLEET_URL")&&Ug(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Gc}</string>`)&&!Ug(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),k2=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",Gc)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Kg=(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()},k0=e=>{let t=e(Hg,["qc",bp,"8192"]);return t.status===0?t.stdout:""},Vg=e=>{let t=e(Gg,u2(bp)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},C2=async e=>{try{return e==="win32"?Kg(e,k0(Vc)):Kg(e,await kp(e==="darwin"?Ns:wp,"utf8"))}catch{return}},A2=async e=>{try{if(e==="win32")return await Zg(g0)&&Kg(e,k0(Vc))!==void 0;let n=await kp(e==="darwin"?Ns:wp,"utf8");return e==="darwin"?b2(n):k2(n)}catch{return!1}},C0=async(e,t={})=>{let n=t.exists??Zg,r=t.command??Vc,o,a="absent";if(e==="win32")a=Vg(r),o=await n(c2)&&a!=="absent";else{let l=e==="darwin"?await n(Ns):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(i2)&&l}let s=await(t.configured??A2)(e),i=await(t.hasNodeKey??(()=>g2(w2(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}},v2=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),A0=(e,t)=>{let n=Jg(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
|
+
`&&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},S2=(e,t)=>{let n=A0(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},r0=(e,t,n)=>{let r=`
|
|
382
382
|
<key>${t}</key>
|
|
383
|
-
<string>${
|
|
383
|
+
<string>${v2(n)}</string>`,o=A0(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Jg(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new he("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)},I2=(e,t,n=Gc)=>{let r=S2(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=r0(r,"ORBIT_FLEET_URL",t),r0(r,"ORBIT_ENROLL_SECRET_PATH",n)},E2=(e,t,n=Gc)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
|
|
384
384
|
`).filter(a=>{let s=a.indexOf("=");return s<0?!0:!r.has(a.slice(0,s).trim())}).filter((a,s,i)=>a.trim()!==""||i[s-1]?.trim()!=="").join(`
|
|
385
385
|
`).trimEnd()}
|
|
386
386
|
|
|
@@ -390,33 +390,33 @@ available; on Windows, run it from a shell started as Administrator.`,Yg=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
|
-
`},v0=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}},
|
|
393
|
+
`},v0=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}},x2=Ke.object({code:Ke.string().min(1).optional(),message:Ke.string().min(1).optional()}).passthrough(),o0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},R2=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=x2.safeParse(t);if(!r.success)return n;let o=o0(r.data.message??""),a=o0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},a0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??r2),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":Le},body:"{}",signal:r.signal})}catch{throw new he("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new he("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new he(R2(a.status,c))}let s;try{s=await a.json()}catch{throw new he("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||!v0(i.data.fleetUrl))throw new he("The gateway returned invalid endpoint enrollment data.");return i.data},O2=async(e={})=>{let t=e.exists??Zg;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 he("Linux endpoint installation requires either dpkg or rpm.")},_2=async e=>e==="darwin"?"pkg":e==="win32"?"msi":O2(),Xg=e=>`fleetd.${e}`,T2=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",P2=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),n2);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},D2=async(e,t={})=>{let n=Xg(e),r=t.fetchResponse??fetch,o;try{o=await P2(`${Qx}/SHA256SUMS`,r)}catch{throw new he("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new he(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=Lg(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await p0(gp(qK(),"anyray-endpoint-")),i=gp(s,n);try{await Wg(s,448),await(t.download??Wc)(`${Qx}/${n}`,i,a)}catch(c){if(await Co(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof ka&&c.status===404)return;throw new he("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Co(s,{recursive:!0,force:!0})}},N2=async(e,t,n)=>{await ZK(QK(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Co(r,{force:!0});try{await zK(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await JK(r,e)}catch(o){throw await Co(r,{force:!0}).catch(()=>{}),o}},s0=async e=>{let t=VK("sha256");for await(let n of KK(e))t.update(n);return t.digest("hex")},L2=async(e,t={})=>{let n=await YK(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new he("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await s0(e.path)!==e.sha256)throw new he("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await p0(gp(s2,"anyray-endpoint-root-")),o=gp(r,Xg(e.kind));try{if(await Wg(r,448),await jK(e.path,o),await Wg(o,384),await s0(o)!==e.sha256)throw new he("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Co(r,{recursive:!0,force:!0})}}catch(a){throw await Co(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ds=(e,t)=>{if(e.status!==0)throw new he(t)},i0="com.fleetdm.fleetd.config",$2="com.fleetdm.fleetd.enroll.secret",M2=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",h0],B2=[l2,y0],F2=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(i0))throw new he(`This machine already receives its endpoint configuration from an MDM profile (${i0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},c0=async(e,t,n)=>{let r=n.removeFile??(o=>Co(o,{force:!0}));for(let o of e==="win32"?B2:M2)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",$2,"/Library/Keychains/System.keychain"])},U2=e=>{e(yp,[Hc,"/inheritance:r"]),e(yp,[Hc,"/grant:r","*S-1-5-18:(F)"]),e(yp,[Hc,"/grant:r","*S-1-5-32-544:(F)"]),e(yp,[Hc,"/remove:g","*S-1-5-32-545"])},W2=(e,t,n)=>{if(e.kind==="pkg"){Ds(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ds(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ds(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ds(t(d2,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},H2=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<Fg;r++){if(n=t("/bin/launchctl",["bootstrap","system",Ns]),n.status===0)return;t("/bin/sleep",[a2])}throw new he(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(Hg,["stop",bp]);for(let n=0;n<Fg;n++){let r=Vg(t);if(r==="Stopped"||r==="absent")break;t(Gg,t0)}for(let n=0;n<Fg;n++){if(t(Hg,["start",bp]).status===0||Vg(t)==="Running")return;t(Gg,t0)}throw new he("Orbit was configured, but the Windows service could not be started.")}Ds(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ds(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},G2=e=>new Promise(t=>setTimeout(t,e)),S0=async(e,t={})=>{let n=t.command??Vc,r=t.readText??(c=>kp(c,"utf8")),o=t.writeText??N2,a=t.removeSecret??(()=>Co(n0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&F2(n),e.package&&!T2(e.os,e.package.kind))throw new he("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new he("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await c0(e.os,n,t),e.package){let d=await(t.preparePackage??L2)(e.package);i=d.cleanup,W2(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Ns);await o(Ns,I2(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(wp);await o(wp,E2(d,e.fleetUrl),420)}else await o(g0,`anyray
|
|
394
394
|
`,384);e.os!=="win32"&&await c0(e.os,n,t),await o(n0(e.os),`${e.enrollSecret}
|
|
395
|
-
`,384),e.os==="win32"&&
|
|
396
|
-
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??
|
|
397
|
-
sudo anyray-connect endpoint install`),"deferred"},
|
|
398
|
-
`;if(Buffer.byteLength(t)>m0)throw new he("The privileged endpoint plan is unexpectedly large.");let n=Rn(["__anyray-endpoint-install"]);return d0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},
|
|
399
|
-
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=
|
|
395
|
+
`,384),e.os==="win32"&&U2(n),s=e.os!=="win32"}H2(e.os,n);let c=t.checkIn??(async d=>{let u=await C0(d);return u.running&&u.checkedIn}),l=t.wait??G2;for(let d=0;d<(t.attempts??e0);d++){if(await c(e.os))return;d+1<(t.attempts??e0)&&await l(o2)}throw new he("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(()=>{})}},K2=async()=>{try{return await u0("/dev/tty",f0.R_OK),!0}catch{return!1}},V2=12288,j2=e=>{let t=e(jg,["/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>=V2},Y2=async(e,t={})=>{if((t.os??Ls())==="win32")return(t.elevated??(()=>j2(t.command??Vc)))()?(await e(),"direct"):((t.print??k)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
396
|
+
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??K2)()){if(await(t.reexec??(async()=>1))()!==0)throw new he("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??k)(`Administrator access is required. Run:
|
|
397
|
+
sudo anyray-connect endpoint install`),"deferred"},Z2=async e=>{let t=`${JSON.stringify(e)}
|
|
398
|
+
`;if(Buffer.byteLength(t)>m0)throw new he("The privileged endpoint plan is unexpectedly large.");let n=Rn(["__anyray-endpoint-install"]);return d0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},J2=async(e,t={})=>(t.withRoot??Y2)(()=>(t.apply??S0)(e),{...t.root,reexec:()=>(t.sudo??Z2)(e)}),l0=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return L();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return L();let t;try{let s=(await kp("/etc/passwd","utf8")).split(`
|
|
399
|
+
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Ls()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await L()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},I0=async(e={},t={})=>{let n=t.os??Ls();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new he("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??C0)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??l0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??C2)(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??a0)(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 he("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??l0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new he("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??a0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let p=await(t.packageKind??(()=>_2(r)))();if(i=await(t.stagePackage??D2)(p),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${Xg(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??J2)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},zg=e=>e instanceof he?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",E0=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return k(p2),0;if(e.length!==1||e[0]!=="install")return D("Usage: anyray-connect endpoint install"),1;try{let t=await I0();return t.message&&(t.outcome==="installed"?B(t.message):M(t.message)),0}catch(t){return D(zg(t)),1}},X2=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>m0)throw new he("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new he("The privileged endpoint plan is malformed.")}let r=y2.safeParse(n);if(!r.success||r.data.os!==Ls()||r.data.action==="configure"&&!v0(r.data.fleetUrl))throw new he("The privileged endpoint plan is invalid.");return r.data},x0=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 S0(await X2()),0}catch(t){return D(zg(t)),1}},R0=async(e,t=I0)=>{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: ${zg(n)} Tool routing remains configured.`);return}};import{promises as AV}from"node:fs";var nr=e=>typeof e=="string"?e:"",z2=e=>{let t=nr(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=nr(o.text).trim();a&&r.push(a)}return r.join(`
|
|
400
400
|
|
|
401
|
-
`).trim()},
|
|
401
|
+
`).trim()},q2=e=>{let t=nr(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},Q2=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=z2(r);if(!o)continue;let a=nr(r.created_at).trim();t.push({role:q2(r),text:o,...a?{createdAt:a}:{}})}return t},Cp=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=Q2(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(nr(s.uuid)||nr(s.id)).trim(),l=(nr(s.name)||nr(s.title)).trim()||"Untitled conversation",d=nr(s.created_at).trim(),u=nr(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 yV}from"node:crypto";import{promises as Zc}from"node:fs";import{homedir as L0}from"node:os";import{join as vp}from"node:path";import{promises as O0}from"node:fs";import qg from"node:path";var eV=4e4,tV=16*1024*1024,jc=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Yc=async(e,t={})=>{let n=(e??"").trim();if(!n)return jc("","path is required");let r=t.cwd??process.cwd(),o=qg.resolve(r,n),a=qg.relative(r,o);if(a.startsWith("..")||qg.isAbsolute(a))return jc(n,"path is outside the workspace");let s=t.maxBytes??eV,i;try{let g=await O0.stat(o);if(!g.isFile())return jc(n,"not a regular file");let y=t.maxFileBytes??tV;if(g.size>y)return jc(n,`file too large to read (${g.size} bytes; limit ${y})`);i=await O0.readFile(o,"utf8")}catch(g){return jc(n,g instanceof Error?g.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(`
|
|
403
403
|
`),m=l<=d?d:l,f=!1,h=!1;if(Buffer.byteLength(p,"utf8")>s){let g=0,y=0;for(let w of u){let b=Buffer.byteLength(w,"utf8")+(y===0?0:1);if(g+b>s)break;g+=b,y+=1}y===0?(p=Buffer.from(u[0]??"","utf8").subarray(0,s).toString("utf8").replace(/\uFFFD$/,""),m=l,f=!0):(p=u.slice(0,y).join(`
|
|
404
404
|
`),m=l+y-1),h=!0}return{ok:!0,content:p,path:n,lines:c.length,truncated:h,span:{startLine:l,endLine:m,...f?{partialLine:!0}:{}}}},Qg=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
|
|
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
|
-
${e.content}`};import{spawn as
|
|
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:T0(l,t)})}return r},
|
|
408
|
-
`);for(let C=0;C<A.length;C+=1){let x=c(A[C]);if(l.some(O=>x.includes(O))&&(u.push({file:tw.relative(t,w),line:C+1,text:T0(A[C],o)}),u.length>=r)){m=!0;return}}}}};return await f(t),{ok:!0,matches:u,truncated:m,engine:"walk"}},Ap=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??nw,s=t.maxColumns??
|
|
406
|
+
${e.content}`};import{spawn as nV}from"node:child_process";import{promises as ew}from"node:fs";import tw from"node:path";var nw=400,rV=240,oV=4e3,aV=4e3,sV=512*1024,iV=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),T0=(e,t)=>e.length>t?e.slice(0,t):e,cV=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"]),lV=8,dV=2e3,uV=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],pV=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")},P0=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!cV.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=lV))break}return n},D0=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},fV=(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)},_0=(e,t,n)=>{let r=[];for(let o of e.split(`
|
|
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:T0(l,t)})}return r},mV=(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 uV)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=nV("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=_0(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=_0(d,o,r+1),g=h.length>r;p({ok:!0,matches:g?h.slice(0,r):h,truncated:g,engine:"ripgrep"})})}),hV=async(e,t,n,r,o,a,s)=>{let i=D0(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 g;try{g=await ew.readdir(h,{withFileTypes:!0})}catch{return}for(let y of g){if(u.length>=r||Date.now()>a){m=!0;return}let w=tw.join(h,y.name);if(y.isDirectory()){if(iV.has(y.name))continue;await f(w)}else if(y.isFile()){if(p>=aV){m=!0;return}if(d.length&&!d.some(C=>y.name.endsWith(C))||pV(tw.relative(t,w)))continue;p+=1;let b;try{if((await ew.stat(w)).size>sV)continue;b=await ew.readFile(w,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let A=b.split(`
|
|
408
|
+
`);for(let C=0;C<A.length;C+=1){let x=c(A[C]);if(l.some(O=>x.includes(O))&&(u.push({file:tw.relative(t,w),line:C+1,text:T0(A[C],o)}),u.length>=r)){m=!0;return}}}}};return await f(t),{ok:!0,matches:u,truncated:m,engine:"walk"}},Ap=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??nw,s=t.maxColumns??rV,i=t.timeoutMs??oV,c=Date.now()+i,l=P0(n),d=l.length>1,u=Math.min(a*4,dV),p=(y,w)=>hV(n,r,o,y,s,c,w),m=async y=>{let w=await y(u,l);if(!w.ok)return w;let b=fV(w.matches,l,D0(l)),A=b.length>a;return{...w,matches:A?b.slice(0,a):b,truncated:w.truncated||A,matched:"tokens",tokens:l}};if(t.engine==="walk"){let y=await p(a);return y.matches.length>0||!d?y:m((w,b)=>p(w,b))}let f=(y,w)=>mV(n,r,o,y,s,Math.max(0,c-Date.now()),w),h=await f(a);if(h.ok){if(h.matches.length>0||!d)return h;let y=await m((w,b)=>f(w,b));return y.ok?y:m((w,b)=>p(w,b))}let g=await p(a);return g.matches.length>0||!d?g:m((y,w)=>p(y,w))},N0=(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=P0(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(`
|
|
412
|
-
`)};var $0=448,
|
|
412
|
+
`)};var $0=448,gV=384,wV=4e4,vo=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=vp(L0(),".anyray");try{if((await Zc.stat(t)).isDirectory())return vp(t,"history")}catch{}return vp(L0(),".anyray-history")},bV=e=>{let t=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),n=(e.createdAt??"").slice(0,10),r=(e.uuid||"").replace(/[^a-zA-Z0-9-]/g,"").slice(0,65),o=r.length>0&&r.length<=64?r:kV(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},kV=e=>{let t=yV("sha256");t.update(e.title),t.update("\0"),t.update(e.createdAt??""),t.update("\0");for(let n of e.messages)t.update(n.role),t.update("\0"),t.update(n.text),t.update("\0");return t.digest("hex").slice(0,16)},CV=e=>{let t=[`# ${e.title}`,"",e.createdAt?`- Created: ${e.createdAt}`:"",e.updatedAt?`- Updated: ${e.updatedAt}`:"",e.uuid?`- Claude conversation id: ${e.uuid}`:"",""].filter((r,o,a)=>!(r===""&&a[o-1]==="")),n=e.messages.map(r=>{let o=r.role==="user"?"User":"Claude",a=r.createdAt?` (${r.createdAt})`:"";return`## ${o}${a}
|
|
413
413
|
|
|
414
414
|
${r.text}
|
|
415
415
|
`});return[...t,...n].join(`
|
|
416
416
|
`).replace(/\n{3,}/g,`
|
|
417
417
|
|
|
418
418
|
`)+`
|
|
419
|
-
`},Sp=async e=>{let t=await vo();await Zc.mkdir(t,{recursive:!0,mode:$0});try{await Zc.chmod(t,$0)}catch{}let n=0,r=0;for(let o of e)try{await Zc.writeFile(vp(t,
|
|
419
|
+
`},Sp=async e=>{let t=await vo();await Zc.mkdir(t,{recursive:!0,mode:$0});try{await Zc.chmod(t,$0)}catch{}let n=0,r=0;for(let o of e)try{await Zc.writeFile(vp(t,bV(o)),CV(o),{mode:gV}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},$s=async()=>{try{let e=await vo();return(await Zc.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},M0=async e=>{let t=await vo();return Ap(e,{cwd:t,globs:["*.md"]})},B0=async e=>{let t=await vo();return Yc(e,{cwd:t,maxBytes:wV})};var F0=`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
|
-
`,
|
|
440
|
+
`,vV=async e=>{try{return{raw:await AV.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"})`}}},SV=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return D("Usage: anyray-connect history import <conversations.json>"),k(v("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await vV(t);if("error"in n)return D(n.error),1;let r=Cp(n.raw);if(!r.ok)return D(`Could not read that export: ${r.message??"unrecognized format"}`),k(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 Sp(r.conversations)}catch(a){let s=a?.code;return D(`Could not create the history archive (${s??"write failed"}).`),k(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&&k(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.`),k(""),k(Z("Your history is now searchable from any Anyray-connected client.")),k(v(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),k(v(" and the assistant can search this archive and pull it up.")),k(v(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),k(v(" for them, they do not reappear as a clickable list in the app.")),0},IV=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return D("Usage: anyray-connect history restore <export.zip>"),k(v("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await Eu(t);return n.ok?(B(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&k(v(` ${n.skipped} already present, left untouched.`)),n.failed>0&&P(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),k(""),k(Z("Open Claude Desktop \u2014 they are in the sidebar again.")),k(v(" Anyray stays configured; this changed nothing about your routing.")),k(v(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),k(v(" undocumented. A future Desktop release could stop reading it \u2014 your export")),k(v(" file still works, and `history import` remains a second copy.")),0):(D(`Could not restore into Claude Desktop: ${n.reason}`),k(v(` ${n.remedy}`)),1)},EV=async()=>{let e=await vo(),t=await $s();return t===0?(k(`No conversations imported yet. Archive would live at ${e}`),k(v(" Import one with: anyray-connect history import <conversations.json>")),0):(B(`${t} conversation${t===1?"":"s"} in ${e}`),0)},U0=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(F0),0):t==="import"?SV(e.slice(1)):t==="restore"?IV(e.slice(1)):t==="status"?EV():(D(`Unknown history command: ${t}`),console.log(F0),1)};var xV=1e4,rw=/^[\w.:-]{1,64}$/,rn=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},ow=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,W0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),xV);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 rn("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},RV=e=>{let t=ow(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}},OV=e=>{let t=ow(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&rw.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&rw.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},_V=e=>{let t=ow(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Pe(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!rw.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}}},TV=e=>new Promise(t=>setTimeout(t,e)),PV=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new rn("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}k("Available teams:"),e.forEach((i,c)=>k(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Os("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 rn("invalid-team","Choose one of the teams shown above.");return s},DV=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??TV,a=t.loadProfile??L,s=t.saveProfile??pe,i=t.clearDevKey??hi,c=t.chooseTeam??PV,l=t.apply??(async y=>{await Dn.apply(y,{dryRun:!1})}),d=t.log??M,u=await a(),p=tr(e.gateway,u),m=await W0(`${p}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),f=RV(m.body);if(m.status!==200||!f)throw new rn("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??Nr)(f.browser_url);let h=r()+f.expires_in*1e3,g=e.team?.trim()||void 0;for(;r()<h;){let y=await W0(`${p}/sso/cli/poll/${encodeURIComponent(f.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":f.poll_secret,...g?{"x-anyray-team":g}:{}}},n);if(y.status===202){await o(f.interval*1e3);continue}if(y.status===401)throw new rn("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new rn("expired","SSO login expired before it completed. Run anyray-connect login again.");let w=OV(y.body);if(y.status===200&&w){if(g&&!w.teams.includes(g))throw new rn("invalid-team",`Team ${g} is not available for this account.`);g=await c(w.teams,w.default_team,e.interactive??xt());continue}let b=_V(y.body);if(y.status!==200||!b)throw new rn("login-failed","SSO login could not be completed.");let A={...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(A),await l(Re({origin:p,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new rn("expired","SSO login expired before it completed. Run anyray-connect login again.")},NV=`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.`,H0=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return k(Lj),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 Dj({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 Et)throw o;return D(o instanceof rn?o.message:"SSO login failed."),1}};import{writeFileSync as k2}from"node:fs";import{chmod as yw,stat as C2}from"node:fs/promises";import{platform as kR}from"node:os";import{dirname as CR,isAbsolute as A2}from"node:path";var Nj="https://app.anyray.ai",$j=new Set(["localhost","::1","[::1]"]),Mj=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Bj=e=>$j.has(e)||Mj.test(e),aw=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&Bj(t.hostname)},Fj=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},vn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!aw(e)?Nj:Fj(e)};import{createHash as qj,generateKeyPairSync as Qj,randomBytes as cw}from"node:crypto";import{createPrivateKey as Uj,sign as Wj}from"node:crypto";var rr=async(e,t)=>{let n=Uj(t);return Wj(null,new TextEncoder().encode(e),n).toString("base64url")};var Hj=["HTTPS_PROXY","https_proxy"],G0=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"]),K0=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),V0=new Set(["ENOTFOUND","EAI_AGAIN"]),j0=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Y0=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),Gj=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 Kj(e)},Kj=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...G0,...K0,...V0,...j0,...Y0])if(t.includes(n))return n}},Vj=e=>e?.name==="AbortError"||e?.name==="TimeoutError",jj=e=>Hj.filter(t=>(e[t]??"").trim()!==""),Yj=(e,t=process.env)=>{let n=Gj(e),r=jj(t);return{kind:n&&G0.has(n)?"tls-unknown-issuer":n&&K0.has(n)?"tls-invalid-cert":n&&V0.has(n)?"dns":Vj(e)||n&&Y0.has(n)?"timeout":n&&j0.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},Zj=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}},Rt=(e,t=process.env)=>Zj(Yj(e,t));var Jj="enl_",Z0="enp_",J0=e=>e.startsWith(Jj)||e.startsWith(Z0),sw=e=>e.startsWith(Z0),Xj=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],iw=e=>Xj.find(t=>e.startsWith(t.prefix)),X0=/^\/enroll\/([^/]+)\/?$/,z0=/^\/i\/([^/]+)\/?$/,q0=e=>{let t=e.match(X0);if(t)return iw(t[1])?void 0:t[1];let n=e.match(z0);return n&&J0(n[1])?n[1]:void 0},zj=1e4,Ip=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=q0(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!iw(t))return{cpOrigin:vn(),token:t}},Q0=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(X0)??o.pathname.match(z0);if(!a)return;n=a[1]}catch{}let r=iw(n);return r?{flag:r.flag,what:r.what}:void 0},Xc=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:q0(n.pathname)!==void 0}catch{return J0(t)}},Ms=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},Jc=e=>typeof e=="string"&&e.trim()?e.trim():void 0,eR=async(e,t={})=>{let n=t.timeoutMs??zj,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.`:Rt(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 Ms(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"&&Jc(u.url)!==void 0),d=Jc(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:Jc(l?.deploymentId),org:Jc(i.org),email:Jc(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 lw=1e4,Aa=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Aa).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Aa(e[n])}`).join(",")}}`,tR="stable-key-heartbeat-v1",nR="key-heartbeat",e2=["reapply_config","remint","revert"],dw=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var rR=e=>qj("sha256").update(e).digest("hex"),et=e=>typeof e=="string"&&e.trim()?e.trim():void 0,t2=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],oR={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"},n2=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${oR[e]}. Ask your IT admin.`,r2=e=>typeof e=="string"&&e in oR,uw=async e=>{try{let t=await e.json(),n=et(t?.message),r=et(t?.error),o=r2(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:n2(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},o2=async e=>(await uw(e)).message,ct=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}},zc=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="GatewayUnreachableError"}},qc=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="ControlPlaneUnreachableError"}},pw=e=>e instanceof Ms||e instanceof ct&&e.policyCode==="sso_required",Bs=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}},fw=async(e,t,n,r)=>{try{return await r(Aa(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Fs=()=>{let{publicKey:e,privateKey:t}=Qj("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},Sn=async(e,t,n,r={})=>{let o=r.timeoutMs??lw,a=`${e}/connect/verify`,s=et(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:cw(16).toString("hex"),...dw(t,r.machineUuid)},c=await fw(i,n,"verification",r.signer??rr),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(w){let b=w instanceof Error&&w.name==="AbortError"?` no response within ${o}ms.`:Rt(w);throw new zc(`could not reach the gateway at ${a}.${b}`,w)}finally{clearTimeout(d)}if(!u.ok)throw new ct(u.status,await uw(u));let p;try{p=await u.text()}catch{p=""}let m;try{m=JSON.parse(p)}catch{let w=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(w)||/^\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=et(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=et(m.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let g=a2(m.directive),y=t2(m.capabilities);return{key:f,user:h,team:et(m.team),expiresAt:et(m.expiresAt),...y.length>0?{capabilities:y}:{},...g?{directive:g}:{}}},aR=async(e,t,n,r,o={})=>{let a=o.timeoutMs??lw,s=`${e}/connect/key/heartbeat`,i=et(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:cw(16).toString("hex"),purpose:nR,...dw(n,o.machineUuid)},l=await fw(c,r,"heartbeat",o.signer??rr),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 g=h instanceof Error&&h.name==="AbortError"?` no response within ${a}ms.`:Rt(h);throw new Error(`could not reach the gateway at ${s}.${g}`,{cause:h})}finally{clearTimeout(u)}if(!p.ok)throw new Bs(p.status,await uw(p));let m;try{m=await p.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let f=et(m.expiresAt);if(!f||!Number.isFinite(Date.parse(f))||m.credentialMode!==tR||m.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:f,credentialMode:tR}},sR=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??lw,i=`${e.replace(/\/$/,"")}/connect/machine`,c=et(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:cw(16).toString("hex"),purpose:nR,...dw(n,o)},d=await fw(l,r,"heartbeat",a.signer??rr),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)}},a2=e=>{if(e===null||typeof e!="object")return null;let t=e,n=et(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!e2.includes(r)?null:{id:n,kind:r}},s2=1e4,i2=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!et(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!et(r.deploymentId)&&!!et(r.user)&&!!et(r.devPublicKey)&&!!et(r.issuedAt)&&!!et(r.expiresAt)},c2=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??s2,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.`:Rt(u);throw new qc(`could not reach the control plane at ${s}.${p}`,u)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await o2(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new Ms(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(!i2(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},iR=(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())},cR=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=Fs();return{cert:await c2(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await Sn(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};var mw=1e4,l2=900*1e3,dR="tnt_",d2=/^\/sso\/([^/]+)\/?$/,u2=/^\/i\/([^/]+)\/?$/,p2=e=>{let t=e.match(d2);if(t)return t[1];let n=e.match(u2);return n?.[1].startsWith(dR)?n[1]:void 0},Ft=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=p2(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(dR))return{cpOrigin:vn(),tenantId:t}},bt=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Ot=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},f2=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),uR=async e=>{try{let t=await e.json();return f2(t)?t:{}}catch{return{}}},Qc=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 uR(s)}}finally{clearTimeout(a)}},pR=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 uR(s)}}finally{clearTimeout(a)}},m2=e=>new Promise(t=>setTimeout(t,e)),Ep=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Fs)(),a;try{a=await Qc(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},mw,n)}catch(f){throw new bt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${Rt(f)}`)}if(a.status!==200){let f=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new bt(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 bt("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??l2,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}`),h2(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},h2=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},xp=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??m2,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 Qc(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},mw,o)}catch(c){throw new Ot("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${Rt(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 Ot("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Ot("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Ot("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var lR="sdc_",fR=e=>{let t=e.trim();if(!t)return;if(t.startsWith(lR))return{cpOrigin:vn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!aw(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(lR)))return{cpOrigin:n.origin,claim:r}},mR=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Fs)(),o;try{o=await Qc(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},mw,t)}catch(s){throw new Ot("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${Rt(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 Ot("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Ot("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Ot("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 y2}from"node:fs/promises";import{isAbsolute as g2,posix as hR,win32 as hw}from"node:path";var el=(e=process.platform,t=process.env)=>e==="darwin"?hR.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?hw.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):hR.join("/etc","anyray","bootstrap.json"),w2=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),yR=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(g2(e)||hw.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),b2=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}},So=async(e=el())=>{try{let t=await y2(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!w2(n)||n.v!==1||typeof n.sso!="string")return;let r=Ft(n.sso);if(!r)return;let o=b2(n.gateway)?n.gateway:void 0,a=yR(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},gR=(e,t,n)=>{let r=Ft(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!yR(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&hw.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.`,H0=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return k(NV),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 DV({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 Et)throw o;return D(o instanceof rn?o.message:"SSO login failed."),1}};import{writeFileSync as kj}from"node:fs";import{chmod as yw,stat as Cj}from"node:fs/promises";import{platform as kR}from"node:os";import{dirname as CR,isAbsolute as Aj}from"node:path";var LV="https://app.anyray.ai",$V=new Set(["localhost","::1","[::1]"]),MV=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,BV=e=>$V.has(e)||MV.test(e),aw=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&BV(t.hostname)},FV=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},vn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!aw(e)?LV:FV(e)};import{createHash as qV,generateKeyPairSync as QV,randomBytes as cw}from"node:crypto";import{createPrivateKey as UV,sign as WV}from"node:crypto";var rr=async(e,t)=>{let n=UV(t);return WV(null,new TextEncoder().encode(e),n).toString("base64url")};var HV=["HTTPS_PROXY","https_proxy"],G0=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"]),K0=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),V0=new Set(["ENOTFOUND","EAI_AGAIN"]),j0=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Y0=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),GV=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 KV(e)},KV=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...G0,...K0,...V0,...j0,...Y0])if(t.includes(n))return n}},VV=e=>e?.name==="AbortError"||e?.name==="TimeoutError",jV=e=>HV.filter(t=>(e[t]??"").trim()!==""),YV=(e,t=process.env)=>{let n=GV(e),r=jV(t);return{kind:n&&G0.has(n)?"tls-unknown-issuer":n&&K0.has(n)?"tls-invalid-cert":n&&V0.has(n)?"dns":VV(e)||n&&Y0.has(n)?"timeout":n&&j0.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},ZV=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}},Rt=(e,t=process.env)=>ZV(YV(e,t));var JV="enl_",Z0="enp_",J0=e=>e.startsWith(JV)||e.startsWith(Z0),sw=e=>e.startsWith(Z0),XV=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],iw=e=>XV.find(t=>e.startsWith(t.prefix)),X0=/^\/enroll\/([^/]+)\/?$/,z0=/^\/i\/([^/]+)\/?$/,q0=e=>{let t=e.match(X0);if(t)return iw(t[1])?void 0:t[1];let n=e.match(z0);return n&&J0(n[1])?n[1]:void 0},zV=1e4,Ip=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=q0(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!iw(t))return{cpOrigin:vn(),token:t}},Q0=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(X0)??o.pathname.match(z0);if(!a)return;n=a[1]}catch{}let r=iw(n);return r?{flag:r.flag,what:r.what}:void 0},Xc=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:q0(n.pathname)!==void 0}catch{return J0(t)}},Ms=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},Jc=e=>typeof e=="string"&&e.trim()?e.trim():void 0,eR=async(e,t={})=>{let n=t.timeoutMs??zV,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.`:Rt(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 Ms(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"&&Jc(u.url)!==void 0),d=Jc(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:Jc(l?.deploymentId),org:Jc(i.org),email:Jc(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 lw=1e4,Aa=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Aa).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Aa(e[n])}`).join(",")}}`,tR="stable-key-heartbeat-v1",nR="key-heartbeat",ej=["reapply_config","remint","revert"],dw=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var rR=e=>qV("sha256").update(e).digest("hex"),et=e=>typeof e=="string"&&e.trim()?e.trim():void 0,tj=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],oR={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"},nj=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${oR[e]}. Ask your IT admin.`,rj=e=>typeof e=="string"&&e in oR,uw=async e=>{try{let t=await e.json(),n=et(t?.message),r=et(t?.error),o=rj(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:nj(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},oj=async e=>(await uw(e)).message,ct=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}},zc=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="GatewayUnreachableError"}},qc=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="ControlPlaneUnreachableError"}},pw=e=>e instanceof Ms||e instanceof ct&&e.policyCode==="sso_required",Bs=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}},fw=async(e,t,n,r)=>{try{return await r(Aa(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Fs=()=>{let{publicKey:e,privateKey:t}=QV("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},Sn=async(e,t,n,r={})=>{let o=r.timeoutMs??lw,a=`${e}/connect/verify`,s=et(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:cw(16).toString("hex"),...dw(t,r.machineUuid)},c=await fw(i,n,"verification",r.signer??rr),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":Le},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(w){let b=w instanceof Error&&w.name==="AbortError"?` no response within ${o}ms.`:Rt(w);throw new zc(`could not reach the gateway at ${a}.${b}`,w)}finally{clearTimeout(d)}if(!u.ok)throw new ct(u.status,await uw(u));let p;try{p=await u.text()}catch{p=""}let m;try{m=JSON.parse(p)}catch{let w=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(w)||/^\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=et(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=et(m.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let g=aj(m.directive),y=tj(m.capabilities);return{key:f,user:h,team:et(m.team),expiresAt:et(m.expiresAt),...y.length>0?{capabilities:y}:{},...g?{directive:g}:{}}},aR=async(e,t,n,r,o={})=>{let a=o.timeoutMs??lw,s=`${e}/connect/key/heartbeat`,i=et(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:cw(16).toString("hex"),purpose:nR,...dw(n,o.machineUuid)},l=await fw(c,r,"heartbeat",o.signer??rr),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":Le},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(h){let g=h instanceof Error&&h.name==="AbortError"?` no response within ${a}ms.`:Rt(h);throw new Error(`could not reach the gateway at ${s}.${g}`,{cause:h})}finally{clearTimeout(u)}if(!p.ok)throw new Bs(p.status,await uw(p));let m;try{m=await p.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let f=et(m.expiresAt);if(!f||!Number.isFinite(Date.parse(f))||m.credentialMode!==tR||m.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:f,credentialMode:tR}},sR=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??lw,i=`${e.replace(/\/$/,"")}/connect/machine`,c=et(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:cw(16).toString("hex"),purpose:nR,...dw(n,o)},d=await fw(l,r,"heartbeat",a.signer??rr),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":Le},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)}},aj=e=>{if(e===null||typeof e!="object")return null;let t=e,n=et(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!ej.includes(r)?null:{id:n,kind:r}},sj=1e4,ij=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!et(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!et(r.deploymentId)&&!!et(r.user)&&!!et(r.devPublicKey)&&!!et(r.issuedAt)&&!!et(r.expiresAt)},cj=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??sj,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.`:Rt(u);throw new qc(`could not reach the control plane at ${s}.${p}`,u)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await oj(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new Ms(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(!ij(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},iR=(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())},cR=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=Fs();return{cert:await cj(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await Sn(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};var mw=1e4,lj=900*1e3,dR="tnt_",dj=/^\/sso\/([^/]+)\/?$/,uj=/^\/i\/([^/]+)\/?$/,pj=e=>{let t=e.match(dj);if(t)return t[1];let n=e.match(uj);return n?.[1].startsWith(dR)?n[1]:void 0},Ft=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=pj(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(dR))return{cpOrigin:vn(),tenantId:t}},bt=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Ot=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},fj=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),uR=async e=>{try{let t=await e.json();return fj(t)?t:{}}catch{return{}}},Qc=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 uR(s)}}finally{clearTimeout(a)}},pR=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 uR(s)}}finally{clearTimeout(a)}},mj=e=>new Promise(t=>setTimeout(t,e)),Ep=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Fs)(),a;try{a=await Qc(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},mw,n)}catch(f){throw new bt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${Rt(f)}`)}if(a.status!==200){let f=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new bt(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 bt("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??lj,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}`),hj(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},hj=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},xp=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??mj,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 Qc(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},mw,o)}catch(c){throw new Ot("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${Rt(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 Ot("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Ot("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Ot("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var lR="sdc_",fR=e=>{let t=e.trim();if(!t)return;if(t.startsWith(lR))return{cpOrigin:vn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!aw(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(lR)))return{cpOrigin:n.origin,claim:r}},mR=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Fs)(),o;try{o=await Qc(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},mw,t)}catch(s){throw new Ot("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${Rt(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 Ot("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Ot("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Ot("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 yj}from"node:fs/promises";import{isAbsolute as gj,posix as hR,win32 as hw}from"node:path";var el=(e=process.platform,t=process.env)=>e==="darwin"?hR.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?hw.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):hR.join("/etc","anyray","bootstrap.json"),wj=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),yR=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(gj(e)||hw.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),bj=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}},So=async(e=el())=>{try{let t=await yj(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!wj(n)||n.v!==1||typeof n.sso!="string")return;let r=Ft(n.sso);if(!r)return;let o=bj(n.gateway)?n.gateway:void 0,a=yR(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},gR=(e,t,n)=>{let r=Ft(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!yR(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&hw.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 gw=`${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,13 +531,13 @@ ${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`,wR=["claude-code","jetbrains","shell","bootstrap"],
|
|
535
|
-
`)},Op=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}
|
|
536
|
-
`),
|
|
537
|
-
`),tt(v("# acp.json for ~/.jetbrains/acp.json (per user).")),tt(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),tt(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),tt(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},
|
|
538
|
-
`),tt(v(`# managed-settings.json for ${Kt()}`)),n)tt(v("# Deferred SSO: hooks only; no credential or managed env block.")),tt(v(`# Push the binary to ${n.binaryPath} before this file.`)),tt(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of RR(t))tt(v(`# ${o}`));kw(t,tt)}return 0},
|
|
534
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,wR=["claude-code","jetbrains","shell","bootstrap"],vj=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(!wR.includes(a))throw new Error(`unknown --tool ${a} (expected ${wR.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&&!Ft(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};var bR=e=>({extraKnownMarketplaces:{[_n]:{source:{source:"url",url:Zk(e)}}},strictPluginOnlyCustomization:{skills:!0}});function Rp(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]:[]],s={hooks:{UserPromptSubmit:[cr(xl(t.binaryPath,a),{timeout:30})],SessionStart:[cr(xl(t.binaryPath,[...a,"--session-start"]),{async:!0})]}};return Fl(s,i=>xl(t.binaryPath,[i])),{...s,...n.lockSkills?bR(e.origin):{}}}let{env:r}=Tn(e,{includeAuthToken:!1,includeClientKey:!1}),o=n.lockSkills?bR(e.origin):{};return n.scrubDirectMode?{env:{...Object.fromEntries(lr.map(a=>[a.name,""])),...r},...o}:{env:r,...o}}var Sj=(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 Fo)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,xf(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 AR(r),n.extraKnownMarketplaces&&(r.extraKnownMarketplaces={...r.extraKnownMarketplaces??{},...n.extraKnownMarketplaces}),n.strictPluginOnlyCustomization&&(r.strictPluginOnlyCustomization=n.strictPluginOnlyCustomization),r},AR=e=>{let t=!1,n=e.extraKnownMarketplaces;return n&&typeof n=="object"&&_n in n&&(delete n[_n],Object.keys(n).length===0&&delete e.extraKnownMarketplaces,t=!0),JSON.stringify(e.strictPluginOnlyCustomization)===JSON.stringify({skills:!0})&&(delete e.strictPluginOnlyCustomization,t=!0),t},Ij=e=>{let t=e.env,n=xf(e);if(t){for(let r of Fo)r in t&&(delete t[r],n=!0);for(let{name:r}of lr)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return AR(e)&&(n=!0),n},vR=async e=>{let t=async n=>{try{return(await Cj(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(CR(e))!==void 0}},SR=async(e,t)=>(t.dirExisted||await yw(CR(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await yw(e,420),{mode:420,keptRestricted:!1}):(await yw(e,t.mode),{mode:t.mode,keptRestricted:!0})),IR=(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.`),k(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.")))},ER=()=>process.getuid?.()===0,tt=e=>{process.stderr.write(`${e}
|
|
535
|
+
`)},Op=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}kj(e.out,t,"utf8"),tt(v(`# Wrote ${e.out}`))},ww=e=>Re({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),bw=e=>Aj(e)||/^[A-Za-z]:[\\/]/.test(e),xR=e=>{if(!e.sso)return;let t=Ft(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??De();if(!e.bin&&!ne())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(!bw(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}},RR=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)"}`],kw=(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{}},Ej=(e,t)=>({agent_servers:{[Pr]:{command:e,args:[Fu,"claude",t,"jetbrains"],env:{}},[Dr]:{command:e,args:[Fu,"codex",t,"jetbrains"],env:{}}}}),xj=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
|
+
`),Rj=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(!bw(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(!Hu(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return Op(e,`${JSON.stringify(Ej(e.bin,e.npx),null,2)}
|
|
537
|
+
`),tt(v("# acp.json for ~/.jetbrains/acp.json (per user).")),tt(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),tt(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),tt(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},Oj=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&&!bw(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return Op(e,gR(e.sso,e.gateway,e.bin)),tt(v(`# Fleet bootstrap for ${el("linux")}`)),tt(v(`# macOS: ${el("darwin")}`)),tt(v(`# Windows: ${el("win32",{ProgramData:"C:\\ProgramData"})}`)),tt(v("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},_j=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=ww(e);return Op(e,xj(t)),tt(v("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),kw(t,tt),0},Tj=e=>{let t=ww(e),n=xR(e),r=n?Rp(t,n,{lockSkills:e.lockSkills}):Rp(t,void 0,{scrubDirectMode:e.scrubDirectMode,lockSkills:e.lockSkills});if(Op(e,`${JSON.stringify(r,null,2)}
|
|
538
|
+
`),tt(v(`# managed-settings.json for ${Kt()}`)),n)tt(v("# Deferred SSO: hooks only; no credential or managed env block.")),tt(v(`# Push the binary to ${n.binaryPath} before this file.`)),tt(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of RR(t))tt(v(`# ${o}`));kw(t,tt)}return 0},Pj=async e=>{let t=kR();if(t!=="darwin"&&t!=="linux")return D("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!ER())return D("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),k(v(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=ww(e),r=xR(e);r||kw(n,p=>P(p.replace(/^!\s*/,"")));let o=Kt(t),a=Xr(o),s=a.value,i=r?Rp(n,r,{lockSkills:e.lockSkills}):Rp(n,void 0,{scrubDirectMode:e.scrubDirectMode,lockSkills:e.lockSkills}),c=e.scrubDirectMode?lr.filter(({name:p})=>{let m=s.env?.[p];return typeof m=="string"&&m.trim()!==""}):[],l=Sj(s,i),d=await vR(o);await q(o,l,{expectedFingerprint:a.fingerprint});let u=await SR(o,d);B(`Wrote ${o}`),IR(o,u);for(let{name:p,cloud:m}of c)P(`${p} was set in this file and is now pinned empty \u2014 Claude Code no longer talks to ${m} directly. The gateway serves it instead; re-add the key here to undo.`);if(r)k(v(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),k(v(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let p of RR(n))k(` ${v(p)}`);return k(v(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},Dj=async()=>{let e=kR();if(e!=="darwin"&&e!=="linux")return D("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!ER())return D("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Kt(e);if(!await R(t))return k(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=Xr(t),r=n.value;if(!Ij(r))return k(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let o=await vR(t);await q(t,r,{expectedFingerprint:n.fingerprint});let a=await SR(t,o);return B(`Removed Anyray-owned keys from ${t} (other keys left intact).`),IR(t,a),0},OR=async e=>{let t;try{t=vj(e)}catch(n){return D(n instanceof Error?n.message:"invalid managed arguments"),k(`
|
|
539
539
|
`+gw),1}if(t.help||e.length===0&&!t.mode)return k(gw),0;if(!t.mode)return D("Specify a mode: --print, --write, or --revert."),k(`
|
|
540
|
-
`+gw),1;if(t.out!==void 0&&t.mode!=="print")return D(`--out is valid with --print only, not --${t.mode}.`),1;if(t.scrubDirectMode){let n=t.sso!==void 0?"--sso emits a hooks-only file with no env block":(t.tool??"claude-code")!=="claude-code"?`--tool ${t.tool} does not write Claude Code env`:t.mode==="revert"?"--revert already removes the pin (and leaves a truthy value alone)":void 0;if(n)return D(`--scrub-direct-mode cannot be combined with this mode: ${n}.`),1}try{let n=t.tool??"claude-code";return n!=="claude-code"?t.mode!=="print"?(D(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?
|
|
540
|
+
`+gw),1;if(t.out!==void 0&&t.mode!=="print")return D(`--out is valid with --print only, not --${t.mode}.`),1;if(t.scrubDirectMode){let n=t.sso!==void 0?"--sso emits a hooks-only file with no env block":(t.tool??"claude-code")!=="claude-code"?`--tool ${t.tool} does not write Claude Code env`:t.mode==="revert"?"--revert already removes the pin (and leaves a truthy value alone)":void 0;if(n)return D(`--scrub-direct-mode cannot be combined with this mode: ${n}.`),1}try{let n=t.tool??"claude-code";return n!=="claude-code"?t.mode!=="print"?(D(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?Rj(t):n==="bootstrap"?Oj(t):_j(t):t.mode==="print"?Tj(t):t.mode==="write"?await Pj(t):await Dj()}catch(n){return D(n instanceof Error?n.message:"managed settings failed"),1}};import{promises as Nj}from"node:fs";var Lj=`anyray-connect migrate [options]
|
|
541
541
|
|
|
542
542
|
Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
|
|
543
543
|
|
|
@@ -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
|
-
`,$
|
|
570
|
-
`).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${M2(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";k(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&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(` ${_R[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${Zy(s.reason,s.lane,Tt("migrate"))}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&k(v(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},F2=async(e,t)=>{if(k(""),k(Z("2. Your claude.ai chats")),t){k(v(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){k(" These live on your Claude account, not this machine, so they need"),k(" an export. Anyray cannot fetch them: the only credential that could"),k(" is your claude.ai session, which Connect never holds."),k(v(" claude.ai -> Settings -> Privacy -> Export data, then:")),k(v(` ${Tt("migrate --export ~/Downloads/claude-export.zip")}`));return}let n=await Eu(e.exportZip);if(!n.ok){D(` ${n.reason}`),k(` ${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`:"")),k(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&&k(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},U2=async e=>{if(k(""),k(Z("3. Searchable from every Anyray client")),!e.conversations){let o=await $s();o>0?k(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(k(v(" Optional. Pass the conversations.json inside the export:")),k(v(` ${Tt("migrate --conversations <path>/conversations.json")}`)));return}let t;try{t=await L2.readFile(e.conversations,"utf8")}catch{D(` could not read ${e.conversations}`);return}let n=Cp(t);if(!n.ok){D(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Sp(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`:"")),k(v(` Ask any Anyray-connected client about a past chat. ${await vo()}`))},W2=e=>{k(""),k(Z("Next")),k(" 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."),k(v(` No Chat tab? Configured before this Connect version: run \`${Tt("desktop")}\`.`))},TR=async(e,t={})=>{let n;try{n=$2(e)}catch(o){return D(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(N2),0;k(Z("Migrating Claude Desktop onto Anyray")),k(v("Claude Desktop must be fully quit.")),k("");let r=await B2(n,t);return await F2(n,!r),await U2(n),r?(W2(n),0):(k(""),P("Fix the item above and re-run to finish the migration."),1)};import{spawn as sZ}from"node:child_process";import{homedir as iZ}from"node:os";import{join as bO}from"node:path";import{readFile as cZ,writeFile as kO,chmod as lZ,stat as dZ,unlink as lO}from"node:fs/promises";import{mkdir as G2,readFile as K2,rm as V2,rmdir as j2,writeFile as Y2}from"node:fs/promises";import{join as tl}from"node:path";import{z as ge}from"zod";var va="required",H2=e=>e==="subscription"?"subscription":"placeholder",PR=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?H2(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}:{}}},_p=(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]??va,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}},DR=(e,t,n)=>{let r=[],o=[],a=[];if(t===void 0||t.defaulted===!0){for(let c of n)zr(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]??va;if(d==="optional"){a.push({id:l,reason:"optional"});continue}if(zr(c)){d==="locked"?r.push(l):a.push({id:l,reason:"consent"});continue}r.push(l)}return{applyIds:r,revertIds:o,skipped:a}};var Z2=1e4,J2=1,$R=ge.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),X2=ge.object({id:$R,name:ge.string().min(1),version:ge.string().min(1),body:ge.string(),plugin:ge.boolean().optional()}),z2=ge.object({url:ge.string().url(),plugins:ge.array($R)}),q2=ge.object({version:ge.literal(J2).optional(),skills:ge.array(X2),skillsIncomplete:ge.boolean().optional(),marketplace:z2.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()}),Us=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},vw=e=>e instanceof Us&&e.kind==="auth",Cw=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",Ws=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",Hs=async(e,t,n={})=>{let r=n.timeoutMs??Z2,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.`:Rt(l);throw new Us("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Us(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 Us("malformed","team policy fetch failed: the gateway returned a malformed response")}return q2.parse(c)},LR=/^[a-z0-9][a-z0-9-]{0,31}$/,NR=64,MR=e=>{let t=e.tools;if(!t||t.defaulted===!0)return;let n=t.enabled.filter(o=>LR.test(o)).slice(0,NR).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>LR.test(o)).slice(0,NR).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},Sw=async(e,t,n=Hs)=>{let r=await n(e,t),o=MR(r);return await yi(a=>{let{fleetToolPolicy:s,...i}=a;return{next:{...i,...o?{fleetToolPolicy:o}:{}},result:void 0}}),r},Q2=e=>e.updates?{mode:e.updates.mode}:void 0,nl=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??va)==="locked":!1},Gs=async(e,t={})=>{let n=t.loadProfile??N,r=t.saveProfile??pe,o=t.targetFromProfile??Je,a=t.adapters??ie,s=t.repairTools??tn,i=t.recordManaged??Vr,c=await n(),l={...c},d=PR(c,{routingOrigin:e.routing?.origin?dn(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=_p(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers,defaulted:e.tools?.defaulted},u||p||m),{candidateIds:h,freshIds:g}=f,y=0,w=0,b=0;if(h.length>0||g.length>0){let E=await o(async()=>l);if(E){let T;if(u||p||m){let G=new Set(h);T=[];for(let X of a)if(G.has(X.id))try{(await X.detect()).installed&&T.push(X)}catch{}}else T=await Ts(h,E.target.origin,a);let I=new Set(g),K=[];for(let G of a)if(I.has(G.id))try{(await G.detect()).installed&&K.push(G)}catch{}if(y=T.length+K.length,y>0){let G=await s([...T,...K],E.target);w=G.filter(ga).length;let X=G.filter(ae=>I.has(ae.id));if(b=X.filter(ga).length,X.length>0)try{await i(X,!1)}catch{}}}}let A=MR(e),C=Q2(e),x=await n(),O=JSON.stringify(A??null)!==JSON.stringify(x.fleetToolPolicy??null),S=JSON.stringify(C??null)!==JSON.stringify(x.fleetUpdatePolicy??null);if(O||S){let{fleetToolPolicy:E,fleetUpdatePolicy:T,...I}=x;await r({...I,...A?{fleetToolPolicy:A}:{},...C?{fleetUpdatePolicy:C}:{}})}return{routingUpdated:u,teamUpdated:p,laneUpdated:m,toolsRequested:y,toolsApplied:w,toolsEnrolled:b,toolsTombstoned:f.tombstonedIds,profileUpdated:u||p||m,updatesMode:C?.mode??"auto",updatesUpdated:S}},eY=(e,t=ie,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()]},tY=e=>e.map(t=>typeof t=="string"?{dir:t,includePluginSkills:!0}:t),Aw=async(e,t)=>{await V2(tl(e,t,"SKILL.md"),{force:!0}),await j2(tl(e,t)).catch(()=>{})},nY=e=>{let t=e.body.replace(/\r\n?/g,`
|
|
569
|
+
`,$j=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},_R={code:"Claude Code sessions",cowork:"Cowork tasks"},Mj=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`${_R[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},Bj=async(e,t)=>{k(Z("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??la)({account:e.account,allAccounts:e.allAccounts,command:Tt("migrate")});if(!n.ok){D(` ${n.reason}`);for(let s of n.remedy.split(`
|
|
570
|
+
`).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${Mj(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";k(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&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(` ${_R[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${Zy(s.reason,s.lane,Tt("migrate"))}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&k(v(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},Fj=async(e,t)=>{if(k(""),k(Z("2. Your claude.ai chats")),t){k(v(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){k(" These live on your Claude account, not this machine, so they need"),k(" an export. Anyray cannot fetch them: the only credential that could"),k(" is your claude.ai session, which Connect never holds."),k(v(" claude.ai -> Settings -> Privacy -> Export data, then:")),k(v(` ${Tt("migrate --export ~/Downloads/claude-export.zip")}`));return}let n=await Eu(e.exportZip);if(!n.ok){D(` ${n.reason}`),k(` ${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`:"")),k(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&&k(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},Uj=async e=>{if(k(""),k(Z("3. Searchable from every Anyray client")),!e.conversations){let o=await $s();o>0?k(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(k(v(" Optional. Pass the conversations.json inside the export:")),k(v(` ${Tt("migrate --conversations <path>/conversations.json")}`)));return}let t;try{t=await Nj.readFile(e.conversations,"utf8")}catch{D(` could not read ${e.conversations}`);return}let n=Cp(t);if(!n.ok){D(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Sp(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`:"")),k(v(` Ask any Anyray-connected client about a past chat. ${await vo()}`))},Wj=e=>{k(""),k(Z("Next")),k(" 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."),k(v(` No Chat tab? Configured before this Connect version: run \`${Tt("desktop")}\`.`))},TR=async(e,t={})=>{let n;try{n=$j(e)}catch(o){return D(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(Lj),0;k(Z("Migrating Claude Desktop onto Anyray")),k(v("Claude Desktop must be fully quit.")),k("");let r=await Bj(n,t);return await Fj(n,!r),await Uj(n),r?(Wj(n),0):(k(""),P("Fix the item above and re-run to finish the migration."),1)};import{spawn as sZ}from"node:child_process";import{homedir as iZ}from"node:os";import{join as bO}from"node:path";import{readFile as cZ,writeFile as kO,chmod as lZ,stat as dZ,unlink as lO}from"node:fs/promises";import{mkdir as Gj,readFile as Kj,rm as Vj,rmdir as jj,writeFile as Yj}from"node:fs/promises";import{join as tl}from"node:path";import{z as ge}from"zod";var va="required",Hj=e=>e==="subscription"?"subscription":"placeholder",PR=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?Hj(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}:{}}},_p=(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]??va,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}},DR=(e,t,n)=>{let r=[],o=[],a=[];if(t===void 0||t.defaulted===!0){for(let c of n)zr(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]??va;if(d==="optional"){a.push({id:l,reason:"optional"});continue}if(zr(c)){d==="locked"?r.push(l):a.push({id:l,reason:"consent"});continue}r.push(l)}return{applyIds:r,revertIds:o,skipped:a}};var Zj=1e4,Jj=1,$R=ge.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),Xj=ge.object({id:$R,name:ge.string().min(1),version:ge.string().min(1),body:ge.string(),plugin:ge.boolean().optional()}),zj=ge.object({url:ge.string().url(),plugins:ge.array($R)}),qj=ge.object({version:ge.literal(Jj).optional(),skills:ge.array(Xj),skillsIncomplete:ge.boolean().optional(),marketplace:zj.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()}),Us=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},vw=e=>e instanceof Us&&e.kind==="auth",Cw=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",Ws=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",Hs=async(e,t,n={})=>{let r=n.timeoutMs??Zj,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.`:Rt(l);throw new Us("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Us(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 Us("malformed","team policy fetch failed: the gateway returned a malformed response")}return qj.parse(c)},NR=/^[a-z0-9][a-z0-9-]{0,31}$/,LR=64,MR=e=>{let t=e.tools;if(!t||t.defaulted===!0)return;let n=t.enabled.filter(o=>NR.test(o)).slice(0,LR).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>NR.test(o)).slice(0,LR).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},Sw=async(e,t,n=Hs)=>{let r=await n(e,t),o=MR(r);return await yi(a=>{let{fleetToolPolicy:s,...i}=a;return{next:{...i,...o?{fleetToolPolicy:o}:{}},result:void 0}}),r},Qj=e=>e.updates?{mode:e.updates.mode}:void 0,nl=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??va)==="locked":!1},Gs=async(e,t={})=>{let n=t.loadProfile??L,r=t.saveProfile??pe,o=t.targetFromProfile??Je,a=t.adapters??ie,s=t.repairTools??tn,i=t.recordManaged??Vr,c=await n(),l={...c},d=PR(c,{routingOrigin:e.routing?.origin?dn(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=_p(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers,defaulted:e.tools?.defaulted},u||p||m),{candidateIds:h,freshIds:g}=f,y=0,w=0,b=0;if(h.length>0||g.length>0){let E=await o(async()=>l);if(E){let T;if(u||p||m){let G=new Set(h);T=[];for(let X of a)if(G.has(X.id))try{(await X.detect()).installed&&T.push(X)}catch{}}else T=await Ts(h,E.target.origin,a);let I=new Set(g),K=[];for(let G of a)if(I.has(G.id))try{(await G.detect()).installed&&K.push(G)}catch{}if(y=T.length+K.length,y>0){let G=await s([...T,...K],E.target);w=G.filter(ga).length;let X=G.filter(ae=>I.has(ae.id));if(b=X.filter(ga).length,X.length>0)try{await i(X,!1)}catch{}}}}let A=MR(e),C=Qj(e),x=await n(),O=JSON.stringify(A??null)!==JSON.stringify(x.fleetToolPolicy??null),S=JSON.stringify(C??null)!==JSON.stringify(x.fleetUpdatePolicy??null);if(O||S){let{fleetToolPolicy:E,fleetUpdatePolicy:T,...I}=x;await r({...I,...A?{fleetToolPolicy:A}:{},...C?{fleetUpdatePolicy:C}:{}})}return{routingUpdated:u,teamUpdated:p,laneUpdated:m,toolsRequested:y,toolsApplied:w,toolsEnrolled:b,toolsTombstoned:f.tombstonedIds,profileUpdated:u||p||m,updatesMode:C?.mode??"auto",updatesUpdated:S}},eY=(e,t=ie,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()]},tY=e=>e.map(t=>typeof t=="string"?{dir:t,includePluginSkills:!0}:t),Aw=async(e,t)=>{await Vj(tl(e,t,"SKILL.md"),{force:!0}),await jj(tl(e,t)).catch(()=>{})},nY=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]===`
|
|
@@ -576,9 +576,9 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
|
|
|
576
576
|
${u.join(`
|
|
577
577
|
`)}
|
|
578
578
|
---
|
|
579
|
-
${s}`)},Tp=e=>/^[ \t]*/.exec(e)?.[0]??"",rY=/^([ \t]*)(?:"name"|'name'|name)[ \t]*:(.*)$/i,oY=/^([ \t]*)(?:"description"|'description'|description)[ \t]*:(.*)$/i,aY=async(e,t,n)=>{for(let r of e)try{if(await
|
|
579
|
+
${s}`)},Tp=e=>/^[ \t]*/.exec(e)?.[0]??"",rY=/^([ \t]*)(?:"name"|'name'|name)[ \t]*:(.*)$/i,oY=/^([ \t]*)(?:"description"|'description'|description)[ \t]*:(.*)$/i,aY=async(e,t,n)=>{for(let r of e)try{if(await Kj(tl(r,t,"SKILL.md"),"utf-8")!==n)return!1}catch{return!1}return!0},sY=async(e,t,n,r={})=>{let o=tY(t),a=[],s={},i=new Set,c=0,l=0;for(let p of e.skills){if(!Cw(p.id))continue;i.add(p.id),s[p.id]=p.version;let m=nY(p),f=o.filter(y=>y.includePluginSkills||!p.plugin).map(y=>y.dir);for(let y of o)f.includes(y.dir)||await Aw(y.dir,p.id);if(n[p.id]===p.version&&await aY(f,p.id,m)){l+=1,a.push({id:p.id,name:p.name,version:p.version,written:!1,files:[]});continue}let g=[];for(let y of f){let w=tl(y,p.id),b=tl(w,"SKILL.md");await Gj(w,{recursive:!0}),await Yj(b,m,"utf-8"),g.push(b)}c+=1,a.push({id:p.id,name:p.name,version:p.version,written:!0,files:g})}let d=[];for(let[p,m]of Object.entries(n))if(!(i.has(p)||!Cw(p))){if(e.skillsIncomplete){s[p]=m;continue}for(let f of o)await Aw(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)]))Cw(m)&&await Aw(p,m);u.push(p)}return{results:a,changed:c,unchanged:l,removed:d,cleanedDirs:u,versions:s,updatedAt:e.updatedAt}},iY=e=>e.endsWith(`
|
|
580
580
|
`)?e:`${e}
|
|
581
|
-
`,cY=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}},lY=(e,t)=>{let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>e[r]===t[r])},Iw=async(e,t={})=>{let n=t.loadProfile??N,r=BR(t,n),o=t.adapters??ie,a=await n(),s=await cY(e.marketplace,a.managedTools,o),i=eY(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 sY(c.length===0?{...e,skills:[]}:e,i,l,{staleDirs:u});if(p.changed>0||p.removed.length>0||p.cleanedDirs.length>0||!lY(l,p.versions)||!dY(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}},BR=(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}:yi},dY=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),Ew=async(e,t={})=>{let n=t.loadProfile??N,r=await n(),o=t.adapters??ie,a=e.mcp?.org.url&&r.clientKey?{url:e.mcp.org.url,clientKey:r.clientKey}:void 0,s=a!==void 0,i=[],c=yC(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 pY(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 BR(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,uY)},result:void 0}})}catch{}return{changed:i,served:s}},uY=8,Pp=async(e,t={})=>{if(!e.gateway||!e.clientKey)return;let n=await(t.fetchTeamPolicy??Hs)(e.gateway,e.clientKey),r=await(t.syncSkills??Iw)(n).catch(()=>{}),o=await(t.syncOrgMcp??Ew)(n).catch(()=>{});return{policy:n,skills:r,mcp:o}},pY=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 fY}from"node:crypto";var mY=1e4,hY="machine:",FR=e=>e.startsWith(hY),yY="cert-renew",gY=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)},UR=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??vn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:fY(16).toString("hex"),purpose:yY},c;try{c=await(n.signer??rr)(Aa(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),mY),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 gY(m)?{ok:!0,cert:m}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var xw=async(e,t=e.origin,n=ie)=>{let r=0,o=0,a=!0;for(let s of n)try{if(!s.pointsAt||!await s.pointsAt(t)||await s.usesDynamicCredential?.(t))continue;r+=1,(await s.apply(e,{dryRun:!1})).status==="configured"?o+=1:a=!1}catch{a=!1}return{matched:r,rewritten:o,complete:a}},Rw=async(e,t=e.origin,n=ie)=>(await xw(e,t,n)).complete;var wY=["claude","codex","cursor","opencode"],bY=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],kY=new Set(["missing_key","key_expired"]);var CY=600*1e3,AY=600*1e3,WR=1440*60*1e3,vY=1440*60*1e3,SY=10080*60*1e3,IY=3600*1e3,EY=720*60*1e3,xY=e=>Math.min(EY,IY*2**Math.max(0,e-1)),rl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ks=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,HR=e=>typeof e=="string"&&bY.includes(e),or=e=>{if(!rl(e))return{};let t={};if(Ks(e.watchSince)&&(t.watchSince=e.watchSince),rl(e.invoked)){let n={};for(let r of wY){let o=e.invoked[r];Ks(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return rl(e.authFailure)&&Ks(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...HR(e.authFailure.code)?{code:e.authFailure.code}:{}}),rl(e.repair)&&Ks(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,...Ks(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Dp=e=>{try{let n=JSON.parse(e);if(rl(n)&&HR(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"},Ow=e=>e!==void 0&&kY.has(e),_w=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=CY},GR=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),Tw=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=AY},KR=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),VR=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,jR=(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},YR=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>WR||!Ow(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<xY(r.failures??1))},Lp=e=>{let t=Object.values(e?.invoked??{}).filter(Ks);return t.length>0?Math.max(...t):null},Pw=(e,t)=>{if(Lp(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=SY},ZR=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=vY)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=WR)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var Dw="x-anyray-retrieve-probe",Np=8e3,RY=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Lw=e=>{try{let t=e?.name;if(typeof t=="string"&&/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(t))return t}catch{}return"Error"},JR=e=>Lw(e)==="AbortError",XR=(e,t)=>{let n=fn(e);return t?.probe&&(n[Dw]="1"),n},Vs=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(),Np);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:XR(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=RY(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=JR(a);return{ok:!1,kind:s?"timeout":"network",message:s?"Retrieval timed out.":`Retrieval failed to reach the gateway (${Lw(a)}).`}}finally{clearTimeout(o)}},$p=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(),Np);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:XR(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=JR(s);return{ok:!1,kind:i?"timeout":"network",message:i?"Recall timed out.":`Recall failed to reach the gateway (${Lw(s)}).`}}finally{clearTimeout(a)}};var OY=5e3,_Y=2048,TY=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}"`))},js=async(e={})=>{let t=e.readTarget??pt,n=e.fetch??fetch,r=e.timeoutMs??OY,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=fn(o);i["content-type"]="application/json",i[Dw]="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,_Y);if(!TY(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let p=Dp(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)}},Nw=(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 LY}from"node:crypto";import{execSync as $w}from"node:child_process";import{hostname as PY}from"node:os";var DY=e=>{try{if(e==="darwin"){let t=$w("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=$w('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 $w("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Mp=(e={platform:process.platform,read:()=>DY(process.platform),hostname:PY})=>e.read().trim()||e.hostname().trim();var on=(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??(()=>Mp());try{return r().trim().toLowerCase()}catch{return""}}return""};var NY=500,zR=2e3,$Y=2e3,MY=250,qR=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),NY);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)}},BY=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},FY=e=>new Promise(t=>setTimeout(t,e)),UY=async(e,t,n=FY)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),zR),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=BY(i)??MY,s>$Y))return!1}finally{clearTimeout(a)}await n(s)}},WY=async(e,t={})=>{try{let r=(await(t.loadProfile??N)()).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:LY(16).toString("hex"),events:e},i;try{i=await(t.signer??rr)(Aa(s),o)}catch{return!1}return await(t.post??UY)(`${t.origin??vn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},HY=async(e,t,n={})=>{try{let o=(await(n.loadProfile??N)()).enrolledCert,a=await(n.loadDevKey??Ye)();if(!o||!a)return;await(n.verify??Sn)(e,o,a,{timeoutMs:zR,machineUuid:(n.machineUuid??on)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},QR=async(e,t)=>{if(e.length!==0)try{let n=await pt(),r=n&&await qR(n.origin,fn(n),e,t);if(n&&await HY(n.origin,e),r)return;await WY(e)}catch{}},Mw=async(e,t,n={readTarget:()=>pt("profile"),post:qR})=>{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 Ia=["hook_registration","mcp_registration","hook_binary","beacon_target"];var tO=128,nO=300*1e3,rO=8,GY=["repaired","repair_failed","flapping","pending"],KY=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],oO=["rebroke_same_day","repeat_days"],aO=new Set(ie.map(e=>e.id)),Sa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),al=(e,t)=>typeof e=="string"&&t.some(n=>n===e),sO=e=>al(e,Ia),Bp=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},Io=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,ol=e=>{if(!(!Array.isArray(e)||!e.every(sO)))return $r(e)},VY=e=>{if(!Sa(e))return;let t=ol(e.checks);if(!(!Io(e.since)||!al(e.reason,oO)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},jY=e=>{if(!Sa(e))return;let t={};Bp(e.day)&&(t.day=e.day),Io(e.attempts)&&(t.attempts=e.attempts);let n=ol(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=ol(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=ol(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=ol(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Bp(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Io(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),Sa(e.lastRepaired)){let i={};for(let c of Ia){let l=e.lastRepaired[c];Io(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=VY(e.flapping);return s&&(t.flapping=s),t},YY=e=>{if(!Sa(e)||!Bp(e.day)||!Io(e.sequence)||e.sequence===0||typeof e.tool!="string"||!aO.has(e.tool)||!sO(e.checkId)||!al(e.status,GY)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!al(e.errorClass,KY))return;t=e.errorClass}else if(e.status==="flapping"){if(!al(e.errorClass,oO))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,...Io(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},eO=e=>{if(!Sa(e))return{};let t={};if(Sa(e.adapters)){let n={};for(let r of aO){let o=jY(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(YY).filter(n=>n!==void 0).slice(-tO)),Io(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Sa(e.report)&&Bp(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Io(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(-rO)}:{}}),t},ZY=e=>new Date(e).toISOString().slice(0,10),JY=(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)],Fp=(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}:{}}},sl=(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(-tO),nextSequence:r}},XY=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),zY=async e=>await Je(async()=>e)??null,qY=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=Fp(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)},iO=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:JY(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}},QY=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=Fp(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(w=>m.checks[w]==="owned"),h=p.filter(w=>{let b=m.checks[w];return b==="missing"||b==="foreign"}),g=p.filter(w=>{let b=m.checks[w];return b===void 0||b==="unreadable"}),y=iO(u,f,n,r);c[l]={...y.adapter,awaiting:g.length>0?g:void 0},i=sl(i,n,[...f.map(w=>({tool:l,checkId:w,status:"repaired"})),...h.map(w=>({tool:l,checkId:w,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?f.map(w=>({tool:l,checkId:w,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},eZ=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Fp(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(A=>!(l.brokenReportedChecks??[]).includes(A));if(y.length===0)return{result:void 0};let w=l.flapping;return c[e]={...l,brokenReportedChecks:$r([...l.brokenReportedChecks??[],...y]),flapping:{since:w?.since??a,reason:"rebroke_same_day",checks:$r([...w?.checks??[],...y])}},{next:sl({...i,adapters:c},o,y.map(A=>({tool:e,checkId:A,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:sl({...i,adapters:c},o,m.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:p,fastFlaps:m}}},void 0),tZ=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Fp(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:$r([...l.awaiting??[],...t])},{next:sl({...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=iO(l,d,o,a);c[e]=p.adapter;let m=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"apply_unconfirmed";return{next:sl({...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)},nZ=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>=nO));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??Mw)(o.map(XY),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)},rZ=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 Ia){let h=p[f];if(!h||h==="unreadable")continue;let g,y;m?.awaiting?.includes(f)&&c.has(u.id)?g="pending":h==="missing"&&m?.flapping?.checks.includes(f)?(g="flapping",y=m.flapping.reason):g=h==="owned"?"ok":h,g!=="ok"&&g!=="pending"&&(i=!0),s.push({tool:u.id,checkId:f,status:g,...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&&ot(e)&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Nn)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??$n)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=ZR(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},oZ=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<nO?{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 rZ(e,t,n,c,o,s);await(s.report??Mw)(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(-rO)}},result:void 0}:{result:void 0},void 0)},cO=async(e,t,n)=>{let r=n.now??Date.now,o=ZY(r()),a=e.managedTools??[],s={...n,readState:async()=>eO(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(eO(l)),c)};try{let i=await(s.findIntegrations??Eg)(a);await qY(i,o,s);let c=await(s.listPending??Mn)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await QY(i,l,o,r(),s);let d=await(s.resolveTarget??zY)(e),u=d?await(s.findDrifted??Ts)(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??ne)();if(d)for(let{adapter:y,checks:w}of m.values()){let b=h?Ia.filter(T=>w[T]==="missing"):[];if(b.length===0&&!p.has(y.id))continue;let A=w;if(y.integrationStatus)try{A=await y.integrationStatus()}catch{A=Object.fromEntries(Ia.map(T=>[T,"unreadable"]))}let C=b.filter(T=>A[T]==="missing"),x=p.has(y.id);if(x&&y.pointsAt&&(x=!await y.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!x)continue;let O=await eZ(y.id,C,x,l.has(y.id),o,r(),s);if(!O)continue;let[S]=await(s.repair??tn)([y],d.target);if(!S)continue;f=!0;let E;S.status==="configured"&&y.integrationStatus&&(E=await y.integrationStatus().catch(()=>{})),await tZ(y.id,O.checks,S,E,o,r(),s)}await nZ(o,r(),t,s),i=await(s.findIntegrations??Eg)(a);let g=await(s.listPending??Mn)().catch(()=>[]);return await oZ(e,i,g,o,r(),t,s),f}catch{return!1}};var uZ=14,pZ=.35,fZ=900*1e3,dO=360*60*1e3,mZ=.2,hZ=1800*1e3,uO=3600*1e3,yZ=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),gZ=300*1e3,wZ=30*1e3,bZ=900*1e3,kZ=(e=0)=>Math.min(bZ,wZ*2**Math.max(0,e)),pO=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}},fO=1440*60*1e3,CZ=300*1e3,AZ=.25,vZ=.5,mO=3600*1e3,SZ=720*60*60*1e3,IZ=360*60*1e3,EZ=1440*60*1e3,xZ=()=>bO(iZ(),".anyray"),Bw=()=>bO(xZ(),"refresh-state.json"),Fw=e=>process.env?.[e],CO=()=>Fw("ANYRAY_REFRESH_DISABLE")==="true",Uw=()=>{let e=Fw("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:uZ)*EZ},Ww=e=>{let t=Uw(),n=e?xi(e):void 0;if(!n)return t;let r=Math.max(fZ,Math.round(n*pZ));return Math.min(t,r)},RZ=e=>{let t=Fw("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(dO,Math.max(hZ,Math.round(e*mZ))):dO},Ut=async()=>{try{let e=await cZ(Bw(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Wp=async e=>{try{let t=Bw(),n=`${t}.${process.pid}.tmp`;await kO(n,JSON.stringify(e),{mode:384}),await ke(n,t),await lZ(t,384).catch(()=>{})}catch{}},OZ=3e4,_Z=()=>`${Bw()}.lock`,hO=async e=>{try{return await kO(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},kt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Ut,a=n.writeState??Wp,s=_Z(),i=!1;try{if(i=await hO(s),!i){if(await dZ(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<OZ)return t;await lO(s).catch(()=>{}),i=await hO(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await lO(s).catch(()=>{})}},Up=async(e,t={})=>{await kt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Ys=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 kt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},Ea=async(e={})=>{let t=e.now??Date.now;await kt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},TZ=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(SZ,Math.max(mO,Math.round(o*vZ))):mO},AO=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Hw=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??pe,a=n.loadProfile??N,s=n.loadDevKey??Ye,i=n.renew??UR,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(FR(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()>TZ(e))return{outcome:"not-due",profile:e};if(!await kt(g=>r()-(g.lastCertRenewAt??0)<IZ?{result:!1}:{next:{...g,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 AO(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}},yO=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*AZ):fO,r=Math.min(fO,n);return Math.min(r,CZ*2**Math.max(0,e-1))},PZ=()=>{let{command:e,args:t}=Qr(Zr);return{exe:e,args:t}},Eo=async(e={})=>{if(CO())return;let t=e.now??Date.now,n=e.readState??Ut,r=e.writeState??Wp,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=PZ();sZ(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await kt(s=>t()-(s.lastSpawnAt??0)<RZ(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},DZ=Rw,LZ=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 Ts(n,r.target.origin),a=t?Nx(o):o;return a.length===0?!1:(await tn(a,r.target),!0)}catch{return!1}},NZ=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=ie.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=Re({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}},$Z=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Ut,a=t.writeState??Wp;return cO(e,Ne,{now:r,deadWatcherObserved:n,readHookLane:()=>Hp({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>kt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Hp=async(e={})=>{let n=await(e.readState??Ut)().catch(()=>({}));return or(n.hookLane)},vO=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hp(t);if(!_w(r,e,n()))return;await kt(o=>{let a=or(o.hookLane);return _w(a,e,n())?{next:{...o,hookLane:GR(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},SO=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hp(t);if(!Tw(r,n()))return;await kt(o=>{let a=or(o.hookLane);return Tw(a,n())?{next:{...o,hookLane:KR(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},MZ=async(e={})=>{try{let t=e.now??Date.now;if((await Hp(e)).watchSince!==void 0)return;await kt(n=>{let r=or(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:VR(r,t())},result:void 0}},void 0,e)}catch{}},gO=async(e,t={})=>{try{let n=t.now??Date.now;await kt(r=>{let o=or(r.hookLane),a=jR(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},IO=async(e={})=>{try{if((await(e.readState??Ut)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>kt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??vk)())return await r()?"stamped":"skipped";let o=await(e.load??N)(),s=await(e.findTools??wa)(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??tn)(s,i.target),"repathed")}catch{return"skipped"}},EO=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Ut)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>kt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??N)(),i=await(e.findTools??wa)(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??tn)(i,c.target)).some(d=>d.status==="failed")?(await kt(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"}},BZ=async e=>{try{let t=await Pp(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 Gs(n);return i.profileUpdated||i.toolsApplied>0||a||s}catch{return!1}},wO=async(e,t,n)=>{let o=await(t.reconcilePolicy??BZ)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>LZ(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},an=async(e={})=>{if(CO())return"disabled";let t=e.now??Date.now,n=e.loadProfile??N,r=e.saveProfile??pe,o=e.loadDevKey??Ye,a=e.readState??Ut,s=e.writeState??Wp,i=e.remint??Sn,c=e.heartbeat??aR,l=e.detectSeat??Vn,d=e.rewriteTools??DZ,u=e.rewriteHookLaneTools??xw,p=e.probeHookLane??js,m=e.classifyBeacon??jl,f=e.force===!0,h=!1,g=!1,y=!1,w=!1;e.hookLaneRepair===!0&&(f=!0,w=!0);let b=async C=>{if(!w){C==="repaired"&&await gO("none",{now:t,readState:a,writeState:s});return}let x=C;if(C==="repaired"){let O=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));x=O.verdict==="live"?"repaired":O.verdict==="dark"?"repair_failed":"unverified"}await gO(x,{now:t,readState:a,writeState:s})},A=async()=>{if(!e.runAmbientSelfcheck||g||!h)return!1;g=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(O=>$Z(O,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await Mn().then(U=>U.some(Q=>!$n(Q.watcherPid))).catch(()=>!1),await MZ({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??CA)();let C=await n();if(h=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let x=C.gateway,O=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(O)||O<=t())return"cert-expired";let S=await o();if(!S)return"not-enrolled";let E=(e.resolveMachineUuid??on)()||void 0,T=await Hw(C,S,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=T.profile;let I=T.outcome==="renewed",K=C.enrolledCert;if(!K)return"not-enrolled";let G=Date.parse(C.clientKeyExpiresAt??""),X=Number.isFinite(G)?G-t():0,ae=await a(),Ae=!C.clientKey||X<=Ww(C);if(!f&&YR(or(ae.hookLane),t())&&await m().catch(()=>"unreadable")!=="foreign"&&(f=!0,w=!0),C.clientKey&&(f||Ae)){let U=await kt(Q=>{let ye=t()-(Q.lastAttemptAt??0);return ye<uO?{result:"throttled"}:Q.failureCount&&ye<yO(Q.failureCount,Q.keyTtlMs)?{result:"backoff"}:{next:{...Q,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(U!=="ok")return U;try{let Q=await c(x,C.clientKey,K,S,{machineUuid:E}),ye=await n().catch(()=>C);return ye.clientKey!==C.clientKey||ye.enrolledCert?.sig!==K.sig?"failed":(await r({...ye,clientKeyExpiresAt:Q.expiresAt}),await Up(({lastError:we,...Y})=>({...Y,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:xi(C)??Y.keyTtlMs}),{now:t,readState:a,writeState:s}),w?await b(await NZ(C,x,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Q){let ye=pO(Q);return await Up(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 Bs&&Q.policyCode==="managed_device_required"&&console.error(Q.message),Q instanceof Bs?Q.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!f&&C.clientKey&&!Ae){let U=await wO(C,e,n),Q=await A();return U||Q?"repaired":I?"cert-renewed":"not-due"}let me=await kt(U=>{let Q=t()-(U.lastAttemptAt??0);if(f)return Q<kZ(U.failureCount)?{result:"throttled"}:{next:{...U,lastAttemptAt:t()},result:"ok"};let ye=U.lastError?.code!==void 0&&yZ.has(U.lastError.code)?gZ:uO;return Q<ye?{result:"throttled"}:U.failureCount&&Q<yO(U.failureCount,U.keyTtlMs)?{result:"backoff"}:{next:{...U,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(me!=="ok")return me;try{let U=await i(x,K,S,{machineUuid:E}),Q=await l().catch(()=>{}),ye=Re({origin:x,clientKey:U.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Q,user:C.name,team:C.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(()=>C),Ie=null;Y.enrolledCert&&await AO(Y,K.sig,S,o)&&(Ie={...Y,clientKey:U.key,clientKeyExpiresAt:U.expiresAt??Y.clientKeyExpiresAt},await r(Ie));let cn=U.expiresAt?Date.parse(U.expiresAt):NaN,Fr=xi(C)??(Number.isFinite(cn)&&cn-t()>0?cn-t():void 0);return await Up(({lastError:Ur,...Wr})=>({...Wr,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Fr??Wr.keyTtlMs}),{now:t,readState:a,writeState:s}),Ie&&await wO(Ie,e,n),await b(Ie?"repaired":"repair_failed"),await A(),"refreshed"}catch(U){let Q=pO(U);return await Up(ye=>({...ye,lastAttemptAt:t(),failureCount:(ye.failureCount??0)+1,lastError:{name:U instanceof Error?U.name:"Error",...Q!==void 0?{code:Q}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),U instanceof ct&&U.policyCode==="managed_device_required"&&console.error(U.message),U instanceof ct?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await A()}catch{}}};var FZ=`anyray-connect print-key [--json | --passthrough-headers]
|
|
581
|
+
`,cY=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}},lY=(e,t)=>{let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>e[r]===t[r])},Iw=async(e,t={})=>{let n=t.loadProfile??L,r=BR(t,n),o=t.adapters??ie,a=await n(),s=await cY(e.marketplace,a.managedTools,o),i=eY(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 sY(c.length===0?{...e,skills:[]}:e,i,l,{staleDirs:u});if(p.changed>0||p.removed.length>0||p.cleanedDirs.length>0||!lY(l,p.versions)||!dY(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}},BR=(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}:yi},dY=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),Ew=async(e,t={})=>{let n=t.loadProfile??L,r=await n(),o=t.adapters??ie,a=e.mcp?.org.url&&r.clientKey?{url:e.mcp.org.url,clientKey:r.clientKey}:void 0,s=a!==void 0,i=[],c=yC(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 pY(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 BR(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,uY)},result:void 0}})}catch{}return{changed:i,served:s}},uY=8,Pp=async(e,t={})=>{if(!e.gateway||!e.clientKey)return;let n=await(t.fetchTeamPolicy??Hs)(e.gateway,e.clientKey),r=await(t.syncSkills??Iw)(n).catch(()=>{}),o=await(t.syncOrgMcp??Ew)(n).catch(()=>{});return{policy:n,skills:r,mcp:o}},pY=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 fY}from"node:crypto";var mY=1e4,hY="machine:",FR=e=>e.startsWith(hY),yY="cert-renew",gY=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)},UR=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??vn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:fY(16).toString("hex"),purpose:yY},c;try{c=await(n.signer??rr)(Aa(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),mY),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 gY(m)?{ok:!0,cert:m}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var xw=async(e,t=e.origin,n=ie)=>{let r=0,o=0,a=!0;for(let s of n)try{if(!s.pointsAt||!await s.pointsAt(t)||await s.usesDynamicCredential?.(t))continue;r+=1,(await s.apply(e,{dryRun:!1})).status==="configured"?o+=1:a=!1}catch{a=!1}return{matched:r,rewritten:o,complete:a}},Rw=async(e,t=e.origin,n=ie)=>(await xw(e,t,n)).complete;var wY=["claude","codex","cursor","opencode"],bY=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],kY=new Set(["missing_key","key_expired"]);var CY=600*1e3,AY=600*1e3,WR=1440*60*1e3,vY=1440*60*1e3,SY=10080*60*1e3,IY=3600*1e3,EY=720*60*1e3,xY=e=>Math.min(EY,IY*2**Math.max(0,e-1)),rl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ks=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,HR=e=>typeof e=="string"&&bY.includes(e),or=e=>{if(!rl(e))return{};let t={};if(Ks(e.watchSince)&&(t.watchSince=e.watchSince),rl(e.invoked)){let n={};for(let r of wY){let o=e.invoked[r];Ks(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return rl(e.authFailure)&&Ks(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...HR(e.authFailure.code)?{code:e.authFailure.code}:{}}),rl(e.repair)&&Ks(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,...Ks(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Dp=e=>{try{let n=JSON.parse(e);if(rl(n)&&HR(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"},Ow=e=>e!==void 0&&kY.has(e),_w=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=CY},GR=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),Tw=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=AY},KR=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),VR=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,jR=(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},YR=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>WR||!Ow(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<xY(r.failures??1))},Np=e=>{let t=Object.values(e?.invoked??{}).filter(Ks);return t.length>0?Math.max(...t):null},Pw=(e,t)=>{if(Np(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=SY},ZR=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=vY)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=WR)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var Dw="x-anyray-retrieve-probe",Lp=8e3,RY=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Nw=e=>{try{let t=e?.name;if(typeof t=="string"&&/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(t))return t}catch{}return"Error"},JR=e=>Nw(e)==="AbortError",XR=(e,t)=>{let n=fn(e);return t?.probe&&(n[Dw]="1"),n},Vs=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(),Lp);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:XR(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=RY(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=JR(a);return{ok:!1,kind:s?"timeout":"network",message:s?"Retrieval timed out.":`Retrieval failed to reach the gateway (${Nw(a)}).`}}finally{clearTimeout(o)}},$p=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(),Lp);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:XR(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=JR(s);return{ok:!1,kind:i?"timeout":"network",message:i?"Recall timed out.":`Recall failed to reach the gateway (${Nw(s)}).`}}finally{clearTimeout(a)}};var OY=5e3,_Y=2048,TY=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}"`))},js=async(e={})=>{let t=e.readTarget??pt,n=e.fetch??fetch,r=e.timeoutMs??OY,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=fn(o);i["content-type"]="application/json",i[Dw]="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,_Y);if(!TY(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let p=Dp(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)}},Lw=(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 NY}from"node:crypto";import{execSync as $w}from"node:child_process";import{hostname as PY}from"node:os";var DY=e=>{try{if(e==="darwin"){let t=$w("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=$w('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 $w("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Mp=(e={platform:process.platform,read:()=>DY(process.platform),hostname:PY})=>e.read().trim()||e.hostname().trim();var on=(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??(()=>Mp());try{return r().trim().toLowerCase()}catch{return""}}return""};var LY=500,zR=2e3,$Y=2e3,MY=250,qR=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),LY);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)}},BY=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},FY=e=>new Promise(t=>setTimeout(t,e)),UY=async(e,t,n=FY)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),zR),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=BY(i)??MY,s>$Y))return!1}finally{clearTimeout(a)}await n(s)}},WY=async(e,t={})=>{try{let r=(await(t.loadProfile??L)()).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:NY(16).toString("hex"),events:e},i;try{i=await(t.signer??rr)(Aa(s),o)}catch{return!1}return await(t.post??UY)(`${t.origin??vn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},HY=async(e,t,n={})=>{try{let o=(await(n.loadProfile??L)()).enrolledCert,a=await(n.loadDevKey??Ye)();if(!o||!a)return;await(n.verify??Sn)(e,o,a,{timeoutMs:zR,machineUuid:(n.machineUuid??on)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},QR=async(e,t)=>{if(e.length!==0)try{let n=await pt(),r=n&&await qR(n.origin,fn(n),e,t);if(n&&await HY(n.origin,e),r)return;await WY(e)}catch{}},Mw=async(e,t,n={readTarget:()=>pt("profile"),post:qR})=>{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 Ia=["hook_registration","mcp_registration","hook_binary","beacon_target"];var tO=128,nO=300*1e3,rO=8,GY=["repaired","repair_failed","flapping","pending"],KY=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],oO=["rebroke_same_day","repeat_days"],aO=new Set(ie.map(e=>e.id)),Sa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),al=(e,t)=>typeof e=="string"&&t.some(n=>n===e),sO=e=>al(e,Ia),Bp=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},Io=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,ol=e=>{if(!(!Array.isArray(e)||!e.every(sO)))return $r(e)},VY=e=>{if(!Sa(e))return;let t=ol(e.checks);if(!(!Io(e.since)||!al(e.reason,oO)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},jY=e=>{if(!Sa(e))return;let t={};Bp(e.day)&&(t.day=e.day),Io(e.attempts)&&(t.attempts=e.attempts);let n=ol(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=ol(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=ol(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=ol(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Bp(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Io(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),Sa(e.lastRepaired)){let i={};for(let c of Ia){let l=e.lastRepaired[c];Io(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=VY(e.flapping);return s&&(t.flapping=s),t},YY=e=>{if(!Sa(e)||!Bp(e.day)||!Io(e.sequence)||e.sequence===0||typeof e.tool!="string"||!aO.has(e.tool)||!sO(e.checkId)||!al(e.status,GY)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!al(e.errorClass,KY))return;t=e.errorClass}else if(e.status==="flapping"){if(!al(e.errorClass,oO))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,...Io(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},eO=e=>{if(!Sa(e))return{};let t={};if(Sa(e.adapters)){let n={};for(let r of aO){let o=jY(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(YY).filter(n=>n!==void 0).slice(-tO)),Io(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Sa(e.report)&&Bp(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Io(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(-rO)}:{}}),t},ZY=e=>new Date(e).toISOString().slice(0,10),JY=(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)],Fp=(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}:{}}},sl=(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(-tO),nextSequence:r}},XY=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),zY=async e=>await Je(async()=>e)??null,qY=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=Fp(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)},iO=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:JY(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}},QY=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=Fp(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(w=>m.checks[w]==="owned"),h=p.filter(w=>{let b=m.checks[w];return b==="missing"||b==="foreign"}),g=p.filter(w=>{let b=m.checks[w];return b===void 0||b==="unreadable"}),y=iO(u,f,n,r);c[l]={...y.adapter,awaiting:g.length>0?g:void 0},i=sl(i,n,[...f.map(w=>({tool:l,checkId:w,status:"repaired"})),...h.map(w=>({tool:l,checkId:w,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?f.map(w=>({tool:l,checkId:w,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},eZ=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Fp(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(A=>!(l.brokenReportedChecks??[]).includes(A));if(y.length===0)return{result:void 0};let w=l.flapping;return c[e]={...l,brokenReportedChecks:$r([...l.brokenReportedChecks??[],...y]),flapping:{since:w?.since??a,reason:"rebroke_same_day",checks:$r([...w?.checks??[],...y])}},{next:sl({...i,adapters:c},o,y.map(A=>({tool:e,checkId:A,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:sl({...i,adapters:c},o,m.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:p,fastFlaps:m}}},void 0),tZ=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Fp(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:$r([...l.awaiting??[],...t])},{next:sl({...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=iO(l,d,o,a);c[e]=p.adapter;let m=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"apply_unconfirmed";return{next:sl({...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)},nZ=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>=nO));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??Mw)(o.map(XY),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)},rZ=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 Ia){let h=p[f];if(!h||h==="unreadable")continue;let g,y;m?.awaiting?.includes(f)&&c.has(u.id)?g="pending":h==="missing"&&m?.flapping?.checks.includes(f)?(g="flapping",y=m.flapping.reason):g=h==="owned"?"ok":h,g!=="ok"&&g!=="pending"&&(i=!0),s.push({tool:u.id,checkId:f,status:g,...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&&ot(e)&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Ln)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??$n)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=ZR(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},oZ=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<nO?{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 rZ(e,t,n,c,o,s);await(s.report??Mw)(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(-rO)}},result:void 0}:{result:void 0},void 0)},cO=async(e,t,n)=>{let r=n.now??Date.now,o=ZY(r()),a=e.managedTools??[],s={...n,readState:async()=>eO(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(eO(l)),c)};try{let i=await(s.findIntegrations??Eg)(a);await qY(i,o,s);let c=await(s.listPending??Mn)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await QY(i,l,o,r(),s);let d=await(s.resolveTarget??zY)(e),u=d?await(s.findDrifted??Ts)(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??ne)();if(d)for(let{adapter:y,checks:w}of m.values()){let b=h?Ia.filter(T=>w[T]==="missing"):[];if(b.length===0&&!p.has(y.id))continue;let A=w;if(y.integrationStatus)try{A=await y.integrationStatus()}catch{A=Object.fromEntries(Ia.map(T=>[T,"unreadable"]))}let C=b.filter(T=>A[T]==="missing"),x=p.has(y.id);if(x&&y.pointsAt&&(x=!await y.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!x)continue;let O=await eZ(y.id,C,x,l.has(y.id),o,r(),s);if(!O)continue;let[S]=await(s.repair??tn)([y],d.target);if(!S)continue;f=!0;let E;S.status==="configured"&&y.integrationStatus&&(E=await y.integrationStatus().catch(()=>{})),await tZ(y.id,O.checks,S,E,o,r(),s)}await nZ(o,r(),t,s),i=await(s.findIntegrations??Eg)(a);let g=await(s.listPending??Mn)().catch(()=>[]);return await oZ(e,i,g,o,r(),t,s),f}catch{return!1}};var uZ=14,pZ=.35,fZ=900*1e3,dO=360*60*1e3,mZ=.2,hZ=1800*1e3,uO=3600*1e3,yZ=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),gZ=300*1e3,wZ=30*1e3,bZ=900*1e3,kZ=(e=0)=>Math.min(bZ,wZ*2**Math.max(0,e)),pO=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}},fO=1440*60*1e3,CZ=300*1e3,AZ=.25,vZ=.5,mO=3600*1e3,SZ=720*60*60*1e3,IZ=360*60*1e3,EZ=1440*60*1e3,xZ=()=>bO(iZ(),".anyray"),Bw=()=>bO(xZ(),"refresh-state.json"),Fw=e=>process.env?.[e],CO=()=>Fw("ANYRAY_REFRESH_DISABLE")==="true",Uw=()=>{let e=Fw("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:uZ)*EZ},Ww=e=>{let t=Uw(),n=e?xi(e):void 0;if(!n)return t;let r=Math.max(fZ,Math.round(n*pZ));return Math.min(t,r)},RZ=e=>{let t=Fw("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(dO,Math.max(hZ,Math.round(e*mZ))):dO},Ut=async()=>{try{let e=await cZ(Bw(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Wp=async e=>{try{let t=Bw(),n=`${t}.${process.pid}.tmp`;await kO(n,JSON.stringify(e),{mode:384}),await ke(n,t),await lZ(t,384).catch(()=>{})}catch{}},OZ=3e4,_Z=()=>`${Bw()}.lock`,hO=async e=>{try{return await kO(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},kt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Ut,a=n.writeState??Wp,s=_Z(),i=!1;try{if(i=await hO(s),!i){if(await dZ(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<OZ)return t;await lO(s).catch(()=>{}),i=await hO(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await lO(s).catch(()=>{})}},Up=async(e,t={})=>{await kt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Ys=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 kt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},Ea=async(e={})=>{let t=e.now??Date.now;await kt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},TZ=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(SZ,Math.max(mO,Math.round(o*vZ))):mO},AO=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Hw=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??pe,a=n.loadProfile??L,s=n.loadDevKey??Ye,i=n.renew??UR,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(FR(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()>TZ(e))return{outcome:"not-due",profile:e};if(!await kt(g=>r()-(g.lastCertRenewAt??0)<IZ?{result:!1}:{next:{...g,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 AO(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}},yO=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*AZ):fO,r=Math.min(fO,n);return Math.min(r,CZ*2**Math.max(0,e-1))},PZ=()=>{let{command:e,args:t}=Qr(Zr);return{exe:e,args:t}},Eo=async(e={})=>{if(CO())return;let t=e.now??Date.now,n=e.readState??Ut,r=e.writeState??Wp,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=PZ();sZ(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await kt(s=>t()-(s.lastSpawnAt??0)<RZ(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},DZ=Rw,NZ=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 Ts(n,r.target.origin),a=t?Lx(o):o;return a.length===0?!1:(await tn(a,r.target),!0)}catch{return!1}},LZ=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=ie.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=Re({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}},$Z=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Ut,a=t.writeState??Wp;return cO(e,Le,{now:r,deadWatcherObserved:n,readHookLane:()=>Hp({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>kt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Hp=async(e={})=>{let n=await(e.readState??Ut)().catch(()=>({}));return or(n.hookLane)},vO=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hp(t);if(!_w(r,e,n()))return;await kt(o=>{let a=or(o.hookLane);return _w(a,e,n())?{next:{...o,hookLane:GR(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},SO=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hp(t);if(!Tw(r,n()))return;await kt(o=>{let a=or(o.hookLane);return Tw(a,n())?{next:{...o,hookLane:KR(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},MZ=async(e={})=>{try{let t=e.now??Date.now;if((await Hp(e)).watchSince!==void 0)return;await kt(n=>{let r=or(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:VR(r,t())},result:void 0}},void 0,e)}catch{}},gO=async(e,t={})=>{try{let n=t.now??Date.now;await kt(r=>{let o=or(r.hookLane),a=jR(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},IO=async(e={})=>{try{if((await(e.readState??Ut)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>kt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??vk)())return await r()?"stamped":"skipped";let o=await(e.load??L)(),s=await(e.findTools??wa)(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??tn)(s,i.target),"repathed")}catch{return"skipped"}},EO=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Ut)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>kt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??L)(),i=await(e.findTools??wa)(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??tn)(i,c.target)).some(d=>d.status==="failed")?(await kt(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"}},BZ=async e=>{try{let t=await Pp(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 Gs(n);return i.profileUpdated||i.toolsApplied>0||a||s}catch{return!1}},wO=async(e,t,n)=>{let o=await(t.reconcilePolicy??BZ)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>NZ(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},an=async(e={})=>{if(CO())return"disabled";let t=e.now??Date.now,n=e.loadProfile??L,r=e.saveProfile??pe,o=e.loadDevKey??Ye,a=e.readState??Ut,s=e.writeState??Wp,i=e.remint??Sn,c=e.heartbeat??aR,l=e.detectSeat??Vn,d=e.rewriteTools??DZ,u=e.rewriteHookLaneTools??xw,p=e.probeHookLane??js,m=e.classifyBeacon??jl,f=e.force===!0,h=!1,g=!1,y=!1,w=!1;e.hookLaneRepair===!0&&(f=!0,w=!0);let b=async C=>{if(!w){C==="repaired"&&await gO("none",{now:t,readState:a,writeState:s});return}let x=C;if(C==="repaired"){let O=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));x=O.verdict==="live"?"repaired":O.verdict==="dark"?"repair_failed":"unverified"}await gO(x,{now:t,readState:a,writeState:s})},A=async()=>{if(!e.runAmbientSelfcheck||g||!h)return!1;g=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(O=>$Z(O,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await Mn().then(U=>U.some(Q=>!$n(Q.watcherPid))).catch(()=>!1),await MZ({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??CA)();let C=await n();if(h=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let x=C.gateway,O=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(O)||O<=t())return"cert-expired";let S=await o();if(!S)return"not-enrolled";let E=(e.resolveMachineUuid??on)()||void 0,T=await Hw(C,S,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=T.profile;let I=T.outcome==="renewed",K=C.enrolledCert;if(!K)return"not-enrolled";let G=Date.parse(C.clientKeyExpiresAt??""),X=Number.isFinite(G)?G-t():0,ae=await a(),Ae=!C.clientKey||X<=Ww(C);if(!f&&YR(or(ae.hookLane),t())&&await m().catch(()=>"unreadable")!=="foreign"&&(f=!0,w=!0),C.clientKey&&(f||Ae)){let U=await kt(Q=>{let ye=t()-(Q.lastAttemptAt??0);return ye<uO?{result:"throttled"}:Q.failureCount&&ye<yO(Q.failureCount,Q.keyTtlMs)?{result:"backoff"}:{next:{...Q,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(U!=="ok")return U;try{let Q=await c(x,C.clientKey,K,S,{machineUuid:E}),ye=await n().catch(()=>C);return ye.clientKey!==C.clientKey||ye.enrolledCert?.sig!==K.sig?"failed":(await r({...ye,clientKeyExpiresAt:Q.expiresAt}),await Up(({lastError:we,...Y})=>({...Y,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:xi(C)??Y.keyTtlMs}),{now:t,readState:a,writeState:s}),w?await b(await LZ(C,x,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Q){let ye=pO(Q);return await Up(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 Bs&&Q.policyCode==="managed_device_required"&&console.error(Q.message),Q instanceof Bs?Q.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!f&&C.clientKey&&!Ae){let U=await wO(C,e,n),Q=await A();return U||Q?"repaired":I?"cert-renewed":"not-due"}let me=await kt(U=>{let Q=t()-(U.lastAttemptAt??0);if(f)return Q<kZ(U.failureCount)?{result:"throttled"}:{next:{...U,lastAttemptAt:t()},result:"ok"};let ye=U.lastError?.code!==void 0&&yZ.has(U.lastError.code)?gZ:uO;return Q<ye?{result:"throttled"}:U.failureCount&&Q<yO(U.failureCount,U.keyTtlMs)?{result:"backoff"}:{next:{...U,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(me!=="ok")return me;try{let U=await i(x,K,S,{machineUuid:E}),Q=await l().catch(()=>{}),ye=Re({origin:x,clientKey:U.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Q,user:C.name,team:C.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(()=>C),Ie=null;Y.enrolledCert&&await AO(Y,K.sig,S,o)&&(Ie={...Y,clientKey:U.key,clientKeyExpiresAt:U.expiresAt??Y.clientKeyExpiresAt},await r(Ie));let cn=U.expiresAt?Date.parse(U.expiresAt):NaN,Fr=xi(C)??(Number.isFinite(cn)&&cn-t()>0?cn-t():void 0);return await Up(({lastError:Ur,...Wr})=>({...Wr,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Fr??Wr.keyTtlMs}),{now:t,readState:a,writeState:s}),Ie&&await wO(Ie,e,n),await b(Ie?"repaired":"repair_failed"),await A(),"refreshed"}catch(U){let Q=pO(U);return await Up(ye=>({...ye,lastAttemptAt:t(),failureCount:(ye.failureCount??0)+1,lastError:{name:U instanceof Error?U.name:"Error",...Q!==void 0?{code:Q}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),U instanceof ct&&U.policyCode==="managed_device_required"&&console.error(U.message),U instanceof ct?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await A()}catch{}}};var FZ=`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
|
|
|
@@ -590,7 +590,7 @@ Options:
|
|
|
590
590
|
"x-anyray-provider":"anthropic","x-anyray-metadata":"..."}).
|
|
591
591
|
Carries the client key, never the seat OAuth token.
|
|
592
592
|
--help Show this help.
|
|
593
|
-
`,UZ=e=>{let t=!1,n=!1,r=!1;for(let o of e)if(o==="--json")t=!0;else if(o==="--passthrough-headers")n=!0;else if(o==="--help"||o==="-h")r=!0;else throw new Error(`Unknown option: ${o}`);if(t&&n)throw new Error("Use only one of --json or --passthrough-headers.");return{json:t,passthroughHeaders:n,help:r}},WZ=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Ww(e):!0},xO=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},RO=(e,t)=>{if(!Pe(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},Gw=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,HZ=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Gw(t)}\`.`:"Enrollment certificate expired. Re-run `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"cert-rejected":return t.ssoLink?`Your SSO reconnect credential is no longer valid. Reconnect with \`${Gw(t)}\`.`:"Your enrollment certificate is no longer valid. Reconnect with `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"gateway-incompatible":return"The gateway key-renewal route is unavailable (HTTP 404). Check the deployment version and routing; your enrollment certificate was not rejected.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${Gw(t)}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.";case"disabled":return"Automatic key refresh is disabled.";case"backoff":case"throttled":return"Key refresh is temporarily unavailable; retry shortly.";case"not-due":case"repaired":case"cert-renewed":case"heartbeat-refreshed":case"refreshed":return""}},il=async(e={})=>{let t=e.loadProfile??
|
|
593
|
+
`,UZ=e=>{let t=!1,n=!1,r=!1;for(let o of e)if(o==="--json")t=!0;else if(o==="--passthrough-headers")n=!0;else if(o==="--help"||o==="-h")r=!0;else throw new Error(`Unknown option: ${o}`);if(t&&n)throw new Error("Use only one of --json or --passthrough-headers.");return{json:t,passthroughHeaders:n,help:r}},WZ=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Ww(e):!0},xO=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},RO=(e,t)=>{if(!Pe(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},Gw=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,HZ=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Gw(t)}\`.`:"Enrollment certificate expired. Re-run `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"cert-rejected":return t.ssoLink?`Your SSO reconnect credential is no longer valid. Reconnect with \`${Gw(t)}\`.`:"Your enrollment certificate is no longer valid. Reconnect with `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"gateway-incompatible":return"The gateway key-renewal route is unavailable (HTTP 404). Check the deployment version and routing; your enrollment certificate was not rejected.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${Gw(t)}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.";case"disabled":return"Automatic key refresh is disabled.";case"backoff":case"throttled":return"Key refresh is temporarily unavailable; retry shortly.";case"not-due":case"repaired":case"cert-renewed":case"heartbeat-refreshed":case"refreshed":return""}},il=async(e={})=>{let t=e.loadProfile??L,n=e.refreshIfDue??an,r=e.now??Date.now,o=await t();if(xO(o),!o.enrolledCert){if(!RO(o,r))throw new Error("No valid Anyray client key is stored. Set ANYRAY_CLIENT_KEY to a minted ark_ key or enroll this machine.");return{profile:o,token:o.clientKey}}let a;if(!o.clientKey||WZ(o,r)){let i=HZ(await n(),o);if(i){if(!RO(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(xO(s),!Pe(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},OO=e=>be({user:e.name,team:e.team}),Gp=({profile:e,token:t})=>{let n={},r=OO(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Kw=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=OO(e);return r&&(n["x-anyray-metadata"]=r),n},GZ=e=>JSON.stringify(Kw(e)),_O=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=UZ(e);if(o.help)return n.write(FZ),0;let a=await il(t);a.warning&&r.write(`${a.warning}
|
|
594
594
|
`);let s=o.passthroughHeaders?GZ(a):o.json?Gp(a):a.token;return n.write(`${s}
|
|
595
595
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
596
596
|
`),1}};var KZ=`anyray-connect retrieve <handle> [--source auto|claude|profile]
|
|
@@ -623,7 +623,7 @@ Options:
|
|
|
623
623
|
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${jZ(c.preview)}
|
|
624
624
|
`)}return r.write(`Fetch a full original: anyray-connect retrieve <handle>
|
|
625
625
|
`),0}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
626
|
-
`),1}};var
|
|
626
|
+
`),1}};var NO=`anyray-connect update [--check] [--auto on|off] [--json]
|
|
627
627
|
|
|
628
628
|
Keep this machine's anyray-connect binary on the published release. Runs
|
|
629
629
|
automatically about every 30 minutes; this command forces it now.
|
|
@@ -634,12 +634,12 @@ Options:
|
|
|
634
634
|
Off still accepts a release the Anyray team marks mandatory.
|
|
635
635
|
--json Emit the result as JSON.
|
|
636
636
|
--help Show this help.
|
|
637
|
-
`,YZ=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},ZZ=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"sidecar":return"This engine is part of the Anyray Connect desktop app, which updates itself. Nothing to do here.";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}.`}},
|
|
637
|
+
`,YZ=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},ZZ=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"sidecar":return"This engine is part of the Anyray Connect desktop app, which updates itself. Nothing to do here.";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}.`}},LO=async(e,t={})=>{let n;try{n=YZ(e)}catch(a){return D(a.message),process.stderr.write(NO),1}if(n.help)return process.stdout.write(NO),0;if(n.auto!==void 0){let a=await L();if(a.autoUpdate!==!1!==n.auto&&await pe({...a,autoUpdate:n.auto}),n.json||(B(`Automatic updates ${n.auto?"enabled":"disabled"}.`),n.auto||k("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!n.auto)return n.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
|
|
638
638
|
`),0}let r=await(t.runSelfUpdate??Ps)({checkOnly:n.check,force:!n.check,allowNpmMigration:!0,initiator:"human"});if(n.json){let a=await(t.selfUpdateStatus??Ca)();return process.stdout.write(`${JSON.stringify({...r,autoUpdate:a.autoUpdate,path:a.path,selfUpdateAvailable:a.available,selfUpdateState:a.state,fleetUpdateMode:a.fleetMode},null,2)}
|
|
639
|
-
`),r.outcome==="failed"?1:0}let o=ZZ(r);switch(r.outcome){case"updated":case"migrated":B(o);break;case"current":B(o);break;case"available":case"migration-available":k(o),n.check&&k(`Run ${Z("anyray-connect update")} to install it.`);break;case"migration-deferred":P(o),k(v("Use the newer npm runtime until that standalone release is published."));break;case"disabled":P(o),k(`Run ${Z("anyray-connect update")} to install it now, or ${Z("--auto on")} to resume.`);break;case"fleet-directed":case"fleet-off":k(o),k(v("Ask your Anyray administrator if you need a newer version."));break;case"sidecar":k(o);break;case"unmanaged":k(o),k(v("A copy your IT team placed is theirs to roll."));break;case"container":k(o);break;case"platform-unsupported":P(o),k(v("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":P(o);break;case"failed":return D(o),1}return 0};var cl=e=>!e.some(t=>t==="--dry-run"||t==="--revert"||t==="--project"),xo=()=>!1,JZ=new Map([["managed",{run:OR,persistsRuntime:e=>e.includes("--write")&&!e.includes("--revert")}],["endpoint",{run:E0,persistsRuntime:xo}],["print-key",{run:_O,persistsRuntime:xo}],["models",{run:
|
|
640
|
-
`,{mode:384}),await zZ(n,384),await ke(n,t)}catch(r){throw await MO(n,{force:!0}).catch(()=>{}),r}},Kp=async()=>{await MO(jw(),{force:!0}).catch(()=>{})},sJ=()=>XZ(32).toString("base64url"),iJ=e=>e instanceof Error?e.name:"UnknownError",FO=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??
|
|
639
|
+
`),r.outcome==="failed"?1:0}let o=ZZ(r);switch(r.outcome){case"updated":case"migrated":B(o);break;case"current":B(o);break;case"available":case"migration-available":k(o),n.check&&k(`Run ${Z("anyray-connect update")} to install it.`);break;case"migration-deferred":P(o),k(v("Use the newer npm runtime until that standalone release is published."));break;case"disabled":P(o),k(`Run ${Z("anyray-connect update")} to install it now, or ${Z("--auto on")} to resume.`);break;case"fleet-directed":case"fleet-off":k(o),k(v("Ask your Anyray administrator if you need a newer version."));break;case"sidecar":k(o);break;case"unmanaged":k(o),k(v("A copy your IT team placed is theirs to roll."));break;case"container":k(o);break;case"platform-unsupported":P(o),k(v("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":P(o);break;case"failed":return D(o),1}return 0};var cl=e=>!e.some(t=>t==="--dry-run"||t==="--revert"||t==="--project"),xo=()=>!1,JZ=new Map([["managed",{run:OR,persistsRuntime:e=>e.includes("--write")&&!e.includes("--revert")}],["endpoint",{run:E0,persistsRuntime:xo}],["print-key",{run:_O,persistsRuntime:xo}],["models",{run:Nx,persistsRuntime:e=>cl(e)&&e.some(t=>!t.startsWith("-"))}],["copilot-login",{run:Px,persistsRuntime:cl}],["retrieve",{run:PO,persistsRuntime:xo}],["recall",{run:DO,persistsRuntime:xo}],["history",{run:U0,persistsRuntime:xo}],["migrate",{run:TR,persistsRuntime:xo}],["login",{run:H0,persistsRuntime:cl}],["update",{run:LO,persistsRuntime:xo}],["connectors",{run:Tx,persistsRuntime:xo}]]),Vw=e=>e===void 0?void 0:JZ.get(e);import{randomBytes as XZ}from"node:crypto";import{chmod as zZ,readFile as qZ,rm as MO,writeFile as QZ}from"node:fs/promises";import{join as eJ}from"node:path";var tJ=/^[A-Za-z0-9_-]{43}$/,$O=3900,nJ=1e4,jw=()=>eJ(ee(),"device-token.json"),rJ=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&tJ.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},BO=async()=>{try{let e=JSON.parse(await qZ(jw(),"utf-8"));return rJ(e)?e:null}catch{return null}},oJ=0,aJ=async e=>{await Xe();let t=jw(),n=`${t}.${process.pid}.${oJ++}.tmp`;try{await QZ(n,`${JSON.stringify(e)}
|
|
640
|
+
`,{mode:384}),await zZ(n,384),await ke(n,t)}catch(r){throw await MO(n,{force:!0}).catch(()=>{}),r}},Kp=async()=>{await MO(jw(),{force:!0}).catch(()=>{})},sJ=()=>XZ(32).toString("base64url"),iJ=e=>e instanceof Error?e.name:"UnknownError",FO=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??L)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=sJ(),i=new AbortController,c=setTimeout(()=>i.abort(),nJ),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:$O}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await aJ({v:1,token:s,expiresAt:t()+$O*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${iJ(r)}`),!1}};var UO=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??L)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=e.readState??BO,i=await s();return(!i||i.expiresAt<=r())&&(await(e.rotateToken??FO)(),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 WO,dirname as cJ}from"node:path";import{mkdir as lJ,readFile as Zw,rm as HO,writeFile as GO}from"node:fs/promises";var Yw=["claude-code","codex"],dJ="anyray-connect print-key",Jw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),uJ=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:pi,authMode:"placeholder",metadata:{}}),Xw=e=>WO(e,".claude","settings.json"),pJ=async(e,t,n)=>{let r=Xw(e),o=await F(r),{env:a}=Tn(t,{includeAuthToken:!1,includeClientKey:!1}),s=Jw(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Uo(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=dJ,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]}},KO=async(e=process.cwd())=>{let t=[],n=Xw(e);try{if(await R(n)){let o=await F(n),a=Jw(o.env)?o.env:{};(Fo.some(s=>s in a)||Uo(o))&&t.push(n)}}catch{}let r=zw(e);try{if(await R(r)){let o=await Zw(r,"utf-8");dd(o)&&t.push(r)}}catch{}return t},fJ=async(e,t)=>{let n=Xw(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await F(n),o=!1;if(Jw(r.env)){let s={...r.env};for(let i of Fo)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Uo(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 HO(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]}},zw=e=>WO(e,".codex","config.toml"),mJ=async(e,t,n)=>{let r=zw(e),o=await Zw(r,"utf-8").catch(()=>""),a=fd(o,Ti(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await lJ(cJ(r),{recursive:!0}),await GO(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]}},hJ=async(e,t)=>{let n=zw(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Zw(n,"utf-8"),o=md(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await HO(n,{force:!0}):await GO(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},VO=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Yw],r=n.filter(s=>!Yw.includes(s));if(r.length>0)return D(`--project supports ${Yw.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
|
|
642
|
+
`),0)};import{join as WO,dirname as cJ}from"node:path";import{mkdir as lJ,readFile as Zw,rm as HO,writeFile as GO}from"node:fs/promises";var Yw=["claude-code","codex"],dJ="anyray-connect print-key",Jw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),uJ=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:pi,authMode:"placeholder",metadata:{}}),Xw=e=>WO(e,".claude","settings.json"),pJ=async(e,t,n)=>{let r=Xw(e),o=await F(r),{env:a}=Tn(t,{includeAuthToken:!1,includeClientKey:!1}),s=Jw(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Uo(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=dJ,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]}},KO=async(e=process.cwd())=>{let t=[],n=Xw(e);try{if(await R(n)){let o=await F(n),a=Jw(o.env)?o.env:{};(Fo.some(s=>s in a)||Uo(o))&&t.push(n)}}catch{}let r=zw(e);try{if(await R(r)){let o=await Zw(r,"utf-8");dd(o)&&t.push(r)}}catch{}return t},fJ=async(e,t)=>{let n=Xw(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await F(n),o=!1;if(Jw(r.env)){let s={...r.env};for(let i of Fo)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Uo(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 HO(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]}},zw=e=>WO(e,".codex","config.toml"),mJ=async(e,t,n)=>{let r=zw(e),o=await Zw(r,"utf-8").catch(()=>""),a=fd(o,Ti(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await lJ(cJ(r),{recursive:!0}),await GO(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]}},hJ=async(e,t)=>{let n=zw(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Zw(n,"utf-8"),o=md(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await HO(n,{force:!0}):await GO(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},VO=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Yw],r=n.filter(s=>!Yw.includes(s));if(r.length>0)return D(`--project supports ${Yw.join(", ")} \u2014 not: ${r.join(", ")}. Other tools keep per-machine state (run anyray-connect without --project there).`),1;let o;if(!e.revert){let s=await L(),i=e.gateway??s.gateway;if(!i)return 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=uJ(dt(i))}if(k(Z(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),W("Project"),k(` Directory: ${t}`),o&&k(` Gateway: ${o.origin}`),k(` 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(!xt())return D(`
|
|
644
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 ya(`
|
|
645
645
|
${s} ${n.length} tool(s)?`))return M("Aborted. Nothing changed."),0}e.dryRun&&M(`
|
|
@@ -652,7 +652,7 @@ Dry run \u2014 no files will be written.`);let a=[];for(let s of n){W(s==="claud
|
|
|
652
652
|
`),1;try{let o=await il(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(`${ZO}
|
|
655
|
-
`),1}};import{mkdir as _J,writeFile as TJ}from"node:fs/promises";import{dirname as PJ}from"node:path";import{Buffer as DJ}from"node:buffer";var IJ=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),EJ=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,xJ=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.")},RJ=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!==""||xJ(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Zs=(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()}},XO=e=>{if(!RJ(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!IJ.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Zs(e.clientId,"clientId",!0),r=Zs(e.scopes,"scopes",!0),o=Zs(e.issuer,"issuer",!1),a=Zs(e.authorizationUrl,"authorizationUrl",!1),s=Zs(e.tokenUrl,"tokenUrl",!1),i=Zs(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}:{}}},zO=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return XO(t)},Qw=e=>e==="windows"?sp:ap,OJ=(e,t)=>{let n=new URL(e);return n.searchParams.set("os",t),n.toString()},jp=(e,t)=>{let n=OJ(Vp(e.url,"--bootstrap-url"),t),r=e.oidc?XO(e.oidc):void 0,o;if(e.deploymentOrganizationUuid!==void 0&&(o=e.deploymentOrganizationUuid.trim(),!EJ.test(o)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:n,bootstrapHeadersHelper:Qw(t),...r?{bootstrapOidc:r}:{},...o?{deploymentOrganizationUuid:o}:{}}},qO=(e,t)=>yo(jp(e,t));var
|
|
655
|
+
`),1}};import{mkdir as _J,writeFile as TJ}from"node:fs/promises";import{dirname as PJ}from"node:path";import{Buffer as DJ}from"node:buffer";var IJ=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),EJ=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,xJ=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.")},RJ=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!==""||xJ(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Zs=(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()}},XO=e=>{if(!RJ(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!IJ.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Zs(e.clientId,"clientId",!0),r=Zs(e.scopes,"scopes",!0),o=Zs(e.issuer,"issuer",!1),a=Zs(e.authorizationUrl,"authorizationUrl",!1),s=Zs(e.tokenUrl,"tokenUrl",!1),i=Zs(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}:{}}},zO=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return XO(t)},Qw=e=>e==="windows"?sp:ap,OJ=(e,t)=>{let n=new URL(e);return n.searchParams.set("os",t),n.toString()},jp=(e,t)=>{let n=OJ(Vp(e.url,"--bootstrap-url"),t),r=e.oidc?XO(e.oidc):void 0,o;if(e.deploymentOrganizationUuid!==void 0&&(o=e.deploymentOrganizationUuid.trim(),!EJ.test(o)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:n,bootstrapHeadersHelper:Qw(t),...r?{bootstrapOidc:r}:{},...o?{deploymentOrganizationUuid:o}:{}}},qO=(e,t)=>yo(jp(e,t));var NJ=`anyray-connect desktop [disconnect] [options]
|
|
656
656
|
|
|
657
657
|
The minimum Claude Desktop workflow:
|
|
658
658
|
anyray-connect desktop Connect this machine
|
|
@@ -697,7 +697,7 @@ Options:
|
|
|
697
697
|
|
|
698
698
|
Older flag-based Claude artifacts and Codex fleet output remain accepted for
|
|
699
699
|
compatibility, but are not part of the recommended Claude Desktop workflow.
|
|
700
|
-
`,
|
|
700
|
+
`,LJ=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",$J=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),MJ=e=>{if(e[0]!=="fleet")return e;if(e.includes("--help")||e.includes("-h"))return["--help"];let t=e[1];if(t!=="bootstrap"&&t!=="static")throw new Error("desktop fleet requires bootstrap or static.");let n=e[2];if(n!=="macos"&&n!=="windows"&&n!=="linux")throw new Error("desktop fleet target must be macos, windows, or linux.");let r=e[3];if(!r||r.startsWith("-"))throw new Error(t==="bootstrap"?"desktop fleet bootstrap requires an HTTPS URL.":"desktop fleet static requires an absolute credential-helper path.");let o=e.slice(4),a=o[0]&&!o[0].startsWith("-")?o.shift():void 0;return[LJ(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...$J(o)]},BJ=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),eb=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>BJ.has(r))||t.includes("--apply")&&t.includes("--revert")||n==="disconnect"&&t.includes("--apply")))return n==="disconnect"&&(t=["--revert",...t.slice(1)]),t=t.filter(r=>r!=="--apply"),[...t,"--tools","claude-desktop"]},Mr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),QO=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),FJ=(e,t)=>` <key>${Mr(e)}</key>
|
|
701
701
|
<string>${Mr(t)}</string>`,tb=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>FJ(i,c)).join(`
|
|
702
702
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
703
703
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
@@ -734,7 +734,7 @@ ${s}
|
|
|
734
734
|
`},ll={disableDeploymentModeChooser:!0},t_=(e,t)=>tb("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",yo({...sa(e,t),...ll})),UJ=(e,t)=>`${JSON.stringify({...sa(e,t),...ll},null,2)}
|
|
735
735
|
`,WJ=e=>tb("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",yo({...jp(e,"macos"),...ll})),HJ=e=>`${JSON.stringify({...jp(e,"linux"),...ll},null,2)}
|
|
736
736
|
`,n_=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries({...e,...yo(ll)}).map(([n,r])=>`"${QO(n)}"="${QO(r)}"`),""].join(`
|
|
737
|
-
`),r_=(e,t)=>{let n=Su(e,t);return n_(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},GJ=e=>n_(qO(e,"windows")),o_=(e,t,n)=>{if(t==="darwin"){let r=
|
|
737
|
+
`),r_=(e,t)=>{let n=Su(e,t);return n_(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},GJ=e=>n_(qO(e,"windows")),o_=(e,t,n)=>{if(t==="darwin"){let r=Nc;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:t_(e,r),helperPath:r}}if(t==="win32"){let r=Lc;return{path:`${n}\\claude-desktop-anyray.reg`,content:r_(e,r),helperPath:r}}},a_=(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."],KJ=(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=cp(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${Ti(e,o).join(`
|
|
738
738
|
`)}
|
|
739
739
|
`},VJ=e=>tb("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:DJ.from(e,"utf-8").toString("base64")}),jJ=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},YJ=e=>{if(!e.gateway?.trim())throw new Error("--gateway is required for static fleet artifacts; local profile and environment values are intentionally ignored.");let t=dn(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:pi,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},e_=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??_J,o=n.writeFile??TJ;await r(PJ(t),{recursive:!0}),await o(t,e)},ZJ=(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}"
|
|
@@ -756,13 +756,13 @@ Reopen Claude Desktop \u2014 migrated ${c} available in the Anyray profile.
|
|
|
756
756
|
Your previous profile is untouched, so \`desktop disconnect\` still works.
|
|
757
757
|
`)}else n.write(`
|
|
758
758
|
Nothing new to migrate \u2014 no local sessions or portable local data needed copying.
|
|
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},s_=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=MJ(e);if(o[0]==="helper")return Yx(o.slice(1),t);let a=jJ(o);if(a.help)return n.write(
|
|
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 ${
|
|
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},s_=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=MJ(e);if(o[0]==="helper")return Yx(o.slice(1),t);let a=jJ(o);if(a.help)return n.write(NJ),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 XJ(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:zO(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},p=a.artifact==="reg"?GJ(u):a.artifact==="json"?HJ(u):WJ(u);return await e_(p,a.path,t),JJ(a.artifact==="reg"?"windows":a.artifact==="json"?"linux":"macos",r),a.path&&n.write(`Wrote ${a.path}
|
|
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 ${Nc} on macOS/Linux or ${Lc} 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(!$c(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"&&cp("windows",i);let l=YJ(a),d;if(a.target==="claude")d=a.artifact==="reg"?r_(l,i):a.artifact==="json"?UJ(l,i):t_(l,i);else{let u=KJ(l,i);d=a.artifact==="mobileconfig"?VJ(u):u}return await e_(d,a.path,t),ZJ(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 zJ=3e3,Yp=async(e,t={})=>{let n=t.timeoutMs??zJ,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`:Rt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};import{execFileSync as d_}from"node:child_process";import{lstatSync as u_,readFileSync as qJ}from"node:fs";import QJ from"node:os";import{z as nb}from"zod";var p_="ai.anyray.connect",xa="EnrollmentEmail",Ra="EnrollmentUrl",
|
|
762
|
+
`),1}};var zJ=3e3,Yp=async(e,t={})=>{let n=t.timeoutMs??zJ,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`:Rt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};import{execFileSync as d_}from"node:child_process";import{lstatSync as u_,readFileSync as qJ}from"node:fs";import QJ from"node:os";import{z as nb}from"zod";var p_="ai.anyray.connect",xa="EnrollmentEmail",Ra="EnrollmentUrl",eX="HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Anyray\\Connect",i_="/etc/anyray/anyray-enroll.json",tX=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,nX=254,rX=2048,oX=64*1024,aX=e=>e.isFile()&&e.uid===0&&(e.mode&63)===0&&e.size<=oX,sX=()=>`/Library/Managed Preferences/${p_}.plist`,iX=e=>`/Library/Managed Preferences/${e}/${p_}.plist`;var cX=nb.record(nb.string(),nb.unknown()),c_=e=>{try{let t=JSON.parse(e),n=cX.safeParse(t);return n.success?n.data:void 0}catch{return}};var l_=(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}},lX=(e,t)=>e.split(/\r?\n/u).some(n=>/^\s*(\S+)\s+REG_\S+(?:\s|$)/u.exec(n)?.[1]===t),f_=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(!t||t.length>nX))return tX.test(t)?t:void 0},dX=e=>{if(!e)return;let t=e.trim();if(!(!t||t.length>rX))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}},uX={lstat:e=>{u_(e)},convert:e=>d_("plutil",["-convert","json","-o","-",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})},pX=(e,t=uX)=>{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"}}},fX=()=>{try{return QJ.userInfo().username||void 0}catch{return}},mX={windowsHide:!0},hX=`
|
|
763
763
|
$ErrorActionPreference = 'Stop'
|
|
764
764
|
try {
|
|
765
|
-
$item = Get-Item -LiteralPath 'Registry::${
|
|
765
|
+
$item = Get-Item -LiteralPath 'Registry::${eX}'
|
|
766
766
|
} catch [System.Management.Automation.ItemNotFoundException] {
|
|
767
767
|
exit 2
|
|
768
768
|
} catch {
|
|
@@ -789,21 +789,21 @@ try {
|
|
|
789
789
|
}
|
|
790
790
|
} catch {
|
|
791
791
|
exit 3
|
|
792
|
-
}`,
|
|
792
|
+
}`,yX={query:(e,t)=>d_("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],...t})},gX=(e=yX)=>{try{return{kind:"ok",value:e.query(hX,mX)}}catch(t){return t.status===2?{kind:"absent"}:{kind:"unreadable"}}},wX={lstat:e=>u_(e),readFile:e=>qJ(e,"utf8")},bX=(e=wX)=>{try{let t=e.lstat(i_);return aX(t)?{kind:"ok",json:e.readFile(i_)}:{kind:"untrusted"}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable"}}},ob={platform:process.platform,readMacPlistJson:pX,username:fX,readWindowsRegQuery:gX,readLinuxPolicy:bX},kX=e=>{let t=e.map(f_).find(n=>n!==void 0);return t?{email:t}:{}},rb=e=>typeof e=="string"?{kind:"ok",value:e}:e??{kind:"absent"},CX=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?c_(t.json):void 0,o=n?c_(n.json):void 0,a=kX([typeof r?.[xa]=="string"?r[xa]:void 0,typeof o?.[xa]=="string"?o[xa]: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&&Ra in o){let s=o[Ra],i=typeof s=="string"?dX(s):void 0;return i?{status:"valid",enrollment:{...a,enrollmentUrl:i}}:{status:"invalid",reason:"malformed-url",enrollment:a}}return r&&Ra in r?{status:"invalid",reason:"untrusted-file",enrollment:a}:{status:"absent",enrollment:a}},AX=e=>{if(e.platform==="darwin"){let t=e.username(),n=rb(t?e.readMacPlistJson(iX(t)):{kind:"absent"}),r=rb(e.readMacPlistJson(sX())),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=rb(e.readWindowsRegQuery());if(t.kind!=="ok")return t;let n=t.value;if(!n)return{kind:"absent"};let r=l_(n,xa),o=l_(n,Ra),a=lX(n,Ra);return{kind:"document",documents:[{scope:"device",json:JSON.stringify({...r?{[xa]:r}:{},...a?{[Ra]: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"}},ab=(e=ob)=>{try{return CX(AX(e))}catch{return{status:"invalid",reason:"unreadable",enrollment:{}}}},dl=(e=ob)=>ab(e).enrollment,m_=(e,t)=>{if(!e?.length)return;let n=t?.trim().split(/[\\/]/).at(-1)?.toLowerCase();if(n)return f_(`${n}@${e[0]}`)},h_=(e=ob)=>dl(e).email;import{z as ce}from"zod";import{createHash as vX,randomBytes as SX}from"node:crypto";import{createServer as IX}from"node:http";var Js="127.0.0.1",y_=/^[A-Za-z0-9_-]{43}$/,g_=/^[A-Za-z0-9_-]{86}$/,EX=2147483647,Wt=class extends Error{kind;constructor(t,n){super(n),this.name="DesktopSignInCallbackError",this.kind=t}},Zp=()=>new Wt("denied","Desktop sign-in could not be completed. Try again."),Xs=(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)},xX=(e,t)=>{let n=vX("sha256").update(t,"utf8").digest().toString("base64url");return`ANYRAY-DESKTOP-SSO-COMPLETION-PROOF-V1
|
|
793
793
|
${e}
|
|
794
794
|
${n}
|
|
795
795
|
POLL
|
|
796
|
-
`},w_=async()=>{let e;try{e=
|
|
796
|
+
`},w_=async()=>{let e;try{e=SX(32).toString("base64url")}catch{throw new Wt("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=IX((l,d)=>{if(l.socket.remoteAddress!==Js||l.method!=="GET"||l.url===void 0||!l.url.startsWith("/")||l.headers.host!==t){Xs(d,404,"Not found.");return}let u;try{u=new URL(l.url,`http://${Js}`)}catch{Xs(d,404,"Not found.");return}if(u.pathname!==`/${e}`){Xs(d,404,"Not found.");return}if(o){Xs(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"),g=p.length!==2||m.length!==1||f.length!==1||h.length!==0||!y_.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(g===void 0&&y===void 0){o=!0,n({status:"invalid"}),Xs(d,400,"Invalid sign-in callback.");return}o=!0,n(g!==void 0?{status:"complete",...g}:{status:"rejected",...y}),Xs(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:Js,port:0},()=>{a.off("error",u),l()})})}catch{throw a.close(),new Wt("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!==Js||s.port<=0)throw a.close(),new Wt("cp-unreachable","Desktop sign-in could not open its local callback. Try again.");let i=`http://${Js}:${s.port}/${e}`;t=`${Js}:${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 Wt("expired","Desktop sign-in timed out. Try again.");let m;try{m=await new Promise((h,g)=>{let y=!1,w=C=>{y||(y=!0,clearTimeout(A),d.signal?.removeEventListener("abort",b),C())},b=()=>w(()=>g(Zp())),A=setTimeout(()=>w(()=>g(new Wt("expired","Desktop sign-in timed out. Try again."))),Math.min(p,EX));if(d.signal?.aborted){b();return}d.signal?.addEventListener("abort",b,{once:!0}),r.then(C=>w(()=>h(C)))})}catch(h){throw await c(),h}if(m.status==="unavailable")throw await c(),new Wt("cp-unreachable","Desktop sign-in lost its local callback. Try again.");if(m.status==="invalid"||m.grantId!==l.id)throw await c(),Zp();if(m.status==="rejected")throw await c(),m.reason==="no_company"?new Wt("no-company","No company found for this email. Ask your admin for a link."):new Wt("denied","Desktop sign-in was denied. Try again.");let f;try{f=await rr(xX(l.id,m.completionSecret),l.privateKeyPem)}catch{throw await c(),Zp()}if(!g_.test(f)||Buffer.from(f,"base64url").length!==64)throw await c(),Zp();return await c(),{completionSecret:m.completionSecret,keyProof:f}},close:c}},b_=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},k_=e=>e!==void 0&&y_.test(e.completionSecret)&&g_.test(e.keyProof)&&Buffer.from(e.keyProof,"base64url").length===64;var C_=1e4,RX=/^[BCDFGHJKMNPQRSTVWXYZ23456789]{4}-[BCDFGHJKMNPQRSTVWXYZ23456789]{4}$/,OX=ce.strictObject({id:ce.string().min(1),browser_url:ce.string().min(1),user_code:ce.string().regex(RX),poll_secret:ce.string().min(1),interval:ce.number().positive(),expires_in:ce.number().positive()}),_X=ce.object({payload:ce.object({v:ce.number(),deploymentId:ce.string().min(1),user:ce.string().min(1),team:ce.string().min(1).optional(),source:ce.enum(["sso","provisioning","manual","mdm","device"]).optional(),devPublicKey:ce.string().min(1),devKeyAlg:ce.literal("ES256").optional(),issuedAt:ce.string().min(1),expiresAt:ce.string().min(1),keyTtlSeconds:ce.number().optional()}).passthrough(),alg:ce.literal("Ed25519"),sig:ce.string().min(1)}).passthrough(),TX=ce.strictObject({status:ce.literal("pending")}),PX=ce.strictObject({status:ce.literal("complete"),cert:_X,deploymentId:ce.string().min(1),gatewayUrl:ce.string().min(1).optional()}),DX=ce.strictObject({status:ce.literal("rejected"),reason:ce.enum(["no_company","denied"])}),NX=ce.strictObject({status:ce.literal("failure")}),LX=ce.strictObject({status:ce.literal("failure"),retryable:ce.literal(!0),message:ce.string().min(1).max(256)}),$X=e=>new Promise(t=>setTimeout(t,e)),MX=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},A_=async e=>{let t=e.cpOrigin??vn(),n=e.fetch??fetch,r=e.now??Date.now;if(!b_(e.callbackUri))throw new bt("cp-unreachable","Desktop sign-in could not register its local callback. Try again.");let{publicKeyPem:o,privateKeyPem:a}=(e.generateKeypair??Fs)(),s;try{s=await Qc(`${t}/sso/desktop/start`,{devPublicKey:o,callback_uri:e.callbackUri},C_,n)}catch{throw new bt("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 bt(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=OX.safeParse(s.json);if(!i.success)throw new bt("cp-unreachable","Desktop sign-in failed: the control plane returned an incomplete response.");if(!MX(i.data.browser_url,t))throw new bt("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},sn=class extends Error{kind;constructor(t,n){super(n),this.name="DesktopSignInPollError",this.kind=t}},v_=async(e,t)=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??$X,a=t.pollIntervalMs??e.intervalMs;if(!k_(t.completion))throw new sn("denied","Desktop sign-in was not completed. Try again.");for(;r()<e.grantExpiresAt;){let s;try{s=await pR(`${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},C_,n)}catch{throw new sn("cp-unreachable","Desktop sign-in lost contact with the control plane. Check your network and try again.")}if(s.status===202){if(TX.safeParse(s.json).success){let i=e.grantExpiresAt-r();if(i<=0)break;await o(Math.min(a,i));continue}throw new sn("cp-unreachable","Desktop sign-in failed: the control plane returned an unexpected response.")}if(s.status===503&&LX.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=PX.safeParse(s.json);if(i.success)return{cert:i.data.cert,privateKeyPem:e.privateKeyPem,gatewayUrl:i.data.gatewayUrl,deploymentId:i.data.deploymentId};let c=DX.safeParse(s.json);if(c.success&&c.data.reason==="no_company")throw new sn("no-company","No company found for this email. Ask your admin for a link.");if(c.success)throw new sn("denied","Desktop sign-in was denied. Try again.")}throw s.status===404&&NX.safeParse(s.json).success?new sn("denied","Desktop sign-in was not completed. Try again."):new sn("cp-unreachable","Desktop sign-in failed: the control plane returned an unexpected response.")}throw new sn("expired","Desktop sign-in timed out. Try again.")};var S_=()=>Ag(),I_=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??S_)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},BX=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},E_=async(e,t={})=>{let n=(t.openInput??S_)(),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=xs(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 g=e.items[h],y=h===s?l("36","\u276F"):" ",w=e.single?a[h]?"(\u25CF)":"(\u25CB)":a[h]?"[x]":"[ ]",b=g.hint?` ${l("2",g.hint)}`:"";f.push(`${y} ${w} ${g.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 g=()=>{r.off("data",C),r.off("end",b),r.off("close",b),r.off("error",A)},y=x=>{g(),f(x)},w=x=>{g(),h(x)},b=()=>y({kind:"cancelled"}),A=x=>w(x),C=x=>{try{for(let O of
|
|
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 g=()=>{r.off("data",C),r.off("end",b),r.off("close",b),r.off("error",A)},y=x=>{g(),f(x)},w=x=>{g(),h(x)},b=()=>y({kind:"cancelled"}),A=x=>w(x),C=x=>{try{for(let O of BX(x)){if(O===""||O==="\x1B"||O==="q"){y({kind:"cancelled"});return}if(e.items.length===0){(O==="\r"||O===`
|
|
800
800
|
`)&&y({kind:"ok",values:[]});continue}if(O==="\x1B[A"||O==="k")s=(s-1+e.items.length)%e.items.length,d();else if(O==="\x1B[B"||O==="j")s=(s+1)%e.items.length,d();else if(O===" "){if(e.single){let S=!a[s];a.fill(!1),a[s]=S}else a[s]=!a[s];d()}else if(O==="a"&&!e.single){let S=e.items.map((T,I)=>({item:T,index:I})).filter(({item:T})=>T.requiresExplicitChoice!==!0),E=!S.every(({index:T})=>a[T]);for(let{index:T}of S)a[T]=E;d()}else if(O==="\r"||O===`
|
|
801
|
-
`){y({kind:"ok",values:e.items.filter((S,E)=>a[E]).map(S=>S.value)});return}}}catch(O){w(O)}};r.on("data",C),r.on("end",b),r.on("close",b),r.on("error",A)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),m&&r.setRawMode(p)}catch{}n.close()}};var x_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],
|
|
802
|
-
`),t();let a=0,s=()=>{r.write(`\r${x_[a++%x_.length]} ${e}`)};s();let i=setInterval(s,
|
|
803
|
-
`)};import{chmod as
|
|
804
|
-
`,{mode:384}),await cX(n,384),await ke(n,t)}catch(r){throw await D_(n,{force:!0}).catch(()=>{}),r}},pl=async()=>{await D_(sb(),{force:!0}).catch(()=>{})},L_=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 N_}from"zod";var mX=5e3,hX=N_.object({lane:N_.enum(["subscription","org"]).optional().catch(void 0)}),$_=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??mX);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=hX.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},M_=(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 yX=12e3,gX="anyray-wiring-probe-not-a-real-token",wX={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},cb={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},Oa=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},F_=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},lb=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},B_=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."],bX=e=>e.includes("no provider key configured for"),db=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},ub=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>"]}),fl=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."]}),kX=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:bX(t)?{kind:"provider-rejected",providerKeyAbsent:!0,detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Oa(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")?B_([" \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?db(t)?ub(e):lb(t)?fl(e):F_(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Oa(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}): ${Oa(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).",...B_([" \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}: ${Oa(t)}`,remedy:[]},CX=(e,t)=>{if(lb(t))return fl(e);if(db(t))return ub(e);if(F_(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}: ${Oa(t)}`,remedy:[]}},AX=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),vX=(e,t)=>{if(lb(t))return fl(e);if(db(t))return ub(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")||AX(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}: ${Oa(t)}`,remedy:[`The probe asks for a fixed model (${cb.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."]}},ib=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)}},SX=async(e,t)=>{if(!e.clientKey)return fl(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?fl(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Oa(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},IX=(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."]}},EX=e=>e.providerKeyAbsent===!0?!1:e.kind==="ok"?!0:null,U_=async(e,t={})=>{try{return EX(await ti(e,t))}catch{return null}},ti=async(e,t={})=>{let n=t.timeoutMs??yX,r=be(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await SX(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 ib(`${e.anthropicBaseUrl}/v1/messages`,l,cb,n);return vX(d,u)}if(se(e,"anthropic")){let l={Authorization:`Bearer ${gX}`,"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 ib(`${e.anthropicBaseUrl}/v1/messages`,l,cb,n);return CX(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await ib(`${e.openaiBaseUrl}/chat/completions`,s,wX,n);return kX(i,c,t.tools??[])}catch(o){return IX(n,o)}};var W_=async(e,t={})=>{let n=await N(),r=!n.enrolledCert&&n.managedEnrollmentDisabled!==!0&&!!(t.managedEnrollment??dl)().enrollmentUrl,o;try{o=tr(e.gateway,n)}catch(s){return k(Z("Anyray connect \u2014 status")),M(`Gateway: ${s.message}`),0}k(Z("Anyray connect \u2014 status")),W("Gateway"),k(` Origin: ${it(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)"),W("Identity"),k(` Name: ${n.name??v("(not set)")}`),k(` Team: ${n.team??v("(not set)")}`);let a=Ln();a&&(W("Environment"),k(` Remote dev context: ${Va(a)}`),pr(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&&(W("Credential renewal"),B(" Direct gateway routing with a proof-backed key heartbeat."),M(" Renewal extends the same key; tool configuration is not rewritten.")),W("Tools");for(let s of ie){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`),k(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===bo&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,p=await np();l=rp({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=op(l,d);P(` ${s.title}: ${u.headline}`);for(let p of u.detail)k(v(` ${p}`))}else M(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as a3}from"node:fs";import{isAbsolute as s3}from"node:path";import{homedir as i3}from"node:os";import{readFile as xX,stat as RX}from"node:fs/promises";import{homedir as OX,platform as _X}from"node:os";var TX=e=>e.replace(/\\(\d{3})/g,(t,n)=>String.fromCharCode(parseInt(n,8))),PX=e=>e.split(`
|
|
805
|
-
`).map(t=>t.split(" ")[4]).filter(t=>!!t).map(
|
|
806
|
-
`)){let o=new RegExp(`${e3}=(\\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"},r3=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",nf=(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 ${Hn} and ${Gn}; 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."}},J_=async(e={})=>{let{installedVariant:t=os,receiptMode:n=Wd,awaitingReload:r=Ud,readSettings:o=t3,probeBridge:a=n3,home:s=XX()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:nf("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.":nf("not-applicable","unknown")}}let l=await o(Zi(i)),d=await a(),u=r3({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:nf(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:nf("not-applicable","unknown")}}};var Ht="connect",rf=e=>e.replace(/-/g,"_"),X_=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Ht,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:Ht,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Ht,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:Ht,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:Ht,checkId:"update_lane",status:"fleet_directive"}),e.identity.sharedIdentityRisk&&t.push({tool:Ht,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Ht,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),t.push({tool:Ht,checkId:"desktop_config_carry",status:e.claudeDesktopConfigCarry}),e.retrieval){let i=rf(e.retrieval.kind);t.push({tool:Ht,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":rf(e.verify.kind);t.push({tool:Ht,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:Ht,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:rf(e.hookLane.reason)}:{}})}t.push({tool:Ht,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:rf(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:Ht,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};var bb="claude-desktop",o3=async(e,t,n)=>{if(t.some(o=>o.adapter===bb))return!0;if(e.managedTools!==void 0)return e.managedTools.includes(bb);let r=n(bb);return!e.gateway||!r?.pointsAt?!1:r.pointsAt(e.gateway).catch(()=>!1)},yl=async(e={})=>{let t=(e.firstPartyRoot??aa)(),n=(e.thirdPartyRoot??Rr)();if(!t||!n)return"unsupported";let[r,o]=await Promise.all([(e.loadProfile??N)(),(e.listPendingOps??Mn)()]);return await o3(r,o,e.toolById??Qe)?(e.inspect??EE)(t,n):"not_routed"};var c3=e=>{let t=i3();return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e};function z_(){return Ne}var l3=(e,t)=>e!=="managed"?"package":t?"fleet_directive":"self",d3="ctx_doctor-probe-synthetic",u3=(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: ${Ab(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 p3(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function f3(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Ab(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 q_=e=>rp({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),kb=e=>e.tombstoned!==!0&&(e.applyBlocked===!0||e.configuredKeyStale===!0||e.pointedAt===!1&&q_(e)!=="unverifiable"),Q_=e=>e.registered&&e.command&&s3(e.command)?a3(e.command):null,m3=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."}},Cb=e=>(kb(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),h3=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,y3=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},eT=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},g3=(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(Ia),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(g=>a.has(g[0])&&r(g[1])).map(([g,y])=>({checkId:g,at:y})),p=n(l.flapping)?l.flapping:void 0,m=Array.isArray(p?.checks)?p.checks.filter(g=>typeof g=="string"&&a.has(g)):[],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},w3=async(e,t,n,r,o,a,s,i=n,c=ti,l=!0,d=ja,u=Ca,p=Ut,m=js,f=()=>yl({loadProfile:async()=>t,toolById:y=>r.find(w=>w.id===y)}),h=Uy(),g=Nn)=>{let y=l?await Yp(e):null,w=process.env.ANYRAY_CLIENT_KEY?.trim(),b=w?"env":t.clientKey?"profile":null,A=In(w||t.clientKey)??null,C=J=>J&&gg(J)?"machine_default":null,x=t.enrolledCert?.payload,O=x?.expiresAt??t.enrolledCertExpiry??null,E=(await a())?.sso??null,T=f3({ssoLink:E,enrolledViaToken:!!t.enrolledTokenHash}),I=s(),K=!x&&t.managedEnrollmentDisabled!==!0&&I.status==="valid",G=mt(),X=await QC(G),ae=X?[]:kd(Re({origin:e})),Ae=[];for(let J of r){let At=await J.detect(),To=null;if(At.installed&&J.mcpStatus)try{let ck=await J.mcpStatus();To={...ck,commandOk:Q_(ck)}}catch{}let Po=At.installed&&J.id===bo?await o():void 0,Hr=At.installed&&J.pointsAt?await J.pointsAt(e):null,Da=await h3(Hr,J,t.managedTools??[]),Il=Hr===!1&&Da===null,di=Da===!1&&J.routingPendingReload?await J.routingPendingReload().catch(()=>!1):!1,El=Da===!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:de,claudeCodeHookPolicy:ln}=z,xe=t.fleetToolPolicy,ui=xe?.enabled.includes(J.id)?xe.tiers?.[J.id]??va:void 0;Ae.push({id:J.id,title:J.title,installed:At.installed,...At.detail?{detail:At.detail}:{},pointedAt:Da,...El===!1?{configuredKeyStale:!0}:{},...Il?{routingHeld:!0}:{},...di?{routingPendingReload:!0}:{},...de.length?{routingOverrides:de}:{},...ln===void 0?{}:{claudeCodeHookPolicy:ln},mcp:To,...ui?{policyTier:ui}:{},...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}:{},...Po===void 0?{}:{inferenceIntrospectable:Po.authoritative,...Po.authoritative?{}:{inferenceUnverifiableReason:Po.reason}}})}let me=i?await(async()=>{let{kind:J,detail:At,remedy:To}=await c(Re({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:To}})():null,U=me?.kind==="provider-rejected"&&await y3(t.managedTools??[],r),Q=me?{...me,...U?{notApplicableSubscription:!0}:{}}:null,ye=n?u3(await Vs({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:be({user:t.name,team:t.team})},d3,{probe:!0}),{mode:T,ssoLink:E}):null,we=await p().catch(()=>({})),Y=or(we.hookLane),Ie=i?await eT(r):!1,cn=Ie?await(async()=>{let J=await m().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...Nw(J,{hookRegistered:Ie,neverInvoked:Pw(Y,Date.now())}),lastInvokedAt:Lp(Y)}})():null,Fr=(await Mn()).map(J=>({adapter:J.adapter,op:J.op,requestedAt:J.requestedAt,watcherAlive:$n(J.watcherPid)})),Ur=Fr.find(J=>J.adapter==="cursor"),Wr=Ur?{op:Ur.op,requestedAt:Ur.requestedAt,watcherAlive:Ur.watcherAlive}:null,_o=await f().catch(()=>"unknown"),Sl=Ae.some(J=>J.id===bo&&J.installed),li;if(Sl&&_o!=="unsupported"){let J;try{J=h()}catch{J="probe_failed"}li=J==="probe_failed"?"failed":"answered"}let L=!!t.refreshSchedulerEnabled,_=await g(),V=L&&!_&&!ot(t),_e=await u(),nt=await _a(),Gt=t.anyrayFleetManaged===!0&&nt,Ct=t.persistenceOwner==="tray",Ve=Ct?await d(t)==="healthy":null,je=await MC({schedulerEnabled:L&&!Ct&&!V,schedulerInstalled:_,binaryDurable:!ut(Wo()),schedulerInstalledOnce:t.refreshSchedulerInstalledOnce===!0,trayManaged:Ct}),Te=0;y&&!y.reachable&&(Te+=1),Ct?L&&!Ve&&(Te+=1):L&&!_&&!V&&(Te+=1);for(let J of Ae)Te+=Cb(J);Q&&Q.kind!=="ok"&&!Q.notApplicableSubscription&&(Te+=1),ye&&ye.kind!=="ok"&&(Te+=1),cn?.verdict==="dark"&&(Te+=1),ae.length>0&&(Te+=1),Te+=Fr.filter(J=>!J.watcherAlive).length;let ir=await J_();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:z_(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:Ln(),fileBindMounts:await qp(),selfUpdate:{managed:_e.managed,available:_e.available,autoUpdate:_e.autoUpdate,state:_e.state,fleetMode:_e.fleetMode,updateLane:l3(_e.state,Gt)}},gateway:{origin:e,reachable:y?y.reachable:null,detail:y?y.detail:"not probed (--quick)"},refreshScheduler:{enabled:L,installed:_,owner:Ct?"tray":"os",...Ct?{trayHealthy:!!Ve}:{},...V?{retired:!0}:{}},serviceRemoval:je,fleetdPresent:nt,identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:b,keyKind:A,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:C(t.name)},enrollment:{enrolled:!!x,deploymentId:x?.deploymentId??null,issuedAt:x?.issuedAt??null,expiresAt:O,expired:O?Date.parse(O)<Date.now():null,orgMode:T,ssoLink:E,managedPending:K,managedPreference:I.status,managedPreferenceReason:I.reason??null},shell:{profilePath:G,blockPresent:X,staleExports:ae},claudeDesktopConfigCarry:_o,...li?{claudeDesktopRunningProbe:li}:{},tools:Ae,...t.fleetToolPolicy?{fleetPlan:_p(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Wr,pendingOps:Fr,ambientRepairs:g3(we,r),verify:Q,retrieval:ye,hookLane:cn,hookPolicies:ni(t.hookPolicies),hookPolicyMetrics:await ef(),agentsWindow:ir,problems:Te}},b3=e=>{if(e.serviceRemoval.suspected){if(!e.serviceRemoval.removed){W("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)k(v(` expected: ${t}`));return}W("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)k(v(` missing: ${t}`));k(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(v(" tools straight at the gateway (your key then needs a periodic re-run).")),k(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},k3=(e,t)=>{if(k(Z("Anyray connect \u2014 doctor")),e.connect.remoteContext||e.connect.fileBindMounts.length>0){W("Environment"),e.connect.remoteContext&&(k(` Remote dev context: ${Va(e.connect.remoteContext)}`),pr(e.connect.remoteContext)&&k(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)k(` Bind-mounted config file: ${c3(l)}`),k(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(W("CLI updates"),e.connect.selfUpdate.state){case"managed":B(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.fleetMode==="off"?k(v(" Your organization manages Connect updates; this machine downloads nothing.")):e.connect.selfUpdate.fleetMode==="directed"?k(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."),k(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."),k(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(v(" This copy is externally managed; update it with the method that installed it."));break;case"sidecar":k(v(" This engine is part of the desktop app, which updates the whole app."));break;case"container":k(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}if(W("Gateway"),e.gateway.reachable===null?k(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})`),k(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(W("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."),k(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")||k(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),b3(e),e.identity.keyKind==="service")W("Service key (agent)"),B(e.identity.personalKeySource==="env"?" Service key present ($ANYRAY_CLIENT_KEY).":" Service key present (stored by connect)."),k(v(" Identity and team come from the key. Not a seat: no key refresh here, and no seat health report."));else switch(W("Personal key"),p3(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."),k(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}).`),k(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."),k(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."),k(v(` Fix: ${Ab(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&&(W("Shell"),D(" This terminal still exports Anyray, but the config is gone."),k(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(v(" Anything you start from this terminal keeps reaching the gateway with")),k(v(" no credential, and fails with 401.")),k(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(v(" reuses the environment it captured at launch, so a new terminal")),k(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};W("Claude Code hook policy"),D(` ${Kl(l)}.`),k(v(` ${Vl(l)}`))}if(e.tools.some(l=>l.id===bo&&l.installed)){W("Claude Desktop profile");let l=hE[e.claudeDesktopConfigCarry];switch(e.claudeDesktopConfigCarry){case"carried":B(` ${l}.`);break;case"pending":P(` ${l}.`),k(v(" Connect completes it on the next reconcile, or the next time Claude Desktop is fully quit."));break;case"unreadable":P(` ${l}.`),k(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":k(v(` ${l}.`));break}e.claudeDesktopRunningProbe==="failed"&&(P(" Could not tell whether Claude Desktop is running: the process probe failed."),k(v(" Queued copies wait until the probe answers; check that pgrep (macOS) or tasklist (Windows) runs from this account.")))}W("Tools");let r=!1,o=!1,a=l=>{for(let d of l.routingOverrides??[])D(` ${l.title}: ${d.problem}.`),k(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}).`),k(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.`),k(v(` Fix: ${m3(l)}`))))};for(let l of e.tools){if(!l.installed){k(v(` ${l.title}: not installed (skipped)`));continue}if(l.pointedAt===null){k(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`),k(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"&&k(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===bo&&k(v(` ${QS(Tt("migrate"),Tt("desktop"))}`)),l.id==="codex"&&k(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=q_(l);if(d==="not-routed"||d==="unverifiable"){let u=op(d,{...l.inferenceUnverifiableReason?{reason:l.inferenceUnverifiableReason}:{},mcpRegistered:l.mcp?.registered===!0});P(` ${l.title}: ${u.headline}`);for(let p of u.detail)k(v(` ${p}`));d==="unverifiable"&&(o=!0)}else l.tombstoned?l.policyTier==="required"?(P(` ${l.title}: reverted locally against admin policy (out of compliance)`),k(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`):k(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`),k(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`),k(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`),k(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}`),k(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."),k(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){W("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.`),k(v(` Fix: quit ${d} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){W("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):k(m)}}let c=e.fleetPlan;if(c&&(c.freshIds.length>0||c.tombstonedIds.length>0)){W("Fleet policy");let l=d=>d.map(u=>Qe(u)?.title??u).join(", ");c.freshIds.length>0&&k(` 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(W("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)k(v(` ${l}`))}if(e.retrieval)if(W("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)k(v(` ${l}`))}if(e.hookLane){if(W("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)k(v(` ${l}`))}else{P(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let l of e.hookLane.remedy)k(v(` ${l}`))}e.hookLane.lastInvokedAt!==null&&k(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(W("VS Code Agents window"),P(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(W("VS Code Agents window"),B(` ${e.agentsWindow.detail}`)),W("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)."),k(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.`)},C3=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}),A3=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Ow(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??js,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??an)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=or((await(t.readRefreshState??Ut)().catch(()=>({}))).hookLane),l=Nw(i,{hookRegistered:await eT(t.adapters??ie).catch(()=>!1),neverInvoked:Pw(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:Lp(c)},note:d}},v3=async(e,t,n={})=>{let r=n.adapters??ie,o=n.resolveTarget??Je,a=n.applyTools??tn,s=await A3(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(w=>w.installed&&(kb(w)||w.mcp?.commandOk===!1||w.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(w=>({id:w.id,title:w.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 ${Ab(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),p=[],m=[...c.notes],f=[];for(let w of l){let b=r.find(A=>A.id===w.id);if(!u.has(w.id)||!b){p.push({id:w.id,title:w.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),g=new Map,y=0;for(let w of h){if(p.push(w),!ga(w))continue;let b=e.tools.find(I=>I.id===w.id);if(!b)continue;let A=r.find(I=>I.id===w.id),C=b.mcp;if(A?.mcpStatus)try{let I=await A.mcpStatus();C={...I,commandOk:Q_(I)}}catch{}let x=kb(b)?!0:b.pointedAt;if(A?.pointsAt&&b.pointedAt!==null)try{x=await A.pointsAt(e.gateway.origin)}catch{}let O=b.routingOverrides,S=b.claudeCodeHookPolicy;if(A?.runtimeDiagnostics)try{let I=await A.runtimeDiagnostics();O=I.routingOverrides.length?I.routingOverrides:void 0,S=I.claudeCodeHookPolicy}catch{}else if(A?.routingOverrides)try{let I=await A.routingOverrides();O=I.length?I:void 0}catch{}let E=b.configuredKeyStale;if(A?.configuredKeyIsCurrent&&t.clientKey)try{let I=await A.configuredKeyIsCurrent(t.clientKey);I!==null&&(E=!I)}catch{}let T={...b,pointedAt:x,mcp:C,...E?{configuredKeyStale:!0}:{},...O?{routingOverrides:O}:{},...S===void 0?{}:{claudeCodeHookPolicy:S}};E||delete T.configuredKeyStale,O||delete T.routingOverrides,S===void 0&&delete T.claudeCodeHookPolicy,g.set(w.id,T),y+=Cb(b)-Cb(T)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:g,...s?{hookLane:s.hookLane}:{},notes:m}},S3=e=>{W("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-")?k(v(` ${t.title}: ${t.status}`)):D(` ${t.title}: ${t.status}`);for(let t of e.notes)k(v(` ${t}`))},of=async(e,t={})=>{let n=await N();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(BC({connectVersion:z_(),...l?{gatewayHost:l}:{}}),null,2)),0}if(!e.silent){k(Z("Anyray connect \u2014 security review"));for(let l of FC())k(l?` ${l}`:"")}return 0}let r;try{r=tr(e.gateway,n)}catch(l){return e.silent?1:e.json?(console.log(JSON.stringify({error:l.message})),1):(k(Z("Anyray connect \u2014 doctor")),D(` Gateway URL: ${l.message}`),k(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"})):(k(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 w3(r,n,!!e.verify&&!e.quick,t.adapters??ie,t.inferenceIntrospection??np,t.fleetBootstrap??So,t.managedPreference??ab,o,t.verifyAuth??ti,!e.quick,t.checkTray??ja,t.updateStatus??Ca,t.readRefreshState??Ut,t.probeHookLane??js,t.claudeDesktopConfigCarry??(()=>yl({loadProfile:async()=>n,toolById:l=>(t.adapters??ie).find(d=>d.id===l)})),t.claudeDesktopRunningProbe??Uy(),t.isRefreshSchedulerInstalled??Nn),s=e.repair?await v3(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(C3(i),null,2)):(k3(i,n.managedEnrollmentDisabled===!0),s&&S3(s)));let c=i.identity.keyKind!=="service";try{!e.quick&&c&&await(t.reportHealth??QR)(X_(i),i.connect.version)}catch{}return i.problems===0?0:1};var tT=async e=>{let t=await N();k(Z("Anyray connect \u2014 sync"));let n;try{n=tr(e.gateway,t)}catch(i){return D(i.message),1}M(`Gateway: ${n}`);let r=Sx(t.clientKey,"anyray-placeholder"),o;try{o=await Hs(n,r)}catch(i){return D(`Team policy sync failed: ${Ws(i)}`),1}let{summary:a,dirs:s}=await Iw(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{W("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."),W("Summary"),k(` ${it(String(a.changed))} updated, ${a.unchanged} unchanged, ${a.removed.length} removed, across ${s.length} tool dir(s).`)}try{let i=await Ew(o);i.changed.length>0&&k(`Org connectors: ${i.served?"registered":"removed"} the anyray-org MCP entry in ${i.changed.join(", ")}.`)}catch(i){M(`Org connectors sync skipped: ${Ws(i)}`)}try{let i=await Gs(o);(i.routingUpdated||i.teamUpdated||i.toolsRequested>0||i.toolsTombstoned.length>0)&&(k(`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: ${Ws(i)}`)}return 0};import{gzip as Uz}from"node:zlib";import{promisify as Wz}from"node:util";var Ro={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},vb=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),nT=e=>`
|
|
801
|
+
`){y({kind:"ok",values:e.items.filter((S,E)=>a[E]).map(S=>S.value)});return}}}catch(O){w(O)}};r.on("data",C),r.on("end",b),r.on("close",b),r.on("error",A)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),m&&r.setRawMode(p)}catch{}n.close()}};var x_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],FX=80,zs=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&xs(r,n.env??process.env)))return r.write(`${e}
|
|
802
|
+
`),t();let a=0,s=()=>{r.write(`\r${x_[a++%x_.length]} ${e}`)};s();let i=setInterval(s,FX);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createHash as UX}from"node:crypto";import{createReadStream as WX}from"node:fs";import{spawnSync as R_}from"node:child_process";import{mkdir as O_,readdir as __,rename as HX,rm as Qs}from"node:fs/promises";import{platform as GX}from"node:os";import{join as qs}from"node:path";import{z as ar}from"zod";var KX=1e4,VX=3e4,jX=e=>e!=="."&&e!==".."&&!e.includes("\0")&&!/[\\/]/.test(e),YX={staging:"https://github.com/anyrayHQ/install/releases/download/connect-desktop-staging/connect-desktop-staging.json",stable:"https://github.com/anyrayHQ/install/releases/download/connect-desktop/connect-desktop.json"},ZX={staging:{artifact:"anyray-connect-desktop-staging",tagPrefix:"connect-desktop-staging-v"},stable:{artifact:"anyray-connect-desktop",tagPrefix:"connect-desktop-v"}},JX=ar.object({schemaVersion:ar.literal(1),artifact:ar.string().min(1),version:ar.string().min(1),tag:ar.string().regex(/^[\w.-]{1,120}$/),minVersion:ar.string().min(1).optional(),artifacts:ar.array(ar.object({sha256:ar.string().regex(/^[0-9a-f]{64}$/),name:ar.string().regex(/^[\w.-]{1,160}$/)})).min(1)}),XX=(e,t)=>{let n=t==="darwin"?"-macos-universal.app.tar.gz":t==="win32"?"-windows-x64.msi":void 0;return n?e.artifacts.find(r=>r.name.endsWith(n)):void 0},zX=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),KX);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},qX=async(e,t)=>{try{let n=UX("sha256");for await(let r of WX(e))n.update(r);return n.digest("hex")===t}catch{return!1}},QX=async e=>{let t=[],n=async r=>{for(let o of await __(r,{withFileTypes:!0})){if(!o.isDirectory())continue;let a=qs(r,o.name);o.name.endsWith(".app")?t.push(a):await n(a)}};return await n(e),t},e5=async(e,t)=>{await Qs(t,{recursive:!0,force:!0}),await O_(t,{recursive:!0,mode:448});let n=R_("/usr/bin/tar",["-xzf",e,"-C",t],{stdio:"ignore"});if(n.error||n.status!==0)return;let r=await QX(t);return r.length===1?r[0]:void 0},t5=async(e,t=R_)=>{let r=t("powershell",["-NoProfile","-NonInteractive","-Command","$signature = Get-AuthenticodeSignature -LiteralPath $env:CONNECT_DESKTOP_MSI_PATH; if ($signature.Status -eq 'Valid' -and $signature.SignerCertificate.Subject -match 'O=Othentic Labs LTD') { exit 0 }; exit 1"],{stdio:"ignore",timeout:VX,windowsHide:!0,env:{...process.env,CONNECT_DESKTOP_MSI_PATH:e}});return!r.error&&r.status===0},n5=async(e,t)=>{for(let n of await __(e,{withFileTypes:!0}).catch(()=>[]))!n.isDirectory()||n.name===t||await Qs(qs(e,n.name),{recursive:!0,force:!0}).catch(()=>{})},Jp=async(e,t)=>(await Qs(e,{recursive:!0,force:!0}).catch(()=>{}),{status:"rejected",reason:t}),ul=async(e,t={})=>{let n;try{if(n=await zX(YX[e.channel],t.fetchImpl??fetch),!n.ok)return{status:"unreachable"}}catch{return{status:"unreachable"}}let r;try{let d=JX.safeParse(await n.json());if(!d.success)return{status:"unreachable",reason:"manifest"};r=d.data;let u=ZX[e.channel];if(!jX(r.version)||r.artifact!==u.artifact||!r.tag.startsWith(`${u.tagPrefix}${r.version}-`))return{status:"unreachable",reason:"manifest"}}catch{return{status:"unreachable",reason:"manifest"}}if(ko(r.version,e.current)<=0)return{status:"none",version:r.version,minVersion:r.minVersion};let o=t.os??GX(),a=XX(r,o);if(a&&!a.name.includes(`-${r.version}-`))return{status:"unreachable",reason:"manifest"};if(!a)return{status:"none",version:r.version,minVersion:r.minVersion,artifact:!1};let s=qs(t.stateDir??ee(),"desktop-updates"),i=qs(s,r.version),c=qs(i,a.name);if(await O_(i,{recursive:!0,mode:448}),!await qX(c,a.sha256)){let d=`${c}.part-${process.pid}`;await Qs(d,{force:!0}).catch(()=>{});try{await(t.download??Wc)(`https://github.com/anyrayHQ/install/releases/download/${r.tag}/${a.name}`,d,a.sha256),await HX(d,c)}catch(u){return await Qs(d,{force:!0}).catch(()=>{}),u instanceof ka||u instanceof TypeError?(await Qs(i,{recursive:!0,force:!0}).catch(()=>{}),{status:"unreachable"}):Jp(i,"checksum")}}let l=c;if(o==="darwin"){let d=await e5(c,qs(i,"extracted")).catch(()=>{});if(!d)return Jp(i,"archive");let u=await(t.verifyApp??Ri)(d);if(!u.ok)return Jp(i,u.reason);l=d}else if(o==="win32"&&!await(t.verifyMsi??t5)(c))return Jp(i,"signature");return await n5(s,r.version),{status:"staged",version:r.version,path:l,minVersion:r.minVersion}};import{z as le}from"zod";var r5=le.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"]),T_=le.enum(["personal","service"]),o5=le.strictObject({event:le.literal("sso_grant"),verificationUriComplete:le.string().min(1),userCode:le.string().min(1).optional(),expiresAt:le.iso.datetime(),tenantId:le.string().min(1).optional()}),a5=le.strictObject({event:le.literal("enrolled"),via:le.enum(["sso","enroll","claim","sign-in"]),user:le.string().min(1).optional(),team:le.string().min(1).optional(),authMode:le.string().min(1),gateway:le.string().min(1),deploymentId:le.string().min(1).optional(),certExpiresAt:le.string().min(1).optional(),keyKind:T_.optional()}),Xp=le.strictObject({id:le.string().min(1),reason:le.string()}),s5=le.strictObject({event:le.literal("applied"),connected:le.array(le.string().min(1)),queued:le.array(le.string().min(1)),held:le.array(Xp),manual:le.array(Xp),failed:le.array(Xp),keyKind:T_.optional(),reverted:le.array(le.string().min(1)).optional(),skipped:le.array(Xp).optional()}),i5=le.strictObject({event:le.literal("error"),code:r5,message:le.string().min(1)}),jue=le.discriminatedUnion("event",[o5,a5,s5,i5]),P_=(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]}:{}}},sr=e=>{process.stdout.write(`${JSON.stringify(e)}
|
|
803
|
+
`)};import{chmod as c5,readFile as l5,rm as D_,writeFile as d5}from"node:fs/promises";import{join as u5}from"node:path";var sb=()=>u5(ee(),"sso-gate.json"),p5=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))},ei=async()=>{try{let e=JSON.parse(await l5(sb(),"utf-8"));return p5(e)?e:null}catch{return null}},f5=0,zp=async e=>{await Xe();let t=sb(),n=`${t}.${process.pid}.${f5++}.tmp`;try{await d5(n,`${JSON.stringify(e)}
|
|
804
|
+
`,{mode:384}),await c5(n,384),await ke(n,t)}catch(r){throw await D_(n,{force:!0}).catch(()=>{}),r}},pl=async()=>{await D_(sb(),{force:!0}).catch(()=>{})},N_=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 L_}from"zod";var m5=5e3,h5=L_.object({lane:L_.enum(["subscription","org"]).optional().catch(void 0)}),$_=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??m5);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=h5.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},M_=(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 y5=12e3,g5="anyray-wiring-probe-not-a-real-token",w5={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},cb={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},Oa=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},F_=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},lb=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},B_=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."],b5=e=>e.includes("no provider key configured for"),db=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},ub=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>"]}),fl=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."]}),k5=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:b5(t)?{kind:"provider-rejected",providerKeyAbsent:!0,detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Oa(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")?B_([" \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?db(t)?ub(e):lb(t)?fl(e):F_(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Oa(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}): ${Oa(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).",...B_([" \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}: ${Oa(t)}`,remedy:[]},C5=(e,t)=>{if(lb(t))return fl(e);if(db(t))return ub(e);if(F_(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}: ${Oa(t)}`,remedy:[]}},A5=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),v5=(e,t)=>{if(lb(t))return fl(e);if(db(t))return ub(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")||A5(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}: ${Oa(t)}`,remedy:[`The probe asks for a fixed model (${cb.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."]}},ib=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)}},S5=async(e,t)=>{if(!e.clientKey)return fl(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?fl(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Oa(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},I5=(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."]}},E5=e=>e.providerKeyAbsent===!0?!1:e.kind==="ok"?!0:null,U_=async(e,t={})=>{try{return E5(await ti(e,t))}catch{return null}},ti=async(e,t={})=>{let n=t.timeoutMs??y5,r=be(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await S5(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 ib(`${e.anthropicBaseUrl}/v1/messages`,l,cb,n);return v5(d,u)}if(se(e,"anthropic")){let l={Authorization:`Bearer ${g5}`,"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 ib(`${e.anthropicBaseUrl}/v1/messages`,l,cb,n);return C5(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await ib(`${e.openaiBaseUrl}/chat/completions`,s,w5,n);return k5(i,c,t.tools??[])}catch(o){return I5(n,o)}};var W_=async(e,t={})=>{let n=await L(),r=!n.enrolledCert&&n.managedEnrollmentDisabled!==!0&&!!(t.managedEnrollment??dl)().enrollmentUrl,o;try{o=tr(e.gateway,n)}catch(s){return k(Z("Anyray connect \u2014 status")),M(`Gateway: ${s.message}`),0}k(Z("Anyray connect \u2014 status")),W("Gateway"),k(` Origin: ${it(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)"),W("Identity"),k(` Name: ${n.name??v("(not set)")}`),k(` Team: ${n.team??v("(not set)")}`);let a=Nn();a&&(W("Environment"),k(` Remote dev context: ${Va(a)}`),pr(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&&(W("Credential renewal"),B(" Direct gateway routing with a proof-backed key heartbeat."),M(" Renewal extends the same key; tool configuration is not rewritten.")),W("Tools");for(let s of ie){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`),k(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===bo&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,p=await np();l=rp({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=op(l,d);P(` ${s.title}: ${u.headline}`);for(let p of u.detail)k(v(` ${p}`))}else M(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as a3}from"node:fs";import{isAbsolute as s3}from"node:path";import{homedir as i3}from"node:os";import{readFile as x5,stat as R5}from"node:fs/promises";import{homedir as O5,platform as _5}from"node:os";var T5=e=>e.replace(/\\(\d{3})/g,(t,n)=>String.fromCharCode(parseInt(n,8))),P5=e=>e.split(`
|
|
805
|
+
`).map(t=>t.split(" ")[4]).filter(t=>!!t).map(T5),D5=async(e,t,n=async r=>(await R5(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},qp=async()=>{if(_5()!=="linux")return[];try{let e=await x5("/proc/self/mountinfo","utf-8");return await D5(P5(e),O5())}catch{return[]}};import{z as pb}from"zod";var fb=pb.object({greenCollapse:pb.boolean().default(!1),rereadStub:pb.boolean().default(!1)}),ni=e=>{let t=fb.safeParse(e??{});return t.success?t.data:{greenCollapse:!1,rereadStub:!1}};import{createHash as N5,randomUUID as ri}from"node:crypto";import{mkdir as L5,readFile as $5,readdir as M5,rename as mb,rm as hb,writeFile as H_}from"node:fs/promises";import{join as hl}from"node:path";import{z as lt}from"zod";var Br=e=>N5("sha256").update(e).digest("hex"),_t=lt.number().int().nonnegative(),oi=lt.string().regex(/^[a-f0-9]{64}$/),B5=lt.object({key:oi,fileHash:oi,outputHash:oi,handle:lt.string().regex(/^ctx_[a-f0-9]{16}$/),turn:_t}).strict(),F5=lt.object({key:oi,at:_t,turn:_t,epoch:oi.default(()=>Br(ri())),lifecycleReady:lt.boolean().default(!1),reads:lt.array(B5).max(256),seen:lt.array(oi).max(256).default([]),pending:lt.array(lt.object({turn:_t,failed:lt.boolean(),kind:lt.enum(["reread","green"]).default("reread"),handle:lt.string().regex(/^ctx_[a-f0-9]{16}$/).optional()}).strict()).max(5)}).strict(),Qp=lt.object({observationGaps:_t.default(0),greenCollapses:_t.default(0),rereadStubs:_t.default(0),retrievesAfterStub:_t.default(0),retrievesAfterCollapse:_t.default(0),retrievalMissesAfterPolicy:_t.default(0),editFailuresAfterStub:_t.default(0),stubsFollowedByEditFailure:_t.default(0),completedWindows:_t.default(0),censoredWindows:_t.default(0)}).strict(),U5=lt.object({sessions:lt.array(F5).max(64),metrics:Qp}).strict(),G_=()=>({sessions:[],metrics:Qp.parse({})}),yb=()=>hl(ee(),"hook-policy-state.json"),ml=()=>hl(ee(),"hook-policy-observation-gap"),W5=8*1024*1024,K_=async()=>(await M5(ee()).catch(()=>[])).filter(e=>/^hook-policy-observation-gap(?:\.[a-f0-9-]+\.recovering)?$/.test(e)).map(e=>hl(ee(),e)),H5=1440*60*1e3,V_=async()=>{try{let e=await $5(yb());return e.length>W5?{state:G_(),invalid:!0}:{state:U5.parse(JSON.parse(e.toString("utf8"))),invalid:!1}}catch(e){return{state:G_(),invalid:e.code!=="ENOENT"}}},ef=async()=>{let{state:e,invalid:t}=await V_();return{...e.metrics,observationGap:t||(await K_()).length>0}},tf=async e=>{let t,n,r=[],o=!1;try{await Xe();let a=hl(ee(),"hook-policy-locks");await L5(a,{recursive:!0,mode:448}),t=await $a(hl(a,"state"),{waitMs:1e3});let{state:s,invalid:i}=await V_();r.push(...(await K_()).filter(d=>d!==ml()));let c=`${ml()}.${ri()}.recovering`;try{await mb(ml(),c),r.push(c)}catch(d){if(d.code!=="ENOENT")throw d}if(i||r.length>0){s.metrics.observationGaps++,s.metrics.censoredWindows+=s.sessions.reduce((d,u)=>d+u.pending.length,0);for(let d of s.sessions)d.reads=[],d.pending=[],d.seen=[],d.turn=0,d.epoch=Br(ri())}let l=await e(s);return n=`${yb()}.${ri()}.tmp`,await H_(n,JSON.stringify(s),{mode:384}),await mb(n,yb()),o=!0,l}catch{let a=`${ml()}.${ri()}.tmp`;try{await H_(a,"",{mode:384}),await mb(a,ml())}catch{}finally{await hb(a,{force:!0}).catch(()=>{})}return null}finally{if(o)for(let a of r)await hb(a,{force:!0}).catch(()=>{});n&&await hb(n,{force:!0}).catch(()=>{}),await t?.().catch(()=>{})}},gb=e=>typeof e.session_id=="string"&&e.session_id.length>0&&e.session_id.length<=256?Br(e.session_id):null,wb=(e,t)=>{let n=Date.now();e.sessions=e.sessions.filter(o=>n-o.at<=H5?!0:(e.metrics.censoredWindows+=o.pending.length,!1));let r=e.sessions.find(o=>o.key===t);return r||(e.sessions.length>=64&&(e.metrics.censoredWindows+=e.sessions.shift().pending.length),r={key:t,at:n,turn:0,epoch:Br(ri()),lifecycleReady:!1,reads:[],seen:[],pending:[]},e.sessions.push(r)),r.at=n,r},j_=(e,t,n,r=null,o=!1)=>{e.turn++;let a=e.pending.filter(i=>r!==null&&i.handle===r);a.some(i=>i.kind==="reread")&&t.retrievesAfterStub++,a.some(i=>i.kind==="green")&&t.retrievesAfterCollapse++,a.length>0&&o&&t.retrievalMissesAfterPolicy++;let s=e.pending.filter(i=>i.kind==="reread");if(n&&s.length>0){t.editFailuresAfterStub++;for(let i of s)i.failed||t.stubsFollowedByEditFailure++,i.failed=!0}e.pending=e.pending.filter(i=>e.turn-i.turn<5?!0:(t.completedWindows++,!1))};var Y_=async e=>{let t=e.hook_event_name;if(!["SessionStart","PreCompact","SessionEnd"].includes(String(t)))return;let n=gb(e);n&&await tf(async r=>{let o=r.sessions.find(a=>a.key===n);r.metrics.censoredWindows+=o?.pending.length??0,r.sessions=r.sessions.filter(a=>a.key!==n),t!=="SessionEnd"&&(wb(r,n).lifecycleReady=!0)})};import{access as G5}from"node:fs/promises";import{constants as K5}from"node:fs";import{platform as V5}from"node:os";var j5=async e=>{try{return await G5(e,K5.F_OK),!0}catch{return!1}},Y5=e=>e==="darwin"?["/Library/LaunchDaemons/com.fleetdm.orbit.plist","/opt/orbit/bin/orbit"]:e==="linux"?["/etc/systemd/system/orbit.service","/usr/lib/systemd/system/orbit.service","/opt/orbit/bin/orbit"]:e==="win32"?["C:\\Program Files\\Orbit\\bin\\orbit\\orbit.exe"]:[],_a=async(e={})=>{let t=e.os??V5(),n=e.exists??j5;for(let r of Y5(t))if(await n(r))return!0;return!1};import{execFile as Z5}from"node:child_process";import{readFile as J5}from"node:fs/promises";import{homedir as X5,platform as z5}from"node:os";import{promisify as q5}from"node:util";var Q5=q5(Z5),e3="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",Z_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),t3=async e=>{let t;try{t=await J5(e,"utf-8")}catch(n){return n?.code==="ENOENT"?{readable:!0}:{readable:!1}}try{if(t.trim()==="")return{readable:!0};let n=Dt(t);if(!Z_(n))return{readable:!1};let r=n[Hn],o=n[Gn];return{readable:!0,supportsAnyray:Z_(r)?r[oe]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},n3=async(e=async()=>(await Q5("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(z5()==="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(`${e3}=(\\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"},r3=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",nf=(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 ${Hn} and ${Gn}; 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."}},J_=async(e={})=>{let{installedVariant:t=os,receiptMode:n=Wd,awaitingReload:r=Ud,readSettings:o=t3,probeBridge:a=n3,home:s=X5()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:nf("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.":nf("not-applicable","unknown")}}let l=await o(Zi(i)),d=await a(),u=r3({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:nf(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:nf("not-applicable","unknown")}}};var Ht="connect",rf=e=>e.replace(/-/g,"_"),X_=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Ht,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:Ht,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Ht,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:Ht,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:Ht,checkId:"update_lane",status:"fleet_directive"}),e.identity.sharedIdentityRisk&&t.push({tool:Ht,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Ht,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),t.push({tool:Ht,checkId:"desktop_config_carry",status:e.claudeDesktopConfigCarry}),e.retrieval){let i=rf(e.retrieval.kind);t.push({tool:Ht,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":rf(e.verify.kind);t.push({tool:Ht,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:Ht,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:rf(e.hookLane.reason)}:{}})}t.push({tool:Ht,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:rf(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:Ht,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};var bb="claude-desktop",o3=async(e,t,n)=>{if(t.some(o=>o.adapter===bb))return!0;if(e.managedTools!==void 0)return e.managedTools.includes(bb);let r=n(bb);return!e.gateway||!r?.pointsAt?!1:r.pointsAt(e.gateway).catch(()=>!1)},yl=async(e={})=>{let t=(e.firstPartyRoot??aa)(),n=(e.thirdPartyRoot??Rr)();if(!t||!n)return"unsupported";let[r,o]=await Promise.all([(e.loadProfile??L)(),(e.listPendingOps??Mn)()]);return await o3(r,o,e.toolById??Qe)?(e.inspect??EE)(t,n):"not_routed"};var c3=e=>{let t=i3();return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e};function z_(){return Le}var l3=(e,t)=>e!=="managed"?"package":t?"fleet_directive":"self",d3="ctx_doctor-probe-synthetic",u3=(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: ${Ab(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 p3(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function f3(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Ab(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 q_=e=>rp({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),kb=e=>e.tombstoned!==!0&&(e.applyBlocked===!0||e.configuredKeyStale===!0||e.pointedAt===!1&&q_(e)!=="unverifiable"),Q_=e=>e.registered&&e.command&&s3(e.command)?a3(e.command):null,m3=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."}},Cb=e=>(kb(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),h3=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,y3=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},eT=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},g3=(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(Ia),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(g=>a.has(g[0])&&r(g[1])).map(([g,y])=>({checkId:g,at:y})),p=n(l.flapping)?l.flapping:void 0,m=Array.isArray(p?.checks)?p.checks.filter(g=>typeof g=="string"&&a.has(g)):[],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},w3=async(e,t,n,r,o,a,s,i=n,c=ti,l=!0,d=ja,u=Ca,p=Ut,m=js,f=()=>yl({loadProfile:async()=>t,toolById:y=>r.find(w=>w.id===y)}),h=Uy(),g=Ln)=>{let y=l?await Yp(e):null,w=process.env.ANYRAY_CLIENT_KEY?.trim(),b=w?"env":t.clientKey?"profile":null,A=In(w||t.clientKey)??null,C=J=>J&&gg(J)?"machine_default":null,x=t.enrolledCert?.payload,O=x?.expiresAt??t.enrolledCertExpiry??null,E=(await a())?.sso??null,T=f3({ssoLink:E,enrolledViaToken:!!t.enrolledTokenHash}),I=s(),K=!x&&t.managedEnrollmentDisabled!==!0&&I.status==="valid",G=mt(),X=await QC(G),ae=X?[]:kd(Re({origin:e})),Ae=[];for(let J of r){let At=await J.detect(),To=null;if(At.installed&&J.mcpStatus)try{let ck=await J.mcpStatus();To={...ck,commandOk:Q_(ck)}}catch{}let Po=At.installed&&J.id===bo?await o():void 0,Hr=At.installed&&J.pointsAt?await J.pointsAt(e):null,Da=await h3(Hr,J,t.managedTools??[]),Il=Hr===!1&&Da===null,di=Da===!1&&J.routingPendingReload?await J.routingPendingReload().catch(()=>!1):!1,El=Da===!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:de,claudeCodeHookPolicy:ln}=z,xe=t.fleetToolPolicy,ui=xe?.enabled.includes(J.id)?xe.tiers?.[J.id]??va:void 0;Ae.push({id:J.id,title:J.title,installed:At.installed,...At.detail?{detail:At.detail}:{},pointedAt:Da,...El===!1?{configuredKeyStale:!0}:{},...Il?{routingHeld:!0}:{},...di?{routingPendingReload:!0}:{},...de.length?{routingOverrides:de}:{},...ln===void 0?{}:{claudeCodeHookPolicy:ln},mcp:To,...ui?{policyTier:ui}:{},...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}:{},...Po===void 0?{}:{inferenceIntrospectable:Po.authoritative,...Po.authoritative?{}:{inferenceUnverifiableReason:Po.reason}}})}let me=i?await(async()=>{let{kind:J,detail:At,remedy:To}=await c(Re({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:To}})():null,U=me?.kind==="provider-rejected"&&await y3(t.managedTools??[],r),Q=me?{...me,...U?{notApplicableSubscription:!0}:{}}:null,ye=n?u3(await Vs({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:be({user:t.name,team:t.team})},d3,{probe:!0}),{mode:T,ssoLink:E}):null,we=await p().catch(()=>({})),Y=or(we.hookLane),Ie=i?await eT(r):!1,cn=Ie?await(async()=>{let J=await m().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...Lw(J,{hookRegistered:Ie,neverInvoked:Pw(Y,Date.now())}),lastInvokedAt:Np(Y)}})():null,Fr=(await Mn()).map(J=>({adapter:J.adapter,op:J.op,requestedAt:J.requestedAt,watcherAlive:$n(J.watcherPid)})),Ur=Fr.find(J=>J.adapter==="cursor"),Wr=Ur?{op:Ur.op,requestedAt:Ur.requestedAt,watcherAlive:Ur.watcherAlive}:null,_o=await f().catch(()=>"unknown"),Sl=Ae.some(J=>J.id===bo&&J.installed),li;if(Sl&&_o!=="unsupported"){let J;try{J=h()}catch{J="probe_failed"}li=J==="probe_failed"?"failed":"answered"}let N=!!t.refreshSchedulerEnabled,_=await g(),V=N&&!_&&!ot(t),_e=await u(),nt=await _a(),Gt=t.anyrayFleetManaged===!0&&nt,Ct=t.persistenceOwner==="tray",Ve=Ct?await d(t)==="healthy":null,je=await MC({schedulerEnabled:N&&!Ct&&!V,schedulerInstalled:_,binaryDurable:!ut(Wo()),schedulerInstalledOnce:t.refreshSchedulerInstalledOnce===!0,trayManaged:Ct}),Te=0;y&&!y.reachable&&(Te+=1),Ct?N&&!Ve&&(Te+=1):N&&!_&&!V&&(Te+=1);for(let J of Ae)Te+=Cb(J);Q&&Q.kind!=="ok"&&!Q.notApplicableSubscription&&(Te+=1),ye&&ye.kind!=="ok"&&(Te+=1),cn?.verdict==="dark"&&(Te+=1),ae.length>0&&(Te+=1),Te+=Fr.filter(J=>!J.watcherAlive).length;let ir=await J_();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:z_(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:Nn(),fileBindMounts:await qp(),selfUpdate:{managed:_e.managed,available:_e.available,autoUpdate:_e.autoUpdate,state:_e.state,fleetMode:_e.fleetMode,updateLane:l3(_e.state,Gt)}},gateway:{origin:e,reachable:y?y.reachable:null,detail:y?y.detail:"not probed (--quick)"},refreshScheduler:{enabled:N,installed:_,owner:Ct?"tray":"os",...Ct?{trayHealthy:!!Ve}:{},...V?{retired:!0}:{}},serviceRemoval:je,fleetdPresent:nt,identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:b,keyKind:A,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:C(t.name)},enrollment:{enrolled:!!x,deploymentId:x?.deploymentId??null,issuedAt:x?.issuedAt??null,expiresAt:O,expired:O?Date.parse(O)<Date.now():null,orgMode:T,ssoLink:E,managedPending:K,managedPreference:I.status,managedPreferenceReason:I.reason??null},shell:{profilePath:G,blockPresent:X,staleExports:ae},claudeDesktopConfigCarry:_o,...li?{claudeDesktopRunningProbe:li}:{},tools:Ae,...t.fleetToolPolicy?{fleetPlan:_p(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Wr,pendingOps:Fr,ambientRepairs:g3(we,r),verify:Q,retrieval:ye,hookLane:cn,hookPolicies:ni(t.hookPolicies),hookPolicyMetrics:await ef(),agentsWindow:ir,problems:Te}},b3=e=>{if(e.serviceRemoval.suspected){if(!e.serviceRemoval.removed){W("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)k(v(` expected: ${t}`));return}W("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)k(v(` missing: ${t}`));k(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(v(" tools straight at the gateway (your key then needs a periodic re-run).")),k(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},k3=(e,t)=>{if(k(Z("Anyray connect \u2014 doctor")),e.connect.remoteContext||e.connect.fileBindMounts.length>0){W("Environment"),e.connect.remoteContext&&(k(` Remote dev context: ${Va(e.connect.remoteContext)}`),pr(e.connect.remoteContext)&&k(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)k(` Bind-mounted config file: ${c3(l)}`),k(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(W("CLI updates"),e.connect.selfUpdate.state){case"managed":B(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.fleetMode==="off"?k(v(" Your organization manages Connect updates; this machine downloads nothing.")):e.connect.selfUpdate.fleetMode==="directed"?k(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."),k(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."),k(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(v(" This copy is externally managed; update it with the method that installed it."));break;case"sidecar":k(v(" This engine is part of the desktop app, which updates the whole app."));break;case"container":k(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}if(W("Gateway"),e.gateway.reachable===null?k(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})`),k(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(W("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."),k(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")||k(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),b3(e),e.identity.keyKind==="service")W("Service key (agent)"),B(e.identity.personalKeySource==="env"?" Service key present ($ANYRAY_CLIENT_KEY).":" Service key present (stored by connect)."),k(v(" Identity and team come from the key. Not a seat: no key refresh here, and no seat health report."));else switch(W("Personal key"),p3(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."),k(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}).`),k(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."),k(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."),k(v(` Fix: ${Ab(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&&(W("Shell"),D(" This terminal still exports Anyray, but the config is gone."),k(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(v(" Anything you start from this terminal keeps reaching the gateway with")),k(v(" no credential, and fails with 401.")),k(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(v(" reuses the environment it captured at launch, so a new terminal")),k(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};W("Claude Code hook policy"),D(` ${Kl(l)}.`),k(v(` ${Vl(l)}`))}if(e.tools.some(l=>l.id===bo&&l.installed)){W("Claude Desktop profile");let l=hE[e.claudeDesktopConfigCarry];switch(e.claudeDesktopConfigCarry){case"carried":B(` ${l}.`);break;case"pending":P(` ${l}.`),k(v(" Connect completes it on the next reconcile, or the next time Claude Desktop is fully quit."));break;case"unreadable":P(` ${l}.`),k(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":k(v(` ${l}.`));break}e.claudeDesktopRunningProbe==="failed"&&(P(" Could not tell whether Claude Desktop is running: the process probe failed."),k(v(" Queued copies wait until the probe answers; check that pgrep (macOS) or tasklist (Windows) runs from this account.")))}W("Tools");let r=!1,o=!1,a=l=>{for(let d of l.routingOverrides??[])D(` ${l.title}: ${d.problem}.`),k(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}).`),k(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.`),k(v(` Fix: ${m3(l)}`))))};for(let l of e.tools){if(!l.installed){k(v(` ${l.title}: not installed (skipped)`));continue}if(l.pointedAt===null){k(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`),k(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"&&k(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===bo&&k(v(` ${QS(Tt("migrate"),Tt("desktop"))}`)),l.id==="codex"&&k(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=q_(l);if(d==="not-routed"||d==="unverifiable"){let u=op(d,{...l.inferenceUnverifiableReason?{reason:l.inferenceUnverifiableReason}:{},mcpRegistered:l.mcp?.registered===!0});P(` ${l.title}: ${u.headline}`);for(let p of u.detail)k(v(` ${p}`));d==="unverifiable"&&(o=!0)}else l.tombstoned?l.policyTier==="required"?(P(` ${l.title}: reverted locally against admin policy (out of compliance)`),k(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`):k(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`),k(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`),k(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`),k(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}`),k(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."),k(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){W("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.`),k(v(` Fix: quit ${d} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){W("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):k(m)}}let c=e.fleetPlan;if(c&&(c.freshIds.length>0||c.tombstonedIds.length>0)){W("Fleet policy");let l=d=>d.map(u=>Qe(u)?.title??u).join(", ");c.freshIds.length>0&&k(` 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(W("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)k(v(` ${l}`))}if(e.retrieval)if(W("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)k(v(` ${l}`))}if(e.hookLane){if(W("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)k(v(` ${l}`))}else{P(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let l of e.hookLane.remedy)k(v(` ${l}`))}e.hookLane.lastInvokedAt!==null&&k(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(W("VS Code Agents window"),P(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(W("VS Code Agents window"),B(` ${e.agentsWindow.detail}`)),W("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)."),k(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.`)},C3=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}),A3=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Ow(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??js,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??an)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=or((await(t.readRefreshState??Ut)().catch(()=>({}))).hookLane),l=Lw(i,{hookRegistered:await eT(t.adapters??ie).catch(()=>!1),neverInvoked:Pw(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:Np(c)},note:d}},v3=async(e,t,n={})=>{let r=n.adapters??ie,o=n.resolveTarget??Je,a=n.applyTools??tn,s=await A3(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(w=>w.installed&&(kb(w)||w.mcp?.commandOk===!1||w.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(w=>({id:w.id,title:w.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 ${Ab(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),p=[],m=[...c.notes],f=[];for(let w of l){let b=r.find(A=>A.id===w.id);if(!u.has(w.id)||!b){p.push({id:w.id,title:w.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),g=new Map,y=0;for(let w of h){if(p.push(w),!ga(w))continue;let b=e.tools.find(I=>I.id===w.id);if(!b)continue;let A=r.find(I=>I.id===w.id),C=b.mcp;if(A?.mcpStatus)try{let I=await A.mcpStatus();C={...I,commandOk:Q_(I)}}catch{}let x=kb(b)?!0:b.pointedAt;if(A?.pointsAt&&b.pointedAt!==null)try{x=await A.pointsAt(e.gateway.origin)}catch{}let O=b.routingOverrides,S=b.claudeCodeHookPolicy;if(A?.runtimeDiagnostics)try{let I=await A.runtimeDiagnostics();O=I.routingOverrides.length?I.routingOverrides:void 0,S=I.claudeCodeHookPolicy}catch{}else if(A?.routingOverrides)try{let I=await A.routingOverrides();O=I.length?I:void 0}catch{}let E=b.configuredKeyStale;if(A?.configuredKeyIsCurrent&&t.clientKey)try{let I=await A.configuredKeyIsCurrent(t.clientKey);I!==null&&(E=!I)}catch{}let T={...b,pointedAt:x,mcp:C,...E?{configuredKeyStale:!0}:{},...O?{routingOverrides:O}:{},...S===void 0?{}:{claudeCodeHookPolicy:S}};E||delete T.configuredKeyStale,O||delete T.routingOverrides,S===void 0&&delete T.claudeCodeHookPolicy,g.set(w.id,T),y+=Cb(b)-Cb(T)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:g,...s?{hookLane:s.hookLane}:{},notes:m}},S3=e=>{W("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-")?k(v(` ${t.title}: ${t.status}`)):D(` ${t.title}: ${t.status}`);for(let t of e.notes)k(v(` ${t}`))},of=async(e,t={})=>{let n=await L();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(BC({connectVersion:z_(),...l?{gatewayHost:l}:{}}),null,2)),0}if(!e.silent){k(Z("Anyray connect \u2014 security review"));for(let l of FC())k(l?` ${l}`:"")}return 0}let r;try{r=tr(e.gateway,n)}catch(l){return e.silent?1:e.json?(console.log(JSON.stringify({error:l.message})),1):(k(Z("Anyray connect \u2014 doctor")),D(` Gateway URL: ${l.message}`),k(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"})):(k(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 w3(r,n,!!e.verify&&!e.quick,t.adapters??ie,t.inferenceIntrospection??np,t.fleetBootstrap??So,t.managedPreference??ab,o,t.verifyAuth??ti,!e.quick,t.checkTray??ja,t.updateStatus??Ca,t.readRefreshState??Ut,t.probeHookLane??js,t.claudeDesktopConfigCarry??(()=>yl({loadProfile:async()=>n,toolById:l=>(t.adapters??ie).find(d=>d.id===l)})),t.claudeDesktopRunningProbe??Uy(),t.isRefreshSchedulerInstalled??Ln),s=e.repair?await v3(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(C3(i),null,2)):(k3(i,n.managedEnrollmentDisabled===!0),s&&S3(s)));let c=i.identity.keyKind!=="service";try{!e.quick&&c&&await(t.reportHealth??QR)(X_(i),i.connect.version)}catch{}return i.problems===0?0:1};var tT=async e=>{let t=await L();k(Z("Anyray connect \u2014 sync"));let n;try{n=tr(e.gateway,t)}catch(i){return D(i.message),1}M(`Gateway: ${n}`);let r=Sx(t.clientKey,"anyray-placeholder"),o;try{o=await Hs(n,r)}catch(i){return D(`Team policy sync failed: ${Ws(i)}`),1}let{summary:a,dirs:s}=await Iw(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{W("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."),W("Summary"),k(` ${it(String(a.changed))} updated, ${a.unchanged} unchanged, ${a.removed.length} removed, across ${s.length} tool dir(s).`)}try{let i=await Ew(o);i.changed.length>0&&k(`Org connectors: ${i.served?"registered":"removed"} the anyray-org MCP entry in ${i.changed.join(", ")}.`)}catch(i){M(`Org connectors sync skipped: ${Ws(i)}`)}try{let i=await Gs(o);(i.routingUpdated||i.teamUpdated||i.toolsRequested>0||i.toolsTombstoned.length>0)&&(k(`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: ${Ws(i)}`)}return 0};import{gzip as Uz}from"node:zlib";import{promisify as Wz}from"node:util";var Ro={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},vb=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),nT=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
|
|
|
@@ -814,43 +814,43 @@ ${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
|
|
|
816
816
|
`),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((p,m)=>l.has(m)?m!==c?.index?[]:[{...c.part,text:d}]:[p]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=I3.find(o=>typeof t[o]=="string");if(!n){let o=-1;for(let[a,s]of Object.entries(t))typeof s=="string"&&s.length>o&&(n=a,o=s.length)}if(!n)return null;let r=n;return{body:t[r],rebuild:o=>({...t,[r]:o})}};var E3=e=>{let t=e.trim();return t?t.length>=200&&!/\s/.test(t.slice(0,200).replace(/[{}[\],":]/g,""))?!0:/^\[?\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/.test(t)||/^\[?\d{2}:\d{2}:\d{2}/.test(t)||/^(ERROR|WARN|WARNING|INFO|DEBUG|TRACE|FATAL)\b/i.test(t)||/^\s*at\s+\S+\s+\(/.test(e)||/^\s*File ".+", line \d+/.test(e)||/^Traceback \(most recent call last\)/.test(t)||/^[{}[\]]/.test(t)||/[}\]],?$/.test(t)||/^"?[\w.-]+"?\s*[:=]\s+\S/.test(t):!1},gl={minChars:8e3,minDataLineRatio:.6,minDataLines:20},sf=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??gl.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??gl.minDataLineRatio,o=t.minDataLines??gl.minDataLines,a=e.split(`
|
|
817
|
-
`),s=0,i=0;for(let c of a)c.trim()&&(s++,E3(c)&&i++);return s===0||i<o?!1:i/s>=r};var wl=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,cf={pytest:"test-run",jest:"test-run",vitest:"test-run",mocha:"test-run",cargo:"test-run",go:"test-run",rg:"grep",grep:"grep",egrep:"grep",fgrep:"grep",ag:"grep",ack:"grep"},sT=new Set(["npm","pnpm","yarn","bun"]),lf=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},x3=e=>{let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return null;let o=lf(r[0]);if(o in cf)return cf[o];if((o==="npx"||o==="bunx")&&r[1]){let a=lf(r[1]);if(a in cf)return cf[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||sT.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},Ib=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=x3(t);if(n)return n}return null},R3={git:new Set(["log","diff","show","blame","shortlog","whatchanged"]),docker:new Set(["logs","ps","images","inspect","history","diff"]),podman:new Set(["logs","ps","images","inspect","history","diff"]),kubectl:new Set(["logs","get","describe"]),journalctl:null,dmesg:null,tsc:null,make:null,gradle:null,mvn:null,bazel:null},O3=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,_3=(e,t,n)=>{let r=(...o)=>n.some(a=>o.includes(a));return(e==="docker"||e==="podman"||e==="kubectl")&&t==="logs"||e==="journalctl"?r("-f","--follow"):e==="kubectl"&&t==="get"||e==="tsc"?r("-w","--watch"):!1},iT=e=>{if(typeof e!="string"||!e.trim())return!1;let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return!1;let o=lf(r[0]);if(sT.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&O3.test(i)}let a=r[1]?lf(r[1]):void 0;if(_3(o,a,r))return!1;let s=R3[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},T3=e=>{let t=e.trim();if(t.length<2)return!1;let n=t[0],r=t[t.length-1];return n==="{"&&r==="}"||n==="["&&r==="]"},P3=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},D3=e=>{let t=e.trim();if(t==="")return!1;let n=!0;for(let o=0;o<t.length;o++){let a=t[o];if(a!=="{"&&a!=="}"&&a!=="["&&a!=="]"&&a!==","){n=!1;break}}if(n)return!0;if(t[0]!=='"')return!1;let r=P3(t);return r>0&&t[r+1]===":"},
|
|
817
|
+
`),s=0,i=0;for(let c of a)c.trim()&&(s++,E3(c)&&i++);return s===0||i<o?!1:i/s>=r};var wl=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,cf={pytest:"test-run",jest:"test-run",vitest:"test-run",mocha:"test-run",cargo:"test-run",go:"test-run",rg:"grep",grep:"grep",egrep:"grep",fgrep:"grep",ag:"grep",ack:"grep"},sT=new Set(["npm","pnpm","yarn","bun"]),lf=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},x3=e=>{let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return null;let o=lf(r[0]);if(o in cf)return cf[o];if((o==="npx"||o==="bunx")&&r[1]){let a=lf(r[1]);if(a in cf)return cf[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||sT.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},Ib=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=x3(t);if(n)return n}return null},R3={git:new Set(["log","diff","show","blame","shortlog","whatchanged"]),docker:new Set(["logs","ps","images","inspect","history","diff"]),podman:new Set(["logs","ps","images","inspect","history","diff"]),kubectl:new Set(["logs","get","describe"]),journalctl:null,dmesg:null,tsc:null,make:null,gradle:null,mvn:null,bazel:null},O3=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,_3=(e,t,n)=>{let r=(...o)=>n.some(a=>o.includes(a));return(e==="docker"||e==="podman"||e==="kubectl")&&t==="logs"||e==="journalctl"?r("-f","--follow"):e==="kubectl"&&t==="get"||e==="tsc"?r("-w","--watch"):!1},iT=e=>{if(typeof e!="string"||!e.trim())return!1;let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return!1;let o=lf(r[0]);if(sT.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&O3.test(i)}let a=r[1]?lf(r[1]):void 0;if(_3(o,a,r))return!1;let s=R3[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},T3=e=>{let t=e.trim();if(t.length<2)return!1;let n=t[0],r=t[t.length-1];return n==="{"&&r==="}"||n==="["&&r==="]"},P3=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},D3=e=>{let t=e.trim();if(t==="")return!1;let n=!0;for(let o=0;o<t.length;o++){let a=t[o];if(a!=="{"&&a!=="}"&&a!=="["&&a!=="]"&&a!==","){n=!1;break}}if(n)return!0;if(t[0]!=='"')return!1;let r=P3(t);return r>0&&t[r+1]===":"},N3=80,L3=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/N3),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,D3(e[o])&&r++;return n>0&&r/n>.3},$3=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,M3=e=>{let t=e.slice(0,80);if(t.length===0)return!1;let n=0;for(let r of t){let o=r.trim();($3.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},B3=[/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b.*\bin\s+[\d.]+\s*s/i,/^=+ FAILURES =+/m,/^=+ short test summary/im,/test session starts/i,/^Test Suites:\s+\d+/m,/^Tests:\s+\d+\s+(failed|passed|total)/m,/^test result:\s+(ok|FAILED)\b/m,/^running \d+ tests?$/m,/^--- (FAIL|PASS): /m,/^(ok|FAIL)\s+\S+\s+[\d.]+s/m],Sb=8192,F3=e=>{let t=e.length>2*Sb?`${e.slice(0,Sb)}
|
|
818
818
|
${e.slice(-Sb)}`:e;return B3.some(n=>n.test(t))},U3=e=>/^[=~_—-]{4,}$/.test(e)||/^=+ .* =+$/.test(e)||/test session starts/i.test(e)||/^platform /i.test(e)||/^(rootdir|cachedir|configfile|plugins):/i.test(e)||/^collected \d+ items?/i.test(e)||/^Ran all test suites/.test(e)||/^(Snapshots|Time):/.test(e)||/^running \d+ tests?$/.test(e)||/^=== RUN /.test(e),W3=e=>/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b/i.test(e)&&/\bin\s+[\d.]+\s*s/i.test(e)||/^Test Suites:\s+\d+/.test(e)||/^Tests:\s+\d+/.test(e)||/^test result:\s+(ok|FAILED)\b/.test(e)||/^FAIL\s+\S+\s+[\d.]+s$/.test(e),H3=e=>{let t=/^_{2,}\s*(.+?)\s*_{2,}$/.exec(e);return t?`FAIL: ${t[1]}`:/^FAIL\s+\S+/.test(e)&&!/\s[\d.]+s$/.test(e)||/^--- FAIL: /.test(e)||/^---- .+ (stdout|stderr) ----$/.test(e)?e:null},G3=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),oT=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(W3(i)){t.push(wl(i));continue}let c=H3(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(wl(c)),o=12;continue}U3(i)||G3(i)||o>0&&(t.push(wl(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
|
|
819
819
|
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},K3=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,cT=e=>{let t=K3.exec(e);return t&&/[/.]/.test(t[1])?t:null},V3=/^([^\s:]+)-(\d+)-/,j3=e=>{if(e==="--")return!0;let t=V3.exec(e);return t!=null&&/[/.]/.test(t[1])},Y3=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>cT(r)!=null).length;return n>=3&&n/t.length>=.7},aT=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=cT(c);if(!l){if(j3(c))return null;r++;continue}o++;let d=n.get(l[1])??[];d.push({line:l[2],content:l[3]}),n.set(l[1],d)}if(o===0||o/(o+r)<t)return null;let a=[`${o} matches in ${n.size} files:`],s=0,i=!1;for(let[c,l]of n){if(s>=200){i=!0;break}a.push("",`${c}:`);let d=Math.min(l.length,25,200-s);for(let u of l.slice(0,d))a.push(wl(` ${u.line}: ${u.content.trim()}`)),s++;l.length>d&&a.push(` \u2026+${l.length-d} more in this file`)}return i&&a.push("",`\u2026+${o-s} more matches elided`),{text:a.join(`
|
|
820
820
|
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},Z3=e=>e.replace(/\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d(?:\.\d+)?Z?/g,"<TS>").replace(/\b\d\d:\d\d:\d\d\b/g,"<TS>").replace(/\b[0-9a-f]{2,}(?:-[0-9a-f]{2,}){2,}\b/gi,"<ID>").replace(/\b0x[0-9a-f]+\b/gi,"<HEX>").replace(/\b\d{8,}\b/g,"<NUM>").trim(),J3=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=Z3(o),s=t.get(a);s?s.n++:(t.set(a,{first:o,n:1}),n.push(a))}return n.length/e.length>.6?null:{text:n.map(o=>{let{first:a,n:s}=t.get(o),i=wl(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
|
|
821
821
|
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},lT=(e,t)=>{if(typeof t!="string"||t.length===0||T3(t))return null;let n=t.split(`
|
|
822
|
-
`).filter(s=>s.trim()!==""),r=Ib(e),o=F3(t),a=null;return r==="test-run"&&o?a=oT(n):r==="grep"&&(a=aT(n,.5)),a||(o?a=oT(n):Y3(n)?a=aT(n,.7):!M3(n)&&!
|
|
822
|
+
`).filter(s=>s.trim()!==""),r=Ib(e),o=F3(t),a=null;return r==="test-run"&&o?a=oT(n):r==="grep"&&(a=aT(n,.5)),a||(o?a=oT(n):Y3(n)?a=aT(n,.7):!M3(n)&&!L3(n)&&(a=J3(n))),!a||a.text.length>=t.length?null:a},dT=e=>`full output: Read ${e}`,Eb=(e,t)=>t?`
|
|
823
823
|
|
|
824
824
|
\u2026[anyray-hook digest \u2014 ${e}; ${dT(t)}]\u2026`:`
|
|
825
825
|
|
|
826
826
|
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,uT=e=>`
|
|
827
827
|
|
|
828
|
-
\u2026[anyray-hook \u2014 ${dT(e)}]\u2026`;import{createHash as X3}from"node:crypto";import{homedir as z3}from"node:os";import{join as Oo}from"node:path";import{chmod as q3,mkdir as Q3,readdir as hT,stat as kl,unlink as bl,utimes as ez,writeFile as Rb}from"node:fs/promises";var df={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},yT=".swept",tz=".sweeping",pT=64,fT=448,Ob=384,_b=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",gT=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,Tb=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=ee();try{if((await kl(t)).isDirectory())return Oo(t,"hook-tee")}catch{}return Oo(z3(),".anyray-hook-tee")},nz=/^(?:ctx_)?([0-9a-f]{16})$/,Pb=e=>e.trim().match(nz)?.[1]??null,Db=async e=>{let t=Pb(e);return t?Oo(await Tb(),`${t}.txt`):null},rz=async(e,t={})=>{let n=t.limits??df;try{let r=Date.now(),o=(await hT(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=pT)await Promise.all(o.slice(c,c+pT).map(async l=>{let d=Oo(e,l);try{let u=await kl(d);if(!u.isFile())return;let p=r-u.mtimeMs>n.ttlMs||r-gT(u)>n.maxAgeMs;if(d!==t.protect&&p){await bl(d);return}a.push({path:d,mtimeMs:u.mtimeMs,size:u.size})}catch{}}));a.sort((c,l)=>l.mtimeMs-c.mtimeMs);let s=0,i=0;for(let c of a){let l=s<n.maxFiles&&i+c.size<=n.maxTotalBytes,d=r-c.mtimeMs<n.writeGraceMs;if(l||s===0||c.path===t.protect||d){s+=1,i+=c.size;continue}await bl(c.path).catch(()=>{})}}catch{}},wT=async e=>{try{return Date.now()-(await kl(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},mT=async e=>{try{return await Rb(e,"",{mode:Ob,flag:"wx"}),!0}catch{return!1}},oz=async(e,t)=>{let n=df,r=Oo(e,tz),o=Oo(e,yT);if(!await mT(r)){let a=0;try{a=Date.now()-(await kl(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await bl(r).catch(()=>{}),!await mT(r)))return!1}try{return await wT(o)<n.sweepIntervalMs?!1:(await Rb(o,"",{mode:Ob}).catch(()=>{}),await rz(e,{protect:t}),!0)}finally{await bl(r).catch(()=>{})}},xb=async(e,t)=>await wT(Oo(e,yT))<df.sweepIntervalMs?!1:oz(e,t),az=async()=>{try{let e=await Tb();if(!(await hT(e)).some(t=>t.endsWith(".txt")))return;await xb(e)}catch{}},uf=async e=>{if(_b())return await az(),null;try{let t=await Tb();await Q3(t,{recursive:!0,mode:fT}),await q3(t,fT).catch(()=>{});let n=`${X3("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=Oo(t,n),o=Date.now();try{let a=await kl(r);if(a.isFile()){if(o-gT(a)<=df.maxAgeMs){let s=new Date(o);return await ez(r,s,s).catch(()=>{}),await xb(t,r),r}await bl(r).catch(()=>{})}}catch{}return await Rb(r,e,{mode:Ob}),await xb(t,r),r}catch{return null}};import{createHash as sz}from"node:crypto";import{homedir as bT}from"node:os";import{join as
|
|
828
|
+
\u2026[anyray-hook \u2014 ${dT(e)}]\u2026`;import{createHash as X3}from"node:crypto";import{homedir as z3}from"node:os";import{join as Oo}from"node:path";import{chmod as q3,mkdir as Q3,readdir as hT,stat as kl,unlink as bl,utimes as ez,writeFile as Rb}from"node:fs/promises";var df={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},yT=".swept",tz=".sweeping",pT=64,fT=448,Ob=384,_b=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",gT=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,Tb=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=ee();try{if((await kl(t)).isDirectory())return Oo(t,"hook-tee")}catch{}return Oo(z3(),".anyray-hook-tee")},nz=/^(?:ctx_)?([0-9a-f]{16})$/,Pb=e=>e.trim().match(nz)?.[1]??null,Db=async e=>{let t=Pb(e);return t?Oo(await Tb(),`${t}.txt`):null},rz=async(e,t={})=>{let n=t.limits??df;try{let r=Date.now(),o=(await hT(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=pT)await Promise.all(o.slice(c,c+pT).map(async l=>{let d=Oo(e,l);try{let u=await kl(d);if(!u.isFile())return;let p=r-u.mtimeMs>n.ttlMs||r-gT(u)>n.maxAgeMs;if(d!==t.protect&&p){await bl(d);return}a.push({path:d,mtimeMs:u.mtimeMs,size:u.size})}catch{}}));a.sort((c,l)=>l.mtimeMs-c.mtimeMs);let s=0,i=0;for(let c of a){let l=s<n.maxFiles&&i+c.size<=n.maxTotalBytes,d=r-c.mtimeMs<n.writeGraceMs;if(l||s===0||c.path===t.protect||d){s+=1,i+=c.size;continue}await bl(c.path).catch(()=>{})}}catch{}},wT=async e=>{try{return Date.now()-(await kl(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},mT=async e=>{try{return await Rb(e,"",{mode:Ob,flag:"wx"}),!0}catch{return!1}},oz=async(e,t)=>{let n=df,r=Oo(e,tz),o=Oo(e,yT);if(!await mT(r)){let a=0;try{a=Date.now()-(await kl(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await bl(r).catch(()=>{}),!await mT(r)))return!1}try{return await wT(o)<n.sweepIntervalMs?!1:(await Rb(o,"",{mode:Ob}).catch(()=>{}),await rz(e,{protect:t}),!0)}finally{await bl(r).catch(()=>{})}},xb=async(e,t)=>await wT(Oo(e,yT))<df.sweepIntervalMs?!1:oz(e,t),az=async()=>{try{let e=await Tb();if(!(await hT(e)).some(t=>t.endsWith(".txt")))return;await xb(e)}catch{}},uf=async e=>{if(_b())return await az(),null;try{let t=await Tb();await Q3(t,{recursive:!0,mode:fT}),await q3(t,fT).catch(()=>{});let n=`${X3("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=Oo(t,n),o=Date.now();try{let a=await kl(r);if(a.isFile()){if(o-gT(a)<=df.maxAgeMs){let s=new Date(o);return await ez(r,s,s).catch(()=>{}),await xb(t,r),r}await bl(r).catch(()=>{})}}catch{}return await Rb(r,e,{mode:Ob}),await xb(t,r),r}catch{return null}};import{createHash as sz}from"node:crypto";import{homedir as bT}from"node:os";import{join as Nb}from"node:path";import{readFile as iz,writeFile as cz,chmod as lz,stat as dz,unlink as uz}from"node:fs/promises";var pz=200,fz=1440*60*1e3,mz=4e6,kT=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",CT=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},hz=()=>CT("ANYRAY_HOOK_CACHE_MAX_ENTRIES",pz),AT=()=>CT("ANYRAY_HOOK_CACHE_TTL_MS",fz),vT=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Nb(bT(),".anyray");try{if((await dz(t)).isDirectory())return Nb(t,"hook-cache.json")}catch{}return Nb(bT(),".anyray-hook-cache.json")},ST=(e,t,n)=>sz("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),IT=async e=>{try{let t=JSON.parse(await iz(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},ET=async e=>{if(kT())return null;try{let n=(await IT(await vT())).entries[e];return!n||Date.now()-n.at>AT()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},yz=e=>{let t=Date.now(),n=AT(),r=Object.entries(e).filter(([,i])=>t-i.at<=n);r.sort((i,c)=>c[1].at-i[1].at);let o=[],a=0,s=hz();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>mz&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},xT=async(e,t)=>{if(kT())return;let n;try{let r=await vT(),o=await IT(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=yz(o.entries),n=`${r}.${process.pid}.tmp`,await cz(n,JSON.stringify(o),{mode:384}),await lz(n,384),await ke(n,r)}catch{if(n)try{await uz(n)}catch{}}};import{open as gz,stat as wz}from"node:fs/promises";var RT=600,bz=3,kz=256e3,Cz=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
829
829
|
`):"",Az=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),vz=e=>{let t=[];for(let n of e)if(!(!n||!n.trim()))try{let r=JSON.parse(n);r&&typeof r=="object"&&!Array.isArray(r)&&t.push(r)}catch{}return t},Sz=e=>{let t=[],n=0;for(let r=e.length-1;r>=0;r--){let o=e[r];if(!o||o.type!=="user"||o.isMeta||o.isSidechain)continue;let a=Cz(o.message?.content).trim();if(!(!a||Az(a))&&(t.unshift(a),n+=a.length,t.length>=bz||n>=RT))break}return t.join(`
|
|
830
|
-
`).slice(0,RT)};var Iz=e=>/(^|[\\/])subagents[\\/]/i.test(e),Ez=e=>/\.jsonl$/i.test(e),xz=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),Rz=e=>{let t=new Set,n=!1;for(let r of e)if(!(r.isSidechain||!Array.isArray(r.message?.content)))for(let o of r.message.content)!o||typeof o!="object"||(r.type==="assistant"&&o.type==="tool_use"&&o.name==="mcp__anyray__anyray_retrieve"&&typeof o.id=="string"&&t.add(o.id),r.type==="user"&&o.type==="tool_result"&&typeof o.tool_use_id=="string"&&t.has(o.tool_use_id)&&(n=o.is_error!==!0));return n},
|
|
830
|
+
`).slice(0,RT)};var Iz=e=>/(^|[\\/])subagents[\\/]/i.test(e),Ez=e=>/\.jsonl$/i.test(e),xz=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),Rz=e=>{let t=new Set,n=!1;for(let r of e)if(!(r.isSidechain||!Array.isArray(r.message?.content)))for(let o of r.message.content)!o||typeof o!="object"||(r.type==="assistant"&&o.type==="tool_use"&&o.name==="mcp__anyray__anyray_retrieve"&&typeof o.id=="string"&&t.add(o.id),r.type==="user"&&o.type==="tool_result"&&typeof o.tool_use_id=="string"&&t.has(o.tool_use_id)&&(n=o.is_error!==!0));return n},Lb=async e=>{let t={intent:"",kind:"unknown",retrieveAvailable:!1};if(!e||!Ez(e))return t;let n;try{let{size:r}=await wz(e),o=Math.max(0,r-kz),a=r-o;if(a<=0)return t;n=await gz(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=vz(i.split(`
|
|
832
|
-
`));return xz(c)?{intent:Sz(c),kind:Iz(e)?"subagent":"main",retrieveAvailable:Rz(c)}:t}catch{return t}finally{try{await n?.close()}catch{}}};import{open as Pz}from"node:fs/promises";import{constants as DT}from"node:fs";import{createHash as Dz}from"node:crypto";import{basename as
|
|
832
|
+
`));return xz(c)?{intent:Sz(c),kind:Iz(e)?"subagent":"main",retrieveAvailable:Rz(c)}:t}catch{return t}finally{try{await n?.close()}catch{}}};import{open as Pz}from"node:fs/promises";import{constants as DT}from"node:fs";import{createHash as Dz}from"node:crypto";import{basename as Nz,isAbsolute as Lz}from"node:path";var OT=e=>{if(e.length>16384||/[\n\r`$;|<>()[\]{}]/.test(e))return!1;let t=e.match(/"[^"\n]*"|'[^'\n]*'|&&|[^\s&"']+/g)??[];if(t.join("").replace(/\s/g,"")!==e.replace(/\s/g,""))return!1;let n=[[]];for(let i of t)i==="&&"?n.push([]):n.at(-1).push(i);let r=i=>/^(["']).*\1$/.test(i)?i.slice(1,-1):i,o=i=>r(i).split("/").at(-1)??"",a=/^(?:test|lint|build|typecheck|type-check|check|compile)(?::[\w-]+)*$/,s=0;for(let[i,c]of n.entries()){let l=[...c];for(;l[0]&&/^[A-Za-z_]\w*=/.test(l[0]);)l.shift();let d=o(l.shift()??"");if(d==="cd"&&i<n.length-1&&l.length===1)continue;if(l.map(r).some(p=>/^--?(?:bench(?:mem)?|cov[^=]*|coverage[^=]*|durations[^=]*|verbose|reporter|watch[^=]*|nocapture|show-output)(?:=|$)/.test(p)||/^--capture=(?:no|tee-sys)$/.test(p)||/^-[qvsx]*[vs][qvsx]*$/.test(p)||p==="-w"))return!1;let u=!1;if(d==="go"||d==="cargo")u=["test","build","check"].includes(l[0]);else if(d==="make")u=l.length>0&&l.every(p=>a.test(p));else if(d==="golangci-lint")u=l[0]==="run";else if(["pytest","pytest-3","vitest","jest","tsc","eslint"].includes(d))u=!0;else if(/^python(?:3(?:\.\d+)?)?$/.test(d))u=l[0]==="-m"&&l[1]==="pytest";else if(["npx","bunx"].includes(d))l[0]==="--no-install"&&l.shift(),u=["vitest","jest","tsc","eslint"].includes(o(l[0]??""));else if(["npm","pnpm","yarn","bun"].includes(d)){for(;["--prefix","--cwd","-C","--filter","-F","--workspace","-w"].includes(l[0]);){if(l.length<3)return!1;l.splice(0,2)}["run","run-script","exec"].includes(l[0])&&l.shift(),u=a.test(l[0]??"")||["t","vitest","jest","tsc","eslint"].includes(l[0])}if(!u)return!1;s++}return s>0},$b=e=>e.replace(/\x1b\[[0-9;]*[A-Za-z]/g,""),Oz=/^> [^\s]+@[\w.+-]+ (?:test|lint|build|typecheck|check|compile)[^\n]*\n(?:> [^\n]*\n)?/gm,pf=e=>{let t=$b(e).replace(Oz,"").split(`
|
|
833
833
|
`).map(n=>{let r=n.trim();return/^test result: ok\./.test(r)?n.replace(/\b0 failed\b/g,""):/^(?:0 fail|# fail 0|Found 0 errors\.?)$/.test(r)?"":n}).join(`
|
|
834
|
-
`);return/\b(?:fail(?:ed|ure|ures)?|panic|error|errors|traceback|assertionerror)\b|\bnot ok\b|^[ \t]*(?:[-+] |[-+](?!-{2} (?:PASS|SKIP)[: ]|-[ ]Docs:)\S|[<>] |E\s+assert\b)|assertion (?:failed|diff)/im.test(t)},_z=e=>/^(?:[✓✔]\s+\S+\s+\(\d+ tests?\)\s+\d+ms\s*$|PASS\s*$|ok\s+\S+\s+(?:[\d.]+s|\(cached\))|\?\s+\S+\s+\[no test files\]|Test (?:Files|Suites):?\s+\d+|Tests:?\s+\d+|Snapshots:\s+\d+|Time:\s+\d|Duration\s+\d|Start at\s+\d|test result: ok\.|running \d+ tests|\d+ (?:pass|fail|skip)$|\d+ issues?\.?$|Found 0 errors\b|[= ]*\d+ passed\b|[= ]*\d+ (?:skipped|deselected)\b|✓ built in\s|Finished .+ target\(s\) in\s|# (?:tests|suites|pass|fail|cancelled|skipped|todo|duration_ms) \d)/.test(e.trim()),Tz=e=>/^(?:\s*$|> |RUN v[\d.]+ \S+\s*$|=== (?:RUN|PAUSE|CONT|NAME)\s+\S+\s*$|--- (?:PASS|SKIP): \S+ \([\d.]+s\)\s*$|test \S+ \.{3} (?:ok|ignored)\s*$|[.·]+\s*$|\S+\.py [ .s]+\s+\[100%\]\s*$)/.test(e.trim()),_T=e=>{if(pf(e))return null;let t=e.match(/[^\n]*\n|[^\n]+$/g)??[],n=new Set,r=0,o=-1;for(let a=0;a<t.length;a++){let s=$b(t[a]);if(_z(s)&&(n.add(a),r++),a>o&&/\b(?:warn(?:ing|ings)?|deprecated|deprecation\w*)\b/i.test(s)){let i=a,c=/warnings summary/i.test(s);if(!c)for(;i>0&&t[i-1].trim();)i--;let l=a;if(c)l=t.length-1;else for(;l+1<t.length&&t[l+1].trim();)l++;for(let d=i;d<=l;d++)n.add(d);o=l}}return r===0||n.size===t.length||t.some((a,s)=>!n.has(s)&&!Tz($b(a)))?null:{text:t.filter((a,s)=>n.has(s)).join(""),hiddenLines:t.length-n.size}},TT=(e,t)=>`[anyray: ${e} lines of passing output hidden; retrieve ${t}]`,PT=e=>`[anyray: identical to your earlier Read of this file in this conversation; retrieve ${e} for the bytes]`;var Ta=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,Mb=e=>{for(let t of["tool_output","tool_response","tool_result"])if(t in e)return e[t]},$z=e=>{if(e.hook_event_name==="PostToolUseFailure")return!1;let t=Ta(Mb(e)),n=[e,...t?[t]:[]],r=n.flatMap(o=>["exit_code","exitCode"].filter(a=>a in o).map(a=>o[a]));return r.length>0&&r.every(o=>o===0)&&n.every(o=>!o.interrupted&&!o.is_error&&!o.isError&&!o.error)},Mz=async e=>{let t=await Pz(e,DT.O_RDONLY|DT.O_NONBLOCK).catch(()=>null);if(!t)return null;try{if(!(await t.stat()).isFile())return null;let n=Dz("sha256"),r=Buffer.alloc(64*1024),o=0;for(;;){let{bytesRead:a}=await t.read(r,0,r.length,null);if(a===0)return n.digest("hex");if(o+=a,o>16*1024*1024)return null;n.update(r.subarray(0,a))}}catch{return null}finally{await t.close().catch(()=>{})}},
|
|
834
|
+
`);return/\b(?:fail(?:ed|ure|ures)?|panic|error|errors|traceback|assertionerror)\b|\bnot ok\b|^[ \t]*(?:[-+] |[-+](?!-{2} (?:PASS|SKIP)[: ]|-[ ]Docs:)\S|[<>] |E\s+assert\b)|assertion (?:failed|diff)/im.test(t)},_z=e=>/^(?:[✓✔]\s+\S+\s+\(\d+ tests?\)\s+\d+ms\s*$|PASS\s*$|ok\s+\S+\s+(?:[\d.]+s|\(cached\))|\?\s+\S+\s+\[no test files\]|Test (?:Files|Suites):?\s+\d+|Tests:?\s+\d+|Snapshots:\s+\d+|Time:\s+\d|Duration\s+\d|Start at\s+\d|test result: ok\.|running \d+ tests|\d+ (?:pass|fail|skip)$|\d+ issues?\.?$|Found 0 errors\b|[= ]*\d+ passed\b|[= ]*\d+ (?:skipped|deselected)\b|✓ built in\s|Finished .+ target\(s\) in\s|# (?:tests|suites|pass|fail|cancelled|skipped|todo|duration_ms) \d)/.test(e.trim()),Tz=e=>/^(?:\s*$|> |RUN v[\d.]+ \S+\s*$|=== (?:RUN|PAUSE|CONT|NAME)\s+\S+\s*$|--- (?:PASS|SKIP): \S+ \([\d.]+s\)\s*$|test \S+ \.{3} (?:ok|ignored)\s*$|[.·]+\s*$|\S+\.py [ .s]+\s+\[100%\]\s*$)/.test(e.trim()),_T=e=>{if(pf(e))return null;let t=e.match(/[^\n]*\n|[^\n]+$/g)??[],n=new Set,r=0,o=-1;for(let a=0;a<t.length;a++){let s=$b(t[a]);if(_z(s)&&(n.add(a),r++),a>o&&/\b(?:warn(?:ing|ings)?|deprecated|deprecation\w*)\b/i.test(s)){let i=a,c=/warnings summary/i.test(s);if(!c)for(;i>0&&t[i-1].trim();)i--;let l=a;if(c)l=t.length-1;else for(;l+1<t.length&&t[l+1].trim();)l++;for(let d=i;d<=l;d++)n.add(d);o=l}}return r===0||n.size===t.length||t.some((a,s)=>!n.has(s)&&!Tz($b(a)))?null:{text:t.filter((a,s)=>n.has(s)).join(""),hiddenLines:t.length-n.size}},TT=(e,t)=>`[anyray: ${e} lines of passing output hidden; retrieve ${t}]`,PT=e=>`[anyray: identical to your earlier Read of this file in this conversation; retrieve ${e} for the bytes]`;var Ta=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,Mb=e=>{for(let t of["tool_output","tool_response","tool_result"])if(t in e)return e[t]},$z=e=>{if(e.hook_event_name==="PostToolUseFailure")return!1;let t=Ta(Mb(e)),n=[e,...t?[t]:[]],r=n.flatMap(o=>["exit_code","exitCode"].filter(a=>a in o).map(a=>o[a]));return r.length>0&&r.every(o=>o===0)&&n.every(o=>!o.interrupted&&!o.is_error&&!o.isError&&!o.error)},Mz=async e=>{let t=await Pz(e,DT.O_RDONLY|DT.O_NONBLOCK).catch(()=>null);if(!t)return null;try{if(!(await t.stat()).isFile())return null;let n=Dz("sha256"),r=Buffer.alloc(64*1024),o=0;for(;;){let{bytesRead:a}=await t.read(r,0,r.length,null);if(a===0)return n.digest("hex");if(o+=a,o>16*1024*1024)return null;n.update(r.subarray(0,a))}}catch{return null}finally{await t.close().catch(()=>{})}},NT=(e,t)=>({originalChars:e.length,trimmedChars:t.length,estTokensSaved:Math.round((e.length-t.length)/4)}),LT=async(e,t)=>{let n=await(t.tee??uf)(e),r=n&&Nz(n).match(/^([0-9a-f]{16})\.txt$/)?.[1];return r?`ctx_${r}`:null},Bz=async(e,t)=>{let n=Ta(e.tool_input);if(!t.canRetrieve||typeof n?.command!="string"||!OT(n.command)||!$z(e))return null;let r=Mb(e),o=Ta(r),a=typeof r=="string"?r:typeof o?.stdout=="string"?o.stdout:null;if(a===null||o&&o.stderr!==void 0&&typeof o.stderr!="string")return null;let s=typeof o?.stderr=="string"?o.stderr:"";if(pf(a)||pf(s))return null;let i=_T(a);if(!i)return null;let c=u=>i.text+(i.text.endsWith(`
|
|
835
835
|
`)?"":`
|
|
836
|
-
`)+TT(i.hiddenLines,u);if(c("ctx_0000000000000000").length>=a.length)return null;let l=await
|
|
836
|
+
`)+TT(i.hiddenLines,u);if(c("ctx_0000000000000000").length>=a.length)return null;let l=await LT(a,t);return l?{replacement:o?{...o,stdout:c(l)}:c(l),metrics:NT(a,c(l))}:null},Fz=e=>{let t=Ta(e);if(!t||t.is_error||t.isError||t.error)return null;let n=Ta(t.file);return t.type==="text"&&typeof n?.content=="string"?{body:n.content,rebuild:r=>({...t,file:{...n,content:r}})}:null},$T=async(e,t)=>{if(!t.mainTranscript)return null;let n=gb(e);if(!n||!t.policies.greenCollapse&&!t.policies.rereadStub)return null;try{let r=Mb(e),o=Ta(r),a=Ta(e.tool_input),s=e.hook_event_name==="PostToolUseFailure"||e.is_error===!0||o?.is_error===!0||o?.isError===!0||!!o?.error||typeof r=="string"&&/^(?:Error:|<tool_use_error>)/.test(r),i=g=>g===void 0||typeof g=="number"&&Number.isSafeInteger(g)&&g>=1,c=t.policies.rereadStub&&e.tool_name==="Read"&&t.canRetrieve&&!s&&typeof a?.file_path=="string"&&Lz(a.file_path)&&i(a.offset)&&i(a.limit)?Fz(r):null,l=c?await(t.fileHash??Mz)(a.file_path):null,d=c?Br(c.body):null,u=c?Br(JSON.stringify([a.file_path,a.offset??null,a.limit??null])):null,p=await tf(async g=>{let y=wb(g,n);if(typeof e.tool_use_id=="string"&&e.tool_use_id.length>0){let b=Br(e.tool_use_id);if(y.seen.includes(b))return null;y.seen=[...y.seen.slice(-255),b]}j_(y,g.metrics,e.tool_name==="Edit"&&s,e.tool_name==="mcp__anyray__anyray_retrieve"&&typeof a?.handle=="string"?a.handle:null,s);let w=!1;if(c&&l&&d&&u&&y.lifecycleReady){let b=y.reads.find(A=>A.key===u);w=!!(b&&b.fileHash===l&&b.outputHash===d),w||(y.reads=y.reads.filter(A=>A.key!==u).slice(-255),y.reads.push({key:u,fileHash:l,outputHash:d,handle:`ctx_${d.slice(0,16)}`,turn:y.turn}))}return{epoch:y.epoch,repeat:w}});if(!p)return null;let m=null,f="green",h=null;if(p.repeat&&c&&d){h=`ctx_${d.slice(0,16)}`;let g=PT(h);if(g.length>=c.body.length||await LT(c.body,t)!==h)return null;m={replacement:c.rebuild(g),metrics:NT(c.body,g)},f="reread"}else if(e.tool_name==="Bash"&&t.policies.greenCollapse&&(m=await Bz(e,t),m)){let g=typeof r=="string"?r:o?.stdout;typeof g=="string"&&(h=`ctx_${Br(g).slice(0,16)}`)}return!m||!h?null:await tf(async g=>{let y=g.sessions.find(w=>w.key===n);return!y||y.epoch!==p.epoch||f==="reread"&&(!y.lifecycleReady||!y.reads.some(w=>w.key===u&&w.fileHash===l&&w.outputHash===d))?null:(f==="reread"?g.metrics.rereadStubs++:g.metrics.greenCollapses++,y.pending.push({turn:y.turn,failed:!1,kind:f,handle:h}),y.pending.length>5&&(y.pending.shift(),g.metrics.censoredWindows++),m)})}catch{return null}};var Hz=3e3,Gz=1500,Kz=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Hz},Vz={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},jz=new Set(["claude","opencode"]),Yz=(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:Vz[t]})},Zz={cacheGet:async()=>null,cachePut:async()=>{}},Jz=(e,t={cacheGet:ET,cachePut:xT,tee:uf})=>e==="claude"?t:Zz,Xz=1e3,MT=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),Cl=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),zz=e=>{try{let t=JSON.parse(e);if(!Cl(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 Cl(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},qz=e=>{try{let t=JSON.parse(e);return Cl(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},Qz=e=>Cl(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
837
837
|
`:"",Bb=e=>Math.round(Math.max(0,e)/4),BT=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",e9=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),t9=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),n9=["tool_output","tool_response","tool_result"],r9=e=>{for(let t of n9)if(t in e)return e[t]},o9=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},a9=120,s9=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??Xz))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=Eb(r.stat,null).length+a9;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=Eb(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}}},i9=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(t.sourcePolicies)try{let x=await t.sourcePolicies(r);if(x!==null){if(x.replacement===void 0)return n;if(x.metrics)try{await t.beacon(o,x.metrics)}catch{}return{stdout:MT(x.replacement),replacement:x.replacement}}}catch{return n}if(r.hook_event_name==="PostToolUseFailure"||e9.has(o)||t9(o))return n;let a=rT(r9(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(UT(o)&&l.retrievalContext!=="available")return n;let d=await s9(t,o9(o,r.tool_input),i),u=d?.body??i,p=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!sf(i,{minChars:Gz})))return n;let m=i.length-u.length-p.length,f=async(x,O,S=x.length+p.length)=>{let E=d?.teePath??null;if(!E&&t.tee)try{E=await t.tee(i)}catch{E=null}let T=E?x.replaceAll("; not retrievable in this context]","]"):x,I=E&&!p?uT(E):"",K=T+p+I,G=I.length,X=K;if(t.finalizeOutput)try{let U=t.finalizeOutput(K);U.length<=K.length&&(X=U)}catch{X=K}let ae=K.length-X.length,Ae=Bb(Math.max(0,m-G))+O+Bb(ae);Ae>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,S+G-ae),estTokensSaved:Ae,...d&&{digest:d.decision}});let me=a.rebuild(X);return{stdout:MT(me),replacement:me}},h=async()=>d?f(u,0):n;if(d&&u.length<=t.sizeGate)return f(u,0);let g=l.intent?`${l.intent}
|
|
838
|
-
${BT(r.tool_input)}`:BT(r.tool_input),y=ST(o,g,u),w=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 A=null;try{A=f9(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{A=null}if(A&&!A.handled&&(A=null),A)return A.optimized&&A.output.length<u.length?(await w({optimized:!0,output:A.output,tokensSaved:Bb(u.length-A.output.length)}),f(A.output,0,u.length+p.length)):(await w({optimized:!1}),h());let C;try{C=t.localTrim(u)}catch{return h()}return C.trimmed?f(C.text,C.estTokensSaved):h()},ai=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},FT=async()=>{try{let e=JSON.parse(await ai());Cl(e)&&await Y_(e)}catch{}return 0},c9=()=>{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")}},l9=Wz(Uz),d9=async e=>{try{let t=await l9(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},UT=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),u9=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},p9=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),f9=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),m9=2048,h9=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,m9),n=Dp(t);if(!n)return;await SO({at:Date.now(),status:e.status,code:n})}catch{}},y9=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),Kz());try{let c=await d9(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...UT(t)||u9(t)&&a==="available"?{reversible:!0}:{},...p9(t)?{semanticRerank:!0}:{},output:r})),l=fn(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 h9(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)}},WT=async(e="claude")=>{let t=await ai();if(e!=="cursor"&&qz(t))return 0;let n=e==="cursor"?zz(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Fb(n,e);if(e==="cursor"){let a=Qz(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Fb=async(e,t="claude",n)=>{await Eo(),await vO(t);let r=c9(),o=await pt(),a=o&&{...o,metadata:Yz(o.metadata,t)},s=Jz(t),i=ni((await
|
|
839
|
-
`),i9(e,{...t==="claude"&&(i.greenCollapse||i.rereadStub)?{sourcePolicies:async c=>{let l=await
|
|
838
|
+
${BT(r.tool_input)}`:BT(r.tool_input),y=ST(o,g,u),w=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 A=null;try{A=f9(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{A=null}if(A&&!A.handled&&(A=null),A)return A.optimized&&A.output.length<u.length?(await w({optimized:!0,output:A.output,tokensSaved:Bb(u.length-A.output.length)}),f(A.output,0,u.length+p.length)):(await w({optimized:!1}),h());let C;try{C=t.localTrim(u)}catch{return h()}return C.trimmed?f(C.text,C.estTokensSaved):h()},ai=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},FT=async()=>{try{let e=JSON.parse(await ai());Cl(e)&&await Y_(e)}catch{}return 0},c9=()=>{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")}},l9=Wz(Uz),d9=async e=>{try{let t=await l9(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},UT=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),u9=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},p9=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),f9=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),m9=2048,h9=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,m9),n=Dp(t);if(!n)return;await SO({at:Date.now(),status:e.status,code:n})}catch{}},y9=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),Kz());try{let c=await d9(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...UT(t)||u9(t)&&a==="available"?{reversible:!0}:{},...p9(t)?{semanticRerank:!0}:{},output:r})),l=fn(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 h9(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)}},WT=async(e="claude")=>{let t=await ai();if(e!=="cursor"&&qz(t))return 0;let n=e==="cursor"?zz(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Fb(n,e);if(e==="cursor"){let a=Qz(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Fb=async(e,t="claude",n)=>{await Eo(),await vO(t);let r=c9(),o=await pt(),a=o&&{...o,metadata:Yz(o.metadata,t)},s=Jz(t),i=ni((await L()).hookPolicies);return t==="claude"&&(i.greenCollapse||i.rereadStub)&&await AC()==="repair deferred"&&process.stderr.write(`Anyray source-policy hook repair deferred.
|
|
839
|
+
`),i9(e,{...t==="claude"&&(i.greenCollapse||i.rereadStub)?{sourcePolicies:async c=>{let l=await Lb(typeof c.transcript_path=="string"?c.transcript_path:""),d=l.kind==="main",u=d&&l.retrieveAvailable&&(await Dn.mcpStatus?.())?.registered===!0;return $T(c,{policies:i,canRetrieve:u,mainTranscript:d})}}:{},optimize:(c,l,d,u,p)=>y9(a,c,l,d,u,p),...t==="claude"?{readContext:async c=>{let l=await Lb(c);return{intent:l.intent,retrievalContext:l.kind==="main"?"available":l.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:c=>af(c,r),beacon:(c,l)=>Yl(a,"hook",l,c),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Ro.maxChars,digestCommand:lT,tee:s.tee,mediumBand:jz.has(t),finalizeOutput:n})};var HT=async()=>0;import{spawn as g9}from"node:child_process";import{homedir as w9}from"node:os";import{join as b9}from"node:path";var k9=3e4,C9=5*6e4,A9=30*6e4,v9=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},S9=()=>b9(w9(),".claude","settings.json"),I9=async e=>{try{let n=(await F(S9())).env;if(!n)return!1;let r=Tn(e).env;for(let[o,a]of Object.entries(r))if(n[o]!==a)return!1;return n.ANTHROPIC_AUTH_TOKEN===void 0}catch{return!1}},E9=async e=>{await Dn.apply(e,{dryRun:!1})},x9=()=>{let{command:e,args:t}=Qr("__anyray-sso-poll");return{exe:e,args:t}},R9=()=>{let{exe:e,args:t}=x9(),n=g9(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))}}},O9=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},GT=(e,t,n,r)=>Re({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),si=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},KT=e=>`Anyray: one-time sign-in required to use AI tools on this device.
|
|
840
840
|
1. Open ${e.verificationUriComplete}
|
|
841
841
|
2. Confirm code ${e.userCode}
|
|
842
842
|
Your prompt was not sent \u2014 complete sign-in, then resubmit it.
|
|
843
843
|
`,Ub=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
|
|
844
844
|
`:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
|
|
845
845
|
`:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
|
|
846
|
-
`,_9=e=>Math.min(C9,k9*2**Math.max(0,e-1)),T9=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?A9:_9(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Pa=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??
|
|
847
|
-
`))}let ae;await h();let Ae=(t.resolveMachineUuid??on)()||void 0;try{ae=await d(S,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:Ae})}catch(me){if(!(me instanceof ct))return si(e,Ub("gateway-unreachable",w.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(ae){let me={...b,gateway:S,name:ae.user,team:e.team??ae.team??b.team,clientKey:ae.key,clientKeyExpiresAt:ae.expiresAt,authMode:"subscription"};return await o(me),await f({expiresAt:ae.expiresAt}),await p(GT(S,me,e.team,ae.key)),{exitCode:0}}}if(A?.status==="pending"&&(A.userCode&&A.verificationUriComplete)&&(A.grantExpiresAt??0)>n()&&c(A.pollerPid)){if(e.sessionStart&&A.verificationUriComplete)try{y(A.verificationUriComplete)}catch{}return si(e,KT(A))}if(A){let G=T9(A,n());if(G)return si(e,Ub(G,w.cpOrigin))}let E;try{E=await l({cpOrigin:w.cpOrigin,tenantId:w.tenantId,gatewayUrl:e.gateway,now:n})}catch(G){let X=G instanceof bt?G.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:A?.lastFailure===X?(A.failureCount??0)+1:1,lastFailure:X}),si(e,Ub(X,w.cpOrigin))}let T={v:1,status:"pending",userCode:E.userCode,verificationUriComplete:E.verificationUriComplete,grantExpiresAt:E.grantExpiresAt,startedAt:E.startedAt,lastAttemptAt:n(),failureCount:0};await i(T);let I=g(),K={...T,pollerPid:I.pid};if(await i(K),I.handoff({deviceCode:E.deviceCode,privateKeyPem:E.privateKeyPem,publicKeyPem:E.publicKeyPem,cpOrigin:E.cpOrigin,tenantId:E.tenantId,intervalMs:E.intervalMs,grantExpiresAt:E.grantExpiresAt,startedAt:E.startedAt,gatewayUrl:E.gatewayUrl,gatewayOverride:e.gateway,team:e.team,priorCertSig:b.enrolledCert?.sig}),e.sessionStart)try{y(E.verificationUriComplete)}catch{}return si(e,KT(K))}catch{return{exitCode:0}}},P9=async()=>{try{for await(let e of process.stdin);}catch{}},VT=async e=>{await P9();try{let t=await Pa(v9(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var D9=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},
|
|
848
|
-
`}catch{return}},
|
|
846
|
+
`,_9=e=>Math.min(C9,k9*2**Math.max(0,e-1)),T9=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?A9:_9(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Pa=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??L,o=t.saveProfile??pe,a=t.loadDevKey??Ye,s=t.readGateState??ei,i=t.writeGateState??zp,c=t.isProcessAlive??N_,l=t.startGrant??Ep,d=t.verify??Sn,u=t.routingIntact??I9,p=t.applyClaudeCode??E9,m=t.maybeSpawnRefresh??Eo,f=t.recordMint??Ys,h=t.reserveMint??Ea,g=t.spawnPoller??R9,y=t.openBrowser??Nr;try{let w=Ft(e.sso);if(!w)return{exitCode:0};let b=await r(),A=await s(),C=b.enrolledCert?await a():void 0,x=O9(b),O=!!(b.enrolledCert&&C)&&Number.isFinite(x)&&x>n(),S=e.gateway??b.gateway;if(O&&b.enrolledCert&&C&&S){let G=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(G)&&G>n()&&b.clientKey){let me=GT(S,b,e.team,b.clientKey);return await u(me)?(G-n()<=Uw()&&await m(),{exitCode:0}):(await p(me),si(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
|
|
847
|
+
`))}let ae;await h();let Ae=(t.resolveMachineUuid??on)()||void 0;try{ae=await d(S,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:Ae})}catch(me){if(!(me instanceof ct))return si(e,Ub("gateway-unreachable",w.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(ae){let me={...b,gateway:S,name:ae.user,team:e.team??ae.team??b.team,clientKey:ae.key,clientKeyExpiresAt:ae.expiresAt,authMode:"subscription"};return await o(me),await f({expiresAt:ae.expiresAt}),await p(GT(S,me,e.team,ae.key)),{exitCode:0}}}if(A?.status==="pending"&&(A.userCode&&A.verificationUriComplete)&&(A.grantExpiresAt??0)>n()&&c(A.pollerPid)){if(e.sessionStart&&A.verificationUriComplete)try{y(A.verificationUriComplete)}catch{}return si(e,KT(A))}if(A){let G=T9(A,n());if(G)return si(e,Ub(G,w.cpOrigin))}let E;try{E=await l({cpOrigin:w.cpOrigin,tenantId:w.tenantId,gatewayUrl:e.gateway,now:n})}catch(G){let X=G instanceof bt?G.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:A?.lastFailure===X?(A.failureCount??0)+1:1,lastFailure:X}),si(e,Ub(X,w.cpOrigin))}let T={v:1,status:"pending",userCode:E.userCode,verificationUriComplete:E.verificationUriComplete,grantExpiresAt:E.grantExpiresAt,startedAt:E.startedAt,lastAttemptAt:n(),failureCount:0};await i(T);let I=g(),K={...T,pollerPid:I.pid};if(await i(K),I.handoff({deviceCode:E.deviceCode,privateKeyPem:E.privateKeyPem,publicKeyPem:E.publicKeyPem,cpOrigin:E.cpOrigin,tenantId:E.tenantId,intervalMs:E.intervalMs,grantExpiresAt:E.grantExpiresAt,startedAt:E.startedAt,gatewayUrl:E.gatewayUrl,gatewayOverride:e.gateway,team:e.team,priorCertSig:b.enrolledCert?.sig}),e.sessionStart)try{y(E.verificationUriComplete)}catch{}return si(e,KT(K))}catch{return{exitCode:0}}},P9=async()=>{try{for await(let e of process.stdin);}catch{}},VT=async e=>{await P9();try{let t=await Pa(v9(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var D9=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},N9=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??So)();if(!r)return;let o=await(t.ssoGate??Pa)({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})}
|
|
848
|
+
`}catch{return}},L9=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},$9=()=>{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")}},M9=(e,t)=>{let n=t.minChars??gl.minChars,r={maxChars:Math.min(Ro.maxChars,n)},o=af(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},jT=async()=>{let e=await L9(),t=await N9(e);t&&process.stdout.write(t);let n=$9(),r=await pt();return await D9(e,{isPaste:o=>sf(o,n),measure:o=>M9(o,n),beacon:o=>Yl(r,"prompt",o)}),0};import{spawn as B9}from"node:child_process";var YT=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),F9=/[|&;<>`$()\n]/,ZT=e=>{if(F9.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},U9=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!YT(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!YT(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(Vf)||!t.isRecognized(o)||ZT(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},W9=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?ZT(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
|
|
849
849
|
`),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
|
|
850
|
-
`),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},H9=16*1024*1024,G9=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=B9(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>H9){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)}}),K9=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Fb(n,"cursor");return typeof r=="string"?r:t},JT=e=>{let t=e[0]==="--b64"?e[1]:void 0;return W9(t,{exec:G9,trim:K9,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},XT=async()=>{let e=await ai();if(process.platform==="win32")return 0;let t=U9(e,{isRecognized:n=>Ib(n)!==null||iT(n),wrap:n=>un(Vf,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as V9}from"node:crypto";import{homedir as zT}from"node:os";import{extname as j9,isAbsolute as Y9,join as Wb,resolve as Al,sep as qT}from"node:path";import{chmod as Z9,readFile as J9,stat as rP,unlink as X9,writeFile as z9}from"node:fs/promises";var Gb=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),q9=16*1024,QT=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],Q9=["pattern","query","regex","search"],eq=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"]),tq=720*60*1e3,nq=512,Hb=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},rq=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],eP=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(qT)?n:n+qT)),oq=(e,t,n)=>Y9(e)?[Al(e)]:[...new Set([Al(t,e),...n.map(r=>Al(r,e))])],tP=(e,t,n)=>V9("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),nP=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),aq=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!Gb(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!Gb(o))return"";let a=rq(n.workspace_roots).map(d=>Al(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=Hb(o,Q9);if(!d)return"";let u=Hb(o,QT);return u&&!eP(Al(s,u),a)||!await t.remember(tP(i,"Grep",d))?"":nP(`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=Hb(o,QT);if(!c||eq.has(j9(c).toLowerCase()))return"";let l=await t.resolveFile(oq(c,s,a));return!l||l.bytes<q9||!eP(l.path,a)||!await t.remember(tP(i,"Read",l.path))?"":nP(`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.`)},sq=async e=>{for(let t of e)try{let n=await rP(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},iq=async()=>{let e=Wb(zT(),".anyray");try{if((await rP(e)).isDirectory())return Wb(e,"cursor-redirects.json")}catch{}return Wb(zT(),".anyray-cursor-redirects.json")},cq=async e=>{let t;try{let n=await iq(),r=Date.now(),o={};try{let s=JSON.parse(await J9(n,"utf-8"));if(s?.v===1&&Gb(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=tq&&(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,nq);return t=`${n}.${process.pid}.tmp`,await z9(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await Z9(t,384),await ke(t,n),!0}catch{if(t)try{await X9(t)}catch{}return!1}},oP=async()=>{let e=await ai(),t="";try{t=await aq(e,{resolveFile:sq,remember:cq})}catch{t=""}return t&&process.stdout.write(t),0};import{execFileSync as lq}from"node:child_process";var sP=new Set(["darwin","win32","linux"]),dq=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),uq=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!dq.has(t)},ff=async(e,t={})=>{try{if(!sP.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}},iP=async(e,t)=>{if(e!=="not-enrolled")return e;try{return!t.readManagedEnrollment().enrollmentUrl||(await t.loadProfile()).managedEnrollmentDisabled===!0||await ff(t)!==0?e:await t.refresh()}catch{return e}},aP=async(e,t=ie)=>{let n=new Set(e.managedTools??[]),r=[];for(let o of t)if(!n.has(o.id)&&!zr(o))try{(await o.detect()).installed&&r.push(o.id)}catch{}return r},pq=e=>new Date(e).toISOString().slice(0,10),cP=async e=>{try{if(!sP.has(e.platform)||e.isUserSession?.()===!1||!e.readManagedEnrollment().enrollmentUrl)return!1;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return!1;let n=pq((e.now??Date.now)());if(t.managedToolAdoptDay===n)return!1;let r=await aP(t,e.adapters);if(r.length===0)return!1;let o=e.saveProfile??pe;if(await o({...await e.loadProfile(),managedToolAdoptDay:n}),await ff(e)!==0)return!1;let a=await e.loadProfile(),s=await aP(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}},mf=e=>({platform:process.platform,readManagedEnrollment:dl,loadProfile:N,isUserSession:()=>{try{if(process.platform==="win32"){let t=lq(jg,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return uq(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var vl=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},hf=e=>typeof e=="string"&&e.trim()?e.trim():void 0,fq=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=vl(n,"deviceCode"),o=vl(n,"privateKeyPem"),a=vl(n,"publicKeyPem"),s=vl(n,"cpOrigin"),i=vl(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=hf(n.gatewayUrl),p=hf(n.gatewayOverride),m=hf(n.team),f=hf(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}},mq=e=>new Promise(t=>setTimeout(t,e)),hq=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})},yq=async(e,t={})=>{let n=t.poll??xp,r=t.verify??Sn,o=t.loadProfile??N,a=t.saveProfile??pe,s=t.saveDevKey??Tl,i=t.withProfileLock??xn,c=t.readGateState??ei,l=t.writeGateState??zp,d=t.clearGateState??pl,u=t.sleep??mq,p=t.now??Date.now,m=t.recordMint??Ys,f=t.reserveMint??Ea,h=t.applyClaudeCode??(async I=>{await Dn.apply(I,{dryRun:!1})}),g=I=>hq(I,{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},w=async()=>{let I=await c();return I?.status!=="pending"||I.startedAt!==e.startedAt},b;try{b=await n(y,{gatewayUrl:e.gatewayOverride})}catch(I){if(await w())return"superseded";let K=I instanceof Ot?I.kind:"cp-unreachable";return await g(K),K}if(await w())return"superseded";let A=I=>I.enrolledCert!==void 0&&I.enrolledCert.sig!==b.cert.sig&&I.enrolledCert.sig!==e.priorCertSig,C=e.gatewayOverride??b.gatewayUrl,x=I=>({...I,gateway:C??I.gateway,name:b.cert.payload.user||I.name,team:e.team??b.cert.payload.team??I.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 I=await o();if(A(I))return;let K=x(I);return await s(b.privateKeyPem),await a(K),K})}catch{return"failed"}if(!O)return"superseded";if(!C)return await g("gateway-unreachable"),"gateway-unreachable";let S;await f();let E=(t.resolveMachineUuid??on)()||void 0;for(let I=0;I<3;I++)try{S=await r(C,b.cert,b.privateKeyPem,{timeoutMs:1e4,machineUuid:E});break}catch(K){if(K instanceof ct||I===2)break;await u(1e3)}if(!S)return await g("gateway-unreachable"),"gateway-unreachable";let T={...O,gateway:C,name:S.user,team:e.team??S.team??O.team,clientKey:S.key,clientKeyExpiresAt:S.expiresAt,authMode:"subscription"};try{if(!await i(async()=>A(await o())?!1:(await a(T),!0)))return"superseded";await m({expiresAt:S.expiresAt});let K=Re({origin:C,clientKey:S.key,subscription:!0,user:T.name,team:T.team});return await h(K),await d(),"enrolled"}catch{return await g("gateway-unreachable"),"failed"}},gq=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},lP=async()=>{let e=fq(await gq());if(e)try{await yq(e)}catch{}return 0};var wq=3e3,dP=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>Mg(wq)),o=e.updateStatus??Ca;t(`anyray-connect ${Ne}
|
|
851
|
-
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&ko(a,
|
|
850
|
+
`),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},H9=16*1024*1024,G9=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=B9(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>H9){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)}}),K9=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Fb(n,"cursor");return typeof r=="string"?r:t},JT=e=>{let t=e[0]==="--b64"?e[1]:void 0;return W9(t,{exec:G9,trim:K9,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},XT=async()=>{let e=await ai();if(process.platform==="win32")return 0;let t=U9(e,{isRecognized:n=>Ib(n)!==null||iT(n),wrap:n=>un(Vf,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as V9}from"node:crypto";import{homedir as zT}from"node:os";import{extname as j9,isAbsolute as Y9,join as Wb,resolve as Al,sep as qT}from"node:path";import{chmod as Z9,readFile as J9,stat as rP,unlink as X9,writeFile as z9}from"node:fs/promises";var Gb=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),q9=16*1024,QT=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],Q9=["pattern","query","regex","search"],eq=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"]),tq=720*60*1e3,nq=512,Hb=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},rq=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],eP=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(qT)?n:n+qT)),oq=(e,t,n)=>Y9(e)?[Al(e)]:[...new Set([Al(t,e),...n.map(r=>Al(r,e))])],tP=(e,t,n)=>V9("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),nP=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),aq=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!Gb(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!Gb(o))return"";let a=rq(n.workspace_roots).map(d=>Al(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=Hb(o,Q9);if(!d)return"";let u=Hb(o,QT);return u&&!eP(Al(s,u),a)||!await t.remember(tP(i,"Grep",d))?"":nP(`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=Hb(o,QT);if(!c||eq.has(j9(c).toLowerCase()))return"";let l=await t.resolveFile(oq(c,s,a));return!l||l.bytes<q9||!eP(l.path,a)||!await t.remember(tP(i,"Read",l.path))?"":nP(`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.`)},sq=async e=>{for(let t of e)try{let n=await rP(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},iq=async()=>{let e=Wb(zT(),".anyray");try{if((await rP(e)).isDirectory())return Wb(e,"cursor-redirects.json")}catch{}return Wb(zT(),".anyray-cursor-redirects.json")},cq=async e=>{let t;try{let n=await iq(),r=Date.now(),o={};try{let s=JSON.parse(await J9(n,"utf-8"));if(s?.v===1&&Gb(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=tq&&(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,nq);return t=`${n}.${process.pid}.tmp`,await z9(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await Z9(t,384),await ke(t,n),!0}catch{if(t)try{await X9(t)}catch{}return!1}},oP=async()=>{let e=await ai(),t="";try{t=await aq(e,{resolveFile:sq,remember:cq})}catch{t=""}return t&&process.stdout.write(t),0};import{execFileSync as lq}from"node:child_process";var sP=new Set(["darwin","win32","linux"]),dq=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),uq=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!dq.has(t)},ff=async(e,t={})=>{try{if(!sP.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}},iP=async(e,t)=>{if(e!=="not-enrolled")return e;try{return!t.readManagedEnrollment().enrollmentUrl||(await t.loadProfile()).managedEnrollmentDisabled===!0||await ff(t)!==0?e:await t.refresh()}catch{return e}},aP=async(e,t=ie)=>{let n=new Set(e.managedTools??[]),r=[];for(let o of t)if(!n.has(o.id)&&!zr(o))try{(await o.detect()).installed&&r.push(o.id)}catch{}return r},pq=e=>new Date(e).toISOString().slice(0,10),cP=async e=>{try{if(!sP.has(e.platform)||e.isUserSession?.()===!1||!e.readManagedEnrollment().enrollmentUrl)return!1;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return!1;let n=pq((e.now??Date.now)());if(t.managedToolAdoptDay===n)return!1;let r=await aP(t,e.adapters);if(r.length===0)return!1;let o=e.saveProfile??pe;if(await o({...await e.loadProfile(),managedToolAdoptDay:n}),await ff(e)!==0)return!1;let a=await e.loadProfile(),s=await aP(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}},mf=e=>({platform:process.platform,readManagedEnrollment:dl,loadProfile:L,isUserSession:()=>{try{if(process.platform==="win32"){let t=lq(jg,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return uq(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var vl=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},hf=e=>typeof e=="string"&&e.trim()?e.trim():void 0,fq=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=vl(n,"deviceCode"),o=vl(n,"privateKeyPem"),a=vl(n,"publicKeyPem"),s=vl(n,"cpOrigin"),i=vl(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=hf(n.gatewayUrl),p=hf(n.gatewayOverride),m=hf(n.team),f=hf(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}},mq=e=>new Promise(t=>setTimeout(t,e)),hq=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})},yq=async(e,t={})=>{let n=t.poll??xp,r=t.verify??Sn,o=t.loadProfile??L,a=t.saveProfile??pe,s=t.saveDevKey??Tl,i=t.withProfileLock??xn,c=t.readGateState??ei,l=t.writeGateState??zp,d=t.clearGateState??pl,u=t.sleep??mq,p=t.now??Date.now,m=t.recordMint??Ys,f=t.reserveMint??Ea,h=t.applyClaudeCode??(async I=>{await Dn.apply(I,{dryRun:!1})}),g=I=>hq(I,{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},w=async()=>{let I=await c();return I?.status!=="pending"||I.startedAt!==e.startedAt},b;try{b=await n(y,{gatewayUrl:e.gatewayOverride})}catch(I){if(await w())return"superseded";let K=I instanceof Ot?I.kind:"cp-unreachable";return await g(K),K}if(await w())return"superseded";let A=I=>I.enrolledCert!==void 0&&I.enrolledCert.sig!==b.cert.sig&&I.enrolledCert.sig!==e.priorCertSig,C=e.gatewayOverride??b.gatewayUrl,x=I=>({...I,gateway:C??I.gateway,name:b.cert.payload.user||I.name,team:e.team??b.cert.payload.team??I.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 I=await o();if(A(I))return;let K=x(I);return await s(b.privateKeyPem),await a(K),K})}catch{return"failed"}if(!O)return"superseded";if(!C)return await g("gateway-unreachable"),"gateway-unreachable";let S;await f();let E=(t.resolveMachineUuid??on)()||void 0;for(let I=0;I<3;I++)try{S=await r(C,b.cert,b.privateKeyPem,{timeoutMs:1e4,machineUuid:E});break}catch(K){if(K instanceof ct||I===2)break;await u(1e3)}if(!S)return await g("gateway-unreachable"),"gateway-unreachable";let T={...O,gateway:C,name:S.user,team:e.team??S.team??O.team,clientKey:S.key,clientKeyExpiresAt:S.expiresAt,authMode:"subscription"};try{if(!await i(async()=>A(await o())?!1:(await a(T),!0)))return"superseded";await m({expiresAt:S.expiresAt});let K=Re({origin:C,clientKey:S.key,subscription:!0,user:T.name,team:T.team});return await h(K),await d(),"enrolled"}catch{return await g("gateway-unreachable"),"failed"}},gq=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},lP=async()=>{let e=fq(await gq());if(e)try{await yq(e)}catch{}return 0};var wq=3e3,dP=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>Mg(wq)),o=e.updateStatus??Ca;t(`anyray-connect ${Le}
|
|
851
|
+
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&ko(a,Le)>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: ${Le} \u2192 ${a}
|
|
852
852
|
${i}
|
|
853
|
-
`)}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 bq=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},kq=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),Cq=async(e={})=>{try{let t=await(e.readBootstrap??So)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??an)().catch(()=>{});let n=await(e.loadProfile??
|
|
853
|
+
`)}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 bq=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},kq=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),Cq=async(e={})=>{try{let t=await(e.readBootstrap??So)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??an)().catch(()=>{});let n=await(e.loadProfile??L)();if(Pe(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Pa)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??L)(),Pe(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??ei)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!bq(a)||!kq(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"}}},uP=async(e={})=>{let t=await Cq(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
854
854
|
`),0};import Aq from"node:path";var vq="2025-06-18",Sq={name:"anyray",version:"1"},pP={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}},Iq=20,fP={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}},wP=nw,Eq=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,wP)},xq=e=>e==="paths"||e==="lines"||e==="full"?e:"full",mP={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-${wP}). 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}},hP={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}},Rq=8,Oq=3,yP={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}},_q=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(`
|
|
855
855
|
`)},Tq=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
856
856
|
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,Rq).map(([a,s])=>{let i=s.slice(0,Oq).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
@@ -862,17 +862,17 @@ If the user expected one, their export may predate it, or no export has been imp
|
|
|
862
862
|
[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(`
|
|
863
863
|
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},bP=e=>{try{e.heartbeat?.().catch(()=>{})}catch{}},Pq=async(e,t)=>{let n=e?.id,r=n===void 0,o=typeof e?.method=="string"?e.method:"";switch(o){case"initialize":return bP(t),Oe(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:vq,capabilities:{tools:{}},serverInfo:Sq});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Oe(n??null,{});case"tools/list":{let a=[pP,fP];t.advertiseContextTools!==!1&&a.push(mP,hP);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(yP),Oe(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===pP.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Oe(n??null,Se("handle is required",!0));let c=g=>{if(g!==void 0)return typeof g!="number"||!Number.isFinite(g)?null:Math.max(Math.round(g),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return Oe(n??null,Se("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return Oe(n??null,Se("grep must be non-empty",!0));if(s.grep.length>256)return Oe(n??null,Se("grep is limited to 256 characters",!0));u=s.grep}let p=l!==void 0||d!==void 0||u!==void 0,m=Pb(i);if(m){let g=await Db(m);if(u!==void 0)return Oe(n??null,Se(`${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 ${g??"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:g??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)`,A=y.truncated&&!y.span?.partialLine&&y.span?` Continue with anyray_retrieve(handle="${i}", startLine=${y.span.endLine+1}).`:"";return Oe(n??null,Se(`[anyray: ${i} is a local hook-tee file, not a stash handle \u2014 served ${b} from ${y.teePath??g}.${A} Read that path directly next time.]
|
|
864
864
|
`+y.content))}let w=y!==null;return Oe(n??null,Se(`${i} is a hook-tee file id, not a stash handle`+(w&&g?`, and ${g} 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 ${g??"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(g){f={ok:!1,message:g instanceof Error?g.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 Oe(n??null,Se(f.kind==="slice-unsupported"?h:f.message,!0));if(p&&(f.partial===void 0||typeof f.totalLines!="number"))return Oe(n??null,Se(h,!0));if(f.partial===!0&&typeof f.totalLines=="number"){let g=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 ${Iq} 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 Oe(n??null,Se(`${g}
|
|
865
|
-
${f.content}`))}return Oe(n??null,Se(f.content))}if(a.name===fP.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Oe(n??null,Se("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 Oe(n??null,l.ok?Se(_q(l.matches)):Se(l.message,!0))}if(a.name===mP.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Oe(n??null,Se("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(p=>typeof p=="string"):void 0,l=Eq(s.maxResults),d=xq(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 Oe(n??null,u.ok?Se(
|
|
866
|
-
`),!0}catch{return!1}},l,d=()=>{l||!n.heartbeat||(l=setInterval(()=>bP(n),
|
|
865
|
+
${f.content}`))}return Oe(n??null,Se(f.content))}if(a.name===fP.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Oe(n??null,Se("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 Oe(n??null,l.ok?Se(_q(l.matches)):Se(l.message,!0))}if(a.name===mP.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Oe(n??null,Se("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(p=>typeof p=="string"):void 0,l=Eq(s.maxResults),d=xq(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 Oe(n??null,u.ok?Se(N0(i,u,d)):Se(u.message??"search failed",!0))}if(a.name===yP.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 Oe(n??null,d.ok?Se(Qg(d)):Se(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Oe(n??null,Se("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 Oe(n??null,l.ok?Se(Tq(c,l)):Se(l.message??"history search failed",!0))}if(a.name===hP.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Oe(n??null,Se("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 Oe(n??null,l.ok?Se(Qg(l)):Se(l.message??"read failed",!0))}return Kb(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Kb(n??null,-32601,`method not found: ${o}`)}},Dq=async(e,t=fetch)=>{if(!e)return!1;let n=new AbortController,r=setTimeout(()=>n.abort(),Lp);try{return(await t(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:fn(e),signal:n.signal})).ok}catch{return!1}finally{clearTimeout(r)}},Nq=(e,t=!0)=>({retrieve:async(n,r)=>Vs(await e(),n,r),recall:async(n,r)=>$p(await e(),n,r),search:(n,r,o)=>Ap(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Yc(n,r),readTee:async(n,r)=>{if(_b())return{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"the hook tee is off (ANYRAY_HOOK_TEE=off)"};let o=await Db(n);return o?{...await Yc(o,{cwd:Aq.dirname(o),...r}),teePath:o}:{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"not a tee id"}},historySearch:n=>M0(n),historyOpen:n=>B0(n),historyAvailable:async()=>await $s()>0,advertiseContextTools:t,heartbeat:async()=>{try{return await Dq(await e())}catch{return!1}}}),Lq=5*6e4,kP=async(e="auto",t={})=>{let n=Nq(()=>pt(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,Eo().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=f=>{try{return o.write(JSON.stringify(f)+`
|
|
866
|
+
`),!0}catch{return!1}},l,d=()=>{l||!n.heartbeat||(l=setInterval(()=>bP(n),Lq),l.unref())},u=async f=>{let h=f.trim();if(!h)return;let g;try{g=JSON.parse(h)}catch{console.error("anyray mcp: dropping unparseable frame");return}let y;try{y=await Pq(g,n)}catch(b){console.error("anyray mcp: dispatch error",gP(b)),y=g?.id===void 0?null:Kb(g.id,-32603,"internal error")}let w=y?c(y):!1;g.method==="initialize"&&y&&!y.error&&w&&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(`
|
|
867
867
|
`))>=0;){let g=m.slice(0,h);m=m.slice(h+1),await u(g)}}m.trim()&&await u(m)}catch(f){console.error("anyray mcp: stdin error",gP(f))}finally{clearInterval(p),l&&clearInterval(l)}return 0};import{spawn as $q}from"node:child_process";var Mq=e=>e==="jetbrains"||e==="windsurf"?e:void 0,Bq=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(`
|
|
868
868
|
`);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}})}
|
|
869
869
|
`),!0)}catch{return!1}},Fq={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},Uq=(e,t,n)=>{let r=new Set(Fq[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}},CP=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
870
870
|
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!Hu(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
871
|
-
`),1;await(n.refreshIfDue??an)().catch(()=>{});let s=await(n.loadProfile??
|
|
871
|
+
`),1;await(n.refreshIfDue??an)().catch(()=>{});let s=await(n.loadProfile??L)(),i=await(n.readBootstrap??So)().catch(()=>{});if(i){let w=await(n.ssoGate??Pa)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(w.exitCode===2&&w.stderr)return await Bq(w.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(w.stderr),1;s=await(n.loadProfile??L)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
|
|
872
872
|
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??Vn)():void 0,d=Re({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=Mq(n.clientTool);u&&(d.metadata.tool=u);let p=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",m=(n.hookBinaryIsDurable??ne)(),f=ox(d,t,{mcpServer:m?Ue("profile"):void 0})[p],h=n.spawn??$q,g=f.command,y=f.args;if(o==="win32"){if(!f.args.every(w=>w==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(w)))return r.write(`Anyray ACP adapter arguments are invalid.
|
|
873
873
|
`),1;g=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${f.command}" ${f.args.join(" ")}`]}return await new Promise(w=>{let b=Uq(e,a,f.env),A=h(g,y,{env:b,stdio:"inherit",windowsHide:!0});A.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
|
|
874
|
-
`),w(1)}),A.once("exit",(C,x)=>{w(typeof C=="number"?C:x?1:0)})})};import{randomUUID as Wq}from"node:crypto";import{open as Hq,rm as Gq}from"node:fs/promises";import{join as Kq}from"node:path";import{z as Ee}from"zod";var yf=Ee.string().min(1).refine(e=>Number.isFinite(Date.parse(e)),"expected an ISO-8601 timestamp"),Vq=Ee.enum(["reconcile","refresh","directives","repair","status","offboard","desktop-update"]),Vb=Ee.union([Ee.literal(0),Ee.literal(1),Ee.literal(2),Ee.literal(3),Ee.literal(4)]),jq=Ee.enum(["locked","required","recommended","optional"]),gf=Ee.object({schemaVersion:Ee.literal(1),hookPolicies:fb.default({greenCollapse:!1,rereadStub:!1}),hookPolicyMetrics:Qp.extend({observationGap:Ee.boolean()}).optional(),generatedAt:yf,connectVersion:Ee.string().min(1),fleetManaged:Ee.boolean(),enrollment:Ee.object({state:Ee.enum(["enrolled","degraded","broken","none"]),lastRefreshAt:yf.optional(),lastRefreshOutcome:Ee.enum(["ok","failed"]).optional()}).strict(),keyExpiresAt:yf.optional(),keyKind:Ee.enum(["personal","service"]).optional(),claudeDesktopConfigCarry:Ee.enum(mE).default("unknown"),tools:Ee.array(Ee.object({id:Ee.string().min(1),tier:jq,routed:Ee.boolean()}).strict()),lastVerb:Ee.object({verb:Vq,exitCode:Vb,at:yf}).strict()}).strict(),AP=(e,t)=>{if(!e)return!1;let n=Date.parse(e);return Number.isFinite(n)&&n>t},Yq=(e,t,n=Date.now())=>{if(!!!(e.clientKey||e.enrolledCert||t))return"none";if(In(e.clientKey)==="service")return e.gateway?"enrolled":"broken";let o=e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt;return!e.gateway||!e.enrolledCert||!t||!AP(o,n)?"broken":!e.clientKey||e.clientKeyExpiresAt&&!AP(e.clientKeyExpiresAt,n)?"degraded":"enrolled"},Zq=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"}},vP=(e,t)=>e.fleetToolPolicy?.tiers?.[t]??"required",Jq=async(e,t)=>{let n=new Set(e.managedTools??[]),r=new Set(e.revertedTools??[]),o=(e.fleetToolPolicy?.enabled??[]).filter(c=>{let l=vP(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:vP(e,c),routed:d})}return i},SP=async(e,t={})=>{let n=t.now??Date.now,r=await(t.loadProfile??
|
|
875
|
-
`,"utf8"),await a.chmod(384),await Kr(a),await a.close(),a=void 0,await(t.publish??ke)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await Gq(o,{force:!0}).catch(()=>{}),s}},jb=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var zq=1e4,ii=e=>e?.name??"Error",Yb=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(zq)})}catch(o){console.error(`anyray seat offboard report: ${ii(o)}`)}},qq=e=>e==="reverted"||e==="queued",wf=async(e={})=>{let t=e.loadProfile??
|
|
874
|
+
`),w(1)}),A.once("exit",(C,x)=>{w(typeof C=="number"?C:x?1:0)})})};import{randomUUID as Wq}from"node:crypto";import{open as Hq,rm as Gq}from"node:fs/promises";import{join as Kq}from"node:path";import{z as Ee}from"zod";var yf=Ee.string().min(1).refine(e=>Number.isFinite(Date.parse(e)),"expected an ISO-8601 timestamp"),Vq=Ee.enum(["reconcile","refresh","directives","repair","status","offboard","desktop-update"]),Vb=Ee.union([Ee.literal(0),Ee.literal(1),Ee.literal(2),Ee.literal(3),Ee.literal(4)]),jq=Ee.enum(["locked","required","recommended","optional"]),gf=Ee.object({schemaVersion:Ee.literal(1),hookPolicies:fb.default({greenCollapse:!1,rereadStub:!1}),hookPolicyMetrics:Qp.extend({observationGap:Ee.boolean()}).optional(),generatedAt:yf,connectVersion:Ee.string().min(1),fleetManaged:Ee.boolean(),enrollment:Ee.object({state:Ee.enum(["enrolled","degraded","broken","none"]),lastRefreshAt:yf.optional(),lastRefreshOutcome:Ee.enum(["ok","failed"]).optional()}).strict(),keyExpiresAt:yf.optional(),keyKind:Ee.enum(["personal","service"]).optional(),claudeDesktopConfigCarry:Ee.enum(mE).default("unknown"),tools:Ee.array(Ee.object({id:Ee.string().min(1),tier:jq,routed:Ee.boolean()}).strict()),lastVerb:Ee.object({verb:Vq,exitCode:Vb,at:yf}).strict()}).strict(),AP=(e,t)=>{if(!e)return!1;let n=Date.parse(e);return Number.isFinite(n)&&n>t},Yq=(e,t,n=Date.now())=>{if(!!!(e.clientKey||e.enrolledCert||t))return"none";if(In(e.clientKey)==="service")return e.gateway?"enrolled":"broken";let o=e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt;return!e.gateway||!e.enrolledCert||!t||!AP(o,n)?"broken":!e.clientKey||e.clientKeyExpiresAt&&!AP(e.clientKeyExpiresAt,n)?"degraded":"enrolled"},Zq=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"}},vP=(e,t)=>e.fleetToolPolicy?.tiers?.[t]??"required",Jq=async(e,t)=>{let n=new Set(e.managedTools??[]),r=new Set(e.revertedTools??[]),o=(e.fleetToolPolicy?.enabled??[]).filter(c=>{let l=vP(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:vP(e,c),routed:d})}return i},SP=async(e,t={})=>{let n=t.now??Date.now,r=await(t.loadProfile??L)(),o=await(t.loadDevKey??Ye)().catch(()=>{}),a=await(t.readRefreshState??Ut)().catch(()=>({})),s=await(t.claudeDesktopConfigCarry??(()=>yl({loadProfile:async()=>r,toolById:t.toolById??Qe})))().catch(()=>"unknown"),i=In(r.clientKey),c={schemaVersion:1,hookPolicies:ni(r.hookPolicies),hookPolicyMetrics:await ef(),generatedAt:new Date(n()).toISOString(),connectVersion:Le,fleetManaged:r.anyrayFleetManaged===!0,enrollment:{state:Yq(r,!!o,n()),...Zq(a)},...r.clientKeyExpiresAt&&Number.isFinite(Date.parse(r.clientKeyExpiresAt))?{keyExpiresAt:r.clientKeyExpiresAt}:{},...i?{keyKind:i}:{},claudeDesktopConfigCarry:s,tools:await Jq(r,t.toolById??Qe),lastVerb:e};return gf.parse(c)},Xq=()=>Kq(ee(),"status.json"),IP=async(e,t={})=>{let n=gf.parse(e);await(t.ensureStateDir??Xe)();let r=Xq(),o=`${r}.${process.pid}.${Wq()}.tmp`,a;try{a=await Hq(o,"wx",384),await a.writeFile(`${JSON.stringify(n,null,2)}
|
|
875
|
+
`,"utf8"),await a.chmod(384),await Kr(a),await a.close(),a=void 0,await(t.publish??ke)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await Gq(o,{force:!0}).catch(()=>{}),s}},jb=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var zq=1e4,ii=e=>e?.name??"Error",Yb=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(zq)})}catch(o){console.error(`anyray seat offboard report: ${ii(o)}`)}},qq=e=>e==="reverted"||e==="queued",wf=async(e={})=>{let t=e.loadProfile??L,n=e.clearDeviceTokenState??Kp,r=e.reportSeatOffboarded??Yb,o=e.clearEnrollment??Pl,a=e.recordManagedTools??Vr,s=e.markSeatOffboarded??Dl,i=e.adapterById??Qe,c=e.uninstallScheduler??fr,l=e.unitsPresent??id,d=e.saveProfile??pe,u=await t(),p=u.managedTools??[];await r(u).catch(()=>{}),await n().catch(()=>{});let m=!1,f=!1;try{m=await o()}catch(C){f=!0,console.error(`anyray offboard: clearing enrollment: ${ii(C)}`)}let h=[],g=[],y=[];for(let C of p){let x=i(C);if(!x){y.push(C);continue}try{let O=await x.revert({dryRun:!1,fullRevert:!0});h.push({id:C,status:O.status}),qq(O.status)?g.push(C):y.push(C)}catch(O){console.error(`anyray offboard: reverting ${C}: ${ii(O)}`),y.push(C)}}let w=!0;try{await a(h,!0,!0)}catch(C){w=!1,console.error(`anyray offboard: recording managed tools: ${ii(C)}`)}let b=y.length===0&&w,A=!1;if(b)try{await s(),A=!0}catch(C){console.error(`anyray offboard: stamping offboard: ${ii(C)}`)}try{((await t()).refreshSchedulerEnabled||await l())&&await c(),await d({...await t(),refreshSchedulerEnabled:!1})}catch(C){console.error(`anyray offboard: unit teardown: ${ii(C)}`)}return{reverted:g,unresolved:y,enrollmentCleared:m,credentialHeld:f,recordPersisted:w,offboardMarked:A,ok:y.length===0&&!f&&w&&A}};var te={success:0,unexpected:1,usage:2,authBroken:3,partial:4},Qq=`Stable non-interactive runtime commands:
|
|
876
876
|
anyray-connect reconcile
|
|
877
877
|
anyray-connect refresh
|
|
878
878
|
anyray-connect directives [--desktop-channel <staging|stable> --desktop-current <version>]
|
|
@@ -891,12 +891,12 @@ Exit codes:
|
|
|
891
891
|
1 unexpected error
|
|
892
892
|
2 usage error (unknown flag or argument)
|
|
893
893
|
3 authentication broken; re-enroll, or rotate a service key in the console
|
|
894
|
-
4 partial; the command ran but drift remains`,e6={reconcile:"reconcile",__anyray_reconcile:"reconcile",refresh:"refresh",__anyray_refresh:"refresh",directives:"directives",__anyray_directives:"directives",repair:"repair",__anyray_repair:"repair",status:"status",__anyray_status:"status",offboard:"offboard",__anyray_offboard:"offboard",desktop_update:"desktop-update",__anyray_desktop_update:"desktop-update"},t6=e=>e.replaceAll("-","_"),n6=/^\d+(\.\d+){1,3}(-[\w.]+)?$/,RP=(e,t,n)=>{if(e.length!==4)return;let r,o;for(let a=0;a<e.length;a+=2){let s=e[a],i=e[a+1];if(s===t&&(i==="staging"||i==="stable")){if(r)return;r=i}else if(s===n&&i&&n6.test(i)){if(o)return;o=i}else return}return r&&o?{channel:r,current:o}:void 0},r6=e=>RP(e,"--channel","--current"),o6=e=>RP(e,"--desktop-channel","--desktop-current"),OP=e=>{let t=e[0];if(!t)return;let n=e6[t6(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};if(n==="desktop-update"){let s=r6(r);return{verb:n,help:!1,usageError:!s,...s?{desktopUpdate:s}:{}}}if(n==="directives"&&r.length>0){let s=o6(r);return{verb:n,help:!1,usageError:!s,...s?{desktop:s}:{}}}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}},Zb=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},a6=async(e=N,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 Hs(n.gateway,n.clientKey);return await Gs(i)}catch(i){if(vw(i))return o?"credential-degraded":"auth-broken";throw i}},s6=e=>e==="auth-broken"?te.authBroken:e==="credential-degraded"||e.toolsApplied<e.toolsRequested||e.toolsTombstoned.length>0?te.partial:te.success,i6=e=>e.refresh==="not-enrolled"||e.refresh==="cert-expired"||e.refresh==="cert-rejected"?te.authBroken:e.refresh==="failed"?te.unexpected:e.partial||e.refresh==="disabled"||e.refresh==="backoff"||e.refresh==="throttled"||e.refresh==="gateway-incompatible"?te.partial:te.success,_P=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",c6=e=>{if(!(e.identity.keyKind!=="service"||!_P(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"},EP=async e=>{let t;return{code:await of({repair:e,quick:!e,silent:!0},{captureReport:r=>t=r}),authBroken:t?_P(t):!1,authBrokenReason:t?c6(t):void 0}},xP=(e,t,n)=>typeof e!="number"&&e.authBroken?(e.authBrokenReason&&n(`anyray-connect ${t}: ${e.authBrokenReason}`),te.authBroken):(typeof e=="number"?e:e.code)===0?te.success:te.partial,l6=(e,t)=>{let n=jb(t);return n===te.authBroken?n:e!==0||n===te.partial?te.partial:te.success},d6=async(e,t)=>{if(e==="reconcile")return s6(await(t.reconcile??(()=>a6(t.loadProfile)))());if(e==="refresh"){if(!t.refresh)throw new Error("refresh runtime is unavailable");return i6(await t.refresh())}let n=t.stderr??console.error;return e==="repair"?xP(await(t.repair??(()=>EP(!0)))(),e,n):e==="status"?xP(await(t.status??(()=>EP(!1)))(),e,n):(await(t.offboard??wf)()).ok?te.success:te.partial},Jb=(e,t)=>gf.parse({...e,lastVerb:{...e.lastVerb,exitCode:t}}),u6=async(e,t)=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.usageError||!e.desktopUpdate)return r("anyray-connect desktop-update: UsageError"),n(JSON.stringify({verb:"desktop-update",status:"unreachable",reason:"usage"})),te.usage;let o=e.desktopUpdate;try{let s=await(t.withProfileLock??xn)(()=>(t.desktopUpdate??ul)(o));return n(JSON.stringify({verb:"desktop-update",...s})),s.status==="none"||s.status==="staged"?te.success:te.unexpected}catch{return r("anyray-connect desktop-update: DesktopUpdateError"),n(JSON.stringify({verb:"desktop-update",status:"unreachable",reason:"engine"})),te.unexpected}},p6=e=>e.status==="not-enrolled"?te.authBroken:e.status==="unreachable"||e.status==="ran"&&e.outcome==="failed"?te.unexpected:te.success,f6=async(e,t)=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.usageError)return r("anyray-connect directives: UsageError"),n(JSON.stringify({verb:"directives",status:"unreachable"})),te.usage;let o;try{o=await(t.withProfileLock??xn)(async()=>{if(!t.directives)throw new Error("directives runtime is unavailable");return t.directives({desktop:e.desktop})})}catch{r("anyray-connect directives: Error"),o={status:"unreachable"}}return n(JSON.stringify({verb:"directives",...o})),p6(o)},TP=async(e,t={})=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.help)return n(Qq),te.success;if(e.verb==="desktop-update")return u6(e,t);if(e.verb==="directives")return f6(e,t);let o=t.now??Date.now,a=new Date(o()).toISOString(),s=t.withProfileLock??xn,i=t.buildStatus??SP,c=t.writeStatus??IP,l,d=e.usageError?te.usage:te.unexpected;e.usageError&&r(`anyray-connect ${e.verb}: UsageError`);try{await s(async()=>{if(!e.usageError)try{d=Vb.parse(await d6(e.verb,t))}catch(u){d=vw(u)?te.authBroken:te.unexpected,r(`anyray-connect ${e.verb}: ${Zb(u)}`)}if(l=await i({verb:e.verb,exitCode:d,at:a},{now:o}),(e.verb==="repair"||e.verb==="status")&&d!==te.unexpected&&d!==te.usage&&d!==te.authBroken)d=l6(d===0?0:1,l);else if(e.verb!=="offboard"&&d!==te.unexpected&&d!==te.usage){let u=jb(l);(u===te.authBroken||d===te.success)&&(d=u)}l=Jb(l,d);try{await c(l)}catch(u){d=te.unexpected,l=Jb(l,d),r(`anyray-connect ${e.verb}: ${Zb(u)}`)}})}catch(u){d=te.unexpected,r(`anyray-connect ${e.verb}: ${Zb(u)}`);try{l=Jb(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 PP=new Set(["not-due","repaired","cert-renewed","heartbeat-refreshed","refreshed"]),DP=async(e,t={})=>await(t.fleetdPresent??_a)()?PP.has(e)?{retired:!0,messages:(await(t.uninstallScheduler??fr)()).messages}:{retired:!1,reason:"refresh-unhealthy",messages:[]}:{retired:!1,reason:"no-fleetd",messages:[]},LP=async(e,t={})=>{if(!PP.has(e))return{retired:!1,reason:"refresh-unhealthy",messages:[]};let r=await(t.load??N)().catch(()=>{});if(!r)return{retired:!1,reason:"no-profile",messages:[]};if(!r.refreshSchedulerEnabled||r.persistenceOwner==="tray")return{retired:!1,reason:"not-installed",messages:[]};if(ot(r,{},t.now??Date.now()))return{retired:!1,reason:"still-needed",messages:[]};let o=await(t.uninstallScheduler??fr)();if(!o.ok)return{retired:!1,reason:"uninstall-failed",messages:o.messages};if(await(t.schedulerInstalled??Nn)().catch(()=>!0))return{retired:!1,reason:"uninstall-failed",messages:o.messages};let s=t.mutate??yi;return await s(l=>!l.refreshSchedulerEnabled||l.persistenceOwner==="tray"||ot(l,{},t.now??Date.now())?{result:!1}:{next:{...l,refreshSchedulerEnabled:!1,refreshSchedulerInstalledOnce:!1},result:!0}).catch(()=>!1)?await(t.schedulerInstalled??Nn)().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 bf=["reapply_config","remint","revert","revert_tool","update"],m6=/^[a-z0-9][a-z0-9-]{0,31}$/;var $P=e=>e?bf:bf.filter(t=>t!=="update"),h6=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"||!bf.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&m6.test(t.tool):t.tool===void 0},NP=e=>e?.name??"error",Xb=async(e,t,n)=>{let r=n.fetchImpl??fetch,o=n.kinds??bf,a=e.replace(/\/$/,""),s=await r(`${a}/connect/directive`,{method:"GET",headers:{"x-anyray-api-key":t,"x-anyray-directive-kinds":o.join(",")},signal:AbortSignal.timeout(1e4)});if(s.status===404)return null;if(!s.ok)throw new Error("directive pull failed");let i=await s.json();if(!h6(i.directive))return null;let c=i.directive;if(!o.includes(c.kind))return null;let l;try{l=await n.execute(c.kind,c.tool)}catch(d){console.error("connect directive execution failed:",NP(d)),l="failed"}if(l==="deferred")return{kind:c.kind,outcome:l};try{await r(`${a}/connect/directive/ack`,{method:"POST",headers:{"x-anyray-api-key":t,"content-type":"application/json"},body:JSON.stringify({id:c.id,result:l}),signal:AbortSignal.timeout(1e4)})}catch(d){console.error("connect directive ack skipped:",NP(d))}return{kind:c.kind,outcome:l}};var MP=e=>e?.name??"Error",zb=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??N,r=t.recordManagedTools??Vr,o=t.adapterById??Qe,a=t.isLocked??nl,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}: ${MP(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${MP(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{basename as y6}from"node:path";import{join as BP}from"node:path";var g6="history.recentlyOpenedPathsList",w6={"ssh-remote":"ssh","dev-container":"devcontainer","attached-container":"attached-container",wsl:"wsl",codespaces:"codespace",tunnel:"tunnel"},b6=e=>{try{let t=JSON.parse(Buffer.from(e,"hex").toString("utf-8"));if(typeof t.hostPath=="string"&&t.hostPath)return{name:y6(t.hostPath),hostPath:t.hostPath};if(typeof t.containerName=="string"&&t.containerName)return{name:t.containerName.replace(/^\//,"")}}catch{}return{name:"container"}},k6=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=w6[n.slice(0,r)];if(!o)return;let a=n.slice(r+1);if(a){if(o==="devcontainer"||o==="attached-container"){let s=b6(a);return{kind:o,name:s.name,...o==="devcontainer"&&s.hostPath?{ref:s.hostPath}:{}}}return{kind:o,name:a}}},C6=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=k6(i);if(!c)continue;let l=`${c.kind}|${c.ref??c.name}`;r.has(l)||(r.add(l),n.push(c))}}return n},A6=()=>[...Xo.map(e=>BP(Bd(e),"User","globalStorage","state.vscdb")),BP(We("Cursor"),"User","globalStorage","state.vscdb")],qb=async(e={})=>{let t=e.readItem??(()=>{let o=ro();return o?o.readItem.bind(o):void 0})();if(!t)return[];let n=[],r=new Set;for(let o of e.dbPaths??A6()){let a;try{a=t(o,g6)}catch{continue}if(a)for(let s of C6(a)){let i=`${s.kind}|${s.ref??s.name}`;r.has(i)||(r.add(i),n.push(s))}}return n};import{execFile as v6,spawn as S6}from"node:child_process";import{promisify as I6}from"node:util";var E6="https://app.anyray.ai/connect.sh",x6=".anyray/bin/anyray-connect",ci=e=>`'${e.replaceAll("'",`'"'"'`)}'`,R6=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=${ci(`connect-v${Ne}`)} \\`,` sh -c ${ci(`curl -fsSL ${E6} | sh`)} >&2 </dev/null`,`echo "$HOME/${x6}"`].join(`
|
|
894
|
+
4 partial; the command ran but drift remains`,e4={reconcile:"reconcile",__anyray_reconcile:"reconcile",refresh:"refresh",__anyray_refresh:"refresh",directives:"directives",__anyray_directives:"directives",repair:"repair",__anyray_repair:"repair",status:"status",__anyray_status:"status",offboard:"offboard",__anyray_offboard:"offboard",desktop_update:"desktop-update",__anyray_desktop_update:"desktop-update"},t4=e=>e.replaceAll("-","_"),n4=/^\d+(\.\d+){1,3}(-[\w.]+)?$/,RP=(e,t,n)=>{if(e.length!==4)return;let r,o;for(let a=0;a<e.length;a+=2){let s=e[a],i=e[a+1];if(s===t&&(i==="staging"||i==="stable")){if(r)return;r=i}else if(s===n&&i&&n4.test(i)){if(o)return;o=i}else return}return r&&o?{channel:r,current:o}:void 0},r4=e=>RP(e,"--channel","--current"),o4=e=>RP(e,"--desktop-channel","--desktop-current"),OP=e=>{let t=e[0];if(!t)return;let n=e4[t4(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};if(n==="desktop-update"){let s=r4(r);return{verb:n,help:!1,usageError:!s,...s?{desktopUpdate:s}:{}}}if(n==="directives"&&r.length>0){let s=o4(r);return{verb:n,help:!1,usageError:!s,...s?{desktop:s}:{}}}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}},Zb=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},a4=async(e=L,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 Hs(n.gateway,n.clientKey);return await Gs(i)}catch(i){if(vw(i))return o?"credential-degraded":"auth-broken";throw i}},s4=e=>e==="auth-broken"?te.authBroken:e==="credential-degraded"||e.toolsApplied<e.toolsRequested||e.toolsTombstoned.length>0?te.partial:te.success,i4=e=>e.refresh==="not-enrolled"||e.refresh==="cert-expired"||e.refresh==="cert-rejected"?te.authBroken:e.refresh==="failed"?te.unexpected:e.partial||e.refresh==="disabled"||e.refresh==="backoff"||e.refresh==="throttled"||e.refresh==="gateway-incompatible"?te.partial:te.success,_P=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",c4=e=>{if(!(e.identity.keyKind!=="service"||!_P(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"},EP=async e=>{let t;return{code:await of({repair:e,quick:!e,silent:!0},{captureReport:r=>t=r}),authBroken:t?_P(t):!1,authBrokenReason:t?c4(t):void 0}},xP=(e,t,n)=>typeof e!="number"&&e.authBroken?(e.authBrokenReason&&n(`anyray-connect ${t}: ${e.authBrokenReason}`),te.authBroken):(typeof e=="number"?e:e.code)===0?te.success:te.partial,l4=(e,t)=>{let n=jb(t);return n===te.authBroken?n:e!==0||n===te.partial?te.partial:te.success},d4=async(e,t)=>{if(e==="reconcile")return s4(await(t.reconcile??(()=>a4(t.loadProfile)))());if(e==="refresh"){if(!t.refresh)throw new Error("refresh runtime is unavailable");return i4(await t.refresh())}let n=t.stderr??console.error;return e==="repair"?xP(await(t.repair??(()=>EP(!0)))(),e,n):e==="status"?xP(await(t.status??(()=>EP(!1)))(),e,n):(await(t.offboard??wf)()).ok?te.success:te.partial},Jb=(e,t)=>gf.parse({...e,lastVerb:{...e.lastVerb,exitCode:t}}),u4=async(e,t)=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.usageError||!e.desktopUpdate)return r("anyray-connect desktop-update: UsageError"),n(JSON.stringify({verb:"desktop-update",status:"unreachable",reason:"usage"})),te.usage;let o=e.desktopUpdate;try{let s=await(t.withProfileLock??xn)(()=>(t.desktopUpdate??ul)(o));return n(JSON.stringify({verb:"desktop-update",...s})),s.status==="none"||s.status==="staged"?te.success:te.unexpected}catch{return r("anyray-connect desktop-update: DesktopUpdateError"),n(JSON.stringify({verb:"desktop-update",status:"unreachable",reason:"engine"})),te.unexpected}},p4=e=>e.status==="not-enrolled"?te.authBroken:e.status==="unreachable"||e.status==="ran"&&e.outcome==="failed"?te.unexpected:te.success,f4=async(e,t)=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.usageError)return r("anyray-connect directives: UsageError"),n(JSON.stringify({verb:"directives",status:"unreachable"})),te.usage;let o;try{o=await(t.withProfileLock??xn)(async()=>{if(!t.directives)throw new Error("directives runtime is unavailable");return t.directives({desktop:e.desktop})})}catch{r("anyray-connect directives: Error"),o={status:"unreachable"}}return n(JSON.stringify({verb:"directives",...o})),p4(o)},TP=async(e,t={})=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.help)return n(Qq),te.success;if(e.verb==="desktop-update")return u4(e,t);if(e.verb==="directives")return f4(e,t);let o=t.now??Date.now,a=new Date(o()).toISOString(),s=t.withProfileLock??xn,i=t.buildStatus??SP,c=t.writeStatus??IP,l,d=e.usageError?te.usage:te.unexpected;e.usageError&&r(`anyray-connect ${e.verb}: UsageError`);try{await s(async()=>{if(!e.usageError)try{d=Vb.parse(await d4(e.verb,t))}catch(u){d=vw(u)?te.authBroken:te.unexpected,r(`anyray-connect ${e.verb}: ${Zb(u)}`)}if(l=await i({verb:e.verb,exitCode:d,at:a},{now:o}),(e.verb==="repair"||e.verb==="status")&&d!==te.unexpected&&d!==te.usage&&d!==te.authBroken)d=l4(d===0?0:1,l);else if(e.verb!=="offboard"&&d!==te.unexpected&&d!==te.usage){let u=jb(l);(u===te.authBroken||d===te.success)&&(d=u)}l=Jb(l,d);try{await c(l)}catch(u){d=te.unexpected,l=Jb(l,d),r(`anyray-connect ${e.verb}: ${Zb(u)}`)}})}catch(u){d=te.unexpected,r(`anyray-connect ${e.verb}: ${Zb(u)}`);try{l=Jb(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 PP=new Set(["not-due","repaired","cert-renewed","heartbeat-refreshed","refreshed"]),DP=async(e,t={})=>await(t.fleetdPresent??_a)()?PP.has(e)?{retired:!0,messages:(await(t.uninstallScheduler??fr)()).messages}:{retired:!1,reason:"refresh-unhealthy",messages:[]}:{retired:!1,reason:"no-fleetd",messages:[]},NP=async(e,t={})=>{if(!PP.has(e))return{retired:!1,reason:"refresh-unhealthy",messages:[]};let r=await(t.load??L)().catch(()=>{});if(!r)return{retired:!1,reason:"no-profile",messages:[]};if(!r.refreshSchedulerEnabled||r.persistenceOwner==="tray")return{retired:!1,reason:"not-installed",messages:[]};if(ot(r,{},t.now??Date.now()))return{retired:!1,reason:"still-needed",messages:[]};let o=await(t.uninstallScheduler??fr)();if(!o.ok)return{retired:!1,reason:"uninstall-failed",messages:o.messages};if(await(t.schedulerInstalled??Ln)().catch(()=>!0))return{retired:!1,reason:"uninstall-failed",messages:o.messages};let s=t.mutate??yi;return await s(l=>!l.refreshSchedulerEnabled||l.persistenceOwner==="tray"||ot(l,{},t.now??Date.now())?{result:!1}:{next:{...l,refreshSchedulerEnabled:!1,refreshSchedulerInstalledOnce:!1},result:!0}).catch(()=>!1)?await(t.schedulerInstalled??Ln)().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 bf=["reapply_config","remint","revert","revert_tool","update"],m4=/^[a-z0-9][a-z0-9-]{0,31}$/;var $P=e=>e?bf:bf.filter(t=>t!=="update"),h4=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"||!bf.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&m4.test(t.tool):t.tool===void 0},LP=e=>e?.name??"error",Xb=async(e,t,n)=>{let r=n.fetchImpl??fetch,o=n.kinds??bf,a=e.replace(/\/$/,""),s=await r(`${a}/connect/directive`,{method:"GET",headers:{"x-anyray-api-key":t,"x-anyray-directive-kinds":o.join(",")},signal:AbortSignal.timeout(1e4)});if(s.status===404)return null;if(!s.ok)throw new Error("directive pull failed");let i=await s.json();if(!h4(i.directive))return null;let c=i.directive;if(!o.includes(c.kind))return null;let l;try{l=await n.execute(c.kind,c.tool)}catch(d){console.error("connect directive execution failed:",LP(d)),l="failed"}if(l==="deferred")return{kind:c.kind,outcome:l};try{await r(`${a}/connect/directive/ack`,{method:"POST",headers:{"x-anyray-api-key":t,"content-type":"application/json"},body:JSON.stringify({id:c.id,result:l}),signal:AbortSignal.timeout(1e4)})}catch(d){console.error("connect directive ack skipped:",LP(d))}return{kind:c.kind,outcome:l}};var MP=e=>e?.name??"Error",zb=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??L,r=t.recordManagedTools??Vr,o=t.adapterById??Qe,a=t.isLocked??nl,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}: ${MP(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${MP(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{basename as y4}from"node:path";import{join as BP}from"node:path";var g4="history.recentlyOpenedPathsList",w4={"ssh-remote":"ssh","dev-container":"devcontainer","attached-container":"attached-container",wsl:"wsl",codespaces:"codespace",tunnel:"tunnel"},b4=e=>{try{let t=JSON.parse(Buffer.from(e,"hex").toString("utf-8"));if(typeof t.hostPath=="string"&&t.hostPath)return{name:y4(t.hostPath),hostPath:t.hostPath};if(typeof t.containerName=="string"&&t.containerName)return{name:t.containerName.replace(/^\//,"")}}catch{}return{name:"container"}},k4=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=w4[n.slice(0,r)];if(!o)return;let a=n.slice(r+1);if(a){if(o==="devcontainer"||o==="attached-container"){let s=b4(a);return{kind:o,name:s.name,...o==="devcontainer"&&s.hostPath?{ref:s.hostPath}:{}}}return{kind:o,name:a}}},C4=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=k4(i);if(!c)continue;let l=`${c.kind}|${c.ref??c.name}`;r.has(l)||(r.add(l),n.push(c))}}return n},A4=()=>[...Xo.map(e=>BP(Bd(e),"User","globalStorage","state.vscdb")),BP(We("Cursor"),"User","globalStorage","state.vscdb")],qb=async(e={})=>{let t=e.readItem??(()=>{let o=ro();return o?o.readItem.bind(o):void 0})();if(!t)return[];let n=[],r=new Set;for(let o of e.dbPaths??A4()){let a;try{a=t(o,g4)}catch{continue}if(a)for(let s of C4(a)){let i=`${s.kind}|${s.ref??s.name}`;r.has(i)||(r.add(i),n.push(s))}}return n};import{execFile as v4,spawn as S4}from"node:child_process";import{promisify as I4}from"node:util";var E4="https://app.anyray.ai/connect.sh",x4=".anyray/bin/anyray-connect",ci=e=>`'${e.replaceAll("'",`'"'"'`)}'`,R4=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=${ci(`connect-v${Le}`)} \\`,` sh -c ${ci(`curl -fsSL ${E4} | sh`)} >&2 </dev/null`,`echo "$HOME/${x4}"`].join(`
|
|
895
895
|
`)}
|
|
896
|
-
`;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}}},
|
|
897
|
-
`;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}}},
|
|
898
|
-
`).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]},FP=(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)}),ek=async(e,t,n={})=>{let r=n.spawn??
|
|
899
|
-
`).map(c=>c.trim()).filter(Boolean).at(-1);return s?(await FP(
|
|
896
|
+
`;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}}},O4=(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=[ci(n),"--yes","--key-stdin","--gateway",ci(t.gateway),...t.user!==void 0?["--user",ci(t.user)]:[],...t.team!==void 0?["--team",ci(t.team)]:[]].join(" "),a=`${t.clientKey}
|
|
897
|
+
`;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}}},_4=I4(v4),T4=async(e,t)=>(await _4(e,[...t],{encoding:"utf8"})).stdout.toString(),Qb=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??T4)("docker",["ps","--filter",`label=devcontainer.local_folder=${r}`,"--format","{{.ID}}"])).split(`
|
|
898
|
+
`).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]},FP=(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)}),ek=async(e,t,n={})=>{let r=n.spawn??S4,o=e.kind==="devcontainer"&&e.ref?{...e,name:await Qb(e,n)}:e,a=await FP(R4(o),r,!0);if(a.code!==0)return a.code;let s=a.stdout.split(`
|
|
899
|
+
`).map(c=>c.trim()).filter(Boolean).at(-1);return s?(await FP(O4(o,t,s),r,!1)).code:1};import{spawnSync as P4}from"node:child_process";import{platform as vf}from"node:os";import{basename as D4}from"node:path";import{createInterface as N4}from"node:readline";var HP=`${Z("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
900
900
|
|
|
901
901
|
${Z("Usage")}
|
|
902
902
|
npx anyray-connect [options]
|
|
@@ -1176,22 +1176,22 @@ ${Z("What it does")}
|
|
|
1176
1176
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1177
1177
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1178
1178
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1179
|
-
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
1180
|
-
${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?`}`,
|
|
1181
|
-
${o} ${n} tool target(s)?`;return await(r.confirm??ya)(a)?"proceed":"declined"},c4=async(e=Ps)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0,initiator:"directive"});switch(t.outcome){case"current":case"updated":case"migrated":case"container":case"sidecar":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}},ak=e=>ZP(e,!1,{managedEnrollmentCarrier:!0}),l4=e=>ff(mf(ak),{json:e}),d4=new Set(["managed","durable","npm"]),VP=async(e={})=>{let t=await(e.load??N)().catch(()=>{});if(!t?.gateway||!t.clientKey)return{status:"not-enrolled"};let{gateway:n,clientKey:r}=t,o=await(e.runtimeKind??(async()=>(await Uc()).kind))().catch(()=>"unmanaged"),a,s=async(c,l)=>{if(c==="revert_tool"&&!await(e.refreshToolPolicy??Sw)(n,r).then(()=>!0,()=>!1))return"deferred";if(c==="update"&&o==="sidecar"&&e.desktop){if(!$g({mode:t.fleetUpdatePolicy?.mode??"auto",initiator:"directive"}).allow)return"failed";let u=await(e.stageDesktop??ul)(e.desktop);return u.status==="staged"?(a=u,"deferred"):u.status==="none"?u.artifact===!1?"deferred":"ok":u.status==="rejected"?"failed":"deferred"}return e.execute?e.execute(c,l):c==="remint"||c==="reapply_config"?await an({force:!0})==="failed"?"failed":"ok":c==="revert_tool"?zb(l):c==="update"?c4():(await wf()).ok?"ok":"failed"},i;try{let c=d4.has(o)||o==="sidecar"&&e.desktop!==void 0,l=o==="sidecar"&&e.desktop!==void 0;i=await Xb(n,r,{execute:s,kinds:$P(c&&!l),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),!i&&l&&(i=await Xb(n,r,{execute:s,kinds:["update"],...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}))}catch{return{status:"unreachable"}}return i?i.outcome==="deferred"?i.kind==="update"&&a?{status:"staged",kind:"update",version:a.version,path:a.path,...a.minVersion?{minVersion:a.minVersion}:{}}:{status:"unreachable"}:{status:"ran",kind:i.kind,outcome:i.outcome}:{status:"none"}},u4=async()=>{let e=!1,t=await iP(await an({runAmbientSelfcheck:!0}),{...mf(ak),refresh:()=>an({})});await cP(mf(ak)),await Cm(),await IO(),await EO()==="retry"&&(e=!0);let n=await N().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await pe(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await _a().catch(()=>!1);if(n&&(await DP(t,{fleetdPresent:async()=>r}).catch(()=>{}),await LP(t).catch(()=>{}),r&&n.gateway&&n.clientKey)){let a=n.gateway,s=n.clientKey,i=on(),c=n.enrolledCert;if(i&&c){let l=await Ye().catch(()=>{});l&&await sR(a,s,c,l,i).catch(()=>{})}}let o=await VP();return o.status==="ran"&&o.outcome==="failed"&&(e=!0),r||await Ps(),{refresh:t,...e?{partial:!0}:{}}},p4=async(e,t={})=>{if(e[0]==="__anyray-hook"){let a=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return WT(a)}if(e[0]==="__anyray-hook-lifecycle")return FT();if(e[0]==="__anyray-codex-hook")return HT();if(e[0]==="__anyray-prompt-hook")return jT();if(e[0]==="__anyray-shell-pretool")return XT();if(e[0]==="__anyray-shell-run")return JT(e.slice(1));if(e[0]==="__anyray-read-pretool")return oP();if(e[0]==="__anyray-sso-gate")return VT(e.slice(1));if(e[0]==="__anyray-sso-poll")return lP();if(e[0]==="__anyray-managed-enroll")try{return await xn(()=>l4(e.slice(1).includes("--json")),{waitMs:KP})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return uP();if(e[0]==="__anyray-spawn-refresh")return await Eo(),0;if(e[0]==="__anyray-mcp-server"){let a=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return kP(a)}if(e[0]==="__anyray-acp-agent")return CP(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return x0(e.slice(1));let n=OP(e);if(n)return TP(n,{refresh:u4,desktopUpdate:ul,directives:a=>VP(a)});if(e[0]==="__anyray-persistence")return LC(e.slice(1));if(e[0]==="__anyray-quit-watch")return gx(e.slice(1));if(e[0]===ho)return YO(e.slice(1));if(e[0]===pc)return JO(e.slice(1));if(e[0]===Vo){let a=e[1];return a&&await lp(a),0}if(e[0]==="--version"||e[0]==="-V")return dP();try{let a=await Ik(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),ik(e)&&sr({event:"error",code:"enroll-failed",message:s}),1}if(o4(e)){let a=r4(await qx());a?.level==="warn"?P(a.message):a&&console.error(a.message)}let r=Vw(e[0]);if(r)return r.run(e.slice(1));if(e[0]==="desktop"){let a=e.slice(1),s=eb(a);return s?nk(s,!1,t.apply):s_(a)}if(e[0]==="remote")return C4(e.slice(1));let o=e[0];if(o&&t4.has(o)){let a=e.slice(1),s;try{s=Sf(a)}catch(i){return D(i.message),k("\nRun `npx anyray-connect --help` for usage."),1}return s.help?(k(s.helpAll?Af:HP),0):o==="status"?W_({gateway:s.gateway}):o==="doctor"?of({gateway:s.gateway,json:s.json,verify:s.verify,noVerify:s.noVerify,quick:s.quick,repair:s.repair,securityReview:s.securityReview}):o==="sync"?tT({gateway:s.gateway}):o==="device-url"?UO():nk(a,!0,t.apply)}return nk(e,!1,t.apply)},jP=async(e,t={})=>{Cg();let n=a4(e);if(n?.json&&(kg(),!n.yes)){let r="--json enrollment requires --yes.";return sr({event:"error",code:"yes-required",message:r}),D(r),1}try{return await p4(e,t)}catch(r){if(r instanceof Et)return console.error(v("Cancelled.")),130;throw r}},f4=e=>{let t=process.platform==="win32"?"where":"which";try{return P6(t,[e],{stdio:"ignore"}).status===0}catch{return!1}},m4=(e,t={})=>{let n=t.which??f4,r=t.platform??vf;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")}},h4=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}},y4=(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?`}},g4=e=>e.interactive&&!e.managed&&!e.yes&&!e.revert&&!e.dryRun,w4=async(e,t={})=>{if(!g4(e)||!Pe(e.clientKey))return;let n=t.discoverRemoteEnvironments??qb,r;try{r=await n()}catch{return}let o=t.confirm??ya,a=t.runRemoteApply??ek,s=t.isCarrierAvailable??m4,i=t.resolveDevcontainer??Qb;for(let c of r){let l=h4(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(y4(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(YP(d.kind))}},YP=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`."}},b4="usage: anyray-connect remote <ssh-host> [--yes] [--dry-run] | remote --devcontainer <host-path> | --wsl <distro> | --codespace <name> [--yes] [--dry-run]",k4=e=>{let t=/[/\\]/.test(e);return{kind:"devcontainer",name:t?D6(e.replaceAll("\\","/")):e,...t?{ref:e}:{}}},C4=async(e,t={})=>{if(e[0]==="--help"||e[0]==="-h")return console.log(Af),0;let n=e[0]&&!e[0].startsWith("-")?e[0]:void 0,r;try{r=Sf(n?e.slice(1):e)}catch(h){return D(h instanceof Error?h.message:String(h)),1}if(r.help)return console.log(Af),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(b4),1;let a=n?{kind:"ssh",name:n}:r.devcontainer!==void 0?k4(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??vf)()!=="win32")return D("--wsl is available only on Windows (win32)."),1;let s=t.isInteractive??xt;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 GP()}catch{return D("could not read the personal gateway key from stdin."),1}let c=await(t.loadProfile??N)(),l=!r.gateway&&!process.env.ANYRAY_GATEWAY_URL?c.gateway:void 0,d=dn(r.gateway??l),u=i||process.env.ANYRAY_CLIENT_KEY?.trim()||rk(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 vg(r.user,c.name,r.yes),m=await Sg(r.team,c.team,r.yes),f;try{f=await(t.runRemoteApply??ek)(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(YP(a.kind))),f},ZP=async(e,t,n={})=>{Cg();let r=ik(e);r&&kg();let o=(L,_)=>{r&&sr({event:"error",code:L,message:_})},a=(L,_)=>(D(_),o(L,_),1),s=n.isInteractive??xt,i;try{i=Sf(e)}catch(L){return a("invalid-args",L.message),k("\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&&pw(L)?"enroll-rejected":L instanceof bt||L instanceof Ot||L instanceof sn||L instanceof Wt?L.kind:L instanceof zc?"gateway-unreachable":L instanceof qc?"cp-unreachable":L instanceof ct&&L.policyCode==="sso_required"?"sso-required":"enroll-failed";if(i.help)return k(i.helpAll?Af:HP),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."):(sk()||In(rk(await N()))==="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."):VO({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 _=i.upstreamKey.trim();if(!_)return a("invalid-args","--upstream-key must not be empty.");d={url:dt(i.upstream),key:_}}let u=await N(),p;if(i.keyStdin)try{p=await GP()}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&&xt()&&!i.gateway&&!i.revert&&!i.yes&&!i.dryRun&&!i.enroll&&!i.sso&&!i.signIn,f=!1;(t||m)&&s()&&(i=await(n.runWizard??q6)(i,u),f=!0);let h;try{h=$6(i.tools)}catch(L){return a("apply-failed",L.message)}k(Z(i.revert?"Anyray connect \u2014 revert":"Anyray connect")),i.gateway&&!i.enroll&&Xc(i.gateway)&&(i.enroll=i.gateway,i.gateway=void 0,k("That looks like an enrollment link \u2014 treating it as --enroll."));let g,y,w,b,A=!1;if(i.enroll){let L=Ip(i.enroll);if(L&&(i.desktopApp||!i.gateway||u.enrolledCert||sw(L.token)))try{let _=await zs("Resolving enrollment link\u2026",()=>(n.resolveEnrollLink??eR)(L)),V=!i.gateway;if(V&&(i.gateway=_.gatewayUrl),g=_.deploymentId,y=_.email,w=_.provisioningKind,b=_.allowedDomains,A=!0,i.desktopApp&&!_.email)return a("invalid-link","The desktop app accepts personal links only. Ask your admin for a personal link.");V&&M(`Enrollment link${_.org?` for ${_.org}`:""}: gateway ${_.gatewayUrl}`),_.seatMode&&!i.subscription&&(i.subscription=!0,M("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(_){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(sw(L.token))return a(l(_),_ instanceof Error?_.message:String(_));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",_ instanceof Error?_.message:String(_))}}let C,x;if(r&&await(n.clearGateState??pl)(),i.claim&&!i.revert)if(i.dryRun)M("dry run: not enrolled (skipped redeeming the enrollment link).");else{let L=fR(i.claim);if(!L)return a("invalid-link","invalid --claim value: expected the sdc_ code from your organization's Anyray page.");try{let _=await zs("Connecting this machine\u2026",()=>(n.redeemClaim??mR)({cpOrigin:L.cpOrigin,claim:L.claim,gatewayUrl:i.gateway}));C={cert:_.cert,privateKeyPem:_.privateKeyPem},_.deploymentId&&(g=_.deploymentId),!i.gateway&&_.gatewayUrl&&(i.gateway=_.gatewayUrl),x=_.ssoLink}catch(_){return a(l(_),_ instanceof Error?_.message:String(_))}}if(i.sso&&!C&&!i.revert)if(i.dryRun)M("dry run: not enrolled via SSO (skipped minting a personal key).");else{let L=Ft(i.sso);if(!L){let _=Xc(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",_)}try{let _=await(n.startDeviceGrant??Ep)({cpOrigin:L.cpOrigin,tenantId:L.tenantId,gatewayUrl:i.gateway,log:r?void 0:_e=>M(_e),open:!r&&s()?Lr:void 0});r&&sr({event:"sso_grant",verificationUriComplete:_.verificationUriComplete,userCode:_.userCode,expiresAt:new Date(_.grantExpiresAt).toISOString(),tenantId:_.tenantId});let V=await zs("Waiting for SSO sign-in\u2026",()=>(n.pollDeviceGrant??xp)(_,{gatewayUrl:i.gateway}));C={cert:V.cert,privateKeyPem:V.privateKeyPem},V.deploymentId&&(g=V.deploymentId),!i.gateway&&V.gatewayUrl&&(i.gateway=V.gatewayUrl)}catch(_){return a(l(_),_ instanceof Error?_.message:String(_))}}if(i.signIn&&!C&&!i.revert)if(i.dryRun)M("dry run: not signed in (skipped minting a personal key).");else{let L;try{let _=await(n.createDesktopSignInCallbackListener??w_)();L=_;let V=await(n.startDesktopSignIn??A_)({callbackUri:_.callbackUri,log:r?void 0:nt=>M(nt),open:!r&&s()?Lr:void 0});r&&sr({event:"sso_grant",verificationUriComplete:V.browserUrl,userCode:V.userCode,expiresAt:new Date(V.grantExpiresAt).toISOString()});let _e=await zs("Waiting for sign-in\u2026",async()=>{let nt=await _.waitForCompletion(V);return(n.pollDesktopSignIn??v_)(V,{completion:nt})});C={cert:_e.cert,privateKeyPem:_e.privateKeyPem},_e.deploymentId&&(g=_e.deploymentId),!i.gateway&&_e.gatewayUrl&&(i.gateway=_e.gatewayUrl)}catch(_){return a(l(_),_ instanceof Error?_.message:String(_))}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=dn(i.gateway)}catch(L){return a("enroll-failed",L.message)}let E,T;O&&!i.revert&&M(`Gateway: ${S} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!i.revert&&dk(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 I=p??process.env.ANYRAY_CLIENT_KEY?.trim(),K=I||rk(u),G,X,ae,Ae,me,U,Q=async L=>{await Ea();let _=rR(L.token),V=iR(u.enrolledCert,u.enrolledCertExpiry,L.deploymentId,Date.now(),_,u.enrolledTokenHash,L.expectedUser),_e=V?await Ye():void 0,nt=on()||void 0,Gt=V&&_e&&u.enrolledCert?{cert:u.enrolledCert,privateKeyPem:_e,publicKeyPem:u.enrolledCert.payload.devPublicKey}:void 0,Ct=Te=>(n.enrollAndVerify??cR)({cpOrigin:L.cpOrigin,token:L.token,gatewayOrigin:S,email:L.email,team:L.team,machineId:L.machineId,deploymentId:L.deploymentId,machineUuid:nt,reuse:Te?Gt:void 0}),Ve=!!Gt,je=await(async()=>{try{return await Ct(Ve)}catch(Te){if(Gt&&Te instanceof ct&&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=kf(i.user,je.user),i.team=kf(i.team,je.team),G=je.cert,X=je.cert.payload.expiresAt,U=je.expiresAt,me=void 0,Ve||(ae=je.privateKeyPem),Ve||(Ae=_),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=Ip(i.enroll);if(!L){let _=Q0(i.enroll),V=_?`that is ${_.what}, not an enrollment link \u2014 re-run with ${_.flag} instead of --enroll.`:Ft(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 _=i.machine?Mp():void 0,V=w==="mdm"&&!y?h_():void 0,_e=w==="mdm"&&!y&&!V?m_(b,qu()):void 0,nt=V??_e;if(nt){let Ve=V?"the email your MDM assigned to this machine":`${nt} (this Mac's login name at the first allowed domain)`;k(i.user?.trim()&&i.user.trim()!==nt?`Ignoring --user: enrolling as ${Ve}.`:`Enrolling as ${Ve}.`)}let Gt=y??nt??N6(i.user);if(!i.machine&&!i.user&&!y&&!nt){let Ve=Ax();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:${_}`:A?Gt:void 0;await Q({cpOrigin:L.cpOrigin,token:L.token,email:Gt,team:i.team,machineId:_,deploymentId:g,expectedUser:Ct})}catch(_){let V=_ instanceof Error?_.message:String(_);return D(V),o(l(_),V),_ instanceof ct&&_.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."),pw(_)?3:1}}if(C){await Ea();try{let L=on()||void 0,_=await(n.verifyWithGateway??Sn)(S,C.cert,C.privateKeyPem,{machineUuid:L});K=_.key,i.user=kf(i.user,_.user),i.team=kf(i.team,_.team),G=C.cert,X=C.cert.payload.expiresAt,ae=C.privateKeyPem,U=_.expiresAt;let V=i.sso?Ft(i.sso):void 0;me=V?`${V.cpOrigin}/sso/${V.tenantId}`:x,B(`Enrolled${_.user?` as ${_.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(L){let _=L instanceof Error?L.message:String(L);return D(_),o(l(L),_),L instanceof ct&&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=In(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;E=await vg(i.user,u.name,L),T=await Sg(i.team,u.team,L)}if(!i.revert&&!i.dryRun){let L=M_(await $_(S,K),{subscription:i.subscription,org:i.placeholder,byoUpstream:!!d});if(L.lane){let _=L.lane==="subscription";i.subscription=_,i.placeholder=!_;let V=_?"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 Vn(),W("Detecting your sign-ins"),k(` Claude (Anthropic): ${d?it("BYO upstream key (passthrough)"):we.anthropic?it("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${we.openai?it("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),(!we.anthropic||!we.openai)&&K&&await U_(Re({origin:S,placeholderKey:i.key,clientKey:K,subscription:!1,placeholder:!0,byoUpstream:d,user:E,team:T,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&&ur()&&(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=Re({origin:S,placeholderKey:i.key,clientKey:K,subscription:i.subscription,placeholder:i.placeholder,byoUpstream:d,seat:we,user:E,team:T,intent:i.intent,intentLabel:i.intentLabel,session:i.session}),Ie=i.revert===!0&&(i.tools?.length??0)===0,cn={dryRun:i.dryRun,fullRevert:Ie};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){W("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 UP(h,"after-enrollment"),M(`
|
|
1182
|
-
Dry run complete \u2014 no files were written.`),0):a("enroll-failed",` ${
|
|
1183
|
-
Dry run \u2014 no files will be written.`);let Ur=await
|
|
1184
|
-
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`);if(Ur==="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
|
|
1185
|
-
Gateway ${Y.origin} is not reachable (${
|
|
1179
|
+
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,L4=e=>{let t=e?.trim();return t||wg()},GP=(e=process.stdin)=>new Promise((t,n)=>{let r=N4({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)}),kf=(e,t)=>t||e,Sf=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},$4=e=>!e||e.length===0?ie:e.map(t=>{let n=Qe(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${ie.map(r=>r.id).join(", ")}`);return n}),Cf=e=>e.keyKind==="service"?"service key (agent)":"personal gateway key",M4=(e,t)=>{if(W("Gateway target"),k(` Origin: ${it(e.origin)}`),e.byoUpstream)k(` Auth: BYO upstream key ${v(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&k(` Client key: ${Cf(e)} (${Zt(e.clientKey)}) ${v("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=se(e,"anthropic")?it("your subscription"):"org key",r=se(e,"openai")?it("your subscription"):"org key";k(` Auth: auto ${v("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&k(` Client key: ${Cf(e)} (${Zt(e.clientKey)})`)}else e.authMode==="subscription"?(k(` Auth: subscription pass-through ${v("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&k(` Client key: ${Cf(e)} (${Zt(e.clientKey)}) ${v("rides x-anyray-api-key")}`)):e.clientKey?k(` Auth: ${Cf(e)} (${Zt(e.clientKey)}) ${v("(replaces the placeholder)")}`):k(` Enrollment: ${v("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&k(` Cursor: ${it("native Team subscription")} ${v("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(se(e,"anthropic")?(k(` Claude Desktop: ${it("subscription-backed Gateway lane")} ${v("(verified macOS builds; Windows fails closed)")}`),k(` ${v("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(k(` Claude Desktop: ${it("third-party API lane")} ${v("(API-billed; switches the active local inference profile)")}`),k(` ${v("The first-party Claude subscription remains untouched.")}`))),k(` Attribution: ${be(e.metadata)??v("(none \u2014 pass --user)")}`)},B4=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}\``}},F4=async()=>{let[e,t]=await Promise.all([qp().catch(()=>[]),qb().catch(()=>[])]);for(let n of e)k(` Bind-mounted config file: ${n} ${v("(cannot be replaced atomically; connect writes it in place, verified)")}`);if(t.length>0){W("Other environments you work in");for(let n of t)M(` ${B4(n)}`);k(v(" This run configures only this machine. Run `anyray-connect` inside each of these too \u2014 see docs.anyray.ai/get-started/remote-environments."))}},UP=async(e,t)=>{W("Selected tools");for(let n of e){let r=await n.detect();r.installed?k(` ${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}`:""}`)}},rk=(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},U4={loadDevKey:Ye,saveDevKey:Tl,clearDevKey:hi,saveProfile:pe},W4=async(e,t,n,r=U4,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}},WP="blocked by machine policy \u2014 your IT team owns this one",H4=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}W(`${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)k(` ${y}`);a+=f.changedFiles?.length??0;let h=f.status==="manual"&&f.manualAudience==="admin",g=f.messages.join(" ").trim()||(h?WP:void 0);l.push({id:p.id,status:f.status,...g?{reason:g}:{}}),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(` ${WP}`)):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}},G4=(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},K4=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>zr(o)&&!r.has(o.id))},V4=async e=>{let t=o_(e,process.platform,ee());if(t){await ve(t.path,t.content);for(let n of a_(t,process.platform))k(` ${n}`)}},j4=async(e,t,n=vf())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!TA(i,n)||!_A(i,n))continue;let c=RA(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:OA(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},Y4=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,Z4=e=>`
|
|
1180
|
+
${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?`}`,J4=async(e,t={})=>{let n=t.requestQuit??(a=>DA(a)),r=t.waitFor??(a=>NA(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},X4=(e,t={})=>{let n=t.relaunch??(o=>LA(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 ok=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,z4=(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}},tk=e=>!zr(e),q4=async(e,t,n={})=>{let r=n.hasEnrollment??$f,o=n.canMultiSelect??I_,a=n.multiSelect??E_,s=n.prompt??Os,i=n.registry??ie;if(k(Z("Anyray connect \u2014 guided setup")),k(v("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())k("Stored enrollment will be reused. Run with --revert to clear it.");else if(!e.enroll&&!e.sso&&!e.gateway){W("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 Et;c=d.values[0]}else{k(" 1. Paste an enrollment link"),k(" 2. Sign in with SSO"),k(" 3. I already have a gateway URL");let d=await s("? Connection method (1-3)","1");c=d==="1"?"enroll":d==="2"?"sso":d==="3"?"gateway":void 0}c||P("Choose one of the three connection methods.")}if(!c)throw new Et;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&Xc(d)&&Ip(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&&Ft(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&&Xc(d)){e.enroll=d,k("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=dn(d);break}catch{P("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new Et}if(!e.tools||e.tools.length===0){W("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=>tk(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:ok(f),selected:tk(f),requiresExplicitChoice:!tk(f)}))});if(m.kind==="cancelled")throw new Et;p=m.values}else{p=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(g=>g.trim()).filter(Boolean);let f=new Set(c.map(g=>g.id)),h=p.filter(g=>!f.has(g));if(h.length>0){P(`Unknown or unavailable tool id${h.length===1?"":"s"}. Choose from: ${c.map(g=>g.id).join(", ")}.`);continue}}if(p.length===0){P("Choose at least one installed tool.");continue}e.tools=p}if(!e.tools)throw new Et}l.length>0&&M(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},Q4=async(e,t)=>{W("Verifying the connection");let n=await zs("Checking the gateway\u2026",()=>ti(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)k(v(` ${r}`))},e6=async(e,t={})=>{if(e.dryRun)return;let n=t.install??eo,r=t.uninstall??fr;if(e.want&&e.trayManaged){W("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();W("Automatic key refresh");for(let a of o.messages)k(` ${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 pe({...await L(),refreshSchedulerInstalledOnce:!0}):await pe({...await L(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){W("Automatic key refresh");let o=await r();for(let a of o.messages)k(` ${a}`);await pe({...await L(),refreshSchedulerEnabled:!1,refreshSchedulerInstalledOnce:!1}),B(" Removed the automatic key-refresh schedule.")}},t6=new Set(["wizard","status","doctor","sync","device-url"]),n6=new Set(["device-url","status","remote"]),r6=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"||e.outcome==="sidecar"))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."}},o6=e=>{if(e.includes("--help")||e.includes("--help-all")||e.includes("-h"))return!1;let t=Vw(e[0]);if(t)return t.persistsRuntime(e.slice(1));if(e[0]==="desktop"){let n=eb(e.slice(1));return!!(n&&!n.includes("--dry-run")&&!n.includes("--revert"))}return cl(e)?e[0]==="doctor"?e.includes("--repair"):!e[0]||!n6.has(e[0]):!1},sk=()=>In(process.env.ANYRAY_CLIENT_KEY)==="service",ik=e=>e.includes("--json")&&(e.includes("--desktop-app")||["--sign-in","--sso","--enroll","--claim"].some(t=>e.includes(t))||sk()),a6=e=>{let t=e[0]==="wizard"?e.slice(1):e;if(!(t[0]&&!t[0].startsWith("-")))try{let n=Sf(t);return{json:!!(n.json&&(n.desktopApp||n.signIn||n.sso||n.enroll||n.claim||sk())),yes:!!n.yes}}catch{return}},nk=async(e,t,n={})=>{try{return await ZP(e,t,n)}catch(r){let o=ik(e);if(r instanceof Et)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&&sr({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"})`),sr({event:"error",code:"apply-failed",message:a}),1}throw r}},KP=12e4,s6=async(e,t,n,r=xn)=>e&&!t?r(n,{waitMs:KP}):n(),i6=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??xt)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
|
|
1181
|
+
${o} ${n} tool target(s)?`;return await(r.confirm??ya)(a)?"proceed":"declined"},c6=async(e=Ps)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0,initiator:"directive"});switch(t.outcome){case"current":case"updated":case"migrated":case"container":case"sidecar":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}},ak=e=>ZP(e,!1,{managedEnrollmentCarrier:!0}),l6=e=>ff(mf(ak),{json:e}),d6=new Set(["managed","durable","npm"]),VP=async(e={})=>{let t=await(e.load??L)().catch(()=>{});if(!t?.gateway||!t.clientKey)return{status:"not-enrolled"};let{gateway:n,clientKey:r}=t,o=await(e.runtimeKind??(async()=>(await Uc()).kind))().catch(()=>"unmanaged"),a,s=async(c,l)=>{if(c==="revert_tool"&&!await(e.refreshToolPolicy??Sw)(n,r).then(()=>!0,()=>!1))return"deferred";if(c==="update"&&o==="sidecar"&&e.desktop){if(!$g({mode:t.fleetUpdatePolicy?.mode??"auto",initiator:"directive"}).allow)return"failed";let u=await(e.stageDesktop??ul)(e.desktop);return u.status==="staged"?(a=u,"deferred"):u.status==="none"?u.artifact===!1?"deferred":"ok":u.status==="rejected"?"failed":"deferred"}return e.execute?e.execute(c,l):c==="remint"||c==="reapply_config"?await an({force:!0})==="failed"?"failed":"ok":c==="revert_tool"?zb(l):c==="update"?c6():(await wf()).ok?"ok":"failed"},i;try{let c=d6.has(o)||o==="sidecar"&&e.desktop!==void 0,l=o==="sidecar"&&e.desktop!==void 0;i=await Xb(n,r,{execute:s,kinds:$P(c&&!l),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}),!i&&l&&(i=await Xb(n,r,{execute:s,kinds:["update"],...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}}))}catch{return{status:"unreachable"}}return i?i.outcome==="deferred"?i.kind==="update"&&a?{status:"staged",kind:"update",version:a.version,path:a.path,...a.minVersion?{minVersion:a.minVersion}:{}}:{status:"unreachable"}:{status:"ran",kind:i.kind,outcome:i.outcome}:{status:"none"}},u6=async()=>{let e=!1,t=await iP(await an({runAmbientSelfcheck:!0}),{...mf(ak),refresh:()=>an({})});await cP(mf(ak)),await Cm(),await IO(),await EO()==="retry"&&(e=!0);let n=await L().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await pe(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await _a().catch(()=>!1);if(n&&(await DP(t,{fleetdPresent:async()=>r}).catch(()=>{}),await NP(t).catch(()=>{}),r&&n.gateway&&n.clientKey)){let a=n.gateway,s=n.clientKey,i=on(),c=n.enrolledCert;if(i&&c){let l=await Ye().catch(()=>{});l&&await sR(a,s,c,l,i).catch(()=>{})}}let o=await VP();return o.status==="ran"&&o.outcome==="failed"&&(e=!0),r||await Ps(),{refresh:t,...e?{partial:!0}:{}}},p6=async(e,t={})=>{if(e[0]==="__anyray-hook"){let a=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return WT(a)}if(e[0]==="__anyray-hook-lifecycle")return FT();if(e[0]==="__anyray-codex-hook")return HT();if(e[0]==="__anyray-prompt-hook")return jT();if(e[0]==="__anyray-shell-pretool")return XT();if(e[0]==="__anyray-shell-run")return JT(e.slice(1));if(e[0]==="__anyray-read-pretool")return oP();if(e[0]==="__anyray-sso-gate")return VT(e.slice(1));if(e[0]==="__anyray-sso-poll")return lP();if(e[0]==="__anyray-managed-enroll")try{return await xn(()=>l6(e.slice(1).includes("--json")),{waitMs:KP})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return uP();if(e[0]==="__anyray-spawn-refresh")return await Eo(),0;if(e[0]==="__anyray-mcp-server"){let a=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return kP(a)}if(e[0]==="__anyray-acp-agent")return CP(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return x0(e.slice(1));let n=OP(e);if(n)return TP(n,{refresh:u6,desktopUpdate:ul,directives:a=>VP(a)});if(e[0]==="__anyray-persistence")return NC(e.slice(1));if(e[0]==="__anyray-quit-watch")return gx(e.slice(1));if(e[0]===ho)return YO(e.slice(1));if(e[0]===pc)return JO(e.slice(1));if(e[0]===Vo){let a=e[1];return a&&await lp(a),0}if(e[0]==="--version"||e[0]==="-V")return dP();try{let a=await Ik(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),ik(e)&&sr({event:"error",code:"enroll-failed",message:s}),1}if(o6(e)){let a=r6(await qx());a?.level==="warn"?P(a.message):a&&console.error(a.message)}let r=Vw(e[0]);if(r)return r.run(e.slice(1));if(e[0]==="desktop"){let a=e.slice(1),s=eb(a);return s?nk(s,!1,t.apply):s_(a)}if(e[0]==="remote")return C6(e.slice(1));let o=e[0];if(o&&t6.has(o)){let a=e.slice(1),s;try{s=Sf(a)}catch(i){return D(i.message),k("\nRun `npx anyray-connect --help` for usage."),1}return s.help?(k(s.helpAll?Af:HP),0):o==="status"?W_({gateway:s.gateway}):o==="doctor"?of({gateway:s.gateway,json:s.json,verify:s.verify,noVerify:s.noVerify,quick:s.quick,repair:s.repair,securityReview:s.securityReview}):o==="sync"?tT({gateway:s.gateway}):o==="device-url"?UO():nk(a,!0,t.apply)}return nk(e,!1,t.apply)},jP=async(e,t={})=>{Cg();let n=a6(e);if(n?.json&&(kg(),!n.yes)){let r="--json enrollment requires --yes.";return sr({event:"error",code:"yes-required",message:r}),D(r),1}try{return await p6(e,t)}catch(r){if(r instanceof Et)return console.error(v("Cancelled.")),130;throw r}},f6=e=>{let t=process.platform==="win32"?"where":"which";try{return P4(t,[e],{stdio:"ignore"}).status===0}catch{return!1}},m6=(e,t={})=>{let n=t.which??f6,r=t.platform??vf;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")}},h6=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}},y6=(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?`}},g6=e=>e.interactive&&!e.managed&&!e.yes&&!e.revert&&!e.dryRun,w6=async(e,t={})=>{if(!g6(e)||!Pe(e.clientKey))return;let n=t.discoverRemoteEnvironments??qb,r;try{r=await n()}catch{return}let o=t.confirm??ya,a=t.runRemoteApply??ek,s=t.isCarrierAvailable??m6,i=t.resolveDevcontainer??Qb;for(let c of r){let l=h6(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(y6(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(YP(d.kind))}},YP=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`."}},b6="usage: anyray-connect remote <ssh-host> [--yes] [--dry-run] | remote --devcontainer <host-path> | --wsl <distro> | --codespace <name> [--yes] [--dry-run]",k6=e=>{let t=/[/\\]/.test(e);return{kind:"devcontainer",name:t?D4(e.replaceAll("\\","/")):e,...t?{ref:e}:{}}},C6=async(e,t={})=>{if(e[0]==="--help"||e[0]==="-h")return console.log(Af),0;let n=e[0]&&!e[0].startsWith("-")?e[0]:void 0,r;try{r=Sf(n?e.slice(1):e)}catch(h){return D(h instanceof Error?h.message:String(h)),1}if(r.help)return console.log(Af),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(b6),1;let a=n?{kind:"ssh",name:n}:r.devcontainer!==void 0?k6(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??vf)()!=="win32")return D("--wsl is available only on Windows (win32)."),1;let s=t.isInteractive??xt;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 GP()}catch{return D("could not read the personal gateway key from stdin."),1}let c=await(t.loadProfile??L)(),l=!r.gateway&&!process.env.ANYRAY_GATEWAY_URL?c.gateway:void 0,d=dn(r.gateway??l),u=i||process.env.ANYRAY_CLIENT_KEY?.trim()||rk(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 vg(r.user,c.name,r.yes),m=await Sg(r.team,c.team,r.yes),f;try{f=await(t.runRemoteApply??ek)(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(YP(a.kind))),f},ZP=async(e,t,n={})=>{Cg();let r=ik(e);r&&kg();let o=(N,_)=>{r&&sr({event:"error",code:N,message:_})},a=(N,_)=>(D(_),o(N,_),1),s=n.isInteractive??xt,i;try{i=Sf(e)}catch(N){return a("invalid-args",N.message),k("\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=N=>n.managedEnrollmentCarrier===!0&&pw(N)?"enroll-rejected":N instanceof bt||N instanceof Ot||N instanceof sn||N instanceof Wt?N.kind:N instanceof zc?"gateway-unreachable":N instanceof qc?"cp-unreachable":N instanceof ct&&N.policyCode==="sso_required"?"sso-required":"enroll-failed";if(i.help)return k(i.helpAll?Af:HP),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."):(sk()||In(rk(await L()))==="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."):VO({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 N;try{N=new URL(i.upstream.trim())}catch{return a("invalid-args",`invalid --upstream URL: "${i.upstream}"`)}if(N.protocol!=="http:"&&N.protocol!=="https:")return a("invalid-args",`invalid --upstream URL: "${i.upstream}" \u2014 must start with http:// or https://`);let _=i.upstreamKey.trim();if(!_)return a("invalid-args","--upstream-key must not be empty.");d={url:dt(i.upstream),key:_}}let u=await L(),p;if(i.keyStdin)try{p=await GP()}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&&xt()&&!i.gateway&&!i.revert&&!i.yes&&!i.dryRun&&!i.enroll&&!i.sso&&!i.signIn,f=!1;(t||m)&&s()&&(i=await(n.runWizard??q4)(i,u),f=!0);let h;try{h=$4(i.tools)}catch(N){return a("apply-failed",N.message)}k(Z(i.revert?"Anyray connect \u2014 revert":"Anyray connect")),i.gateway&&!i.enroll&&Xc(i.gateway)&&(i.enroll=i.gateway,i.gateway=void 0,k("That looks like an enrollment link \u2014 treating it as --enroll."));let g,y,w,b,A=!1;if(i.enroll){let N=Ip(i.enroll);if(N&&(i.desktopApp||!i.gateway||u.enrolledCert||sw(N.token)))try{let _=await zs("Resolving enrollment link\u2026",()=>(n.resolveEnrollLink??eR)(N)),V=!i.gateway;if(V&&(i.gateway=_.gatewayUrl),g=_.deploymentId,y=_.email,w=_.provisioningKind,b=_.allowedDomains,A=!0,i.desktopApp&&!_.email)return a("invalid-link","The desktop app accepts personal links only. Ask your admin for a personal link.");V&&M(`Enrollment link${_.org?` for ${_.org}`:""}: gateway ${_.gatewayUrl}`),_.seatMode&&!i.subscription&&(i.subscription=!0,M("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(_){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(sw(N.token))return a(l(_),_ instanceof Error?_.message:String(_));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",_ instanceof Error?_.message:String(_))}}let C,x;if(r&&await(n.clearGateState??pl)(),i.claim&&!i.revert)if(i.dryRun)M("dry run: not enrolled (skipped redeeming the enrollment link).");else{let N=fR(i.claim);if(!N)return a("invalid-link","invalid --claim value: expected the sdc_ code from your organization's Anyray page.");try{let _=await zs("Connecting this machine\u2026",()=>(n.redeemClaim??mR)({cpOrigin:N.cpOrigin,claim:N.claim,gatewayUrl:i.gateway}));C={cert:_.cert,privateKeyPem:_.privateKeyPem},_.deploymentId&&(g=_.deploymentId),!i.gateway&&_.gatewayUrl&&(i.gateway=_.gatewayUrl),x=_.ssoLink}catch(_){return a(l(_),_ instanceof Error?_.message:String(_))}}if(i.sso&&!C&&!i.revert)if(i.dryRun)M("dry run: not enrolled via SSO (skipped minting a personal key).");else{let N=Ft(i.sso);if(!N){let _=Xc(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",_)}try{let _=await(n.startDeviceGrant??Ep)({cpOrigin:N.cpOrigin,tenantId:N.tenantId,gatewayUrl:i.gateway,log:r?void 0:_e=>M(_e),open:!r&&s()?Nr:void 0});r&&sr({event:"sso_grant",verificationUriComplete:_.verificationUriComplete,userCode:_.userCode,expiresAt:new Date(_.grantExpiresAt).toISOString(),tenantId:_.tenantId});let V=await zs("Waiting for SSO sign-in\u2026",()=>(n.pollDeviceGrant??xp)(_,{gatewayUrl:i.gateway}));C={cert:V.cert,privateKeyPem:V.privateKeyPem},V.deploymentId&&(g=V.deploymentId),!i.gateway&&V.gatewayUrl&&(i.gateway=V.gatewayUrl)}catch(_){return a(l(_),_ instanceof Error?_.message:String(_))}}if(i.signIn&&!C&&!i.revert)if(i.dryRun)M("dry run: not signed in (skipped minting a personal key).");else{let N;try{let _=await(n.createDesktopSignInCallbackListener??w_)();N=_;let V=await(n.startDesktopSignIn??A_)({callbackUri:_.callbackUri,log:r?void 0:nt=>M(nt),open:!r&&s()?Nr:void 0});r&&sr({event:"sso_grant",verificationUriComplete:V.browserUrl,userCode:V.userCode,expiresAt:new Date(V.grantExpiresAt).toISOString()});let _e=await zs("Waiting for sign-in\u2026",async()=>{let nt=await _.waitForCompletion(V);return(n.pollDesktopSignIn??v_)(V,{completion:nt})});C={cert:_e.cert,privateKeyPem:_e.privateKeyPem},_e.deploymentId&&(g=_e.deploymentId),!i.gateway&&_e.gatewayUrl&&(i.gateway=_e.gatewayUrl)}catch(_){return a(l(_),_ instanceof Error?_.message:String(_))}finally{await N?.close()}}let O=!i.gateway&&!process.env.ANYRAY_GATEWAY_URL?u.gateway:void 0;O&&(i.gateway=O);let S;try{S=dn(i.gateway)}catch(N){return a("enroll-failed",N.message)}let E,T;O&&!i.revert&&M(`Gateway: ${S} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!i.revert&&dk(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 I=p??process.env.ANYRAY_CLIENT_KEY?.trim(),K=I||rk(u),G,X,ae,Ae,me,U,Q=async N=>{await Ea();let _=rR(N.token),V=iR(u.enrolledCert,u.enrolledCertExpiry,N.deploymentId,Date.now(),_,u.enrolledTokenHash,N.expectedUser),_e=V?await Ye():void 0,nt=on()||void 0,Gt=V&&_e&&u.enrolledCert?{cert:u.enrolledCert,privateKeyPem:_e,publicKeyPem:u.enrolledCert.payload.devPublicKey}:void 0,Ct=Te=>(n.enrollAndVerify??cR)({cpOrigin:N.cpOrigin,token:N.token,gatewayOrigin:S,email:N.email,team:N.team,machineId:N.machineId,deploymentId:N.deploymentId,machineUuid:nt,reuse:Te?Gt:void 0}),Ve=!!Gt,je=await(async()=>{try{return await Ct(Ve)}catch(Te){if(Gt&&Te instanceof ct&&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=kf(i.user,je.user),i.team=kf(i.team,je.team),G=je.cert,X=je.cert.payload.expiresAt,U=je.expiresAt,me=void 0,Ve||(ae=je.privateKeyPem),Ve||(Ae=_),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 N=Ip(i.enroll);if(!N){let _=Q0(i.enroll),V=_?`that is ${_.what}, not an enrollment link \u2014 re-run with ${_.flag} instead of --enroll.`:Ft(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 _=i.machine?Mp():void 0,V=w==="mdm"&&!y?h_():void 0,_e=w==="mdm"&&!y&&!V?m_(b,qu()):void 0,nt=V??_e;if(nt){let Ve=V?"the email your MDM assigned to this machine":`${nt} (this Mac's login name at the first allowed domain)`;k(i.user?.trim()&&i.user.trim()!==nt?`Ignoring --user: enrolling as ${Ve}.`:`Enrolling as ${Ve}.`)}let Gt=y??nt??L4(i.user);if(!i.machine&&!i.user&&!y&&!nt){let Ve=Ax();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:${_}`:A?Gt:void 0;await Q({cpOrigin:N.cpOrigin,token:N.token,email:Gt,team:i.team,machineId:_,deploymentId:g,expectedUser:Ct})}catch(_){let V=_ instanceof Error?_.message:String(_);return D(V),o(l(_),V),_ instanceof ct&&_.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."),pw(_)?3:1}}if(C){await Ea();try{let N=on()||void 0,_=await(n.verifyWithGateway??Sn)(S,C.cert,C.privateKeyPem,{machineUuid:N});K=_.key,i.user=kf(i.user,_.user),i.team=kf(i.team,_.team),G=C.cert,X=C.cert.payload.expiresAt,ae=C.privateKeyPem,U=_.expiresAt;let V=i.sso?Ft(i.sso):void 0;me=V?`${V.cpOrigin}/sso/${V.tenantId}`:x,B(`Enrolled${_.user?` as ${_.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(N){let _=N instanceof Error?N.message:String(N);return D(_),o(l(N),_),N instanceof ct&&N.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=In(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 N=i.yes;E=await vg(i.user,u.name,N),T=await Sg(i.team,u.team,N)}if(!i.revert&&!i.dryRun){let N=M_(await $_(S,K),{subscription:i.subscription,org:i.placeholder,byoUpstream:!!d});if(N.lane){let _=N.lane==="subscription";i.subscription=_,i.placeholder=!_;let V=_?"your own subscription seat":"the organization's provider account";N.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 Vn(),W("Detecting your sign-ins"),k(` Claude (Anthropic): ${d?it("BYO upstream key (passthrough)"):we.anthropic?it("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${we.openai?it("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),(!we.anthropic||!we.openai)&&K&&await U_(Re({origin:S,placeholderKey:i.key,clientKey:K,subscription:!1,placeholder:!0,byoUpstream:d,user:E,team:T,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&&ur()&&(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=Re({origin:S,placeholderKey:i.key,clientKey:K,subscription:i.subscription,placeholder:i.placeholder,byoUpstream:d,seat:we,user:E,team:T,intent:i.intent,intentLabel:i.intentLabel,session:i.session}),Ie=i.revert===!0&&(i.tools?.length??0)===0,cn={dryRun:i.dryRun,fullRevert:Ie};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){W("Enrollment required");let N="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return i.dryRun?(P(` ${N}`),M(" Dry run only \u2014 no placeholder configuration will be written."),await UP(h,"after-enrollment"),M(`
|
|
1182
|
+
Dry run complete \u2014 no files were written.`),0):a("enroll-failed",` ${N}`)}i.revert||M4(Y,h);let Fr=!i.revert&&!i.yes&&s();(f||Fr)&&!i.revert&&await UP(h,"plan"),Fr&&await F4(),i.dryRun&&M(`
|
|
1183
|
+
Dry run \u2014 no files will be written.`);let Ur=await i6(i,f,h.length,{isInteractive:s,confirm:n.confirm});if(Ur==="non-interactive")return a("apply-failed",`
|
|
1184
|
+
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`);if(Ur==="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 N=await Yp(Y.origin);if(!N.reachable){let _=`
|
|
1185
|
+
Gateway ${Y.origin} is not reachable (${N.detail}).`;return D(_),o("gateway-unreachable",_),k(v(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1186
1186
|
that would break them until you re-run with --revert.`)),k(`
|
|
1187
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1}B(`Gateway reachable (${
|
|
1188
|
-
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let je=h,Te=[],ir;if(n.managedEnrollmentCarrier===!0){let z=u.fleetToolPolicy,de=z?"cached admin list (no key to fetch with)":"none (no key to fetch with)";if(Y.clientKey)try{z=(await Sw(Y.origin,Y.clientKey,n.fetchTeamPolicy)).tools,de=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,de=z?"cached admin list (gateway unreachable this run)":"none (gateway unreachable, nothing cached)"}ir=DR(u,z,ie);let ln=new Set(ir.applyIds);je=ie.filter(xe=>ln.has(xe.id)),W("Fleet policy"),k(` Policy: ${de}`);for(let xe of ir.skipped)P(` ${
|
|
1187
|
+
Start the gateway and try again, or pass --force to configure anyway.`),1}B(`Gateway reachable (${N.detail}).`)}let Wr=i.revert?[]:await j4(h,Y.origin),_o=[],Sl=()=>{_o.length!==0&&(W("Reopening"),X4(_o),_o=[])};if(Wr.length>0){let N=Wr.map(V=>V.title),_=N.length===1?"it":"them";if(W("Open apps"),Y4(i,xt()))i.quitApps===!0||await ya(Z4(N))?_o=await J4(Wr):M(` Leaving ${_} open \u2014 restart when convenient.`);else{let V=i.noQuitApps===!0?"":" (or pass --quit-apps)";M(i.dryRun?` Would offer to quit ${N.join(", ")} \u2014 dry run, nothing was closed.`:` ${N.join(", ")} ${N.length===1?"is":"are"} open; restart ${_} to pick this up${V}.`)}}let li=async()=>{if(!i.dryRun)try{await Xe()}catch{return a("enroll-failed","Could not prepare the owner-only Anyray state directory.")}let N=u.anyrayFleetManaged===!0&&await _a().catch(()=>!1),_=b0(i,vf(),N),V=!!(I&&Y.clientKey===I&&!G),_e=ot({...u,enrolledCert:G??u.enrolledCert},{toolIds:h.map(z=>z.id),keyExpiresAt:U}),nt=Y.keyKind==="service",Gt=!i.revert&&i.noKeyRefresh!==!0&&!V&&!nt&&_e,Ct=i.dryRun?await ja(u):await Cm(),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:E,team:T,clientKey:Y.clientKey??u.clientKey,enrolledCert:V?void 0:G??u.enrolledCert,enrolledCertExpiry:V?void 0:X??u.enrolledCertExpiry,enrolledTokenHash:V?void 0:Ae??u.enrolledTokenHash,ssoLink:V?void 0:C?me:G?void 0:u.ssoLink,clientKeyExpiresAt:V?void 0:U??(Y.clientKey===u.clientKey?.trim()?u.clientKeyExpiresAt:void 0),authMode:Y.authMode,byoUpstream:Y.byoUpstream,refreshSchedulerEnabled:Gt};try{await(n.withProfileLock??xn)(()=>W4(u,z,ae,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??pl)().catch(()=>{}),sr({event:"enrolled",via:c,...E?{user:E}:{},...T?{team:T}:{},authMode:Y.authMode,gateway:Y.origin,...g??G?.payload.deploymentId?{deploymentId:g??G?.payload.deploymentId}:{},...X?{certExpiresAt:X}:{},...Y.keyKind?{keyKind:Y.keyKind}:{}})),U&&!V&&await Ys({expiresAt:U})}if(Ie)if(i.dryRun)await $f()&&(W("Enrollment"),k(" would remove the stored gateway credential"));else{await Yb(u),await Kp().catch(()=>{});try{await Pl()&&(W("Enrollment"),B(" Removed the stored gateway credential."),M(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(z){W("Enrollment"),P(" Could not remove the stored gateway credential."),P(` Delete ${ee()} by hand, or a credential refresh may restore your tool config.`)}}else i.revert&&!i.dryRun&&(k(`
|
|
1188
|
+
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let je=h,Te=[],ir;if(n.managedEnrollmentCarrier===!0){let z=u.fleetToolPolicy,de=z?"cached admin list (no key to fetch with)":"none (no key to fetch with)";if(Y.clientKey)try{z=(await Sw(Y.origin,Y.clientKey,n.fetchTeamPolicy)).tools,de=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,de=z?"cached admin list (gateway unreachable this run)":"none (gateway unreachable, nothing cached)"}ir=DR(u,z,ie);let ln=new Set(ir.applyIds);je=ie.filter(xe=>ln.has(xe.id)),W("Fleet policy"),k(` Policy: ${de}`);for(let xe of ir.skipped)P(` ${z4(xe.id,xe.reason)}`);for(let xe of ir.revertIds)P(` ${xe}: reverting, removed from the policy's enabled list`)}else if(Te=K4(je,i,u.managedTools),Te.length>0){W("Not configured \u2014 needs your say-so");for(let de of Te)P(` ${de.id}: ${ok(de)??"changes where inference is billed"}.`),k(` Configure it deliberately with \`npx anyray-connect --tools ${de.id}\`.`);let z=new Set(Te.map(de=>de.id));je=je.filter(de=>!z.has(de.id))}if(i.revert&&!Ie){let z=h.filter(de=>nl(u,de.id));if(z.length>0){W("Fleet policy");for(let de of z)P(` ${de.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);je=h.filter(de=>!nl(u,de.id))}}let{changes:J,manual:At,manualAdminOnly:To,manualAdminOnlyIds:Po,results:Hr,skippedIds:Da}=await H4(je,Y,cn,i.revert,new Set(i.tools??[]));if(ir)for(let z of ir.revertIds){let de=await zb(z);Hr.push(de==="ok"?{id:z,status:"reverted"}:{id:z,status:"failed",reason:"revert failed"})}r&&sr(P_([...Hr,...Te.map(z=>({id:z.id,status:"held",reason:ok(z)??"changes where inference is billed"}))],Y.keyKind,ir?.skipped));let Il;if(Yg(i)){W("Endpoint agent");try{Il=await(n.installEndpointAfterEnrollment??R0)({gateway:S,clientKey:Y.clientKey})}catch{M("Endpoint agent setup did not complete. Tool routing remains configured.")}}let di=_&&w0(Il),El=Gt&&!di;if(_&&!di&&Gt&&!i.dryRun&&M(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),di&&!i.dryRun&&await pe({...await L(),refreshSchedulerEnabled:!1}).catch(()=>{}),i.dryRun||(await Vr(Hr,i.revert,Ie).catch(()=>{}),i.revert||await pe({...await L(),toolSelection:(i.tools?.length??0)>0?"explicit":"all"}).catch(()=>{}),Ie&&await Dl().catch(()=>{})),await e6({want:El,scopedRevert:!!i.revert&&!Ie,dryRun:!!i.dryRun,wasEnabled:!!u.refreshSchedulerEnabled||!El&&await id(),trayManaged:Ve}),!i.revert&&!i.dryRun)if(Sk(u.managedTools,Hr,Da)){let z=await Ml().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=ae??await Ye();z&&await Hw(await L(),z).catch(()=>{})}if(!i.revert&&!i.dryRun){W("Team content");try{let z=await(n.seedTeamContent??Pp)(await L());if(!z)M(" Skipped: no enrolled key on this seat.");else{let de=z.skills?.summary;de?de.changed>0||de.removed.length>0?B(` Org skills: ${de.changed} written, ${de.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 ln=z.mcp;ln?ln.changed.length>0?B(` Org connectors: ${ln.served?"registered":"removed"} the anyray-org MCP entry in ${ln.changed.join(", ")}.`):M(ln.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 (${Ws(z)}); the background refresh retries.`)}}if(Sl(),W("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 KO();z.length>0&&(W("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."),k(`
|
|
1189
1189
|
Remove them from the repo (then commit):`),k(v(" anyray-connect --project --revert")));let de=kd(Y);de.length>0&&(W("This terminal still points at the gateway"),P(` Still exported here: ${de.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."),k(`
|
|
1190
1190
|
Fix this terminal:`),k(v(` unset ${de.join(" ")}`)),k(`
|
|
1191
|
-
Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(B(`Done (${J} file(s) written).`),At.length>0){let xe=To.length===At.length;W(xe?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let ui of
|
|
1192
|
-
Skipped the connection smoke test (--skip-verify).`):await
|
|
1191
|
+
Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(B(`Done (${J} file(s) written).`),At.length>0){let xe=To.length===At.length;W(xe?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let ui of G4(At,To,Po.includes("claude-desktop")?process.platform:void 0))P(ui);if(Po.includes("claude-desktop")&&!i.dryRun)try{await V4(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>`.")}xt()&&!i.yes&&!xe&&(await ya("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(`
|
|
1192
|
+
Skipped the connection smoke test (--skip-verify).`):await Q4(Y,h.map(xe=>xe.id)),W("What's next");let z=new Set(Hr.filter(xe=>xe.status==="configured").map(xe=>xe.id)),de=h.filter(xe=>z.has(xe.id)).map(xe=>xe.title);if(k(de.length>0?` Connected: ${de.join(", ")}`:" Connected: no tools completed automatic configuration."),k(" Restart any editor that was already running \u2014 it loaded our config at startup."),k(" If something looks wrong: npx anyray-connect doctor"),Y.keyKind==="personal"&&Y.clientKey&&await w6({interactive:xt(),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;k(`
|
|
1193
1193
|
Re-test by hand any time:`),Y.authMode!=="placeholder"&&h.length===1&&h[0]?.id==="cursor"?(k(v(` curl -sS ${Y.origin}/connect/savings \\
|
|
1194
1194
|
-H "x-anyray-api-key: $(anyray-connect print-key)"`)),k(v(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):k(v(` curl -sS ${Y.openaiBaseUrl}/chat/completions \\
|
|
1195
1195
|
-H "Content-Type: application/json" \\
|
|
1196
1196
|
-H "Authorization: Bearer ${Y.clientKey?`<your personal key (${Zt(Y.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
|
|
1197
|
-
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await
|
|
1197
|
+
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await s6(i.revert,i.dryRun,li,n.withProfileLock)}catch(N){if(N instanceof Error&&N.message==="connect profile is busy; retry the command")return a("apply-failed","Another Connect update is in progress. Try again.");if(r){let _="Connect could not apply the configuration.";return D(`${_} (${N instanceof Error?N.name:"Error"})`),o("apply-failed",_),1}throw N}finally{Sl()}};jP(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
|