anyray-connect 0.11.131 → 0.11.133
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 +234 -230
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`),await fe(o,e),await
|
|
4
|
-
`,{mode:384})}catch(a){throw await
|
|
5
|
-
`,{mode:384}),await
|
|
6
|
-
`)},
|
|
7
|
-
`)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},Dg=async()=>{try{let e=await T();return e.gateway?{origin:new URL(e.gateway).origin,metadata:le({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},rt=async(e="auto")=>e==="profile"?Dg():e==="claude"?Lg():await Lg()??await Dg(),lc=async(e={})=>{let t=e.readTarget??rt,n=e.loadProfile??T,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return nt(r)&&r.fallbackPort&&a.add(`http://${ht}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},Zt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},dc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),IO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Zt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var xn=()=>pc(uc(),".claude","settings.json"),qa=()=>pc(uc(),".claude.json"),OO=ac,er="anyray",RO=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),Fr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_O=e=>{if("mcpServers"in e&&!Fr(e.mcpServers))return"conflict";let t=Fr(e.mcpServers)?{...e.mcpServers}:{},n=t[er];return n!==void 0&&!Yt(n,"claude")?"conflict":(t[er]=RO(),e.mcpServers=t,"installed")},Ng=e=>{let t=e.mcpServers;return!t||!(er in t)||!Yt(t[er],"claude")?!1:(delete t[er],Object.keys(t).length===0&&delete e.mcpServers,!0)},PO=e=>{nc(e,"PostToolUse",Ze,Sn(Rt(Ze),{matcher:"*"})),nc(e,"UserPromptSubmit",zn,Sn(Rt(zn)))},TO=e=>{nc(e,"SessionStart",qn,Sn(Rt(qn),{async:!0}))},Fg=e=>_o(e,"SessionStart",qn),$g=e=>{let t=_o(e,"PostToolUse",Ze),n=_o(e,"UserPromptSubmit",zn),r=Fg(e);return t||n||r},LO="print-key",DO=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Re()),Br=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===LO&&DO(t)},NO=async(e,t)=>{let n=(await Lr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of OO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},$O=e=>typeof e.apiKeyHelper=="string"&&!Br(e),Bg=async e=>{let t=await Fu(),n=async()=>t,[r,o,a]=await Promise.all([Sg({userSettings:e,readManaged:n}),_g({userSettings:e,readManaged:n}).catch(()=>[]),Rg({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},Mg=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await Bg(e),o=Mu(t),a=Tg(n);return{routingOverrides:[...t.map(i=>({problem:$u(i),fix:i.repairable?"Fix: run `anyray-connect doctor --repair` (or re-run `anyray-connect`) \u2014 apply disables this switch by pinning it empty in settings.json.":o,repairable:i.repairable})),...n.map(i=>({problem:Pg(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},tr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=pc(uc(),".claude"),t=await O(e);return{installed:t,detail:t?xn():"no ~/.claude directory"}},async apply(e,t){let n=xn(),r=await F(n),o=bg(r),a=await kg(e.origin,e.clientKey,o),s=Ag(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=dn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await Bg(r),h=f.filter(I=>!I.repairable),m=f.filter(I=>I.repairable),w=[...h.map(I=>`WARNING: ${$u(I)}.`),...h.length?[Mu(h)]:[],...p.state==="fine"?[]:[`WARNING: ${ic(p)}.`,cc(p)],...m.map(I=>Eg(I)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let g=r.env??{};r.env={...g,...i};let y=r.env;for(let{name:I}of En)m.some(R=>R.name===I)?y[I]="":y[I]===""&&(process.env[I]??"").trim()===""&&delete y[I];if(u||delete y.ANTHROPIC_CUSTOM_HEADERS,c&&(g.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete y.ANTHROPIC_AUTH_TOKEN),l)for(let I of wg)delete y[I];let b=!!e.clientKey,v=ce(),S=$O(r);!c&&!l&&b&&v&&!S?(r.apiKeyHelper=gg(),delete y.ANTHROPIC_AUTH_TOKEN,w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Br(r)&&delete r.apiKeyHelper,S&&!c&&!l&&b&&v&&w.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&v?(TO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Fg(r),ce()?(PO(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):($g(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await Z(n,r);let x=[n],A=qa();try{let I=await F(A),R=!1;ce()?_O(I)==="conflict"?w.push(`MCP name conflict in ${A}: mcpServers.${er} is not owned by Anyray Connect, so it was left untouched.`):(R=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):R=Ng(I),R&&(await Z(A,I),x.push(A))}catch(I){w.push(`Could not register the Anyray MCP server in ${A} (${I instanceof Error?I.message:String(I)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:x}},skillsDir(){return pc(uc(),".claude","skills")},async watchPaths(){return[xn(),qa()]},async pointsAt(e){let t=xn();if(!await O(t))return!1;try{let o=(await F(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await F(xn()).catch(()=>({}));return Mg(e)},async routingOverrides(){let e=await F(xn()).catch(()=>({}));return(await Mg(e)).routingOverrides},async mcpStatus(){let e=qa();if(!await O(e))return{registered:!1,command:null};try{let r=(await F(e)).mcpServers?.[er];return!r||!Yt(r,"claude")?{registered:!1,command:null}:{registered:!0,command:typeof r.command=="string"?r.command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=xn();if(!await O(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!Fr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>Jn(c,Ze))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>Jn(c,Ze)&&Fr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Fr(l)&&rc(l.command,Ze))))}}catch{e="unreadable"}let r,o=!0,a=qa();if(!await O(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!Fr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[er];r=i===void 0?"missing":Yt(i,"claude")?"owned":"foreign",r==="owned"&&(o=oc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await $r()?"owned":"missing",beacon_target:await lc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await F(xn()),t=Fr(e.env)?e.env:{},n=typeof t.ANTHROPIC_CUSTOM_HEADERS=="string"?t.ANTHROPIC_CUSTOM_HEADERS:"";if(/^x-anyray-custom-host:/m.test(n))return["byo"];if(/^x-anyray-auth-mode:\s*passthrough$/m.test(n))return["subscription"];if(typeof t.ANTHROPIC_AUTH_TOKEN=="string"||typeof e.apiKeyHelper=="string")return["api_key"]}catch{}return["unknown"]},async revert(e){let t=xn();if(!await O(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await F(t),r=n.env,o=$g(n),a=Br(n);a&&delete n.apiKeyHelper;let s=r?await NO(t,r):[],i=Cg(typeof n.model=="string"?n.model:void 0,(await Lr(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await Z(t,n,{backup:!1});let c=[`removed Anyray keys from ${t}`];i!==void 0&&c.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&c.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&c.push("Removed the Anyray apiKeyHelper."),s.length&&c.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let l=qa();try{let d=await F(l);Ng(d)&&(await Z(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await ne(t),{status:"reverted",messages:c,changedFiles:[t]}}};var we="0.11.131";var un=e=>{let{command:t,args:n}=ln([e]);return{command:t,args:n}},nr=()=>Nr();import{homedir as Ug,userInfo as MO}from"node:os";var Qa=()=>{try{return Ug()!==MO().homedir}catch{return!1}},Po=e=>[`Skipped ${e} \u2014 HOME (${Ug()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var yt=(e=process.env)=>e.CODESPACES==="true"||e.CODESPACE_NAME?"codespaces":e.REMOTE_CONTAINERS==="true"||e.REMOTE_CONTAINERS_IPC||e.DEVCONTAINER?"devcontainer":e.SSH_CONNECTION||e.SSH_TTY?"ssh":null,es=(e=process.env)=>yt(e)!==null,kt=e=>e==="codespaces"||e==="devcontainer",rr=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var Wu="__anyray-fallback-proxy",rs="ai.anyray.connect.fallback",or="anyray-fallback",jg=rs,ke=8785,os=60,Ku="x-anyray-local",Gu=()=>un(Wu),Hg=nr,hc=async(e=ke)=>{let t=n=>new Promise(r=>{let o=UO();o.once("error",()=>r(!1)),o.listen(n,"127.0.0.1",()=>o.close(()=>r(!0)))});for(let n=e;n<e+20;n++)if(await t(n))return n;return e},be=async(e,t=1500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}/__anyray/health`,{signal:n.signal});return o.ok?await o.json():null}catch{return null}finally{clearTimeout(r)}},No=()=>Do(ns(),"Library","LaunchAgents",`${jg}.plist`),as=()=>Do(ns(),".anyray","logs"),ts=()=>Do(as(),"connect-daemon.log"),Vg=async(e,t=1048576)=>{await Kg(e).then(r=>r.size,()=>0)>t&&await BO(e).catch(()=>{})},$o=()=>Do(ns(),".config","systemd","user",`${or}.service`),Bu=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),ss=(e=Gu())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${Bu(o)}</string>`).join(`
|
|
2
|
+
var OI="http://localhost:8787",Wa="anyray-placeholder",Ie=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Ye=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},uu=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,_I=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),By=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!_I.has(n)}catch{return!1}},ln=e=>{let t=Ye(e||process.env.ANYRAY_GATEWAY_URL||OI),n;try{n=new URL(t)}catch{throw new Error(`invalid gateway URL: "${t}" (expected e.g. http://localhost:8787)`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`invalid gateway URL: "${t}" \u2014 must start with http:// or https://`);return t},ht="127.0.0.1",vn=(e,t)=>{let n=`http://${ht}:${t}`;return{...e,anthropicBaseUrl:n,openaiBaseUrl:`${n}/v1`,viaLocalProxy:!0}},ge=(e={})=>{let t=ln(e.origin),n=e.placeholderKey?.trim()||Wa,r=e.clientKey?.trim()||process.env.ANYRAY_CLIENT_KEY?.trim()||void 0,o={user:e.user?.trim()||void 0,team:e.team?.trim()||void 0,intent:uu(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:uu(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:uu(e.session,"ANYRAY_METADATA_SESSION")},a=e.subscription?"subscription":e.placeholder?"placeholder":e.seat?"auto":"placeholder";return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:n,clientKey:r,authMode:a,byoUpstream:e.byoUpstream,seat:a==="auto"?e.seat:void 0,metadata:o}};import{homedir as rs,platform as Do}from"node:os";import{join as No}from"node:path";import{mkdir as Hu,readFile as Kg,rename as ZR,stat as Gg,truncate as XR,writeFile as jg,rm as Lo}from"node:fs/promises";import{spawnSync as fn}from"node:child_process";import{createServer as JR}from"node:net";import{homedir as fc}from"node:os";import{join as hc}from"node:path";import{access as NI,chmod as $I,mkdir as pu,open as gu,readFile as Vy,rm as Yt,stat as Hy,utimes as MI}from"node:fs/promises";import{createHash as FI,randomUUID as Yy}from"node:crypto";import{dirname as wu,join as BI}from"node:path";import{isDeepStrictEqual as Eo}from"node:util";import{randomUUID as TI}from"node:crypto";import{lstat as PI,rename as Yi,rm as LI}from"node:fs/promises";import{platform as Uy}from"node:os";var DI=e=>e?.code==="ENOENT",Ka=async(e,t=Uy())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},fe=async(e,t,n=Uy())=>{if(n!=="win32"){await Yi(e,t);return}let r=`${t}.anyray-old-${process.pid}-${TI()}`,o=!1;try{let a=await PI(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await Yi(t,r),o=!0}catch(a){if(!DI(a))throw a}try{await Yi(e,t)}catch(a){if(o)try{await Yi(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await LI(r,{force:!0})};var Ga=e=>`${e}.anyray-bak`,Zy=async e=>{let t;try{t=await gu(wu(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},Wy=async(e,t)=>{let n,r;try{n=await gu(e,"wx",384),await n.writeFile(t,"utf-8"),await Ka(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Yt(e,{force:!0}).catch(()=>{}),r;await Zy(e)},UI=async e=>{let t;try{t=await gu(e,"r"),await Ka(t)}finally{await t?.close().catch(()=>{})}await Zy(e)},R=async e=>{try{return await NI(e),!0}catch{return!1}},M=async e=>{if(!await R(e))return{};let t=await Vy(e,"utf-8");if(!t.trim())return{};let n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n},Z=async(e,t,n={})=>{await pu(wu(e),{recursive:!0,mode:448});let r=Ga(e);if(n.backup!==!1&&await R(e)&&!await R(r))try{await Wy(r,await Vy(e,"utf-8"))}catch(a){if(a.code!=="EEXIST")throw a}let o=`${e}.anyray-tmp-${process.pid}-${Yy()}`;try{await Wy(o,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`),await fe(o,e),await $I(e,384),await UI(e)}finally{await Yt(o,{force:!0}).catch(()=>{})}},Xy=1,Ky=3e4,HI=5e3,WI=/^[a-f0-9]{64}$/,Jy=e=>`${e}.pending`,KI=e=>`${e}.lock`,fu=e=>{if(e===void 0)return"null";if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(n=>fu(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${fu(t[n])}`).join(",")}}`},hu=(e,t)=>({exists:e,sha256:FI("sha256").update(fu(t)).digest("hex")}),mu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gy=e=>mu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&WI.test(e.sha256),GI=e=>mu(e)&&e.transactionVersion===Xy&&Gy(e.before)&&Gy(e.after)&&mu(e.journal),yu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,xo=async(e,t)=>{try{return await M(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},jI=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},zy=async e=>{let t=KI(e),n=BI(t,"owner.json");await pu(wu(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=Yy();try{await pu(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await xo(n,"ownership journal");if(typeof c.pid!="number"||!Number.isSafeInteger(c.pid)||c.pid<=0)throw new Error("lock owner is missing or invalid");let l=Date.now()-(await Hy(n)).mtimeMs;i=!jI(c.pid)||l>Ky}catch{try{i=Date.now()-(await Hy(t)).mtimeMs>Ky}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Yt(t,{recursive:!0,force:!0});continue}try{await Z(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Yt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await xo(n,"ownership journal")).nonce!==o)return;let i=new Date;await MI(n,i,i)}catch{}})()},HI);return a.unref(),async()=>{clearInterval(a);try{(await xo(n,"ownership journal")).nonce===o&&await Yt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},qy=async e=>{let t=await R(e),n={};if(t)try{n=await M(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:hu(t,n)}},Qy=async(e,t)=>{let n=Jy(t);if(!await R(n))return;let r=await xo(n,"prepared ownership transaction");if(!GI(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await qy(e),a=await R(t),s=await R(Ga(e)),i=yu(o.fingerprint,r.before),c=yu(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await Z(t,r.journal,{backup:!1}),await Yt(n,{force:!0});return}if(i){await Yt(n,{force:!0}),a||await re(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},Zi=async(e,t,n)=>{let r=await zy(t);try{return await Qy(e,t),await n()}finally{await r()}},jy=async(e,t,n,r)=>{if(!await R(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await xo(e,"ownership journal");if(!(n&&Eo(a,t))){if(!Eo(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await Z(e,t,{backup:!1}):await Yt(e,{force:!0})}},Xi=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await zy(a);try{await Qy(n,a);let l=await qy(n),d=hu(i,r),u=await R(a),f=u?await xo(a,"ownership journal"):void 0,p=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!yu(l.fingerprint,d)){if(Eo(l.value,o)&&f&&Eo(f,p))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&Eo(l.value,o)&&f&&Eo(f,p))return;let h=await R(Ga(n));if(f?.fileExisted===!0&&!h)throw new Error("ownership backup is missing; configuration was left unchanged");if(h&&!f)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let m=Jy(a),w={transactionVersion:Xy,before:l.fingerprint,after:hu(!0,o),journal:p};await Z(m,w,{backup:!1});try{await Z(n,o,f?{backup:!1}:{}),await(t.writeJournal??Z)(a,p,{backup:!1}),await Yt(m,{force:!0})}catch(g){try{await jy(n,l.value,l.exists,o)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed and config rollback was incomplete")}try{await jy(a,f??{},u,p),await Yt(m,{force:!0}),!h&&!f&&await re(n)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed after config rollback")}throw g}}finally{await c()}},Dr=async e=>{try{return await M(Ga(e))}catch{return{}}},re=async e=>{await Yt(Ga(e),{force:!0}).catch(()=>{})};import{access as gR}from"node:fs/promises";import{spawnSync as nR}from"node:child_process";import{readFileSync as rR,realpathSync as Ya,statSync as lg}from"node:fs";import{access as oR,cp as dg,mkdir as ig,readdir as aR,readFile as Iu,realpath as sR,rename as iR,rm as Eu,writeFile as cR}from"node:fs/promises";import{tmpdir as lR}from"node:os";import{basename as Ro,dirname as Ke,join as Re,resolve as dR}from"node:path";import{writeFile as Ji,readFile as ja,chmod as ku,stat as Au,mkdir as tg,rm as Nr,access as VI}from"node:fs/promises";import{randomUUID as YI}from"node:crypto";import{homedir as ng}from"node:os";import{join as Sn}from"node:path";var q=()=>Sn(ng(),".anyray"),Io=async()=>{let e=q();try{if((await Au(e)).isDirectory())return Sn(e,"connect.json")}catch{}return e},Cu=()=>Sn(q(),"dev-key.pem"),kt=async()=>{let e=q(),t;try{if(!(await Au(e)).isDirectory())t=await ja(e,"utf-8").catch(()=>{}),await Nr(e,{force:!0});else return}catch{}if(await tg(e,{recursive:!0,mode:448}),t!==void 0){let n=Sn(e,"connect.json");await Ji(n,t,{mode:384}),await ku(n,384)}},zi=async e=>{await kt();let t=Cu();await Ji(t,e,{mode:384}),await ku(t,384)},Be=async()=>{try{let e=await ja(Cu(),"utf-8");return e.trim()?e:void 0}catch{return}},Va=async()=>{await Nr(Cu(),{force:!0}).catch(()=>{})},ZI=e=>{let{fallbackEnabled:t,fallbackGatewayTimeoutMs:n,fallbackBreaker:r,...o}=e,a=o;return t===!0&&(a.keyRefreshEnabled=!0),a},P=async()=>{try{let e=await ja(await Io(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:ZI(t)}catch{return{}}},XI=0,JI=3e4,zI=5e3,qI=25,QI=()=>Sn(ng(),".anyray-connect-profile.lock"),eR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},tR=async e=>{try{let t=JSON.parse(await ja(Sn(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!eR(t.pid)}catch{}return Date.now()-(await Au(e)).mtimeMs>JI},rg=async()=>{let e=QI(),t=Sn(e,"owner.json"),n=Date.now()+zI;for(;;){let r=YI();try{await tg(e,{mode:448});try{await Ji(t,`${JSON.stringify({pid:process.pid,nonce:r})}
|
|
4
|
+
`,{mode:384})}catch(a){throw await Nr(e,{recursive:!0,force:!0}).catch(()=>{}),a}return async()=>{try{JSON.parse(await ja(t,"utf-8")).nonce===r&&await Nr(e,{recursive:!0,force:!0})}catch{}}}catch(a){if(a.code!=="EEXIST")throw a}if(!(await tR(e).catch(()=>!1)&&await Nr(e,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=n)throw new Error("connect profile is busy; retry the command");await new Promise(a=>setTimeout(a,qI))}}},og=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Io(),r=`${n}.${process.pid}.${XI++}.tmp`;await Ji(r,`${JSON.stringify(t,null,2)}
|
|
5
|
+
`,{mode:384}),await ku(r,384);try{await fe(r,n)}catch(o){throw await Nr(r,{force:!0}).catch(()=>{}),o}},te=async e=>{let t=await rg();try{await og(e)}finally{await t()}},ag=async e=>{let t=await rg();try{let n=await P(),{next:r,result:o}=e(n);return r&&await og(r),o}finally{await t()}},bu=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],eg="ssoLink",vu=async()=>{let e=await P();return bu.some(t=>e[t]!==void 0)?!0:await Be()!==void 0},qi=async()=>{let e=await P(),t=bu.some(a=>e[a]!==void 0),n=e[eg]!==void 0,r=e.byoUpstream!==void 0,o=await Be()!==void 0;if(!t&&!n&&!r&&!o)return!1;if(t||n||r){let a={...e};for(let s of bu)delete a[s];delete a[eg],delete a.byoUpstream,delete a.anyrayFleetManaged,await te(a)}if(await Va(),await Be())throw new Error(`could not remove the dev key from ${q()}`);return!0},sg=["fallback-bundle.enc","fallback-key","fallback-usage-queue.jsonl"],Qi=async()=>{let e=q();for(let t of sg)await Nr(Sn(e,t),{force:!0}).catch(()=>{})},Su=async()=>{let e=q(),t=[];for(let n of sg){let r=Sn(e,n);try{await VI(r),t.push(r)}catch{}}return t},Xn=async(e,t,n=!1)=>{let r=await P(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let h of e){let m=h.status==="configured"||h.status==="queued";!t&&m&&(o.add(h.id),a.delete(h.id),s=void 0),t&&(h.status==="reverted"||h.status==="queued")&&(o.delete(h.id),a.add(h.id))}n&&o.clear();let i=[...o].sort(),c=[...r.managedTools??[]].sort(),l=[...a].sort(),d=[...r.revertedTools??[]].sort();if(i.length===c.length&&i.every((h,m)=>h===c[m])&&r.revertedTools!=null&&l.length===d.length&&l.every((h,m)=>h===d[m])&&s===r.offboardedAt)return;let{offboardedAt:f,...p}=r;await te({...p,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},ec=async(e=new Date().toISOString())=>{await te({...await P(),offboardedAt:e})};var Oo=e=>dR(e).replace(/\\/g,"/").toLowerCase(),xu=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",Za=e=>`${e}.source`,ug=e=>/(^|\/)_npx(\/|$)/.test(Oo(e)),Ru=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Oo(e)),Ou=e=>{let t=Oo(e),n=[lR(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Oo);return ug(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},mt=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),Xa=e=>/[\\/](node|node\.exe)$/i.test(e),Jn=(e=mt())=>Xa(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,cg=e=>{try{let t=lg(e);return t.isFile()?t.size:void 0}catch{return}},_u=e=>{let t=Ke(e);if(Ro(t)==="versions")return t;let n=Ke(t);return Ro(n)==="versions"?n:void 0},nc=(e,t)=>t!==void 0&&(Ke(e)===t||Ke(Ke(e))===t),uR=e=>{let t=_u(e);if(!t)return;let n=Re(Ke(t),"bin",xu());try{let r=Ya(n);return r===Ya(e)||nc(r,Ya(t))?n:void 0}catch{return}},_o=(e=q(),t=process.platform)=>{let n=Re(e,"bin",xu(t));try{let r=Ya(n),o=Ya(Re(e,"versions"));if(nc(r,o))return n;if(t==="win32"){let a=rR(Za(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=cg(Re(o,a,xu(t)))??cg(Re(o,a));if(s!==void 0&&s===lg(n).size)return n}}catch{return}},$r=(e=mt())=>{let t=Jn(e),n=Ru(t)||Pu(t)?_o():void 0;return uR(e.execPath)??n??t},pg=(e=mt())=>$r(e)!==Jn(e),dn=(e,t=mt())=>{let n=$r(t);return Xa(t.execPath)&&t.scriptPath!==void 0&&n===Jn(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},fg=(e=mt())=>{let t=$r(e);return!Xa(e.execPath)&&!Ou(t)?Ke(t):Re(q(),"bin")},tc=async e=>{try{return await oR(e),!0}catch{return!1}},pR=async e=>{let t=await sR(e),n=Ke(t),r=Ke(n),o=Re(r,"package.json"),a=await Iu(o,"utf8"),s=JSON.parse(a);if(typeof s.version!="string"||!/^[0-9A-Za-z][0-9A-Za-z.-]*$/.test(s.version))throw new Error("published package has no safe version");if(!await tc(Re(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},fR=async(e,t)=>{let n=t;for(;;){let r=Re(n,"node_modules",e);if(await tc(Re(r,"package.json")))return r;let o=Ke(n);if(o===n)return;n=o}},hR=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Iu(Re(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await fR(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await dg(i,Re(t,s),{recursive:!0}),r.push(i)}}},mR=async(e=mt())=>{let t=_o();if(t)return{command:t,args:[],entryPath:t};if(!Xa(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await pR(e.scriptPath);await kt();let r=Re(q(),"bin",`connect-runtime-${n.version}`),o=Re(r,"dist","index.js");if(!await tc(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Eu(a,{recursive:!0,force:!0}),await ig(a,{recursive:!0,mode:448});try{await dg(n.dist,Re(a,"dist"),{recursive:!0}),await cR(Re(a,"package.json"),await Iu(n.packageJson),{mode:384}),await hR(n.root,Re(a,"node_modules")),await ig(Ke(r),{recursive:!0,mode:448});try{await iR(a,r)}catch(s){if(!await tc(o))throw s}}finally{await Eu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Tu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,yR=e=>{let t=Ro(Ke(Ke(e)));return Tu.test(t)?t:void 0},Pu=(e,t=q())=>{let n=Ke(Ke(e));return Oo(Ke(n))===Oo(Re(t,"bin"))&&Tu.test(Ro(n))&&Ro(Ke(e))==="dist"&&Ro(e)==="index.js"},rc=async(e=mt())=>{let t=Re(q(),"bin"),n=yR(Jn(e)),r=[];for(let o of await aR(t).catch(()=>[])){if(!Tu.test(o)||o===n)continue;let a=Re(t,o);await Eu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},hg=async(e,t=mt())=>{let n=Jn(t);if(!Xa(t.execPath)||!ug(n)||_o())return;let r=await mR(t),o=nR(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Lu=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,Ja=(e,t)=>[e,...t].map(Lu).join(" "),En=(e,t={})=>({...t.matcher!==void 0?{matcher:t.matcher}:{},hooks:[{type:"command",command:e,...t.timeout!==void 0?{timeout:t.timeout}:{},...t.async!==void 0?{async:t.async}:{}}]}),zn=(e,t)=>{if(e===null||typeof e!="object")return!1;let n=e.hooks;return Array.isArray(n)&&n.some(r=>r!==null&&typeof r=="object"&&typeof r.command=="string"&&r.command.includes(t))},oc=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!zn(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},To=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!zn(s,n));return a.length===o.length?!1:(a.length?r[t]=a:delete r[t],Object.keys(r).length===0&&delete e.hooks,!0)},Du=e=>{let t=e.hooks;if(!t)return!1;let n=!1;for(let[r,o]of Object.entries(t)){if(!Array.isArray(o))continue;let a=o.filter(s=>!zn(s,"__anyray-"));a.length!==o.length&&(n=!0,a.length?t[r]=a:delete t[r])}return n&&Object.keys(t).length===0&&delete e.hooks,n};var Ze="__anyray-hook",mg="__anyray-codex-hook",qn="__anyray-prompt-hook",yg="__anyray-shell-pretool",Nu="__anyray-shell-run",gg="__anyray-read-pretool",Qn="__anyray-refresh",za=(e,t=[])=>{let{command:n,args:r}=dn([e,...t]);return{command:n,args:r}},Tt=(e,t=[])=>{let n=za(e,t);return[n.command,...n.args].map(Lu).join(" ")},ac=(e,t,n=[])=>typeof e=="string"&&e.trim()===Tt(t,n),wg=()=>Tt("print-key"),Oe=()=>$r(),Ge=Ou,ce=()=>!Ge(Oe()),Mr=async()=>{if(!ce())return!1;try{return await gR(Oe()),!0}catch{return!1}},er="__anyray-mcp-server",je=e=>za(er,[e]),wR=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),sc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=je(t);return n.command===r.command&&wR(n.args,r.args)},Zt=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(typeof n.command!="string"||!Array.isArray(n.args)||!n.args.every(o=>typeof o=="string"))return!1;let r=n.args;return(r.length===2||r.length===3)&&r.at(-2)===er&&r.at(-1)===t};var J=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,le=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Fr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],bg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],ic=[...Fr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],bR=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
|
|
6
|
+
`)},un=(e,t={})=>{let n=e.byoUpstream,r=!n&&J(e,"anthropic"),o=le({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1&&!((r||n)&&e.viaLocalProxy),s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=bR(o,r,a?e.clientKey:void 0,n?.url);return{env:{ANTHROPIC_BASE_URL:e.anthropicBaseUrl,...c?{ANTHROPIC_CUSTOM_HEADERS:c}:{},...n&&s?{ANTHROPIC_AUTH_TOKEN:n.key}:{},...r||n||!s?{}:{ANTHROPIC_AUTH_TOKEN:e.clientKey??e.placeholderKey},...n?{}:{ENABLE_TOOL_SEARCH:"true"},...n?{}:{_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL:"1"},...i!==void 0?{CLAUDE_CODE_MAX_CONTEXT_TOKENS:String(i)}:{}},subscription:r,byoUpstream:!!n,meta:o,headers:c}};import{z as $u}from"zod";var kR=5e3,AR=1e3,CR=1e8,vR=$u.object({modelContext:$u.object({contextTokens:$u.number().int().min(AR).max(CR)}).optional()}),kg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},Ag=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??kR,a=new AbortController,s=setTimeout(()=>a.abort(),o);try{let i=`${e}/connect/policy?model=${encodeURIComponent(n)}`,c=await fetch(i,{method:"GET",headers:{"x-anyray-api-key":t},signal:a.signal});if(!c.ok)return;let l=vR.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var SR=1e6,qa="[1m]",ER=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Cg=(e,t)=>!e||t===void 0?{}:ER(e)?{envTokens:t}:t<SR?{}:e.toLowerCase().endsWith(qa)?{}:{model:`${e}${qa}`},vg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(qa))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(qa))return e.slice(0,-qa.length)};import{platform as xR}from"node:os";var Pt=(e=xR())=>{switch(e){case"darwin":return"/Library/Application Support/ClaudeCode/managed-settings.json";case"win32":return"C:\\Program Files\\ClaudeCode\\managed-settings.json";default:return"/etc/claude-code/managed-settings.json"}};var xn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],cc=e=>typeof e=="string"&&e.trim()!=="",IR=(e,t)=>typeof e[t]=="string"&&!cc(e[t]),Sg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},RR=()=>M(Pt()).catch(()=>({})),Eg=async(e={})=>{let t=e.env??process.env,n=Sg(e.userSettings??{}),r=Sg(await(e.readManaged??RR)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of xn)cc(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Pt()})`,repairable:!1}):cc(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!IR(n,a)&&cc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Mu=e=>`${e.name} is set (${e.source}) \u2014 Claude Code sends requests straight to ${e.cloud} and ignores the gateway routing written here, so none of its traffic reaches Anyray until that setting is removed`,Fu=e=>"Fix: remove the setting where it is set"+(e.some(t=>t.kind==="managed")?" (the managed settings file is IT-owned \u2014 ask your admin)":"")+", then restart Claude Code. The gateway can serve Bedrock/Vertex itself once its provider is configured \u2014 see the Bedrock page in the Anyray docs.",xg=e=>`Disabled direct ${e.cloud} mode: ${e.name} was set (${e.source}), which would bypass the gateway route entirely \u2014 pinned it empty in settings.json (the env block outranks shell exports, and '' is Claude Code's documented unset). Delete the original setting to drop the pin.`;var OR=xn.map(e=>e.name),_R=ic.filter(e=>!OR.includes(e)),Ig=e=>typeof e=="string"&&e.trim()!=="",Rg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},TR=(e,t,n)=>{if(typeof e!="string"||typeof t!="string")return!1;let r=o=>n?o.trim().replace(/\/+$/,""):o.trim();return r(e)===r(t)},PR=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Bu=()=>M(Pt()).catch(()=>({})),Og=Bu,LR=e=>{let t=e.hooks;if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t.PostToolUse;return Array.isArray(n)&&n.some(r=>zn(r,Ze))},_g=async(e={})=>{let t=await(e.readManaged??Og)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!LR(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},lc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Pt()}) \u2014 Claude Code skips every hook and the status line, including Anyray's savings hook`:e.state==="restricted_dropping_ours"?`allowManagedHooksOnly is true in managed settings (${Pt()}), but that file does not carry the Anyray PostToolUse hook \u2014 Claude Code silently drops the user-scope hook Connect installed`:"Claude Code managed hook policy allows the Anyray hook lane",dc=e=>e.state==="disabled"?"Fix: ask the MDM owner to drop `disableAllHooks`, then restart Claude Code. Connect never overrides machine policy.":e.state==="restricted_dropping_ours"?"Fix: ask the MDM owner to drop `allowManagedHooksOnly`, or add the Anyray hooks to the managed file. `anyray-connect managed --print --sso <link> --bin <path>` emits the credential-free block; then restart Claude Code.":"No action required.",Tg=async(e={})=>{let t=Rg(e.userSettings??{}),n=Rg(await(e.readManaged??Og)().catch(()=>({}))),r=[];for(let o of _R){if(!Ig(n[o])||!Ig(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(TR(n[o],t[o],a))continue;let s=a?PR(n[o]):void 0;r.push({name:o,source:`managed settings (${Pt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},Pg=e=>e.routing?`${e.name} is set to a different value (${e.source}), which outranks the routing written in settings.json \u2014 Claude Code sends its traffic to ${e.managedOrigin??"that endpoint"} instead, so none of it reaches Anyray until the managed value changes`:`${e.name} is set to a different value (${e.source}), which outranks the value written in settings.json \u2014 Claude Code uses the managed one, so the behavior this key controls is not the one connect configured`,Lg=e=>"Fix: the managed settings file is IT-owned \u2014 ask your admin to "+(e.some(t=>t.routing)?"point it at the Anyray gateway (`anyray-connect managed --print` emits the block to deploy) or drop the key so per-user setup governs":"drop the key so per-user setup governs")+", then restart Claude Code.";import{homedir as DR}from"node:os";import{join as NR}from"node:path";import{readFile as $R}from"node:fs/promises";var nt=e=>!!e.keyRefreshEnabled;var MR=400,Dg=async()=>{try{let e=NR(DR(),".claude","settings.json"),n=JSON.parse(await $R(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
|
|
7
|
+
`)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},Ng=async()=>{try{let e=await P();return e.gateway?{origin:new URL(e.gateway).origin,metadata:le({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},rt=async(e="auto")=>e==="profile"?Ng():e==="claude"?Dg():await Dg()??await Ng(),uc=async(e={})=>{let t=e.readTarget??rt,n=e.loadProfile??P,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return nt(r)&&r.fallbackPort&&a.add(`http://${ht}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},Xt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},pc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),MR);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Xt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var In=()=>hc(fc(),".claude","settings.json"),Qa=()=>hc(fc(),".claude.json"),FR=ic,tr="anyray",BR=()=>({type:"stdio",...je("claude"),alwaysLoad:!0}),Br=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),UR=e=>{if("mcpServers"in e&&!Br(e.mcpServers))return"conflict";let t=Br(e.mcpServers)?{...e.mcpServers}:{},n=t[tr];return n!==void 0&&!Zt(n,"claude")?"conflict":(t[tr]=BR(),e.mcpServers=t,"installed")},$g=e=>{let t=e.mcpServers;return!t||!(tr in t)||!Zt(t[tr],"claude")?!1:(delete t[tr],Object.keys(t).length===0&&delete e.mcpServers,!0)},HR=e=>{oc(e,"PostToolUse",Ze,En(Tt(Ze),{matcher:"*"})),oc(e,"UserPromptSubmit",qn,En(Tt(qn)))},WR=e=>{oc(e,"SessionStart",Qn,En(Tt(Qn),{async:!0}))},Bg=e=>To(e,"SessionStart",Qn),Mg=e=>{let t=To(e,"PostToolUse",Ze),n=To(e,"UserPromptSubmit",qn),r=Bg(e);return t||n||r},KR="print-key",GR=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Ur=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===KR&&GR(t)},jR=async(e,t)=>{let n=(await Dr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of FR){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},VR=e=>typeof e.apiKeyHelper=="string"&&!Ur(e),Ug=async e=>{let t=await Bu(),n=async()=>t,[r,o,a]=await Promise.all([Eg({userSettings:e,readManaged:n}),Tg({userSettings:e,readManaged:n}).catch(()=>[]),_g({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},Fg=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await Ug(e),o=Fu(t),a=Lg(n);return{routingOverrides:[...t.map(i=>({problem:Mu(i),fix:i.repairable?"Fix: run `anyray-connect doctor --repair` (or re-run `anyray-connect`) \u2014 apply disables this switch by pinning it empty in settings.json.":o,repairable:i.repairable})),...n.map(i=>({problem:Pg(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},nr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=hc(fc(),".claude"),t=await R(e);return{installed:t,detail:t?In():"no ~/.claude directory"}},async apply(e,t){let n=In(),r=await M(n),o=kg(r),a=await Ag(e.origin,e.clientKey,o),s=Cg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=un(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await Ug(r),h=f.filter(I=>!I.repairable),m=f.filter(I=>I.repairable),w=[...h.map(I=>`WARNING: ${Mu(I)}.`),...h.length?[Fu(h)]:[],...p.state==="fine"?[]:[`WARNING: ${lc(p)}.`,dc(p)],...m.map(I=>xg(I)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let g=r.env??{};r.env={...g,...i};let y=r.env;for(let{name:I}of xn)m.some(T=>T.name===I)?y[I]="":y[I]===""&&(process.env[I]??"").trim()===""&&delete y[I];if(u||delete y.ANTHROPIC_CUSTOM_HEADERS,c&&(g.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete y.ANTHROPIC_AUTH_TOKEN),l)for(let I of bg)delete y[I];let b=!!e.clientKey,v=ce(),S=VR(r);!c&&!l&&b&&v&&!S?(r.apiKeyHelper=wg(),delete y.ANTHROPIC_AUTH_TOKEN,w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Ur(r)&&delete r.apiKeyHelper,S&&!c&&!l&&b&&v&&w.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&v?(WR(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Bg(r),ce()?(HR(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(Mg(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await Z(n,r);let x=[n],A=Qa();try{let I=await M(A),T=!1;ce()?UR(I)==="conflict"?w.push(`MCP name conflict in ${A}: mcpServers.${tr} is not owned by Anyray Connect, so it was left untouched.`):(T=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):T=$g(I),T&&(await Z(A,I),x.push(A))}catch(I){w.push(`Could not register the Anyray MCP server in ${A} (${I instanceof Error?I.message:String(I)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:x}},skillsDir(){return hc(fc(),".claude","skills")},async watchPaths(){return[In(),Qa()]},async pointsAt(e){let t=In();if(!await R(t))return!1;try{let o=(await M(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await M(In()).catch(()=>({}));return Fg(e)},async routingOverrides(){let e=await M(In()).catch(()=>({}));return(await Fg(e)).routingOverrides},async mcpStatus(){let e=Qa();if(!await R(e))return{registered:!1,command:null};try{let r=(await M(e)).mcpServers?.[tr];return!r||!Zt(r,"claude")?{registered:!1,command:null}:{registered:!0,command:typeof r.command=="string"?r.command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=In();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!Br(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>zn(c,Ze))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>zn(c,Ze)&&Br(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Br(l)&&ac(l.command,Ze))))}}catch{e="unreadable"}let r,o=!0,a=Qa();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!Br(s.mcpServers))r="unreadable";else{let i=s.mcpServers[tr];r=i===void 0?"missing":Zt(i,"claude")?"owned":"foreign",r==="owned"&&(o=sc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Mr()?"owned":"missing",beacon_target:await uc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(In()),t=Br(e.env)?e.env:{},n=typeof t.ANTHROPIC_CUSTOM_HEADERS=="string"?t.ANTHROPIC_CUSTOM_HEADERS:"";if(/^x-anyray-custom-host:/m.test(n))return["byo"];if(/^x-anyray-auth-mode:\s*passthrough$/m.test(n))return["subscription"];if(typeof t.ANTHROPIC_AUTH_TOKEN=="string"||typeof e.apiKeyHelper=="string")return["api_key"]}catch{}return["unknown"]},async revert(e){let t=In();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await M(t),r=n.env,o=Mg(n),a=Ur(n);a&&delete n.apiKeyHelper;let s=r?await jR(t,r):[],i=vg(typeof n.model=="string"?n.model:void 0,(await Dr(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await Z(t,n,{backup:!1});let c=[`removed Anyray keys from ${t}`];i!==void 0&&c.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&c.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&c.push("Removed the Anyray apiKeyHelper."),s.length&&c.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let l=Qa();try{let d=await M(l);$g(d)&&(await Z(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await re(t),{status:"reverted",messages:c,changedFiles:[t]}}};var be="0.11.133";var pn=e=>{let{command:t,args:n}=dn([e]);return{command:t,args:n}},rr=()=>$r();import{homedir as Hg,userInfo as YR}from"node:os";var es=()=>{try{return Hg()!==YR().homedir}catch{return!1}},Po=e=>[`Skipped ${e} \u2014 HOME (${Hg()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var yt=(e=process.env)=>e.CODESPACES==="true"||e.CODESPACE_NAME?"codespaces":e.REMOTE_CONTAINERS==="true"||e.REMOTE_CONTAINERS_IPC||e.DEVCONTAINER?"devcontainer":e.SSH_CONNECTION||e.SSH_TTY?"ssh":null,ts=(e=process.env)=>yt(e)!==null,At=e=>e==="codespaces"||e==="devcontainer",or=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var Ku="__anyray-fallback-proxy",os="ai.anyray.connect.fallback",ar="anyray-fallback",Vg=os,Ae=8785,as=60,Gu="x-anyray-local",ju=()=>pn(Ku),Wg=rr,yc=async(e=Ae)=>{let t=n=>new Promise(r=>{let o=JR();o.once("error",()=>r(!1)),o.listen(n,"127.0.0.1",()=>o.close(()=>r(!0)))});for(let n=e;n<e+20;n++)if(await t(n))return n;return e},ke=async(e,t=1500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}/__anyray/health`,{signal:n.signal});return o.ok?await o.json():null}catch{return null}finally{clearTimeout(r)}},$o=()=>No(rs(),"Library","LaunchAgents",`${Vg}.plist`),ss=()=>No(rs(),".anyray","logs"),ns=()=>No(ss(),"connect-daemon.log"),Yg=async(e,t=1048576)=>{await Gg(e).then(r=>r.size,()=>0)>t&&await XR(e).catch(()=>{})},Mo=()=>No(rs(),".config","systemd","user",`${ar}.service`),Uu=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),is=(e=ju())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${Uu(o)}</string>`).join(`
|
|
8
8
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
9
9
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
10
10
|
<plist version="1.0">
|
|
11
11
|
<dict>
|
|
12
|
-
<key>Label</key><string>${
|
|
12
|
+
<key>Label</key><string>${Vg}</string>
|
|
13
13
|
<key>ProgramArguments</key>
|
|
14
14
|
<array>
|
|
15
15
|
${r}
|
|
@@ -17,12 +17,12 @@ ${r}
|
|
|
17
17
|
<key>RunAtLoad</key><true/>
|
|
18
18
|
<key>KeepAlive</key><true/>
|
|
19
19
|
<key>ProcessType</key><string>Background</string>
|
|
20
|
-
<key>ExitTimeOut</key><integer>${
|
|
21
|
-
<key>StandardOutPath</key><string>${
|
|
22
|
-
<key>StandardErrorPath</key><string>${
|
|
20
|
+
<key>ExitTimeOut</key><integer>${as}</integer>
|
|
21
|
+
<key>StandardOutPath</key><string>${Uu(ns())}</string>
|
|
22
|
+
<key>StandardErrorPath</key><string>${Uu(ns())}</string>
|
|
23
23
|
</dict>
|
|
24
24
|
</plist>
|
|
25
|
-
`},
|
|
25
|
+
`},cs=(e=ju())=>{let{command:t,args:n}=e;return`[Unit]
|
|
26
26
|
Description=Anyray connect local key-refresh proxy
|
|
27
27
|
After=network-online.target
|
|
28
28
|
|
|
@@ -30,93 +30,93 @@ After=network-online.target
|
|
|
30
30
|
ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
|
|
31
31
|
Restart=always
|
|
32
32
|
RestartSec=2
|
|
33
|
-
TimeoutStopSec=${
|
|
33
|
+
TimeoutStopSec=${as}
|
|
34
34
|
|
|
35
35
|
[Install]
|
|
36
36
|
WantedBy=default.target
|
|
37
|
-
`},
|
|
38
|
-
`,"utf-8")}catch{}},
|
|
37
|
+
`},mc=()=>{let{command:e,args:t}=ju();return["Auto-start is not wired for this OS. Run the key-refresh proxy yourself:",` ${[e,...t].map(r=>/\s/.test(r)?JSON.stringify(r):r).join(" ")}`,"(keep it running in the background \u2014 your tools route through it)."]},Zg=async()=>{let e=Do();if(e!=="darwin"&&e!=="linux")return!1;let t=e==="darwin"?$o():Mo();try{return await Gg(t),!0}catch{return!1}},Xg=async()=>{let e=Do();if(e!=="darwin"&&e!=="linux")return!0;let t=e==="darwin"?$o():Mo(),n=e==="darwin"?is():cs();return await Kg(t,"utf-8").catch(()=>null)===n},Wu=async e=>{await Hu(No(rs(),"Library","LaunchAgents"),{recursive:!0}),await Hu(ss(),{recursive:!0,mode:448}),await jg(e,is())},Jg=async()=>{let e=Do();return e==="darwin"?(await Wu($o()),!0):e==="linux"?(await Hu(No(rs(),".config","systemd","user"),{recursive:!0}),await jg(Mo(),cs()),!0):!1},zg=async()=>Jg().catch(()=>!1),zR=async(e,t)=>{let n=Do();if(n!=="darwin"&&n!=="linux")return!1;let r=n==="darwin"?$o():Mo(),o=n==="darwin"?is():cs();if(await Kg(r,"utf-8").catch(()=>null)!==o)return!1;let s=await ke(e);return s?.version!==be?!1:typeof s.remoteOrigin=="string"&&Ye(s.remoteOrigin)===Ye(t)},Lt=async e=>{if(Ge(Wg()))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 anyray-connect is running from a temporary path (${Wg()}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(es())return{ok:!1,messages:Po("key-refresh auto-start")};{let n=yt();if(At(n))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 ${or(n)} has no per-user service manager to supervise the daemon.`]}}if(await zR(e.port,e.remoteOrigin))return{ok:!0,messages:["Key-refresh service already current \u2014 left running."]};let t=Do();try{if(t==="darwin"){let n=$o(),r=String(process.getuid?.()??""),o=`${n}.new-${process.pid}`;await Lo(o,{force:!0}).catch(()=>{}),await Wu(o),fn("launchctl",["bootout",`gui/${r}`,n]),await Lo(n,{force:!0}).catch(()=>{});try{await ZR(o,n)}catch{await Wu(n),await Lo(o,{force:!0}).catch(()=>{})}return fn("launchctl",["bootstrap",`gui/${r}`,n]).status===0||fn("launchctl",["load","-w",n]).status===0?{ok:!0,messages:[`Installed launchd agent ${n}.`]}:{ok:!1,messages:[`Wrote ${n} but launchd would not load the agent.`,...mc()]}}if(t==="linux"){let n=Mo();return await Jg(),fn("systemctl",["--user","daemon-reload"]),fn("systemctl",["--user","enable",`${ar}.service`]),fn("systemctl",["--user","restart",`${ar}.service`]).status!==0?{ok:!1,messages:[`Wrote ${n} but \`systemctl --user restart\` failed.`,...mc()]}:{ok:!0,messages:[`Installed systemd user unit ${n}.`]}}return{ok:!1,messages:mc()}}catch(n){return{ok:!1,messages:[`Could not install the key-refresh service: ${n instanceof Error?n.message:String(n)}`,...mc()]}}},Vu=async(e=Ae,t={})=>{if(await ke(e)===null)return!1;let n=t.drain==="idle"?"?drain=idle":"";try{let r=new AbortController,o=setTimeout(()=>r.abort(),1500);try{await fetch(`http://127.0.0.1:${e}/__anyray/shutdown${n}`,{method:"POST",headers:{[Gu]:"1"},signal:r.signal})}finally{clearTimeout(o)}}catch{}for(let r=0;r<10&&await ke(e,300)!==null;r++)await new Promise(o=>setTimeout(o,100));return!0},Jt=async(e=Ae)=>{let t=Do();await Lo(ns(),{force:!0}).catch(()=>{});let n=[],r=es();try{if(r)n.push(...Po("key-refresh service teardown"));else if(t==="darwin"){let o=$o(),a=String(process.getuid?.()??"");fn("launchctl",["bootout",`gui/${a}`,o]),fn("launchctl",["unload",o]),await Lo(o,{force:!0}),n.push("Removed the launchd key-refresh agent.")}else t==="linux"&&(fn("systemctl",["--user","disable","--now",`${ar}.service`]),await Lo(Mo(),{force:!0}),fn("systemctl",["--user","daemon-reload"]),n.push("Removed the systemd key-refresh unit."))}catch{}try{await Vu(e)&&n.push("Stopped the running key-refresh proxy daemon.")}catch{}return{ok:!0,messages:n}};import{stat as sZ}from"node:fs/promises";import{readFileSync as qR,rmSync as QR,writeFileSync as eO,mkdirSync as tO}from"node:fs";import{join as nO}from"node:path";var Yu=()=>nO(q(),"draining"),qg=e=>{try{tO(q(),{recursive:!0}),eO(Yu(),`${Math.floor(e)}
|
|
38
|
+
`,"utf-8")}catch{}},Zu=()=>{try{QR(Yu(),{force:!0})}catch{}},rO=16*6e4,Xu=(e=Date.now())=>{let t;try{t=qR(Yu(),"utf-8")}catch{return!1}let n=t.trim();if(!/^\d+$/.test(n))return!1;let r=Number(n);return Number.isSafeInteger(r)&&r>e&&r<=e+rO};import{homedir as Qu,platform as ep}from"node:os";import{join as Fo}from"node:path";import{mkdir as Ju,readFile as oO,rename as aO,writeFile as gc,rm as Hr}from"node:fs/promises";import{spawnSync as sO}from"node:child_process";var qu=()=>Fo(ss(),"connect-refresh.log"),bc=1800,us="ai.anyray.connect.refresh",Wr="anyray-refresh",kc="\\AnyrayConnectKeyRefresh",Ac=us,ps=Wr,ds=kc,iO=String(bc/60),tp=(e,t)=>{let n=sO(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},np=()=>Fo(Qu(),"Library","LaunchAgents",`${Ac}.plist`),rp=()=>Fo(Qu(),".config","systemd","user"),Qg=()=>Fo(rp(),`${ps}.service`),wc=()=>Fo(rp(),`${ps}.timer`),zu=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Cc=()=>pn(Qn),cO=(e=Cc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${zu(o)}</string>`).join(`
|
|
39
39
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
40
40
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
41
41
|
<plist version="1.0">
|
|
42
42
|
<dict>
|
|
43
|
-
<key>Label</key><string>${
|
|
43
|
+
<key>Label</key><string>${Ac}</string>
|
|
44
44
|
<key>ProgramArguments</key>
|
|
45
45
|
<array>
|
|
46
46
|
${r}
|
|
47
47
|
</array>
|
|
48
|
-
<key>StartInterval</key><integer>${
|
|
48
|
+
<key>StartInterval</key><integer>${bc}</integer>
|
|
49
49
|
<key>RunAtLoad</key><true/>
|
|
50
50
|
<key>ProcessType</key><string>Background</string>
|
|
51
51
|
<key>LowPriorityIO</key><true/>
|
|
52
|
-
<key>StandardOutPath</key><string>${
|
|
53
|
-
<key>StandardErrorPath</key><string>${
|
|
52
|
+
<key>StandardOutPath</key><string>${zu(qu())}</string>
|
|
53
|
+
<key>StandardErrorPath</key><string>${zu(qu())}</string>
|
|
54
54
|
</dict>
|
|
55
55
|
</plist>
|
|
56
|
-
`},
|
|
56
|
+
`},lO=(e=Cc())=>{let{command:t,args:n}=e;return`[Unit]
|
|
57
57
|
Description=Anyray connect gateway key refresh
|
|
58
58
|
After=network-online.target
|
|
59
59
|
|
|
60
60
|
[Service]
|
|
61
61
|
Type=oneshot
|
|
62
62
|
ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
|
|
63
|
-
`},
|
|
64
|
-
Description=Anyray connect gateway key refresh (every ${
|
|
63
|
+
`},dO=()=>`[Unit]
|
|
64
|
+
Description=Anyray connect gateway key refresh (every ${bc/60}m)
|
|
65
65
|
|
|
66
66
|
[Timer]
|
|
67
67
|
OnBootSec=5min
|
|
68
|
-
OnUnitActiveSec=${
|
|
68
|
+
OnUnitActiveSec=${bc/60}min
|
|
69
69
|
Persistent=true
|
|
70
70
|
|
|
71
71
|
[Install]
|
|
72
72
|
WantedBy=timers.target
|
|
73
|
-
`,tR=(e=kc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),cs=e=>["Auto-refresh scheduling is not wired for this OS. To keep your gateway","key from expiring mid-session, run this on a ~30-min schedule yourself","(e.g. cron / Task Scheduler), or just re-run connect when a tool 401s:",` ${[e.command,...e.args].map(n=>/\s/.test(n)?JSON.stringify(n):n).join(" ")}`],Qg=e=>!e.run&&Qa(),nR=async(e,t)=>await ZO(tp(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",bc]).ok,ar=async(e={})=>{let t=e.os??Qu(),n=e.invocation??kc(),r=e.run??ep,o=e.binaryPath??nr();if(Ke(o))return{ok:!1,messages:[`Skipped auto-refresh scheduling \u2014 anyray-connect is running from a temporary path (${o}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(Qg(e))return{ok:!1,messages:Po("auto-refresh scheduling")};let a=yt(e.env??(e.run?{}:process.env));if(kt(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${rr(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=tp(),i=qO(n);if(await nR(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await Xu(as(),{recursive:!0,mode:448}),await Xu(Mo(qu(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await Ur(l,{force:!0}).catch(()=>{}),await mc(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await Ur(s,{force:!0}).catch(()=>{});try{await XO(l,s)}catch{await mc(s,i),await Ur(l,{force:!0}).catch(()=>{})}return r("launchctl",["bootstrap",`gui/${c}`,s]).ok||r("launchctl",["load","-w",s]).ok?{ok:!0,messages:[`Scheduled auto-refresh via launchd (${s}).`]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...cs(n)]}}if(t==="linux")return await Xu(np(),{recursive:!0}),await mc(qg(),QO(n)),await mc(yc(),eR()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${us}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${yc()}).`]}:{ok:!1,messages:[`Wrote ${yc()} but \`systemctl --user enable --now\` failed.`,...cs(n)]};if(t==="win32"){let s=tR(n);return r("schtasks",["/Create","/TN",ls,"/TR",s,"/SC","MINUTE","/MO",zO,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",ls]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${ls}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...cs(n)]}}return{ok:!1,messages:cs(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...cs(n)]}}},sr=async(e={})=>{await Ur(zu(),{force:!0}).catch(()=>{});let t=e.os??Qu(),n=e.run??ep,r=[];if(Qg(e))return{ok:!0,messages:Po("scheduler teardown")};try{if(t==="darwin"){let o=tp(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Ur(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${us}.timer`]),await Ur(yc(),{force:!0}),await Ur(qg(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",ls,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Ac=async(e=Qu(),t=ep)=>e==="win32"?t("schtasks",["/Query","/TN",ls]).ok:e==="darwin"?t("launchctl",["list",bc]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${us}.timer`]).ok:!1;import MU from"node:http";import{spawn as XF}from"node:child_process";import{createHash as JF}from"node:crypto";import{homedir as zF}from"node:os";import{join as aS}from"node:path";import{readFile as qF,writeFile as sS,chmod as QF,stat as eB,unlink as Xv}from"node:fs/promises";import{homedir as xc,platform as pw}from"node:os";import{join as at}from"node:path";import{execFile as uR}from"node:child_process";import{readFile as pR,readdir as fR}from"node:fs/promises";import{homedir as rR,platform as oR}from"node:os";import{join as Cc}from"node:path";var ot=e=>{let t=rR();switch(oR()){case"darwin":return Cc(t,"Library","Application Support",e);case"win32":return Cc(process.env.APPDATA??Cc(t,"AppData","Roaming"),e);default:return Cc(t,".config",e)}};import{readFile as nw}from"node:fs/promises";import{homedir as Wr,platform as Fo}from"node:os";import{join as In,posix as aR,win32 as sR}from"node:path";var ps=["Code","Code - Insiders","VSCodium"],vc="1.121.0",ew=1,iR=121,rw="1.102.0",tw=1,cR=102,lR={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Sc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},rp=e=>{let t=Sc(e);return t?t.major!==ew?t.major>ew:t.minor>=iR:!1},ow=e=>{let t=Sc(e);return t?t.major!==tw?t.major>tw:t.minor>=cR:!1},dR=async e=>{if(Fo()!=="darwin")return;let t=In("/Applications",`${lR[e]}.app`,"Contents","Resources","app","package.json");if(await O(t))try{let n=JSON.parse(await nw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},aw=(e,t=Fo(),n=Wr(),r=process.env)=>{switch(t){case"darwin":return In(n,"Library","Application Support",e);case"win32":return In(r.APPDATA??In(n,"AppData","Roaming"),e);default:return In(n,".config",e)}},op=(e,t)=>e?t==="win32"?sR.join:aR.join:In,Bo=(e,t=!1,n=Fo(),r=Wr(),o=process.env)=>t?op(t,n)(r,ap[e],"data","User"):In(aw(e,n,r,o),"User"),sw=async(e,t=!1,n=Fo(),r=Wr(),o=process.env)=>{try{let a=op(t,n)(Bo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await nw(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[]}},iw=async(e,t=Fo(),n=Wr(),r=process.env)=>{let a=(await sw(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},cw=async(e,t=!1,n=Fo(),r=Wr(),o=process.env)=>{let a=op(t,n),s=Bo(e,t,n,r,o),i=await sw(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Ec=async()=>{for(let e of ps)if(await O(aw(e)))return e},ap={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},lw=(e,t=Wr())=>In(t,ap[e],"extensions"),sp=async(e=Wr())=>{for(let t of ps)if(await O(In(e,ap[t])))return t},dw=async e=>{let t=e??await Ec();if(!t)return{status:"unknown"};let n=await dR(t);return n?{variant:t,version:n,status:rp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var hR=3e3,mR="Claude Code-credentials",yR=["copilot-cli","CopilotCLI"],fw=e=>new Promise(t=>{try{uR("security",["find-generic-password","-s",e],{timeout:hR},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),gR=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=at(xc(),".claude");return!!(await O(at(e,".oauth_token"))||await O(at(e,".credentials.json"))||pw()==="darwin"&&await fw(mR))},wR=async()=>{let e=at(process.env.CODEX_HOME?.trim()||at(xc(),".codex"),"auth.json");if(!await O(e))return!1;try{let t=JSON.parse(await pR(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},uw=async e=>{try{return(await fR(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},ip=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of ps){let n=at(ot(t),"User","globalStorage");if(await O(at(n,"github.copilot-chat"))||await O(at(n,"github.copilot")))return!0}let e=at(xc(),".config","github-copilot");if(await O(at(e,"apps.json"))||await O(at(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await uw(at(xc(),t,"extensions")))return!0;for(let t of ps){if(await uw(lw(t)))return!0;let n=at(Bo(t,!0),"globalStorage");if(await O(at(n,"github.copilot-chat"))||await O(at(n,"github.copilot")))return!0}if(pw()==="darwin"){for(let t of yR)if(await fw(t))return!0}return!1},Tt=async()=>{let[e,t,n]=await Promise.all([gR(),wR(),ip()]);return{anthropic:e,openai:t,copilot:n}};var _e=async(e=T,t=Tt,n)=>{let r=await e();if(!r.gateway||!r.clientKey)return;let o=await t().catch(()=>{}),a=ye({origin:r.gateway,clientKey:r.clientKey,subscription:r.authMode==="subscription",placeholder:r.authMode==="placeholder",byoUpstream:r.byoUpstream,seat:o,user:r.name,team:r.team});if(!nt(r))return{target:a,toolOrigin:a.origin};if(!(!Number.isInteger(r.fallbackPort)||r.fallbackPort<1||r.fallbackPort>65535))return n&&await n(r.fallbackPort)===null?{target:a,toolOrigin:a.origin}:{target:Cn(a,r.fallbackPort),toolOrigin:`http://${ht}:${r.fallbackPort}`}};import{homedir as xR}from"node:os";import{join as Dc}from"node:path";import{chmod as IR,readFile as fs,rm as bw,copyFile as OR}from"node:fs/promises";var Kr="# >>> anyray connect >>>",Rc="# <<< anyray connect <<<",cp="# restore: ",hw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),_c=e=>{let t=new RegExp(`\\n*${hw(Kr)}[\\s\\S]*?${hw(Rc)}\\n?`,"g");return e.replace(t,"")},lp=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},Ic=(e,t)=>e.split(t).length-1,mw=e=>Ic(e,"[")-Ic(e,"]"),bR=e=>e.replace(/^['"]|['"]$/g,""),Oc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Ic(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+mw(lp(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?bR(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=lp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Ic(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+mw(l)))}return t},dp=e=>e.findIndex(t=>t.kind==="table"),up=e=>e.includes(Kr),yw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
74
|
-
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},
|
|
75
|
-
`),o=
|
|
76
|
-
`),s=
|
|
73
|
+
`,uO=(e=Cc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),ls=e=>["Auto-refresh scheduling is not wired for this OS. To keep your gateway","key from expiring mid-session, run this on a ~30-min schedule yourself","(e.g. cron / Task Scheduler), or just re-run connect when a tool 401s:",` ${[e.command,...e.args].map(n=>/\s/.test(n)?JSON.stringify(n):n).join(" ")}`],ew=e=>!e.run&&es(),pO=async(e,t)=>await oO(np(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Ac]).ok,sr=async(e={})=>{let t=e.os??ep(),n=e.invocation??Cc(),r=e.run??tp,o=e.binaryPath??rr();if(Ge(o))return{ok:!1,messages:[`Skipped auto-refresh scheduling \u2014 anyray-connect is running from a temporary path (${o}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(ew(e))return{ok:!1,messages:Po("auto-refresh scheduling")};let a=yt(e.env??(e.run?{}:process.env));if(At(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${or(a)} has no per-user service manager.`,"Claude Code re-mints its key on demand via the apiKeyHelper; other tools refresh whenever `anyray-connect` runs (add it to your postStartCommand or shell profile)."]};try{if(t==="darwin"){let s=np(),i=cO(n);if(await pO(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await Ju(ss(),{recursive:!0,mode:448}),await Ju(Fo(Qu(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await Hr(l,{force:!0}).catch(()=>{}),await gc(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await Hr(s,{force:!0}).catch(()=>{});try{await aO(l,s)}catch{await gc(s,i),await Hr(l,{force:!0}).catch(()=>{})}return r("launchctl",["bootstrap",`gui/${c}`,s]).ok||r("launchctl",["load","-w",s]).ok?{ok:!0,messages:[`Scheduled auto-refresh via launchd (${s}).`]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...ls(n)]}}if(t==="linux")return await Ju(rp(),{recursive:!0}),await gc(Qg(),lO(n)),await gc(wc(),dO()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${ps}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${wc()}).`]}:{ok:!1,messages:[`Wrote ${wc()} but \`systemctl --user enable --now\` failed.`,...ls(n)]};if(t==="win32"){let s=uO(n);return r("schtasks",["/Create","/TN",ds,"/TR",s,"/SC","MINUTE","/MO",iO,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",ds]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${ds}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...ls(n)]}}return{ok:!1,messages:ls(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...ls(n)]}}},ir=async(e={})=>{await Hr(qu(),{force:!0}).catch(()=>{});let t=e.os??ep(),n=e.run??tp,r=[];if(ew(e))return{ok:!0,messages:Po("scheduler teardown")};try{if(t==="darwin"){let o=np(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Hr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${ps}.timer`]),await Hr(wc(),{force:!0}),await Hr(Qg(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",ds,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},vc=async(e=ep(),t=tp)=>e==="win32"?t("schtasks",["/Query","/TN",ds]).ok:e==="darwin"?t("launchctl",["list",Ac]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${ps}.timer`]).ok:!1;import n1 from"node:http";import{spawn as pB}from"node:child_process";import{createHash as fB}from"node:crypto";import{homedir as hB}from"node:os";import{join as uS}from"node:path";import{readFile as mB,writeFile as pS,chmod as yB,stat as gB,unlink as tS}from"node:fs/promises";import{homedir as Rc,platform as fw}from"node:os";import{join as at}from"node:path";import{execFile as AO}from"node:child_process";import{readFile as CO,readdir as vO}from"node:fs/promises";import{homedir as fO,platform as hO}from"node:os";import{join as Sc}from"node:path";var ot=e=>{let t=fO();switch(hO()){case"darwin":return Sc(t,"Library","Application Support",e);case"win32":return Sc(process.env.APPDATA??Sc(t,"AppData","Roaming"),e);default:return Sc(t,".config",e)}};import{readFile as rw}from"node:fs/promises";import{homedir as Kr,platform as Bo}from"node:os";import{join as Rn,posix as mO,win32 as yO}from"node:path";var fs=["Code","Code - Insiders","VSCodium"],Ec="1.121.0",tw=1,gO=121,ow="1.102.0",nw=1,wO=102,bO={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},xc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},op=e=>{let t=xc(e);return t?t.major!==tw?t.major>tw:t.minor>=gO:!1},aw=e=>{let t=xc(e);return t?t.major!==nw?t.major>nw:t.minor>=wO:!1},kO=async e=>{if(Bo()!=="darwin")return;let t=Rn("/Applications",`${bO[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await rw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},sw=(e,t=Bo(),n=Kr(),r=process.env)=>{switch(t){case"darwin":return Rn(n,"Library","Application Support",e);case"win32":return Rn(r.APPDATA??Rn(n,"AppData","Roaming"),e);default:return Rn(n,".config",e)}},ap=(e,t)=>e?t==="win32"?yO.join:mO.join:Rn,Uo=(e,t=!1,n=Bo(),r=Kr(),o=process.env)=>t?ap(t,n)(r,sp[e],"data","User"):Rn(sw(e,n,r,o),"User"),iw=async(e,t=!1,n=Bo(),r=Kr(),o=process.env)=>{try{let a=ap(t,n)(Uo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await rw(a,"utf8"))?.userDataProfiles;if(!Array.isArray(i))return[];let c=i.map(l=>l).filter(l=>typeof l.name=="string"&&l.name.trim().length>0&&l.name.length<=128&&!/[\u0000-\u001f\u007f]/.test(l.name)&&typeof l.location=="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(l.location)&&l.location!=="."&&l.location!=="..").map(({name:l,location:d})=>({name:l,location:d}));return c.filter((l,d)=>c.findIndex(u=>u.location===l.location)===d)}catch{return[]}},cw=async(e,t=Bo(),n=Kr(),r=process.env)=>{let a=(await iw(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},lw=async(e,t=!1,n=Bo(),r=Kr(),o=process.env)=>{let a=ap(t,n),s=Uo(e,t,n,r,o),i=await iw(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Ic=async()=>{for(let e of fs)if(await R(sw(e)))return e},sp={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},dw=(e,t=Kr())=>Rn(t,sp[e],"extensions"),ip=async(e=Kr())=>{for(let t of fs)if(await R(Rn(e,sp[t])))return t},uw=async e=>{let t=e??await Ic();if(!t)return{status:"unknown"};let n=await kO(t);return n?{variant:t,version:n,status:op(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var SO=3e3,EO="Claude Code-credentials",xO=["copilot-cli","CopilotCLI"],hw=e=>new Promise(t=>{try{AO("security",["find-generic-password","-s",e],{timeout:SO},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),IO=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=at(Rc(),".claude");return!!(await R(at(e,".oauth_token"))||await R(at(e,".credentials.json"))||fw()==="darwin"&&await hw(EO))},RO=async()=>{let e=at(process.env.CODEX_HOME?.trim()||at(Rc(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await CO(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},pw=async e=>{try{return(await vO(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},cp=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of fs){let n=at(ot(t),"User","globalStorage");if(await R(at(n,"github.copilot-chat"))||await R(at(n,"github.copilot")))return!0}let e=at(Rc(),".config","github-copilot");if(await R(at(e,"apps.json"))||await R(at(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await pw(at(Rc(),t,"extensions")))return!0;for(let t of fs){if(await pw(dw(t)))return!0;let n=at(Uo(t,!0),"globalStorage");if(await R(at(n,"github.copilot-chat"))||await R(at(n,"github.copilot")))return!0}if(fw()==="darwin"){for(let t of xO)if(await hw(t))return!0}return!1},Dt=async()=>{let[e,t,n]=await Promise.all([IO(),RO(),cp()]);return{anthropic:e,openai:t,copilot:n}};var _e=async(e=P,t=Dt,n)=>{let r=await e();if(!r.gateway||!r.clientKey)return;let o=await t().catch(()=>{}),a=ge({origin:r.gateway,clientKey:r.clientKey,subscription:r.authMode==="subscription",placeholder:r.authMode==="placeholder",byoUpstream:r.byoUpstream,seat:o,user:r.name,team:r.team});if(!nt(r))return{target:a,toolOrigin:a.origin};if(!(!Number.isInteger(r.fallbackPort)||r.fallbackPort<1||r.fallbackPort>65535))return n&&await n(r.fallbackPort)===null?{target:a,toolOrigin:a.origin}:{target:vn(a,r.fallbackPort),toolOrigin:`http://${ht}:${r.fallbackPort}`}};import{homedir as $O}from"node:os";import{join as $c}from"node:path";import{chmod as MO,readFile as hs,rm as kw,copyFile as FO}from"node:fs/promises";var Gr="# >>> anyray connect >>>",Tc="# <<< anyray connect <<<",lp="# restore: ",mw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Pc=e=>{let t=new RegExp(`\\n*${mw(Gr)}[\\s\\S]*?${mw(Tc)}\\n?`,"g");return e.replace(t,"")},dp=e=>{let t="",n=!1,r="";for(let o=0;o<e.length;o++){let a=e[o];if(n){if(a==="\\"&&r==='"'){o++;continue}a===r&&(n=!1);continue}if(a==='"'||a==="'"){n=!0,r=a;continue}if(a==="#")break;t+=a}return t},Oc=(e,t)=>e.split(t).length-1,yw=e=>Oc(e,"[")-Oc(e,"]"),OO=e=>e.replace(/^['"]|['"]$/g,""),_c=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Oc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+yw(dp(a))),t.push({kind:"other"});continue}let s=a.trim();if(s===""||s.startsWith("#")){t.push({kind:"other"});continue}if(s.startsWith("[")){t.push({kind:"table"});continue}let i=a.indexOf("="),c=i>=0?OO(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=dp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Oc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+yw(l)))}return t},up=e=>e.findIndex(t=>t.kind==="table"),pp=e=>e.includes(Gr),gw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
74
|
+
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},fp=(e,t)=>gw(Pc(e),t),hp=e=>{let t=e.indexOf(Gr);if(t<0)return;let n=e.indexOf(Tc,t+Gr.length);if(!(n<0))return e.slice(t,n)},ww=(e,t)=>{let n=e.indexOf(Gr);if(n<0)return!1;let r=e.indexOf(Tc,n+Gr.length);return r<0?!1:gw(e.slice(n,r),t)},mp=(e,t)=>{let r=Pc(e).split(`
|
|
75
|
+
`),o=_c(r),a=up(o),s=a<0?r.length:a;for(let i=0;i<s;i++){let c=o[i];if(c.kind!=="key"||c.key!==t)continue;let l=r[i].indexOf("="),d=dp(r[i].slice(l+1)).trim();if(!/^\d[\d_]*$/.test(d))return;let u=Number(d.replaceAll("_",""));return Number.isSafeInteger(u)&&u>0?u:void 0}},Lc=(e,t,n)=>{let r=bw(e),a=Pc(e).split(`
|
|
76
|
+
`),s=_c(a),i=up(s),c=new Set(n),l=i===-1?a.length:i,d=[],u=new Map(r);for(let b=0;b<a.length;b++){let v=s[b];if(b<l&&v.kind==="key"&&c.has(v.key)){u.has(v.key)||u.set(v.key,a[b].trim());continue}d.push(a[b])}let f=_c(d),p=up(f),h=(p===-1?d:d.slice(0,p)).join(`
|
|
77
77
|
`),m=p===-1?"":d.slice(p).join(`
|
|
78
|
-
`),w=[...u.entries()].sort(([b],[v])=>b.localeCompare(v)).map(([,b])=>`${
|
|
78
|
+
`),w=[...u.entries()].sort(([b],[v])=>b.localeCompare(v)).map(([,b])=>`${lp}${b}`),g=[Gr,...w,...t,Tc].join(`
|
|
79
79
|
`);return[h.replace(/\s*$/,""),g,m.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
|
|
80
80
|
|
|
81
81
|
`).replace(/\s*$/,"")+`
|
|
82
|
-
`},
|
|
83
|
-
`)){let o=r.trim();if(!o.startsWith(
|
|
82
|
+
`},bw=e=>{let t=new Map,n=hp(e);if(n===void 0)return t;for(let r of n.split(`
|
|
83
|
+
`)){let o=r.trim();if(!o.startsWith(lp))continue;let a=o.slice(lp.length).trim(),[s]=_c([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Dc=e=>{if(!pp(e))return null;let t=[...bw(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Pc(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
|
|
84
84
|
`),n].filter(a=>a.length>0).join(`
|
|
85
85
|
|
|
86
86
|
`);return o.length>0?o+`
|
|
87
|
-
`:""};import{randomUUID as
|
|
87
|
+
`:""};import{randomUUID as _O}from"node:crypto";import{chmod as TO,mkdir as PO,rm as LO,writeFile as DO}from"node:fs/promises";import{dirname as NO}from"node:path";var he=async(e,t)=>{await PO(NO(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${_O()}`;try{await DO(n,t,{flag:"wx",mode:384}),await fe(n,e),await TO(e,384)}finally{await LO(n,{force:!0}).catch(()=>{})}};var BO="codex",UO="Codex app / CLI / IDE",HO="https://chatgpt.com/backend-api/codex",WO="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",KO="x-anyray-client-context-window",GO="x-anyray-client-auto-compact-limit",Mc=()=>process.env.CODEX_HOME?.trim()||$c($O(),".codex"),jr=()=>$c(Mc(),"config.toml"),Nc=()=>`${jr()}.anyray-bak`,yp=()=>$c(Mc(),"hooks.json"),On=()=>$c(Mc(),"anyray.config.toml"),Aw=e=>To(e,"PostToolUse",mg),Cw=(e,t=!1)=>le({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||BO,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||UO}),st=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,gp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,ms=(e,t={})=>{let n=Cw(e,t.ignoreEnv),r=J(e,"openai"),o=t.auth==="command"&&!r,a=r?"openai":t.ignoreEnv?void 0:process.env.ANYRAY_CODEX_PROVIDER?.trim(),s=t.ignoreEnv?void 0:gp(),i=e.clientKey&&!e.viaLocalProxy,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${st(HO)}`,`"x-anyray-forward-headers" = ${st(WO)}`,...i?[`"x-anyray-api-key" = ${st(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${st(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${st(n)}`),a&&c.push(`"x-anyray-provider" = ${st(a)}`),t.modelContextWindow&&c.push(`"${KO}" = ${st(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${GO}" = ${st(String(t.modelAutoCompactTokenLimit))}`),["# Anyray always-on routing \u2014 plain `codex` routes through the gateway.","# Managed by anyray-connect (this block is owned by the tool).",'model_provider = "anyray"',...s?[`model = ${st(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${st(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${st(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>st(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${st(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(st).join(", ")}]`]:[]]},jO=()=>gp()?["model_provider","model"]:["model_provider"],vw={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=Mc(),t=await R(e);return{installed:t,detail:t?jr():`no ${e} directory`}},async apply(e,t){let n=jr(),r=yp(),o=Cw(e),a=J(e,"openai"),s=gp(),i=ce(),c={},l=await R(r);try{l&&(c=await M(r))}catch(v){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${v instanceof Error?v.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run Connect so the retired Anyray PostToolUse entry can be removed safely.`]}}let d=Aw(c),u=await R(n),f=u?await hs(n,"utf-8"):"";if(fp(f,"model_providers.anyray"))return{status:"manual",messages:[`Refused to replace the existing model provider in ${n}: model_providers.anyray is not owned by Anyray Connect. Rename that provider or route it manually; the file was left unchanged.`]};let p=fp(f,"mcp_servers.anyray"),h=mp(f,"model_context_window"),m=mp(f,"model_auto_compact_token_limit"),w=[`${n} \u2190 always-on default route (model_provider = anyray)`,`Base URL: ${e.openaiBaseUrl}/responses (wire_api = responses)`,"Plain `codex` now routes through the gateway \u2014 no --profile needed.","Codex app, CLI, and IDE extension share this config.toml route.",a?"Subscription mode: Codex keeps your ChatGPT sign-in; its OAuth token passes through the gateway to the ChatGPT backend (never stored). Requires being signed in with ChatGPT, not an API key.":`Auth: ${e.clientKey?"personal gateway key (written to the config, not shown here)":"placeholder token (gateway swaps in the server-held key)"}`,s?`Model: ${s} (pinned via ANYRAY_CODEX_MODEL)`:"Model: inherits your existing default. If the desktop or IDE model picker ignores custom providers, re-run with ANYRAY_CODEX_MODEL pinned.",m?`Context budget: follows model_auto_compact_token_limit=${m}.`:h?`Context budget: follows model_context_window=${h}.`:"Context budget: follows the request model; unknown models use the safe fallback.",`Attribution: ${o??"(none \u2014 pass --user)"}`,"Codex cloud/web tasks run on OpenAI infrastructure and cannot route through a local gateway."];if(t.dryRun)return w.push(d?`Would remove the retired Anyray Codex PostToolUse hook from ${r}.`:"Codex source-side tool-output trimming remains unavailable: its only replacement signal rejects the already-completed tool promise and is unsafe for side-effecting tools."),{status:"configured",messages:w};let g=[];d?(await Z(r,c,{backup:!1}),await re(r),g.push(r),w.push(`Removed the retired Anyray Codex PostToolUse hook from ${r}; Codex does not expose a safe pre-transcript replacement seam for side-effecting tools.`)):w.push("Codex source-side tool-output trimming is not installed because its blocking PostToolUse result can turn a completed side effect into an apparent failure."),u&&!await R(Nc())&&(await FO(n,Nc()),await MO(Nc(),384),w.push(`Backed up your original config to ${Nc()}.`));let y=i&&!p?je("profile"):void 0;w.push(p?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:y?"Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.":`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable retrieval.`);let b=Lc(f,ms(e,{mcpServer:y,modelContextWindow:h,modelAutoCompactTokenLimit:m}),jO());return await he(n,b),g.push(n),await R(On())&&(await kw(On(),{force:!0}),g.push(On()),w.push(`Removed the old opt-in profile ${On()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:g}},async pointsAt(e){let t=jr();if(!await R(t))return!1;try{let n=await hs(t,"utf-8"),r=`base_url = ${st(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){let e=jr();if(!await R(e))return{registered:!1,command:null};try{let t=await hs(e,"utf-8");if(!ww(t,"mcp_servers.anyray"))return{registered:!1,command:null};let n=t.match(/\[mcp_servers\.anyray\]\r?\ncommand = ("(?:[^"\\]|\\.)*")/),r=null;if(n)try{r=JSON.parse(n[1])}catch{r=null}return{registered:!0,command:r}}catch{return{registered:!1,command:null}}},async inferenceAuthLanes(){try{let e=await hs(jr(),"utf-8"),t=hp(e);if(!t||!t.includes("[model_providers.anyray]"))return["unknown"];if(/^requires_openai_auth = true$/m.test(t)||t.includes('"x-anyray-auth-mode" = "passthrough"'))return["subscription"];if(t.includes('"Authorization" = "Bearer ')||t.includes("[model_providers.anyray.auth]"))return["api_key"]}catch{}return["unknown"]},async revert(e){let t=jr(),n=await R(t),r=await R(On()),o=await R(yp());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=yp(),c;try{c=await M(i)}catch(l){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${i} (${l instanceof Error?l.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run --revert.`]}}Aw(c)&&(e.dryRun||(await Z(i,c,{backup:!1}),await re(i)),s.push(i),a.push(e.dryRun?`would remove the retired Anyray Codex PostToolUse hook from ${i}`:`removed the retired Anyray Codex PostToolUse hook from ${i}`))}if(n){let i=Dc(await hs(t,"utf-8"));i!==null&&(e.dryRun||await he(t,i),s.push(t),a.push(e.dryRun?`would remove the Anyray default route from ${t}`:`removed the Anyray default route from ${t}`))}return r&&(e.dryRun||await kw(On(),{force:!0}),s.push(On()),a.push(e.dryRun?`would remove the old opt-in profile ${On()}`:`removed the old opt-in profile ${On()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await re(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as zO}from"node:os";import{join as qO}from"node:path";import{readFile as Iw,rm as bp}from"node:fs/promises";import{readFile as VO,writeFile as Sw,access as YO}from"node:fs/promises";import{homedir as ZO}from"node:os";import{join as wp}from"node:path";var XO="# >>> anyray connect >>>",JO="# <<< anyray connect <<<",ys=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:XO,end:JO},Ct=()=>{let e=ZO(),t=process.env.SHELL||"";return t.includes("zsh")?wp(e,".zshrc"):t.includes("bash")?wp(e,".bashrc"):wp(e,".profile")},Fc=async e=>{try{return await YO(e),await VO(e,"utf-8")}catch{return""}},Ew=(e,t)=>{let{begin:n,end:r}=ys(t),o=e.indexOf(n);if(o===-1)return e;let a=e.indexOf(r,o+n.length);if(a===-1)return e;let s=o;for(;s>0&&e[s-1]===`
|
|
88
88
|
`;)s-=1;let i=a+r.length;return e[i]===`
|
|
89
|
-
`&&(i+=1),e.slice(0,s)+e.slice(i)},
|
|
89
|
+
`&&(i+=1),e.slice(0,s)+e.slice(i)},Bc=async(e,t,n)=>{let r=await Fc(e),{begin:o,end:a}=ys(n),s=Ew(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
|
|
90
90
|
`),c=s?`${s}
|
|
91
91
|
|
|
92
92
|
${i}
|
|
93
93
|
`:`${i}
|
|
94
|
-
`;return await
|
|
95
|
-
`).filter(c=>c.trim().length>0)},
|
|
96
|
-
`),!0):!1};var
|
|
97
|
-
`)):w&&y&&await
|
|
94
|
+
`;return await Sw(e,c),e},Uc=async(e,t)=>{let n=await Fc(e),{begin:r,end:o}=ys(t),a=n.indexOf(r);if(a===-1)return;let s=a+r.length,i=n.indexOf(o,s);if(i!==-1)return n.slice(s,i).split(`
|
|
95
|
+
`).filter(c=>c.trim().length>0)},xw=async(e,t)=>(await Fc(e)).includes(ys(t).begin),gs=async(e,t)=>{let n=await Fc(e);return n.includes(ys(t).begin)?(await Sw(e,Ew(n,t).replace(/\s*$/,"")+`
|
|
96
|
+
`),!0):!1};var Nt=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var Se=e=>`'${e.replace(/'/g,"'\\''")}'`,QO=e=>{let t=Se(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},Rw=(e,t,n,r)=>{let a=e.viaLocalProxy===!0?e.placeholderKey:t;return[`export OPENAI_BASE_URL=${Se(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${Se(a)}`],`export ANTHROPIC_BASE_URL=${Se(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${Se(a)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]]},e_=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],t_=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],kp=()=>qO(zO(),".anyray","shell-env.sh"),_w="# Managed by anyray-connect. Do not source this file anywhere else.",Ow=e=>e.split(/\r?\n/,1)[0]===_w,Ap=e=>t_.some(t=>e.startsWith(`export ${t}=`)),Tw=(e,t=process.env)=>Cp([e],t),Cp=(e,t=process.env)=>e.some(r=>t.ANTHROPIC_BASE_URL===r.anthropicBaseUrl||t.OPENAI_BASE_URL===r.openaiBaseUrl)?e_.filter(r=>(t[r]??"")!==""):[],Pw={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=Ct();return{installed:!0,detail:await R(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await Uc(Ct());return e?e.some(n=>Ap(n)||n.includes(kp()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=Ct(),r=J(e,"openai"),o=J(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=Rw(e,s,r,o),c=i.filter(Ap),l=i.filter(b=>!Ap(b)),d=kp(),u=fg(),f=[QO(u),...l,...c.length>0?[`[ -r ${Se(d)} ] && . ${Se(d)}`]:[]],p=e.clientKey?Rw(e,Nt(e.clientKey),r,o):i,h=r&&o?"either family":r?"OpenAI":"Anthropic",m=[`${n} \u2190 managed Anyray block`,` ${u} added to PATH (so \`anyray-connect\` runs from a new shell)`,...p.map(b=>` ${b}`),...c.length>0?[`${d} \u2190 owner-only credentials (mode 0600)`]:[],`Run \`source ${n}\` or open a new terminal to apply.`,...a?[`No auth token exported for ${h} \u2014 your seat-based tool keeps`,"its own sign-in (a placeholder here would override it). Raw SDK/script","calls on a seat need your own key."]:["Note: standard SDK env vars carry no per-user header, so attribution","for these falls back to the gateway default."]],w=await R(d),g=w?await Iw(d,"utf8"):void 0,y=g===void 0||Ow(g);if(c.length>0&&!y)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(y||m.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:m};try{c.length>0?await he(d,[_w,...c,""].join(`
|
|
97
|
+
`)):w&&y&&await bp(d,{force:!0}),await Bc(n,f)}catch(b){try{g!==void 0&&y?await he(d,g):y&&await bp(d,{force:!0})}catch{throw new Error("shell environment update failed and credential rollback could not be completed")}throw b}return{status:"configured",messages:m,changedFiles:[n,...c.length>0||w&&y?[d]:[]]}},async revert(e){let t=Ct(),n=kp(),r=await R(n),o=r?Ow(await Iw(n,"utf8")):!1;if(e.dryRun)return{status:"reverted",messages:[`would remove the Anyray block from ${t}`,...o?[`would remove owner-only credentials from ${n}`]:r?[`would preserve user-managed ${n}`]:[]]};let a=await gs(t);o&&await bp(n,{force:!0});let s=[...a?[t]:[],...o?[n]:[]];return{status:s.length>0?"reverted":"not-found",messages:[a?`removed the Anyray block from ${t}`:`no Anyray block found in ${t}`,...o?[`removed owner-only credentials from ${n}`]:r?[`preserved user-managed ${n}`]:[]],changedFiles:s.length>0?s:void 0}}};import{spawnSync as $_}from"node:child_process";import{closeSync as M_,copyFileSync as F_,existsSync as Ee,mkdirSync as B_,openSync as U_,readFileSync as db,readSync as H_,renameSync as W_,rmSync as hn,writeFileSync as Mp}from"node:fs";import{homedir as ub,platform as K_}from"node:os";import{dirname as pb,join as Go,resolve as G_}from"node:path";import{isIP as _p}from"node:net";import{execFileSync as Kc}from"node:child_process";import{mkdtempSync as n_,rmSync as r_,writeFileSync as o_}from"node:fs";import{createRequire as a_}from"node:module";import{tmpdir as s_}from"node:os";import{join as Lw}from"node:path";var ws=class extends Error{},bs=e=>e instanceof ws?`: ${e.message}`:"",Dw=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new ws("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new ws(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},Nw=()=>{try{return Kc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Sp=64*1024*1024,i_=Sp*2+64,Wc=e=>`'${e.replace(/'/g,"''")}'`,c_=(e,t)=>Kc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:i_,stdio:["ignore","pipe","pipe"]}),l_=(e,t)=>Kc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Sp,stdio:["pipe","pipe","pipe"]}),$w=(e,t,n=c_)=>{let r=Wc(t),o=`SELECT 'present:' || COALESCE(hex(CAST(value AS BLOB)), '') FROM ItemTable WHERE key=${r} UNION ALL SELECT 'absent:' WHERE NOT EXISTS (SELECT 1 FROM ItemTable WHERE key=${r});`,a=n(e,o),s=a.endsWith(`\r
|
|
98
98
|
`)?a.slice(0,-2):a.endsWith(`
|
|
99
|
-
`)?a.slice(0,-1):a;if(s==="absent:")return;if(!s.startsWith("present:"))throw new Error("state DB returned an unexpected item encoding");let i=s.slice(8);if(i.length%2!==0||!/^[0-9a-f]*$/i.test(i))throw new Error("state DB returned an unexpected item encoding");return Buffer.from(i,"hex").toString("utf-8")}
|
|
99
|
+
`)?a.slice(0,-1):a;if(s==="absent:")return;if(!s.startsWith("present:"))throw new Error("state DB returned an unexpected item encoding");let i=s.slice(8);if(i.length%2!==0||!/^[0-9a-f]*$/i.test(i))throw new Error("state DB returned an unexpected item encoding");return Buffer.from(i,"hex").toString("utf-8")},Mw=(e,t=l_)=>{let r=t(e,`.bail on
|
|
100
100
|
.timeout 5000
|
|
101
101
|
PRAGMA wal_checkpoint(TRUNCATE);
|
|
102
|
-
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");
|
|
103
|
-
`);
|
|
104
|
-
`,{mode:384}),await fe(n,t)},
|
|
105
|
-
`),
|
|
106
|
-
`,{encoding:"utf-8",flag:"wx",mode:384})},
|
|
107
|
-
`,{encoding:"utf-8",flag:"wx",mode:384});try{T_(n,e)}catch(r){throw fn(n,{force:!0}),r}},z_=(e,t)=>{let n=Uo(e);mb(e,{...n,lastWritten:t})},te=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ib=e=>te(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Uo=e=>{let t=lb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(te(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||te(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(!te(n)||n.version!==1||!te(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Xe],o=n.rows[ct];if(!ib(r)||!ib(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}},cb=e=>{let t=Buffer.alloc(16),n=__(e,"r");try{return P_(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{I_(n)}},q_=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return te(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var yb=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(".")&&Rp(t)===0||t==="0.0.0.0")return!0;if(Rp(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(Rp(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 yb(`${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},Tp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!yb(t.hostname)}catch{return!1}},Q_=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},eP=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Ye(e.origin)}/v1${Pp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Pp}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),Ho=(e,t=!1)=>[...t?[`Cursor's server-side BYOK lane bypasses the local key-refresh proxy and points directly at ${e.openaiBaseUrl}.`]:[],"Route capability: only custom-model requests Cursor actually sends to its OpenAI BYOK endpoint. Cursor's Agent wire behavior varies by release; native Team models, Tab, indexing, and other first-party traffic stay on Cursor-hosted services.","Billing: this lane bills as an Anyray subscription seat \u2014 each distinct attributed developer with usage in a month is one seat. Attribution rides your per-user ark_ key (Cursor sends no metadata header), so enroll each developer with their own key."],gb=()=>{let e=Vr();if(!Ee(e))return"clear";let t=bs();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Xe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return te(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},tP=(e,t)=>{if(!Tp(e))return{routed:!1,problem:"gateway-not-public-https"};let n=Vr();if(!Ee(n))return{routed:!1,problem:"state-db-missing"};let r=bs();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Xe),a=r.readItem(n,ct)}catch{return{routed:!1,problem:"state-db-unreadable"}}if(o===void 0)return{routed:!1,problem:"settings-missing"};let s;try{s=JSON.parse(o)}catch{return{routed:!1,problem:"settings-malformed"}}if(!te(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ye(e)}/v1${Pp}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ie(a)||!Ie(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},nP=(e,t=[])=>({command:Rt(e,[...t,zc])}),Fp=(e,t,n)=>{if(!te(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Rt(t,[...n,zc])||r===Rt(t,n)||r.endsWith(` ${zc}`)&&r.includes(` ${t} `)},rP=(e,t)=>te(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),wb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Fp(a,t,n)){r=!0;continue}if(!te(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!rP(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}},Bp=(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},bb=(e,t,n,r,o)=>te(e.hooks)&&Bp(e.hooks,t).some(a=>te(a)&&a.matcher===o&&Fp(a,n,r)),oP=(e,t,n,r,o)=>te(e.hooks)&&Bp(e.hooks,t).some(a=>te(a)&&a.matcher===o&&Fp(a,n,r)&&rc(a.command,n,[...r,zc])),kb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!te(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=te(e.hooks)?{...e.hooks}:{},{entries:s}=wb(Bp(a,t),n,r);return s.push({...nP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},aP=(e,t,n,r=[])=>{if(!te(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=wb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},sP=async()=>{let e=Jt();if(!ce()){let t=await Cb();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${Re()}). 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 Yr)t=kb(t,n.event,n.flag,n.trailingArgs,n.matcher);return await Z(e,t),{changedFiles:[e],messages:[`Installed Cursor global hooks in ${e} (postToolUse trims oversized MCP tool outputs; preToolUse trims recognized Shell command output and redirects bulky built-in Read/Grep to Anyray's context tools; beforeSubmitPrompt beacons oversized pasted-data prompts). Cursor hook cache/tee persistence is disabled; gateway request logs and savings/spend rows remain metadata-only, while trace decision content follows the deployment's ANYRAY_CONTENT_MODE.`],complete:!0}}catch{return{changedFiles:[],messages:[`Could not install Cursor hooks in ${e}. Chat can still route through Anyray, but hook-based trimming/beacons are unavailable until this is fixed.`],complete:!1}}},Jc=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,hb]}},Lp=e=>te(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===Jc().command&&e.args.length===Jc().args.length&&e.args.every((t,n)=>t===Jc().args[n]),iP=e=>{if(!te(e)||Object.keys(e).some(o=>o!=="command"&&o!=="args")||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(o=>typeof o=="string")||Ke(e.command))return!1;let t=e.args;if(t.at(-2)!==Qn||t.at(-1)!=="profile")return!1;let n=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(n))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(n)||t.length!==3)return!1;let r=t[0].replaceAll("\\","/");return!Ke(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},qc=e=>te(e)&&Array.isArray(e.args)&&e.args.at(-1)===hb||iP(e),cP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,lP=async()=>{if(!ce())return Ab();let e=zt();try{let t=await F(e);if(t.mcpServers!==void 0&&!te(t.mcpServers))throw new Error("mcpServers is not an object");let n=te(t.mcpServers)?{...t.mcpServers}:{},r=n[Dt];return r!==void 0&&!qc(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Dt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Dt]=Jc(),await Z(e,{...t,mcpServers:n}),{changedFiles:[e],messages:[`Registered the Anyray retrieval MCP server (anyray_retrieve) in ${e} for explicit recovery of stashed context.`],complete:!0})}catch{return{changedFiles:[],messages:[`Could not register the Anyray MCP server in ${e}; retrieval via anyray_retrieve is unavailable until this is fixed.`],complete:!1}}},Ab=async()=>{let e=zt();if(!await O(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e);if(!te(t.mcpServers)||!(Dt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!qc(t.mcpServers[Dt]))return{changedFiles:[],messages:[`Preserved the foreign ${Dt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Dt];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await Z(e,r,{backup:!1}),{changedFiles:[e],messages:["Removed the Anyray retrieval MCP server (anyray_retrieve)."],complete:!0}}catch{return{changedFiles:[],messages:[`Could not remove the Anyray MCP server from ${e}; the registration was left in place.`],complete:!1}}},Cb=async()=>{let e=Jt();if(!await O(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e),n=t;for(let r of Yr)n=aP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await Z(e,n,{backup:!1}),{changedFiles:[e],messages:["Removed Cursor global Anyray hooks."],complete:!0})}catch{return{changedFiles:[],messages:[`Could not remove Cursor hooks from ${e}; the hooks were left in place.`],complete:!1}}},dP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=F_(e);if(!n)return t;let r=Ko(n,vs),o=M_();try{if(Ee(r)){let a=lb(r,"utf8");if(a===o)return t;if(!a.includes(fb))return{...t,messages:[`Left ${vs} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Mp}"`]}}return R_(ub(r),{recursive:!0}),$p(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${vs} 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 ${vs} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},vb=async()=>{let e=await sP(),t=await lP(),n=await dP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Dp=async()=>{let e=await Cb(),t=await Ab();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Sb=async()=>{if(!ce()){let e=await Dp();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${Re()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await F(Jt());for(let r of Yr)e=kb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await F(zt());if(t.mcpServers!==void 0&&!te(t.mcpServers))throw new Error("mcpServers is not an object");let n=te(t.mcpServers)?t.mcpServers[Dt]:void 0;return n!==void 0&&!qc(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${zt()} already contains a foreign ${Dt} 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 ${Jt()} and ${zt()}, then re-run Connect.`],complete:!1}}},uP=async()=>{if(!ce())return!1;try{let e=await F(Jt());if(!te(e.hooks)||!Yr.every(r=>bb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await F(zt()),n=te(t.mcpServers)?t.mcpServers[Dt]:void 0;return Lp(n)}catch{return!1}},Eb=["openAIBaseUrl","useOpenAIKey"],Es=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!te(t))throw new Error("Cursor application-user settings are not an object");return t},pP=(e,t,n)=>{let r=Es(e),o=Es(t??void 0),a=n===void 0?void 0:Es(n),s={...r},i=[];for(let c of Eb){let l=Object.prototype.hasOwnProperty.call(r,c),d=a!==void 0&&Object.prototype.hasOwnProperty.call(a,c);if(a===void 0||l!==d||l&&!Object.is(r[c],a[c])){i.push(c);continue}Object.prototype.hasOwnProperty.call(o,c)?s[c]=o[c]:delete s[c]}return{mutation:Object.keys(s).length===0?{key:Xe}:{key:Xe,value:JSON.stringify(s)},conflicts:i}},_p=(e,t)=>{let n=Es(e),r=Es(t??void 0),o={...n};for(let a of Eb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Xe}:{key:Xe,value:JSON.stringify(o)}},Yc=e=>typeof e=="string"&&e.startsWith("ark_"),Zc=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);te(o)&&(n=o)}catch{}let r=Yc(t)||n!==null&&(Yc(n.useOpenAIKey)||Yc(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,Yc(o.openAIKey)&&delete o.openAIKey,{applicationUser:Object.keys(o).length===0?null:JSON.stringify(o),openAIKey:null}}if(Object.prototype.hasOwnProperty.call(n,"useOpenAIKey")&&typeof n.useOpenAIKey!="boolean"){let o={...n};return delete o.useOpenAIKey,{applicationUser:Object.keys(o).length===0?null:JSON.stringify(o),openAIKey:t}}return{applicationUser:e,openAIKey:t}},it=(e,t)=>{if(!e.clientKey)return[...t?[t]:[],"Enrollment required: Cursor needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; do not save a placeholder Custom Endpoint.",...Ho(e)];let n=le(e.metadata);return[...t?[t]:[],"Configure Cursor by hand: Cursor \u2192 Settings \u2192 Models \u2192 OpenAI API Key:",` \u2022 Override OpenAI Base URL: ${e.openaiBaseUrl}`," \u2022 API key: run `anyray-connect print-key` and paste the returned personal gateway key (the key is not shown here).",n?` \u2022 Cursor has no custom-header field, so attribution rides your per-user key, not ${n}.`:" \u2022 (No attribution metadata resolved; set --user, or use --enroll for a per-user key.)","This is Cursor's OpenAI-BYOK lane: usage counts toward your Anyray subscription seat, but the upstream still needs a provider API key. It does not consume the native Cursor Team entitlement; exact custom-model Agent compatibility varies by Cursor release.",...Ho(e)]},Np=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ce())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await As("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]}},fP=async(e,t)=>{if(!Ie(e.clientKey))return{status:"manual",messages:["Cursor native subscription mode was not changed: a valid personal ark_ gateway key is required for Anyray hooks and MCP retrieval."]};if(!t.dryRun&&!t.preservePendingOp)try{await cr("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 Sb();if(!n.complete)return{status:"manual",messages:n.messages};let r=Ee(Ss())||Ee(Wo());if(r&&Xc())return Np("native",t,{status:"manual",messages:["Cursor is running \u2014 fully quit it and re-run so Connect can restore the journaled BYOK override before enabling native subscription mode."]},["No native Claude/Opus request will be redirected: the queued operation restores Cursor\u2019s prior settings, then installs only Anyray hooks/MCP."]);if(!r){let c=gb();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Ee(Wo())?Wo():Ss()}, 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 ${Jt()}, and register the Anyray retrieval MCP server in ${zt()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await xs.revert({dryRun:!1,preservePendingOp:!0}),o.status!=="reverted"))return{...o,messages:[...o.messages,"Cursor native subscription mode was not reported active because the prior BYOK route could not be restored safely."]};let a=await vb(),s=[];if(!t.preservePendingOp)try{await cr("cursor")}catch{s.push("Could not clear Cursor's stale queue marker.")}return{status:a.complete&&s.length===0?"configured":"manual",changedFiles:[...new Set([...o?.changedFiles??[],...a.changedFiles])],messages:[...o?.messages??[],"Kept Cursor's native Team sign-in and Claude/Opus model route; no Anyray OpenAI override or model credential was written.",...a.messages,...s,"Claude/Opus inference remains Cursor-hosted and will not produce gateway inference traces. Anyray records content-free hook savings only when a supported oversized Shell/MCP result is actually reduced.",`Make it seamless org-wide: paste this into Cursor's dashboard Team Rules and mark it Required, so every member's agent uses Anyray's tools without being asked -- "${Mp}" (connect already writes ${vs} 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."]}},xs={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>Xc(),quitTarget:N_,needsTarget:e=>e!=="revert",async complete(e,t,n){return $_(e)?e!=="revert"&&t?xs.apply(t,n):xs.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=pb(),t=Ee(e);return{installed:t,detail:t?Vr():"Cursor user dir not found"}},async watchPaths(){return[Jt(),zt()]},async mcpStatus(){let e=zt();if(!await O(e))return{registered:!1,command:null};try{let t=await F(e),n=te(t.mcpServers)?t.mcpServers[Dt]:void 0;return Lp(n)?{registered:!0,command:cP(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=Jt();if(!await O(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!te(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Yr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Yr.every(c=>bb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Yr.every(c=>oP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=zt();if(!await O(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!te(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Dt];r=i===void 0?"missing":qc(i)?"owned":"foreign",r==="owned"&&(o=Lp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await $r()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await T();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(B_(e))return fP(e,t);let n=eP(e),r=Q_(e.openaiBaseUrl),o=Vr(),a=Ss(),s=Wo();if(!Ie(e.clientKey))return{status:"manual",messages:it(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let i={changedFiles:[],messages:[],complete:!0},c=y=>{let b=y.status==="configured"&&!i.complete;return{...y,status:b?"manual":y.status,changedFiles:[...y.changedFiles??[],...i.changedFiles],messages:[...y.messages,...i.messages,...b?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Tp(n.openaiBaseUrl))return c({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach loopback/LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect. No proxy, DNS, certificate, or interception workaround is installed.",...Ho(n)]});let l=await Sb();if(!l.complete)return{status:"manual",messages:l.messages};let d=bs();if(!d)return c({status:"manual",messages:it(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Ee(o))return c({status:"manual",messages:it(n,`No Cursor state DB at ${o} (open Cursor once first).`)});let u=null,f;if(Ee(s)){if(Ee(a))return c({status:"manual",messages:it(n,`Both a legacy Cursor Anyray backup (${s}) and a current value backup (${a}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{cb(s)?u="sqlite":(Uo(s),u="value")}catch{u=null}if(!u)return c({status:"manual",messages:it(n,`Legacy Cursor Anyray backup at ${s} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(Ee(a))try{p=Uo(a)}catch{return c({status:"manual",messages:it(n,`Existing Cursor backup at ${a} is invalid \u2014 refusing to write or replace recovery data.`)})}if(Xc())return c(await Np("apply",t,{status:"manual",messages:it(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Ho(n,r),...u?[`The legacy Anyray backup at ${s} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...u?[`Would migrate the legacy Anyray backup at ${s}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${o}, ${Ee(a)?`retain the original value backup at ${a}`:`create a mode-0600 value backup at ${a}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${Jt()}, and register the Anyray retrieval MCP server in ${zt()}.`,...Ho(n,r)]};if(u){try{d.checkpointWal(o)}catch(b){return c({status:"manual",messages:it(n,`Couldn't checkpoint Cursor's state DB at ${o} while migrating the legacy Anyray backup at ${s}${ws(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=Zc(d.readItem(s,Xe)??null,d.readItem(s,ct)??null);else{let b=Uo(s);y=Zc(b.applicationUser,b.openAIKey)}}catch{return c({status:"manual",messages:it(n,`Couldn't read the legacy Anyray backup at ${s} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{d.mutateRows(o,[_p(d.readItem(o,Xe),y.applicationUser),y.openAIKey===null?{key:ct}:{key:ct,value:y.openAIKey}])}catch{return c({status:"manual",messages:it(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${s} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{fn(s,{force:!0}),fn(`${s}-wal`,{force:!0}),fn(`${s}-shm`,{force:!0}),f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held and removed it.`}catch{f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{d.checkpointWal(o)}catch(y){return c({status:"manual",messages:it(n,`Couldn't checkpoint Cursor's state DB at ${o}${ws(y)} \u2014 refusing to write; set it by hand:`)})}let h;try{h=d.readItem(o,Xe)}catch{return c({status:"manual",messages:it(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=q_(h,n);if(!m)return c({status:"manual",messages:it(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let w={applicationUser:m.value,openAIKey:e.clientKey};if(Ee(a))try{z_(a,w)}catch{return c({status:"manual",messages:it(n,`Couldn't update three-way ownership in the protected Cursor backup at ${a} \u2014 refusing to write; set it by hand:`)})}else try{J_(d,a,o,w)}catch{return c({status:"manual",messages:it(n,`Couldn't create the protected Cursor value backup at ${a} \u2014 refusing to write; set it by hand:`)})}try{d.mutateRows(o,[{key:Xe,value:m.value},{key:ct,value:e.clientKey}])}catch{let y=!0;if(p)try{mb(a,p)}catch{y=!1}return c({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${a}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${a} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}i=await vb();let g=[];if(!t.preservePendingOp)try{await cr("cursor")}catch{g.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return c({status:"configured",changedFiles:[o],messages:[...f?[f]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${a}).`,"Stored the API key in Cursor's credential row (not shown here).",...g,...Ho(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await T().catch(()=>{}),n=e;if(!Tp(n)){let o=t&&nt(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&Ye(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Ee(Ss())||Ee(Wo())||gb()!=="clear"?!1:uP():tP(n,r).routed},async revert(e){let t=Vr(),n=Ss(),r=Wo(),o=Ee(n),a=Ee(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${Jt()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${Jt()} and unregister its owned retrieval MCP server.`]};if((o||a)&&Xc()){if(e.fullRevert){let h=await Dp(),m=!0;try{await cr("cursor")}catch{m=!1}return{status:"manual",changedFiles:h.changedFiles,messages:[...h.messages,...m?[]:["Could not clear Cursor's stale queue marker."],`Cursor is running, so its saved settings in ${a?r:n} were left in place and nothing was queued. Quit Cursor and re-run --revert to restore them.`]}}return Np("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=bs(),i=!1,c=!1,l,d=[];if(a)try{if(cb(r))if(Ee(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let h=Zc(s.readItem(r,Xe)??null,s.readItem(r,ct)??null);s.mutateRows(t,[_p(s.readItem(t,Xe),h.applicationUser),h.openAIKey===null?{key:ct}:{key:ct,value:h.openAIKey}]),c=!0}else i=!0,O_(r,t),fn(`${t}-wal`,{force:!0}),fn(`${t}-shm`,{force:!0});else{let h=Uo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ee(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let m=Zc(h.applicationUser,h.openAIKey);s.mutateRows(t,[_p(s.readItem(t,Xe),m.applicationUser),m.openAIKey===null?{key:ct}:{key:ct,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${ws(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Uo(n)}catch{return{status:"manual",messages:[`Couldn't read a supported Cursor value backup from ${n}; the backup was retained.`]}}if(l){if(!l.lastWritten)return{status:"manual",messages:[`The Cursor backup at ${n} predates three-way ownership, so Connect cannot prove which current values are still its own. The backup was retained and no hook or MCP cleanup was attempted.`]};if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ee(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let h=pP(s.readItem(t,Xe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,ct);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:ct}:{key:ct,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${ws(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{fn(r,{force:!0}),fn(`${r}-wal`,{force:!0}),fn(`${r}-shm`,{force:!0}),fn(n,{force:!0})}catch{f=!1,u.push("Cursor values were restored, but a recovery sidecar could not be removed; retain it until a later revert can finish cleanup.")}if(!e.preservePendingOp)try{await cr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await Dp();return f=f&&p.complete,{status:f?"reverted":"manual",changedFiles:[...o||a?[t]:[],...p.changedFiles],messages:[i?"Restored Cursor's state DB from the legacy Anyray backup.":c?"Restored Cursor's managed settings fields and credential from the legacy Anyray backup while preserving current unrelated settings and rows.":l?"Restored Cursor's managed settings fields and credential from the Anyray backup while preserving current unrelated settings.":"No Cursor row backup was present; only owned hook and MCP integrations were considered for cleanup.",...u,...d.length>0?[`Preserved Cursor values changed after Connect configured them: ${[...new Set(d)].join(", ")}.`]:[],...p.messages,"Restart Cursor."]}}};import{chmod as jP,mkdir as VP,readFile as Jb,rm as YP,writeFile as ZP}from"node:fs/promises";import{randomUUID as XP}from"node:crypto";import{dirname as JP,join as zb}from"node:path";var hP=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
|
|
108
|
-
`;)r+=1;r-=1;continue}if(o==="/"&&e[r+1]==="*"){let a=e.indexOf("*/",r+2);r=a===-1?e.length:a+1,t+=" ";continue}t+=o}return t},mP=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o===","){let a=r+1;for(;a<e.length&&/\s/.test(e[a]);)a+=1;if(e[a]==="}"||e[a]==="]")continue}t+=o}return t},ur=e=>JSON.parse(mP(hP(e)));import{spawnSync as yP}from"node:child_process";import{platform as gP}from"node:os";var xb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},wP=(e,t,n)=>yP(e,t,n),Ib=wP,bP,kP=()=>{let e=bP??gP();if(e==="win32"){let n=Ib(Cs("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],xb);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=Ib("pgrep",[n,r],xb);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},AP=kP,Is=()=>AP();var Qc={darwinAppName:"Visual Studio Code",darwinBundleId:"com.microsoft.VSCode",win32Image:"Code.exe",linuxProcess:"code",win32Install:[{root:"localAppData",path:"Programs\\Microsoft VS Code\\Code.exe"},{root:"programFiles",path:"Microsoft VS Code\\Code.exe"},{root:"programFilesX86",path:"Microsoft VS Code\\Code.exe"}]};import{execFile as CP}from"node:child_process";import{readdirSync as vP}from"node:fs";import{createHash as Pb,randomBytes as SP,randomUUID as Tb}from"node:crypto";import{chmod as EP,lstat as xP,mkdir as Hp,readFile as Xr,rm as Lb,unlink as Db,writeFile as Wp}from"node:fs/promises";import{homedir as jo,platform as Kp}from"node:os";import{dirname as Nb,join as Os,posix as Rb,win32 as IP}from"node:path";import{promisify as OP}from"node:util";var Rn="0.1.21";var Zr="8c2875844439f1b8a906d1b16e85cfc04f559096f7af88f6b9a26d877eee1c82",el="22be5f6ea9b3bf833982e1be741254dba1c37395e5b133caa071fbc3d91efdcc",Ob="UEsDBBQAAAgIAHwuCl3s2NkrBwMAALQJAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGcoqXlU+GsNhAUOxEqBQrk+hhgRI5WE1MkweHKUn99sbv6spKmlV3ktsuZeY/zwUfm79dLK1YYmbzryW52JQU67Q25sierNO/8Lt8Xlxf5BPQjlDgGR3PkJB52IdfZVR20XlrHPblIKdwoxXqBS+BsSTp69vOUab9UBldofcCoVrzutD7q+qrb3YbfmBcAdAwyla7FKS4vLvIxJjCQoP65yIcGXaK0ESNwZQUl9iS6zp9TKYamJ8FtImw6K9beoDxkdZV1s+uuFJNqZokXGHeuUqgW9wNxsLD5DEss+o1JzH0UD1Mx8AZzdWxvA5B1pJDIuzrdGw6gsSdDRMa4Qln0jRG4DpY0JbGFLCHhE2zE0hu0LHzcGjpPEUJAIwY+kPVJcDU7wG+90yL6qlzs9vQGgud3LPx8TprACrutSKfxFyH6FRmMoj8ZZrk62m+bwD2UXDyP4Vw1q419AAlLHwm56A/fjkEvyKEYIURHrszVkb3x/wjWYtzc2RqhKbTO1bPF2q1xncS662kXul/YNE0c74fkgbgCO02VIZ/VOWe3riRXdxZshT35tZt1r5spV2cjrRO6ejo+YEBn0GlC3gO/BrA+W/8L0B/kzB7oycfHZsbeVvQC0JHXYOkvNLtz87pcHcwsmn6gOsQz2B/AnZ026iohD9qj24KlWOELAKcYV6SRsxG5R86mvor6AFqLEt8oVVJaVLNGilo1+PRFLb3zEYPPSkrnFeaE8yMmThATml/MS+lTNfu1nNMqBB/TWaSKmKt6Cl/B24jRWay/RQSzPBmpF/C3Vb6zsPIRzRjio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Wy0KXbKGeo15AgAAJwQAABUAAAAAAAAAAAAAAKSBBgcAAGV4dGVuc2lvbi9MSUNFTlNFLnR4dFBLAQI/AxQACAgIAHwuCl11FYs5RzcAAD6kAAAbAAAAAAAAAAAAAACkgcIJAABleHRlbnNpb24vZGlzdC9leHRlbnNpb24uanNQSwUGAAAAAAUABQBVAQAAUkEAAAAA";var Pe="anyray.anyray-vscode",RP="vscode-handoffs",$b="vscode-receipts",Rs=2,_P=OP(CP),pr={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"]}},PP={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"}},TP=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),Mb=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&TP(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},_s=e=>{if(Mb(e))try{return new URL(e.trim()).origin}catch{return}},LP=(e,t)=>{if(!e.endsWith(".app"))return!1;let n=e.slice(0,-4);if(n===t)return!0;if(!n.startsWith(`${t} `))return!1;let r=n.slice(t.length+1);return r.length>0&&/^\d+$/.test(r)},DP=e=>{try{return vP(e)}catch{return[]}},NP=(e,t,n)=>{let{macAppName:r,commands:o}=pr[e],a=o[0],s=[];for(let i of["/Applications",Rb.join(t,"Applications")])for(let c of n(i))LP(c,r)&&s.push(Rb.join(i,c,"Contents/Resources/app/bin",a));return s},$P=(e,t=Kp(),n=jo(),r=process.env,o=DP)=>{if(t==="darwin")return[...new Set([...pr[e].commands,...NP(e,n,o)])];if(t!=="win32"){let l=pr[e].commands[0];return[...new Set([l,`/usr/bin/${l}`,`/usr/local/bin/${l}`])]}let a=PP[e],s=IP.join,i=r.LOCALAPPDATA??s(n,"AppData","Local"),c=[s(i,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(l=>!!l);return[...new Set([...c.map(l=>s(l,a.directory,a.executable)),pr[e].commands[0]])]},Fb={run:async(e,t)=>({stdout:(await _P(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>SP(24).toString("base64url"),home:"",commandCandidates:e=>$P(e)},Go=(e,t)=>Os(e,".anyray",$b,`${t}.json`),Gp=(e,t)=>Os(e,".anyray",$b,`${t}.applied.json`),Bb=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Sc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},Ub=async(e,t)=>{let n=await Bb(e,t);if(n)try{let r=await t.run(n.command,["--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===Pe.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===Rn}catch{return}},Hb=250,MP=9e4,FP=MP/Hb,BP=async(e,t,n,r)=>{for(let o=0;o<FP;o++){try{let a=JSON.parse(await Xr(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Rs&&a.action===n?"confirmed":a.extensionVersion!==Rn||a.extensionDistSha256!==Zr?"reload-required":a.version===Rs&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(Hb)}return"timeout"},UP=async e=>{try{let t=await xP(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},_b=e=>Pb("sha256").update(e).digest("hex"),HP=async(e=jo())=>{let t=Buffer.from(Ob,"base64");if(t.length<4||t[0]!==80||t[1]!==75||_b(t)!==el)throw new Error("bundled VS Code extension failed integrity validation");let n=Os(e,".anyray","vscode-extension"),r=Os(n,`anyray-vscode-${Rn}-${el.slice(0,12)}.vsix`);try{if(_b(await Xr(r))===el)return r}catch{}await Hp(n,{recursive:!0,mode:448});let o=`${r}.${Tb()}.tmp`;try{await Wp(o,t,{mode:384}),await fe(o,r),Kp()!=="win32"&&await EP(r,384)}finally{await Lb(o,{force:!0})}return r},Up=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=>Up(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Up(t[n])}`).join(",")}}`},Wb=(e,t,n)=>Pb("sha256").update(Up({gatewayUrl:_s(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:Rn,extensionDistSha256:Zr,profiles:[...n].sort()})).digest("hex"),WP=async(e,t,n,r,o,a)=>{let s=JSON.parse(await Xr(Gp(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==Wb(t,n,r))return!1;let i=JSON.parse(await Xr(Go(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===Rn&&i.extensionDistSha256===Zr&&i.gatewayUrl===_s(t.origin)?await Ub(e,a)===!0:!1},KP=async(e,t,n,r)=>{let o=Gp(e,t),a=`${o}.${Tb()}.tmp`;try{await Hp(Nb(o),{recursive:!0,mode:448}),await Wp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
109
|
-
`,{mode:384}),await fe(a,o)}catch{}finally{await
|
|
110
|
-
`,{mode:384});let w={installed:[],failed:[]};try{if(n==="configure"){await a.run(l,["--install-extension",f,"--force"]);for(let y of u)try{await a.run(l,["--profile",y,"--install-extension",f,"--force"]),w.installed.push(y)}catch{w.failed.push(y)}}await a.run(l,["--open-url",`${s.scheme}://${
|
|
111
|
-
`,{flag:"wx",mode:384}),await fe(n,e),await jP(e,384)}finally{await YP(n,{force:!0}).catch(()=>{})}},jp=e=>{if(!Ct(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!==fr||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(!Ct(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!==ek(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!Ct(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}})},Vp=e=>{let t=e.filter(n=>!jp(n));return{next:t,removed:t.length!==e.length}},QP=async(e,t)=>{let n=Ps(e),r=await tl(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 "${fr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=Vp(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${fr}" Custom Endpoint from ${n}.`]};try{return await tk(n,o),await ne(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${fr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${fr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},eT=async e=>{try{let t=ur(await Jb(e,"utf-8"));if(Ct(t))return Qb(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Ts}.${nl} in ${e}, which uses JSONC that Connect will not rewrite; remove it manually.`]}:{changedFiles:[],messages:[],manual:!1}}catch{}return{changedFiles:[],manual:!0,messages:[`Could not parse ${e}; remove an old Anyray ${Ts}.${nl} value manually if present.`]}},nk=async(e,t)=>{let n=zP(e),r;try{r=await F(n)}catch{return eT(n)}let{next:o,removed:a}=Qb(r);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the retired Anyray Copilot debug override from ${n}.`]};try{return await Z(n,o,{backup:!1}),await ne(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.`]}}},tT=async(e,t)=>{let n=await QP(e,t),r=await nk(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},rk=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,qb]}},ok=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},ak=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),nT=e=>Array.isArray(e.args)&&e.args.at(-1)===qb,sk=(e,t)=>{if(!t.hookBinaryIsDurable()||!Ct(e)||!ok(e,["type","command","args"]))return!1;let n=rk(t);return e.type==="stdio"&&e.command===n.command&&ak(e.args,n.args)},rT=(e,t)=>{if(!Ct(e)||!ok(e,["type","command","args"])||e.type!=="stdio"||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(i=>typeof i=="string"))return!1;let n=t.mcpServerCommand("profile");if(e.command===n.command&&ak(e.args,n.args))return!0;if(Ke(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===Qn&&r.at(-1)==="profile"))return!1;let a=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(a))return r.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(a)||r.length!==3)return!1;let s=r[0].replaceAll("\\","/");return!Ke(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},Yp=(e,t)=>sk(e,t)?"exact":Ct(e)&&nT(e)||rT(e,t)?"stale-owned":"foreign",Yb=e=>`MCP name conflict in ${e}: servers.${hn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,oT=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let p of a)try{let h=await F(p);if(i){if("servers"in h&&!Ct(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${p} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let y=Ct(h.servers)?{...h.servers}:{},b=rk(o),v=y[hn],S=v===void 0?void 0:Yp(v,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(Yb(p));continue}if(t){d+=1;continue}y[hn]=b,f.push({path:p,next:{...h,servers:y},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!Ct(h.servers)||!(hn in h.servers))continue;if(Yp(h.servers[hn],o)==="foreign"){u=!0,l.push(Yb(p));continue}if(t)continue;let w={...h.servers};delete w[hn];let g={...h};Object.keys(w).length===0?delete g.servers:g.servers=w,f.push({path:p,next:g,backup:!1,clearBackupAfter:!0})}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let p of f)try{await Z(p.path,p.next,p.backup?{}:{backup:!1}),p.clearBackupAfter&&await ne(p.path),c.push(p.path),i&&(d+=1)}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p.path} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`);break}return i?l.unshift(t?d===a.length?`Would register the Anyray retrieval MCP server in ${a.length} VS Code user profile config(s).`:`Would register the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); resolve the conflicts below first.`:d===a.length?`Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) in ${a.length} VS Code user profile config(s).`:`Registered the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); see the profile-specific errors below.`):n?l.unshift(t?`Would skip the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary.`:`Skipped the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary; removed any stale owned registration. Re-run via the installer or a global install to enable retrieval.`):l.unshift(`${t?"Would skip":"Skipped"} the Anyray retrieval MCP server because this VS Code build predates profile-scoped mcp.json support (${rw}+).`),{changedFiles:c,messages:l,manual:u}},aT=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await O(c))try{let l=await F(c);if(!Ct(l.servers)||!(hn in l.servers)||Yp(l.servers[hn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[hn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await Z(c,u,{backup:!1}),await ne(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}},ik=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.`]:[]],ck=()=>`${Pe} is already installed and configured for this gateway \u2014 skipped the VSIX reinstall and the VS Code URI confirmation prompt. (Run --revert first to force re-delivery.)`,Zb=e=>[`${Pe} mirrors the GitHub Copilot models available to this VS Code install.`,`Gateway: ${e.origin} (client key stored by VS Code SecretStorage).`,"Mode: SUBSCRIPTION \u2014 requests use your existing Copilot sign-in and model; Anyray supplies a supported before-request optimization provider.","Inline completions remain native GitHub Copilot traffic. Choose an \u201CAnyray \xB7 \u2026\u201D model in Chat for optimized requests.",'Copilot\u2019s internal utility models (chat titles, summaries) keep working with an Anyray main model: the extension sets VS Code\u2019s chat.byokUtilityModelDefault to "copilot" unless you already set it yourself.',"VS Code profiles scope extensions; Connect installs the provider into every profile registered at apply time. A profile created later needs a Connect re-run (or VS Code\u2019s \u201CApply Extension to all Profiles\u201D action).","Copilot Business/Enterprise administrators must allow language-model providers in GitHub\u2019s Bring Your Own Language Model Key policy."],lk=(e,t,n,r)=>({runMcp:o=>oT(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):tT(e,o)}),sT=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=lk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${Pe} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...Zb(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${Pe}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"copilot-seat"});if(!d.ok)return{status:"manual",messages:[d.reason==="reload-required"?`A newer ${Pe} build was installed, but ${e} is still running the previous build. Reload VS Code completely, then re-run anyray-connect.`:d.reason==="cli-not-found"?`The ${e} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`:d.reason==="unsupported-version"?`The Anyray language-model provider requires VS Code ${vc} or newer. Upgrade ${e}, then re-run anyray-connect; no extension configuration was written.`:d.reason==="unsafe-gateway"?"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.":d.reason==="extension-missing"?`This anyray-connect installation is missing its bundled ${Pe} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`:`VS Code did not confirm the one-time ${Pe} configuration. Open VS Code and re-run anyray-connect.`]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[ck()]:[],...Zb(t),...d.alreadyCurrent?[]:ik(d.profiles),...f.messages,...u.messages]}},Xb=e=>[`${Pe} exposes the configured Anyray gateway models without writing a key to chatLanguageModels.json.`,`Gateway: ${e.origin} (personal client key and attribution stored together in VS Code SecretStorage).`,"Mode: API KEY \u2014 the extension streams normal /v1/chat/completions requests through Anyray. Text chat only: the models register without tool calling (the OpenAI bridge cannot carry VS Code's structured tool results).",`Models in the picker: ${Ds().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."],iT=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=lk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${Pe} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...Xb(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${Pe}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Ds().map(p=>({id:p,name:ek(p)}))});if(!d.ok)return{status:"manual",messages:[d.reason==="reload-required"?`A newer ${Pe} build was installed, but ${e} is still running the previous build. Reload VS Code completely, then re-run anyray-connect.`:d.reason==="cli-not-found"?`The ${e} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`:d.reason==="unsupported-version"?`The Anyray language-model provider requires VS Code ${vc} or newer. Upgrade ${e}, then re-run anyray-connect; no extension configuration was written.`:d.reason==="unsafe-gateway"?"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.":d.reason==="extension-missing"?`This anyray-connect installation is missing its bundled ${Pe} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`:`VS Code did not confirm the one-time ${Pe} gateway API configuration. Open VS Code and re-run anyray-connect.`]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[ck()]:[],...Xb(t),...d.alreadyCurrent?[]:ik(d.profiles),...f.messages,...u.messages]}},cT=async(e,t,n)=>{let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null};let o=[];for(let s of r){if(!await O(s))return{registered:!1,command:null};try{let i=await F(s),c=Ct(i.servers)?i.servers[hn]:void 0;if(!sk(c,n))return{registered:!1,command:null};o.push(c.command)}catch{return{registered:!1,command:null}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var lT=async(e={installedVariant:Ec,remoteServerVariant:sp,isRemoteDevContext:es})=>{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}},dT={installedVariant:Ec,remoteServerVariant:sp,detectVscodeLmProviderEligibility:dw,configureVscodeExtension:Kb,vscodeExtensionPointsAt:Vb,vscodeExtensionAwaitingReload:Gb,vscodeExtensionReceiptMode:jb,hookBinaryIsDurable:ce,hookBinaryPath:Re,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:cw,isRemoteDevContext:es},uT=(e={})=>{let t={...dT,...e},n=()=>lT(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Is,quitTarget:Qc},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Bo(r,!0)}`:Ps(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ie(r.clientKey))return{status:"manual",messages:["Enrollment required: Copilot setup needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; no VS Code configuration was written."]};let{variant:a,remote:s}=await n();if(!a)return{status:"manual",messages:[t.isRemoteDevContext()?"No VS Code server found here yet \u2014 this looks like a dev container, Codespace, or SSH remote. `--tools copilot` now configures the Anyray provider directly in a remote VS Code window, but only after VS Code has attached to this machine and installed its server. Open this machine with the VS Code Remote-SSH (or Dev Containers) extension, then re-run anyray-connect --tools copilot in that window\u2019s integrated terminal. To route this shell through Anyray without the Copilot UI, use an in-container tool instead: anyray-connect --tools opencode --sso <link> --subscription.":"No VS Code install found. Install VS Code, then re-run anyray-connect; the personal key will be transferred directly into SecretStorage."]};let i=await t.detectVscodeLmProviderEligibility(a);if(i.status==="needs-update")return{status:"manual",messages:[`${a} ${i.version??""} cannot expose public third-party models in Chat's picker. Upgrade to VS Code ${vc} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||ow(i.version);return J(r,"copilot")?sT(a,r,o,t.configureVscodeExtension,c,s,t):iT(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?cT(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=_s(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await tl(Ps(o));if(s.kind==="array"){let c=s.entries.find(jp)?.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 tl(Ps(r));if(o.kind==="array"&&o.entries.some(jp))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 aT(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await nk(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${Pe} to clear its global configuration and SecretStorage key`);else{let y=await t.configureVscodeExtension(o,void 0,"reset");y.ok?(c=!0,d=y.receipt,u.push(`Cleared ${Pe} gateway configuration and secret.`)):(l=!0,u.push(y.reason==="cli-not-found"?`The ${o} command-line launcher was not found, so Anyray could not ask ${Pe} to clear its SecretStorage configuration. Install the launcher and re-run revert.`:`VS Code did not confirm the ${Pe} reset. Open VS Code and re-run revert.`))}let f=Ps(o),p=await tl(f),h=p.kind==="missing"||p.kind==="array"&&!Vp(p.entries).removed,m=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),h)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:m.length?m:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:m.length?m:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:m,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(p.kind==="unrecognized")return{status:"manual",changedFiles:m.length?m:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${fr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=Vp(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${fr} Custom Endpoint from ${f}`]};await tk(f,w);let g=[...u,`Removed the ${fr} Custom Endpoint from ${f}.`];return await ne(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},dk=uT();import{accessSync as LT,constants as Ak,statSync as DT}from"node:fs";import{readFile as Ck,rm as $s}from"node:fs/promises";import{homedir as rf,platform as Rk}from"node:os";import{delimiter as NT,join as of,resolve as $T}from"node:path";import{execFile as yT}from"node:child_process";import{readFile as gT}from"node:fs/promises";import{homedir as Jp,platform as wT}from"node:os";import{join as Ns}from"node:path";import{join as pT}from"node:path";var Zp="Iv1.b507a08c87ecfe98",fT="https://github.com/login/device/code",hT="https://github.com/login/oauth/access_token",mT="read:user",uk=1e4,Vo=()=>pT(q(),"copilot-seat-login.json"),pk={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},Xp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fk=async(e={})=>{let t={...pk,...e};try{let n=await t.fetch(fT,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Zp,scope:mT}),signal:AbortSignal.timeout(uk)});if(!n.ok)return;let r=await n.json();if(!Xp(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}},hk=async(e,t={})=>{let n={...pk,...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(hT,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Zp,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(uk)})).json();if(!Xp(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"}},mk=async(e,t)=>{let n=Vo();return await he(n,`${JSON.stringify({token:e,clientId:Zp,mintedAtIso:t},null,2)}
|
|
112
|
-
`),n},
|
|
113
|
-
`))}`]:[],`export ${
|
|
114
|
-
`).map(
|
|
115
|
-
`)):V&&z&&await
|
|
102
|
+
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");Dw(o?.slice(1).map(Number))},d_=(e,t)=>{let n=n_(Lw(s_(),"anyray-cursor-"));try{let o=[".bail on",".timeout 5000","BEGIN IMMEDIATE;",...t.map((a,s)=>{if(a.value===void 0)return`DELETE FROM ItemTable WHERE key=${Wc(a.key)};`;let i=Lw(n,`value-${s}`);return o_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${Wc(a.key)}, CAST(readfile(${Wc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
|
|
103
|
+
`);Kc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Sp,stdio:["pipe","ignore","pipe"]})}finally{try{r_(n,{recursive:!0,force:!0})}catch{}}},u_={kind:"sqlite3-cli",readItem:(e,t)=>$w(e,t),checkpointWal:e=>Mw(e),mutateRows:d_},p_=()=>{try{let t=a_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},vp=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},f_=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),h_=e=>({kind:"node-sqlite",readItem:(t,n)=>vp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:f_(o.value)}),checkpointWal:t=>vp(e,t,n=>{let r=n.prepare("PRAGMA wal_checkpoint(TRUNCATE);").get(),o=[r?.busy,r?.log,r?.checkpointed].map(a=>typeof a=="bigint"?Number(a):a);Dw(o)}),mutateRows:(t,n)=>vp(e,t,r=>{r.exec("BEGIN IMMEDIATE;");try{for(let o of n)o.value===void 0?r.prepare("DELETE FROM ItemTable WHERE key = ?").run(o.key):r.prepare("INSERT INTO ItemTable(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(o.key,o.value);r.exec("COMMIT;")}catch(o){try{r.exec("ROLLBACK;")}catch{}throw o}})}),Hc,ks=()=>{if(Hc!==void 0)return Hc;let e=p_();return Hc=e?h_(e):Nw()?u_:null,Hc};import{spawn as m_}from"node:child_process";import{randomUUID as Fw}from"node:crypto";import{constants as Bw}from"node:fs";import{chmod as y_,copyFile as Uw,mkdir as g_,readdir as w_,readFile as b_,rename as k_,rm as As,writeFile as A_}from"node:fs/promises";import{join as Ep}from"node:path";var xp=/^[a-z0-9][a-z0-9-]{0,31}$/,C_=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,Hw=/^[a-z0-9][a-z0-9-]{0,31}$/,v_=/^[0-9TZ:.+-]{1,40}$/,Ip=()=>Ep(q(),"pending"),jc=e=>{if(!xp.test(e)||C_.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Ep(Ip(),`${e}.json`)},Ww=()=>Ep(q(),"cursor-pending.json"),S_=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),E_=(e,t)=>{if(!S_(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!xp.test(n)||typeof e.op!="string"||!Hw.test(e.op)||typeof e.requestedAt!="string"||!v_.test(e.requestedAt)||Number.isNaN(Date.parse(e.requestedAt))))return{version:1,adapter:n,op:e.op,requestedAt:e.requestedAt,watcherPid:typeof e.watcherPid=="number"&&Number.isSafeInteger(e.watcherPid)&&e.watcherPid>0?e.watcherPid:void 0,...typeof e.generation=="string"&&e.generation?{generation:e.generation}:{}}},Rp=async(e,t)=>{try{return E_(JSON.parse(await b_(e,"utf-8")),t)}catch{return}},Kw=async()=>{let e=Ww(),t=await Rp(e,"cursor");if(!t)return;let n=!1;try{await Gw(),await Uw(e,jc("cursor"),Bw.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await As(e,{force:!0})}catch{}return t},Vc=async e=>{let t=await Rp(jc(e),e);return t||(e==="cursor"?Kw():void 0)},cr=async()=>{let e;try{e=await w_(Ip())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!xp.test(r))continue;let o=await Vc(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await Kw();n&&t.push(n)}return t},Gw=async()=>{await kt();let e=Ip();await g_(e,{recursive:!0,mode:448});try{await y_(e,448)}catch{}},Gc=async e=>{await Gw();let t=jc(e.adapter),n=`${t}.${process.pid}.tmp`;await A_(n,`${JSON.stringify(e)}
|
|
104
|
+
`,{mode:384}),await fe(n,t)},x_=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,lr=async(e,t)=>await Op(e,t)==="claimed",Op=async(e,t)=>{let n=jc(e);if(t){let o=`${n}.${process.pid}.${Fw()}.claimed`;try{await k_(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Rp(o,e);if(a&&x_(a,t))return await As(o,{force:!0}),"claimed";let s=!1;try{await Uw(o,n,Bw.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await As(o,{force:!0})}return"superseded"}let r=!1;try{await As(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await As(Ww(),{force:!0})}catch{}return r?"claimed":"absent"},dr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},I_=e=>{let{command:t,args:n}=pn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},R_=e=>{let{exe:t,args:n}=I_(e),r=m_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},jw=R_;var Vw=async()=>{let e=[],t;try{t=await cr()}catch{return e}for(let n of t)if(!dr(n.watcherPid))try{let r=jw(n.adapter);if(!r)continue;await Gc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},Cs=async(e,t)=>{if(!Hw.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await Vc(e),r=new Date().toISOString(),o=Fw();if(n&&dr(n.watcherPid))return await Gc({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await Gc({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=jw(e)}catch{a=void 0}return a&&await Gc({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as O_,spawnSync as Zw}from"node:child_process";import{existsSync as Yc}from"node:fs";import{homedir as __,platform as ur}from"node:os";import{join as Xw,win32 as Yw}from"node:path";var Jw=(e,t={})=>{let n=t.env??process.env,r=t.exists??Yc,o=(t.home??__)(),a={localAppData:n.LOCALAPPDATA??Yw.join(o,"AppData","Local"),programFiles:n.ProgramFiles,programFilesX86:n["ProgramFiles(x86)"]};for(let s of e.win32Install??[]){let i=a[s.root];if(!i)continue;let c=Yw.join(i,s.path);if(r(c))return c}},Vr=/^[A-Za-z0-9 ._-]{1,64}$/,T_=/^[A-Za-z0-9.-]{1,128}$/,Zc=e=>e.darwinBundleId&&T_.test(e.darwinBundleId)?e.darwinBundleId:void 0,zw=(e,t=ur())=>t==="darwin"?Zc(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",qw=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",Qw=(e,t=ur(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return Jw(e,r)!==void 0;let o=e.linuxProcess;return!o||!Vr.test(o)?!1:n.split(":").filter(Boolean).some(a=>Yc(Xw(a,o)))},eb=(e,t=ur())=>{if(t==="darwin"&&Zc(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Vr.test(n))},tb=1e4,vs=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=Xw(t,"System32",e);return Yc(n)?n:e},P_=e=>{let t=`/usr/bin/${e}`;return Yc(t)?t:e},L_=(e,t)=>{try{let n=Zw(e,t,{encoding:"utf-8",timeout:tb,windowsHide:!0,...ur()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:ur()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},D_=e=>new Promise(t=>setTimeout(t,e)),nb=(e,t={})=>{let n=t.runtimePlatform??ur(),r=t.run??L_;if(n==="darwin"){let a=Zc(e);if(a&&r("/usr/bin/osascript",["-e",`if application id "${a}" is running then tell application id "${a}" to quit`]))return!0;let s=e.darwinAppName;return!s||!Vr.test(s)?!1:r("/usr/bin/osascript",["-e",`if application "${s}" is running then tell application "${s}" to quit`])}if(n==="win32"){let a=e.win32Image;return!a||!Vr.test(a)?!1:r(vs("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(P_("pkill"),["-TERM","-o","-x",o])},rb=async(e,t=2e4,n={})=>{let r=n.sleep??D_,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},N_=(e,t,n={})=>{let r=ur();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=Zw(e,t,{stdio:"ignore",timeout:tb,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=O_(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},ob=(e,t={})=>{let n=t.runtimePlatform??ur(),r=t.launch??N_;if(n==="darwin"){let a=Zc(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Vr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=Jw(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(o,[])};var j_={darwinAppName:"Cursor",darwinBundleId:"com.todesktop.230313mzl4w4u92",win32Image:"Cursor.exe",linuxProcess:"cursor",win32Install:[{root:"localAppData",path:"Programs\\cursor\\Cursor.exe"},{root:"programFiles",path:"cursor\\Cursor.exe"},{root:"programFilesX86",path:"cursor\\Cursor.exe"}]},V_=e=>e==="apply"||e==="native"||e==="revert",fb=()=>ot("Cursor"),Yr=()=>Go(fb(),"User","globalStorage","state.vscdb"),Es=()=>`${Yr()}.anyray-bak.json`,Ko=()=>`${Yr()}.anyray-bak`,Xe="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",ct="cursorAuth/openAIKey";var Pp="/seat/cursor",Fp="Prefer the anyray_search and anyray_read tools over the built-in codebase search and file read. anyray_search returns relevance-filtered matches; anyray_read returns the pertinent slice of a file plus a retrieve handle you can pass to anyray_retrieve to recover any elided detail. Use them when finding or reading code.",Ss=Go(".cursor","rules","anyray.mdc"),hb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",Y_=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",hb,"",Fp,""].join(`
|
|
105
|
+
`),Z_=e=>{let t=G_(e);for(;;){if(Ee(Go(t,".git")))return t;let n=pb(t);if(n===t)return null;t=n}},X_=e=>e.authMode!=="placeholder",zt=()=>Go(ub(),".cursor","hooks.json"),qt=()=>Go(ub(),".cursor","mcp.json"),$t="anyray",mb="--anyray-owner=cursor-v1",J_="postToolUse",z_="beforeSubmitPrompt",ab="preToolUse",q_="^MCP:",Q_="UserPromptSubmit",eT="Shell",tT="^(Read|Grep)$",Qc="--anyray-owner=cursor-hook-v1",Zr=[{event:J_,flag:Ze,trailingArgs:["cursor"],matcher:q_},{event:z_,flag:qn,trailingArgs:[],matcher:Q_},{event:ab,flag:yg,trailingArgs:[],matcher:eT},{event:ab,flag:gg,trailingArgs:[],matcher:tT}];var sb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},nT=(e,t,n)=>$_(e,t,n),ib=nT,rT,oT=()=>{let e=rT??K_();if(e==="win32"){let t=ib(vs("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],sb);return t.error||t.signal||t.status!==0?!0:/(?:^|\r?\n)"Cursor\.exe",/iu.test(t.stdout??"")}for(let t of e==="linux"?["cursor","Cursor"]:["Cursor"]){let n=ib("pgrep",["-x",t],sb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},aT=oT,zc=()=>aT();var sT=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Xe)??null,openAIKey:e.readItem(n,ct)??null,lastWritten:r};Mp(t,`${JSON.stringify(o,null,2)}
|
|
106
|
+
`,{encoding:"utf-8",flag:"wx",mode:384})},yb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Mp(n,`${JSON.stringify(t,null,2)}
|
|
107
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{W_(n,e)}catch(r){throw hn(n,{force:!0}),r}},iT=(e,t)=>{let n=Ho(e);yb(e,{...n,lastWritten:t})},ne=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),cb=e=>ne(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Ho=e=>{let t=db(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(ne(n)&&(Object.keys(n).length===2||Object.keys(n).length===3)&&Object.prototype.hasOwnProperty.call(n,"applicationUser")&&Object.prototype.hasOwnProperty.call(n,"openAIKey")&&(typeof n.applicationUser=="string"||n.applicationUser===null)&&(typeof n.openAIKey=="string"||n.openAIKey===null)&&(n.lastWritten===void 0||ne(n.lastWritten)&&Object.keys(n.lastWritten).length===2&&typeof n.lastWritten.applicationUser=="string"&&typeof n.lastWritten.openAIKey=="string"))return{applicationUser:n.applicationUser,openAIKey:n.openAIKey,...n.lastWritten?{lastWritten:{applicationUser:n.lastWritten.applicationUser,openAIKey:n.lastWritten.openAIKey}}:{}};if(!ne(n)||n.version!==1||!ne(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Xe],o=n.rows[ct];if(!cb(r)||!cb(o))throw new Error("Cursor value backup is missing an exact managed row");return{applicationUser:r.exists?r.value:null,openAIKey:o.exists?o.value:null}},lb=e=>{let t=Buffer.alloc(16),n=U_(e,"r");try{return H_(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{M_(n)}},cT=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return ne(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var gb=e=>{let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".lan")||t.endsWith(".internal")||t.endsWith(".home")||!t.includes(".")&&_p(t)===0||t==="0.0.0.0")return!0;if(_p(t)===4){let[n,r,o]=t.split(".").map(Number);return n===10||n===0||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===192&&r===0&&(o===0||o===2)||n===198&&(r===18||r===19)||n===198&&r===51&&o===100||n===203&&r===0&&o===113||n>=224}if(_p(t)===6){let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return gb(`${r>>>8}.${r&255}.${o>>>8}.${o&255}`)}return t==="::"||t==="::1"||t.startsWith("fc")||t.startsWith("fd")?!0:/^fe[89a-f]/.test(t)}return!1},Lp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!gb(t.hostname)}catch{return!1}},lT=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},dT=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Ye(e.origin)}/v1${Pp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Pp}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),Wo=(e,t=!1)=>[...t?[`Cursor's server-side BYOK lane bypasses the local key-refresh proxy and points directly at ${e.openaiBaseUrl}.`]:[],"Route capability: only custom-model requests Cursor actually sends to its OpenAI BYOK endpoint. Cursor's Agent wire behavior varies by release; native Team models, Tab, indexing, and other first-party traffic stay on Cursor-hosted services.","Billing: this lane bills as an Anyray subscription seat \u2014 each distinct attributed developer with usage in a month is one seat. Attribution rides your per-user ark_ key (Cursor sends no metadata header), so enroll each developer with their own key."],wb=()=>{let e=Yr();if(!Ee(e))return"clear";let t=ks();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Xe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ne(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},uT=(e,t)=>{if(!Lp(e))return{routed:!1,problem:"gateway-not-public-https"};let n=Yr();if(!Ee(n))return{routed:!1,problem:"state-db-missing"};let r=ks();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Xe),a=r.readItem(n,ct)}catch{return{routed:!1,problem:"state-db-unreadable"}}if(o===void 0)return{routed:!1,problem:"settings-missing"};let s;try{s=JSON.parse(o)}catch{return{routed:!1,problem:"settings-malformed"}}if(!ne(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ye(e)}/v1${Pp}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ie(a)||!Ie(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},pT=(e,t=[])=>({command:Tt(e,[...t,Qc])}),Bp=(e,t,n)=>{if(!ne(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Tt(t,[...n,Qc])||r===Tt(t,n)||r.endsWith(` ${Qc}`)&&r.includes(` ${t} `)},fT=(e,t)=>ne(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),bb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Bp(a,t,n)){r=!0;continue}if(!ne(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!fT(c,t));if(s.length===a.hooks.length){o.push(a);continue}r=!0;let i=Object.keys(a).every(c=>c==="matcher"||c==="hooks");s.length===0&&i||o.push({...a,hooks:s})}return{entries:o,changed:r}},Up=(e,t)=>{let n=e[t];if(n===void 0)return[];if(!Array.isArray(n))throw new Error(`Cursor hook event ${t} is not an array`);return n},kb=(e,t,n,r,o)=>ne(e.hooks)&&Up(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Bp(a,n,r)),hT=(e,t,n,r,o)=>ne(e.hooks)&&Up(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Bp(a,n,r)&&ac(a.command,n,[...r,Qc])),Ab=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!ne(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=ne(e.hooks)?{...e.hooks}:{},{entries:s}=bb(Up(a,t),n,r);return s.push({...pT(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},mT=(e,t,n,r=[])=>{if(!ne(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=bb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},yT=async()=>{let e=zt();if(!ce()){let t=await vb();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await M(e);for(let n of Zr)t=Ab(t,n.event,n.flag,n.trailingArgs,n.matcher);return await Z(e,t),{changedFiles:[e],messages:[`Installed Cursor global hooks in ${e} (postToolUse trims oversized MCP tool outputs; preToolUse trims recognized Shell command output and redirects bulky built-in Read/Grep to Anyray's context tools; beforeSubmitPrompt beacons oversized pasted-data prompts). Cursor hook cache/tee persistence is disabled; gateway request logs and savings/spend rows remain metadata-only, while trace decision content follows the deployment's ANYRAY_CONTENT_MODE.`],complete:!0}}catch{return{changedFiles:[],messages:[`Could not install Cursor hooks in ${e}. Chat can still route through Anyray, but hook-based trimming/beacons are unavailable until this is fixed.`],complete:!1}}},qc=()=>{let e=je("profile");return{command:e.command,args:[...e.args,mb]}},Dp=e=>ne(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===qc().command&&e.args.length===qc().args.length&&e.args.every((t,n)=>t===qc().args[n]),gT=e=>{if(!ne(e)||Object.keys(e).some(o=>o!=="command"&&o!=="args")||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(o=>typeof o=="string")||Ge(e.command))return!1;let t=e.args;if(t.at(-2)!==er||t.at(-1)!=="profile")return!1;let n=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(n))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(n)||t.length!==3)return!1;let r=t[0].replaceAll("\\","/");return!Ge(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},el=e=>ne(e)&&Array.isArray(e.args)&&e.args.at(-1)===mb||gT(e),wT=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,bT=async()=>{if(!ce())return Cb();let e=qt();try{let t=await M(e);if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?{...t.mcpServers}:{},r=n[$t];return r!==void 0&&!el(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${$t} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[$t]=qc(),await Z(e,{...t,mcpServers:n}),{changedFiles:[e],messages:[`Registered the Anyray retrieval MCP server (anyray_retrieve) in ${e} for explicit recovery of stashed context.`],complete:!0})}catch{return{changedFiles:[],messages:[`Could not register the Anyray MCP server in ${e}; retrieval via anyray_retrieve is unavailable until this is fixed.`],complete:!1}}},Cb=async()=>{let e=qt();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!ne(t.mcpServers)||!($t in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!el(t.mcpServers[$t]))return{changedFiles:[],messages:[`Preserved the foreign ${$t} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[$t];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await Z(e,r,{backup:!1}),{changedFiles:[e],messages:["Removed the Anyray retrieval MCP server (anyray_retrieve)."],complete:!0}}catch{return{changedFiles:[],messages:[`Could not remove the Anyray MCP server from ${e}; the registration was left in place.`],complete:!1}}},vb=async()=>{let e=zt();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e),n=t;for(let r of Zr)n=mT(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await Z(e,n,{backup:!1}),{changedFiles:[e],messages:["Removed Cursor global Anyray hooks."],complete:!0})}catch{return{changedFiles:[],messages:[`Could not remove Cursor hooks from ${e}; the hooks were left in place.`],complete:!1}}},kT=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=Z_(e);if(!n)return t;let r=Go(n,Ss),o=Y_();try{if(Ee(r)){let a=db(r,"utf8");if(a===o)return t;if(!a.includes(hb))return{...t,messages:[`Left ${Ss} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Fp}"`]}}return B_(pb(r),{recursive:!0}),Mp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Ss} so Cursor agents in this repo default to Anyray's tools (that is what produces gateway traces \u2014 Cursor's built-in search and read never reach Anyray). Commit it to share with the team.`],complete:!0}}catch{return{...t,messages:[`Could not write ${Ss} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Sb=async()=>{let e=await yT(),t=await bT(),n=await kT();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Np=async()=>{let e=await vb(),t=await Cb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Eb=async()=>{if(!ce()){let e=await Np();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${Oe()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await M(zt());for(let r of Zr)e=Ab(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(qt());if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?t.mcpServers[$t]:void 0;return n!==void 0&&!el(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${qt()} already contains a foreign ${$t} MCP registration. Rename or remove that entry explicitly, then re-run Connect.`],complete:!1}:{changedFiles:[],messages:[],complete:!0}}catch{return{changedFiles:[],messages:[`Cursor routing was not changed because its hook or MCP configuration could not be validated safely. Repair ${zt()} and ${qt()}, then re-run Connect.`],complete:!1}}},AT=async()=>{if(!ce())return!1;try{let e=await M(zt());if(!ne(e.hooks)||!Zr.every(r=>kb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(qt()),n=ne(t.mcpServers)?t.mcpServers[$t]:void 0;return Dp(n)}catch{return!1}},xb=["openAIBaseUrl","useOpenAIKey"],xs=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!ne(t))throw new Error("Cursor application-user settings are not an object");return t},CT=(e,t,n)=>{let r=xs(e),o=xs(t??void 0),a=n===void 0?void 0:xs(n),s={...r},i=[];for(let c of xb){let l=Object.prototype.hasOwnProperty.call(r,c),d=a!==void 0&&Object.prototype.hasOwnProperty.call(a,c);if(a===void 0||l!==d||l&&!Object.is(r[c],a[c])){i.push(c);continue}Object.prototype.hasOwnProperty.call(o,c)?s[c]=o[c]:delete s[c]}return{mutation:Object.keys(s).length===0?{key:Xe}:{key:Xe,value:JSON.stringify(s)},conflicts:i}},Tp=(e,t)=>{let n=xs(e),r=xs(t??void 0),o={...n};for(let a of xb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Xe}:{key:Xe,value:JSON.stringify(o)}},Xc=e=>typeof e=="string"&&e.startsWith("ark_"),Jc=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ne(o)&&(n=o)}catch{}let r=Xc(t)||n!==null&&(Xc(n.useOpenAIKey)||Xc(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,Xc(o.openAIKey)&&delete o.openAIKey,{applicationUser:Object.keys(o).length===0?null:JSON.stringify(o),openAIKey:null}}if(Object.prototype.hasOwnProperty.call(n,"useOpenAIKey")&&typeof n.useOpenAIKey!="boolean"){let o={...n};return delete o.useOpenAIKey,{applicationUser:Object.keys(o).length===0?null:JSON.stringify(o),openAIKey:t}}return{applicationUser:e,openAIKey:t}},it=(e,t)=>{if(!e.clientKey)return[...t?[t]:[],"Enrollment required: Cursor needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; do not save a placeholder Custom Endpoint.",...Wo(e)];let n=le(e.metadata);return[...t?[t]:[],"Configure Cursor by hand: Cursor \u2192 Settings \u2192 Models \u2192 OpenAI API Key:",` \u2022 Override OpenAI Base URL: ${e.openaiBaseUrl}`," \u2022 API key: run `anyray-connect print-key` and paste the returned personal gateway key (the key is not shown here).",n?` \u2022 Cursor has no custom-header field, so attribution rides your per-user key, not ${n}.`:" \u2022 (No attribution metadata resolved; set --user, or use --enroll for a per-user key.)","This is Cursor's OpenAI-BYOK lane: usage counts toward your Anyray subscription seat, but the upstream still needs a provider API key. It does not consume the native Cursor Team entitlement; exact custom-model Agent compatibility varies by Cursor release.",...Wo(e)]},$p=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ce())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await Cs("cursor",e)}catch{return n}return{status:"queued",messages:[`Cursor is running \u2014 ${o} queued. It completes automatically the next time Cursor fully quits; relaunch Cursor afterwards to pick it up.`,a.alreadyWatching?"A queue watcher was already waiting; it will run the latest queued operation.":a.watcherPid?"A background watcher is now waiting for Cursor to quit.":"The queue was saved, but a background watcher could not be started; the next Connect run will service it.",...r]}},vT=async(e,t)=>{if(!Ie(e.clientKey))return{status:"manual",messages:["Cursor native subscription mode was not changed: a valid personal ark_ gateway key is required for Anyray hooks and MCP retrieval."]};if(!t.dryRun&&!t.preservePendingOp)try{await lr("cursor")}catch{return{status:"manual",messages:["Cursor native subscription mode was not changed because Connect could not cancel Cursor's stale queued operation. Repair the owner-only ~/.anyray cursor queue and re-run."]}}let n=await Eb();if(!n.complete)return{status:"manual",messages:n.messages};let r=Ee(Es())||Ee(Ko());if(r&&zc())return $p("native",t,{status:"manual",messages:["Cursor is running \u2014 fully quit it and re-run so Connect can restore the journaled BYOK override before enabling native subscription mode."]},["No native Claude/Opus request will be redirected: the queued operation restores Cursor\u2019s prior settings, then installs only Anyray hooks/MCP."]);if(!r){let c=wb();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Ee(Ko())?Ko():Es()}, then install Anyray's local hooks and retrieval MCP server.`:`Would leave Cursor's native Team sign-in and model route unchanged, install global hooks in ${zt()}, and register the Anyray retrieval MCP server in ${qt()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Is.revert({dryRun:!1,preservePendingOp:!0}),o.status!=="reverted"))return{...o,messages:[...o.messages,"Cursor native subscription mode was not reported active because the prior BYOK route could not be restored safely."]};let a=await Sb(),s=[];if(!t.preservePendingOp)try{await lr("cursor")}catch{s.push("Could not clear Cursor's stale queue marker.")}return{status:a.complete&&s.length===0?"configured":"manual",changedFiles:[...new Set([...o?.changedFiles??[],...a.changedFiles])],messages:[...o?.messages??[],"Kept Cursor's native Team sign-in and Claude/Opus model route; no Anyray OpenAI override or model credential was written.",...a.messages,...s,"Claude/Opus inference remains Cursor-hosted and will not produce gateway inference traces. Anyray records content-free hook savings only when a supported oversized Shell/MCP result is actually reduced.",`Make it seamless org-wide: paste this into Cursor's dashboard Team Rules and mark it Required, so every member's agent uses Anyray's tools without being asked -- "${Fp}" (connect already writes ${Ss} when run inside a repo, which covers that repo once committed; see docs/integrations/cursor.md).`,"Restart Cursor so its MCP registration is loaded; hooks.json itself is watched and reloads automatically."]}},Is={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>zc(),quitTarget:j_,needsTarget:e=>e!=="revert",async complete(e,t,n){return V_(e)?e!=="revert"&&t?Is.apply(t,n):Is.revert(n):{status:"manual",messages:[`Cursor could not service a queued "${e}" operation it does not recognise; the queue entry was dropped.`]}}},async detect(){let e=fb(),t=Ee(e);return{installed:t,detail:t?Yr():"Cursor user dir not found"}},async watchPaths(){return[zt(),qt()]},async mcpStatus(){let e=qt();if(!await R(e))return{registered:!1,command:null};try{let t=await M(e),n=ne(t.mcpServers)?t.mcpServers[$t]:void 0;return Dp(n)?{registered:!0,command:wT(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=zt();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!ne(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Zr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Zr.every(c=>kb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Zr.every(c=>hT(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=qt();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!ne(s.mcpServers))r="unreadable";else{let i=s.mcpServers[$t];r=i===void 0?"missing":el(i)?"owned":"foreign",r==="owned"&&(o=Dp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Mr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await P();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(X_(e))return vT(e,t);let n=dT(e),r=lT(e.openaiBaseUrl),o=Yr(),a=Es(),s=Ko();if(!Ie(e.clientKey))return{status:"manual",messages:it(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let i={changedFiles:[],messages:[],complete:!0},c=y=>{let b=y.status==="configured"&&!i.complete;return{...y,status:b?"manual":y.status,changedFiles:[...y.changedFiles??[],...i.changedFiles],messages:[...y.messages,...i.messages,...b?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Lp(n.openaiBaseUrl))return c({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach loopback/LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect. No proxy, DNS, certificate, or interception workaround is installed.",...Wo(n)]});let l=await Eb();if(!l.complete)return{status:"manual",messages:l.messages};let d=ks();if(!d)return c({status:"manual",messages:it(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Ee(o))return c({status:"manual",messages:it(n,`No Cursor state DB at ${o} (open Cursor once first).`)});let u=null,f;if(Ee(s)){if(Ee(a))return c({status:"manual",messages:it(n,`Both a legacy Cursor Anyray backup (${s}) and a current value backup (${a}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{lb(s)?u="sqlite":(Ho(s),u="value")}catch{u=null}if(!u)return c({status:"manual",messages:it(n,`Legacy Cursor Anyray backup at ${s} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(Ee(a))try{p=Ho(a)}catch{return c({status:"manual",messages:it(n,`Existing Cursor backup at ${a} is invalid \u2014 refusing to write or replace recovery data.`)})}if(zc())return c(await $p("apply",t,{status:"manual",messages:it(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Wo(n,r),...u?[`The legacy Anyray backup at ${s} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...u?[`Would migrate the legacy Anyray backup at ${s}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${o}, ${Ee(a)?`retain the original value backup at ${a}`:`create a mode-0600 value backup at ${a}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${zt()}, and register the Anyray retrieval MCP server in ${qt()}.`,...Wo(n,r)]};if(u){try{d.checkpointWal(o)}catch(b){return c({status:"manual",messages:it(n,`Couldn't checkpoint Cursor's state DB at ${o} while migrating the legacy Anyray backup at ${s}${bs(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=Jc(d.readItem(s,Xe)??null,d.readItem(s,ct)??null);else{let b=Ho(s);y=Jc(b.applicationUser,b.openAIKey)}}catch{return c({status:"manual",messages:it(n,`Couldn't read the legacy Anyray backup at ${s} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{d.mutateRows(o,[Tp(d.readItem(o,Xe),y.applicationUser),y.openAIKey===null?{key:ct}:{key:ct,value:y.openAIKey}])}catch{return c({status:"manual",messages:it(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${s} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{hn(s,{force:!0}),hn(`${s}-wal`,{force:!0}),hn(`${s}-shm`,{force:!0}),f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held and removed it.`}catch{f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{d.checkpointWal(o)}catch(y){return c({status:"manual",messages:it(n,`Couldn't checkpoint Cursor's state DB at ${o}${bs(y)} \u2014 refusing to write; set it by hand:`)})}let h;try{h=d.readItem(o,Xe)}catch{return c({status:"manual",messages:it(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=cT(h,n);if(!m)return c({status:"manual",messages:it(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let w={applicationUser:m.value,openAIKey:e.clientKey};if(Ee(a))try{iT(a,w)}catch{return c({status:"manual",messages:it(n,`Couldn't update three-way ownership in the protected Cursor backup at ${a} \u2014 refusing to write; set it by hand:`)})}else try{sT(d,a,o,w)}catch{return c({status:"manual",messages:it(n,`Couldn't create the protected Cursor value backup at ${a} \u2014 refusing to write; set it by hand:`)})}try{d.mutateRows(o,[{key:Xe,value:m.value},{key:ct,value:e.clientKey}])}catch{let y=!0;if(p)try{yb(a,p)}catch{y=!1}return c({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${a}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${a} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}i=await Sb();let g=[];if(!t.preservePendingOp)try{await lr("cursor")}catch{g.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return c({status:"configured",changedFiles:[o],messages:[...f?[f]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${a}).`,"Stored the API key in Cursor's credential row (not shown here).",...g,...Wo(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await P().catch(()=>{}),n=e;if(!Lp(n)){let o=t&&nt(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&Ye(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Ee(Es())||Ee(Ko())||wb()!=="clear"?!1:AT():uT(n,r).routed},async revert(e){let t=Yr(),n=Es(),r=Ko(),o=Ee(n),a=Ee(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${zt()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${zt()} and unregister its owned retrieval MCP server.`]};if((o||a)&&zc()){if(e.fullRevert){let h=await Np(),m=!0;try{await lr("cursor")}catch{m=!1}return{status:"manual",changedFiles:h.changedFiles,messages:[...h.messages,...m?[]:["Could not clear Cursor's stale queue marker."],`Cursor is running, so its saved settings in ${a?r:n} were left in place and nothing was queued. Quit Cursor and re-run --revert to restore them.`]}}return $p("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=ks(),i=!1,c=!1,l,d=[];if(a)try{if(lb(r))if(Ee(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let h=Jc(s.readItem(r,Xe)??null,s.readItem(r,ct)??null);s.mutateRows(t,[Tp(s.readItem(t,Xe),h.applicationUser),h.openAIKey===null?{key:ct}:{key:ct,value:h.openAIKey}]),c=!0}else i=!0,F_(r,t),hn(`${t}-wal`,{force:!0}),hn(`${t}-shm`,{force:!0});else{let h=Ho(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ee(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let m=Jc(h.applicationUser,h.openAIKey);s.mutateRows(t,[Tp(s.readItem(t,Xe),m.applicationUser),m.openAIKey===null?{key:ct}:{key:ct,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${bs(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Ho(n)}catch{return{status:"manual",messages:[`Couldn't read a supported Cursor value backup from ${n}; the backup was retained.`]}}if(l){if(!l.lastWritten)return{status:"manual",messages:[`The Cursor backup at ${n} predates three-way ownership, so Connect cannot prove which current values are still its own. The backup was retained and no hook or MCP cleanup was attempted.`]};if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ee(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let h=CT(s.readItem(t,Xe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,ct);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:ct}:{key:ct,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${bs(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{hn(r,{force:!0}),hn(`${r}-wal`,{force:!0}),hn(`${r}-shm`,{force:!0}),hn(n,{force:!0})}catch{f=!1,u.push("Cursor values were restored, but a recovery sidecar could not be removed; retain it until a later revert can finish cleanup.")}if(!e.preservePendingOp)try{await lr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await Np();return f=f&&p.complete,{status:f?"reverted":"manual",changedFiles:[...o||a?[t]:[],...p.changedFiles],messages:[i?"Restored Cursor's state DB from the legacy Anyray backup.":c?"Restored Cursor's managed settings fields and credential from the legacy Anyray backup while preserving current unrelated settings and rows.":l?"Restored Cursor's managed settings fields and credential from the Anyray backup while preserving current unrelated settings.":"No Cursor row backup was present; only owned hook and MCP integrations were considered for cleanup.",...u,...d.length>0?[`Preserved Cursor values changed after Connect configured them: ${[...new Set(d)].join(", ")}.`]:[],...p.messages,"Restart Cursor."]}}};import{chmod as tP,mkdir as nP,readFile as zb,rm as rP,writeFile as oP}from"node:fs/promises";import{randomUUID as aP}from"node:crypto";import{dirname as sP,join as qb}from"node:path";var ST=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
|
|
108
|
+
`;)r+=1;r-=1;continue}if(o==="/"&&e[r+1]==="*"){let a=e.indexOf("*/",r+2);r=a===-1?e.length:a+1,t+=" ";continue}t+=o}return t},ET=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o===","){let a=r+1;for(;a<e.length&&/\s/.test(e[a]);)a+=1;if(e[a]==="}"||e[a]==="]")continue}t+=o}return t},pr=e=>JSON.parse(ET(ST(e)));import{spawnSync as xT}from"node:child_process";import{platform as IT}from"node:os";var Ib={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},RT=(e,t,n)=>xT(e,t,n),Rb=RT,OT,_T=()=>{let e=OT??IT();if(e==="win32"){let n=Rb(vs("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],Ib);return n.error||n.signal||n.status!==0?!0:/(?:^|\r?\n)"Code\.exe",/iu.test(n.stdout??"")}let t=e==="linux"?[["-f","Visual Studio Code"],["-x","code"]]:[["-f","Visual Studio Code"]];for(let[n,r]of t){let o=Rb("pgrep",[n,r],Ib);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},TT=_T,Rs=()=>TT();var tl={darwinAppName:"Visual Studio Code",darwinBundleId:"com.microsoft.VSCode",win32Image:"Code.exe",linuxProcess:"code",win32Install:[{root:"localAppData",path:"Programs\\Microsoft VS Code\\Code.exe"},{root:"programFiles",path:"Microsoft VS Code\\Code.exe"},{root:"programFilesX86",path:"Microsoft VS Code\\Code.exe"}]};import{execFile as PT}from"node:child_process";import{readdirSync as LT}from"node:fs";import{createHash as Pb,randomBytes as DT,randomUUID as Lb}from"node:crypto";import{chmod as NT,lstat as $T,mkdir as Wp,readFile as Jr,rm as Db,unlink as Nb,writeFile as Kp}from"node:fs/promises";import{homedir as Vo,platform as Gp}from"node:os";import{dirname as $b,join as Os,posix as _b,win32 as MT}from"node:path";import{promisify as FT}from"node:util";var _n="0.1.21";var Xr="8c2875844439f1b8a906d1b16e85cfc04f559096f7af88f6b9a26d877eee1c82",nl="22be5f6ea9b3bf833982e1be741254dba1c37395e5b133caa071f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AAAAAUABQBVAQAAUkEAAAAA";var Te="anyray.anyray-vscode",BT="vscode-handoffs",Mb="vscode-receipts",_s=2,UT=FT(PT),fr={Code:{slug:"code",scheme:"vscode",macAppName:"Visual Studio Code",commands:["code","/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"]},"Code - Insiders":{slug:"code-insiders",scheme:"vscode-insiders",macAppName:"Visual Studio Code - Insiders",commands:["code-insiders","/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin/code-insiders"]},VSCodium:{slug:"vscodium",scheme:"vscodium",macAppName:"VSCodium",commands:["codium","/Applications/VSCodium.app/Contents/Resources/app/bin/codium"]}},HT={Code:{directory:"Microsoft VS Code",executable:"Code.exe"},"Code - Insiders":{directory:"Microsoft VS Code Insiders",executable:"Code - Insiders.exe"},VSCodium:{directory:"VSCodium",executable:"VSCodium.exe"}},WT=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),Fb=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&WT(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ts=e=>{if(Fb(e))try{return new URL(e.trim()).origin}catch{return}},KT=(e,t)=>{if(!e.endsWith(".app"))return!1;let n=e.slice(0,-4);if(n===t)return!0;if(!n.startsWith(`${t} `))return!1;let r=n.slice(t.length+1);return r.length>0&&/^\d+$/.test(r)},GT=e=>{try{return LT(e)}catch{return[]}},jT=(e,t,n)=>{let{macAppName:r,commands:o}=fr[e],a=o[0],s=[];for(let i of["/Applications",_b.join(t,"Applications")])for(let c of n(i))KT(c,r)&&s.push(_b.join(i,c,"Contents/Resources/app/bin",a));return s},VT=(e,t=Gp(),n=Vo(),r=process.env,o=GT)=>{if(t==="darwin")return[...new Set([...fr[e].commands,...jT(e,n,o)])];if(t!=="win32"){let l=fr[e].commands[0];return[...new Set([l,`/usr/bin/${l}`,`/usr/local/bin/${l}`])]}let a=HT[e],s=MT.join,i=r.LOCALAPPDATA??s(n,"AppData","Local"),c=[s(i,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(l=>!!l);return[...new Set([...c.map(l=>s(l,a.directory,a.executable)),fr[e].commands[0]])]},Bb={run:async(e,t)=>({stdout:(await UT(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>DT(24).toString("base64url"),home:"",commandCandidates:e=>VT(e)},jo=(e,t)=>Os(e,".anyray",Mb,`${t}.json`),jp=(e,t)=>Os(e,".anyray",Mb,`${t}.applied.json`),Ub=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&xc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},Hb=async(e,t)=>{let n=await Ub(e,t);if(n)try{let r=await t.run(n.command,["--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===Te.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===_n}catch{return}},Wb=250,YT=9e4,ZT=YT/Wb,XT=async(e,t,n,r)=>{for(let o=0;o<ZT;o++){try{let a=JSON.parse(await Jr(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===_s&&a.action===n?"confirmed":a.extensionVersion!==_n||a.extensionDistSha256!==Xr?"reload-required":a.version===_s&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(Wb)}return"timeout"},JT=async e=>{try{let t=await $T(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},Tb=e=>Pb("sha256").update(e).digest("hex"),zT=async(e=Vo())=>{let t=Buffer.from(Ob,"base64");if(t.length<4||t[0]!==80||t[1]!==75||Tb(t)!==nl)throw new Error("bundled VS Code extension failed integrity validation");let n=Os(e,".anyray","vscode-extension"),r=Os(n,`anyray-vscode-${_n}-${nl.slice(0,12)}.vsix`);try{if(Tb(await Jr(r))===nl)return r}catch{}await Wp(n,{recursive:!0,mode:448});let o=`${r}.${Lb()}.tmp`;try{await Kp(o,t,{mode:384}),await fe(o,r),Gp()!=="win32"&&await NT(r,384)}finally{await Db(o,{force:!0})}return r},Hp=e=>{if(e===void 0)return"null";if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(n=>Hp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Hp(t[n])}`).join(",")}}`},Kb=(e,t,n)=>Pb("sha256").update(Hp({gatewayUrl:Ts(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:_n,extensionDistSha256:Xr,profiles:[...n].sort()})).digest("hex"),qT=async(e,t,n,r,o,a)=>{let s=JSON.parse(await Jr(jp(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==Kb(t,n,r))return!1;let i=JSON.parse(await Jr(jo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===_n&&i.extensionDistSha256===Xr&&i.gatewayUrl===Ts(t.origin)?await Hb(e,a)===!0:!1},QT=async(e,t,n,r)=>{let o=jp(e,t),a=`${o}.${Lb()}.tmp`;try{await Wp($b(o),{recursive:!0,mode:448}),await Kp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
109
|
+
`,{mode:384}),await fe(a,o)}catch{}finally{await Db(a,{force:!0})}},eP=async(e,t)=>{await Nb(jp(e,t)).catch(()=>{})},Gb=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...Bb,...r,home:r.home??Vo()},s=fr[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!Fb(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((g,y,b)=>typeof g.id=="string"&&g.id.length>0&&g.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(g.id)&&typeof g.name=="string"&&g.name.length>0&&g.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(g.name)&&b.findIndex(v=>v.id===g.id)===y);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await Ub(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!op(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,d=a.listProfiles??(g=>cw(g,Gp(),a.home)),u=n==="configure"?await d(e).catch(()=>[]):[];if(n==="configure"&&await qT(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:jo(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let f=a.extensionPath;if(n==="configure"){try{f??=await zT(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await JT(f))return{ok:!1,reason:"extension-missing"}}let p=a.nonce(),h=Os(a.home,".anyray",BT,`${p}.json`),m=jo(a.home,s.slug);await Wp($b(h),{recursive:!0,mode:448}),await Kp(h,`${JSON.stringify({version:_s,action:n,nonce:p,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:_n,expectedExtensionDistSha256:Xr})}
|
|
110
|
+
`,{mode:384});let w={installed:[],failed:[]};try{if(n==="configure"){await a.run(l,["--install-extension",f,"--force"]);for(let y of u)try{await a.run(l,["--profile",y,"--install-extension",f,"--force"]),w.installed.push(y)}catch{w.failed.push(y)}}await a.run(l,["--open-url",`${s.scheme}://${Te}/configure?nonce=${encodeURIComponent(p)}`]);let g=await XT(m,p,n,a);return g!=="confirmed"?{ok:!1,reason:g==="reload-required"?"reload-required":"activation-timeout"}:(n==="configure"?w.failed.length===0&&await QT(a.home,s.slug,Kb(t,o,u),p):await eP(a.home,s.slug),{ok:!0,receipt:m,profiles:w})}catch{return{ok:!1,reason:"failed"}}finally{await Nb(h).catch(()=>{})}},jb=async(e,t=Vo())=>{try{let n=JSON.parse(await Jr(jo(t,fr[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==_n||n.extensionDistSha256!==Xr)}catch{return!1}},Vb=async(e,t=Vo())=>{try{let n=JSON.parse(await Jr(jo(t,fr[e].slug),"utf8"));return n.version!==_s||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},Yb=async(e,t,n=Vo(),r={})=>{try{let o=Ts(t);if(!o)return!1;let a=JSON.parse(await Jr(jo(n,fr[e].slug),"utf8"));if(!(a.version===_s&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===_n&&a.extensionDistSha256===Xr))return!1;let i={...Bb,...r,home:n};return await Hb(e,i)===!0}catch{return!1}};var hr="Anyray",mn="anyray",Qb="--anyray-owner=vscode-profile-v1",Ps=e=>qb(ot(e),"User","chatLanguageModels.json"),iP=e=>qb(ot(e),"User","settings.json"),Ls="github.copilot.advanced",ol="debug.overrideCapiUrl",vt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cP=e=>{if(typeof e!="string")return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&!t.username&&!t.password&&!t.search&&!t.hash&&/^\/v1\/copilot\/[^/]+\/ark_[A-Za-z0-9_-]{20,512}\/?$/.test(t.pathname)}catch{return!1}},ek=e=>{let t=e[Ls];if(!vt(t)||!cP(t[ol]))return{next:e,removed:!1};let n={...t};delete n[ol];let r={...e};return Object.keys(n).length>0?r[Ls]=n:delete r[Ls],{next:r,removed:!0}},Ds="anyray-default",Ns=()=>{let e=(process.env.ANYRAY_COPILOT_MODEL??"").split(",").map(t=>t.trim()).filter(t=>t.length>0&&t.length<=200&&!/[\u0000-\u001f\u007f]/.test(t)).filter((t,n,r)=>r.indexOf(t)===n).slice(0,64);return e.length?e:[Ds]},tk=e=>e===Ds?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),rl=async e=>{if(!await R(e))return{kind:"missing"};try{let t=await zb(e,"utf-8");if(!t.trim())return{kind:"array",entries:[]};let n=JSON.parse(t);return Array.isArray(n)?{kind:"array",entries:n}:{kind:"unrecognized"}}catch{return{kind:"unrecognized"}}},nk=async(e,t)=>{await nP(sP(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${aP()}`;try{await oP(n,`${JSON.stringify(t,null,2)}
|
|
111
|
+
`,{flag:"wx",mode:384}),await fe(n,e),await tP(e,384)}finally{await rP(n,{force:!0}).catch(()=>{})}},Vp=e=>{if(!vt(e))return!1;let t=e,n=Object.keys(t).sort(),r=["apiType",...t.apiKey===void 0?[]:["apiKey"],"models","name","vendor"].sort();return n.length!==r.length||!n.every((o,a)=>o===r[a])||t.name!==hr||t.vendor!=="customendpoint"||t.apiType!=="chat-completions"||!(t.apiKey===void 0||typeof t.apiKey=="string"&&t.apiKey.length>0&&t.apiKey.length<=512&&!/[\u0000-\u001f\u007f]/.test(t.apiKey))||!Array.isArray(t.models)||t.models.length===0||t.models.length>64?!1:t.models.every(o=>{if(!vt(o))return!1;let a=["id","maxInputTokens","maxOutputTokens","name",...o.requestHeaders===void 0?[]:["requestHeaders"],"toolCalling","url","vision"].sort(),s=Object.keys(o).sort();if(s.length!==a.length||!s.every((i,c)=>i===a[c])||typeof o.id!="string"||o.id.length===0||o.id.length>200||o.name!==tk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!vt(o.requestHeaders)||Object.keys(o.requestHeaders).length!==1||typeof o.requestHeaders["x-anyray-metadata"]!="string"||o.requestHeaders["x-anyray-metadata"].length>8192))return!1;try{let i=new URL(o.url);return(i.protocol==="https:"||i.protocol==="http:")&&!i.username&&!i.password&&!i.search&&!i.hash&&i.pathname==="/v1/chat/completions"}catch{return!1}})},Yp=e=>{let t=e.filter(n=>!Vp(n));return{next:t,removed:t.length!==e.length}},lP=async(e,t)=>{let n=Ps(e),r=await rl(n);if(r.kind==="missing")return{changedFiles:[],messages:[],manual:!1};if(r.kind==="unrecognized")return{changedFiles:[],manual:!0,messages:[`Could not recognize ${n}; left it untouched. Remove the legacy "${hr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=Yp(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${hr}" Custom Endpoint from ${n}.`]};try{return await nk(n,o),await re(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${hr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${hr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},dP=async e=>{try{let t=pr(await zb(e,"utf-8"));if(vt(t))return ek(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Ls}.${ol} in ${e}, which uses JSONC that Connect will not rewrite; remove it manually.`]}:{changedFiles:[],messages:[],manual:!1}}catch{}return{changedFiles:[],manual:!0,messages:[`Could not parse ${e}; remove an old Anyray ${Ls}.${ol} value manually if present.`]}},rk=async(e,t)=>{let n=iP(e),r;try{r=await M(n)}catch{return dP(n)}let{next:o,removed:a}=ek(r);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the retired Anyray Copilot debug override from ${n}.`]};try{return await Z(n,o,{backup:!1}),await re(n),{changedFiles:[n],manual:!1,messages:[`Removed the retired Anyray Copilot debug override from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the retired Anyray Copilot debug override from ${n}; remove it manually.`]}}},uP=async(e,t)=>{let n=await lP(e,t),r=await rk(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},ok=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,Qb]}},ak=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},sk=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),pP=e=>Array.isArray(e.args)&&e.args.at(-1)===Qb,ik=(e,t)=>{if(!t.hookBinaryIsDurable()||!vt(e)||!ak(e,["type","command","args"]))return!1;let n=ok(t);return e.type==="stdio"&&e.command===n.command&&sk(e.args,n.args)},fP=(e,t)=>{if(!vt(e)||!ak(e,["type","command","args"])||e.type!=="stdio"||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(i=>typeof i=="string"))return!1;let n=t.mcpServerCommand("profile");if(e.command===n.command&&sk(e.args,n.args))return!0;if(Ge(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===er&&r.at(-1)==="profile"))return!1;let a=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(a))return r.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(a)||r.length!==3)return!1;let s=r[0].replaceAll("\\","/");return!Ge(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},Zp=(e,t)=>ik(e,t)?"exact":vt(e)&&pP(e)||fP(e,t)?"stale-owned":"foreign",Zb=e=>`MCP name conflict in ${e}: servers.${mn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,hP=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let p of a)try{let h=await M(p);if(i){if("servers"in h&&!vt(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${p} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let y=vt(h.servers)?{...h.servers}:{},b=ok(o),v=y[mn],S=v===void 0?void 0:Zp(v,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(Zb(p));continue}if(t){d+=1;continue}y[mn]=b,f.push({path:p,next:{...h,servers:y},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!vt(h.servers)||!(mn in h.servers))continue;if(Zp(h.servers[mn],o)==="foreign"){u=!0,l.push(Zb(p));continue}if(t)continue;let w={...h.servers};delete w[mn];let g={...h};Object.keys(w).length===0?delete g.servers:g.servers=w,f.push({path:p,next:g,backup:!1,clearBackupAfter:!0})}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let p of f)try{await Z(p.path,p.next,p.backup?{}:{backup:!1}),p.clearBackupAfter&&await re(p.path),c.push(p.path),i&&(d+=1)}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p.path} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`);break}return i?l.unshift(t?d===a.length?`Would register the Anyray retrieval MCP server in ${a.length} VS Code user profile config(s).`:`Would register the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); resolve the conflicts below first.`:d===a.length?`Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) in ${a.length} VS Code user profile config(s).`:`Registered the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); see the profile-specific errors below.`):n?l.unshift(t?`Would skip the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary.`:`Skipped the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary; removed any stale owned registration. Re-run via the installer or a global install to enable retrieval.`):l.unshift(`${t?"Would skip":"Skipped"} the Anyray retrieval MCP server because this VS Code build predates profile-scoped mcp.json support (${ow}+).`),{changedFiles:c,messages:l,manual:u}},mP=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await R(c))try{let l=await M(c);if(!vt(l.servers)||!(mn in l.servers)||Zp(l.servers[mn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[mn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await Z(c,u,{backup:!1}),await re(c),a.push(c)}catch{}return t&&i>0?s.push(`would remove the Anyray retrieval MCP server from ${i} VS Code user profile config(s)`):a.length>0&&s.push("Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."),{changedFiles:a,messages:s,manual:!1}},ck=e=>[...e.installed.length>0?[`Also installed into ${e.installed.length} additional VS Code profile(s): ${e.installed.join(", ")}. Config is shared through SecretStorage \u2014 no further steps.`]:[],...e.failed.length>0?[`Couldn\u2019t install into profile(s): ${e.failed.join(", ")}. Open VS Code with that profile and use \u201CApply Extension to all Profiles\u201D, or re-run anyray-connect.`]:[]],lk=()=>`${Te} is already installed and configured for this gateway \u2014 skipped the VSIX reinstall and the VS Code URI confirmation prompt. (Run --revert first to force re-delivery.)`,Xb=e=>[`${Te} mirrors the GitHub Copilot models available to this VS Code install.`,`Gateway: ${e.origin} (client key stored by VS Code SecretStorage).`,"Mode: SUBSCRIPTION \u2014 requests use your existing Copilot sign-in and model; Anyray supplies a supported before-request optimization provider.","Inline completions remain native GitHub Copilot traffic. Choose an \u201CAnyray \xB7 \u2026\u201D model in Chat for optimized requests.",'Copilot\u2019s internal utility models (chat titles, summaries) keep working with an Anyray main model: the extension sets VS Code\u2019s chat.byokUtilityModelDefault to "copilot" unless you already set it yourself.',"VS Code profiles scope extensions; Connect installs the provider into every profile registered at apply time. A profile created later needs a Connect re-run (or VS Code\u2019s \u201CApply Extension to all Profiles\u201D action).","Copilot Business/Enterprise administrators must allow language-model providers in GitHub\u2019s Bring Your Own Language Model Key policy."],dk=(e,t,n,r)=>({runMcp:o=>hP(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):uP(e,o)}),yP=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=dk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${Te} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...Xb(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${Te}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"copilot-seat"});if(!d.ok)return{status:"manual",messages:[d.reason==="reload-required"?`A newer ${Te} build was installed, but ${e} is still running the previous build. Reload VS Code completely, then re-run anyray-connect.`:d.reason==="cli-not-found"?`The ${e} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`:d.reason==="unsupported-version"?`The Anyray language-model provider requires VS Code ${Ec} or newer. Upgrade ${e}, then re-run anyray-connect; no extension configuration was written.`:d.reason==="unsafe-gateway"?"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.":d.reason==="extension-missing"?`This anyray-connect installation is missing its bundled ${Te} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`:`VS Code did not confirm the one-time ${Te} configuration. Open VS Code and re-run anyray-connect.`]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[lk()]:[],...Xb(t),...d.alreadyCurrent?[]:ck(d.profiles),...f.messages,...u.messages]}},Jb=e=>[`${Te} exposes the configured Anyray gateway models without writing a key to chatLanguageModels.json.`,`Gateway: ${e.origin} (personal client key and attribution stored together in VS Code SecretStorage).`,"Mode: API KEY \u2014 the extension streams normal /v1/chat/completions requests through Anyray. Text chat only: the models register without tool calling (the OpenAI bridge cannot carry VS Code's structured tool results).",`Models in the picker: ${Ns().join(", ")}.`,"Inline GitHub Copilot completions remain native GitHub traffic; choose an Anyray model in Chat for gateway-routed requests.",'Copilot\u2019s internal utility models (chat titles, summaries) follow the selected Anyray model: the extension sets VS Code\u2019s chat.byokUtilityModelDefault to "mainAgent" unless you already set it yourself.',"VS Code profiles scope extensions; Connect installs the provider into every profile registered at apply time. A profile created later needs a Connect re-run (or VS Code\u2019s \u201CApply Extension to all Profiles\u201D action).","Copilot Business/Enterprise administrators must allow language-model providers in GitHub\u2019s Bring Your Own Language Model Key policy."],gP=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=dk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${Te} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...Jb(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${Te}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Ns().map(p=>({id:p,name:tk(p)}))});if(!d.ok)return{status:"manual",messages:[d.reason==="reload-required"?`A newer ${Te} build was installed, but ${e} is still running the previous build. Reload VS Code completely, then re-run anyray-connect.`:d.reason==="cli-not-found"?`The ${e} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`:d.reason==="unsupported-version"?`The Anyray language-model provider requires VS Code ${Ec} or newer. Upgrade ${e}, then re-run anyray-connect; no extension configuration was written.`:d.reason==="unsafe-gateway"?"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.":d.reason==="extension-missing"?`This anyray-connect installation is missing its bundled ${Te} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`:`VS Code did not confirm the one-time ${Te} gateway API configuration. Open VS Code and re-run anyray-connect.`]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[lk()]:[],...Jb(t),...d.alreadyCurrent?[]:ck(d.profiles),...f.messages,...u.messages]}},wP=async(e,t,n)=>{let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null};let o=[];for(let s of r){if(!await R(s))return{registered:!1,command:null};try{let i=await M(s),c=vt(i.servers)?i.servers[mn]:void 0;if(!ik(c,n))return{registered:!1,command:null};o.push(c.command)}catch{return{registered:!1,command:null}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var bP=async(e={installedVariant:Ic,remoteServerVariant:ip,isRemoteDevContext:ts})=>{let t=await e.installedVariant();if(t)return{variant:t,remote:!1};if(!e.isRemoteDevContext())return{remote:!1};let n=await e.remoteServerVariant();return n?{variant:n,remote:!0}:{remote:!1}},kP={installedVariant:Ic,remoteServerVariant:ip,detectVscodeLmProviderEligibility:uw,configureVscodeExtension:Gb,vscodeExtensionPointsAt:Yb,vscodeExtensionAwaitingReload:jb,vscodeExtensionReceiptMode:Vb,hookBinaryIsDurable:ce,hookBinaryPath:Oe,mcpServerCommand:je,vscodeUserMcpConfigPaths:lw,isRemoteDevContext:ts},AP=(e={})=>{let t={...kP,...e},n=()=>bP(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Rs,quitTarget:tl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Uo(r,!0)}`:Ps(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ie(r.clientKey))return{status:"manual",messages:["Enrollment required: Copilot setup needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; no VS Code configuration was written."]};let{variant:a,remote:s}=await n();if(!a)return{status:"manual",messages:[t.isRemoteDevContext()?"No VS Code server found here yet \u2014 this looks like a dev container, Codespace, or SSH remote. `--tools copilot` now configures the Anyray provider directly in a remote VS Code window, but only after VS Code has attached to this machine and installed its server. Open this machine with the VS Code Remote-SSH (or Dev Containers) extension, then re-run anyray-connect --tools copilot in that window\u2019s integrated terminal. To route this shell through Anyray without the Copilot UI, use an in-container tool instead: anyray-connect --tools opencode --sso <link> --subscription.":"No VS Code install found. Install VS Code, then re-run anyray-connect; the personal key will be transferred directly into SecretStorage."]};let i=await t.detectVscodeLmProviderEligibility(a);if(i.status==="needs-update")return{status:"manual",messages:[`${a} ${i.version??""} cannot expose public third-party models in Chat's picker. Upgrade to VS Code ${Ec} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||aw(i.version);return J(r,"copilot")?yP(a,r,o,t.configureVscodeExtension,c,s,t):gP(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?wP(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ts(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await rl(Ps(o));if(s.kind==="array"){let c=s.entries.find(Vp)?.models?.[0]?.url;if(typeof c=="string"&&new URL(c).origin===a)return!0}return!1},async routingExpected(r){if(r.includes("copilot"))return!0;let{variant:o}=await n();return o?(await t.detectVscodeLmProviderEligibility(o)).status!=="needs-update":!1},async routingPendingReload(){let{variant:r}=await n();return r?t.vscodeExtensionAwaitingReload(r):!1},async inferenceAuthLanes(){try{let{variant:r}=await n();if(!r)return["unknown"];let o=await rl(Ps(r));if(o.kind==="array"&&o.entries.some(Vp))return["api_key"];let a=await t.vscodeExtensionReceiptMode(r);if(a==="copilot-seat")return["subscription"];if(a==="gateway-api")return["api_key"]}catch{}return["unknown"]},async revert(r){let{variant:o,remote:a}=await n();if(!o)return{status:"not-found",messages:["no VS Code install found \u2014 nothing to revert"]};let s=await mP(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await rk(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${Te} to clear its global configuration and SecretStorage key`);else{let y=await t.configureVscodeExtension(o,void 0,"reset");y.ok?(c=!0,d=y.receipt,u.push(`Cleared ${Te} gateway configuration and secret.`)):(l=!0,u.push(y.reason==="cli-not-found"?`The ${o} command-line launcher was not found, so Anyray could not ask ${Te} to clear its SecretStorage configuration. Install the launcher and re-run revert.`:`VS Code did not confirm the ${Te} reset. Open VS Code and re-run revert.`))}let f=Ps(o),p=await rl(f),h=p.kind==="missing"||p.kind==="array"&&!Yp(p.entries).removed,m=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),h)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:m.length?m:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:m.length?m:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:m,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(p.kind==="unrecognized")return{status:"manual",changedFiles:m.length?m:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${hr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=Yp(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${hr} Custom Endpoint from ${f}`]};await nk(f,w);let g=[...u,`Removed the ${hr} Custom Endpoint from ${f}.`];return await re(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},uk=AP();import{accessSync as KP,constants as Ck,statSync as GP}from"node:fs";import{readFile as vk,rm as Ms}from"node:fs/promises";import{homedir as of,platform as _k}from"node:os";import{delimiter as jP,join as af,resolve as VP}from"node:path";import{execFile as xP}from"node:child_process";import{readFile as IP}from"node:fs/promises";import{homedir as zp,platform as RP}from"node:os";import{join as $s}from"node:path";import{join as CP}from"node:path";var Xp="Iv1.b507a08c87ecfe98",vP="https://github.com/login/device/code",SP="https://github.com/login/oauth/access_token",EP="read:user",pk=1e4,Yo=()=>CP(q(),"copilot-seat-login.json"),fk={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},Jp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hk=async(e={})=>{let t={...fk,...e};try{let n=await t.fetch(vP,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Xp,scope:EP}),signal:AbortSignal.timeout(pk)});if(!n.ok)return;let r=await n.json();if(!Jp(r))return;let o=r.device_code,a=r.user_code,s=r.verification_uri;if(typeof o!="string"||typeof a!="string"||typeof s!="string")return;let i=r.interval,c=r.expires_in;return{deviceCode:o,userCode:a,verificationUri:s,intervalSeconds:typeof i=="number"&&i>0?i:5,expiresInSeconds:typeof c=="number"&&c>0?c:900}}catch{return}},mk=async(e,t={})=>{let n={...fk,...t},r=n.now()+e.expiresInSeconds*1e3,o=e.intervalSeconds*1e3;for(;n.now()<r;){await n.sleep(o);try{let s=await(await n.fetch(SP,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Xp,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(pk)})).json();if(!Jp(s))continue;let i=s.access_token;if(typeof i=="string"&&i.length>0)return{status:"ok",token:i};let c=s.error;if(c==="authorization_pending")continue;if(c==="slow_down"){let l=s.interval;o=(typeof l=="number"&&l>0?l:o/1e3+5)*1e3;continue}return c==="access_denied"?{status:"denied"}:c==="expired_token"?{status:"expired"}:{status:"failed"}}catch{continue}}return{status:"expired"}},yk=async(e,t)=>{let n=Yo();return await he(n,`${JSON.stringify({token:e,clientId:Xp,mintedAtIso:t},null,2)}
|
|
112
|
+
`),n},al=async()=>{try{let e=await M(Yo());if(!Jp(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var OP=5e3,qp=5e3,_P=["copilot-cli","CopilotCLI"],TP="https://api.github.com/copilot_internal/user",wk="~/.copilot/config.json",bk="macOS Keychain (Copilot CLI)",kk=e=>e===wk||e===bk,Zo=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),Qt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),PP=()=>process.env.XDG_CONFIG_HOME?.trim()||$s(zp(),".config"),LP=()=>process.env.XDG_DATA_HOME?.trim()||$s(zp(),".local","share"),DP=async()=>{try{let e=await IP($s(zp(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return Zo(t)?t:void 0}catch{}},NP=async e=>{try{let t=await M($s(PP(),"github-copilot",e));if(!Qt(t))return;for(let n of Object.values(t))if(Qt(n)&&Zo(n.oauth_token))return n.oauth_token}catch{}},$P=async()=>{try{let e=await M($s(LP(),"opencode","auth.json")),t=Qt(e)?e["github-copilot"]:void 0;if(!Qt(t)||t.type!=="oauth")return;if(Zo(t.access))return t.access;if(Zo(t.refresh))return t.refresh}catch{}},MP=(e,t)=>new Promise((n,r)=>{try{xP(e,[...t],{timeout:OP},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),FP=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return Zo(r)?r:void 0}catch{return}},BP=async(e=MP)=>{for(let t of _P){let n=await FP(t,e);if(n)return n}};var sl={env:process.env,platform:RP,tokenFromDeviceLogin:al,tokenFromCopilotCliConfig:DP,tokenFromSharedConfig:NP,tokenFromOpenCode:$P,tokenFromKeychain:BP,fetch:(...e)=>fetch(...e)},UP=new Set([401,403,404]),Ak=/^[a-z][a-z0-9-]{0,30}$/,HP=e=>e!=="default"&&Ak.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",WP=e=>typeof e!="string"?"default":/^https:\/\/api\.([a-z][a-z0-9-]{0,30})\.githubcopilot\.com\/?$/.exec(e.trim())?.[1]??"default",Qp=async(e,t={})=>{let n={...sl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),qp);try{let a=await n.fetch(TP,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=Qt(i)&&Qt(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:WP(s)}}return{verdict:UP.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var Xo=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${Ak.test(n)?n:"default"}/header/models`,a=await gk(o,e,r.clientKey,t);if(a.length>0)return a}return gk(`${HP(n)}/models`,e,void 0,t)},gk=async(e,t,n,r={})=>{let o={...sl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),qp);try{let i=await o.fetch(e,{headers:{authorization:`Bearer ${t}`,...n?{"x-anyray-api-key":n}:{}},signal:a.signal});if(!i.ok)return[];let c=await i.json(),l=Qt(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!Qt(u))continue;let f=u.id;if(typeof f!="string"||f.length===0||u.model_picker_enabled!==!0)continue;let p=u.policy;if(Qt(p)&&p.state!=="enabled")continue;let h=u.supported_endpoints,m=Array.isArray(h)?h.filter(E=>typeof E=="string"):[],w=u.capabilities,g=Qt(w)?w.limits:void 0,y=E=>{let x=Qt(g)?g[E]:void 0;return typeof x=="number"&&Number.isFinite(x)&&x>0?Math.floor(x):void 0},b={id:f,endpoints:m},v=y("max_prompt_tokens"),S=y("max_output_tokens");v!==void 0&&(b.maxPromptTokens=v),S!==void 0&&(b.maxOutputTokens=S),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},il=async(e,t,n,r={})=>{let o={...sl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),qp);try{let i=/\/responses\/?$/.test(new URL(e).pathname),c=await o.fetch(e,{method:"POST",headers:{...t,"content-type":"application/json"},body:JSON.stringify(i?{model:n,max_output_tokens:16,input:"ping"}:{model:n,max_tokens:1,messages:[{role:"user",content:"ping"}]}),signal:a.signal});return c.ok?"ok":c.status===400||c.status===404||c.status===422?"rejected":"unreachable"}catch{return"unreachable"}finally{clearTimeout(s)}},cl=async(e={},t={})=>{let n={...sl,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return Zo(a)?a:void 0}},{source:"~/.config/github-copilot/apps.json",read:()=>n.tokenFromSharedConfig("apps.json")},{source:"~/.config/github-copilot/hosts.json",read:()=>n.tokenFromSharedConfig("hosts.json")},{source:"OpenCode github-copilot login",read:()=>n.tokenFromOpenCode()},{source:"Anyray Copilot sign-in (device login)",read:()=>n.tokenFromDeviceLogin()},...e.allowKeychainPrompt===!0&&n.platform()==="darwin"?[{source:bk,read:()=>n.tokenFromKeychain()}]:[],{source:wk,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await Qp(s,t);if(i.verdict==="no-copilot"){o.push(a.source);continue}return{token:{token:s,source:a.source},rejected:o,capiSegment:i.capiSegment}}return{rejected:o}};var Qr="copilot-cli",yn="copilot-cli",YP=Rs,ZP=()=>YP()?["VS Code is open \u2014 its Copilot CLI runs inside the extension host, which","captured your shell environment when the editor launched. Restart VS Code,","or its CLI chat and Autopilot sessions stay on native GitHub traffic and","never reach the gateway (no spend, no traces) even though this block is set."]:[],Tk=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],sf=()=>Object.fromEntries(Tk.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),ef=()=>af(of(),".anyray","copilot-cli.sh"),Pk="# Managed by anyray-connect. Do not source this file anywhere else.",Sk=e=>e.split(/\r?\n/,1)[0]===Pk,XP=["COPILOT_PROVIDER_TYPE","COPILOT_PROVIDER_BASE_URL","COPILOT_PROVIDER_WIRE_API","COPILOT_PROVIDER_HEADERS","COPILOT_MODEL","COPILOT_PROVIDER_MAX_PROMPT_TOKENS","COPILOT_PROVIDER_MAX_OUTPUT_TOKENS","COPILOT_PROVIDER_API_KEY"],ll="COPILOT_PROVIDER_API_KEY",Ek=e=>e.startsWith(`export ${ll}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Pn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",JP=()=>Ns()[0],Fs=(e="default")=>`/copilot/${e}/header`,yz=Fs(),zr=e=>e.replace(/\/+$/,""),zP=(e,t="default")=>`${zr(e.openaiBaseUrl)}${Fs(t)}`,tf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),rf="claude-sonnet-5",qP=()=>{let e=Ns()[0];return e===Ds?rf:e},Lk=e=>e.endpoints.includes(Pn(e.id)==="responses"?"/responses":"/chat/completions"),cf=e=>{let t=e.filter(Lk),n=a=>{let s=/^claude-sonnet-(\d+(?:\.\d+)*)$/.exec(a);return s?s[1].split(".").map(Number):void 0},r=t.map(a=>({m:a,version:n(a.id)})).filter(a=>!!a.version).sort((a,s)=>xk(a.version,s.version)?-1:xk(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var xk=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n+=1){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r>0}return!1},Ik=(e,t,n,r,o,a="default")=>{let s=le({...e.metadata,tool:Qr}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...Tk];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Se(zP(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Pn(t)}'`,`export COPILOT_MODEL=${Se(t)}`,...o?.maxPromptTokens?[`export COPILOT_PROVIDER_MAX_PROMPT_TOKENS='${o.maxPromptTokens}'`]:[],...o?.maxOutputTokens?[`export COPILOT_PROVIDER_MAX_OUTPUT_TOKENS='${o.maxOutputTokens}'`]:[],...i.length>0?[`export COPILOT_PROVIDER_HEADERS=${Se(i.join(`
|
|
113
|
+
`))}`]:[],`export ${ll}=${Se(n)}`]},nf=(e,t,n)=>{let r=le({...e.metadata,tool:Qr});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Se(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Pn(t)}'`,`export COPILOT_MODEL=${Se(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${Se(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${ll}=${Se(n)}`]:[]]},QP=(e,t)=>t||!J(e,"copilot"),Rk=()=>{let e=XP.filter(t=>(process.env[t]??"")!=="");return e.length===0?[]:[`This shell still exports ${e.join(", ")} \u2014 Copilot CLI keeps using BYOK until you`,`run \`unset ${e.join(" ")}\` or open a new terminal (fully quit a long-lived parent app).`]},Ok=(e,t=[])=>["Left on native GitHub Copilot inference \u2014 a Copilot seat was detected, but no","Copilot sign-in Connect can read. To route the CLI through Anyray with billing","KEPT on your Copilot plan, give Connect a seat token and re-run:",...e==="darwin"?[" - run `copilot` once and `/login` (macOS Keychain; read on",` \`anyray-connect --tools ${Qr}\`), or`]:[" - run `copilot` once and `/login` (say YES to storing credentials locally),"," then re-run \u2014 Connect reads the sign-in left in ~/.copilot/ or"," ~/.config/github-copilot/ on any run, with no extra flag, or"]," - set COPILOT_GITHUB_TOKEN to a Copilot OAuth token, or sign into"," OpenCode\u2019s github-copilot provider.",...t.length>0?[`GitHub rejected the sign-in Connect did find (${t.join(", ")}):`,"it is expired, or its account holds no Copilot seat. Sign in again."]:[],"To route on org API billing instead (replaces seat inference), re-run with `--org`."],eL=(e=process.env.PATH,t=_k())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(jP)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=VP(o,n);try{if(!GP(a).isFile())continue;return KP(a,t==="win32"?Ck.F_OK:Ck.X_OK),a}catch{}}},tL=()=>af(of(),".copilot","config.json"),Tn=()=>af(of(),".copilot","mcp-config.json"),qr="anyray",nL=()=>({type:"local",...je("profile"),tools:["*"]}),mr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rL=async()=>{let e=Tn(),t;try{t=await M(e)}catch{return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because ${e} could not be parsed; it was left unchanged.`}}if("mcpServers"in t&&!mr(t.mcpServers))return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because mcpServers in ${e} is not an object; it was left unchanged.`};let r=(mr(t.mcpServers)?t.mcpServers:{})[qr];return r!==void 0&&!Zt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${qr} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},oL=async e=>{let t=Tn(),n=e.json,r=mr(n.mcpServers)?n.mcpServers:{};r[qr]=nL(),n.mcpServers=r,await Z(t,n)},aL=async()=>{let e=Tn(),t;try{let r=await M(e);if(!mr(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!mr(n)||!(qr in n)||!Zt(n[qr],"profile")?!1:(delete n[qr],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Ms(e,{force:!0}):await Z(e,t,{backup:!1}),await re(e),!0)},sL={resolveCopilotCommand:eL,platform:_k,detectCopilotSeat:cp,discoverSeatToken:cl,readDeviceLoginToken:al,fetchSeatModelCatalog:Xo,probeSeatChatModel:il},iL=e=>`'${e.replace(/'/g,"''")}'`,cL=e=>e.split(`
|
|
114
|
+
`).map(iL).join(" + [Environment]::NewLine + "),lL=(e={})=>{let t={...sL,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Uc(Ct(),yn))?.find(c=>c.startsWith("export COPILOT_PROVIDER_BASE_URL="));if(i)return i.slice(i.indexOf("=")+1).replace(/^'|'$/g,"")},o=(s,i)=>s!==void 0&&zr(s)===`${zr(i)}/v1`,a=(s,i)=>s!==void 0&&tf(s)&&zr(s).startsWith(`${zr(i)}/v1/copilot/`);return{id:Qr,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Rs,quitTarget:tl},async usesDynamicCredential(s){let i=await r();return a(i,s)||!o(i,s)?!1:!await R(ef())},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=tL();return await R(i)?{installed:!0,detail:i}:{installed:!1,detail:"no `copilot` on PATH and no ~/.copilot state"}},async apply(s,i){let c=Ct(),l=async(E,x,A)=>{let I=E.filter(Ek),T=E.filter(xe=>!Ek(xe)),B=ef(),X=[...T,...I.length>0?[`[ -r ${Se(B)} ] && . ${Se(B)}`]:[]],V=await R(B),W=V?await vk(B,"utf8"):void 0,z=W===void 0||Sk(W);if(I.length>0&&!z)return{status:"manual",messages:[`Refused to overwrite user-managed ${B}; move or rename that file, then run Connect again.`]};let me=ce(),De=me?await rL():void 0,ee=[`${c} \u2190 managed Anyray block (${yn})`,...x.map(xe=>` ${xe}`),...I.length>0?[`${B} \u2190 owner-only credential (mode 0600)`]:["No key exported \u2014 the local refresh daemon injects a freshly minted","key per request, so a running CLI session never carries a stale one."],...A,De?.status==="skipped"?De.message:me?`${Tn()} \u2190 Anyray retrieval MCP server (anyray_retrieve / anyray_recall)`:`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable retrieval.`,"Inline `copilot` completions and GitHub-hosted features stay native GitHub traffic.",`Run \`source ${c}\` or open a new terminal to apply.`,...ZP()];if(i.dryRun)return{status:"configured",messages:ee};let Fe=!1;De?.status==="installable"&&(await oL(De),Fe=!0);try{I.length>0?await he(B,[Pk,...I,""].join(`
|
|
115
|
+
`)):V&&z&&await Ms(B,{force:!0}),await Bc(c,X,yn)}catch(xe){try{W!==void 0&&z?await he(B,W):z&&await Ms(B,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw xe}return{status:"configured",messages:ee,changedFiles:[c,...I.length>0||V&&z?[B]:[],...Fe?[Tn()]:[]]}},d=await r(),u=d!==void 0&&!tf(d),f=s.authMode==="placeholder",p=u&&!s.viaLocalProxy,h=u&&(!p||!J(s,"copilot")),m=f?void 0:await t.readDeviceLoginToken().catch(()=>{}),w=f||h&&!m?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),g=w.token,y=w.rejected;if(g){let E=w.capiSegment??"default",x=qP(),A=x!==rf||!!process.env.ANYRAY_COPILOT_MODEL,I=await t.fetchSeatModelCatalog(g.token,{},E,{laneOrigin:zr(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),T=I.find(ee=>ee.id===x);if(!A){let ee=cf(I);if(T=ee[0],!i.dryRun&&ee.length>0){let Fe=H=>`${zr(s.origin)}/v1${Fs(E)}/${Pn(H)==="responses"?"responses":"chat/completions"}`,xe={...sf(),authorization:`Bearer ${g.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},_=new Set,L;for(let H of ee.slice(0,4)){let ye=await t.probeSeatChatModel(Fe(H.id),xe,H.id);if(ye==="ok"){L=H;break}if(ye==="unreachable")break;_.add(H.id)}T=L??ee.find(H=>!_.has(H.id))??ee[0]}x=T?.id??rf}let B=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,X=B&&s.clientKey?Nt(B):B,V=Ik(s,x,g.token,B,T,E),W=Ik(s,x,Nt(g.token),X,T,E),z=Pn(x),me=I.filter(ee=>Lk(ee)&&Pn(ee.id)===z).map(ee=>ee.id).filter(ee=>ee!==x),De=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${g.source}).`,`Model: ${x}${A?" (pinned via ANYRAY_COPILOT_MODEL)":I.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...I.length===0&&kk(g.source)?["GitHub served no current models for this sign-in \u2014 the Copilot CLI's own login is","entitled to legacy models only. Fix it with: `anyray-connect copilot-login`","(one browser step), then re-run this command."]:[],...me.length>0?[`Your plan also serves: ${me.slice(0,8).join(", ")}${me.length>8?", \u2026":""} \u2014 switch anytime with \`copilot --model <id>\`.`]:[]];return n()?{status:"manual",messages:["Windows: run these in PowerShell (persists user env), then restart your terminal \u2014",...W.map(ee=>{let Fe=ee.indexOf("="),xe=ee.slice(7,Fe),_=ee.slice(Fe+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${xe}', ${cL(_)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${g.source}, and the gateway key from \`anyray-connect print-key\`.)`,...De]}:l(V,W,De)}if(!QP(s,h)){if(p&&!i.dryRun){let E=Ct();if(await gs(E,yn))return{status:"reverted",changedFiles:[E],messages:[`removed a stale Anyray ${yn} block from ${E}`,"It routed the CLI on ORG API billing, which predates the Copilot","seat lane and is not a lane you chose. Nothing replaces it yet:",...Ok(t.platform(),y),...Rk()]}}return{status:"held",messages:[...p&&i.dryRun?[`would remove a stale Anyray ${yn} block from ${Ct()} (org lane, not chosen)`]:[],...Ok(t.platform(),y)]}}let b=JP(),v=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,S=v&&s.clientKey?Nt(v):v;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...nf(s,b,S).map(E=>{let[x,...A]=E.replace(/^export /,"").split("=");return` setx ${x} "${A.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${ll} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(nf(s,b,v),nf(s,b,S),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===Ds?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=Ct(),c=ef(),l=await R(c),d=l?Sk(await vk(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${yn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Tn()} if registered`,...await R(Yo())?[`would remove the Copilot sign-in Connect minted (${Yo()})`]:[]]};let u=await gs(i,yn);d&&await Ms(c,{force:!0});let f=await aL(),p=Yo(),h=await R(p);h&&await Ms(p,{force:!0});let m=[...u?[i]:[],...d?[c]:[],...f?[Tn()]:[],...h?[p]:[]];return{status:m.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${yn} block from ${i}`:`no Anyray ${yn} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...h?[`removed the Copilot sign-in Connect minted (${p})`]:[],...f?[`removed the Anyray MCP server from ${Tn()}`]:[],...Rk()],changedFiles:m.length>0?m:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){try{let s=await M(Tn()),i=mr(s)?s.mcpServers:void 0,c=mr(i)?i[qr]:void 0;return!mr(c)||!Zt(c,"profile")?{registered:!1,command:null}:{registered:!0,command:typeof c.command=="string"?c.command:null}}catch{return{registered:!1,command:null}}},async inferenceAuthLanes(){try{let s=await r();return s===void 0?["native"]:tf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(Qr)?!0:!await t.detectCopilotSeat()}}},Dk=lL();import{homedir as Wk}from"node:os";import{join as gr}from"node:path";import{constants as pL,chmod as fL,copyFile as hL,readFile as pl}from"node:fs/promises";import{applyEdits as mL,modify as yL}from"jsonc-parser";import{readFile as Nk,rm as dL}from"node:fs/promises";var $k="// Managed by anyray-connect: OpenCode trim carrier v1",uL=5e3,lf=e=>`${$k}
|
|
116
116
|
import { spawn } from "node:child_process"
|
|
117
117
|
|
|
118
118
|
const hookCommand = ${JSON.stringify([e.command,...e.args])}
|
|
119
|
-
const hookTimeoutMs = ${
|
|
119
|
+
const hookTimeoutMs = ${uL}
|
|
120
120
|
|
|
121
121
|
const invokeHook = (payload) =>
|
|
122
122
|
new Promise((resolve) => {
|
|
@@ -183,38 +183,38 @@ export const AnyrayTrimPlugin = async () => ({
|
|
|
183
183
|
}
|
|
184
184
|
},
|
|
185
185
|
})
|
|
186
|
-
`,
|
|
187
|
-
`)?"owned":"foreign":"absent"
|
|
188
|
-
`,r=n.trim()?
|
|
186
|
+
`,Bs=async e=>await R(e)?(await Nk(e,"utf-8")).startsWith(`${$k}
|
|
187
|
+
`)?"owned":"foreign":"absent",Mk=async(e,t)=>{let n=lf(t),r=await Bs(e);return r==="foreign"?"foreign":r==="owned"&&await Nk(e,"utf-8")===n?"unchanged":(await he(e,n),"installed")},df=async e=>{let t=await Bs(e);return t!=="owned"?t:(await dL(e,{force:!0}),"removed")};var uf="https://opencode.ai/config.json",Nn="x-anyray-metadata",Mt="x-anyray-api-key",pf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Ln="Authorization",yr=["anthropic","openai"],$n="github-copilot",gL="header",Dn="anyray",wL=()=>process.env.XDG_CONFIG_HOME?.trim()||gr(Wk(),".config"),bL=()=>process.env.XDG_DATA_HOME?.trim()||gr(Wk(),".local","share"),fl=()=>gr(wL(),"opencode"),dl=()=>gr(fl(),"plugins","anyrayTrim.js"),Kk=()=>gr(bL(),"opencode"),Gk=async()=>{try{let e=await pl(gr(Kk(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return U(t)?{chatGptOAuth:U(t.openai)&&t.openai.type==="oauth",readable:!0}:{chatGptOAuth:!1,readable:!1}}catch(e){return e.code==="ENOENT"?{chatGptOAuth:!1,readable:!0}:{chatGptOAuth:!1,readable:!1}}},Fk=async()=>(await Gk()).chatGptOAuth,kL=["opencode.jsonc","opencode.json","config.json"],zo=async()=>{let e=fl(),t=[];for(let n of kL){let r=gr(e,n);await R(r)&&t.push(r)}return t},Bk=async()=>(await zo())[0]??gr(fl(),"opencode.json"),Jo=async e=>{let t=await R(e),n=t?await pl(e,"utf8"):`{}
|
|
188
|
+
`,r=n.trim()?pr(n):{};if(!U(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},jk=(e,t,n=[])=>{if(U(e)&&U(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...jk(e[o],t[o],[...n,o])):r.push({path:[...n,o],value:t[o]}):r.push({path:[...n,o],value:void 0});return r}return JSON.stringify(e)===JSON.stringify(t)?[]:[{path:n,value:t}]},Uk=async(e,t,n,r)=>{let o=jk(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await hL(e,`${e}.anyray-bak`,pL.COPYFILE_EXCL),await fL(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await he(`${e}.anyray-bak`,`{}
|
|
189
189
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
190
190
|
`)?`\r
|
|
191
191
|
`:`
|
|
192
|
-
`},s=t.raw;for(let i of o)s=
|
|
192
|
+
`},s=t.raw;for(let i of o)s=mL(s,yL(s,i.path,i.value,{formattingOptions:a}));return await he(e,s.endsWith(`
|
|
193
193
|
`)?s:`${s}
|
|
194
|
-
`),!0},uL=async e=>{try{let t=ur(await dl(`${e}.anyray-bak`,"utf8"));return U(t)?t:void 0}catch{return}},pf=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",ff=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${pf()}/${iL}`,U=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},pL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===mr[0]||n===mr[1]||n===Nn?[]:U(r)&&U(r.options)&&wf(r.options.baseURL,t)?[n]:[]),hf=/claude/i,bf=["model","small_model"],jk=(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)||!hf.test(o)))return`${mr[0]}/${o}`},mf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)mf(n,t);return t}if(!U(e))return t;for(let[n,r]of Object.entries(e))bf.includes(n)&&typeof r=="string"?t.push(r):mf(r,t);return t},fL=(e,t,n)=>{if(!U(e)||!U(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>hf.test(a)))return!1;let o=`${n}/`;return mf(t).filter(a=>a.startsWith(o)).every(a=>hf.test(a.slice(o.length)))},yf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>yf(o,t,n));if(!U(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=bf.includes(o)?jk(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=yf(a,t,n)}return r},gf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>gf(o,t[a],n));if(!U(e)||!U(t))return e;let r={};for(let[o,a]of Object.entries(e))bf.includes(o)&&typeof a=="string"&&jk(t[o],n)===a?r[o]=t[o]:r[o]=gf(a,t[o],n);return r},hL=e=>{if(U(e))for(let t of mr){let n=e[t];if(U(n)&&U(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Bs=e=>{if(!U(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Yt({command:t,args:n},"profile")},ll=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),mL=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return U(t)&&t.tool==="opencode"}catch{return!1}},kf=e=>J(e,"copilot")&&!!e.clientKey,yL=e=>e.byoUpstream?[]:J(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],gL=(e,t)=>J(e,"openai")?[`OpenAI subscription: OpenCode's built-in ChatGPT Pro/Plus OAuth is ${t?"detected":"not signed in yet (run `opencode auth login`)"}. Its Codex endpoint is hard-coded to chatgpt.com, so provider.baseURL cannot redirect it. Connect leaves machine networking untouched. Use the Codex app/CLI/IDE for ChatGPT subscription pass-through, or sign OpenCode into an API-key/Copilot provider that Connect can route.`]:[],wL=e=>kf(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."]:[],bL=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=df);let o=!1;if(n)if("mcp"in r&&!U(r.mcp))o=!0;else{let y=U(r.mcp)?{...r.mcp}:{},b=y[Ln];b!==void 0&&!Bs(b)?o=!0:(y[Ln]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(U(r.mcp)&&Bs(r.mcp[Ln])){let y={...r.mcp};delete y[Ln],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=U(r.provider)?{...r.provider}:{},s=pL(a,t.origin),i=s.every(y=>fL(a[y],e,y))?s:[],c=s.filter(y=>!i.includes(y)),l=[];if(i.length>0){for(let y of i)delete a[y];r=yf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,h=le({...t.metadata,tool:"opencode"});for(let y of c){let b={...a[y]},v={...b.options};if("headers"in v&&!U(v.headers)){u.push(y);continue}let S=U(v.headers)?{...v.headers}:{},E=!1;for(let[x,A]of[[Nt,p],...h?[[Dn,h]]:[]])x in S?(typeof S[x]!="string"||S[x].trim()==="")&&u.push(`${y}.${x}`):(S[x]=A,d.push(`${y}.${x}`),E=!0);E&&(v.headers=S,b.options=v,a[y]=b)}let m=c.length>0?[]:mr.filter(y=>y!=="openai"||!J(t,"openai")),w=t.byoUpstream;for(let y of m){let b=U(a[y])?{...a[y]}:{},v=U(b.options)?{...b.options}:{};v.baseURL=f;let S=U(v.headers)?{...v.headers}:{};if(y==="anthropic"&&w)v.apiKey=w.key,S[Tn]=`Bearer ${w.key}`,S["x-anyray-provider"]="anthropic",S["x-anyray-auth-mode"]="passthrough",S["x-anyray-custom-host"]=w.url;else{v.apiKey=p,"x-anyray-custom-host"in S&&delete S[Tn];for(let E of uf)delete S[E]}S[Nt]=p,h&&(S[Dn]=h),v.headers=S,b.options=v,a[y]=b}let g=c.length===0&&kf(t);if(g){let y=U(a[Nn])?{...a[Nn]}:{},b=U(y.options)?{...y.options}:{};b.baseURL=ff(t);let v=U(b.headers)?{...b.headers}:{};v[Nt]=t.clientKey,h&&(v[Dn]=h),b.headers=v,y.options=b,a[Nn]=y}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:g,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},kL=["baseURL","apiKey"],Uk=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!U(s)||!U(s.options))return!1;let i={...s},c={...s.options},l=!1;if(n){let d=typeof c.baseURL=="string"&&c.baseURL.includes("/v1/copilot/"),u=U(c.headers)?{...c.headers}:void 0,f=u?.[Nt],p=ll(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let h=u,m=U(r)?r.options:void 0,w=U(m)&&U(m.headers)?m.headers:void 0;for(let g of[Nt,Dn])w&&g in w?h[g]!==w[g]&&(h[g]=w[g],l=!0):g in h&&(delete h[g],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}else{let d=U(r)?r.options:void 0,u=U(d)?d:{},f=U(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Nt]=="string"||typeof f[Dn]=="string"||uf.some(h=>h in f);if(!o&&!p)return!1;for(let h of kL)h in u?c[h]!==u[h]&&(c[h]=u[h],l=!0):h in c&&(delete c[h],l=!0);if(U(c.headers)){let h={...c.headers},m=U(u.headers)?u.headers:{};"x-anyray-custom-host"in h&&Tn in h&&(Tn in m?h[Tn]!==m[Tn]&&(h[Tn]=m[Tn],l=!0):(delete h[Tn],l=!0));for(let w of[Nt,Dn,...uf])w in m?h[w]!==m[w]&&(h[w]=m[w],l=!0):w in h&&(delete h[w],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}return l?(Object.keys(c).length===0?delete i.options:i.options=c,Object.keys(i).length===0?delete e[t]:e[t]=i,!0):!1},AL=(e,t,n)=>{let r=e[t];if(!U(r)||!U(r.options)||!U(n)||!U(n.options))return!1;let o={...r.options};if(!U(o.headers)||"headers"in n.options&&!U(n.options.headers))return!1;let a={...o.headers},s=U(n.options.headers)?n.options.headers:{},i=!1;return!(Nt in s)&&ll(a[Nt])&&(delete a[Nt],i=!0),!(Dn in s)&&mL(a[Dn])&&(delete a[Dn],i=!0),i?(Object.keys(a).length===0?"headers"in n.options?o.headers=s:delete o.headers:o.headers=a,e[t]={...r,options:o},!0):!1},CL=(e,t)=>{let n={...e},r=!1,o=hL(e.provider);if(U(n.mcp)&&Bs(n.mcp[Ln])){let c={...n.mcp};delete c[Ln],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!U(n.provider))return{next:n,removed:r};let a={...n.provider},s=U(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===df&&mr.every(c=>{let l=a[c];return U(l)&&U(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of mr)Uk(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...mr,Nn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;AL(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&U(u)&&U(u.options)&&wf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=gf(n,t,l))}return Uk(a,Nn,!0,s[Nn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===df&&(delete n.$schema,r=!0),{next:n,removed:r}},Vk={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=ul(),t=Wk(),n=await O(e)||await O(t),r=n&&await Mk();return{installed:n,detail:n?`${await Fk()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await Fk(),r=e.openaiBaseUrl,o=le({...e.metadata,tool:"opencode"}),a=kf(e),s=J(e,"openai"),i=await Mk(),c;try{c=await Xo(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(ff(e))}, "headers": { "${Nt}": "<your personal ark_ key>" } } }`]:[]]}:{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Enroll with --enroll or --sso before configuring OpenCode.`]}}let l=await $r()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=bL(c.data,e,l),g=u.length>0,y=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(A=>`provider.${A}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...p.length>0?[`Updated model references: ${p.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=g?[`${n} already routes through ${e.origin} via ${u.map(A=>`provider.${A}`).join(", ")}; existing provider values were preserved.`,h.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${h.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...m.length>0?[`Could not safely add required headers at ${m.join(", ")} because the existing values have incompatible shapes. Fix those values manually; no existing value was replaced.`]:[],"Canonical anthropic, openai, and github-copilot provider blocks were left untouched.","Restart OpenCode (or start a new session) to pick up the change."]:[...y,s?`${n} \u2192 provider.anthropic options.baseURL = ${r}; provider.openai left untouched because OpenCode's ChatGPT OAuth loader has no configurable endpoint.`:`${n} \u2192 provider.anthropic + provider.openai options.baseURL = ${r}`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${o??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...yL(e),...gL(e,i),a?`provider.github-copilot options.baseURL \u2192 ${ff(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. ${pf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${pf()} 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).",...wL(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Ln} is not owned by Anyray Connect, so it was left untouched.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let v=m.length>0?"manual":"configured";if(t.dryRun)return{status:v,messages:b};let E=await Bk(n,c,d,!0)?[n]:[],x=cl();if(ce())try{let A=await $k(x,Ja(Ze,["opencode"]));A==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${x} already exists and is not owned by Anyray.`):(A==="installed"&&E.push(x),b.push(`The OpenCode tool.execute.after carrier is active in ${x}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${x}. Gateway-side optimization remains active.`)}else{try{await lf(x)==="removed"&&E.push(x)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:v,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await Jo())try{let{data:n}=await Xo(t);if(!U(n.provider))continue;for(let r of Object.values(n.provider))if(!(!U(r)||!U(r.options))&&wf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await Jo())try{let{data:t}=await Xo(e);if(!U(t.mcp))continue;let n=t.mcp[Ln];if(!Bs(n)||!U(n))continue;return{registered:!0,command:Array.isArray(n.command)&&typeof n.command[0]=="string"?n.command[0]:null}}catch{}return{registered:!1,command:null}},async integrationStatus(){let e,t=!0;try{let i=await Fs(cl());e=i==="absent"?"missing":i,e==="owned"&&(t=await dl(cl(),"utf-8")===cf(Ja(Ze,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await Jo()){let c;try{c=await Xo(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!U(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Ln];if(l!==void 0)if(Bs(l))if(n=!0,!U(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;oc({command:d,args:u},"profile")||(a=!1)}else r=!0}return{hook_registration:e,mcp_registration:o?"unreadable":r?"foreign":n?"owned":"missing",hook_binary:t&&a&&await $r()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await Kk(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await Jo()){let{data:o}=await Xo(r);if(U(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!U(s)||!U(s.options)){e.add("unknown");continue}let i=s.options,c=U(i.headers)?i.headers:{};if(a===Nn&&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===Nn&&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(ll(c[Nt])||ll(i.apiKey)||typeof i.apiKey=="string"&&i.apiKey.length>0||typeof c.Authorization=="string"&&c.Authorization.length>0){e.add("api_key");continue}e.add("unknown")}}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=await Jo(),n=cl(),r="absent";try{r=await Fs(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 Xo(i)}catch{s.push(i);continue}let{next:l,removed:d}=CL(c.data,await uL(i));d&&(await Bk(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await ne(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 lf(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 zk}from"node:os";import{join as fl}from"node:path";import{constants as IL,chmod as OL,copyFile as RL,readFile as qk}from"node:fs/promises";import{applyEdits as _L,modify as PL}from"jsonc-parser";import{homedir as vL}from"node:os";import{dirname as SL,join as Us}from"node:path";import{mkdir as EL,readFile as Zk,rm as xL}from"node:fs/promises";var Af="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",Yk=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfQogICAgfQogIH0sCiAgImNvbmZpZ1NjaGVtYSI6IHsKICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAiYWRkaXRpb25hbFByb3BlcnRpZXMiOiBmYWxzZSwKICAgICJyZXF1aXJlZCI6IFsiZ2F0ZXdheVVybCJdLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkFueXJheSBnYXRld2F5IG9yaWdpbiwgZS5nLiBodHRwczovL2dhdGV3YXkuZXhhbXBsZS5hbnlyYXkuYWkgKG5vIC92MSBzdWZmaXgpLiIKICAgICAgfSwKICAgICAgImFwaUtleSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJQZXJzb25hbCBBbnlyYXkgY2xpZW50IGtleSAoYXJrX+KApikuIFN1cHBvcnRzICR7RU5WX1ZBUn0gc3Vic3RpdHV0aW9uOyBkZWZhdWx0cyB0byAke0FOWVJBWV9DTElFTlRfS0VZfS4iCiAgICAgIH0sCiAgICAgICJ1c2VyIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkF0dHJpYnV0aW9uIHVzZXIgKGNvbnRlbnQtZnJlZTsgdXN1YWxseSBhbiBlbWFpbCkuIE9wdGlvbmFsIOKAlCB0aGUgY2xpZW50IGtleSBhbHJlYWR5IGF0dHJpYnV0ZXMgdGhlIGVucm9sbGVkIHVzZXIuIgogICAgICB9LAogICAgICAidGVhbSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB0ZWFtIChjb250ZW50LWZyZWUpLiBPcHRpb25hbC4iCiAgICAgIH0KICAgIH0sCiAgICAidWlIaW50cyI6IHsKICAgICAgImdhdGV3YXlVcmwiOiB7CiAgICAgICAgImxhYmVsIjogIkdhdGV3YXkgVVJMIiwKICAgICAgICAiaGVscCI6ICJZb3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IG9yaWdpbi4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgImxhYmVsIjogIkNsaWVudCBrZXkiLAogICAgICAgICJoZWxwIjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudC4gTGVhdmUgdW5zZXQgdG8gcmVhZCAkQU5ZUkFZX0NMSUVOVF9LRVkuIgogICAgICB9CiAgICB9CiAgfQp9Cg=="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVy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WwpID0+IHsKICAgICAgaWYgKHBheWxvYWQgJiYgdHlwZW9mIHBheWxvYWQgPT09ICdvYmplY3QnICYmICFBcnJheS5pc0FycmF5KHBheWxvYWQpKSB7CiAgICAgICAgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5KAogICAgICAgICAgcGF5bG9hZCBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPiwKICAgICAgICAgIHNlc3Npb25JZAogICAgICAgICk7CiAgICAgIH0KICAgICAgcmV0dXJuIGNhbGxlck9uUGF5bG9hZCA/IGNhbGxlck9uUGF5bG9hZChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpIDogcGF5bG9hZDsKICAgIH07CiAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdHMpOwogIH07CiAgcmV0dXJuIHdyYXBwZWQ7Cn07Cg=="}];var Cf=".anyray-source-sha",Qt=()=>Us(vL(),".anyray","openclaw-plugin"),Xk=async(e=Qt())=>{try{if((await Zk(Us(e,Cf),"utf8")).trim()===Af)return"current"}catch{}for(let t of Yk){let n=Us(e,t.path);await EL(SL(n),{recursive:!0,mode:448}),await he(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await he(Us(e,Cf),`${Af}
|
|
195
|
-
`),"installed"},
|
|
196
|
-
`,r=n.trim()?
|
|
194
|
+
`),!0},AL=async e=>{try{let t=pr(await pl(`${e}.anyray-bak`,"utf8"));return U(t)?t:void 0}catch{return}},ff=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",hf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${ff()}/${gL}`,U=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},CL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===yr[0]||n===yr[1]||n===$n?[]:U(r)&&U(r.options)&&bf(r.options.baseURL,t)?[n]:[]),mf=/claude/i,kf=["model","small_model"],Vk=(e,t)=>{if(typeof e!="string")return;let n=e.indexOf("/");if(n<=0)return;let r=e.slice(0,n),o=e.slice(n+1);if(!(!t.includes(r)||!mf.test(o)))return`${yr[0]}/${o}`},yf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)yf(n,t);return t}if(!U(e))return t;for(let[n,r]of Object.entries(e))kf.includes(n)&&typeof r=="string"?t.push(r):yf(r,t);return t},vL=(e,t,n)=>{if(!U(e)||!U(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>mf.test(a)))return!1;let o=`${n}/`;return yf(t).filter(a=>a.startsWith(o)).every(a=>mf.test(a.slice(o.length)))},gf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>gf(o,t,n));if(!U(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=kf.includes(o)?Vk(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=gf(a,t,n)}return r},wf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>wf(o,t[a],n));if(!U(e)||!U(t))return e;let r={};for(let[o,a]of Object.entries(e))kf.includes(o)&&typeof a=="string"&&Vk(t[o],n)===a?r[o]=t[o]:r[o]=wf(a,t[o],n);return r},SL=e=>{if(U(e))for(let t of yr){let n=e[t];if(U(n)&&U(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Us=e=>{if(!U(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Zt({command:t,args:n},"profile")},ul=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),EL=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return U(t)&&t.tool==="opencode"}catch{return!1}},Af=e=>J(e,"copilot")&&!!e.clientKey,xL=e=>e.byoUpstream?[]:J(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],IL=(e,t)=>J(e,"openai")?[`OpenAI subscription: OpenCode's built-in ChatGPT Pro/Plus OAuth is ${t?"detected":"not signed in yet (run `opencode auth login`)"}. Its Codex endpoint is hard-coded to chatgpt.com, so provider.baseURL cannot redirect it. Connect leaves machine networking untouched. Use the Codex app/CLI/IDE for ChatGPT subscription pass-through, or sign OpenCode into an API-key/Copilot provider that Connect can route.`]:[],RL=e=>Af(e)?["Tip: to spend your Copilot subscription (incl. Claude & GPT), pick the github-copilot/* models in OpenCode \u2014 e.g. github-copilot/claude-sonnet-4.5. The anthropic/* and openai/* entries are the direct providers (api-key mode, separate billing) \u2014 not your Copilot plan."]:[],OL=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=uf);let o=!1;if(n)if("mcp"in r&&!U(r.mcp))o=!0;else{let y=U(r.mcp)?{...r.mcp}:{},b=y[Dn];b!==void 0&&!Us(b)?o=!0:(y[Dn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(U(r.mcp)&&Us(r.mcp[Dn])){let y={...r.mcp};delete y[Dn],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=U(r.provider)?{...r.provider}:{},s=CL(a,t.origin),i=s.every(y=>vL(a[y],e,y))?s:[],c=s.filter(y=>!i.includes(y)),l=[];if(i.length>0){for(let y of i)delete a[y];r=gf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,h=le({...t.metadata,tool:"opencode"});for(let y of c){let b={...a[y]},v={...b.options};if("headers"in v&&!U(v.headers)){u.push(y);continue}let S=U(v.headers)?{...v.headers}:{},E=!1;for(let[x,A]of[[Mt,p],...h?[[Nn,h]]:[]])x in S?(typeof S[x]!="string"||S[x].trim()==="")&&u.push(`${y}.${x}`):(S[x]=A,d.push(`${y}.${x}`),E=!0);E&&(v.headers=S,b.options=v,a[y]=b)}let m=c.length>0?[]:yr.filter(y=>y!=="openai"||!J(t,"openai")),w=t.byoUpstream;for(let y of m){let b=U(a[y])?{...a[y]}:{},v=U(b.options)?{...b.options}:{};v.baseURL=f;let S=U(v.headers)?{...v.headers}:{};if(y==="anthropic"&&w)v.apiKey=w.key,S[Ln]=`Bearer ${w.key}`,S["x-anyray-provider"]="anthropic",S["x-anyray-auth-mode"]="passthrough",S["x-anyray-custom-host"]=w.url;else{v.apiKey=p,"x-anyray-custom-host"in S&&delete S[Ln];for(let E of pf)delete S[E]}S[Mt]=p,h&&(S[Nn]=h),v.headers=S,b.options=v,a[y]=b}let g=c.length===0&&Af(t);if(g){let y=U(a[$n])?{...a[$n]}:{},b=U(y.options)?{...y.options}:{};b.baseURL=hf(t);let v=U(b.headers)?{...b.headers}:{};v[Mt]=t.clientKey,h&&(v[Nn]=h),b.headers=v,y.options=b,a[$n]=y}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:g,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},_L=["baseURL","apiKey"],Hk=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!U(s)||!U(s.options))return!1;let i={...s},c={...s.options},l=!1;if(n){let d=typeof c.baseURL=="string"&&c.baseURL.includes("/v1/copilot/"),u=U(c.headers)?{...c.headers}:void 0,f=u?.[Mt],p=ul(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let h=u,m=U(r)?r.options:void 0,w=U(m)&&U(m.headers)?m.headers:void 0;for(let g of[Mt,Nn])w&&g in w?h[g]!==w[g]&&(h[g]=w[g],l=!0):g in h&&(delete h[g],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}else{let d=U(r)?r.options:void 0,u=U(d)?d:{},f=U(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Mt]=="string"||typeof f[Nn]=="string"||pf.some(h=>h in f);if(!o&&!p)return!1;for(let h of _L)h in u?c[h]!==u[h]&&(c[h]=u[h],l=!0):h in c&&(delete c[h],l=!0);if(U(c.headers)){let h={...c.headers},m=U(u.headers)?u.headers:{};"x-anyray-custom-host"in h&&Ln in h&&(Ln in m?h[Ln]!==m[Ln]&&(h[Ln]=m[Ln],l=!0):(delete h[Ln],l=!0));for(let w of[Mt,Nn,...pf])w in m?h[w]!==m[w]&&(h[w]=m[w],l=!0):w in h&&(delete h[w],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}return l?(Object.keys(c).length===0?delete i.options:i.options=c,Object.keys(i).length===0?delete e[t]:e[t]=i,!0):!1},TL=(e,t,n)=>{let r=e[t];if(!U(r)||!U(r.options)||!U(n)||!U(n.options))return!1;let o={...r.options};if(!U(o.headers)||"headers"in n.options&&!U(n.options.headers))return!1;let a={...o.headers},s=U(n.options.headers)?n.options.headers:{},i=!1;return!(Mt in s)&&ul(a[Mt])&&(delete a[Mt],i=!0),!(Nn in s)&&EL(a[Nn])&&(delete a[Nn],i=!0),i?(Object.keys(a).length===0?"headers"in n.options?o.headers=s:delete o.headers:o.headers=a,e[t]={...r,options:o},!0):!1},PL=(e,t)=>{let n={...e},r=!1,o=SL(e.provider);if(U(n.mcp)&&Us(n.mcp[Dn])){let c={...n.mcp};delete c[Dn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!U(n.provider))return{next:n,removed:r};let a={...n.provider},s=U(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===uf&&yr.every(c=>{let l=a[c];return U(l)&&U(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of yr)Hk(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...yr,$n]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;TL(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&U(u)&&U(u.options)&&bf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=wf(n,t,l))}return Hk(a,$n,!0,s[$n])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===uf&&(delete n.$schema,r=!0),{next:n,removed:r}},Yk={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=fl(),t=Kk(),n=await R(e)||await R(t),r=n&&await Fk();return{installed:n,detail:n?`${await Bk()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await Bk(),r=e.openaiBaseUrl,o=le({...e.metadata,tool:"opencode"}),a=Af(e),s=J(e,"openai"),i=await Fk(),c;try{c=await Jo(n)}catch{return e.clientKey?{status:"manual",messages:[`Couldn't parse ${n} \u2014 set it by hand. Under "provider", add:`,e.byoUpstream?` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your upstream key>", "headers": { "Authorization": "Bearer <your upstream key>", "x-anyray-auth-mode": "passthrough", "x-anyray-provider": "anthropic", "x-anyray-custom-host": ${JSON.stringify(e.byoUpstream.url)}, "x-anyray-api-key": "<your personal ark_ key>" } } }`:` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`,...s?[]:[` "openai": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`],...a?[` "github-copilot": { "options": { "baseURL": ${JSON.stringify(hf(e))}, "headers": { "${Mt}": "<your personal ark_ key>" } } }`]:[]]}:{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Enroll with --enroll or --sso before configuring OpenCode.`]}}let l=await Mr()?je("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=OL(c.data,e,l),g=u.length>0,y=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(A=>`provider.${A}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...p.length>0?[`Updated model references: ${p.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=g?[`${n} already routes through ${e.origin} via ${u.map(A=>`provider.${A}`).join(", ")}; existing provider values were preserved.`,h.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${h.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...m.length>0?[`Could not safely add required headers at ${m.join(", ")} because the existing values have incompatible shapes. Fix those values manually; no existing value was replaced.`]:[],"Canonical anthropic, openai, and github-copilot provider blocks were left untouched.","Restart OpenCode (or start a new session) to pick up the change."]:[...y,s?`${n} \u2192 provider.anthropic options.baseURL = ${r}; provider.openai left untouched because OpenCode's ChatGPT OAuth loader has no configurable endpoint.`:`${n} \u2192 provider.anthropic + provider.openai options.baseURL = ${r}`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${o??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...xL(e),...IL(e,i),a?`provider.github-copilot options.baseURL \u2192 ${hf(e)} with the personal gateway key in options.headers (never the URL). OpenCode keeps its Copilot sign-in, GitHub bills your plan, and the gateway meters it. ${ff()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${ff()} plan-specific host selected by ANYRAY_COPILOT_PLAN.`}`:"GitHub Copilot: not routed \u2014 needs a Copilot seat plus enrollment (a detected Copilot plan or --subscription, and --enroll for the seat key).",...RL(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Dn} is not owned by Anyray Connect, so it was left untouched.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let v=m.length>0?"manual":"configured";if(t.dryRun)return{status:v,messages:b};let E=await Uk(n,c,d,!0)?[n]:[],x=dl();if(ce())try{let A=await Mk(x,za(Ze,["opencode"]));A==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${x} already exists and is not owned by Anyray.`):(A==="installed"&&E.push(x),b.push(`The OpenCode tool.execute.after carrier is active in ${x}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${x}. Gateway-side optimization remains active.`)}else{try{await df(x)==="removed"&&E.push(x)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:v,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await zo())try{let{data:n}=await Jo(t);if(!U(n.provider))continue;for(let r of Object.values(n.provider))if(!(!U(r)||!U(r.options))&&bf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await zo())try{let{data:t}=await Jo(e);if(!U(t.mcp))continue;let n=t.mcp[Dn];if(!Us(n)||!U(n))continue;return{registered:!0,command:Array.isArray(n.command)&&typeof n.command[0]=="string"?n.command[0]:null}}catch{}return{registered:!1,command:null}},async integrationStatus(){let e,t=!0;try{let i=await Bs(dl());e=i==="absent"?"missing":i,e==="owned"&&(t=await pl(dl(),"utf-8")===lf(za(Ze,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await zo()){let c;try{c=await Jo(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!U(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Dn];if(l!==void 0)if(Us(l))if(n=!0,!U(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;sc({command:d,args:u},"profile")||(a=!1)}else r=!0}return{hook_registration:e,mcp_registration:o?"unreadable":r?"foreign":n?"owned":"missing",hook_binary:t&&a&&await Mr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await Gk(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await zo()){let{data:o}=await Jo(r);if(U(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!U(s)||!U(s.options)){e.add("unknown");continue}let i=s.options,c=U(i.headers)?i.headers:{};if(a===$n&&typeof i.baseURL=="string"&&i.baseURL.includes("/v1/copilot/")){e.add("subscription");continue}if(a==="openai"&&n&&i.baseURL===void 0&&i.apiKey===void 0){e.add("native");continue}if(a===$n&&i.baseURL===void 0&&i.apiKey===void 0){e.add("native");continue}if(typeof c["x-anyray-custom-host"]=="string"){e.add("byo");continue}if(c["x-anyray-auth-mode"]==="passthrough"){e.add("subscription");continue}if(ul(c[Mt])||ul(i.apiKey)||typeof i.apiKey=="string"&&i.apiKey.length>0||typeof c.Authorization=="string"&&c.Authorization.length>0){e.add("api_key");continue}e.add("unknown")}}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=await zo(),n=dl(),r="absent";try{r=await Bs(n)}catch{}if(t.length===0&&r!=="owned")return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[...t.map(i=>`would remove Anyray provider settings from ${i}`),...r==="owned"?[`would remove the Anyray OpenCode trim carrier from ${n}`]:[]]};let o=[],a=[],s=[];for(let i of t){let c;try{c=await Jo(i)}catch{s.push(i);continue}let{next:l,removed:d}=PL(c.data,await AL(i));d&&(await Uk(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await re(i)}for(let i of s)o.push(`Couldn't parse ${i} \u2014 if you added Anyray settings there by hand, remove the baseURL/apiKey from provider.anthropic, provider.openai, and provider.github-copilot yourself.`);if(r==="owned")try{await df(n)==="removed"&&(a.push(n),o.push(`removed the Anyray OpenCode trim carrier from ${n}`))}catch{o.push(`Could not remove the Anyray OpenCode trim carrier from ${n}. Remove that file manually.`)}return a.length===0&&s.length===0&&o.push("no Anyray provider settings found"),{status:a.length===0&&s.length>0?"manual":"reverted",messages:o,changedFiles:a.length?a:void 0}}};import{homedir as qk}from"node:os";import{join as ml}from"node:path";import{constants as ML,chmod as FL,copyFile as BL,readFile as Qk}from"node:fs/promises";import{applyEdits as UL,modify as HL}from"jsonc-parser";import{homedir as LL}from"node:os";import{dirname as DL,join as Hs}from"node:path";import{mkdir as NL,readFile as Xk,rm as $L}from"node:fs/promises";var Cf="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",Zk=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfQogICAgfQogIH0sCiAgImNvbmZpZ1NjaGVtYSI6IHsKICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAiYWRkaXRpb25hbFByb3BlcnRpZXMiOiBmYWxzZSwKICAgICJyZXF1aXJlZCI6IFsiZ2F0ZXdheVVybCJdLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkFueXJheSBnYXRld2F5IG9yaWdpbiwgZS5nLiBodHRwczovL2dhdGV3YXkuZXhhbXBsZS5hbnlyYXkuYWkgKG5vIC92MSBzdWZmaXgpLiIKICAgICAgfSwKICAgICAgImFwaUtleSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJQZXJzb25hbCBBbnlyYXkgY2xpZW50IGtleSAoYXJrX+KApikuIFN1cHBvcnRzICR7RU5WX1ZBUn0gc3Vic3RpdHV0aW9uOyBkZWZhdWx0cyB0byAke0FOWVJBWV9DTElFTlRfS0VZfS4iCiAgICAgIH0sCiAgICAgICJ1c2VyIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkF0dHJpYnV0aW9uIHVzZXIgKGNvbnRlbnQtZnJlZTsgdXN1YWxseSBhbiBlbWFpbCkuIE9wdGlvbmFsIOKAlCB0aGUgY2xpZW50IGtleSBhbHJlYWR5IGF0dHJpYnV0ZXMgdGhlIGVucm9sbGVkIHVzZXIuIgogICAgICB9LAogICAgICAidGVhbSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB0ZWFtIChjb250ZW50LWZyZWUpLiBPcHRpb25hbC4iCiAgICAgIH0KICAgIH0sCiAgICAidWlIaW50cyI6IHsKICAgICAgImdhdGV3YXlVcmwiOiB7CiAgICAgICAgImxhYmVsIjogIkdhdGV3YXkgVVJMIiwKICAgICAgICAiaGVscCI6ICJZb3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IG9yaWdpbi4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgImxhYmVsIjogIkNsaWVudCBrZXkiLAogICAgICAgICJoZWxwIjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudC4gTGVhdmUgdW5zZXQgdG8gcmVhZCAkQU5ZUkFZX0NMSUVOVF9LRVkuIgogICAgICB9CiAgICB9CiAgfQp9Cg=="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjEuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZ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AgICAgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5KAogICAgICAgICAgcGF5bG9hZCBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPiwKICAgICAgICAgIHNlc3Npb25JZAogICAgICAgICk7CiAgICAgIH0KICAgICAgcmV0dXJuIGNhbGxlck9uUGF5bG9hZCA/IGNhbGxlck9uUGF5bG9hZChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpIDogcGF5bG9hZDsKICAgIH07CiAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdHMpOwogIH07CiAgcmV0dXJuIHdyYXBwZWQ7Cn07Cg=="}];var vf=".anyray-source-sha",en=()=>Hs(LL(),".anyray","openclaw-plugin"),Jk=async(e=en())=>{try{if((await Xk(Hs(e,vf),"utf8")).trim()===Cf)return"current"}catch{}for(let t of Zk){let n=Hs(e,t.path);await NL(DL(n),{recursive:!0,mode:448}),await he(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await he(Hs(e,vf),`${Cf}
|
|
195
|
+
`),"installed"},hl=async(e=en())=>{try{await Xk(Hs(e,vf),"utf8")}catch{return!1}return await $L(e,{recursive:!0,force:!0}),!0};var If="x-anyray-metadata",qo="x-anyray-api-key",Rf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],to="Authorization",no="anthropic-beta",yl="interleaved-thinking-2025-05-14",gl=["anthropic","openai"],eA="short",_f="anthropic-messages",Tf=32e3,wl="anthropic/claude-sonnet-4-5",Pf=["anthropic/claude-haiku-4-5"],Lf="anyray/claude-sonnet-4-5",Df=["anyray/claude-haiku-4-5"],WL=[wl,Lf],KL=[Pf,Df],Je="anyray",wr="ANYRAY_API_KEY",Ks="openclaw",tA=()=>process.env.OPENCLAW_STATE_DIR?.trim()||ml(qk(),".openclaw"),eo=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||ml(tA(),"openclaw.json"),D=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zk=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Ws=async e=>{let t=await R(e),n=t?await Qk(e,"utf8"):`{}
|
|
196
|
+
`,r=n.trim()?pr(n):{};if(!D(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},nA=(e,t,n=[])=>{if(D(e)&&D(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...nA(e[o],t[o],[...n,o])):r.push({path:[...n,o],value:t[o]}):r.push({path:[...n,o],value:void 0});return r}return JSON.stringify(e)===JSON.stringify(t)?[]:[{path:n,value:t}]},Sf=async(e,t,n,r)=>{let o=nA(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await BL(e,`${e}.anyray-bak`,ML.COPYFILE_EXCL),await FL(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await he(`${e}.anyray-bak`,`{}
|
|
197
197
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
198
198
|
`)?`\r
|
|
199
199
|
`:`
|
|
200
|
-
`},s=t.raw;for(let i of o)s=
|
|
200
|
+
`},s=t.raw;for(let i of o)s=UL(s,HL(s,i.path,i.value,{formattingOptions:a}));return await he(e,s.endsWith(`
|
|
201
201
|
`)?s:`${s}
|
|
202
|
-
`),!0},Sf=async e=>{try{let t=ur(await qk(`${e}.anyray-bak`,"utf8"));return D(t)?t:void 0}catch{return}},Of=e=>{if(!D(e))return{};let t=e.models;return!D(t)||!D(t.providers)?{}:t.providers},DL=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=le({...t.metadata,tool:Ws}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!D(l.models)&&d.push("models");let u=D(l.models)?{...l.models}:{};if("providers"in u&&!D(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=D(u.providers)?{...u.providers}:{},p=!1;if(n){let S=D(l.plugins)?{...l.plugins}:{},E=D(S.load)?{...S.load}:{},x=D(S.entries)?{...S.entries}:{},A=D(x[Je])?{...x[Je]}:{},I=D(A.config)?{...A.config}:{};if("plugins"in l&&!D(l.plugins)||"load"in S&&!D(S.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in S&&!D(S.entries)||Je in x&&!D(x[Je])||"config"in A&&!D(A.config)||"env"in l&&!D(l.env))d.push("plugins");else{let R=Array.isArray(E.paths)?[...E.paths]:[];R.includes(n)||R.push(n),E.paths=R,S.load=E,A.enabled=!0,I.gatewayUrl=t.anthropicBaseUrl,I.apiKey=r;let M=t.metadata.user,X=t.metadata.team;M&&(I.user=M),X&&(I.team=X),A.config=I,x[Je]=A,S.entries=x,l.plugins=S;let V=D(l.env)?{...l.env}:{};V[gr]=r,l.env=V,p=!0}}let h=ml.filter(S=>S!=="openai"||!J(t,"openai"));for(let S of h){if(S in f&&!D(f[S])){d.push(`models.providers.${S}`);continue}let E=D(f[S])?{...f[S]}:{};if("headers"in E&&!D(E.headers)){i.push(S);continue}let x=D(E.headers)?{...E.headers}:{};if(E.baseUrl=S==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,S==="anthropic"&&(E.api=Rf,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=_f)),S==="anthropic"&&a)E.apiKey=a.key,x[eo]=`Bearer ${a.key}`,x["x-anyray-provider"]="anthropic",x["x-anyray-auth-mode"]="passthrough",x["x-anyray-custom-host"]=a.url;else{E.apiKey=r,"x-anyray-custom-host"in x&&delete x[eo];for(let A of If)delete x[A]}x[zo]=r,o&&(x[xf]=o),S==="anthropic"&&(to in x?c=x[to]!==hl:x[to]=hl),E.headers=x,f[S]=E,s.push(S)}u.providers=f,l.models=u;let m=!1,w=!1,g=!1,y,b=[],v="agents"in l&&!D(l.agents)||D(l.agents)&&"defaults"in l.agents&&!D(l.agents.defaults)||D(l.agents)&&D(l.agents.defaults)&&("params"in l.agents.defaults&&!D(l.agents.defaults.params)||"model"in l.agents.defaults&&!D(l.agents.defaults.model));if(v&&d.push("agents.defaults"),s.includes("anthropic")&&!v){let S=D(l.agents)?{...l.agents}:{},E=D(S.defaults)?{...S.defaults}:{},x=D(E.params)?{...E.params}:{};"cacheRetention"in x||(x.cacheRetention=Qk,m=!0,E.params=x);let A=D(E.model)?{...E.model}:{},I=p?[...s,Je]:s,R=M=>typeof M=="string"&&I.some(X=>M.startsWith(`${X}/`));typeof A.primary!="string"||A.primary.trim()===""?(A.primary=p?Tf:yl,w=!0,E.model=A,"fallbacks"in A||(A.fallbacks=p?[...Lf]:[...Pf],g=!0)):R(A.primary)||(y=A.primary),b=(Array.isArray(A.fallbacks)?A.fallbacks:[]).filter(M=>typeof M=="string"&&!R(M)),(m||w)&&(S.defaults=E,l.agents=S)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:g,unroutedPrimary:y,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},NL=["baseUrl","apiKey","api","maxTokens"],Ef=(e,t,n=ml,r)=>{let o={...e},a=!("models"in o)||D(o.models)&&(!("providers"in o.models)||D(o.models.providers)),s=D(o.models)?{...o.models}:{},i=D(s.providers)?{...s.providers}:{},c=Of(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!D(f))continue;let p={...f},h=D(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof h[zo]=="string"||typeof h[xf]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||If.some(S=>S in h)))continue;let w=D(c[u])?c[u]:{},g=D(w.headers)?w.headers:{},y="x-anyray-custom-host"in h,b=S=>S==="api"?p.api===Rf:S==="maxTokens"?p.maxTokens===_f:S==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let S of NL)b(S)&&(S in w?p[S]!==w[S]&&(p[S]=w[S],l=!0):S in p&&(delete p[S],l=!0));let v=[zo,xf,...If,..."x-anyray-custom-host"in h?[eo]:[]];h[to]===hl&&v.push(to);for(let S of v)S in g?h[S]!==g[S]&&(h[S]=g[S],l=!0):S in h&&(delete h[S],l=!0);eo in g&&!(eo in h)&&(h[eo]=g[eo],l=!0),Object.keys(h).length===0?delete p.headers:p.headers=h,Object.keys(p).length===0?delete i[u]:i[u]=p}if(a&&(Object.keys(i).length===0?delete s.providers:s.providers=i,Object.keys(s).length===0?delete o.models:o.models=s),r&&n.includes("anthropic")){let u=D(o.plugins)?{...o.plugins}:{},f=D(u.load)?{...u.load}:{},p=D(u.entries)?{...u.entries}:{};if((!("plugins"in o)||D(o.plugins))&&(!("load"in u)||D(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||D(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let w=f.paths.filter(g=>g!==r);w.length===0?delete f.paths:f.paths=w,l=!0}let m=p[Je];if(D(m)){let w=D(m.config)?m.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let y=D(t?.plugins)?t.plugins:{},b=D(y.entries)?y.entries:{};Je in b?JSON.stringify(p[Je])!==JSON.stringify(b[Je])&&(p[Je]=b[Je],l=!0):(delete p[Je],l=!0)}}if(Object.keys(f).length===0?delete u.load:u.load=f,Object.keys(p).length===0?delete u.entries:u.entries=p,Object.keys(u).length===0?delete o.plugins:o.plugins=u,D(o.env)){let w={...o.env},g=w[gr];if(typeof g=="string"&&g.startsWith("ark_")){let y=D(t?.env)?t.env:{};gr in y?w[gr]!==y[gr]&&(w[gr]=y[gr],l=!0):(delete w[gr],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||D(o.agents)&&(!("defaults"in o.agents)||D(o.agents.defaults)&&(!("params"in o.agents.defaults)||D(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||D(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=D(o.agents)?{...o.agents}:{},f=D(u.defaults)?{...u.defaults}:{},p=D(f.params)?{...f.params}:{},h=D(t.agents)?t.agents:{},m=D(h.defaults)?h.defaults:{},w=D(m.params)?m.params:{};p.cacheRetention===Qk&&("cacheRetention"in w?p.cacheRetention!==w.cacheRetention&&(p.cacheRetention=w.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let g=D(f.model)?{...f.model}:{},y=D(m.model)?m.model:{};TL.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),LL.some(b=>JSON.stringify(g.fallbacks)===JSON.stringify(b))&&("fallbacks"in y?JSON.stringify(g.fallbacks)!==JSON.stringify(y.fallbacks)&&(g.fallbacks=y.fallbacks,l=!0):(delete g.fallbacks,l=!0)),Object.keys(g).length===0?delete f.model:f.model=g,Object.keys(p).length===0?delete f.params:f.params=p,Object.keys(f).length===0?delete u.defaults:u.defaults=f,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},nA={id:Ws,title:"OpenClaw",automatic:!0,async detect(){let e=await O(Qr())||await O(eA());return{installed:e,detail:e?Qr():`no ${fl(zk(),".openclaw")} state dir`}},async apply(e,t){let n=Qr();if(!e.byoUpstream&&J(e,"anthropic")){let E=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${Ws}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],x;try{x=await Hs(n)}catch{return{status:"held",messages:E}}let{next:A,removed:I}=Ef(x.data,await Sf(n),ml,Qt());return I?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...E]}:(await vf(n,x,A,!1),await ne(n),await pl(),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...E]}):(t.dryRun||await pl(),{status:"held",messages:E})}let r=Qt(),o=!1;if(!t.dryRun)try{await Xk(r)}catch{r=void 0,o=!0}let a;try{a=await Hs(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Rf}", "maxTokens": ${_f}, "apiKey": "<your personal ark_ key>", "headers": { "${zo}": "<your personal ark_ key>", "${to}": "${hl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${zo}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${yl}") if none is set,`,'and under "agents.defaults.params" set "cacheRetention": "short" \u2014',"custom Anthropic-compatible hosts get no prompt-cache auto-seed, and","an unset value would leave the provider cache permanently cold.","Then run `openclaw config validate`."]}}let{next:s,routed:i,cacheRetentionSeeded:c,betaPreserved:l,headerConflicts:d,primarySeeded:u,fallbacksSeeded:f,unroutedPrimary:p,unroutedFallbacks:h,structureConflicts:m,pluginConfigured:w}=DL(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=Ef(g,await Sf(n),["openai"]);E.removed&&(g=E.next,y=!0)}let b=[i.includes("openai")?`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; models.providers.openai baseUrl = ${e.openaiBaseUrl}`:`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; openai left on its native ChatGPT sign-in`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${le({...e.metadata,tool:Ws})??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...c?['Seeded agents.defaults.params.cacheRetention = "short": OpenClaw',"skips its prompt-cache auto-seed on custom hosts, and an unset","value would leave the provider cache permanently cold."]:["Kept your existing cacheRetention setting."],...l?[`Kept your existing ${to} header value (OpenClaw suppresses its implicit beta headers off-host; yours replaces our default restore).`]:[],...d.length>0?[`Could not add headers on models.providers.${d.join(", ")}: the existing "headers" value is not an object. Fix it manually; nothing there was replaced.`]:[],...u?[`Seeded agents.defaults.model.primary = ${w?Tf:yl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?Lf:Pf).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...p!==void 0?[`Your primary model (${p}) resolves to a provider Connect does not route, so those requests bypass the gateway. Pick an anthropic/* or openai/* model to route them; your setting was kept.`]:[],...h.length>0?[`Fallback model(s) ${h.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...y?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...w?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${Qt()}) and registered it under plugins.entries.${Je}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${Qt()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...m.length>0?[`Left ${m.join(", ")} untouched: the existing value has the wrong shape (array or null where an object belongs), and OpenClaw's strict schema will refuse it as-is. Fix the shape and re-run.`]:[],"OpenClaw hot-reloads model config; run `openclaw config validate` to confirm the merged config passes its strict schema."],v=d.length>0||m.length>0?"manual":"configured";if(t.dryRun)return{status:v,messages:b};let S=await vf(n,a,g,!0);return{status:v,messages:b,changedFiles:S?[n]:[]}},async pointsAt(e){try{let{data:t}=await Hs(Qr());for(let a of Object.values(Of(t)))if(D(a)&&Jk(a.baseUrl,e))return!0;let n=D(t.plugins)?t.plugins:{},o=(D(n.entries)?n.entries:{})[Je];if(D(o)&&D(o.config)&&Jk(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[Qr(),fl(Qt(),".anyray-source-sha")]},async routingExpected(e){return e.includes(Ws)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Hs(Qr());for(let a of Object.values(Of(t))){if(!D(a))continue;let s=D(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[zo]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=D(t.plugins)?t.plugins:{},o=(D(n.entries)?n.entries:{})[Je];if(D(o)&&D(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=Qr();if(!await O(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Hs(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}=Ef(n.data,await Sf(t),ml,Qt()),a=await pl();return o?(await vf(t,n,r,!1),await ne(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${Qt()}`]:[]],changedFiles:[t]}):(await ne(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${Qt()}`]:[]]})}};import{execFile as v$}from"node:child_process";import{readFile as S$}from"node:fs/promises";import{homedir as ii,platform as br}from"node:os";import{join as bn}from"node:path";import{isDeepStrictEqual as bh,promisify as E$}from"node:util";var Ks=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},gl=(e,t)=>{let n=Ks(e),r=Ks(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 UN}from"node:crypto";import{promises as fC}from"node:fs";import{platform as HN,tmpdir as WN}from"node:os";import{join as Nl}from"node:path";import{execFile as $L}from"node:child_process";import{promises as Gs}from"node:fs";import{homedir as ML,platform as FL}from"node:os";import{delimiter as BL,join as wl}from"node:path";import{promisify as UL}from"node:util";var HL=UL($L),WL=15*6e4,KL=64*1024*1024,GL=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],rA=async(e={})=>{let t=(e.home??ML)(),n=e.env??process.env,r=GL(e.runtimePlatform??FL()),o=[wl(t,".local","bin"),wl(t,".claude","local"),...(n.PATH??"").split(BL).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=wl(a,`claude${s}`);try{return await Gs.access(i),i}catch{}}return null},jL=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},VL=async e=>{let t=wl(e,"projects"),n;try{n=(await Gs.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(!XL.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},YL=e=>{if(!e||!e.startsWith("{"))return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.sessionIds,o=n.jsonlPaths;if(!Array.isArray(r)||!Array.isArray(o))return null;let a=Array.isArray(n.titles)?n.titles:[],s=Array.isArray(n.createdAts)?n.createdAts:[],i=Array.isArray(n.updatedAts)?n.updatedAts:[],c=d=>typeof d=="number"&&Number.isFinite(d)?d:void 0,l=[];for(let d=0;d<r.length;d+=1){let u=r[d],f=o[d];if(typeof u!="string"||typeof f!="string"||u.length===0||f.length===0)continue;let p=a[d];l.push({sessionId:u,transcriptPath:f,title:typeof p=="string"&&p.length>0?p:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:jL(n.projectList)}},ZL=async e=>{let t,n;try{let r=await Gs.readFile(e,"utf8");for(let o of r.split(`
|
|
203
|
-
`)){if(o.length===0)continue;let a;try{a=JSON.parse(o).timestamp}catch{continue}if(typeof a!="string")continue;let s=Date.parse(a);Number.isFinite(s)&&(t??=s,n=s)}}catch{return{}}return{createdAt:t,lastActivityAt:n??t}},
|
|
204
|
-
`).filter(d=>d.trim().length>0),i=YL(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 ZL(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await VL(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as qL}from"node:crypto";import{promises as $n}from"node:fs";import{homedir as QL,platform as eD}from"node:os";import{join as vt}from"node:path";var aA=448,Mn="local_",tD="local-agent-mode-sessions",Df="-3p",nD="cowork_account_settings.json",no=(e={})=>{let t=(e.home??QL)(),n=e.runtimePlatform??eD(),r=e.env??process.env;if(n==="darwin")return vt(t,"Library","Application Support",`Claude${Df}`);if(n==="win32"){let o=r.LOCALAPPDATA??vt(t,"AppData","Local");return vt(o,`Claude${Df}`)}return null},js=(e={})=>{let t=no(e);return t?t.slice(0,-Df.length):null},Nf=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)}`},bl=async e=>{let t=vt(e,tD),n;try{n=(await $n.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 $n.readdir(vt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=vt(t,o,s);try{await $n.access(vt(i,nD)),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]}},$f=async e=>{try{let t=await $n.readdir(e);return new Set(t.filter(n=>n.startsWith(Mn)&&n.endsWith(".json")).map(n=>n.slice(Mn.length,-5)))}catch{return new Set}},qo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),rD=async(e,t)=>{let n=`${Mn}${t.sessionId}`,r=vt(e,n),o=vt(r,"outputs"),a=vt(r,".claude"),s=vt(a,"projects",Nf(o));await $n.mkdir(o,{recursive:!0,mode:aA}),await $n.mkdir(s,{recursive:!0,mode:aA});let i=vt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${qL()}`;await $n.copyFile(t.transcriptPath,c),await $n.chmod(c,384),await $n.rename(c,i);let l=t.createdAt??Date.now();await Z(vt(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})},sA=async(e,t)=>{let n=await $f(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!qo(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await rD(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as Qo}from"node:fs";import{homedir as oD}from"node:os";import{dirname as aD,join as Vs}from"node:path";var sD=448,iD=["Documents","Claude","Projects"],cD="spaces.json",lD=(e={})=>Vs((e.home??oD)(),...iD),dD=async e=>{try{let t=JSON.parse(await Qo.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}}},uD=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Mf=async e=>{try{return await Qo.access(e),!0}catch{return!1}},pD=async(e,t,n)=>{let r=Vs(t,uD(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Mf(r)?o:r;return a===o&&await Mf(o)?null:(await Qo.mkdir(aD(a),{recursive:!0}),await Qo.cp(e,a,{recursive:!0}),a)},fD=async e=>{try{let t=(await Qo.readFile(Vs(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},iA=async e=>{let t=lD({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=Vs(e.storageDir,cD),{spaces:a,readable:s}=await dD(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=Vs(e.stagedProjectsDir,l.dirName);try{if(!await Mf(d)){n.failed+=1;continue}let u=await pD(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await fD(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...f?{instructions:f}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await Qo.mkdir(e.storageDir,{recursive:!0,mode:sD}),await Z(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as gD}from"node:crypto";import{execFile as wD,spawnSync as wA}from"node:child_process";import{constants as bA}from"node:fs";import{access as El,chmod as bD,mkdir as kD,readFile as Bf,rename as AD,rm as ta,stat as kA,writeFile as CD}from"node:fs/promises";import{homedir as vD,platform as SD,userInfo as ED}from"node:os";import{dirname as xD,isAbsolute as na,join as $t,resolve as pA}from"node:path";import{isDeepStrictEqual as Zs,promisify as ID}from"node:util";var Ys="__anyray-claude-desktop-credential";var kl=["Heads up: Claude Desktop's third-party mode uses its own app profile, so it opens signed out with empty conversation lists. Nothing is deleted and your Claude account is unchanged \u2014 sign back in with the account you already use.","Your Claude Code sessions and Cowork tasks come across on their own once this new profile has been signed in to and the app is fully quit \u2014 no second command.","Your claude.ai chats live on your Claude account rather than this machine, so those need your data export: `anyray-connect migrate --export <file.zip>`."],Al=["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."],cA="Note: third-party mode runs in a separate app profile, so Claude Desktop starts with empty conversation lists while it is active. Nothing is lost \u2014 local sessions come across on their own once the profile is signed in to and Claude Desktop is fully quit (see any queued migration above), claude.ai chats need your data export via `anyray-connect migrate --export <file.zip>`, and `anyray-connect desktop disconnect` restores the first-party profile.";var Cl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],lA=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],hD=new Set(lA),mD=new Set(lA.map(e=>e.toLowerCase())),yD=new Set(Cl.map(e=>e.toLowerCase())),vl=(e,t=!1)=>(t?mD:hD).has(t?e.toLowerCase():e),dA=(e,t=!1)=>t?yD.has(e.toLowerCase()):Cl.some(n=>n===e),uA=["*"],ro=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...uA]}),ea=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var Xs=/^[a-f0-9-]{36}$/,AA="Anyray",Uf=4,qs=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],Qs=["deploymentMode","awaitingSignIn"],CA=[...qs,...Qs,"configLibrary","_meta.json"],yn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),lt=e=>structuredClone(e),Js=async e=>{try{return await El(e),!0}catch{return!1}},OD=async e=>{try{return await El(e),"present"}catch(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"?"absent":"unreadable"}},en=(e={})=>{let t=(e.home??vD)(),n=(e.username??(()=>ED().username))(),r=$t(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",$t("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:$t(r,"configLibrary"),meta:$t(r,"configLibrary","_meta.json"),appConfig:$t(r,"claude_desktop_config.json"),helper:$t(t,".anyray","bin","claude-desktop-credential-helper"),journal:$t(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},xl=()=>{let e=wA("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},vA=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],RD=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...vA(t)]}},Hf=(e="json")=>{let t=ln(vA(e)),n=pA(t.command),r=pA(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ce()&&(!o||r!==n)}},_D=e=>`'${e.replace(/'/g,`'"'"'`)}'`,Wf=e=>[e.command,...e.args].map(_D).join(" "),PD=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!na(e.command))throw new Error("the credential helper executable is not absolute")},SA=(e,t)=>{PD(e);let n=Il(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!na(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},EA=e=>(SA(e,"--json"),`#!/bin/sh
|
|
205
|
-
exec ${
|
|
206
|
-
`),
|
|
207
|
-
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,
|
|
208
|
-
`)},
|
|
202
|
+
`),!0},Ef=async e=>{try{let t=pr(await Qk(`${e}.anyray-bak`,"utf8"));return D(t)?t:void 0}catch{return}},Of=e=>{if(!D(e))return{};let t=e.models;return!D(t)||!D(t.providers)?{}:t.providers},GL=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=le({...t.metadata,tool:Ks}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!D(l.models)&&d.push("models");let u=D(l.models)?{...l.models}:{};if("providers"in u&&!D(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=D(u.providers)?{...u.providers}:{},p=!1;if(n){let S=D(l.plugins)?{...l.plugins}:{},E=D(S.load)?{...S.load}:{},x=D(S.entries)?{...S.entries}:{},A=D(x[Je])?{...x[Je]}:{},I=D(A.config)?{...A.config}:{};if("plugins"in l&&!D(l.plugins)||"load"in S&&!D(S.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in S&&!D(S.entries)||Je in x&&!D(x[Je])||"config"in A&&!D(A.config)||"env"in l&&!D(l.env))d.push("plugins");else{let T=Array.isArray(E.paths)?[...E.paths]:[];T.includes(n)||T.push(n),E.paths=T,S.load=E,A.enabled=!0,I.gatewayUrl=t.anthropicBaseUrl,I.apiKey=r;let B=t.metadata.user,X=t.metadata.team;B&&(I.user=B),X&&(I.team=X),A.config=I,x[Je]=A,S.entries=x,l.plugins=S;let V=D(l.env)?{...l.env}:{};V[wr]=r,l.env=V,p=!0}}let h=gl.filter(S=>S!=="openai"||!J(t,"openai"));for(let S of h){if(S in f&&!D(f[S])){d.push(`models.providers.${S}`);continue}let E=D(f[S])?{...f[S]}:{};if("headers"in E&&!D(E.headers)){i.push(S);continue}let x=D(E.headers)?{...E.headers}:{};if(E.baseUrl=S==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,S==="anthropic"&&(E.api=_f,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=Tf)),S==="anthropic"&&a)E.apiKey=a.key,x[to]=`Bearer ${a.key}`,x["x-anyray-provider"]="anthropic",x["x-anyray-auth-mode"]="passthrough",x["x-anyray-custom-host"]=a.url;else{E.apiKey=r,"x-anyray-custom-host"in x&&delete x[to];for(let A of Rf)delete x[A]}x[qo]=r,o&&(x[If]=o),S==="anthropic"&&(no in x?c=x[no]!==yl:x[no]=yl),E.headers=x,f[S]=E,s.push(S)}u.providers=f,l.models=u;let m=!1,w=!1,g=!1,y,b=[],v="agents"in l&&!D(l.agents)||D(l.agents)&&"defaults"in l.agents&&!D(l.agents.defaults)||D(l.agents)&&D(l.agents.defaults)&&("params"in l.agents.defaults&&!D(l.agents.defaults.params)||"model"in l.agents.defaults&&!D(l.agents.defaults.model));if(v&&d.push("agents.defaults"),s.includes("anthropic")&&!v){let S=D(l.agents)?{...l.agents}:{},E=D(S.defaults)?{...S.defaults}:{},x=D(E.params)?{...E.params}:{};"cacheRetention"in x||(x.cacheRetention=eA,m=!0,E.params=x);let A=D(E.model)?{...E.model}:{},I=p?[...s,Je]:s,T=B=>typeof B=="string"&&I.some(X=>B.startsWith(`${X}/`));typeof A.primary!="string"||A.primary.trim()===""?(A.primary=p?Lf:wl,w=!0,E.model=A,"fallbacks"in A||(A.fallbacks=p?[...Df]:[...Pf],g=!0)):T(A.primary)||(y=A.primary),b=(Array.isArray(A.fallbacks)?A.fallbacks:[]).filter(B=>typeof B=="string"&&!T(B)),(m||w)&&(S.defaults=E,l.agents=S)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:g,unroutedPrimary:y,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},jL=["baseUrl","apiKey","api","maxTokens"],xf=(e,t,n=gl,r)=>{let o={...e},a=!("models"in o)||D(o.models)&&(!("providers"in o.models)||D(o.models.providers)),s=D(o.models)?{...o.models}:{},i=D(s.providers)?{...s.providers}:{},c=Of(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!D(f))continue;let p={...f},h=D(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof h[qo]=="string"||typeof h[If]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Rf.some(S=>S in h)))continue;let w=D(c[u])?c[u]:{},g=D(w.headers)?w.headers:{},y="x-anyray-custom-host"in h,b=S=>S==="api"?p.api===_f:S==="maxTokens"?p.maxTokens===Tf:S==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let S of jL)b(S)&&(S in w?p[S]!==w[S]&&(p[S]=w[S],l=!0):S in p&&(delete p[S],l=!0));let v=[qo,If,...Rf,..."x-anyray-custom-host"in h?[to]:[]];h[no]===yl&&v.push(no);for(let S of v)S in g?h[S]!==g[S]&&(h[S]=g[S],l=!0):S in h&&(delete h[S],l=!0);to in g&&!(to in h)&&(h[to]=g[to],l=!0),Object.keys(h).length===0?delete p.headers:p.headers=h,Object.keys(p).length===0?delete i[u]:i[u]=p}if(a&&(Object.keys(i).length===0?delete s.providers:s.providers=i,Object.keys(s).length===0?delete o.models:o.models=s),r&&n.includes("anthropic")){let u=D(o.plugins)?{...o.plugins}:{},f=D(u.load)?{...u.load}:{},p=D(u.entries)?{...u.entries}:{};if((!("plugins"in o)||D(o.plugins))&&(!("load"in u)||D(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||D(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let w=f.paths.filter(g=>g!==r);w.length===0?delete f.paths:f.paths=w,l=!0}let m=p[Je];if(D(m)){let w=D(m.config)?m.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let y=D(t?.plugins)?t.plugins:{},b=D(y.entries)?y.entries:{};Je in b?JSON.stringify(p[Je])!==JSON.stringify(b[Je])&&(p[Je]=b[Je],l=!0):(delete p[Je],l=!0)}}if(Object.keys(f).length===0?delete u.load:u.load=f,Object.keys(p).length===0?delete u.entries:u.entries=p,Object.keys(u).length===0?delete o.plugins:o.plugins=u,D(o.env)){let w={...o.env},g=w[wr];if(typeof g=="string"&&g.startsWith("ark_")){let y=D(t?.env)?t.env:{};wr in y?w[wr]!==y[wr]&&(w[wr]=y[wr],l=!0):(delete w[wr],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||D(o.agents)&&(!("defaults"in o.agents)||D(o.agents.defaults)&&(!("params"in o.agents.defaults)||D(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||D(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=D(o.agents)?{...o.agents}:{},f=D(u.defaults)?{...u.defaults}:{},p=D(f.params)?{...f.params}:{},h=D(t.agents)?t.agents:{},m=D(h.defaults)?h.defaults:{},w=D(m.params)?m.params:{};p.cacheRetention===eA&&("cacheRetention"in w?p.cacheRetention!==w.cacheRetention&&(p.cacheRetention=w.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let g=D(f.model)?{...f.model}:{},y=D(m.model)?m.model:{};WL.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),KL.some(b=>JSON.stringify(g.fallbacks)===JSON.stringify(b))&&("fallbacks"in y?JSON.stringify(g.fallbacks)!==JSON.stringify(y.fallbacks)&&(g.fallbacks=y.fallbacks,l=!0):(delete g.fallbacks,l=!0)),Object.keys(g).length===0?delete f.model:f.model=g,Object.keys(p).length===0?delete f.params:f.params=p,Object.keys(f).length===0?delete u.defaults:u.defaults=f,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},rA={id:Ks,title:"OpenClaw",automatic:!0,async detect(){let e=await R(eo())||await R(tA());return{installed:e,detail:e?eo():`no ${ml(qk(),".openclaw")} state dir`}},async apply(e,t){let n=eo();if(!e.byoUpstream&&J(e,"anthropic")){let E=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${Ks}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],x;try{x=await Ws(n)}catch{return{status:"held",messages:E}}let{next:A,removed:I}=xf(x.data,await Ef(n),gl,en());return I?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...E]}:(await Sf(n,x,A,!1),await re(n),await hl(),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...E]}):(t.dryRun||await hl(),{status:"held",messages:E})}let r=en(),o=!1;if(!t.dryRun)try{await Jk(r)}catch{r=void 0,o=!0}let a;try{a=await Ws(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${_f}", "maxTokens": ${Tf}, "apiKey": "<your personal ark_ key>", "headers": { "${qo}": "<your personal ark_ key>", "${no}": "${yl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${qo}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${wl}") if none is set,`,'and under "agents.defaults.params" set "cacheRetention": "short" \u2014',"custom Anthropic-compatible hosts get no prompt-cache auto-seed, and","an unset value would leave the provider cache permanently cold.","Then run `openclaw config validate`."]}}let{next:s,routed:i,cacheRetentionSeeded:c,betaPreserved:l,headerConflicts:d,primarySeeded:u,fallbacksSeeded:f,unroutedPrimary:p,unroutedFallbacks:h,structureConflicts:m,pluginConfigured:w}=GL(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=xf(g,await Ef(n),["openai"]);E.removed&&(g=E.next,y=!0)}let b=[i.includes("openai")?`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; models.providers.openai baseUrl = ${e.openaiBaseUrl}`:`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; openai left on its native ChatGPT sign-in`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${le({...e.metadata,tool:Ks})??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...c?['Seeded agents.defaults.params.cacheRetention = "short": OpenClaw',"skips its prompt-cache auto-seed on custom hosts, and an unset","value would leave the provider cache permanently cold."]:["Kept your existing cacheRetention setting."],...l?[`Kept your existing ${no} header value (OpenClaw suppresses its implicit beta headers off-host; yours replaces our default restore).`]:[],...d.length>0?[`Could not add headers on models.providers.${d.join(", ")}: the existing "headers" value is not an object. Fix it manually; nothing there was replaced.`]:[],...u?[`Seeded agents.defaults.model.primary = ${w?Lf:wl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?Df:Pf).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...p!==void 0?[`Your primary model (${p}) resolves to a provider Connect does not route, so those requests bypass the gateway. Pick an anthropic/* or openai/* model to route them; your setting was kept.`]:[],...h.length>0?[`Fallback model(s) ${h.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...y?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...w?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${en()}) and registered it under plugins.entries.${Je}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${en()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...m.length>0?[`Left ${m.join(", ")} untouched: the existing value has the wrong shape (array or null where an object belongs), and OpenClaw's strict schema will refuse it as-is. Fix the shape and re-run.`]:[],"OpenClaw hot-reloads model config; run `openclaw config validate` to confirm the merged config passes its strict schema."],v=d.length>0||m.length>0?"manual":"configured";if(t.dryRun)return{status:v,messages:b};let S=await Sf(n,a,g,!0);return{status:v,messages:b,changedFiles:S?[n]:[]}},async pointsAt(e){try{let{data:t}=await Ws(eo());for(let a of Object.values(Of(t)))if(D(a)&&zk(a.baseUrl,e))return!0;let n=D(t.plugins)?t.plugins:{},o=(D(n.entries)?n.entries:{})[Je];if(D(o)&&D(o.config)&&zk(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[eo(),ml(en(),".anyray-source-sha")]},async routingExpected(e){return e.includes(Ks)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Ws(eo());for(let a of Object.values(Of(t))){if(!D(a))continue;let s=D(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[qo]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=D(t.plugins)?t.plugins:{},o=(D(n.entries)?n.entries:{})[Je];if(D(o)&&D(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=eo();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Ws(t)}catch{return{status:"manual",messages:[`Couldn't parse ${t} \u2014 if you added Anyray settings there by hand, remove baseUrl/apiKey and the x-anyray-* headers from models.providers.anthropic and models.providers.openai yourself.`]}}let{next:r,removed:o}=xf(n.data,await Ef(t),gl,en()),a=await hl();return o?(await Sf(t,n,r,!1),await re(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${en()}`]:[]],changedFiles:[t]}):(await re(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${en()}`]:[]]})}};import{execFile as L$}from"node:child_process";import{readFile as D$}from"node:fs/promises";import{homedir as ci,platform as kr}from"node:os";import{join as kn}from"node:path";import{isDeepStrictEqual as kh,promisify as N$}from"node:util";var Gs=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},bl=(e,t)=>{let n=Gs(e),r=Gs(t);if(!(!n||!r)){for(let o=0;o<Math.max(n.length,r.length);o+=1){let a=(n[o]??0)-(r[o]??0);if(a!==0)return a}return 0}};import{randomUUID as JN}from"node:crypto";import{promises as hC}from"node:fs";import{platform as zN,tmpdir as qN}from"node:os";import{join as Ml}from"node:path";import{execFile as VL}from"node:child_process";import{promises as js}from"node:fs";import{homedir as YL,platform as ZL}from"node:os";import{delimiter as XL,join as kl}from"node:path";import{promisify as JL}from"node:util";var zL=JL(VL),qL=15*6e4,QL=64*1024*1024,eD=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],oA=async(e={})=>{let t=(e.home??YL)(),n=e.env??process.env,r=eD(e.runtimePlatform??ZL()),o=[kl(t,".local","bin"),kl(t,".claude","local"),...(n.PATH??"").split(XL).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=kl(a,`claude${s}`);try{return await js.access(i),i}catch{}}return null},tD=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let{uuid:r,name:o,dirName:a}=n;typeof r!="string"||typeof a!="string"||a.length===0||a.includes("/")||a.includes("\\")||a==="."||a===".."||t.push({uuid:r,name:typeof o=="string"&&o.length>0?o:"Project",dirName:a})}return t},nD=async e=>{let t=kl(e,"projects"),n;try{n=(await js.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return[]}let r=[];for(let o of n){let a=o.slice(-36);if(!aD.test(a))continue;let s=o.slice(0,-37).split("-").filter(i=>i.length>0).map(i=>i[0].toUpperCase()+i.slice(1)).join(" ");r.push({uuid:a,name:s.length>0?s:"Project",dirName:o})}return r},rD=e=>{if(!e||!e.startsWith("{"))return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.sessionIds,o=n.jsonlPaths;if(!Array.isArray(r)||!Array.isArray(o))return null;let a=Array.isArray(n.titles)?n.titles:[],s=Array.isArray(n.createdAts)?n.createdAts:[],i=Array.isArray(n.updatedAts)?n.updatedAts:[],c=d=>typeof d=="number"&&Number.isFinite(d)?d:void 0,l=[];for(let d=0;d<r.length;d+=1){let u=r[d],f=o[d];if(typeof u!="string"||typeof f!="string"||u.length===0||f.length===0)continue;let p=a[d];l.push({sessionId:u,transcriptPath:f,title:typeof p=="string"&&p.length>0?p:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:tD(n.projectList)}},oD=async e=>{let t,n;try{let r=await js.readFile(e,"utf8");for(let o of r.split(`
|
|
203
|
+
`)){if(o.length===0)continue;let a;try{a=JSON.parse(o).timestamp}catch{continue}if(typeof a!="string")continue;let s=Date.parse(a);Number.isFinite(s)&&(t??=s,n=s)}}catch{return{}}return{createdAt:t,lastActivityAt:n??t}},aD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sD=/\.(?:cmd|bat)$/i,iD=(e,t)=>sD.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},aA=async(e,t={})=>{let n=t.exec??zL,r=["import-conversations",e.exportPath,"--cwd",e.workDir];if([e.binary,...r].some(d=>d.includes('"')))return{ok:!1,reason:"the export path contains an unsupported character"};await js.mkdir(e.configDir,{recursive:!0,mode:448}),await js.mkdir(e.workDir,{recursive:!0,mode:448});let o=iD(e.binary,r),a;try{a=(await n(o.file,o.args,{env:{...process.env,CLAUDE_IMPORT_CONVERSATIONS:"1",CLAUDE_CONFIG_DIR:e.configDir},timeout:qL,maxBuffer:QL,windowsVerbatimArguments:o.verbatim})).stdout}catch(d){let u=d.code;return{ok:!1,reason:typeof u=="number"?`the Claude Code importer exited with status ${u}`:"the Claude Code importer could not be run"}}let s=a.split(`
|
|
204
|
+
`).filter(d=>d.trim().length>0),i=rD(s.at(-1));if(!i)return{ok:!1,reason:"the Claude Code importer produced no readable summary"};let c=await Promise.all(i.conversations.map(async d=>{if(d.createdAt!==void 0)return d;let u=await oD(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await nD(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as cD}from"node:crypto";import{promises as Mn}from"node:fs";import{homedir as lD,platform as dD}from"node:os";import{join as St}from"node:path";var sA=448,Fn="local_",uD="local-agent-mode-sessions",Nf="-3p",pD="cowork_account_settings.json",ro=(e={})=>{let t=(e.home??lD)(),n=e.runtimePlatform??dD(),r=e.env??process.env;if(n==="darwin")return St(t,"Library","Application Support",`Claude${Nf}`);if(n==="win32"){let o=r.LOCALAPPDATA??St(t,"AppData","Local");return St(o,`Claude${Nf}`)}return null},Vs=(e={})=>{let t=ro(e);return t?t.slice(0,-Nf.length):null},$f=e=>{let t=e.replace(/[^a-zA-Z0-9]/g,"-");if(t.length<=200)return t;let n=0;for(let r=0;r<e.length;r+=1)n=Math.imul(n,31)+e.charCodeAt(r)|0;return`${t.slice(0,200)}-${Math.abs(n).toString(36)}`},Al=async e=>{let t=St(e,uD),n;try{n=(await Mn.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return{ok:!1,reason:"no-profile",found:[]}}let r=[];for(let o of n){let a;try{a=(await Mn.readdir(St(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=St(t,o,s);try{await Mn.access(St(i,pD)),r.push(i)}catch{}}}return r.length===0?{ok:!1,reason:"no-account",found:[]}:r.length>1?{ok:!1,reason:"ambiguous",found:r}:{ok:!0,dir:r[0]}},Mf=async e=>{try{let t=await Mn.readdir(e);return new Set(t.filter(n=>n.startsWith(Fn)&&n.endsWith(".json")).map(n=>n.slice(Fn.length,-5)))}catch{return new Set}},Qo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),fD=async(e,t)=>{let n=`${Fn}${t.sessionId}`,r=St(e,n),o=St(r,"outputs"),a=St(r,".claude"),s=St(a,"projects",$f(o));await Mn.mkdir(o,{recursive:!0,mode:sA}),await Mn.mkdir(s,{recursive:!0,mode:sA});let i=St(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${cD()}`;await Mn.copyFile(t.transcriptPath,c),await Mn.chmod(c,384),await Mn.rename(c,i);let l=t.createdAt??Date.now();await Z(St(e,`${n}.json`),{sessionId:n,cliSessionId:t.sessionId,processName:"claude-ai-import",cwd:o,hostLoopMode:!0,title:t.title,createdAt:l,lastActivityAt:t.lastActivityAt??l,isArchived:!1,userSelectedFolders:[],pendingNotifications:[]},{backup:!1})},iA=async(e,t)=>{let n=await Mf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!Qo(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await fD(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as ea}from"node:fs";import{homedir as hD}from"node:os";import{dirname as mD,join as Ys}from"node:path";var yD=448,gD=["Documents","Claude","Projects"],wD="spaces.json",bD=(e={})=>Ys((e.home??hD)(),...gD),kD=async e=>{try{let t=JSON.parse(await ea.readFile(e,"utf8"));if(!t||typeof t!="object")return{spaces:[],readable:!1};let n=t.spaces;return Array.isArray(n)?{spaces:n.filter(r=>!!r&&typeof r=="object"&&typeof r.id=="string"),readable:!0}:{spaces:[],readable:!1}}catch(t){return t.code==="ENOENT"?{spaces:[],readable:!0}:{spaces:[],readable:!1}}},AD=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Ff=async e=>{try{return await ea.access(e),!0}catch{return!1}},CD=async(e,t,n)=>{let r=Ys(t,AD(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Ff(r)?o:r;return a===o&&await Ff(o)?null:(await ea.mkdir(mD(a),{recursive:!0}),await ea.cp(e,a,{recursive:!0}),a)},vD=async e=>{try{let t=(await ea.readFile(Ys(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},cA=async e=>{let t=bD({home:e.home}),n={imported:0,alreadyPresent:0,skippedCollision:0,failed:0,root:t},r=e.projects??[];if(r.length===0)return n;let o=Ys(e.storageDir,wD),{spaces:a,readable:s}=await kD(o);if(!s)return n.failed=r.length,n;let i=new Set(a.map(l=>l.id)),c=[];for(let l of r){if(i.has(l.uuid)){n.alreadyPresent+=1;continue}let d=Ys(e.stagedProjectsDir,l.dirName);try{if(!await Ff(d)){n.failed+=1;continue}let u=await CD(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await vD(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...f?{instructions:f}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await ea.mkdir(e.storageDir,{recursive:!0,mode:yD}),await Z(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as ID}from"node:crypto";import{execFile as RD,spawnSync as bA}from"node:child_process";import{constants as kA}from"node:fs";import{access as Il,chmod as OD,mkdir as _D,readFile as Uf,rename as TD,rm as na,stat as AA,writeFile as PD}from"node:fs/promises";import{homedir as LD,platform as DD,userInfo as ND}from"node:os";import{dirname as $D,isAbsolute as ra,join as Ft,resolve as fA}from"node:path";import{isDeepStrictEqual as Xs,promisify as MD}from"node:util";var Zs="__anyray-claude-desktop-credential";var Cl=["Heads up: Claude Desktop's third-party mode uses its own app profile, so it opens signed out with empty conversation lists. Nothing is deleted and your Claude account is unchanged \u2014 sign back in with the account you already use.","Your Claude Code sessions and Cowork tasks come across on their own once this new profile has been signed in to and the app is fully quit \u2014 no second command.","Your claude.ai chats live on your Claude account rather than this machine, so those need your data export: `anyray-connect migrate --export <file.zip>`."],vl=["Your Claude account conversations are reachable in the app again once it reopens.","Chats made while third-party mode was active stay in its separate profile and come back if you configure it again."],lA="Note: third-party mode runs in a separate app profile, so Claude Desktop starts with empty conversation lists while it is active. Nothing is lost \u2014 local sessions come across on their own once the profile is signed in to and Claude Desktop is fully quit (see any queued migration above), claude.ai chats need your data export via `anyray-connect migrate --export <file.zip>`, and `anyray-connect desktop disconnect` restores the first-party profile.";var Sl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],dA=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],SD=new Set(dA),ED=new Set(dA.map(e=>e.toLowerCase())),xD=new Set(Sl.map(e=>e.toLowerCase())),El=(e,t=!1)=>(t?ED:SD).has(t?e.toLowerCase():e),uA=(e,t=!1)=>t?xD.has(e.toLowerCase()):Sl.some(n=>n===e),pA=["*"],oo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...pA]}),ta=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var Js=/^[a-f0-9-]{36}$/,CA="Anyray",Hf=4,Qs=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],ei=["deploymentMode","awaitingSignIn"],vA=[...Qs,...ei,"configLibrary","_meta.json"],gn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),lt=e=>structuredClone(e),zs=async e=>{try{return await Il(e),!0}catch{return!1}},FD=async e=>{try{return await Il(e),"present"}catch(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"?"absent":"unreadable"}},tn=(e={})=>{let t=(e.home??LD)(),n=(e.username??(()=>ND().username))(),r=Ft(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Ft("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Ft(r,"configLibrary"),meta:Ft(r,"configLibrary","_meta.json"),appConfig:Ft(r,"claude_desktop_config.json"),helper:Ft(t,".anyray","bin","claude-desktop-credential-helper"),journal:Ft(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Rl=()=>{let e=bA("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},SA=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],BD=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...SA(t)]}},Wf=(e="json")=>{let t=dn(SA(e)),n=fA(t.command),r=fA(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ce()&&(!o||r!==n)}},UD=e=>`'${e.replace(/'/g,`'"'"'`)}'`,Kf=e=>[e.command,...e.args].map(UD).join(" "),HD=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ra(e.command))throw new Error("the credential helper executable is not absolute")},EA=(e,t)=>{HD(e);let n=Ol(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!ra(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},xA=e=>(EA(e,"--json"),`#!/bin/sh
|
|
205
|
+
exec ${Kf(e)}
|
|
206
|
+
`),WD=`#!/bin/sh
|
|
207
|
+
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,IA=e=>{EA(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),Zs]};return["#!/bin/sh","# Anyray subscription pass-through credential helper v2 for Claude Desktop.","# The durable credential runtime reads and validates the Keychain JSON,","# combines it with Anyray headers, and writes one credential response.",`exec ${Kf(t)}`,""].join(`
|
|
208
|
+
`)},KD=e=>e.args.at(-1)==="--passthrough-headers"?IA(e):xA(e),Ol=e=>/[\\/](node|node\.exe)$/i.test(e),Gf=e=>{let t=[],n=0;for(;n<e.length;){if(e[n]!=="'")return;n++;let r="";for(;n<e.length;){let o=e.indexOf("'",n);if(o<0)return;if(r+=e.slice(n,o),e.startsWith(`'"'"'`,o)){r+="'",n=o+5;continue}n=o+1;break}if(t.push(r),n===e.length)return t;if(e[n]!==" "||n+1===e.length)return;n++}},GD=e=>{let t=`#!/bin/sh
|
|
209
209
|
exec `;if(!e.startsWith(t)||!e.endsWith(`
|
|
210
210
|
`))return;let n=e.slice(t.length,-1);if(n.includes(`
|
|
211
|
-
`)||n.includes("\r"))return;let r=
|
|
212
|
-
# Anyray subscription pass-through credential helper`,
|
|
213
|
-
`)},
|
|
214
|
-
`,384)},
|
|
215
|
-
`,384)},zs=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!Xs.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!yn(o)||typeof o.id!="string"||!Xs.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},JD=async(e,t,n)=>{let r=await gn(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:lt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[lt(t.metaEntry)]}}}let c=zs(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!Zs(d,t.metaEntry))throw new Error("Claude changed the Anyray config-library entry after apply");return{configId:t.configId,meta:r,metaFileExisted:t.metaFileExisted,originalAppliedId:t.originalAppliedId,metaEntry:lt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...lt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=zs(r.value);let c=$t(e.library,`${o}.json`);if(!await Js(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=lt(r.value.entries)}let s=n();if(!Xs.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await Js($t(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:AA};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?lt(r.value):{},appliedId:s,entries:[...a,i]}}},zD=(e,t)=>{let n=ro(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},RA=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),qD=async(e,t,n,r,o,a,s)=>{let i=RA(),c=Object.fromEntries(qs.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(Qs.map(d=>[d,{original:s?.deployment[d].original??OA(r.value,d),lastWritten:i[d]}]));return{version:Uf,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??lt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await ei(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Sl=e=>({status:"manual",messages:[e]}),QD=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}`)]}},eN=ID(wD),tN=new Set(Cl),nN=async e=>{try{let{stdout:t}=await eN("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return yn(n)?Object.keys(n):void 0}catch{return}},oo=async(e,t={})=>{let n=t.readManagedPolicyKeys??nN;for(let r of e.managedPolicies){let o=await OD(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=>vl(i)&&!tN.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},Vf=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.`},Yf=e=>(e.platform??SD)()==="darwin",_A=async(e,t,n={})=>{if(!Yf(n))return Sl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??xl)()&&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=en(n),a=await oo(o,n);if(a&&r.push({audience:"admin",message:Vf(a)}),r.length>0)return QD(r);let s=!1,i=!1,c=[o.journal];try{let l=J(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??BD)())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=RD((n.credentialCommand??(()=>Hf(d)))(),d),f=LD(u),p=await jf(o),h=await ei(o.helper);if(p&&h.present&&h.content!==p.helper.lastWritten&&h.content!==p.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!p&&h.present&&h.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let m=await JD(o,p,n.randomUUID??gD),w=$t(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await gn(w),y=await gn(o.appConfig),b=zD(e,o.helper),v=await qD(o,m,g,y,f,b,p);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${m.configId} for ${e.anthropicBaseUrl}, activate it in third-party mode, and install a ${l?"subscription pass-through":"dynamic API-billed"} credential helper at ${o.helper}.`]};s=!0,await yA(o.journal,v),i=!0,await Ol(o.helper,f,448),v.helper.previousWritten!==void 0&&(delete v.helper.previousWritten,await yA(o.journal,v));let S=lt(g.value);for(let A of qs)Ff(S,A,b[A]);await Fn(w,S),m.metaToWrite&&await Fn(o.meta,m.metaToWrite);let E=lt(y.value),x=RA();for(let A of Qs)Ff(E,A,x[A]);return await Fn(o.appConfig,E),{status:"configured",changedFiles:[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig],messages:[`Configured Claude Desktop's native local gateway profile \u2192 ${e.anthropicBaseUrl}.`,l?`Installed a subscription pass-through credential helper at ${o.helper}; the helper reads your Claude Code subscription token on demand and no credential is stored in Claude's config.`:`Installed a dynamic credential helper at ${o.helper}; no gateway key is stored in Claude's config.`,l?"Claude Desktop Gateway requests now ride your Claude subscription through Anyray for content-free metering and optimization. Stay signed in to Claude Code so the token remains available.":"Claude Desktop uses its API-billed third-party inference lane; its first-party subscription remains separate.","Fully quit and reopen Claude Desktop to load the change.",...kl]}}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.`]}:Sl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},gA=(e,t,n,r)=>{let o=lt(e);for(let a of n){let s=t[a];Zs(OA(e,a),s.lastWritten)?Ff(o,a,s.original):r.push(a)}return o},PA=async(e,t={})=>{if(!Yf(t))return{status:"not-found",messages:[]};if((t.appRunning??xl)())return Sl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=en(t);try{let r=await jf(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=$t(n.library,`${r.configId}.json`);if(e.dryRun)return{status:"reverted",messages:[`Would restore Anyray-owned Claude Desktop fields from ${n.journal}, preserving user changes.`]};let a=[],s=await gn(o),i=s.value;s.present&&(i=gA(s.value,r.config,qs,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await gn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=zs(l.value),m=lt(l.value.entries),w=m.findIndex(b=>b.id===r.configId),g=w>=0?m[w]:void 0,y=g!==void 0&&Zs(g,r.metaEntry);if(g!==void 0&&!y&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=lt(l.value),h===r.configId){let b=r.originalAppliedId;b&&m.some(v=>v.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&y?(m.splice(w,1),d.entries=m):c&&g===void 0&&(d.entries=m)}else{let b=Zs(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(y&&m.splice(w,1),d={...lt(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await ta(o,{force:!0}):await Fn(o,i)),l.present&&(u?await ta(n.meta,{force:!0}):Zs(l.value,d)||await Fn(n.meta,d));let f=await gn(n.appConfig);if(f.present){let h=gA(f.value,r.deployment,Qs,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await ta(n.appConfig,{force:!0}):await Fn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await ei(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Ol(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await ta(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await ta(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?[]:Al]}}catch(r){return Sl(`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.`)}},Zf=async(e,t={})=>{if(!Yf(t))return!1;let n=en(t);if(await oo(n,t))return!1;try{let r=await gn(n.meta);if(!r.present)return!1;let o=zs(r.value),a=await gn($t(n.library,`${o}.json`)),s=await gn(n.appConfig);if(!a.present||!s.present)return!1;await El(n.helper,bA.X_OK);let i=Ye(e);return a.value.inferenceProvider==="gateway"&&a.value.inferenceGatewayBaseUrl===i&&a.value.inferenceGatewayAuthScheme==="bearer"&&a.value.inferenceCredentialKind==="helper-script"&&a.value.inferenceCredentialHelper===n.helper&&!Object.prototype.hasOwnProperty.call(a.value,"inferenceGatewayApiKey")&&s.value.deploymentMode==="3p"&&!Object.prototype.hasOwnProperty.call(s.value,"awaitingSignIn")}catch{return!1}},TA=async(e={})=>{try{let t=en(e),n=await ei(t.helper);if(!n.present||typeof n.content!="string")return;let r=IA(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},LA=async(e,t={})=>{if(!await Zf(e,t))return!1;let n=en(t);try{let r=await jf(n);if(!r)return!1;let o=await gn(n.meta);if(!o.present||zs(o.value)!==r.configId)return!1;let a=await ei(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=IA(a.content??"");return s?await(t.helperLauncherAvailable??UD)(s):!1}catch{return!1}};import{createHash as XA,randomUUID as JA}from"node:crypto";import{spawn as rN,spawnSync as oN}from"node:child_process";import{link as th,mkdir as Xf,open as zA,readFile as Jf,readdir as qA,rename as QA,rm as tn,stat as eC}from"node:fs/promises";import{homedir as nh}from"node:os";import{basename as tC,dirname as ni,join as la,win32 as aN}from"node:path";import{isDeepStrictEqual as ra}from"node:util";var Te="HKCU\\SOFTWARE\\Policies\\Claude",ti="HKLM\\SOFTWARE\\Policies\\Claude",Tl=5,da="inferenceGatewayApiKey",Ne=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",da],DA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",da],NA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",da],$A=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",da],nC="Managed by anyray-connect; dynamic credential only.",sN=e=>/^[A-Za-z]:[\\/]/.test(e)&&aN.isAbsolute(e),MA=e=>{if(!sN(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)},rC=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!MA(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&&!MA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},rh=(e={})=>la((e.home??nh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),iN=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},cN=e=>(rC(e),["@echo off",`REM ${nC}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(iN).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
216
|
-
`)),
|
|
217
|
-
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${
|
|
211
|
+
`)||n.includes("\r"))return;let r=Gf(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Ol(o);if(!ra(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!ra(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return xA(i)===e?i:void 0}catch{return}},jD=e=>{if(!e.startsWith(WD))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=Gf(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==Zs)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return IA(a)===e?a:void 0}catch{return}},VD=`#!/bin/sh
|
|
212
|
+
# Anyray subscription pass-through credential helper`,YD=e=>{let t=Ol(e.command);if(!(!ra(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!ra(e.args[0]):e.args.length!==2)))return["#!/bin/sh","# Anyray subscription pass-through credential helper for Claude Desktop.","# Reads the Claude subscription token from the login keychain at request","# time and wraps it with Anyray pass-through headers. connect never stores","# the token; only this on-machine helper reads it.","set -eu",`headers=$(${Kf(e)})`,'if [ -z "${headers}" ]; then'," echo 'Anyray: could not resolve gateway headers; is this machine enrolled? Run: anyray-connect' >&2"," exit 1","fi","token=$(security find-generic-password -s 'Claude Code-credentials' -w 2>/dev/null | grep -oE 'sk-ant-oat[0-9A-Za-z._-]+' | head -n1)",'if [ -z "${token}" ]; then'," echo 'Anyray: no Claude subscription sign-in found; run: claude' >&2"," exit 1","fi",'printf \'{"token":"%s","headers":%s}\\n\' "${token}" "${headers}"',""].join(`
|
|
213
|
+
`)},ZD=e=>{if(!e.startsWith(VD))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=Gf(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return YD(a)===e?a:void 0},RA=e=>GD(e)??jD(e)??ZD(e),XD=async()=>{let e=bA("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},JD=async e=>{let t=[e.command,...Ol(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>AA(r)))).every(r=>r.isFile())?(await Il(e.command,kA.X_OK),!0):!1}catch{return!1}},zD=0,_l=async(e,t,n)=>{await _D($D(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${zD++}.tmp`;try{await PD(r,t,{mode:n}),await OD(r,n),await TD(r,e)}catch(o){throw await na(r,{force:!0}).catch(()=>{}),o}},Bn=async(e,t)=>{await _l(e,`${JSON.stringify(t,null,2)}
|
|
214
|
+
`,384)},wn=async e=>{if(!await zs(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await Uf(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!gn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},ti=async e=>{if(!await zs(e))return{present:!1};let t=await AA(e);return{present:!0,content:await Uf(e,"utf-8"),mode:t.mode&511}},OA=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:lt(e[t])}:{present:!1},Bf=(e,t,n)=>{n.present?e[t]=lt(n.value):delete e[t]},hA=e=>gn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),qD=e=>gn(e)&&hA(e.original)&&hA(e.lastWritten),QD=e=>gn(e)&&typeof e.present=="boolean"&&(!e.present||typeof e.content=="string"&&typeof e.mode=="number"&&Number.isInteger(e.mode)&&e.mode>=0&&e.mode<=511),mA=(e,t)=>gn(e)&&t.every(n=>qD(e[n])),eN=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],tN=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],jf=(e,t,n,r)=>!(!gn(e)||e.version!==n||typeof e.configId!="string"||!Js.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!Js.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!gn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==CA||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!mA(e.config,r)||r.some(o=>e.config[o].original.present)||!mA(e.deployment,ei)||!gn(e.helper)||e.helper.path!==t.helper||!QD(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),nN=(e,t)=>jf(e,t,Hf,Qs),rN=(e,t)=>jf(e,t,2,eN),oN=(e,t)=>jf(e,t,3,tN),aN=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),yA=e=>({...e,version:Hf,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),Vf=async e=>{if(!await zs(e.journal))return;let t;try{t=JSON.parse(await Uf(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(nN(t,e))return t;if(oN(t,e))return yA(t);if(rN(t,e))return yA(aN(t));throw new Error(`${e.journal} is not a valid ownership journal`)},gA=async(e,t)=>{await _l(e,`${JSON.stringify(t,null,2)}
|
|
215
|
+
`,384)},qs=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!Js.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!gn(o)||typeof o.id!="string"||!Js.test(o.id)||typeof o.name!="string"||r.has(o.id))throw new Error("Claude config-library metadata has an invalid entry");r.add(o.id)}if(!r.has(t))throw new Error("Claude config-library appliedId is not in entries");return t},sN=async(e,t,n)=>{let r=await wn(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:lt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[lt(t.metaEntry)]}}}let c=qs(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!Xs(d,t.metaEntry))throw new Error("Claude changed the Anyray config-library entry after apply");return{configId:t.configId,meta:r,metaFileExisted:t.metaFileExisted,originalAppliedId:t.originalAppliedId,metaEntry:lt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...lt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=qs(r.value);let c=Ft(e.library,`${o}.json`);if(!await zs(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=lt(r.value.entries)}let s=n();if(!Js.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await zs(Ft(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:CA};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?lt(r.value):{},appliedId:s,entries:[...a,i]}}},iN=(e,t)=>{let n=oo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},_A=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),cN=async(e,t,n,r,o,a,s)=>{let i=_A(),c=Object.fromEntries(Qs.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(ei.map(d=>[d,{original:s?.deployment[d].original??OA(r.value,d),lastWritten:i[d]}]));return{version:Hf,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??lt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await ti(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},xl=e=>({status:"manual",messages:[e]}),lN=e=>{let t=[...e.filter(n=>n.audience==="user"),...e.filter(n=>n.audience==="admin")];return{status:"manual",manualAudience:t.some(n=>n.audience==="user")?"user":"admin",messages:t.length===1?[t[0].message]:[`Not configured \u2014 ${t.length} things are in the way:`,...t.map((n,r)=>`${r+1}. ${n.message}`)]}},dN=MD(RD),uN=new Set(Sl),pN=async e=>{try{let{stdout:t}=await dN("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return gn(n)?Object.keys(n):void 0}catch{return}},ao=async(e,t={})=>{let n=t.readManagedPolicyKeys??pN;for(let r of e.managedPolicies){let o=await FD(r);if(o==="absent")continue;if(o==="unreadable")return{path:r,keys:[],unreadable:!0};let a=await n(r);if(a===void 0)return{path:r,keys:[],unreadable:!0};let s=a.filter(i=>El(i)&&!uN.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},Yf=e=>{if(e.unreadable)return`Claude Desktop may be centrally managed by ${e.path}, which could not be read; Connect did not change its inference configuration.`;let t=e.keys.slice(0,8).map(o=>/^[A-Za-z][A-Za-z0-9]{0,63}$/u.test(o)?o:"<unrecognized key>"),n=e.keys.length-t.length,r=`${t.join(", ")}${n>0?`, +${n} more`:""}`;return`Claude Desktop is centrally managed by ${e.path} (${r}); Connect did not change that managed configuration.`},Zf=e=>(e.platform??DD)()==="darwin",TA=async(e,t,n={})=>{if(!Zf(n))return xl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Rl)()&&r.push({audience:"user",message:"Claude Desktop is running. Fully quit it, then re-run connect so its cached state cannot overwrite the change."});let o=tn(n),a=await ao(o,n);if(a&&r.push({audience:"admin",message:Yf(a)}),r.length>0)return lN(r);let s=!1,i=!1,c=[o.journal];try{let l=J(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??XD)())throw new Error("Claude subscription mode requires a readable Claude Code sign-in in the macOS Keychain; run `claude` and sign in, then re-run Connect");let d=l?"passthrough":"json",u=BD((n.credentialCommand??(()=>Wf(d)))(),d),f=KD(u),p=await Vf(o),h=await ti(o.helper);if(p&&h.present&&h.content!==p.helper.lastWritten&&h.content!==p.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!p&&h.present&&h.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let m=await sN(o,p,n.randomUUID??ID),w=Ft(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await wn(w),y=await wn(o.appConfig),b=iN(e,o.helper),v=await cN(o,m,g,y,f,b,p);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${m.configId} for ${e.anthropicBaseUrl}, activate it in third-party mode, and install a ${l?"subscription pass-through":"dynamic API-billed"} credential helper at ${o.helper}.`]};s=!0,await gA(o.journal,v),i=!0,await _l(o.helper,f,448),v.helper.previousWritten!==void 0&&(delete v.helper.previousWritten,await gA(o.journal,v));let S=lt(g.value);for(let A of Qs)Bf(S,A,b[A]);await Bn(w,S),m.metaToWrite&&await Bn(o.meta,m.metaToWrite);let E=lt(y.value),x=_A();for(let A of ei)Bf(E,A,x[A]);return await Bn(o.appConfig,E),{status:"configured",changedFiles:[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig],messages:[`Configured Claude Desktop's native local gateway profile \u2192 ${e.anthropicBaseUrl}.`,l?`Installed a subscription pass-through credential helper at ${o.helper}; the helper reads your Claude Code subscription token on demand and no credential is stored in Claude's config.`:`Installed a dynamic credential helper at ${o.helper}; no gateway key is stored in Claude's config.`,l?"Claude Desktop Gateway requests now ride your Claude subscription through Anyray for content-free metering and optimization. Stay signed in to Claude Code so the token remains available.":"Claude Desktop uses its API-billed third-party inference lane; its first-party subscription remains separate.","Fully quit and reopen Claude Desktop to load the change.",...Cl]}}catch(l){let d=l instanceof Error?l.message:String(l);return s?{status:"manual",changedFiles:c,messages:[i?`Claude Desktop setup stopped after its ownership journal was written (${d}). Some listed files may contain a partial Anyray configuration.`:`Claude Desktop setup stopped while writing its ownership journal (${d}). No app configuration write was attempted, but the journal path may need cleanup.`,i?"Re-run connect to converge the journaled setup, or run --revert to restore the pre-Anyray values.":`Inspect ${o.journal}, then re-run connect.`]}:xl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},wA=(e,t,n,r)=>{let o=lt(e);for(let a of n){let s=t[a];Xs(OA(e,a),s.lastWritten)?Bf(o,a,s.original):r.push(a)}return o},PA=async(e,t={})=>{if(!Zf(t))return{status:"not-found",messages:[]};if((t.appRunning??Rl)())return xl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=tn(t);try{let r=await Vf(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Ft(n.library,`${r.configId}.json`);if(e.dryRun)return{status:"reverted",messages:[`Would restore Anyray-owned Claude Desktop fields from ${n.journal}, preserving user changes.`]};let a=[],s=await wn(o),i=s.value;s.present&&(i=wA(s.value,r.config,Qs,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await wn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=qs(l.value),m=lt(l.value.entries),w=m.findIndex(b=>b.id===r.configId),g=w>=0?m[w]:void 0,y=g!==void 0&&Xs(g,r.metaEntry);if(g!==void 0&&!y&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=lt(l.value),h===r.configId){let b=r.originalAppliedId;b&&m.some(v=>v.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&y?(m.splice(w,1),d.entries=m):c&&g===void 0&&(d.entries=m)}else{let b=Xs(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(y&&m.splice(w,1),d={...lt(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await na(o,{force:!0}):await Bn(o,i)),l.present&&(u?await na(n.meta,{force:!0}):Xs(l.value,d)||await Bn(n.meta,d));let f=await wn(n.appConfig);if(f.present){let h=wA(f.value,r.deployment,ei,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await na(n.appConfig,{force:!0}):await Bn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await ti(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await _l(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await na(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await na(n.journal,{force:!0}),{status:"reverted",changedFiles:[o,n.meta,n.appConfig,n.helper,n.journal],messages:["Restored Claude Desktop fields owned by Anyray.",...a.length>0?[`Preserved values changed after connect: ${[...new Set(a)].join(", ")}.`]:[],"Fully quit and reopen Claude Desktop to load the restored configuration.",...a.length>0?[]:vl]}}catch(r){return xl(`Could not safely revert Claude Desktop (${r instanceof Error?r.message:String(r)}). Existing config was left in place where ownership could not be proven.`)}},Xf=async(e,t={})=>{if(!Zf(t))return!1;let n=tn(t);if(await ao(n,t))return!1;try{let r=await wn(n.meta);if(!r.present)return!1;let o=qs(r.value),a=await wn(Ft(n.library,`${o}.json`)),s=await wn(n.appConfig);if(!a.present||!s.present)return!1;await Il(n.helper,kA.X_OK);let i=Ye(e);return a.value.inferenceProvider==="gateway"&&a.value.inferenceGatewayBaseUrl===i&&a.value.inferenceGatewayAuthScheme==="bearer"&&a.value.inferenceCredentialKind==="helper-script"&&a.value.inferenceCredentialHelper===n.helper&&!Object.prototype.hasOwnProperty.call(a.value,"inferenceGatewayApiKey")&&s.value.deploymentMode==="3p"&&!Object.prototype.hasOwnProperty.call(s.value,"awaitingSignIn")}catch{return!1}},LA=async(e={})=>{try{let t=tn(e),n=await ti(t.helper);if(!n.present||typeof n.content!="string")return;let r=RA(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},DA=async(e,t={})=>{if(!await Xf(e,t))return!1;let n=tn(t);try{let r=await Vf(n);if(!r)return!1;let o=await wn(n.meta);if(!o.present||qs(o.value)!==r.configId)return!1;let a=await ti(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=RA(a.content??"");return s?await(t.helperLauncherAvailable??JD)(s):!1}catch{return!1}};import{createHash as JA,randomUUID as zA}from"node:crypto";import{spawn as fN,spawnSync as hN}from"node:child_process";import{link as nh,mkdir as Jf,open as qA,readFile as zf,readdir as QA,rename as eC,rm as nn,stat as tC}from"node:fs/promises";import{homedir as rh}from"node:os";import{basename as nC,dirname as ri,join as da,win32 as mN}from"node:path";import{isDeepStrictEqual as oa}from"node:util";var Pe="HKCU\\SOFTWARE\\Policies\\Claude",ni="HKLM\\SOFTWARE\\Policies\\Claude",Dl=5,ua="inferenceGatewayApiKey",$e=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ua],NA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ua],$A=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ua],MA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ua],rC="Managed by anyray-connect; dynamic credential only.",yN=e=>/^[A-Za-z]:[\\/]/.test(e)&&mN.isAbsolute(e),FA=e=>{if(!yN(e)||/[\0\r\n"]/u.test(e))return!1;let t=e.replace(/\\/g,"/").toLowerCase();return!/(^|\/)_npx(\/|$)/u.test(t)&&!/\/appdata\/local\/temp(\/|$)/u.test(t)&&!/(^|\/)temp(\/|$)/u.test(t)},oC=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!FA(e.command)||!/\.exe$/iu.test(e.command))throw new Error("the credential helper executable is not durable");if(e.args.length<2||e.args.length>3||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--json"||e.args.length===3&&!FA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},oh=(e={})=>da((e.home??rh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),gN=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},wN=e=>(oC(e),["@echo off",`REM ${rC}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(gN).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
216
|
+
`)),bN=e=>{let t="";for(let n=0;n<e.length;n++){if(e[n]!=="%"){t+=e[n];continue}if(e[n+1]!=="%")return;t+="%",n++}return t},aC=e=>{let t=e.split(`\r
|
|
217
|
+
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${rC}`||t[2]!=="setlocal DisableDelayedExpansion"||t[4]!=="exit /b %ERRORLEVEL%"||t[5]!==""||!t[3].startsWith('"')||!t[3].endsWith('"'))return;let r=t[3].slice(1,-1).split('" "').map(bN);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return oC(s),s}catch{return}},kN=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>tC(r)))).every(r=>r.isFile())}catch{return!1}},AN=async(e,t)=>{let n=aC(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??kN)(n)}catch{return!1}},qf=e=>({sha256:so(e),content:e}),BA=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Bt(t,["sha256","content"])&&ON(t.sha256)&&typeof t.content=="string"&&so(t.content)===t.sha256&&aC(t.content)!==void 0},ah=()=>{let e=hN("tasklist.exe",["/FI","IMAGENAME eq Claude.exe","/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0,timeout:2e3,maxBuffer:65536});return e.error||e.signal||e.status!==0?!0:/(?:^|\r?\n)"Claude\.exe",/iu.test(e.stdout??"")},CN=async(e,t)=>{await Jf(ri(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await qA(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await nh(n,e)}finally{await nn(n,{force:!0}).catch(()=>{})}},vN=e=>`${nC(e)}.anyray-old-`,SN=e=>`${e}.anyray-old-${process.pid}-${zA()}`,sC=async(e,t)=>{try{await nh(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await nn(t,{force:!0}),!0},Pl=async(e,t,n,r,o)=>{let a=SN(e),s=n===void 0?void 0:so(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${zA()}`,c=!1;try{if(i&&n!==void 0){let d=await qA(i,"wx",384);try{await d.writeFile(n,"utf8"),await d.sync()}finally{await d.close()}}await o.helperFileOperationHook?.({operation:r,phase:"before-move",path:e,recoveryPath:a}),await eC(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ca(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await nh(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await la(e)!==s))throw new Error("credential helper publication verification failed");await nn(a,{force:!0}),c=!1}catch(l){throw c&&await sC(e,a).catch(()=>!1),l}finally{i&&await nn(i,{force:!0}).catch(()=>{})}},Qf=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,EN=String.raw`
|
|
218
218
|
$ErrorActionPreference = 'Stop'
|
|
219
219
|
try {
|
|
220
220
|
$request = ConvertFrom-Json ([Console]::In.ReadToEnd())
|
|
@@ -283,29 +283,29 @@ try {
|
|
|
283
283
|
exit 5
|
|
284
284
|
} catch {
|
|
285
285
|
exit 6
|
|
286
|
-
}`,
|
|
287
|
-
`)}catch(a){if(a.code!=="EEXIST")throw await
|
|
288
|
-
`;t.writeJournalFile?await t.writeJournalFile(n,r):await he(n,r)},IN=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,ON=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),RN=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),_N=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),PN=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===_N(t).toUpperCase(),YA=(e,t,n,r,o)=>{let a=Ne.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},TN=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,LN=(e,t)=>{if(!vl(e,!0))return!1;let n=TN(t);if(RN.has(n))return!1;if(ON.has(n))return n==="REG_EXPAND_SZ"?!0:!dA(e,!0)},DN=(e,t)=>{let n=sC(),r=!1,o=!1,a=!1,s=t.toUpperCase()===ti.toUpperCase(),i=(l,d)=>{if(!s)return;let u=LN(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),YA(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||PN(d,t))continue;let u=IN.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),YA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Bn=async(e,t=Te)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:sC(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return DN(n.stdout,t)},wr=async e=>{let t=await Bn(e,ti);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...Ne.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},lh=e=>e.unparsed?`This machine may have a Claude policy under ${ti} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${ti} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${ti} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Dl=(e,t)=>ea(ro(e,t)),iC=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],NN=(e,t)=>{let n=Dl(e,t);return Object.fromEntries(Ne.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},$N=(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}}),MN=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,Qf=e=>Object.fromEntries(Ne.map(t=>[t,wN(t,e[t])])),ZA=(e,t,n,r)=>({version:Tl,registryKey:Te,keyExisted:e,lastWritten:Qf(t),helper:{path:n,lastWritten:zf(r)}}),FN=(e,t,n,r,o,a)=>({version:Tl,registryKey:Te,keyExisted:e,lastWritten:Qf(t),pending:Qf(n),helper:{path:r,...o?{lastWritten:zf(o)}:{},pending:zf(a)}}),eh=(e,t,n)=>oa(n,e.lastWritten[t])||e.pending!==void 0&&oa(n,e.pending[t]),ia=async e=>{try{let t=await Jf(e,"utf8");return{content:t,sha256:ao(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ca=async e=>(await ia(e))?.sha256,aa=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Pl=async(e,t)=>{let n=fN(e),r;try{r=await qA(ni(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>la(ni(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([ia(e),ia(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!aa(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await aC(e,a))throw new Error("credential helper changed during recovery");return}if(t&&aa(t,s.sha256)&&aa(t,i.sha256)){await tn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},dh=async(e,t,n)=>(n.present?await e(iC(Te,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Te,"/v",t,"/f"])).code===0,BN=async(e,t,n)=>{let r=!0,o=await Bn(e);for(let a of Ne)if(!ra(o.values[a],t[a])){if(!ra(o.values[a],n[a])){r=!1;continue}await dh(e,a,t[a])||(r=!1),o=await Bn(e)}return r&&Ne.every(a=>ra(o.values[a],t[a]))},ze=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Ft(n)]}}),cC=async(e,t,n,r={})=>{if(!Ie(t))return ze("A valid personal ark_ gateway key is required.",!1,r);let o=rh(r),a;try{a=cN((r.credentialCommand??Hf)())}catch{return ze("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=ao(a),i=r.runReg??Un,c=Ft(r),l;if(!n.dryRun)try{l=await ah(r)}catch(m){return ze(m instanceof sa?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; the registry was left unchanged.",!1,r)}let d,u,f,p,h=!1;try{let m=await wr(i);if(m)return ze(lh(m),!1,r);let w=await ch(r,!n.dryRun);n.dryRun||await Pl(o,w);let g=await Bn(i),y=NN(e,o),b=await ia(o),v=b?.sha256,S=!1;if(d=w,u=g,f=y,w){let A=Ne.find(I=>!eh(w,I,g.values[I]));if(A)return ze(`Claude's ${A} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(v!==void 0&&!aa(w,v))return ze(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);S=MN(w)}else{if(v!==void 0&&v!==s)return ze(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let A=g.foreignState||Ne.some(M=>g.values[M].present),I=Ne.every(M=>ra(g.values[M],y[M])),R=Ne.every(M=>ra(g.values[M],$N(e,t.trim())[M]));if(A&&!I&&!R)return ze(`Existing Claude third-party-inference policy values under ${Te} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(S=R,I&&v===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Te} into an owner-only journal without rewriting them.`]}:(await Rl(ZA(g.keyPresent,y,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Te} into the ownership journal.`]})}if(S){let A=!0;try{A=(r.appRunning??oh)()}catch{}if(A)return ze("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=FN(w?.keyExisted??g.keyPresent,g.values,y,o,b?.content,a);if(p=E,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Te}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Rl(E,r),h=!0;for(let A of Ne){let I=await Bn(i);if(!oa(I.values[A],E.lastWritten[A])&&!oa(I.values[A],E.pending[A]))throw new Error("registry value changed during apply");if(!ra(I.values[A],y[A])&&!await dh(i,A,y[A]))throw new Error("registry write failed")}let x=await Bn(i);if(!Ne.every(A=>oa(x.values[A],E.pending[A])))throw new Error("registry verification failed");if(v!==s&&(v===void 0?await pN(o,a):await _l(o,v,a,"apply",r)),await ca(o)!==s)throw new Error("credential helper verification failed");return await Rl(ZA(E.keyExisted,y,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Te}.`,`Installed or updated the dynamic credential helper at ${o}; no personal key is stored in policy or the ownership journal.`,"Fully quit and reopen Claude Desktop to load the policy.",...kl]}}catch{if(!h||!u||!f||!p)return ze("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Pl(o,p);let m=!0,w=await ia(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await _l(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await ca(o)===p.helper.lastWritten.sha256):await _l(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await BN(i,u.values,f))return d?await Rl(d,r):await tn(c,{force:!0}),ze("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return ze("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},lC=async(e,t={})=>{let n=t.runReg??Un,r=Ft(t),o;if(!e.dryRun)try{o=await ah(t)}catch(a){return ze(a instanceof sa?"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 ch(t,!e.dryRun);a&&!e.dryRun&&await Pl(a.helper.path,a);let s=await Bn(n);if(!a)return Ne.filter(h=>s.values[h].present).length>0?ze(`Claude policy values exist under ${Te}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=Ne.filter(p=>s.values[p].present&&!eh(a,p,s.values[p])),c=await ca(a.helper.path),l=c!==void 0&&!aa(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Te}.`,`Would remove the Anyray-owned credential helper at ${a.helper.path}.`,...i.length||l?[`Would preserve changed values: ${[...i,...l?["credential helper"]:[]].join(", ")}.`]:[]]};let d=!1,u=new Set(i);for(let p of Ne){let m=(await Bn(n)).values[p];if(m.present){if(!eh(a,p,m)){u.add(p);continue}await dh(n,p,{present:!1})||(d=!0)}}let f=await ca(a.helper.path);if(f!==void 0)if(aa(a,f))try{await _l(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?ze(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await tn(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Te}.`,"Removed the Anyray-owned dynamic credential helper when its content still matched the journal.",...u.size?[`Preserved values changed after Connect: ${[...u].join(", ")}.`]:[],...u.size?[]:Al]})}catch{return ze(`Could not safely inspect or revert ${Te}; no unproven value was removed.`,!1,t)}finally{await o?.()}},dC=async(e,t={})=>{let n=t.runReg??Un;if(!await O(Ft(t)))return;let r;try{r=await ah(t);let o=await ch(t);if(o&&await Pl(o.helper.path,o),!o||o.pending||await wr(n)!==void 0)return;let a=await Bn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ye(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Ne.every(l=>oa(a.values[l],o.lastWritten[l]))))return;let i=await ca(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 uN(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?.()}},uC=async(e,t={})=>await dC(e,t)!==void 0,pC=async(e,t={})=>await dC(e,t)==="dynamic";var ua=(e=HN())=>e==="win32"?oh:xl,uh="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",$l=async(e,t={})=>{let n=(t.profileRoot??no)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:uh};if((t.appRunning??ua(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await fC.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 bl(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 "+uh}:{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??rA)();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=Nl(t.stagingRoot??WN(),`anyray-history-${process.pid}-${UN()}`);try{let s=await(t.runImporter??oA)({binary:o,exportPath:e,configDir:Nl(a,"config"),workDir:Nl(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. "+uh};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 sA(r.dir,s.conversations),c=await iA({stagedProjectsDir:Nl(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 fC.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Et}from"node:fs";import{homedir as d$}from"node:os";import{join as rn,sep as u$}from"node:path";import{isDeepStrictEqual as Ul}from"node:util";import{constants as KN}from"node:fs";import{promises as G}from"node:fs";import{dirname as pa,isAbsolute as fh,join as Q,relative as Ml,resolve as nn,sep as ri}from"node:path";import{randomUUID as Hl}from"node:crypto";var wn=448,oi=384,gC=448,GN=4,hh=3e4,wC=5e3,jN=10*6e4,ph=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),dt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ai=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),bC=(e,t)=>{let n=Ml(nn(e),nn(t));return n===""||!n.startsWith(`..${ri}`)&&n!==".."&&!fh(n)},so=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return dt(n)?{raw:t,value:n}:void 0}catch(t){return St(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},St=e=>e instanceof Error&&"code"in e,VN=e=>{try{return process.kill(e,0),!0}catch(t){return St(t)&&t.code==="EPERM"}},kC=e=>e===0?"owner.json":`owner.${e}.json`,Fl=async e=>{let t;try{t=await G.readdir(e)}catch{return}let r=t.map(d=>{if(d==="owner.json")return{name:d,generation:0};let u=/^owner\.(\d+)\.json$/.exec(d);if(!u)return;let f=Number(u[1]);return Number.isSafeInteger(f)&&f>0?{name:d,generation:f}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=Q(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));dt(d)&&typeof d.pid=="number"&&Number.isSafeInteger(d.pid)&&d.pid>0&&typeof d.nonce=="string"&&d.nonce.length>0&&(a=d.pid,s=d.nonce,typeof d.createdAt=="number"&&Number.isFinite(d.createdAt)&&d.createdAt>=0&&(i=d.createdAt))}catch{}let c=await G.stat(o).then(d=>d.mtimeMs),l=i!==void 0&&i<=Date.now()+6e4?i:c;return{generation:r.generation,pid:a,nonce:s,createdAtMs:l,mtimeMs:c}},AC=e=>{if(e.pid===void 0||!VN(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>hh&&t-e.createdAtMs>jN},YN=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(pa(t),{recursive:!0,mode:wn});let n=Hl(),r,o=!1;try{await G.mkdir(t,{mode:wn}),o=!0}catch(i){if(!St(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Fl(t);if(d){if(!AC(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=hh)return}let l=Q(t,kC(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
289
|
-
`,{flag:"wx",mode:
|
|
290
|
-
`,{mode:
|
|
291
|
-
`,{flag:"wx",mode:
|
|
292
|
-
`)}},gh=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),DC=async e=>{let t=[];for(let n of h$)t.push({lane:n,sources:await y$(e,n)});return t},NC=async(e={})=>{let t=(e.firstPartyRoot??(()=>js()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([DC(t),mh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=gh(n);for(let s of r.accounts)a.add(s);return{sessions:o,accounts:a.size,userSkills:r.skills,userPlugins:r.plugins,localMcpServers:r.localMcpServers}},io=async(e={})=>{let t=(e.home??d$)(),n=(e.firstPartyRoot??(()=>js()))(),r=(e.thirdPartyRoot??(()=>no()))();if(!n||!r)return{ok:!1,kind:"platform-unsupported",reason:"this platform has no Claude Desktop third-party profile",remedy:"Migration applies to macOS and Windows, where Desktop runs third-party mode in its own profile."};if((e.appRunning??ua())())return{ok:!1,kind:"app-running",reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop and run this again \u2014 it rewrites its session list on exit, which would undo the migration."};let[o,a]=await Promise.all([DC(n),mh(n)]),s;if(e.account){let p=e.account;for(let w of o)w.sources=w.sources.filter(g=>g.account.startsWith(p));let h=a.accounts.filter(w=>w.startsWith(p));if(o.every(w=>w.sources.length===0)&&h.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${p}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let m=gh(o);for(let w of h)m.add(w);if(m.size>1)return PC(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=gh(o);for(let h of a.accounts)p.add(h);if(p.size>1)return PC(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${p.size} accounts`,a.accounts);s=[...p]}let i=e.command??"anyray-connect desktop --migrate",c=!await p$(r),l=await RC(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:s});if(l.sourceChanged)return{ok:!1,kind:"account-ambiguous",reason:"the previous Claude Desktop profile changed during migration and now holds local data for another account",remedy:`Re-run \`${i}\` so the account choice is made from a fresh snapshot.`};let d=[],u=[];for(let{lane:p,sources:h}of o){if(h.length===0){d.push(yh(p));continue}let m=await g$(r,p);if("missing"in m){u.push({lane:p,reason:m.missing,waiting:h.reduce((w,g)=>w+g.ids.length,0)}),d.push(yh(p));continue}d.push(await k$(p,h,m.dir,t))}if(!(d.some(p=>p.migrated>0||p.alreadyPresent>0)||l.outcomes.some(p=>p.migrated>0||p.alreadyPresent>0||p.conflicts>0))&&(u.length>0||l.blocked.length>0)){let p=u[0];return p?{ok:!1,kind:p.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:p.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${p.lane} store`:`Claude Desktop has no ${p.lane} store in its third-party profile yet`,remedy:wh(p.reason,p.lane,i,c)}:{ok:!1,kind:"store-missing",reason:"Claude Desktop's third-party profile has no extension store yet",remedy:"Open Claude Desktop once after connecting it to Anyray, then fully quit it so the portable extensions can be copied safely."}}return{ok:!0,lanes:d,portableAssets:l.outcomes,...u.length>0?{blocked:u}:{},...l.blocked.length>0?{blockedAssets:l.blocked}:{},...l.ambiguous.length>0?{ambiguousAssets:l.ambiguous}:{},...l.retryable.length>0?{retryableAssets:l.retryable}:{}}};var C$=e=>[ot(e)],$C=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...C$(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await O(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var MC="1.21459.0",x$=E$(v$),I$=async e=>{try{let{stdout:t}=await x$("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},O$=async e=>{try{return await S$(e)}catch{return}},FC="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",R$=["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."],fa=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(BC??=UC({}),BC):UC(e),BC,UC=async e=>{let t=(e.home??ii)(),n=["/Applications/Claude.app",bn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??I$,o=e.readClaudeAppBundle??O$;for(let a of n){let s=await r(bn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${FC}`}),c=gl(s,MC);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${MC} or newer.`);let l=await o(bn(a,"Contents","Resources","app.asar"));return l?CA.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. ${FC}`}},Gl="anyray",KC="--anyray-owner=claude-desktop-v1",jl=(e={})=>{let t=(e.platform??br)(),n=(e.home??ii)();return t==="darwin"?en(e).appConfig:t==="win32"?bn(process.env.APPDATA??bn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):bn(n,".config","Claude","claude_desktop_config.json")},vh=(e={})=>bn((e.home??ii)(),"Library","Application Support","Claude","claude_desktop_config.json"),GC=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,KC]}},co=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jC=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},_$=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),P$=e=>{if(!co(e)||!jC(e,["command","args"]))return!1;let t=GC();return e.command===t.command&&_$(e.args,t.args)},T$=e=>co(e)&&Array.isArray(e.args)&&e.args.at(-1)===KC,L$=e=>{if(!co(e)||!jC(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||Ke(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===Qn&&t.at(-1)==="profile"))return!1;let r=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(r))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(r)||t.length!==3)return!1;let o=t[0].replaceAll("\\","/");return!Ke(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},D$=e=>e===void 0?"absent":P$(e)?"exact":T$(e)||L$(e)?"stale-owned":"foreign",Be=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},lo=async e=>{let t=await O(e),n;try{n=await F(e)}catch{throw new Be(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!co(n.mcpServers))throw new Be(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(co(n.mcpServers)?n.mcpServers:void 0)?.[Gl];return{path:e,fileExisted:t,json:n,entry:o,ownership:D$(o)}},Vl=e=>{if(e.ownership==="foreign")throw new Be(`MCP name conflict in ${e.path}: mcpServers.${Gl} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},VC=(e,t)=>{let n={...e},r=co(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[Gl]:r[Gl]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},kh=async(e,t)=>{if(bh(e.entry,t))return;let n=await lo(e.path);if(!bh(n.entry,e.entry))throw new Be(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Fn(e.path,VC(n.json,t)),{reading:e,afterEntry:t}},Ah=async e=>{let t=await lo(e.reading.path);if(!bh(t.entry,e.afterEntry))throw new Be(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=VC(t.json,e.reading.entry);await Fn(e.reading.path,n)},N$=async e=>{if(!ce())throw new Be(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Re()} is temporary); no inference setting was changed.`);let t=await lo(jl(e));Vl(t);let n=vh(e),r=(e.platform??br)()==="darwin"&&n!==t.path?await lo(n):void 0;return r&&Vl(r),{active:t,...r?{legacy:r}:{}}},HC=async e=>{let t=await lo(jl(e));Vl(t);let n=vh(e),r=(e.platform??br)()==="darwin"&&n!==t.path?await lo(n):void 0;return r&&Vl(r),{active:t,...r?{legacy:r}:{}}},$$=async e=>{let t=[];try{let n=await kh(e.active,GC());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await kh(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Ah(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Be(`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 Ah(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Be(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},M$=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await kh(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Ah(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Be(`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)},WC=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)."]},F$={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Yl="claude-desktop",Ch="migrate",YC=new Set(["app-running","store-missing"]),B$={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},U$={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"}},H$="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",ZC=e=>{let t=(e.platform??br)(),n=e.home??ii;return{home:n,appRunning:e.appRunning??ua(t),firstPartyRoot:()=>js({home:n,runtimePlatform:t}),thirdPartyRoot:()=>no({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},XC=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=B$[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.`:"")},JC=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=U$[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.`:"")},si=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=ZC(e),r=await(e.pendingDesktopMigrationCount??NC)(n),o=r.userSkills+r.userPlugins+r.localMcpServers;if(r.sessions+o===0)return[];if(t.dryRun)return[`Would bring ${[r.sessions>0?`${r.sessions} existing Claude Desktop session${r.sessions===1?"":"s"}`:"",o>0?`${o} portable configuration ${o===1?"entry":"entries"}`:""].filter(Boolean).join(" and ")} into Claude Desktop's third-party profile, now or automatically the next time Claude Desktop is fully quit.`];let a=await(e.migrateDesktopProfile??io)(n);if(a.ok){let c=XC(a.lanes),l=JC(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(a.blocked??[]).filter(y=>y.reason!=="ambiguous"),p=a.blockedAssets??[],h=a.retryableAssets??[];if(f.length===0&&p.length===0&&h.length===0)return[c,l,u].filter(y=>!!y);if(t.preservePendingOp)return[c,l,u].filter(y=>!!y);await As(Yl,Ch);let m=f.reduce((y,b)=>y+b.waiting,0),w=[m>0?`${m} more session${m===1?"":"s"}`:"",p.length>0?`${p.length} extension ${p.length===1?"store":"stores"}`:""].filter(Boolean),g=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...h.length>0?[`Queued: ${h.length} portable configuration ${h.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...g]}if(!YC.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
293
|
-
${a.remedy}`];if(t.preservePendingOp)return[];await As(Yl,Ch);let s=r.sessions+o,i=`${s} Claude Desktop local ${s===1?"item":"items"}`;return[a.kind==="store-missing"?`Queued: the ${i} still in your previous profile move across once Claude Desktop's new profile has been signed in to and the app is fully quit.`:`Queued: the ${i} still in your previous profile will move across the next time you fully quit Claude Desktop.`]}catch{return["Could not check whether Claude Desktop had existing sessions to bring across; run `anyray-connect migrate` if its lists look empty."]}},W$=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await cr(Yl),[]}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."]}},K$=e=>$C({id:Yl,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??br)(),n=(e.home??ii)();return t==="darwin"?["/Applications/Claude.app",bn(n,"Applications","Claude.app")]:t==="win32"?[bn(process.env.LOCALAPPDATA??bn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>J(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",...WC(t)]:["Claude desktop org/API lane:",...WC(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`."]}),G$=(e={})=>{let t=K$(e),n=()=>(e.platform??br)()==="darwin",r=()=>(e.platform??br)()==="win32",o=(s,i)=>n()?_A(s,i,e):cC(s,s.clientKey??"",i,e),a=s=>n()?PA(s,e):lC(s,e);return{...t,automatic:!0,quitGated:{isRunning:()=>(e.appRunning??ua((e.platform??br)()))(),quitTarget:F$,needsTarget:()=>!1,async complete(s){if(s!==Ch)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??io)(ZC(e));if(i.ok){let c=XC(i.lanes),l=JC(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let f=(i.blocked??[]).filter(m=>m.reason!=="ambiguous"),p=i.blockedAssets??[],h=i.retryableAssets??[];return f.length>0||p.length>0||h.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...f.length>0||p.length>0?["Still waiting on Claude Desktop to create the remaining third-party stores, which appear the first time those parts of the app are opened."]:[],...h.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(m=>!!m):["No portable Claude Desktop data was left to bring across."]}}return YC.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?LA(s,e):r()?pC(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=en(e),p=await oo(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[Vf(p),...await si(e,i)]}}if(r()){let f;try{f=await wr(e.runReg??Un)}catch{return{status:"manual",manualAudience:"admin",messages:[H$,...await si(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[lh(f),...await si(e,i)]}}if(r()&&J(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let f=await fa(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await N$(e)}catch(f){let p=f instanceof Be?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Be?f.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no inference setting was changed."]}}let l=await o(s,{dryRun:!0});if(l.status!=="configured")return l;if(i.dryRun){let f=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...f&&f.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${f.path}.`]:[],...await si(e,i)]}}let d;try{d=await $$(c)}catch(f){let p=f instanceof Be?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Be?f.message:"Could not safely register Claude Desktop retrieval; the inference route was left unchanged."]}}let u;try{u=await o(s,{dryRun:!1})}catch{u={status:"manual",messages:["Claude Desktop inference setup failed before it returned a result."]}}if(u.status!=="configured")try{return await d.rollback(),{...u,changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])],messages:[...u.messages,"Restored the prior Claude Desktop MCP registration because inference setup did not complete. A config file that was absent before setup may remain as an inert object to avoid racing unrelated concurrent writes."]}}catch{return{status:"manual",changedFiles:[...u.changedFiles??[],...d.changedFiles],messages:[...u.messages,"Inference setup did not complete, and the prior MCP registration could not be fully restored. Re-run `anyray-connect desktop disconnect` to recover safely."]}}return{...u,messages:[...u.messages,"Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) with an ownership marker.",...await si(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?R$:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=jl(e),c=await W$(s),l=m=>c.length===0?m:{...m,messages:[...m.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await HC(e)}catch(m){return l({status:"manual",messages:[m instanceof Be?m.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let m=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...m&&m.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${m.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let m=r()?Ft(e):void 0;if(!(m!==void 0&&f.changedFiles?.includes(m)===!0&&!await O(m)))return l(f)}let p;try{p=await M$(await HC(e))}catch(m){let w=m instanceof Be?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof Be?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await ne(i);let h=vh(e);return n()&&h!==i&&await ne(h),l({...f,messages:[...f.messages,...p.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...p])]})},async mcpStatus(){if(!ce())return{registered:!1,command:null};try{let s=await lo(jl(e));return s.ownership!=="exact"||!co(s.entry)?{registered:!1,command:null}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null}}},async pointsAt(s){return n()?(await fa(e)).supported?Zf(s,e):!1:r()?uC(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await fa(e)).supported)return["unknown"];let s=await TA(e);return s?[s]:["unknown"]}if(r())return await O(Ft(e))?await wr(e.runReg??Un)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=en(e);return!await O(s.journal)||await oo(s,e)?!1:(await fa(e)).supported}return r()&&await O(Ft(e))?!await wr(e.runReg??Un):!1}catch{return!1}}}},zC=G$();import{homedir as wM}from"node:os";import{join as bM}from"node:path";import{rm as nd}from"node:fs/promises";import{constants as qC,accessSync as j$,statSync as V$}from"node:fs";import{platform as Sh}from"node:os";import{delimiter as Y$,posix as Z$,resolve as X$,win32 as J$}from"node:path";var z$="0.59.0",q$="1.1.4",Hn="Anyray \xB7 Claude",Wn="Anyray \xB7 Codex",Zl="__anyray-acp-agent",QC=(e,t,n)=>{let{command:r,args:o}=ln([Zl,e,t,n]);return{command:r,args:o,env:{}}},Xl=(e=Sh())=>e==="win32"?"npx.cmd":"npx",Jl=(e=process.env.PATH,t=Sh())=>{if(!e)return;let n=Xl(t);for(let r of e.split(Y$)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=X$(o,n);try{if(!V$(a).isFile())continue;return j$(a,t==="win32"?qC.F_OK:qC.X_OK),a}catch{}}},zl=(e,t=Sh())=>{let n=t==="win32"?J$:Z$;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==Xl(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},Q$="https://chatgpt.com/backend-api/codex",eM="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",ev="ANYRAY_ACP_CODEX_AUTHORIZATION",tv="ANYRAY_ACP_CODEX_CLIENT_KEY",nv="ANYRAY_ACP_CODEX_METADATA",rv=e=>le({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),tM=(e,t={})=>{let n=J(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":Q$,"x-anyray-forward-headers":eM}:{},o=n?{...e.clientKey?{"x-anyray-api-key":tv}:{}}:{Authorization:ev};return rv(e)&&(o["x-anyray-metadata"]=nv),{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}}}:{}}},nM=e=>{let t=J(e,"openai"),n=rv(e);return{...t?e.clientKey?{[tv]:e.clientKey}:{}:{[ev]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[nv]:n}:{}}},ov=(e,t=Xl(),n={})=>({[Hn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${z$}`],env:dn(e).env},[Wn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${q$}`],env:{CODEX_CONFIG:JSON.stringify(tM(e,n)),...nM(e)}}}),ci=(e=Xl(),t="jetbrains")=>({[Hn]:QC("claude",e,t),[Wn]:QC("codex",e,t)}),uo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ql=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as rM}from"node:zlib";import{open as oM,readFile as Rh,readdir as td}from"node:fs/promises";import{dirname as av,join as de}from"node:path";import{homedir as lv,platform as _h}from"node:os";var Ql="2025.3.2",ha="253.30387.147",li="com.intellij.ml.llm",Eh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),aM=1e4,sM=256*1024*1024,iM=16*1024*1024,xh=1024*1024,Ih=22,cM=Ih+65535,Oh=gl,lM=()=>{let e=lv(),t=de(e,".cache","JetBrains","RemoteDev");switch(_h()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:de(e,"Applications"),layout:"app-bundles"},{path:de(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:de(process.env.LOCALAPPDATA??de(e,"AppData","Local"),"Programs"),layout:"children"},{path:de(process.env.LOCALAPPDATA??de(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:de(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:de(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},dM=()=>_h()==="linux"?de(lv(),".local","share","JetBrains"):ot("JetBrains"),uM=()=>_h()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),pM=async(e,t=aM)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await td(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=de(r.path,i.name),l=r.layout==="app-bundles"?de(c,"Contents","Resources","product-info.json"):de(c,"product-info.json");await O(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=de(s,"product-info.json"),l=de(s,"Contents","Resources","product-info.json");if(await O(c)){n.push(c);return}if(await O(l)){n.push(l);return}let d;try{d=await td(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=de(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(f,i-1)}};await a(r.path,7)}return[...new Set(n)]},fM=e=>{let t=av(e);return t.endsWith(`${de("Contents","Resources")}`)?av(t):t},hM=async e=>{try{let t=JSON.parse(await Rh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Ks(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:fM(e)}}catch{return}},ed=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},mM=async(e,t)=>{let n;try{n=await oM(e,"r");let{size:r}=await n.stat();if(r<Ih||r>sM)return;let o=Math.min(r,cM),a=await ed(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Ih;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>iM||c+i>r)return;let l=await ed(n,i,c);if(!l)return;let d=0;for(;d+46<=l.length;){if(l.readUInt32LE(d)!==33639248)return;let u=l.readUInt16LE(d+10),f=l.readUInt32LE(d+20),p=l.readUInt32LE(d+24),h=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),g=l.readUInt32LE(d+42),y=d+46+h+m+w;if(y>l.length)return;let b=l.subarray(d+46,d+46+h).toString("utf8");if(d=y,b!==t)continue;if(f===4294967295||p===4294967295||f>xh||p>xh)return;let v=await ed(n,30,g);if(!v||v.readUInt32LE(0)!==67324752)return;let S=v.readUInt16LE(26),E=v.readUInt16LE(28),x=await ed(n,f,g+30+S+E);return x?u===0?x.toString("utf8"):u===8?rM(x,{maxOutputLength:xh}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},sv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Ks(n)))return{id:t,version:n}},yM=async(e,t)=>{let n=de(e,"META-INF","plugin.xml");if(await O(n))try{let o=sv(await Rh(n,"utf8"));return{present:o?.id===li||t,descriptor:o?.id===li?o:void 0}}catch{return{present:t}}let r=[];try{r=(await td(de(e,"lib"),{withFileTypes:!0})).filter(o=>o.isFile()&&o.name.endsWith(".jar")&&/(?:^|[-_.])(ml-?llm|llm|aia|ai[-_.]?assistant)(?:[-_.]|$)/i.test(o.name)).slice(0,32).map(o=>de(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await mM(o,"META-INF/plugin.xml"),s=a?sv(a):void 0;if(s?.id===li)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},iv=async e=>{let t;try{t=await td(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Eh.has(o.name.toLowerCase()),i=Eh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Eh.has(o.name.toLowerCase());if(!a){let i=de(e,o.name,"META-INF","plugin.xml");if(!await O(i))continue}let s=await yM(de(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},gM=async e=>{try{return(await Rh(de(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(li)}catch{return!1}},cv=e=>e.reduce((t,n)=>t?(Oh(n,t)??-1)>0?n:t:n,void 0),dv=async(e={})=>{let t=e.configRoot??ot("JetBrains"),n=e.userPluginsRoot??dM(),r=await pM(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):lM(),e.scanBudget),o=(await Promise.all(r.map(h=>hM(h)))).filter(h=>h!==void 0),a=o.length>0||await O(t);if(e.wsl??uM())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(h=>(Oh(h.version,Ql)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let h of s){let m=de(t,h.dataDirectoryName);if(!await O(m)){d=!0;continue}let w=[de(m,"plugins"),de(n,h.dataDirectoryName),de(n,h.dataDirectoryName,"plugins")],g;for(let y of[...new Set(w)]){let b=await iv(y);if(b.present){g=b;break}}if(g??=await iv(de(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==li)){if(i.push(g.descriptor.version),await gM(m)){c=!0;continue}if(!((Oh(g.descriptor.version,ha)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${h.version}; AI Assistant ${g.descriptor.version}; ACP supported`,ideVersion:h.version,pluginVersion:g.descriptor.version}}}let u=cv(o.map(h=>h.version)),f=cv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${Ql}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${Ql}+ once, enable AI Assistant ${ha}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${ha}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${ha}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${ha}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${ha}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${Ql}+ from local product-info.json; no ACP config was written.`:p="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:p,ideVersion:u,pluginVersion:f}};var kM=[Hn,Wn],Ph=()=>bM(wM(),".jetbrains","acp.json"),po=()=>`${Ph()}.anyray-state`,AM=(e,t,n="npx")=>{let r=uo(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,ci(n,"jetbrains")),{...e,agent_servers:r}},CM=(e,t,n)=>{if(!uo(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=uo(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of kM)if(c in r){if(!ql(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}},vM=(e=dv)=>({id:"jetbrains",title:"JetBrains AI Assistant",automatic:!0,async detect(){let t=await e();return{installed:t.installed,detail:t.detail}},async apply(t,n){let r=Ph(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=Jl();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await O(r),c;try{c=await F(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=ci(a,"jetbrains");return await Yi({configPath:r,current:c,next:AM(c,t,a),journalPath:po(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,po()]}},async revert(t){let n=Ph(),r=async()=>{if(!await O(n))return t.dryRun||(await ne(n),await nd(po(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await F(n)}catch{return t.dryRun||(await ne(n),await nd(po(),{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(po());(u.version===1||u.version===2)&&uo(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await O(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await 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 Lr(n);let l=CM(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 nd(n,{force:!0}):await Z(n,l.next,{backup:!1})),t.dryRun||(await ne(n),await nd(po(),{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():Vi(n,po(),r)}}),uv=vM();import{homedir as od}from"node:os";import{join as ad}from"node:path";import{rm as Th}from"node:fs/promises";var Lh="1.0.0",sd=["anyray-claude-acp","anyray-codex-acp"],SM=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Dh=()=>ad(od(),".windsurf","acp","registry.json"),Nh=()=>ad(od(),".windsurf-next","acp","registry.json"),ma=e=>`${e}.anyray-state`,pv=e=>({binary:Object.fromEntries(SM.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),hv=(e="npx")=>{let t=ci(e,"windsurf");return[{id:sd[0],name:Hn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:pv(t[Hn])},{id:sd[1],name:Wn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:pv(t[Wn])}]},rd=e=>!Array.isArray(e)||e.some(t=>!uo(t)||typeof t.id!="string")?null:e,EM=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Lh||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:rd(e.agents);if(!n)return null;let r=new Set(sd);return{...e,version:typeof e.version=="string"?e.version:Lh,agents:[...n.filter(o=>!r.has(o.id)),...hv(t)],extensions:e.extensions??[]}},xM=(e,t,n)=>{let r=rd(e.agents);if(!r)return null;let o=rd(t.agents)??[],a=new Map((rd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!sd.includes(u.id)){l.push(u);continue}if(!ql(u,a.get(u.id))){c.push(u.id),l.push(u);continue}let f=s.get(u.id);f&&l.push(f),i.push(u.id)}let d={...e,agents:l};return!Object.prototype.hasOwnProperty.call(t,"agents")&&l.length===0&&delete d.agents,!Object.prototype.hasOwnProperty.call(t,"version")&&d.version===Lh&&delete d.version,!Object.prototype.hasOwnProperty.call(t,"extensions")&&Array.isArray(d.extensions)&&d.extensions.length===0&&delete d.extensions,{next:d,removed:i,conflicts:c}},fv=async()=>{let e=[];return(await O(Nh())||await O(ad(od(),".windsurf-next")))&&e.push(Nh()),(await O(Dh())||await O(ad(od(),".windsurf"))||await O(ot("Devin"))||await O(ot("Windsurf")))&&e.push(Dh()),e},mv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await fv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await fv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=Jl();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=EM(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await O(s),d=hv(r);await Yi({configPath:s,current:i,next:c,journalPath:ma(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,ma(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=[Dh(),Nh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await O(a)){e.dryRun||(await ne(a),await Th(ma(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 p=await F(ma(a));(p.version===1||p.version===2)&&Array.isArray(p.agents)&&(c=p.agents,l=p.version===2&&p.fileExisted===!1,d=p.version===2&&p.fileExisted===!0)}catch{}let u;if(d){let p=`${a}.anyray-bak`;if(!await O(p)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await F(p)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await Lr(a);let f=xM(i,u,c);if(!f){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}f.removed.length&&(n.push(`Removed ${f.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(f.next).length===0?await Th(a,{force:!0}):await Z(a,f.next,{backup:!1}),r.push(a))),f.conflicts.length?(n.push(`Preserved user-modified agents: ${f.conflicts.join(", ")}.`),o=!0):e.dryRun||(await ne(a),await Th(ma(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await Vi(a,ma(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var re=[tr,Cw,xs,dk,Lk,Vk,nA,uv,zC,mv,Pw],Bt=e=>re.find(t=>t.id===e);var IM=["hook_registration","mcp_registration","hook_binary","beacon_target"],fo=e=>e.status==="configured"||e.status==="queued",ho=async(e,t=re)=>{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},kr=async(e,t,n=re)=>{let r=[];for(let o of await ho(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},$h=async(e,t=re)=>{let n=[];for(let r of await ho(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(IM.map(o=>[o,"unreadable"]))})}return n},yv=e=>e.filter(t=>!t.integrationStatus),OM=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},gt=async(e,t)=>{let n=[];for(let r of e)try{let o=await r.apply(t,{dryRun:!1});n.push({id:r.id,title:r.title,status:o.status})}catch(o){let a=OM(o);if(r.classifyApplyError)try{a=r.classifyApplyError(o)}catch{}n.push({id:r.id,title:r.title,status:"failed",errorClass:a})}return n};import{mkdir as RM,writeFile as _M}from"node:fs/promises";import{join as wv}from"node:path";import{z as Ue}from"zod";var ya="required",gv=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team;return{routingUpdated:n,teamUpdated:r,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{}}},id=(e,t,n)=>{let r=new Set(t.enabled??[]),o=e.managedTools??[],a=o.filter(u=>r.has(u)||n),s=new Set(e.revertedTools??[]),i=e.revertedTools!=null,c=u=>t.tiers?.[u]??ya,l=[],d=[];for(let u of r){if(o.includes(u))continue;let f=c(u);if(f!=="optional"){if(f!=="locked"){if(!i)continue;if(s.has(u)){f==="required"&&d.push(u);continue}}l.push(u)}}return{candidateIds:a,freshIds:l,tombstonedIds:d}};var PM=1e4,TM=1,LM=Ue.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),DM=Ue.object({id:LM,name:Ue.string().min(1),version:Ue.string().min(1),body:Ue.string()}),NM=Ue.object({version:Ue.literal(TM).optional(),skills:Ue.array(DM),updatedAt:Ue.string().min(1).optional(),routing:Ue.object({origin:Ue.string().min(1)}).optional(),team:Ue.string().min(1).optional(),tools:Ue.object({enabled:Ue.array(Ue.string().min(1)),tiers:Ue.record(Ue.string().min(1),Ue.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),$M=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",cd=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",ld=async(e,t,n={})=>{let r=n.timeoutMs??PM,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`:l instanceof Error?l.message:String(l);throw new Error(`could not reach the gateway at ${o}: ${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Error(`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch(l){let d=new Error("team policy fetch failed: the gateway returned a malformed response");throw d.name=cd(l),d}return NM.parse(c)},bv=/^[a-z0-9][a-z0-9-]{0,31}$/,kv=64,MM=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>bv.test(o)).slice(0,kv).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>bv.test(o)).slice(0,kv).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},di=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??ya)==="locked":!1},dd=async(e,t={})=>{let n=t.loadProfile??T,r=t.saveProfile??ee,o=t.targetFromProfile??_e,a=t.adapters??re,s=t.repairTools??gt,i=t.recordManaged??Zn,c=await n(),l={...c},d=gv(c,{routingOrigin:e.routing?.origin?cn(e.routing.origin):void 0,team:e.team}),{routingUpdated:u,teamUpdated:f}=d;(u||f)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),await r(l));let p=id(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f),{candidateIds:h,freshIds:m}=p,w=0,g=0,y=0;if(h.length>0||m.length>0){let S=await o(async()=>l);if(S){let E;if(u||f){let I=new Set(h);E=[];for(let R of a)if(I.has(R.id))try{(await R.detect()).installed&&E.push(R)}catch{}}else E=await kr(h,S.toolOrigin,a);let x=new Set(m),A=[];for(let I of a)if(x.has(I.id))try{(await I.detect()).installed&&A.push(I)}catch{}if(w=E.length+A.length,w>0){let I=await s([...E,...A],S.target);g=I.filter(fo).length;let R=I.filter(M=>x.has(M.id));if(y=R.filter(fo).length,R.length>0)try{await i(R,!1)}catch{}}}}let b=MM(e),v=await n();if(JSON.stringify(b??null)!==JSON.stringify(v.fleetToolPolicy??null)){let{fleetToolPolicy:S,...E}=v;await r({...E,...b?{fleetToolPolicy:b}:{}})}return{routingUpdated:u,teamUpdated:f,toolsRequested:w,toolsApplied:g,toolsEnrolled:y,toolsTombstoned:p.tombstonedIds,profileUpdated:u||f}},Av=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!$M(i.id))continue;if(o[i.id]=i.version,n[i.id]===i.version){s+=1,r.push({id:i.id,name:i.name,version:i.version,written:!1,files:[]});continue}let l=[];for(let d of t){let u=wv(d,i.id),f=wv(u,"SKILL.md");await RM(u,{recursive:!0}),await _M(f,FM(i.body),"utf-8"),l.push(f)}a+=1,r.push({id:i.id,name:i.name,version:i.version,written:!0,files:l})}return{results:r,changed:a,unchanged:s,versions:o,updatedAt:e.updatedAt}},FM=e=>e.endsWith(`
|
|
286
|
+
}`,Hn=async e=>new Promise((t,n)=>{let r=fN("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",EN],{windowsHide:!0,stdio:["pipe","pipe","pipe"]}),o="",a=!1,s=!1;r.stdout.setEncoding("utf8"),r.stdout.on("data",i=>{o+=i,o.length>1024*1024&&(a=!0,r.kill())}),r.stderr.resume(),r.on("error",i=>{s||(s=!0,n(new Error(Qf(i))))}),r.on("close",(i,c)=>{if(!s){if(s=!0,a){n(new Error("registry query output exceeded the safety limit"));return}if(i===null){n(new Error(Qf({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Ut=(e={})=>da((e.home??rh)(),".anyray","claude-desktop-windows.json"),xN=e=>da((e.home??rh)(),".anyray","claude-desktop-windows.lock"),ia=class extends Error{},IN=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},sh=async e=>{let t=xN(e);await Jf(ri(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=JA("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=da(t,"owner.json");try{await Jf(t,{mode:448}),await he(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
287
|
+
`)}catch(a){if(a.code!=="EEXIST")throw await nn(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await zf(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!IN(i.pid)}catch{try{s=Date.now()-(await tC(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new ia;await nn(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await zf(o,"utf8")).nonce===r&&await nn(t,{recursive:!0,force:!0})}catch{}}}throw new ia},iC=()=>Object.fromEntries($e.map(e=>[e,{present:!1}])),so=e=>JA("sha256").update(e).digest("hex"),RN=(e,t)=>t.present?e===ua?{present:!0,type:t.type,sha256:so(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},aa=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?so(e.value??"")===t.sha256:e.value===t.value:!0,Bt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Nl=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.present!="boolean"?!1:n.present?n.type!=="REG_SZ"&&n.type!=="REG_EXPAND_SZ"?!1:t===ua?Bt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Bt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},UA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,$e)&&$e.every(t=>Nl(e[t],t)),HA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,NA)&&NA.every(t=>Nl(e[t],t)),ON=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),ih=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=["path",...n.lastWritten===void 0?[]:["lastWritten"],...n.pending===void 0?[]:["pending"]];return Bt(n,r)&&n.path===oh(t)&&(n.lastWritten===void 0||BA(n.lastWritten))&&(n.pending===void 0||BA(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},_N=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Dl&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&UA(e.lastWritten)&&(e.pending===void 0||UA(e.pending))&&ih(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),TN=e=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&HA(e.lastWritten)&&(e.pending===void 0||HA(e.pending)),WA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,$A)&&$A.every(t=>Nl(e[t],t)),PN=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&WA(e.lastWritten)&&(e.pending===void 0||WA(e.pending))&&ih(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),KA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,MA)&&MA.every(t=>Nl(e[t],t)),LN=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&KA(e.lastWritten)&&(e.pending===void 0||KA(e.pending))&&ih(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),GA=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),ch=e=>{let{pending:t,...n}=e;return{...n,version:Dl,lastWritten:GA(e.lastWritten),...t?{pending:GA(t)}:{}}},jA=e=>({...e,chatTabEnabled:{present:!1}}),DN=e=>{let{pending:t,...n}=e;return ch({...n,version:4,lastWritten:jA(e.lastWritten),...t?{pending:jA(t)}:{}})},VA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),NN=(e,t)=>ch({version:4,registryKey:Pe,keyExisted:e.keyExisted,lastWritten:VA(e.lastWritten),...e.pending?{pending:VA(e.pending)}:{},helper:{path:oh(t)}}),lh=async(e,t=!0)=>{let n=Ut(e),r=ri(n),o=`${nC(n)}.anyray-old-`,a=(await QA(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>da(r,l)),s=n;if(!await R(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await eC(a[0],n):s=a[0]}let i=await M(s),c=TN(i)?NN(i,e):PN(i,e)?DN(i):LN(i,e)?ch(i):_N(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>nn(l,{force:!0}))),c},YA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),$N=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Pe,keyExisted:e.keyExisted,lastWritten:YA(e.lastWritten),...e.pending?{pending:YA(e.pending)}:{}}:e,Tl=async(e,t)=>{let n=Ut(t),r=`${JSON.stringify($N(e),null,2)}
|
|
288
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await he(n,r)},MN=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,FN=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),BN=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),UN=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),HN=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===UN(t).toUpperCase(),ZA=(e,t,n,r,o)=>{let a=$e.find(i=>i.toLowerCase()===t.toLowerCase());if(!a)return!1;let s=n==="String"?"REG_SZ":n==="ExpandString"?"REG_EXPAND_SZ":n;if(s!=="REG_SZ"&&s!=="REG_EXPAND_SZ"){if(o)throw new Error("an owned Claude policy value has an unsupported type");return!1}if(e[a].present)throw new Error("a Claude policy value was returned more than once");return e[a]={present:!0,type:s,value:r},!0},WN=e=>e==="String"?"REG_SZ":e==="ExpandString"?"REG_EXPAND_SZ":e==="DWord"?"REG_DWORD":e==="QWord"?"REG_QWORD":e==="MultiString"?"REG_MULTI_SZ":e==="Binary"?"REG_BINARY":e==="None"?"REG_NONE":e,KN=(e,t)=>{if(!El(e,!0))return!1;let n=WN(t);if(BN.has(n))return!1;if(FN.has(n))return n==="REG_EXPAND_SZ"?!0:!uA(e,!0)},GN=(e,t)=>{let n=iC(),r=!1,o=!1,a=!1,s=t.toUpperCase()===ni.toUpperCase(),i=(l,d)=>{if(!s)return;let u=KN(l,d);u===void 0?a=!0:u&&(o=!0)},c=e.trim();if(c.startsWith("{")){let l=JSON.parse(c);if(l.anyrayRegistry!==1||typeof l.key!="string"||l.key.toUpperCase()!==t.toUpperCase()||!Array.isArray(l.values))throw new Error("invalid registry bridge response");for(let d of l.values){if(!d||typeof d!="object"||Array.isArray(d))throw new Error("invalid registry bridge value");let u=d;if(typeof u.name!="string"||typeof u.kind!="string"||typeof u.value!="string")throw new Error("invalid registry bridge value");i(u.name,u.kind),ZA(n,u.name,u.kind,u.value,!s)||(r=!0)}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}}for(let l of e.split(/\r?\n/)){let d=l.trim();if(!d||HN(d,t))continue;let u=MN.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),ZA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Un=async(e,t=Pe)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:iC(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return GN(n.stdout,t)},br=async e=>{let t=await Un(e,ni);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...$e.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},dh=e=>e.unparsed?`This machine may have a Claude policy under ${ni} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${ni} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${ni} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var $l=(e,t)=>ta(oo(e,t)),cC=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],jN=(e,t)=>{let n=$l(e,t);return Object.fromEntries($e.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},VN=(e,t)=>({inferenceProvider:{present:!0,type:"REG_SZ",value:"gateway"},inferenceGatewayBaseUrl:{present:!0,type:"REG_SZ",value:e.anthropicBaseUrl},inferenceGatewayAuthScheme:{present:!0,type:"REG_SZ",value:"bearer"},chatTabEnabled:{present:!1},coworkEgressAllowedHosts:{present:!1},inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},inferenceGatewayApiKey:{present:!0,type:"REG_SZ",value:t}}),YN=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,eh=e=>Object.fromEntries($e.map(t=>[t,RN(t,e[t])])),XA=(e,t,n,r)=>({version:Dl,registryKey:Pe,keyExisted:e,lastWritten:eh(t),helper:{path:n,lastWritten:qf(r)}}),ZN=(e,t,n,r,o,a)=>({version:Dl,registryKey:Pe,keyExisted:e,lastWritten:eh(t),pending:eh(n),helper:{path:r,...o?{lastWritten:qf(o)}:{},pending:qf(a)}}),th=(e,t,n)=>aa(n,e.lastWritten[t])||e.pending!==void 0&&aa(n,e.pending[t]),ca=async e=>{try{let t=await zf(e,"utf8");return{content:t,sha256:so(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},la=async e=>(await ca(e))?.sha256,sa=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Ll=async(e,t)=>{let n=vN(e),r;try{r=await QA(ri(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>da(ri(e),c));if(o.length===0)return;if(o.length!==1)throw new Error("ambiguous credential helper recovery files");let a=o[0],[s,i]=await Promise.all([ca(e),ca(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!sa(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await sC(e,a))throw new Error("credential helper changed during recovery");return}if(t&&sa(t,s.sha256)&&sa(t,i.sha256)){await nn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},uh=async(e,t,n)=>(n.present?await e(cC(Pe,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Pe,"/v",t,"/f"])).code===0,XN=async(e,t,n)=>{let r=!0,o=await Un(e);for(let a of $e)if(!oa(o.values[a],t[a])){if(!oa(o.values[a],n[a])){r=!1;continue}await uh(e,a,t[a])||(r=!1),o=await Un(e)}return r&&$e.every(a=>oa(o.values[a],t[a]))},ze=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Ut(n)]}}),lC=async(e,t,n,r={})=>{if(!Ie(t))return ze("A valid personal ark_ gateway key is required.",!1,r);let o=oh(r),a;try{a=wN((r.credentialCommand??Wf)())}catch{return ze("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=so(a),i=r.runReg??Hn,c=Ut(r),l;if(!n.dryRun)try{l=await sh(r)}catch(m){return ze(m instanceof ia?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; the registry was left unchanged.",!1,r)}let d,u,f,p,h=!1;try{let m=await br(i);if(m)return ze(dh(m),!1,r);let w=await lh(r,!n.dryRun);n.dryRun||await Ll(o,w);let g=await Un(i),y=jN(e,o),b=await ca(o),v=b?.sha256,S=!1;if(d=w,u=g,f=y,w){let A=$e.find(I=>!th(w,I,g.values[I]));if(A)return ze(`Claude's ${A} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(v!==void 0&&!sa(w,v))return ze(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);S=YN(w)}else{if(v!==void 0&&v!==s)return ze(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let A=g.foreignState||$e.some(B=>g.values[B].present),I=$e.every(B=>oa(g.values[B],y[B])),T=$e.every(B=>oa(g.values[B],VN(e,t.trim())[B]));if(A&&!I&&!T)return ze(`Existing Claude third-party-inference policy values under ${Pe} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(S=T,I&&v===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Pe} into an owner-only journal without rewriting them.`]}:(await Tl(XA(g.keyPresent,y,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Pe} into the ownership journal.`]})}if(S){let A=!0;try{A=(r.appRunning??ah)()}catch{}if(A)return ze("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=ZN(w?.keyExisted??g.keyPresent,g.values,y,o,b?.content,a);if(p=E,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Pe}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Tl(E,r),h=!0;for(let A of $e){let I=await Un(i);if(!aa(I.values[A],E.lastWritten[A])&&!aa(I.values[A],E.pending[A]))throw new Error("registry value changed during apply");if(!oa(I.values[A],y[A])&&!await uh(i,A,y[A]))throw new Error("registry write failed")}let x=await Un(i);if(!$e.every(A=>aa(x.values[A],E.pending[A])))throw new Error("registry verification failed");if(v!==s&&(v===void 0?await CN(o,a):await Pl(o,v,a,"apply",r)),await la(o)!==s)throw new Error("credential helper verification failed");return await Tl(XA(E.keyExisted,y,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Pe}.`,`Installed or updated the dynamic credential helper at ${o}; no personal key is stored in policy or the ownership journal.`,"Fully quit and reopen Claude Desktop to load the policy.",...Cl]}}catch{if(!h||!u||!f||!p)return ze("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Ll(o,p);let m=!0,w=await ca(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await Pl(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await la(o)===p.helper.lastWritten.sha256):await Pl(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await XN(i,u.values,f))return d?await Tl(d,r):await nn(c,{force:!0}),ze("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return ze("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},dC=async(e,t={})=>{let n=t.runReg??Hn,r=Ut(t),o;if(!e.dryRun)try{o=await sh(t)}catch(a){return ze(a instanceof ia?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; no registry value was removed.",!1,t)}try{let a=await lh(t,!e.dryRun);a&&!e.dryRun&&await Ll(a.helper.path,a);let s=await Un(n);if(!a)return $e.filter(h=>s.values[h].present).length>0?ze(`Claude policy values exist under ${Pe}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=$e.filter(p=>s.values[p].present&&!th(a,p,s.values[p])),c=await la(a.helper.path),l=c!==void 0&&!sa(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Pe}.`,`Would remove the Anyray-owned credential helper at ${a.helper.path}.`,...i.length||l?[`Would preserve changed values: ${[...i,...l?["credential helper"]:[]].join(", ")}.`]:[]]};let d=!1,u=new Set(i);for(let p of $e){let m=(await Un(n)).values[p];if(m.present){if(!th(a,p,m)){u.add(p);continue}await uh(n,p,{present:!1})||(d=!0)}}let f=await la(a.helper.path);if(f!==void 0)if(sa(a,f))try{await Pl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?ze(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await nn(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Pe}.`,"Removed the Anyray-owned dynamic credential helper when its content still matched the journal.",...u.size?[`Preserved values changed after Connect: ${[...u].join(", ")}.`]:[],...u.size?[]:vl]})}catch{return ze(`Could not safely inspect or revert ${Pe}; no unproven value was removed.`,!1,t)}finally{await o?.()}},uC=async(e,t={})=>{let n=t.runReg??Hn;if(!await R(Ut(t)))return;let r;try{r=await sh(t);let o=await lh(t);if(o&&await Ll(o.helper.path,o),!o||o.pending||await br(n)!==void 0)return;let a=await Un(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ye(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&$e.every(l=>aa(a.values[l],o.lastWritten[l]))))return;let i=await la(o.helper.path),c=o.helper.lastWritten;return a.values.inferenceCredentialKind.value==="helper-script"&&a.values.inferenceCredentialHelper.value===o.helper.path&&!a.values.inferenceGatewayApiKey.present&&c!==void 0&&i===c.sha256&&await AN(c,t)?"dynamic":o.helper.lastWritten===void 0&&!a.values.inferenceCredentialKind.present&&!a.values.inferenceCredentialHelper.present&&a.values.inferenceGatewayApiKey.present?"legacy-static":void 0}catch{return}finally{await r?.()}},pC=async(e,t={})=>await uC(e,t)!==void 0,fC=async(e,t={})=>await uC(e,t)==="dynamic";var pa=(e=zN())=>e==="win32"?ah:Rl,ph="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Fl=async(e,t={})=>{let n=(t.profileRoot??ro)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:ph};if((t.appRunning??pa(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await hC.access(e)}catch{return{ok:!1,reason:`no such file: ${e}`,remedy:"Point at the .zip Anthropic emailed you (claude.ai -> Settings -> Privacy -> Export data)."}}let r=await Al(n);if(!r.ok)return r.reason==="ambiguous"?{ok:!1,reason:"this Claude Desktop profile holds more than one account",remedy:"Choosing which one gets the history is your call, not ours \u2014 "+ph}:{ok:!1,reason:"no Claude Desktop third-party session store found \u2014 the app has not run in this mode yet",remedy:"Open Claude Desktop with Anyray configured, sign in with your usual Claude account, quit it, then run this again."};let o=await(t.findBinary??oA)();if(!o)return{ok:!1,reason:"the Claude Code CLI was not found",remedy:"Install Claude Code (the conversion step uses its importer), then run this again."};let a=Ml(t.stagingRoot??qN(),`anyray-history-${process.pid}-${JN()}`);try{let s=await(t.runImporter??aA)({binary:o,exportPath:e,configDir:Ml(a,"config"),workDir:Ml(a,"work")});if(!s.ok)return{ok:!1,reason:s.reason,remedy:"This step uses an unsupported Claude Code subcommand, so a version change can break it. "+ph};if(s.conversations.length===0)return{ok:!1,reason:"that export contains no conversations",remedy:"Check you pointed at the export archive itself."};let i=await iA(r.dir,s.conversations),c=await cA({stagedProjectsDir:Ml(a,"work","projects"),storageDir:r.dir,projects:s.projects,now:t.now?.()??Date.now()});return{ok:!0,storageDir:r.dir,...i,projects:c}}finally{await hC.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as xt}from"node:fs";import{homedir as k$}from"node:os";import{join as on,sep as A$}from"node:path";import{isDeepStrictEqual as Wl}from"node:util";import{constants as QN}from"node:fs";import{promises as G}from"node:fs";import{dirname as fa,isAbsolute as hh,join as Q,relative as Bl,resolve as rn,sep as oi}from"node:path";import{randomUUID as Kl}from"node:crypto";var bn=448,ai=384,wC=448,e$=4,mh=3e4,bC=5e3,t$=10*6e4,fh=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),dt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),si=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),kC=(e,t)=>{let n=Bl(rn(e),rn(t));return n===""||!n.startsWith(`..${oi}`)&&n!==".."&&!hh(n)},io=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return dt(n)?{raw:t,value:n}:void 0}catch(t){return Et(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},Et=e=>e instanceof Error&&"code"in e,n$=e=>{try{return process.kill(e,0),!0}catch(t){return Et(t)&&t.code==="EPERM"}},AC=e=>e===0?"owner.json":`owner.${e}.json`,Ul=async e=>{let t;try{t=await G.readdir(e)}catch{return}let r=t.map(d=>{if(d==="owner.json")return{name:d,generation:0};let u=/^owner\.(\d+)\.json$/.exec(d);if(!u)return;let f=Number(u[1]);return Number.isSafeInteger(f)&&f>0?{name:d,generation:f}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=Q(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));dt(d)&&typeof d.pid=="number"&&Number.isSafeInteger(d.pid)&&d.pid>0&&typeof d.nonce=="string"&&d.nonce.length>0&&(a=d.pid,s=d.nonce,typeof d.createdAt=="number"&&Number.isFinite(d.createdAt)&&d.createdAt>=0&&(i=d.createdAt))}catch{}let c=await G.stat(o).then(d=>d.mtimeMs),l=i!==void 0&&i<=Date.now()+6e4?i:c;return{generation:r.generation,pid:a,nonce:s,createdAtMs:l,mtimeMs:c}},CC=e=>{if(e.pid===void 0||!n$(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>mh&&t-e.createdAtMs>t$},r$=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(fa(t),{recursive:!0,mode:bn});let n=Kl(),r,o=!1;try{await G.mkdir(t,{mode:bn}),o=!0}catch(i){if(!Et(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Ul(t);if(d){if(!CC(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=mh)return}let l=Q(t,AC(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
289
|
+
`,{flag:"wx",mode:ai}),r=l}catch(d){if(Et(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await G.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await G.readFile(a,"utf8"));if(!dt(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},bC);return s.unref(),async()=>{clearInterval(s);try{(await Ul(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},o$=async(e,t,n)=>{await G.mkdir(fa(e),{recursive:!0,mode:bn});let r=await r$(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!Et(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${Kl()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
|
|
290
|
+
`,{mode:ai,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},Gl=async(e,t)=>{for(let n=0;n<e$;n+=1){let r=await io(e);if(!r)return"failed";let o=t(r.value);if(!o||Wl(o,r.value))return"unchanged";try{if(await o$(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},mC=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},jl=async e=>{let t=[];for(let n of await mC(e))for(let r of await mC(Q(e,n)))t.push(Q(e,n,r));return t},a$=e=>Array.isArray(e.skills)?e.skills.filter(t=>dt(t)&&si(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],s$=async e=>{let t=Q(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await jl(t)){let o=await io(Q(r,"manifest.json"));if(!o)continue;let a=r.split(oi).at(-1)??"";for(let s of a$(o.value))n.push({account:a,packageDir:r,entry:s})}return n},i$=async e=>{let t=await io(Q(e,".claude-plugin","plugin.json"));return!!t&&si(t.value.name)},c$=(e,t)=>{let n=hh(t)?rn(t):rn(e,t);if(!kC(e,n)||n===rn(e))return;let r=Bl(rn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},l$=async e=>{let t=await jl(Q(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(oi).includes("skills-plugin"))continue;let o=Q(r,"cowork_plugins"),a=await io(Q(o,"installed_plugins.json"));if(!a||!dt(a.value.plugins))continue;let s=r.split(oi).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!si(i)||!Array.isArray(c)))for(let l of c){if(!dt(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=c$(o,l.installPath);!d||!await i$(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:Q(r,"cowork_account_settings.json")})}}return n},d$=async e=>{let t=await io(Q(e,"claude_desktop_config.json"));return!t||!dt(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>si(n)&&n.toLowerCase()!=="anyray"&&dt(r)))},vC=async e=>{let[t,n,r]=await Promise.all([s$(e),l$(e),d$(e)]);return{skills:t,plugins:n,localMcpServers:r}},yh=async e=>{let t=await vC(e);return{skills:t.skills.length,plugins:t.plugins.length,localMcpServers:Object.keys(t.localMcpServers).length,accounts:[...new Set([...t.skills.map(n=>n.account),...t.plugins.map(n=>n.account)])].filter(n=>n.length>0)}},yC=async e=>{try{let n=await G.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())return!1}catch{return!1}let t=async n=>{let r;try{r=await G.readdir(n,{withFileTypes:!0})}catch{return!1}for(let o of r){if(!si(o.name))return!1;let a=Q(n,o.name);if(o.isSymbolicLink())return!1;if(o.isDirectory()){if(!await t(a))return!1}else if(!o.isFile())return!1}return!0};return t(e)},u$=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=Q(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,bn);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?wC:ai)}}};await t(e),await G.chmod(e,bn)},SC=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},Hl=async(e,t)=>{try{let[n,r]=await Promise.all([G.readdir(e,{withFileTypes:!0}),G.readdir(t,{withFileTypes:!0})]),o=n.map(s=>s.name).sort(),a=r.map(s=>s.name).sort();if(!Wl(o,a))return!1;for(let s of o){let i=n.find(l=>l.name===s),c=r.find(l=>l.name===s);if(!i||!c||i.isDirectory()!==c.isDirectory()||i.isFile()!==c.isFile())return!1;if(i.isDirectory()){if(!await Hl(Q(e,s),Q(t,s)))return!1}else if(!i.isFile()||!await SC(Q(e,s),Q(t,s)))return!1}return!0}catch{return!1}},EC=e=>`${e}.anyray-incomplete`,xC=async(e,t)=>{let n=!1;if(t){await G.mkdir(fa(e),{recursive:!0,mode:bn});try{await G.mkdir(e,{mode:bn}),n=!0}catch(l){if(!Et(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=Kl(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await Ul(e)}catch{return}if(f){if(!CC(f)||!Number.isSafeInteger(f.generation+1))return;d=f.generation+1}else if(await G.stat(e).then(h=>Date.now()-h.mtimeMs).catch(()=>0)<=mh)return}let u=Q(e,AC(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
291
|
+
`,{flag:"wx",mode:ai}),o=u}catch(f){if(Et(f)&&f.code==="EEXIST"){n=!1;continue}n&&await G.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await G.readFile(a,"utf8"));if(!dt(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},bC);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Ul(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},IC=async e=>{let t=await xC(e,!1);t&&await t.complete()},p$=async(e,t,n)=>{let r=EC(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Hl(e,t))return await IC(r),"present"}catch(c){if(!Et(c)||c.code!=="ENOENT")return"failed"}if(o)try{let c=await G.lstat(r);if(!c.isDirectory()||c.isSymbolicLink())return"conflict"}catch{return"conflict"}let a=await xC(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:bn})}catch(c){if(!Et(c)||c.code!=="EEXIST")return a.abandon(),"failed";try{let l=await G.lstat(t);if(!l.isDirectory()||l.isSymbolicLink())return await a.complete(),"conflict"}catch{return a.abandon(),"failed"}}let s=async(c,l)=>{let d;try{d=await G.readdir(c,{withFileTypes:!0})}catch{return"failed"}for(let u of d){let f=Q(c,u.name),p=Q(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(p,{mode:bn})}catch(m){if(!Et(m)||m.code!=="EEXIST")throw m;let w=await G.lstat(p);if(!w.isDirectory()||w.isSymbolicLink())return"conflict"}let h=await s(f,p);if(h!=="copied")return h}else if(u.isFile())try{await G.copyFile(f,p,QN.COPYFILE_EXCL);let h=await G.stat(f);await G.chmod(p,(h.mode&73)!==0?wC:ai)}catch(h){if(!Et(h)||h.code!=="EEXIST")throw h;if(!await SC(f,p))return"conflict"}else return"failed"}catch(h){return Et(h)&&h.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await Hl(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},RC=async(e,t,n,r)=>{if(!await yC(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Hl(e,t))return await IC(EC(t)),"present"}catch(a){if(!Et(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(fa(t),{recursive:!0,mode:bn});let o=Q(fa(t),`.anyray-stage-${Kl()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await yC(o)?(await u$(o),await n?.(t),await p$(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},gC=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),f$=async e=>{let t=await jl(Q(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await io(Q(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},h$=async e=>{let t=await jl(Q(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(oi).includes("skills-plugin"))try{await G.access(Q(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},m$=async(e,t,n,r,o)=>{let a=Q(t,"manifest.json");for(let s of e){let i=Q(s.packageDir,"skills",s.entry.name);try{await G.access(Q(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=Q(t,"skills",s.entry.name),l=await RC(i,c,r,o);if(l==="conflict"){n.conflicts+=1;continue}if(l==="invalid"){n.invalid+=1;continue}if(l==="failed"){n.failed+=1;continue}let d=!1;await Gl(a,f=>{let p=Array.isArray(f.skills)?f.skills:[];if(p.find(m=>dt(m)&&typeof m.name=="string"&&m.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...f,skills:[...p,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},OC=(e,t)=>({...e,installPath:t}),y$=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=hh(r.installPath)?rn(r.installPath):rn(o,r.installPath),s=OC(e,Bl(rn(t),rn(n))),i={...r,installPath:Bl(rn(o),a)};return Wl(s,i)},g$=async(e,t,n)=>{let r=await io(e);if(!r||!dt(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":Gl(t,a=>{let s=dt(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},w$=async(e,t,n,r,o)=>{let a=Q(t,"cowork_plugins"),s=Q(a,"installed_plugins.json"),i=Q(t,"cowork_account_settings.json");for(let c of e){let l=Q(a,c.relativeInstallPath);if(!kC(a,l)){n.invalid+=1;continue}let d=await RC(c.packageDir,l,r,o);if(d==="conflict"){n.conflicts+=1;continue}if(d==="invalid"){n.invalid+=1;continue}if(d==="failed"){n.failed+=1;continue}let u=!1,f=!1;await Gl(s,h=>{let m=dt(h.plugins)?h.plugins:{},w=m[c.id],g=Array.isArray(w)?w:[],y=g.find(v=>dt(v)&&v.scope==="user");if(y){u=y$(c.entry,fa(c.settingsFile),c.packageDir,y,t),f=!u;return}let b=OC(c.entry,l);return{...h,version:typeof h.version=="number"?h.version:2,plugins:{...m,[c.id]:[...g,b]}}})==="failed"?n.failed+=1:f?n.conflicts+=1:await g$(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},b$=async(e,t,n)=>{let r=Q(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await Gl(r,c=>{let l=dt(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=Wl(l[o],a)?"present":"conflict";return}return{...c,mcpServers:{...l,[o]:a}}})==="failed"?n.failed+=1:s.value==="present"?n.alreadyPresent+=1:s.value==="conflict"?n.conflicts+=1:n.migrated+=1}},_C=async(e,t,n={})=>{let r=await vC(e),o=fh("skill"),a=fh("plugin"),s=fh("local-mcp"),i=[],c=[],l=gC(r.skills,n.account,n.allAccounts),d=gC(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let f=new Set(n.allowedAccounts);if([...new Set([...l.map(h=>h.account),...d.map(h=>h.account)])].some(h=>!f.has(h)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,sourceChanged:!0,retryable:[]}}if(l.length>0){let f=await f$(t);f.state==="found"?await m$(l,f.path,o,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("skill"):(o.conflicts+=l.length,c.push("skill"))}if(d.length>0){let f=await h$(t);f.state==="found"?await w$(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await b$(r.localMcpServers,t,s);let u=[o,a,s];return{outcomes:u,blocked:i,ambiguous:c,sourceChanged:!1,retryable:u.filter(f=>f.failed>0).map(f=>f.kind)}};var C$=async e=>{try{return await xt.access(e),!0}catch{return!1}},TC=448,v$=384,LC={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},S$=["code","cowork"],bh=(e,t,n,r=!1)=>r?"Claude Desktop has not been set up on Anyray yet \u2014 run `anyray-connect desktop` first, then open Claude Desktop once and fully quit it.":e==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${t} store, so which one to fill is your call \u2014 re-run \`${n}\` with \`--account <id>\`.`:t==="cowork"?"Open Claude Desktop, sign in, and open the Cowork tab once \u2014 that is what creates the store \u2014 then fully quit it and run this again.":"Open Claude Desktop, sign in, and start a Claude Code session once \u2014 that is what creates the store \u2014 then fully quit it and run this again.",gh=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),DC=async e=>{let t;try{t=(await xt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&Qo(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await xt.readdir(on(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&Qo(a.name)).map(a=>a.name);for(let a of o)n.push(on(e,r,a))}catch{}return n},E$=async e=>{try{return(await xt.readdir(e)).filter(t=>t.startsWith(Fn)&&t.endsWith(".json")).map(t=>t.slice(Fn.length,-5)).filter(Qo)}catch{return[]}},x$=async(e,t)=>{let n=await DC(on(e,LC[t])),r=[];for(let o of n){let a=await E$(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(A$).slice(-2)[0]})}return r},I$=async(e,t)=>{if(t==="cowork"){let r=await Al(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await DC(on(e,LC.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},R$=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await xt.copyFile(e,n),await xt.chmod(n,v$),await xt.rename(n,t)},O$=async(e,t)=>{try{let n=JSON.parse(await xt.readFile(e,"utf8"));if(!n||typeof n!="object")return!1;let{cwd:r,cliSessionId:o}=n;return typeof r!="string"||typeof o!="string"||r.length===0||!Qo(o)?!1:(await xt.access(on(t,".claude","projects",$f(r),`${o}.jsonl`)),!0)}catch{return!1}},_$=async(e,t,n,r)=>{let o=gh(e),a=await Mf(n);for(let s of t)await T$(e,s,n,r,a,o);return o},T$=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Fn}${s}.json`,c=on(t.dir,i);try{if(e==="code"){if(!await O$(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=on(t.dir,`${Fn}${s}`),d=on(n,`${Fn}${s}`),u=await xt.readdir(l);await xt.mkdir(d,{mode:TC});for(let f of u)await xt.cp(on(l,f),on(d,f),{recursive:!0,force:!1,errorOnExist:!0});await xt.chmod(d,TC)}await R$(c,on(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},PC=(e,t,n,r=[])=>{let o=new Map;for(let{sources:s}of e)for(let i of s){let c=o.get(i.account)??{sessions:0,portable:!1};c.sessions+=i.ids.length,o.set(i.account,c)}for(let s of r){let i=o.get(s)??{sessions:0,portable:!1};i.portable=!0,o.set(s,i)}let a=[...o.entries()].sort((s,i)=>i[1].sessions-s[1].sessions).map(([s,i])=>{let c=i.sessions===0?"portable configuration":`${i.sessions} session${i.sessions===1?"":"s"}${i.portable?" plus portable configuration":""}`;return` ${t} --account ${s.slice(0,8)} (${c})`});return{ok:!1,kind:"account-ambiguous",reason:n,remedy:["Pick the one you want, or take everything:",...a,` ${t} --all-accounts`].join(`
|
|
292
|
+
`)}},wh=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),NC=async e=>{let t=[];for(let n of S$)t.push({lane:n,sources:await x$(e,n)});return t},$C=async(e={})=>{let t=(e.firstPartyRoot??(()=>Vs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([NC(t),yh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=wh(n);for(let s of r.accounts)a.add(s);return{sessions:o,accounts:a.size,userSkills:r.skills,userPlugins:r.plugins,localMcpServers:r.localMcpServers}},co=async(e={})=>{let t=(e.home??k$)(),n=(e.firstPartyRoot??(()=>Vs()))(),r=(e.thirdPartyRoot??(()=>ro()))();if(!n||!r)return{ok:!1,kind:"platform-unsupported",reason:"this platform has no Claude Desktop third-party profile",remedy:"Migration applies to macOS and Windows, where Desktop runs third-party mode in its own profile."};if((e.appRunning??pa())())return{ok:!1,kind:"app-running",reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop and run this again \u2014 it rewrites its session list on exit, which would undo the migration."};let[o,a]=await Promise.all([NC(n),yh(n)]),s;if(e.account){let p=e.account;for(let w of o)w.sources=w.sources.filter(g=>g.account.startsWith(p));let h=a.accounts.filter(w=>w.startsWith(p));if(o.every(w=>w.sources.length===0)&&h.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${p}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let m=wh(o);for(let w of h)m.add(w);if(m.size>1)return PC(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=wh(o);for(let h of a.accounts)p.add(h);if(p.size>1)return PC(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${p.size} accounts`,a.accounts);s=[...p]}let i=e.command??"anyray-connect desktop --migrate",c=!await C$(r),l=await _C(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:s});if(l.sourceChanged)return{ok:!1,kind:"account-ambiguous",reason:"the previous Claude Desktop profile changed during migration and now holds local data for another account",remedy:`Re-run \`${i}\` so the account choice is made from a fresh snapshot.`};let d=[],u=[];for(let{lane:p,sources:h}of o){if(h.length===0){d.push(gh(p));continue}let m=await I$(r,p);if("missing"in m){u.push({lane:p,reason:m.missing,waiting:h.reduce((w,g)=>w+g.ids.length,0)}),d.push(gh(p));continue}d.push(await _$(p,h,m.dir,t))}if(!(d.some(p=>p.migrated>0||p.alreadyPresent>0)||l.outcomes.some(p=>p.migrated>0||p.alreadyPresent>0||p.conflicts>0))&&(u.length>0||l.blocked.length>0)){let p=u[0];return p?{ok:!1,kind:p.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:p.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${p.lane} store`:`Claude Desktop has no ${p.lane} store in its third-party profile yet`,remedy:bh(p.reason,p.lane,i,c)}:{ok:!1,kind:"store-missing",reason:"Claude Desktop's third-party profile has no extension store yet",remedy:"Open Claude Desktop once after connecting it to Anyray, then fully quit it so the portable extensions can be copied safely."}}return{ok:!0,lanes:d,portableAssets:l.outcomes,...u.length>0?{blocked:u}:{},...l.blocked.length>0?{blockedAssets:l.blocked}:{},...l.ambiguous.length>0?{ambiguousAssets:l.ambiguous}:{},...l.retryable.length>0?{retryableAssets:l.retryable}:{}}};var P$=e=>[ot(e)],MC=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...P$(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await R(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var FC="1.21459.0",$$=N$(L$),M$=async e=>{try{let{stdout:t}=await $$("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},F$=async e=>{try{return await D$(e)}catch{return}},BC="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",B$=["Admin policy setup (no JSON): open Developer \u2192 Configure Third-Party Inference; the Anyray connection is already filled in.",'Add approved remote MCP connectors under "Connectors & extensions" and use "Test this connection"; add approved Git marketplaces under "Plugins & skills".',`Choose "Apply locally" to test. For Jamf, first select IT's fleet-wide credential-helper path, then choose Export \u2192 .mobileconfig and deploy the complete profile.`,"If Claude Desktop is already MDM-managed, this window is read-only. Author and export on an unmanaged admin Mac, then redeploy through Jamf."],ha=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(UC??=HC({}),UC):HC(e),UC,HC=async e=>{let t=(e.home??ci)(),n=["/Applications/Claude.app",kn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??M$,o=e.readClaudeAppBundle??F$;for(let a of n){let s=await r(kn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${BC}`}),c=bl(s,FC);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${FC} or newer.`);let l=await o(kn(a,"Contents","Resources","app.asar"));return l?vA.some(d=>!l.includes(d))?i("its local config seam no longer matches the shape Connect writes."):{supported:!0,detectedVersion:s,appPath:a}:i("its app bundle could not be read to verify the local config seam.")}return{supported:!1,message:`Could not verify the installed Claude Desktop version. ${BC}`}},Vl="anyray",GC="--anyray-owner=claude-desktop-v1",Yl=(e={})=>{let t=(e.platform??kr)(),n=(e.home??ci)();return t==="darwin"?tn(e).appConfig:t==="win32"?kn(process.env.APPDATA??kn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):kn(n,".config","Claude","claude_desktop_config.json")},Sh=(e={})=>kn((e.home??ci)(),"Library","Application Support","Claude","claude_desktop_config.json"),jC=()=>{let e=je("profile");return{command:e.command,args:[...e.args,GC]}},lo=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),VC=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},U$=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),H$=e=>{if(!lo(e)||!VC(e,["command","args"]))return!1;let t=jC();return e.command===t.command&&U$(e.args,t.args)},W$=e=>lo(e)&&Array.isArray(e.args)&&e.args.at(-1)===GC,K$=e=>{if(!lo(e)||!VC(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||Ge(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===er&&t.at(-1)==="profile"))return!1;let r=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(r))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(r)||t.length!==3)return!1;let o=t[0].replaceAll("\\","/");return!Ge(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},G$=e=>e===void 0?"absent":H$(e)?"exact":W$(e)||K$(e)?"stale-owned":"foreign",Ue=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},uo=async e=>{let t=await R(e),n;try{n=await M(e)}catch{throw new Ue(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!lo(n.mcpServers))throw new Ue(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(lo(n.mcpServers)?n.mcpServers:void 0)?.[Vl];return{path:e,fileExisted:t,json:n,entry:o,ownership:G$(o)}},Zl=e=>{if(e.ownership==="foreign")throw new Ue(`MCP name conflict in ${e.path}: mcpServers.${Vl} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},YC=(e,t)=>{let n={...e},r=lo(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[Vl]:r[Vl]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Ah=async(e,t)=>{if(kh(e.entry,t))return;let n=await uo(e.path);if(!kh(n.entry,e.entry))throw new Ue(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Bn(e.path,YC(n.json,t)),{reading:e,afterEntry:t}},Ch=async e=>{let t=await uo(e.reading.path);if(!kh(t.entry,e.afterEntry))throw new Ue(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=YC(t.json,e.reading.entry);await Bn(e.reading.path,n)},j$=async e=>{if(!ce())throw new Ue(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Oe()} is temporary); no inference setting was changed.`);let t=await uo(Yl(e));Zl(t);let n=Sh(e),r=(e.platform??kr)()==="darwin"&&n!==t.path?await uo(n):void 0;return r&&Zl(r),{active:t,...r?{legacy:r}:{}}},WC=async e=>{let t=await uo(Yl(e));Zl(t);let n=Sh(e),r=(e.platform??kr)()==="darwin"&&n!==t.path?await uo(n):void 0;return r&&Zl(r),{active:t,...r?{legacy:r}:{}}},V$=async e=>{let t=[];try{let n=await Ah(e.active,jC());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Ah(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Ch(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ue(`Claude Desktop MCP setup failed and could not restore ${r.join(", ")}. Re-run \`anyray-connect desktop disconnect\` to recover safely.`,r):n}return{changedFiles:t.map(n=>n.reading.path),async rollback(){let n=[];for(let r of[...t].reverse())await Ch(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Ue(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},Y$=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Ah(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Ch(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Ue(`Claude Desktop MCP cleanup failed and could not restore ${r.join(", ")}. Re-run revert after resolving the file conflict.`,r):n}return t.map(n=>n.reading.path)},KC=e=>{let t=e.clientKey?`${e.clientKey} (your personal gateway key - keep it private)`:`${e.placeholderKey} (placeholder - the gateway holds the real key)`;return["Step 1 - Turn on Developer Mode."," In the menu bar at the VERY TOP of the screen (NOT the in-app help panel):"," Help -> Troubleshooting -> Enable Developer Mode"," (Windows: open the menu at the top-left of the sign-in screen.)",' A "Developer" menu then appears in that same top-of-screen menu bar.',"","Step 2 - Open the Developer MENU in the menu bar (shown below) - NOT Settings:",""," +----------------------------------------------------------------+"," | Claude File Edit View Window [Developer] Help | <- macOS menu bar (very top of screen)"," +-------------------------------------^--------------------------+"," |",' click Developer -> "Configure Third-Party Inference..."',"",' Heads up: use the "Developer" MENU in the bar above - NOT',' Settings -> Developer, which is the "Local MCP servers" pane'," (that's where Anyray's retrieval server appears, not inference)."," A separate setup window then opens.","","Step 3 - In that window's Connection section, paste:",""," Inference provider: Gateway",` Gateway base URL: ${e.anthropicBaseUrl}`," Auth scheme: Bearer",` API key: ${t}`,"",'Step 4 - Click "Apply locally", then fully quit and reopen Claude'," (the config is read once at launch).","","Billing: this route uses an Anyray gateway credential and provider/API billing, not a Claude subscription allowance.","Fleet/MDM: generate a managed profile with `anyray-connect desktop claude --mobileconfig` (applies with no Developer Mode and no paste)."]},Z$={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Xl="claude-desktop",vh="migrate",ZC=new Set(["app-running","store-missing"]),X$={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},J$={skill:{one:"user-created skill",many:"user-created skills"},plugin:{one:"user-installed plugin",many:"user-installed plugins"},"local-mcp":{one:"local MCP server",many:"local MCP servers"}},z$="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",XC=e=>{let t=(e.platform??kr)(),n=e.home??ci;return{home:n,appRunning:e.appRunning??pa(t),firstPartyRoot:()=>Vs({home:n,runtimePlatform:t}),thirdPartyRoot:()=>ro({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},JC=e=>{let t=e.filter(a=>a.migrated>0);if(t.length===0)return;let n=e.reduce((a,s)=>a+s.skippedNoTranscript,0),r=e.reduce((a,s)=>a+s.failed,0);return`Brought your existing Claude Desktop sessions into its third-party profile: ${t.map(a=>{let s=X$[a.lane];return`${a.migrated} ${a.migrated===1?s.one:s.many}`}).join(", ")}.`+(n>0?` ${n} skipped \u2014 the transcript is no longer on disk.`:"")+(r>0?` ${r} could not be copied.`:"")},zC=e=>{let t=e.filter(s=>s.migrated>0),n=e.reduce((s,i)=>s+i.conflicts,0),r=e.reduce((s,i)=>s+i.invalid,0),o=e.reduce((s,i)=>s+i.failed,0);if(t.length===0&&n+r+o===0)return;let a=t.map(s=>{let i=J$[s.kind];return`${s.migrated} ${s.migrated===1?i.one:i.many}`});return(a.length>0?`Brought your portable Claude Desktop configuration across: ${a.join(", ")}.`:"Portable Claude Desktop configuration was checked; existing target entries were kept.")+(n>0?` ${n} conflicting target ${n===1?"entry was":"entries were"} preserved.`:"")+(r>0?` ${r} unsafe or incomplete ${r===1?"entry was":"entries were"} skipped.`:"")+(o>0?` ${o} could not be copied.`:"")},ii=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=XC(e),r=await(e.pendingDesktopMigrationCount??$C)(n),o=r.userSkills+r.userPlugins+r.localMcpServers;if(r.sessions+o===0)return[];if(t.dryRun)return[`Would bring ${[r.sessions>0?`${r.sessions} existing Claude Desktop session${r.sessions===1?"":"s"}`:"",o>0?`${o} portable configuration ${o===1?"entry":"entries"}`:""].filter(Boolean).join(" and ")} into Claude Desktop's third-party profile, now or automatically the next time Claude Desktop is fully quit.`];let a=await(e.migrateDesktopProfile??co)(n);if(a.ok){let c=JC(a.lanes),l=zC(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(a.blocked??[]).filter(y=>y.reason!=="ambiguous"),p=a.blockedAssets??[],h=a.retryableAssets??[];if(f.length===0&&p.length===0&&h.length===0)return[c,l,u].filter(y=>!!y);if(t.preservePendingOp)return[c,l,u].filter(y=>!!y);await Cs(Xl,vh);let m=f.reduce((y,b)=>y+b.waiting,0),w=[m>0?`${m} more session${m===1?"":"s"}`:"",p.length>0?`${p.length} extension ${p.length===1?"store":"stores"}`:""].filter(Boolean),g=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...h.length>0?[`Queued: ${h.length} portable configuration ${h.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...g]}if(!ZC.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
293
|
+
${a.remedy}`];if(t.preservePendingOp)return[];await Cs(Xl,vh);let s=r.sessions+o,i=`${s} Claude Desktop local ${s===1?"item":"items"}`;return[a.kind==="store-missing"?`Queued: the ${i} still in your previous profile move across once Claude Desktop's new profile has been signed in to and the app is fully quit.`:`Queued: the ${i} still in your previous profile will move across the next time you fully quit Claude Desktop.`]}catch{return["Could not check whether Claude Desktop had existing sessions to bring across; run `anyray-connect migrate` if its lists look empty."]}},q$=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await lr(Xl),[]}catch{return["Could not clear Claude Desktop's queued profile-migration marker; a background watcher may still be waiting for the app to quit. Delete it by hand if it persists."]}},Q$=e=>MC({id:Xl,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??kr)(),n=(e.home??ci)();return t==="darwin"?["/Applications/Claude.app",kn(n,"Applications","Claude.app")]:t==="win32"?[kn(process.env.LOCALAPPDATA??kn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>J(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",...KC(t)]:["Claude desktop org/API lane:",...KC(t),"This Gateway route uses provider/API billing. On verified macOS builds, subscription mode instead installs the Keychain-backed Claude Code credential helper automatically."],revertMessages:["Claude Desktop third-party inference: switch back to the first-party Claude provider in Developer settings (or remove the managed profile). Native setup is restored automatically by `--revert`."]}),eM=(e={})=>{let t=Q$(e),n=()=>(e.platform??kr)()==="darwin",r=()=>(e.platform??kr)()==="win32",o=(s,i)=>n()?TA(s,i,e):lC(s,s.clientKey??"",i,e),a=s=>n()?PA(s,e):dC(s,e);return{...t,automatic:!0,quitGated:{isRunning:()=>(e.appRunning??pa((e.platform??kr)()))(),quitTarget:Z$,needsTarget:()=>!1,async complete(s){if(s!==vh)return{status:"manual",messages:[`Claude Desktop could not service a queued "${s}" operation it does not recognise; the queue entry was dropped.`]};let i=await(e.migrateDesktopProfile??co)(XC(e));if(i.ok){let c=JC(i.lanes),l=zC(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let f=(i.blocked??[]).filter(m=>m.reason!=="ambiguous"),p=i.blockedAssets??[],h=i.retryableAssets??[];return f.length>0||p.length>0||h.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...f.length>0||p.length>0?["Still waiting on Claude Desktop to create the remaining third-party stores, which appear the first time those parts of the app are opened."]:[],...h.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(m=>!!m):["No portable Claude Desktop data was left to bring across."]}}return ZC.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?DA(s,e):r()?fC(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=tn(e),p=await ao(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[Yf(p),...await ii(e,i)]}}if(r()){let f;try{f=await br(e.runReg??Hn)}catch{return{status:"manual",manualAudience:"admin",messages:[z$,...await ii(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[dh(f),...await ii(e,i)]}}if(r()&&J(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let f=await ha(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await j$(e)}catch(f){let p=f instanceof Ue?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Ue?f.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no inference setting was changed."]}}let l=await o(s,{dryRun:!0});if(l.status!=="configured")return l;if(i.dryRun){let f=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...f&&f.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${f.path}.`]:[],...await ii(e,i)]}}let d;try{d=await V$(c)}catch(f){let p=f instanceof Ue?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Ue?f.message:"Could not safely register Claude Desktop retrieval; the inference route was left unchanged."]}}let u;try{u=await o(s,{dryRun:!1})}catch{u={status:"manual",messages:["Claude Desktop inference setup failed before it returned a result."]}}if(u.status!=="configured")try{return await d.rollback(),{...u,changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])],messages:[...u.messages,"Restored the prior Claude Desktop MCP registration because inference setup did not complete. A config file that was absent before setup may remain as an inert object to avoid racing unrelated concurrent writes."]}}catch{return{status:"manual",changedFiles:[...u.changedFiles??[],...d.changedFiles],messages:[...u.messages,"Inference setup did not complete, and the prior MCP registration could not be fully restored. Re-run `anyray-connect desktop disconnect` to recover safely."]}}return{...u,messages:[...u.messages,"Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) with an ownership marker.",...await ii(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?B$:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=Yl(e),c=await q$(s),l=m=>c.length===0?m:{...m,messages:[...m.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await WC(e)}catch(m){return l({status:"manual",messages:[m instanceof Ue?m.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let m=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...m&&m.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${m.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let m=r()?Ut(e):void 0;if(!(m!==void 0&&f.changedFiles?.includes(m)===!0&&!await R(m)))return l(f)}let p;try{p=await Y$(await WC(e))}catch(m){let w=m instanceof Ue?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof Ue?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await re(i);let h=Sh(e);return n()&&h!==i&&await re(h),l({...f,messages:[...f.messages,...p.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...p])]})},async mcpStatus(){if(!ce())return{registered:!1,command:null};try{let s=await uo(Yl(e));return s.ownership!=="exact"||!lo(s.entry)?{registered:!1,command:null}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null}}},async pointsAt(s){return n()?(await ha(e)).supported?Xf(s,e):!1:r()?pC(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await ha(e)).supported)return["unknown"];let s=await LA(e);return s?[s]:["unknown"]}if(r())return await R(Ut(e))?await br(e.runReg??Hn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=tn(e);return!await R(s.journal)||await ao(s,e)?!1:(await ha(e)).supported}return r()&&await R(Ut(e))?!await br(e.runReg??Hn):!1}catch{return!1}}}},qC=eM();import{homedir as RM}from"node:os";import{join as OM}from"node:path";import{rm as od}from"node:fs/promises";import{constants as QC,accessSync as tM,statSync as nM}from"node:fs";import{platform as Eh}from"node:os";import{delimiter as rM,posix as oM,resolve as aM,win32 as sM}from"node:path";var iM="0.59.0",cM="1.1.4",Wn="Anyray \xB7 Claude",Kn="Anyray \xB7 Codex",Jl="__anyray-acp-agent",ev=(e,t,n)=>{let{command:r,args:o}=dn([Jl,e,t,n]);return{command:r,args:o,env:{}}},zl=(e=Eh())=>e==="win32"?"npx.cmd":"npx",ql=(e=process.env.PATH,t=Eh())=>{if(!e)return;let n=zl(t);for(let r of e.split(rM)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=aM(o,n);try{if(!nM(a).isFile())continue;return tM(a,t==="win32"?QC.F_OK:QC.X_OK),a}catch{}}},Ql=(e,t=Eh())=>{let n=t==="win32"?sM:oM;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==zl(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},lM="https://chatgpt.com/backend-api/codex",dM="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",tv="ANYRAY_ACP_CODEX_AUTHORIZATION",nv="ANYRAY_ACP_CODEX_CLIENT_KEY",rv="ANYRAY_ACP_CODEX_METADATA",ov=e=>le({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),uM=(e,t={})=>{let n=J(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":lM,"x-anyray-forward-headers":dM}:{},o=n?{...e.clientKey?{"x-anyray-api-key":nv}:{}}:{Authorization:tv};return ov(e)&&(o["x-anyray-metadata"]=rv),{model_provider:"anyray",model_providers:{anyray:{name:"Anyray Gateway",base_url:e.openaiBaseUrl,wire_api:"responses",...n?{requires_openai_auth:!0}:{},http_headers:r,env_http_headers:o}},...t.mcpServer?{mcp_servers:{anyray:{command:t.mcpServer.command,args:t.mcpServer.args}}}:{}}},pM=e=>{let t=J(e,"openai"),n=ov(e);return{...t?e.clientKey?{[nv]:e.clientKey}:{}:{[tv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[rv]:n}:{}}},av=(e,t=zl(),n={})=>({[Wn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${iM}`],env:un(e).env},[Kn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${cM}`],env:{CODEX_CONFIG:JSON.stringify(uM(e,n)),...pM(e)}}}),li=(e=zl(),t="jetbrains")=>({[Wn]:ev("claude",e,t),[Kn]:ev("codex",e,t)}),po=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ed=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as fM}from"node:zlib";import{open as hM,readFile as _h,readdir as rd}from"node:fs/promises";import{dirname as sv,join as de}from"node:path";import{homedir as dv,platform as Th}from"node:os";var td="2025.3.2",ma="253.30387.147",di="com.intellij.ml.llm",xh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),mM=1e4,yM=256*1024*1024,gM=16*1024*1024,Ih=1024*1024,Rh=22,wM=Rh+65535,Oh=bl,bM=()=>{let e=dv(),t=de(e,".cache","JetBrains","RemoteDev");switch(Th()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:de(e,"Applications"),layout:"app-bundles"},{path:de(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:de(process.env.LOCALAPPDATA??de(e,"AppData","Local"),"Programs"),layout:"children"},{path:de(process.env.LOCALAPPDATA??de(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:de(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:de(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},kM=()=>Th()==="linux"?de(dv(),".local","share","JetBrains"):ot("JetBrains"),AM=()=>Th()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),CM=async(e,t=mM)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await rd(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=de(r.path,i.name),l=r.layout==="app-bundles"?de(c,"Contents","Resources","product-info.json"):de(c,"product-info.json");await R(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=de(s,"product-info.json"),l=de(s,"Contents","Resources","product-info.json");if(await R(c)){n.push(c);return}if(await R(l)){n.push(l);return}let d;try{d=await rd(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=de(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(f,i-1)}};await a(r.path,7)}return[...new Set(n)]},vM=e=>{let t=sv(e);return t.endsWith(`${de("Contents","Resources")}`)?sv(t):t},SM=async e=>{try{let t=JSON.parse(await _h(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Gs(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:vM(e)}}catch{return}},nd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},EM=async(e,t)=>{let n;try{n=await hM(e,"r");let{size:r}=await n.stat();if(r<Rh||r>yM)return;let o=Math.min(r,wM),a=await nd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Rh;u>=0;u-=1)if(a.readUInt32LE(u)===101010256){s=u;break}if(s<0)return;let i=a.readUInt32LE(s+12),c=a.readUInt32LE(s+16);if(i>gM||c+i>r)return;let l=await nd(n,i,c);if(!l)return;let d=0;for(;d+46<=l.length;){if(l.readUInt32LE(d)!==33639248)return;let u=l.readUInt16LE(d+10),f=l.readUInt32LE(d+20),p=l.readUInt32LE(d+24),h=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),g=l.readUInt32LE(d+42),y=d+46+h+m+w;if(y>l.length)return;let b=l.subarray(d+46,d+46+h).toString("utf8");if(d=y,b!==t)continue;if(f===4294967295||p===4294967295||f>Ih||p>Ih)return;let v=await nd(n,30,g);if(!v||v.readUInt32LE(0)!==67324752)return;let S=v.readUInt16LE(26),E=v.readUInt16LE(28),x=await nd(n,f,g+30+S+E);return x?u===0?x.toString("utf8"):u===8?fM(x,{maxOutputLength:Ih}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},iv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Gs(n)))return{id:t,version:n}},xM=async(e,t)=>{let n=de(e,"META-INF","plugin.xml");if(await R(n))try{let o=iv(await _h(n,"utf8"));return{present:o?.id===di||t,descriptor:o?.id===di?o:void 0}}catch{return{present:t}}let r=[];try{r=(await rd(de(e,"lib"),{withFileTypes:!0})).filter(o=>o.isFile()&&o.name.endsWith(".jar")&&/(?:^|[-_.])(ml-?llm|llm|aia|ai[-_.]?assistant)(?:[-_.]|$)/i.test(o.name)).slice(0,32).map(o=>de(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await EM(o,"META-INF/plugin.xml"),s=a?iv(a):void 0;if(s?.id===di)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},cv=async e=>{let t;try{t=await rd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=xh.has(o.name.toLowerCase()),i=xh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=xh.has(o.name.toLowerCase());if(!a){let i=de(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await xM(de(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},IM=async e=>{try{return(await _h(de(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(di)}catch{return!1}},lv=e=>e.reduce((t,n)=>t?(Oh(n,t)??-1)>0?n:t:n,void 0),uv=async(e={})=>{let t=e.configRoot??ot("JetBrains"),n=e.userPluginsRoot??kM(),r=await CM(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):bM(),e.scanBudget),o=(await Promise.all(r.map(h=>SM(h)))).filter(h=>h!==void 0),a=o.length>0||await R(t);if(e.wsl??AM())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(h=>(Oh(h.version,td)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let h of s){let m=de(t,h.dataDirectoryName);if(!await R(m)){d=!0;continue}let w=[de(m,"plugins"),de(n,h.dataDirectoryName),de(n,h.dataDirectoryName,"plugins")],g;for(let y of[...new Set(w)]){let b=await cv(y);if(b.present){g=b;break}}if(g??=await cv(de(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==di)){if(i.push(g.descriptor.version),await IM(m)){c=!0;continue}if(!((Oh(g.descriptor.version,ma)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${h.version}; AI Assistant ${g.descriptor.version}; ACP supported`,ideVersion:h.version,pluginVersion:g.descriptor.version}}}let u=lv(o.map(h=>h.version)),f=lv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${td}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${td}+ once, enable AI Assistant ${ma}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${ma}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${ma}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${ma}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${ma}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${td}+ from local product-info.json; no ACP config was written.`:p="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:p,ideVersion:u,pluginVersion:f}};var _M=[Wn,Kn],Ph=()=>OM(RM(),".jetbrains","acp.json"),fo=()=>`${Ph()}.anyray-state`,TM=(e,t,n="npx")=>{let r=po(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,li(n,"jetbrains")),{...e,agent_servers:r}},PM=(e,t,n)=>{if(!po(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=po(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of _M)if(c in r){if(!ed(r[c],n[c])){s.push(c);continue}c in o?r[c]=o[c]:delete r[c],a.push(c)}let i={...e};return Object.keys(r).length>0?i.agent_servers=r:delete i.agent_servers,{next:i,removed:a,conflicts:s}},LM=(e=uv)=>({id:"jetbrains",title:"JetBrains AI Assistant",automatic:!0,async detect(){let t=await e();return{installed:t.installed,detail:t.detail}},async apply(t,n){let r=Ph(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=ql();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await R(r),c;try{c=await M(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=li(a,"jetbrains");return await Xi({configPath:r,current:c,next:TM(c,t,a),journalPath:fo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,fo()]}},async revert(t){let n=Ph(),r=async()=>{if(!await R(n))return t.dryRun||(await re(n),await od(fo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await re(n),await od(fo(),{force:!0}).catch(()=>{})),{status:"manual",messages:[`Could not parse ${n}; remove the two \u201CAnyray \xB7 \u2026\u201D agent entries manually.`]}}let a={},s=!1,i=!1;try{let u=await M(fo());(u.version===1||u.version===2)&&po(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await R(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await M(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Dr(n);let l=PM(o,c,a),d=[];return l.removed.length&&d.push(`Removed ${l.removed.join(", ")} from ${n}.`),l.conflicts.length&&d.push(`Preserved user-modified ACP entries: ${l.conflicts.join(", ")}.`),!t.dryRun&&l.removed.length&&(s&&Object.keys(l.next).length===0?await od(n,{force:!0}):await Z(n,l.next,{backup:!1})),t.dryRun||(await re(n),await od(fo(),{force:!0}).catch(()=>{})),{status:l.conflicts.length?"manual":"reverted",messages:d.length?d:["No Anyray ACP entries found."],changedFiles:!t.dryRun&&l.removed.length?[n]:void 0}};return t.dryRun?r():Zi(n,fo(),r)}}),pv=LM();import{homedir as sd}from"node:os";import{join as id}from"node:path";import{rm as Lh}from"node:fs/promises";var Dh="1.0.0",cd=["anyray-claude-acp","anyray-codex-acp"],DM=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Nh=()=>id(sd(),".windsurf","acp","registry.json"),$h=()=>id(sd(),".windsurf-next","acp","registry.json"),ya=e=>`${e}.anyray-state`,fv=e=>({binary:Object.fromEntries(DM.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),mv=(e="npx")=>{let t=li(e,"windsurf");return[{id:cd[0],name:Wn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:fv(t[Wn])},{id:cd[1],name:Kn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:fv(t[Kn])}]},ad=e=>!Array.isArray(e)||e.some(t=>!po(t)||typeof t.id!="string")?null:e,NM=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Dh||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:ad(e.agents);if(!n)return null;let r=new Set(cd);return{...e,version:typeof e.version=="string"?e.version:Dh,agents:[...n.filter(o=>!r.has(o.id)),...mv(t)],extensions:e.extensions??[]}},$M=(e,t,n)=>{let r=ad(e.agents);if(!r)return null;let o=ad(t.agents)??[],a=new Map((ad(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!cd.includes(u.id)){l.push(u);continue}if(!ed(u,a.get(u.id))){c.push(u.id),l.push(u);continue}let f=s.get(u.id);f&&l.push(f),i.push(u.id)}let d={...e,agents:l};return!Object.prototype.hasOwnProperty.call(t,"agents")&&l.length===0&&delete d.agents,!Object.prototype.hasOwnProperty.call(t,"version")&&d.version===Dh&&delete d.version,!Object.prototype.hasOwnProperty.call(t,"extensions")&&Array.isArray(d.extensions)&&d.extensions.length===0&&delete d.extensions,{next:d,removed:i,conflicts:c}},hv=async()=>{let e=[];return(await R($h())||await R(id(sd(),".windsurf-next")))&&e.push($h()),(await R(Nh())||await R(id(sd(),".windsurf"))||await R(ot("Devin"))||await R(ot("Windsurf")))&&e.push(Nh()),e},yv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await hv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await hv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=ql();if(!r)return{status:"manual",messages:["Devin ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP registry was written."]};let o=[],a=[];for(let s of n){let i;try{i=await M(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=NM(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await R(s),d=mv(r);await Xi({configPath:s,current:i,next:c,journalPath:ya(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,ya(s))}}return o.push("Devin requires a one-time vendor UI enablement for local registry agents: Devin Settings \u2192 Agents \u2192 enable the two Anyray agents, then restart Devin Desktop."),o.push("Native Devin/Cascade subscription requests are not redirected. The official enterprise consumption connector imports content-free usage instead."),o.push("No proxy, certificate, DNS, DEVIN_API_URL, or private first-party endpoint was changed."),{status:"manual",messages:o,changedFiles:a.length?a:void 0}},async revert(e){let t=[Nh(),$h()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await re(a),await Lh(ya(a),{force:!0}).catch(()=>{}));return}let i;try{i=await M(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let p=await M(ya(a));(p.version===1||p.version===2)&&Array.isArray(p.agents)&&(c=p.agents,l=p.version===2&&p.fileExisted===!1,d=p.version===2&&p.fileExisted===!0)}catch{}let u;if(d){let p=`${a}.anyray-bak`;if(!await R(p)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await M(p)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await Dr(a);let f=$M(i,u,c);if(!f){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}f.removed.length&&(n.push(`Removed ${f.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(f.next).length===0?await Lh(a,{force:!0}):await Z(a,f.next,{backup:!1}),r.push(a))),f.conflicts.length?(n.push(`Preserved user-modified agents: ${f.conflicts.join(", ")}.`),o=!0):e.dryRun||(await re(a),await Lh(ya(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await Zi(a,ya(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var oe=[nr,vw,Is,uk,Dk,Yk,rA,pv,qC,yv,Pw],Ht=e=>oe.find(t=>t.id===e);var MM=["hook_registration","mcp_registration","hook_binary","beacon_target"],ho=e=>e.status==="configured"||e.status==="queued",mo=async(e,t=oe)=>{let n=new Set(e),r=[];for(let o of t)if(n.has(o.id))try{(await o.detect()).installed&&r.push(o)}catch{}return r},Ar=async(e,t,n=oe)=>{let r=[];for(let o of await mo(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},Mh=async(e,t=oe)=>{let n=[];for(let r of await mo(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(MM.map(o=>[o,"unreadable"]))})}return n},gv=e=>e.filter(t=>!t.integrationStatus),FM=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},gt=async(e,t)=>{let n=[];for(let r of e)try{let o=await r.apply(t,{dryRun:!1});n.push({id:r.id,title:r.title,status:o.status})}catch(o){let a=FM(o);if(r.classifyApplyError)try{a=r.classifyApplyError(o)}catch{}n.push({id:r.id,title:r.title,status:"failed",errorClass:a})}return n};import{mkdir as VM,writeFile as YM}from"node:fs/promises";import{join as Sv}from"node:path";import{z as He}from"zod";var BM=["HTTPS_PROXY","https_proxy"],wv=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_UNTRUSTED"]),bv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),kv=new Set(["ENOTFOUND","EAI_AGAIN"]),Av=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Cv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),UM=e=>{let t=e;for(let n=0;n<5&&t;n++){let r=t.code;if(typeof r=="string"&&r)return r;t=t.cause}return HM(e)},HM=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...wv,...bv,...kv,...Av,...Cv])if(t.includes(n))return n}},WM=e=>e?.name==="AbortError"||e?.name==="TimeoutError",KM=e=>BM.filter(t=>(e[t]??"").trim()!==""),GM=(e,t=process.env)=>{let n=UM(e),r=KM(t);return{kind:n&&wv.has(n)?"tls-unknown-issuer":n&&bv.has(n)?"tls-invalid-cert":n&&kv.has(n)?"dns":WM(e)||n&&Cv.has(n)?"timeout":n&&Av.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},jM=e=>{let t=e.proxyVars.length>0?` ${e.proxyVars.join(" and ")} ${e.proxyVars.length>1?"are":"is"} set \u2014 if that proxy is stale or unreachable, unset it and re-run.`:"";switch(e.kind){case"tls-unknown-issuer":return` (TLS certificate signed by an unknown authority: ${e.code}). Your network appears to inspect TLS traffic. curl trusts your system keychain and this binary does not, which is why the download worked and this step did not. Point NODE_EXTRA_CA_CERTS at your organization root certificate (PEM) and re-run.`+t;case"tls-invalid-cert":return` (TLS certificate rejected: ${e.code}). Check this machine's clock and date, and whether a proxy is rewriting HTTPS traffic, then re-run.`+t;case"dns":return` (DNS lookup failed: ${e.code}). Check your VPN or DNS, then re-run.`+t;case"refused":return` (connection failed: ${e.code}).`+(t||" Check your network or firewall, then re-run.");case"timeout":return" (timed out before the control plane answered)."+(t||" Check your connection and re-run.");default:return e.code?` (${e.code}).${t}`:t}},wt=(e,t=process.env)=>jM(GM(e,t));var ga="required",vv=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team;return{routingUpdated:n,teamUpdated:r,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{}}},ld=(e,t,n)=>{let r=new Set(t.enabled??[]),o=e.managedTools??[],a=o.filter(u=>r.has(u)||n),s=new Set(e.revertedTools??[]),i=e.revertedTools!=null,c=u=>t.tiers?.[u]??ga,l=[],d=[];for(let u of r){if(o.includes(u))continue;let f=c(u);if(f!=="optional"){if(f!=="locked"){if(!i)continue;if(s.has(u)){f==="required"&&d.push(u);continue}}l.push(u)}}return{candidateIds:a,freshIds:l,tombstonedIds:d}};var ZM=1e4,XM=1,JM=He.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),zM=He.object({id:JM,name:He.string().min(1),version:He.string().min(1),body:He.string()}),qM=He.object({version:He.literal(XM).optional(),skills:He.array(zM),updatedAt:He.string().min(1).optional(),routing:He.object({origin:He.string().min(1)}).optional(),team:He.string().min(1).optional(),tools:He.object({enabled:He.array(He.string().min(1)),tiers:He.record(He.string().min(1),He.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),QM=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",dd=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",ud=async(e,t,n={})=>{let r=n.timeoutMs??ZM,o=`${e}/connect/policy`,a=new AbortController,s=setTimeout(()=>a.abort(),r),i;try{i=await fetch(o,{method:"GET",headers:{"x-anyray-api-key":t},signal:a.signal})}catch(l){let d=l instanceof Error&&l.name==="AbortError"?` no response within ${r}ms.`:wt(l);throw new Error(`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Error(`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch(l){let d=new Error("team policy fetch failed: the gateway returned a malformed response");throw d.name=dd(l),d}return qM.parse(c)},Ev=/^[a-z0-9][a-z0-9-]{0,31}$/,xv=64,eF=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>Ev.test(o)).slice(0,xv).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>Ev.test(o)).slice(0,xv).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},ui=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??ga)==="locked":!1},pd=async(e,t={})=>{let n=t.loadProfile??P,r=t.saveProfile??te,o=t.targetFromProfile??_e,a=t.adapters??oe,s=t.repairTools??gt,i=t.recordManaged??Xn,c=await n(),l={...c},d=vv(c,{routingOrigin:e.routing?.origin?ln(e.routing.origin):void 0,team:e.team}),{routingUpdated:u,teamUpdated:f}=d;(u||f)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),await r(l));let p=ld(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f),{candidateIds:h,freshIds:m}=p,w=0,g=0,y=0;if(h.length>0||m.length>0){let S=await o(async()=>l);if(S){let E;if(u||f){let I=new Set(h);E=[];for(let T of a)if(I.has(T.id))try{(await T.detect()).installed&&E.push(T)}catch{}}else E=await Ar(h,S.toolOrigin,a);let x=new Set(m),A=[];for(let I of a)if(x.has(I.id))try{(await I.detect()).installed&&A.push(I)}catch{}if(w=E.length+A.length,w>0){let I=await s([...E,...A],S.target);g=I.filter(ho).length;let T=I.filter(B=>x.has(B.id));if(y=T.filter(ho).length,T.length>0)try{await i(T,!1)}catch{}}}}let b=eF(e),v=await n();if(JSON.stringify(b??null)!==JSON.stringify(v.fleetToolPolicy??null)){let{fleetToolPolicy:S,...E}=v;await r({...E,...b?{fleetToolPolicy:b}:{}})}return{routingUpdated:u,teamUpdated:f,toolsRequested:w,toolsApplied:g,toolsEnrolled:y,toolsTombstoned:p.tombstonedIds,profileUpdated:u||f}},Iv=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!QM(i.id))continue;if(o[i.id]=i.version,n[i.id]===i.version){s+=1,r.push({id:i.id,name:i.name,version:i.version,written:!1,files:[]});continue}let l=[];for(let d of t){let u=Sv(d,i.id),f=Sv(u,"SKILL.md");await VM(u,{recursive:!0}),await YM(f,tF(i.body),"utf-8"),l.push(f)}a+=1,r.push({id:i.id,name:i.name,version:i.version,written:!0,files:l})}return{results:r,changed:a,unchanged:s,versions:o,updatedAt:e.updatedAt}},tF=e=>e.endsWith(`
|
|
294
294
|
`)?e:`${e}
|
|
295
|
-
`;import{createHash as BM,createPrivateKey as UM,generateKeyPairSync as HM,randomBytes as Mh,sign as WM}from"node:crypto";var Fh=1e4,mo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(mo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${mo(e[n])}`).join(",")}}`,ui="stable-key-heartbeat-v1",Cv="key-heartbeat",KM=["reapply_config","remint","revert"];var vv=e=>BM("sha256").update(e).digest("hex"),qe=e=>typeof e=="string"&&e.trim()?e.trim():void 0,GM=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],Bh=async e=>{try{let t=await e.json(),n=qe(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},xt=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Ar=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},Uh=(e,t,n)=>{try{let r=UM(t),o=new TextEncoder().encode(mo(e));return WM(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},ud=()=>{let{publicKey:e,privateKey:t}=HM("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},on=async(e,t,n,r={})=>{let o=r.timeoutMs??Fh,a=`${e}/connect/verify`,s=qe(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:Mh(16).toString("hex")},c=Uh(i,n,"verification"),l=new AbortController,d=setTimeout(()=>l.abort(),o),u;try{u=await fetch(a,{method:"POST",headers:{"content-type":"application/json","x-anyray-connect-version":we},body:JSON.stringify({cert:t,challenge:i,sig:c,...r.health?{health:r.health}:{},...r.ack?{ack:r.ack}:{},...r.telemetryOnly?{telemetryOnly:!0}:{}}),signal:l.signal})}catch(y){let b=y instanceof Error&&y.name==="AbortError"?`no response within ${o}ms`:y instanceof Error?y.message:String(y);throw new Error(`could not reach the gateway at ${a}: ${b}`,{cause:y})}finally{clearTimeout(d)}if(!u.ok)throw new xt(u.status,await Bh(u));let f;try{f=await u.text()}catch{f=""}let p;try{p=JSON.parse(f)}catch{let y=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(y)||/^\s*<(?:!doctype|html)/i.test(f);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let h=qe(p?.key);if(!h)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(h))throw new Error("developer verification failed: the gateway returned a malformed key");let m=qe(p.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=jM(p.directive),g=GM(p.capabilities);return{key:h,user:m,team:qe(p.team),expiresAt:qe(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},pd=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Fh,s=`${e}/connect/key/heartbeat`,i=qe(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:Mh(16).toString("hex"),purpose:Cv},l=Uh(c,r,"heartbeat"),d=new AbortController,u=setTimeout(()=>d.abort(),a),f;try{f=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(m){let w=m instanceof Error&&m.name==="AbortError"?`no response within ${a}ms`:m instanceof Error?m.message:String(m);throw new Error(`could not reach the gateway at ${s}: ${w}`,{cause:m})}finally{clearTimeout(u)}if(!f.ok)throw new Ar(f.status,await Bh(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=qe(p.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||p.credentialMode!==ui||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:ui}},Sv=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Fh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=qe(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Mh(16).toString("hex"),purpose:Cv},d=Uh(l,r,"heartbeat"),u=new AbortController,f=setTimeout(()=>u.abort(),s);try{return(await fetch(i,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(p){return console.error("connect machine report skipped:",p instanceof Error?p.name:"error"),!1}finally{clearTimeout(f)}},jM=e=>{if(e===null||typeof e!="object")return null;let t=e,n=qe(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!KM.includes(r)?null:{id:n,kind:r}},VM=1e4,YM=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!qe(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!qe(r.deploymentId)&&!!qe(r.user)&&!!qe(r.devPublicKey)&&!!qe(r.issuedAt)&&!!qe(r.expiresAt)},ZM=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??VM,s=`${e}/v1/enroll`,i=new AbortController,c=setTimeout(()=>i.abort(),a),l;try{l=await fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:t,devPublicKey:n,...r.email?{email:r.email}:{},...r.team?{team:r.team}:{},...r.machineId?{machineId:r.machineId}:{},...r.deploymentId?{deploymentId:r.deploymentId}:{}}),signal:i.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?`no response within ${a}ms`:u instanceof Error?u.message:String(u);throw new Error(`could not reach the control plane at ${s}: ${f}`)}finally{clearTimeout(c)}if(!l.ok)throw new Error(`enrollment failed: ${await Bh(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!YM(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},Ev=(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())},xv=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=ud();return{cert:await ZM(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),privateKeyPem:s.privateKeyPem,publicKeyPem:s.publicKeyPem}})(),a=await on(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};import{createPrivateKey as eF,randomBytes as tF,sign as nF}from"node:crypto";var XM="https://app.anyray.ai",JM=new Set(["localhost","::1","[::1]"]),zM=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,qM=e=>JM.has(e)||zM.test(e),Hh=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&qM(t.hostname)},QM=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Kn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!Hh(e)?XM:QM(e)};var rF=1e4,oF="machine:",Iv=e=>e.startsWith(oF),aF="cert-renew",sF=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)},Ov=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Kn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:tF(16).toString("hex"),purpose:aF},c;try{let h=eF(t),m=new TextEncoder().encode(mo(i));c=nF(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),rF),u;try{u=await r(`${a}/v1/cert/renew`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({cert:e,challenge:i,sig:c}),signal:l.signal})}finally{clearTimeout(d)}if(!u.ok)return{ok:!1,refused:u.status>=400&&u.status<500&&u.status!==429};let p=(await u.json().catch(()=>null))?.cert;return sF(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var Wh=async(e,t=e.origin,n=re)=>{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}},pi=async(e,t=e.origin,n=re)=>(await Wh(e,t,n)).complete;var iF=["claude","codex","cursor","opencode"],cF=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],lF=new Set(["missing_key","key_expired"]);var dF=600*1e3,uF=600*1e3,Rv=1440*60*1e3,pF=1440*60*1e3,fF=10080*60*1e3,hF=3600*1e3,mF=720*60*1e3,yF=e=>Math.min(mF,hF*2**Math.max(0,e-1)),fi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ga=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,_v=e=>typeof e=="string"&&cF.includes(e),kn=e=>{if(!fi(e))return{};let t={};if(ga(e.watchSince)&&(t.watchSince=e.watchSince),fi(e.invoked)){let n={};for(let r of iF){let o=e.invoked[r];ga(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return fi(e.authFailure)&&ga(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,..._v(e.authFailure.code)?{code:e.authFailure.code}:{}}),fi(e.repair)&&ga(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,...ga(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},fd=e=>{try{let n=JSON.parse(e);if(fi(n)&&_v(n.code)&&n.code!=="key_invalid")return n.code}catch{}let t=e.toLowerCase();if(t.includes("valid client key required"))return"key_invalid";if(t.includes("client key required"))return"missing_key"},Kh=e=>e!==void 0&&lF.has(e),Gh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=dF},Pv=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),jh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=uF},Tv=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),Lv=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,Dv=(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},Nv=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>Rv||!Kh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<yF(r.failures??1))},hd=e=>{let t=Object.values(e?.invoked??{}).filter(ga);return t.length>0?Math.max(...t):null},Vh=(e,t)=>{if(hd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=fF},$v=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=pF)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=Rv)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var Yh="x-anyray-retrieve-probe",md=8e3,gF=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Mv=(e,t)=>{let n=Zt(e);return t?.probe&&(n[Yh]="1"),n},wa=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(),md);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:Mv(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=gF(i)&&i.code==="slice_unsupported";return{ok:!1,kind:a.status===401||a.status===403?"auth":c?"slice-unsupported":"unavailable",message:`Retrieval unavailable (gateway returned HTTP ${a.status}).`}}let s;try{s=await a.json()}catch{return{ok:!1,kind:"malformed",message:"Retrieval returned malformed JSON."}}return typeof s?.content!="string"?{ok:!1,kind:"malformed",message:"Retrieval returned no content."}:{ok:!0,content:s.content,...typeof s.totalLines=="number"&&{totalLines:s.totalLines},...typeof s.totalChars=="number"&&{totalChars:s.totalChars},...typeof s.partial=="boolean"&&{partial:s.partial},...typeof s.startLine=="number"&&{startLine:s.startLine},...typeof s.endLine=="number"&&{endLine:s.endLine},...typeof s.grepMatches=="number"&&{grepMatches:s.grepMatches},...typeof s.grepTruncated=="boolean"&&{grepTruncated:s.grepTruncated}}}catch(a){let s=a instanceof Error&&a.name==="AbortError";return{ok:!1,kind:s?"timeout":"network",message:s?"Retrieval timed out.":`Retrieval failed: ${a instanceof Error?a.message:String(a)}`}}finally{clearTimeout(o)}},yd=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(),md);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:Mv(e,r),body:JSON.stringify({query:t,...typeof n=="number"?{k:n}:{}}),signal:o.signal});if(!s.ok)return{ok:!1,kind:s.status===401||s.status===403?"auth":"unavailable",message:`Recall unavailable (gateway returned HTTP ${s.status}).`};let i;try{i=await s.json()}catch{return{ok:!1,kind:"malformed",message:"Recall returned malformed JSON."}}return Array.isArray(i?.matches)?{ok:!0,matches:i.matches}:{ok:!1,kind:"malformed",message:"Recall returned no matches list."}}catch(s){let i=s instanceof Error&&s.name==="AbortError";return{ok:!1,kind:i?"timeout":"network",message:i?"Recall timed out.":`Recall failed: ${s instanceof Error?s.message:String(s)}`}}finally{clearTimeout(a)}};var wF=5e3,bF=2048,kF=e=>{let t=e.toLowerCase();return t.includes("client key required")?!0:["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},ba=async(e={})=>{let t=e.readTarget??rt,n=e.fetch??fetch,r=e.timeoutMs??wF,o=null;try{o=await t()}catch{o=null}if(!o)return{verdict:"dark",reason:"target_null"};let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let i=Zt(o);i["content-type"]="application/json",i[Yh]="1";let c=await n(`${o.origin}/connect/optimize-output`,{method:"POST",headers:i,body:JSON.stringify({}),signal:a.signal});if(c.status===401||c.status===403){let u=(await c.text().catch(()=>"")).slice(0,bF);if(!kF(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=fd(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...f?{code:f}:{}}}if(!c.ok)return{verdict:"indeterminate",reason:c.status>=500?"unreachable":"unsupported",status:c.status};let l;try{l=await c.json()}catch{return{verdict:"indeterminate",reason:"unsupported",status:c.status}}return typeof l=="object"&&l!==null&&l.handled===!0?{verdict:"live",reason:"ok",status:c.status}:{verdict:"indeterminate",reason:"gateway_mismatch",status:c.status}}catch{return{verdict:"indeterminate",reason:"unreachable"}}finally{clearTimeout(s)}},Zh=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{createPrivateKey as AF,randomBytes as CF,sign as vF}from"node:crypto";var SF=500,Fv=2e3,EF=2e3,xF=250,Bv=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),SF);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)}},IF=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},OF=e=>new Promise(t=>setTimeout(t,e)),RF=async(e,t,n=OF)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),Fv),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=IF(i)??xF,s>EF))return!1}finally{clearTimeout(a)}await n(s)}},_F=async e=>{try{let n=(await T()).enrolledCert,r=await Fe(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:CF(16).toString("hex"),events:e},s;try{let i=AF(r),c=new TextEncoder().encode(mo(a));s=vF(null,c,i).toString("base64url")}catch{return!1}return await RF(`${Kn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},PF=async(e,t)=>{try{let r=(await T()).enrolledCert,o=await Fe();if(!r||!o)return;await on(e,r,o,{timeoutMs:Fv,health:{events:t},telemetryOnly:!0})}catch{}},Uv=async(e,t)=>{if(e.length!==0)try{let n=await rt(),r=n&&await Bv(n.origin,Zt(n),e,t);if(n&&await PF(n.origin,e),r)return;await _F(e)}catch{}},Xh=async(e,t,n={readTarget:()=>rt("profile"),post:Bv})=>{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 go=["hook_registration","mcp_registration","hook_binary","beacon_target"];var Wv=128,Kv=300*1e3,TF=["repaired","repair_failed","flapping","pending"],LF=["settings_not_writable","apply_unconfirmed","apply_threw"],Gv=["rebroke_same_day","repeat_days"],jv=new Set(re.map(e=>e.id)),yo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),Vv=e=>mi(e,go),gd=e=>{if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=Date.parse(`${e}T00:00:00.000Z`);return Number.isFinite(t)&&new Date(t).toISOString().slice(0,10)===e},Cr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,hi=e=>{if(!(!Array.isArray(e)||!e.every(Vv)))return Gn(e)},DF=e=>{if(!yo(e))return;let t=hi(e.checks);if(!(!Cr(e.since)||!mi(e.reason,Gv)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},NF=e=>{if(!yo(e))return;let t={};gd(e.day)&&(t.day=e.day),Cr(e.attempts)&&(t.attempts=e.attempts);let n=hi(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=hi(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=hi(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=hi(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),gd(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Cr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),yo(e.lastRepaired)){let i={};for(let c of go){let l=e.lastRepaired[c];Cr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=DF(e.flapping);return s&&(t.flapping=s),t},$F=e=>{if(!yo(e)||!gd(e.day)||!Cr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!jv.has(e.tool)||!Vv(e.checkId)||!mi(e.status,TF)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!mi(e.errorClass,LF))return;t=e.errorClass}else if(e.status==="flapping"){if(!mi(e.errorClass,Gv))return;t=e.errorClass}else if(e.errorClass!==void 0)return;return{day:e.day,sequence:e.sequence,tool:e.tool,checkId:e.checkId,status:e.status,...t?{errorClass:t}:{},delivered:e.delivered,...Cr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},Hv=e=>{if(!yo(e))return{};let t={};if(yo(e.adapters)){let n={};for(let r of jv){let o=NF(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($F).filter(n=>n!==void 0).slice(-Wv)),Cr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),yo(e.report)&&gd(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Cr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},MF=e=>new Date(e).toISOString().slice(0,10),FF=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Gn=e=>[...new Set(e)],wd=(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}:{}}},yi=(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(-Wv),nextSequence:r}},BF=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),UF=async e=>await _e(async()=>e,void 0,be)??null,HF=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=wd(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)},Yv=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:FF(e.lastConfirmedDay,n)?(e.consecutiveRepairDays??0)+1:1,a=o>=3,s={...e.lastRepaired??{}};for(let c of t)s[c]=r;let i=e.flapping;return{adapter:{...e,confirmedChecks:Gn([...e.confirmedChecks??[],...t]),brokenReportedChecks:(e.brokenReportedChecks??[]).filter(c=>!t.includes(c)),lastConfirmedDay:n,consecutiveRepairDays:o,lastRepaired:s,...a?{flapping:{since:i?.since??r,reason:"repeat_days",checks:Gn([...i?.checks??[],...t])}}:{}},slowFlap:a}},WF=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=wd(d,n),f=u.awaiting??[],p=a.get(l);if(f.length===0||t.has(l)||!p){c[l]=u;continue}let h=f.filter(y=>p.checks[y]==="owned"),m=f.filter(y=>{let b=p.checks[y];return b==="missing"||b==="foreign"}),w=f.filter(y=>{let b=p.checks[y];return b===void 0||b==="unreadable"}),g=Yv(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=yi(i,n,[...h.map(y=>({tool:l,checkId:y,status:"repaired"})),...m.map(y=>({tool:l,checkId:y,status:"repair_failed",errorClass:"apply_unconfirmed"})),...g.slowFlap?h.map(y=>({tool:l,checkId:y,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},KF=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=wd(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(g=>!d.includes(g)||u.includes(g)),p=f.filter(g=>u.includes(g)),h=l.attempts??0;if(h>=2||f.length===0&&!n){let g=p.filter(v=>!(l.brokenReportedChecks??[]).includes(v));if(g.length===0)return{result:void 0};let y=l.flapping;return c[e]={...l,brokenReportedChecks:Gn([...l.brokenReportedChecks??[],...g]),flapping:{since:y?.since??a,reason:"rebroke_same_day",checks:Gn([...y?.checks??[],...g])}},{next:yi({...i,adapters:c},o,g.map(v=>({tool:e,checkId:v,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let m=l.flapping;return c[e]={...l,attempts:h+1,attemptedChecks:Gn([...d,...f]),confirmedChecks:u.filter(g=>!f.includes(g)),brokenReportedChecks:Gn([...l.brokenReportedChecks??[],...p]),...p.length>0?{flapping:{since:m?.since??a,reason:"rebroke_same_day",checks:Gn([...m?.checks??[],...p])}}:{}},{next:yi({...i,adapters:c},o,p.map(g=>({tool:e,checkId:g,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),GF=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=wd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:Gn([...l.awaiting??[],...t])},{next:yi({...i,adapters:c},o,t.map(h=>({tool:e,checkId:h,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(h=>r[h]==="owned"):[],u=n.status==="configured"&&r?t.filter(h=>{let m=r[h];return m==="missing"||m==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=Yv(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:yi({...i,adapters:c},o,[...d.map(h=>({tool:e,checkId:h,status:"repaired"})),...u.map(h=>({tool:e,checkId:h,status:"repair_failed",errorClass:p})),...f.slowFlap?d.map(h=>({tool:e,checkId:h,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},jF=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>=Kv));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??Xh)(o.map(BF),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)},VF=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:f}of t){let p=r.adapters?.[u.id];for(let h of go){let m=f[h];if(!m||m==="unreadable")continue;let w,g;p?.awaiting?.includes(h)&&c.has(u.id)?w="pending":m==="missing"&&p?.flapping?.checks.includes(h)?(w="flapping",g=p.flapping.reason):w=m==="owned"?"ok":m,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:h,status:w,...g?{errorClass:g}:{}})}}let l=Date.parse(e.enrolledCert?.payload.expiresAt??e.enrolledCertExpiry??"");e.enrolledCert&&Number.isFinite(l)&&(l<=o?(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"expired"})):l-o<=336*60*60*1e3&&(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"problems",errorClass:"cert_expiring"}))),e.refreshSchedulerEnabled&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Ac)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??lr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=$v(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},YF=async(e,t,n,r,o,a,s)=>{if(!await s.claimState(u=>u.report?.day===r&&u.report.delivered?{result:!1}:u.report?.day===r&&u.report.attemptedAt!==void 0&&u.report.attemptedAt<=o&&o-u.report.attemptedAt<Kv?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await VF(e,t,n,c,o,s);await(s.report??Xh)(l,a).catch(()=>!1)&&await s.claimState(u=>u.report?.day===r?{next:{...u,report:{day:r,delivered:!0}},result:void 0}:{result:void 0},void 0)},Zv=async(e,t,n)=>{let r=n.now??Date.now,o=MF(r()),a=e.managedTools??[],s={...n,readState:async()=>Hv(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(Hv(l)),c)};try{let i=await(s.findIntegrations??$h)(a);await HF(i,o,s);let c=await(s.listPending??ir)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await WF(i,l,o,r(),s);let d=await(s.resolveTarget??UF)(e),u=d?await(s.findDrifted??kr)(a,d.toolOrigin):[],f=new Set(u.map(g=>g.id)),p=new Map(i.map(g=>[g.adapter.id,g]));for(let g of u)p.has(g.id)||p.set(g.id,{adapter:g,checks:{}});let h=!1,m=(s.runtimeDurable??ce)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?go.filter(R=>y[R]==="missing"):[];if(b.length===0&&!f.has(g.id))continue;let v=y;if(g.integrationStatus)try{v=await g.integrationStatus()}catch{v=Object.fromEntries(go.map(R=>[R,"unreadable"]))}let S=b.filter(R=>v[R]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),S.length===0&&!E)continue;let x=await KF(g.id,S,E,l.has(g.id),o,r(),s);if(!x)continue;let[A]=await(s.repair??gt)([g],d.target);if(!A)continue;h=!0;let I;A.status==="configured"&&g.integrationStatus&&(I=await g.integrationStatus().catch(()=>{})),await GF(g.id,x.checks,A,I,o,r(),s)}await jF(o,r(),t,s),i=await(s.findIntegrations??$h)(a);let w=await(s.listPending??ir)().catch(()=>[]);return await YF(e,i,w,o,r(),t,s),h}catch{return!1}};var tB=14,nB=.35,rB=900*1e3,Jv=360*60*1e3,oB=.2,aB=1800*1e3,zv=3600*1e3,sB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),iB=300*1e3,cB=30*1e3,lB=900*1e3,dB=(e=0)=>Math.min(lB,cB*2**Math.max(0,e)),qv=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}},uB=720*60*1e3,Qv=1440*60*1e3,pB=300*1e3,fB=.25,hB=.5,eS=3600*1e3,mB=720*60*60*1e3,yB=360*60*1e3,gB=1440*60*1e3,wB=4,bd=e=>JF("sha256").update(e).digest("hex").slice(0,32),iS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Ut)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??T)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(bd(e))},Jh=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,wB)}),bB=()=>aS(zF(),".anyray"),qh=()=>aS(bB(),"refresh-state.json"),Qh=e=>process.env?.[e],cS=()=>Qh("ANYRAY_REFRESH_DISABLE")==="true",em=()=>{let e=Qh("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:tB)*gB},wi=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},lS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),kB=10080*60*1e3,kd=(e,t,n=Date.now())=>{let r=[],o=wi(e);o!==void 0&&r.push(o);let a=Date.parse(t??e.clientKeyExpiresAt??"");Number.isFinite(a)&&r.push(a-n);let s=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??"");return Number.isFinite(s)&&r.push(s-n),r.length===0?!1:Math.min(...r)<=kB},bi=e=>{let t=em(),n=e?wi(e):void 0;if(!n)return t;let r=Math.max(rB,Math.round(n*nB));return Math.min(t,r)},AB=e=>{let t=Qh("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(Jv,Math.max(aB,Math.round(e*oB))):Jv},Ut=async()=>{try{let e=await qF(qh(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Ad=async e=>{try{let t=qh(),n=`${t}.${process.pid}.tmp`;await sS(n,JSON.stringify(e),{mode:384}),await fe(n,t),await QF(t,384).catch(()=>{})}catch{}},CB=3e4,vB=()=>`${qh()}.lock`,tS=async e=>{try{return await sS(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},ut=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Ut,a=n.writeState??Ad,s=vB(),i=!1;try{if(i=await tS(s),!i){if(await eB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<CB)return t;await Xv(s).catch(()=>{}),i=await tS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await Xv(s).catch(()=>{})}},gi=async(e,t={})=>{await ut(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},ka=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0),a=await(t.loadProfile??T)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?bd(a.clientKey):void 0;await ut(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:Jh(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},wo=async(e={})=>{let t=e.now??Date.now;await ut(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},SB=e=>{let t=e.enrolledCertLifetimeMs,n=Date.parse(e.enrolledCert?.payload.issuedAt??""),r=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??""),o=typeof t=="number"&&Number.isFinite(t)&&t>0?t:Number.isFinite(n)&&Number.isFinite(r)&&r>n?r-n:void 0;return o?Math.min(mB,Math.max(eS,Math.round(o*hB))):eS},zh=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,tm=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??ee,a=n.loadProfile??T,s=n.loadDevKey??Fe,i=n.renew??Ov,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(Iv(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()>SB(e))return{outcome:"not-due",profile:e};if(!await ut(w=>r()-(w.lastCertRenewAt??0)<yB?{result:!1}:{next:{...w,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await zh(f,c.sig,t,s))return{outcome:"superseded",profile:f};let p=u.cert.payload.expiresAt,h=Date.parse(p)-r(),m={...f,enrolledCert:u.cert,enrolledCertExpiry:p,...Number.isFinite(h)&&h>0?{enrolledCertLifetimeMs:h}:{}};return await o(m),{outcome:"renewed",profile:m}},nS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*fB):Qv,r=Math.min(Qv,n);return Math.min(r,pB*2**Math.max(0,e-1))},EB=()=>{let{command:e,args:t}=un(qn);return{exe:e,args:t}},vr=async(e={})=>{if(cS())return;let t=e.now??Date.now,n=e.readState??Ut,r=e.writeState??Ad,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=EB();XF(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await ut(s=>t()-(s.lastSpawnAt??0)<AB(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},xB=pi,IB=async(e,t=be,n=!1)=>{try{let r=e.managedTools??[];if(r.length===0)return!1;let o=await _e(async()=>e,void 0,t);if(!o)return!1;let a=await kr(r,o.toolOrigin),s=n?yv(a):a;return s.length===0?!1:(await gt(s,o.target),!0)}catch{return!1}},OB=async(e,t,n,r,o,a)=>{try{let s=new Set(e.managedTools??[]),i=re.filter(p=>s.has(p.id));if(i.length===0)return!1;let c=await r().catch(()=>{}),l=ye({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:c,user:e.name,team:e.team}),d=e.fallbackPort,u=nt(e)&&Number.isInteger(d)&&d>0&&d<=65535&&await o(d)!==null,f=await a(u?Cn(l,d):l,u?`http://${ht}:${d}`:l.origin,i);return f.matched>0&&f.complete}catch{return!1}},RB=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Ut,a=t.writeState??Ad;return Zv(e,we,{now:r,deadWatcherObserved:n,readHookLane:()=>Cd({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>ut(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Cd=async(e={})=>{let n=await(e.readState??Ut)().catch(()=>({}));return kn(n.hookLane)},dS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Cd(t);if(!Gh(r,e,n()))return;await ut(o=>{let a=kn(o.hookLane);return Gh(a,e,n())?{next:{...o,hookLane:Pv(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},uS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Cd(t);if(!jh(r,n()))return;await ut(o=>{let a=kn(o.hookLane);return jh(a,n())?{next:{...o,hookLane:Tv(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},_B=async(e={})=>{try{let t=e.now??Date.now;if((await Cd(e)).watchSince!==void 0)return;await ut(n=>{let r=kn(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:Lv(r,t())},result:void 0}},void 0,e)}catch{}},rS=async(e,t={})=>{try{let n=t.now??Date.now;await ut(r=>{let o=kn(r.hookLane),a=Dv(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},pS=async(e={})=>{try{if((await(e.readState??Ut)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>ut(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??ug)())return await r()?"stamped":"skipped";let o=await(e.load??T)(),s=await(e.findTools??ho)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await _e(async()=>o,void 0,e.probe??be);return!i||!await r()?"skipped":(await(e.repair??gt)(s,i.target),"repathed")}catch{return"skipped"}},fS=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Ut)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>ut(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??T)(),i=await(e.findTools??ho)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await _e(async()=>a,void 0,e.probe??be);return!c||!await o()?"skipped":(await(e.repair??gt)(i,c.target)).some(d=>d.status==="failed")?(await ut(d=>{if(d.appliedRevision!==t)return{result:void 0};let u={...d};return r===void 0?delete u.appliedRevision:u.appliedRevision=r,{next:u,result:void 0}},void 0,e).catch(()=>{}),"retry"):"swept"}catch{return"skipped"}},PB=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await ld(e.gateway,e.clientKey),n=await dd(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},oS=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??PB)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>IB(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},Qe=async(e={})=>{if(cS())return"disabled";let t=e.now??Date.now,n=e.loadProfile??T,r=e.saveProfile??ee,o=e.loadDevKey??Fe,a=e.readState??Ut,s=e.writeState??Ad,i=e.remint??on,c=e.heartbeat??pd,l=e.detectSeat??Tt,d=e.rewriteTools??xB,u=e.rewriteHookLaneTools??Wh,f=e.probeHookLane??ba,p=e.classifyBeacon??lc,h=e.probe??be,m=e.installProxy??Pt,w=e.pickProxyPort??hc,g=e.force===!0,y=!1,b=!1,v=!1,S=!1;e.hookLaneRepair===!0&&(g=!0,S=!0);let E=async A=>{if(!S){A==="repaired"&&await rS("none",{now:t,readState:a,writeState:s});return}let I=A;if(A==="repaired"){let R=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));I=R.verdict==="live"?"repaired":R.verdict==="dark"?"repair_failed":"unverified"}await rS(I,{now:t,readState:a,writeState:s})},x=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let A;try{A=await n()}catch{return!1}return(e.ambientSelfcheck??(R=>RB(R,{now:t,readState:a,writeState:s},v)))(A).catch(()=>!1)};try{e.runAmbientSelfcheck&&(v=await ir().then(P=>P.some(L=>!lr(L.watcherPid))).catch(()=>!1),await _B({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??jw)();let A=await n();if(y=!0,!A.gateway||!A.enrolledCert)return"not-enrolled";let I=A.gateway,R=A.enrolledCertExpiry?Date.parse(A.enrolledCertExpiry):Date.parse(A.enrolledCert.payload.expiresAt);if(!Number.isFinite(R)||R<=t())return"cert-expired";let M=await o();if(!M)return"not-enrolled";let X=await tm(A,M,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});A=X.profile;let V=X.outcome==="renewed",W=A.enrolledCert;if(!W)return"not-enrolled";let z=Date.parse(A.clientKeyExpiresAt??""),ve=Number.isFinite(z)?z-t():0,je=await a(),oe=!A.clientKey||ve<=bi(A),Me=A.credentialProtocol!=="stable-heartbeat-v1"&&t()-(je.lastSuccessAt??0)>=uB;if(!g&&Nv(kn(je.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,S=!0),A.credentialProtocol==="stable-heartbeat-v1"&&A.clientKey&&(g||oe)){let P=await ut(L=>{let H=t()-(L.lastAttemptAt??0);return H<zv?{result:"throttled"}:L.failureCount&&H<nS(L.failureCount,L.keyTtlMs)?{result:"backoff"}:{next:{...L,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(P!=="ok")return P;try{let L=await c(I,A.clientKey,W,M),H=await n().catch(()=>A);return H.clientKey!==A.clientKey||H.enrolledCert?.sig!==W.sig?"failed":(await r({...H,clientKeyExpiresAt:L.expiresAt}),await gi(({lastError:me,...se})=>({...se,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:wi(A)??se.keyTtlMs}),{now:t,readState:a,writeState:s}),S&&await E(await OB(A,I,A.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(L){let H=L;if(L instanceof Ar&&L.status===404)try{let se=await i(I,W,M),ge=await l().catch(()=>{}),He=ye({origin:I,clientKey:se.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:ge,user:A.name,team:A.team}),ue=A.fallbackPort,ie=Number.isInteger(ue)&&ue>0&&ue<=65535?ue:await w();if(!(await m({port:ie,remoteOrigin:I})).ok||await h(ie)===null)throw new Error("key-refresh proxy recovery failed");let De=await n().catch(()=>A);if(!await zh(De,W.sig,M,o))throw new Error("enrollment changed during proxy recovery");if(await r({...De,clientKey:se.key,clientKeyExpiresAt:se.expiresAt??De.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:ie}),await d(Cn(He,ie),He.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let ft=se.expiresAt?Date.parse(se.expiresAt):NaN,Ve=wi(A)??(Number.isFinite(ft)&&ft-t()>0?ft-t():void 0);return await gi(({lastError:Pr,...sn})=>({...sn,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ve??sn.keyTtlMs,ownKeys:Jh(sn.ownKeys,W.sig,bd(se.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(se){H=se}let me=qv(H);return await gi(se=>({...se,lastAttemptAt:t(),failureCount:(se.failureCount??0)+1,lastError:{name:H instanceof Error?H.name:"Error",...me!==void 0?{code:me}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),H instanceof Ar?"cert-rejected":"failed"}}if(!g&&A.clientKey&&!oe&&!Me){let P=await oS(A,e,n,h),L=await x();return P||L?"repaired":V?"cert-renewed":"not-due"}let xe=await ut(P=>{let L=t()-(P.lastAttemptAt??0);if(g)return L<dB(P.failureCount)?{result:"throttled"}:{next:{...P,lastAttemptAt:t()},result:"ok"};let H=P.lastError?.code!==void 0&&sB.has(P.lastError.code)?iB:zv;return L<H?{result:"throttled"}:P.failureCount&&L<nS(P.failureCount,P.keyTtlMs)?{result:"backoff"}:{next:{...P,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(xe!=="ok")return xe;try{let P=await i(I,W,M),L=await l().catch(()=>{}),H=ye({origin:I,clientKey:P.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:L,user:A.name,team:A.team}),me=H,se=H.origin;if(nt(A)){if(!Number.isInteger(A.fallbackPort)||A.fallbackPort<1||A.fallbackPort>65535)throw new Error("key-refresh proxy profile has no valid port");await h(A.fallbackPort)!==null&&(me=Cn(H,A.fallbackPort),se=`http://${ht}:${A.fallbackPort}`)}let ge=await d(me,se);if(A.directMigration==="pending"&&me.viaLocalProxy===!0){let ft=await d(me,H.origin);ge=ge!==!1&&ft!==!1}if(ge===!1)throw new Error("one or more configured tools rejected the refreshed key");let He=await n().catch(()=>A),ue=null,ie;He.enrolledCert&&await zh(He,W.sig,M,o)&&(ie=bd(P.key),ue={...He,clientKey:P.key,clientKeyExpiresAt:P.expiresAt??He.clientKeyExpiresAt},await r(ue));let Y=P.expiresAt?Date.parse(P.expiresAt):NaN,De=wi(A)??(Number.isFinite(Y)&&Y-t()>0?Y-t():void 0);return await gi(({lastError:ft,...Ve})=>({...Ve,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:De??Ve.keyTtlMs,...ie?{ownKeys:Jh(Ve.ownKeys,W.sig,ie)}:{}}),{now:t,readState:a,writeState:s}),ue&&await oS(ue,e,n,h),await E(ue?"repaired":"repair_failed"),await x(),"refreshed"}catch(P){let L=qv(P);return await gi(H=>({...H,lastAttemptAt:t(),failureCount:(H.failureCount??0)+1,lastError:{name:P instanceof Error?P.name:"Error",...L!==void 0?{code:L}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),P instanceof xt?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await x()}catch{}}};import{readFile as $B}from"node:fs/promises";import{isAbsolute as MB,posix as gS,win32 as om}from"node:path";var nm=1e4,TB=900*1e3,LB="tnt_",Wt=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=/^\/sso\/([^/]+)\/?$/.exec(n.pathname);return r?{cpOrigin:n.origin,tenantId:r[1]}:void 0}if(t.startsWith(LB))return{cpOrigin:Kn(),tenantId:t}},bo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Ht=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},rm=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await r(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:o.signal}),i={};try{i=await s.json()}catch{}return{status:s.status,json:i}}finally{clearTimeout(a)}},DB=e=>new Promise(t=>setTimeout(t,e)),vd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??ud)(),a;try{a=await rm(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},nm,n)}catch{throw new bo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new bo(h?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${m}). Ask your admin to confirm SSO is configured.`,a.status)}let s=a.json;if(!s.device_code||!s.user_code||!s.verification_uri_complete)throw new bo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??TB,l=typeof s.expires_in=="number"&&s.expires_in>0?s.expires_in*1e3:c,d=typeof s.verification_uri=="string"?s.verification_uri:void 0,u=e.gatewayUrl??(typeof s.gateway_url=="string"?s.gateway_url:void 0),f={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:s.device_code,userCode:s.user_code,verificationUri:d,verificationUriComplete:s.verification_uri_complete,intervalMs:Math.max(1,s.interval||5)*1e3,grantExpiresAt:i+Math.min(c,l),startedAt:i,privateKeyPem:o,publicKeyPem:r,gatewayUrl:u},p=e.log??(()=>{});return p("To finish, sign in with your organization at:"),p(` ${f.verificationUriComplete}`),p(`Confirm this code matches your browser: ${f.userCode}`),NB(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},NB=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Sd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??DB,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 rm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},nm,o)}catch{throw new Ht("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}`)}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 Ht("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Ht("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Ht("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var hS="sdc_",mS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(hS))return{cpOrigin:Kn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!Hh(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(hS)))return{cpOrigin:n.origin,claim:r}},yS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??ud)(),o;try{o=await rm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},nm,t)}catch{throw new Ht("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}`)}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 Ht("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Ht("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Ht("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};var ki=(e=process.platform,t=process.env)=>e==="darwin"?gS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?om.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):gS.join("/etc","anyray","bootstrap.json"),FB=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(MB(e)||om.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),BB=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}},Kt=async(e=ki())=>{try{let t=await $B(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!FB(n)||n.v!==1||typeof n.sso!="string")return;let r=Wt(n.sso);if(!r)return;let o=BB(n.gateway)?n.gateway:void 0,a=wS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},bS=(e,t,n)=>{let r=Wt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!wS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&om.isAbsolute(n)&&/^[A-Za-z]:\\/.test(n)&&!/^[A-Za-z]:\\Program Files( \(x86\))?\\/i.test(n))throw new Error("--bin on Windows must live under Program Files (admin-only writable)");return`${JSON.stringify({v:1,sso:`${r.cpOrigin}/sso/${r.tenantId}`,...t?{gateway:t}:{},...n?{bin:n}:{}},null,2)}
|
|
296
|
-
`};import{execFile as
|
|
297
|
-
`,{mode:384}),await
|
|
295
|
+
`;import{createHash as nF,createPrivateKey as rF,generateKeyPairSync as oF,randomBytes as Fh,sign as aF}from"node:crypto";var Bh=1e4,yo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(yo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${yo(e[n])}`).join(",")}}`,pi="stable-key-heartbeat-v1",Rv="key-heartbeat",sF=["reapply_config","remint","revert"];var Ov=e=>nF("sha256").update(e).digest("hex"),qe=e=>typeof e=="string"&&e.trim()?e.trim():void 0,iF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],Uh=async e=>{try{let t=await e.json(),n=qe(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},It=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Cr=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},Hh=(e,t,n)=>{try{let r=rF(t),o=new TextEncoder().encode(yo(e));return aF(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},fd=()=>{let{publicKey:e,privateKey:t}=oF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},an=async(e,t,n,r={})=>{let o=r.timeoutMs??Bh,a=`${e}/connect/verify`,s=qe(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:Fh(16).toString("hex")},c=Hh(i,n,"verification"),l=new AbortController,d=setTimeout(()=>l.abort(),o),u;try{u=await fetch(a,{method:"POST",headers:{"content-type":"application/json","x-anyray-connect-version":be},body:JSON.stringify({cert:t,challenge:i,sig:c,...r.health?{health:r.health}:{},...r.ack?{ack:r.ack}:{},...r.telemetryOnly?{telemetryOnly:!0}:{}}),signal:l.signal})}catch(y){let b=y instanceof Error&&y.name==="AbortError"?` no response within ${o}ms.`:wt(y);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:y})}finally{clearTimeout(d)}if(!u.ok)throw new It(u.status,await Uh(u));let f;try{f=await u.text()}catch{f=""}let p;try{p=JSON.parse(f)}catch{let y=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(y)||/^\s*<(?:!doctype|html)/i.test(f);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let h=qe(p?.key);if(!h)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(h))throw new Error("developer verification failed: the gateway returned a malformed key");let m=qe(p.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=cF(p.directive),g=iF(p.capabilities);return{key:h,user:m,team:qe(p.team),expiresAt:qe(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},hd=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Bh,s=`${e}/connect/key/heartbeat`,i=qe(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:Fh(16).toString("hex"),purpose:Rv},l=Hh(c,r,"heartbeat"),d=new AbortController,u=setTimeout(()=>d.abort(),a),f;try{f=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":be},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(m){let w=m instanceof Error&&m.name==="AbortError"?` no response within ${a}ms.`:wt(m);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:m})}finally{clearTimeout(u)}if(!f.ok)throw new Cr(f.status,await Uh(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=qe(p.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||p.credentialMode!==pi||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:pi}},_v=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Bh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=qe(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Fh(16).toString("hex"),purpose:Rv},d=Hh(l,r,"heartbeat"),u=new AbortController,f=setTimeout(()=>u.abort(),s);try{return(await fetch(i,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":be},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(p){return console.error("connect machine report skipped:",p instanceof Error?p.name:"error"),!1}finally{clearTimeout(f)}},cF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=qe(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!sF.includes(r)?null:{id:n,kind:r}},lF=1e4,dF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!qe(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!qe(r.deploymentId)&&!!qe(r.user)&&!!qe(r.devPublicKey)&&!!qe(r.issuedAt)&&!!qe(r.expiresAt)},uF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??lF,s=`${e}/v1/enroll`,i=new AbortController,c=setTimeout(()=>i.abort(),a),l;try{l=await fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:t,devPublicKey:n,...r.email?{email:r.email}:{},...r.team?{team:r.team}:{},...r.machineId?{machineId:r.machineId}:{},...r.deploymentId?{deploymentId:r.deploymentId}:{}}),signal:i.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${a}ms.`:wt(u);throw new Error(`could not reach the control plane at ${s}.${f}`)}finally{clearTimeout(c)}if(!l.ok)throw new Error(`enrollment failed: ${await Uh(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!dF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},Tv=(e,t,n,r,o,a,s)=>{if(!e)return!1;let i=t?Date.parse(t):NaN;return!(!Number.isFinite(i)||i<=r||n&&e.payload.deploymentId!==n||o&&o!==a||s&&e.payload.user.trim().toLowerCase()!==s.trim().toLowerCase())},Pv=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=fd();return{cert:await uF(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),privateKeyPem:s.privateKeyPem,publicKeyPem:s.publicKeyPem}})(),a=await an(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};import{createPrivateKey as gF,randomBytes as wF,sign as bF}from"node:crypto";var pF="https://app.anyray.ai",fF=new Set(["localhost","::1","[::1]"]),hF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,mF=e=>fF.has(e)||hF.test(e),Wh=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&mF(t.hostname)},yF=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Gn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!Wh(e)?pF:yF(e)};var kF=1e4,AF="machine:",Lv=e=>e.startsWith(AF),CF="cert-renew",vF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||typeof t.sig!="string"||!t.sig.trim())return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n,o=a=>typeof a=="string"&&!!a.trim();return typeof r.v=="number"&&o(r.deploymentId)&&o(r.user)&&o(r.devPublicKey)&&o(r.issuedAt)&&o(r.expiresAt)},Dv=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Gn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:wF(16).toString("hex"),purpose:CF},c;try{let h=gF(t),m=new TextEncoder().encode(yo(i));c=bF(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),kF),u;try{u=await r(`${a}/v1/cert/renew`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({cert:e,challenge:i,sig:c}),signal:l.signal})}finally{clearTimeout(d)}if(!u.ok)return{ok:!1,refused:u.status>=400&&u.status<500&&u.status!==429};let p=(await u.json().catch(()=>null))?.cert;return vF(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var Kh=async(e,t=e.origin,n=oe)=>{let r=0,o=0,a=!0;for(let s of n)try{if(!s.pointsAt||!await s.pointsAt(t)||await s.usesDynamicCredential?.(t))continue;r+=1,(await s.apply(e,{dryRun:!1})).status==="configured"?o+=1:a=!1}catch{a=!1}return{matched:r,rewritten:o,complete:a}},fi=async(e,t=e.origin,n=oe)=>(await Kh(e,t,n)).complete;var SF=["claude","codex","cursor","opencode"],EF=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],xF=new Set(["missing_key","key_expired"]);var IF=600*1e3,RF=600*1e3,Nv=1440*60*1e3,OF=1440*60*1e3,_F=10080*60*1e3,TF=3600*1e3,PF=720*60*1e3,LF=e=>Math.min(PF,TF*2**Math.max(0,e-1)),hi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wa=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,$v=e=>typeof e=="string"&&EF.includes(e),An=e=>{if(!hi(e))return{};let t={};if(wa(e.watchSince)&&(t.watchSince=e.watchSince),hi(e.invoked)){let n={};for(let r of SF){let o=e.invoked[r];wa(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return hi(e.authFailure)&&wa(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...$v(e.authFailure.code)?{code:e.authFailure.code}:{}}),hi(e.repair)&&wa(e.repair.at)&&(e.repair.outcome==="repaired"||e.repair.outcome==="repair_failed"||e.repair.outcome==="unverified")&&(t.repair={at:e.repair.at,outcome:e.repair.outcome,...wa(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},md=e=>{try{let n=JSON.parse(e);if(hi(n)&&$v(n.code)&&n.code!=="key_invalid")return n.code}catch{}let t=e.toLowerCase();if(t.includes("valid client key required"))return"key_invalid";if(t.includes("client key required"))return"missing_key"},Gh=e=>e!==void 0&&xF.has(e),jh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=IF},Mv=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),Vh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=RF},Fv=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),Bv=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,Uv=(e,t,n)=>{if(n==="repair_failed"||n==="unverified")return{...e,repair:{at:t,outcome:n,failures:(e.repair?.failures??0)+1}};let{authFailure:r,...o}=e;return n==="repaired"?{...o,repair:{at:t,outcome:n}}:o},Hv=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>Nv||!Gh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<LF(r.failures??1))},yd=e=>{let t=Object.values(e?.invoked??{}).filter(wa);return t.length>0?Math.max(...t):null},Yh=(e,t)=>{if(yd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=_F},Wv=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=OF)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=Nv)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var Zh="x-anyray-retrieve-probe",gd=8e3,DF=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Kv=(e,t)=>{let n=Xt(e);return t?.probe&&(n[Zh]="1"),n},ba=async(e,t,n)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let r=new AbortController,o=setTimeout(()=>r.abort(),gd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:Kv(e,n),body:JSON.stringify({handle:t,...n?.startLine!==void 0&&{startLine:n.startLine},...n?.endLine!==void 0&&{endLine:n.endLine},...n?.grep!==void 0&&{grep:n.grep}}),signal:r.signal});if(a.status===404)return await a.json().then(c=>typeof c=="object"&&c!==null).catch(()=>!1)?{ok:!1,kind:"not-found",message:`No stashed content for handle ${t} (unknown or expired).`}:{ok:!1,kind:"unsupported",message:"Gateway has no /connect/retrieve route (update the gateway image)."};if(!a.ok){let i=await a.json().catch(()=>{}),c=DF(i)&&i.code==="slice_unsupported";return{ok:!1,kind:a.status===401||a.status===403?"auth":c?"slice-unsupported":"unavailable",message:`Retrieval unavailable (gateway returned HTTP ${a.status}).`}}let s;try{s=await a.json()}catch{return{ok:!1,kind:"malformed",message:"Retrieval returned malformed JSON."}}return typeof s?.content!="string"?{ok:!1,kind:"malformed",message:"Retrieval returned no content."}:{ok:!0,content:s.content,...typeof s.totalLines=="number"&&{totalLines:s.totalLines},...typeof s.totalChars=="number"&&{totalChars:s.totalChars},...typeof s.partial=="boolean"&&{partial:s.partial},...typeof s.startLine=="number"&&{startLine:s.startLine},...typeof s.endLine=="number"&&{endLine:s.endLine},...typeof s.grepMatches=="number"&&{grepMatches:s.grepMatches},...typeof s.grepTruncated=="boolean"&&{grepTruncated:s.grepTruncated}}}catch(a){let s=a instanceof Error&&a.name==="AbortError";return{ok:!1,kind:s?"timeout":"network",message:s?"Retrieval timed out.":`Retrieval failed: ${a instanceof Error?a.message:String(a)}`}}finally{clearTimeout(o)}},wd=async(e,t,n,r)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let o=new AbortController,a=setTimeout(()=>o.abort(),gd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:Kv(e,r),body:JSON.stringify({query:t,...typeof n=="number"?{k:n}:{}}),signal:o.signal});if(!s.ok)return{ok:!1,kind:s.status===401||s.status===403?"auth":"unavailable",message:`Recall unavailable (gateway returned HTTP ${s.status}).`};let i;try{i=await s.json()}catch{return{ok:!1,kind:"malformed",message:"Recall returned malformed JSON."}}return Array.isArray(i?.matches)?{ok:!0,matches:i.matches}:{ok:!1,kind:"malformed",message:"Recall returned no matches list."}}catch(s){let i=s instanceof Error&&s.name==="AbortError";return{ok:!1,kind:i?"timeout":"network",message:i?"Recall timed out.":`Recall failed: ${s instanceof Error?s.message:String(s)}`}}finally{clearTimeout(a)}};var NF=5e3,$F=2048,MF=e=>{let t=e.toLowerCase();return t.includes("client key required")?!0:["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},ka=async(e={})=>{let t=e.readTarget??rt,n=e.fetch??fetch,r=e.timeoutMs??NF,o=null;try{o=await t()}catch{o=null}if(!o)return{verdict:"dark",reason:"target_null"};let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let i=Xt(o);i["content-type"]="application/json",i[Zh]="1";let c=await n(`${o.origin}/connect/optimize-output`,{method:"POST",headers:i,body:JSON.stringify({}),signal:a.signal});if(c.status===401||c.status===403){let u=(await c.text().catch(()=>"")).slice(0,$F);if(!MF(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=md(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...f?{code:f}:{}}}if(!c.ok)return{verdict:"indeterminate",reason:c.status>=500?"unreachable":"unsupported",status:c.status};let l;try{l=await c.json()}catch{return{verdict:"indeterminate",reason:"unsupported",status:c.status}}return typeof l=="object"&&l!==null&&l.handled===!0?{verdict:"live",reason:"ok",status:c.status}:{verdict:"indeterminate",reason:"gateway_mismatch",status:c.status}}catch{return{verdict:"indeterminate",reason:"unreachable"}}finally{clearTimeout(s)}},Xh=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{createPrivateKey as FF,randomBytes as BF,sign as UF}from"node:crypto";var HF=500,Gv=2e3,WF=2e3,KF=250,jv=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),HF);try{return(await fetch(`${e}/connect/health`,{method:"POST",headers:{...t,"x-anyray-connect-version":r},body:JSON.stringify({events:n}),signal:o.signal})).ok}catch{return!1}finally{clearTimeout(a)}},GF=e=>{let t=e.headers?.get?.("retry-after");if(!t)return;let n=Number(t.trim());return Number.isFinite(n)&&n>=0?n*1e3:void 0},jF=e=>new Promise(t=>setTimeout(t,e)),VF=async(e,t,n=jF)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),Gv),s;try{let i=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:t,signal:o.signal});if(i.ok)return!0;let c=i.status===429||i.status>=500;if(r>0||!c||(s=GF(i)??KF,s>WF))return!1}finally{clearTimeout(a)}await n(s)}},YF=async e=>{try{let n=(await P()).enrolledCert,r=await Be(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:BF(16).toString("hex"),events:e},s;try{let i=FF(r),c=new TextEncoder().encode(yo(a));s=UF(null,c,i).toString("base64url")}catch{return!1}return await VF(`${Gn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},ZF=async(e,t)=>{try{let r=(await P()).enrolledCert,o=await Be();if(!r||!o)return;await an(e,r,o,{timeoutMs:Gv,health:{events:t},telemetryOnly:!0})}catch{}},Vv=async(e,t)=>{if(e.length!==0)try{let n=await rt(),r=n&&await jv(n.origin,Xt(n),e,t);if(n&&await ZF(n.origin,e),r)return;await YF(e)}catch{}},Jh=async(e,t,n={readTarget:()=>rt("profile"),post:jv})=>{if(e.length===0)return!1;try{let r=await n.readTarget();return r?await n.post(r.origin,{"content-type":"application/json"},e,t):!1}catch{return!1}};var wo=["hook_registration","mcp_registration","hook_binary","beacon_target"];var Zv=128,Xv=300*1e3,XF=["repaired","repair_failed","flapping","pending"],JF=["settings_not_writable","apply_unconfirmed","apply_threw"],Jv=["rebroke_same_day","repeat_days"],zv=new Set(oe.map(e=>e.id)),go=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),qv=e=>yi(e,wo),bd=e=>{if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=Date.parse(`${e}T00:00:00.000Z`);return Number.isFinite(t)&&new Date(t).toISOString().slice(0,10)===e},vr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,mi=e=>{if(!(!Array.isArray(e)||!e.every(qv)))return jn(e)},zF=e=>{if(!go(e))return;let t=mi(e.checks);if(!(!vr(e.since)||!yi(e.reason,Jv)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},qF=e=>{if(!go(e))return;let t={};bd(e.day)&&(t.day=e.day),vr(e.attempts)&&(t.attempts=e.attempts);let n=mi(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=mi(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=mi(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=mi(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),bd(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),vr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),go(e.lastRepaired)){let i={};for(let c of wo){let l=e.lastRepaired[c];vr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=zF(e.flapping);return s&&(t.flapping=s),t},QF=e=>{if(!go(e)||!bd(e.day)||!vr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!zv.has(e.tool)||!qv(e.checkId)||!yi(e.status,XF)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!yi(e.errorClass,JF))return;t=e.errorClass}else if(e.status==="flapping"){if(!yi(e.errorClass,Jv))return;t=e.errorClass}else if(e.errorClass!==void 0)return;return{day:e.day,sequence:e.sequence,tool:e.tool,checkId:e.checkId,status:e.status,...t?{errorClass:t}:{},delivered:e.delivered,...vr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},Yv=e=>{if(!go(e))return{};let t={};if(go(e.adapters)){let n={};for(let r of zv){let o=qF(e.adapters[r]);o&&(n[r]=o)}Object.keys(n).length>0&&(t.adapters=n)}return Array.isArray(e.events)&&(t.events=e.events.map(QF).filter(n=>n!==void 0).slice(-Zv)),vr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),go(e.report)&&bd(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...vr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},eB=e=>new Date(e).toISOString().slice(0,10),tB=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,jn=e=>[...new Set(e)],kd=(e,t)=>{let n=e??{};if(n.day===t)return n;let r=n.day!==void 0&&n.dayHadNeed===!1;return{...n,day:t,attempts:0,attemptedChecks:[],confirmedChecks:[],brokenReportedChecks:[],dayHadNeed:!1,...r?{consecutiveRepairDays:0,lastConfirmedDay:void 0,flapping:void 0}:{}}},gi=(e,t,n)=>{let r=e.nextSequence??1,o=n.map(a=>({...a,day:t,sequence:r++,delivered:!1}));return{...e,events:[...(e.events??[]).filter(a=>a.day===t),...o].slice(-Zv),nextSequence:r}},nB=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),rB=async e=>await _e(async()=>e,void 0,ke)??null,oB=async(e,t,n)=>{let r=new Map(e.map(({adapter:o,checks:a})=>[o.id,Object.values(a).some(s=>s==="missing")]));await n.claimState(o=>{let a={...o.adapters??{}};for(let{adapter:s}of e){let i=kd(a[s.id],t);a[s.id]={...i,dayHadNeed:!!(i.dayHadNeed||r.get(s.id))}}return{next:{...o,adapters:a,events:(o.events??[]).filter(s=>s.day===t)},result:void 0}},void 0)},Qv=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:tB(e.lastConfirmedDay,n)?(e.consecutiveRepairDays??0)+1:1,a=o>=3,s={...e.lastRepaired??{}};for(let c of t)s[c]=r;let i=e.flapping;return{adapter:{...e,confirmedChecks:jn([...e.confirmedChecks??[],...t]),brokenReportedChecks:(e.brokenReportedChecks??[]).filter(c=>!t.includes(c)),lastConfirmedDay:n,consecutiveRepairDays:o,lastRepaired:s,...a?{flapping:{since:i?.since??r,reason:"repeat_days",checks:jn([...i?.checks??[],...t])}}:{}},slowFlap:a}},aB=async(e,t,n,r,o)=>{let a=new Map(e.map(s=>[s.adapter.id,s]));await o.claimState(s=>{let i=s,c={...s.adapters??{}};for(let[l,d]of Object.entries(c)){let u=kd(d,n),f=u.awaiting??[],p=a.get(l);if(f.length===0||t.has(l)||!p){c[l]=u;continue}let h=f.filter(y=>p.checks[y]==="owned"),m=f.filter(y=>{let b=p.checks[y];return b==="missing"||b==="foreign"}),w=f.filter(y=>{let b=p.checks[y];return b===void 0||b==="unreadable"}),g=Qv(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=gi(i,n,[...h.map(y=>({tool:l,checkId:y,status:"repaired"})),...m.map(y=>({tool:l,checkId:y,status:"repair_failed",errorClass:"apply_unconfirmed"})),...g.slowFlap?h.map(y=>({tool:l,checkId:y,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},sB=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=kd(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(g=>!d.includes(g)||u.includes(g)),p=f.filter(g=>u.includes(g)),h=l.attempts??0;if(h>=2||f.length===0&&!n){let g=p.filter(v=>!(l.brokenReportedChecks??[]).includes(v));if(g.length===0)return{result:void 0};let y=l.flapping;return c[e]={...l,brokenReportedChecks:jn([...l.brokenReportedChecks??[],...g]),flapping:{since:y?.since??a,reason:"rebroke_same_day",checks:jn([...y?.checks??[],...g])}},{next:gi({...i,adapters:c},o,g.map(v=>({tool:e,checkId:v,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let m=l.flapping;return c[e]={...l,attempts:h+1,attemptedChecks:jn([...d,...f]),confirmedChecks:u.filter(g=>!f.includes(g)),brokenReportedChecks:jn([...l.brokenReportedChecks??[],...p]),...p.length>0?{flapping:{since:m?.since??a,reason:"rebroke_same_day",checks:jn([...m?.checks??[],...p])}}:{}},{next:gi({...i,adapters:c},o,p.map(g=>({tool:e,checkId:g,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),iB=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=kd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:jn([...l.awaiting??[],...t])},{next:gi({...i,adapters:c},o,t.map(h=>({tool:e,checkId:h,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(h=>r[h]==="owned"):[],u=n.status==="configured"&&r?t.filter(h=>{let m=r[h];return m==="missing"||m==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=Qv(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:gi({...i,adapters:c},o,[...d.map(h=>({tool:e,checkId:h,status:"repaired"})),...u.map(h=>({tool:e,checkId:h,status:"repair_failed",errorClass:p})),...f.slowFlap?d.map(h=>({tool:e,checkId:h,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},cB=async(e,t,n,r)=>{let o=await r.claimState(i=>{let c=(i.events??[]).filter(u=>u.day===e&&!u.delivered&&(u.attemptedAt===void 0||u.attemptedAt>t||t-u.attemptedAt>=Xv));if(c.length===0)return{result:[]};let l=new Set(c.map(u=>`${u.day}:${u.sequence}`)),d=(i.events??[]).map(u=>l.has(`${u.day}:${u.sequence}`)?{...u,attemptedAt:t}:u);return{next:{...i,events:d},result:c.map(u=>({...u,attemptedAt:t}))}},[]);if(o.length===0||!await(r.report??Jh)(o.map(nB),n).catch(()=>!1))return;let s=new Set(o.map(i=>`${i.day}:${i.sequence}`));await r.claimState(i=>({next:{...i,events:(i.events??[]).map(c=>s.has(`${c.day}:${c.sequence}`)?{...c,delivered:!0}:c)},result:void 0}),void 0)},lB=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:f}of t){let p=r.adapters?.[u.id];for(let h of wo){let m=f[h];if(!m||m==="unreadable")continue;let w,g;p?.awaiting?.includes(h)&&c.has(u.id)?w="pending":m==="missing"&&p?.flapping?.checks.includes(h)?(w="flapping",g=p.flapping.reason):w=m==="owned"?"ok":m,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:h,status:w,...g?{errorClass:g}:{}})}}let l=Date.parse(e.enrolledCert?.payload.expiresAt??e.enrolledCertExpiry??"");e.enrolledCert&&Number.isFinite(l)&&(l<=o?(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"expired"})):l-o<=336*60*60*1e3&&(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"problems",errorClass:"cert_expiring"}))),e.refreshSchedulerEnabled&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??vc)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??dr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=Wv(await a.readHookLane?.().catch(()=>({})),o);return d&&(d.status!=="repaired"&&(i=!0),s.push({tool:"connect",checkId:"hook_lane",status:d.status,...d.errorClass?{errorClass:d.errorClass}:{}})),s.push({tool:"connect",checkId:"selfcheck_report",status:i?"problems":"ok"}),s},dB=async(e,t,n,r,o,a,s)=>{if(!await s.claimState(u=>u.report?.day===r&&u.report.delivered?{result:!1}:u.report?.day===r&&u.report.attemptedAt!==void 0&&u.report.attemptedAt<=o&&o-u.report.attemptedAt<Xv?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await lB(e,t,n,c,o,s);await(s.report??Jh)(l,a).catch(()=>!1)&&await s.claimState(u=>u.report?.day===r?{next:{...u,report:{day:r,delivered:!0}},result:void 0}:{result:void 0},void 0)},eS=async(e,t,n)=>{let r=n.now??Date.now,o=eB(r()),a=e.managedTools??[],s={...n,readState:async()=>Yv(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(Yv(l)),c)};try{let i=await(s.findIntegrations??Mh)(a);await oB(i,o,s);let c=await(s.listPending??cr)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await aB(i,l,o,r(),s);let d=await(s.resolveTarget??rB)(e),u=d?await(s.findDrifted??Ar)(a,d.toolOrigin):[],f=new Set(u.map(g=>g.id)),p=new Map(i.map(g=>[g.adapter.id,g]));for(let g of u)p.has(g.id)||p.set(g.id,{adapter:g,checks:{}});let h=!1,m=(s.runtimeDurable??ce)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?wo.filter(T=>y[T]==="missing"):[];if(b.length===0&&!f.has(g.id))continue;let v=y;if(g.integrationStatus)try{v=await g.integrationStatus()}catch{v=Object.fromEntries(wo.map(T=>[T,"unreadable"]))}let S=b.filter(T=>v[T]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),S.length===0&&!E)continue;let x=await sB(g.id,S,E,l.has(g.id),o,r(),s);if(!x)continue;let[A]=await(s.repair??gt)([g],d.target);if(!A)continue;h=!0;let I;A.status==="configured"&&g.integrationStatus&&(I=await g.integrationStatus().catch(()=>{})),await iB(g.id,x.checks,A,I,o,r(),s)}await cB(o,r(),t,s),i=await(s.findIntegrations??Mh)(a);let w=await(s.listPending??cr)().catch(()=>[]);return await dB(e,i,w,o,r(),t,s),h}catch{return!1}};var wB=14,bB=.35,kB=900*1e3,nS=360*60*1e3,AB=.2,CB=1800*1e3,rS=3600*1e3,vB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),SB=300*1e3,EB=30*1e3,xB=900*1e3,IB=(e=0)=>Math.min(xB,EB*2**Math.max(0,e)),oS=e=>{let t=e;for(let n=0;n<5&&t;n++){let r=t.code;if(typeof r=="string")return r;t=t.cause}},RB=720*60*1e3,aS=1440*60*1e3,OB=300*1e3,_B=.25,TB=.5,sS=3600*1e3,PB=720*60*60*1e3,LB=360*60*1e3,DB=1440*60*1e3,NB=4,Ad=e=>fB("sha256").update(e).digest("hex").slice(0,32),fS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Wt)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??P)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(Ad(e))},zh=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,NB)}),$B=()=>uS(hB(),".anyray"),Qh=()=>uS($B(),"refresh-state.json"),em=e=>process.env?.[e],hS=()=>em("ANYRAY_REFRESH_DISABLE")==="true",tm=()=>{let e=em("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:wB)*DB},bi=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},mS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),MB=10080*60*1e3,Cd=(e,t,n=Date.now())=>{let r=[],o=bi(e);o!==void 0&&r.push(o);let a=Date.parse(t??e.clientKeyExpiresAt??"");Number.isFinite(a)&&r.push(a-n);let s=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??"");return Number.isFinite(s)&&r.push(s-n),r.length===0?!1:Math.min(...r)<=MB},ki=e=>{let t=tm(),n=e?bi(e):void 0;if(!n)return t;let r=Math.max(kB,Math.round(n*bB));return Math.min(t,r)},FB=e=>{let t=em("ANYRAY_REFRESH_THROTTLE_MS"),n=t?Number.parseInt(t,10):NaN;return Number.isFinite(n)&&n>0?n:typeof e=="number"&&Number.isFinite(e)&&e>0?Math.min(nS,Math.max(CB,Math.round(e*AB))):nS},Wt=async()=>{try{let e=await mB(Qh(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},vd=async e=>{try{let t=Qh(),n=`${t}.${process.pid}.tmp`;await pS(n,JSON.stringify(e),{mode:384}),await fe(n,t),await yB(t,384).catch(()=>{})}catch{}},BB=3e4,UB=()=>`${Qh()}.lock`,iS=async e=>{try{return await pS(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},ut=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Wt,a=n.writeState??vd,s=UB(),i=!1;try{if(i=await iS(s),!i){if(await gB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<BB)return t;await tS(s).catch(()=>{}),i=await iS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await tS(s).catch(()=>{})}},wi=async(e,t={})=>{await ut(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Aa=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0),a=await(t.loadProfile??P)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?Ad(a.clientKey):void 0;await ut(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:zh(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},bo=async(e={})=>{let t=e.now??Date.now;await ut(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},HB=e=>{let t=e.enrolledCertLifetimeMs,n=Date.parse(e.enrolledCert?.payload.issuedAt??""),r=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??""),o=typeof t=="number"&&Number.isFinite(t)&&t>0?t:Number.isFinite(n)&&Number.isFinite(r)&&r>n?r-n:void 0;return o?Math.min(PB,Math.max(sS,Math.round(o*TB))):sS},qh=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,nm=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??te,a=n.loadProfile??P,s=n.loadDevKey??Be,i=n.renew??Dv,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(Lv(c.payload.user))return{outcome:"not-due",profile:e};let l=Date.parse(e.enrolledCertExpiry??c.payload.expiresAt??"");if(!Number.isFinite(l))return{outcome:"not-due",profile:e};if(l-r()>HB(e))return{outcome:"not-due",profile:e};if(!await ut(w=>r()-(w.lastCertRenewAt??0)<LB?{result:!1}:{next:{...w,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await qh(f,c.sig,t,s))return{outcome:"superseded",profile:f};let p=u.cert.payload.expiresAt,h=Date.parse(p)-r(),m={...f,enrolledCert:u.cert,enrolledCertExpiry:p,...Number.isFinite(h)&&h>0?{enrolledCertLifetimeMs:h}:{}};return await o(m),{outcome:"renewed",profile:m}},cS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*_B):aS,r=Math.min(aS,n);return Math.min(r,OB*2**Math.max(0,e-1))},WB=()=>{let{command:e,args:t}=pn(Qn);return{exe:e,args:t}},Sr=async(e={})=>{if(hS())return;let t=e.now??Date.now,n=e.readState??Wt,r=e.writeState??vd,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=WB();pB(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await ut(s=>t()-(s.lastSpawnAt??0)<FB(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},KB=fi,GB=async(e,t=ke,n=!1)=>{try{let r=e.managedTools??[];if(r.length===0)return!1;let o=await _e(async()=>e,void 0,t);if(!o)return!1;let a=await Ar(r,o.toolOrigin),s=n?gv(a):a;return s.length===0?!1:(await gt(s,o.target),!0)}catch{return!1}},jB=async(e,t,n,r,o,a)=>{try{let s=new Set(e.managedTools??[]),i=oe.filter(p=>s.has(p.id));if(i.length===0)return!1;let c=await r().catch(()=>{}),l=ge({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:c,user:e.name,team:e.team}),d=e.fallbackPort,u=nt(e)&&Number.isInteger(d)&&d>0&&d<=65535&&await o(d)!==null,f=await a(u?vn(l,d):l,u?`http://${ht}:${d}`:l.origin,i);return f.matched>0&&f.complete}catch{return!1}},VB=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Wt,a=t.writeState??vd;return eS(e,be,{now:r,deadWatcherObserved:n,readHookLane:()=>Sd({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>ut(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Sd=async(e={})=>{let n=await(e.readState??Wt)().catch(()=>({}));return An(n.hookLane)},yS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Sd(t);if(!jh(r,e,n()))return;await ut(o=>{let a=An(o.hookLane);return jh(a,e,n())?{next:{...o,hookLane:Mv(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},gS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Sd(t);if(!Vh(r,n()))return;await ut(o=>{let a=An(o.hookLane);return Vh(a,n())?{next:{...o,hookLane:Fv(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},YB=async(e={})=>{try{let t=e.now??Date.now;if((await Sd(e)).watchSince!==void 0)return;await ut(n=>{let r=An(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:Bv(r,t())},result:void 0}},void 0,e)}catch{}},lS=async(e,t={})=>{try{let n=t.now??Date.now;await ut(r=>{let o=An(r.hookLane),a=Uv(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},wS=async(e={})=>{try{if((await(e.readState??Wt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>ut(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??pg)())return await r()?"stamped":"skipped";let o=await(e.load??P)(),s=await(e.findTools??mo)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await _e(async()=>o,void 0,e.probe??ke);return!i||!await r()?"skipped":(await(e.repair??gt)(s,i.target),"repathed")}catch{return"skipped"}},bS=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Wt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>ut(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??P)(),i=await(e.findTools??mo)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await _e(async()=>a,void 0,e.probe??ke);return!c||!await o()?"skipped":(await(e.repair??gt)(i,c.target)).some(d=>d.status==="failed")?(await ut(d=>{if(d.appliedRevision!==t)return{result:void 0};let u={...d};return r===void 0?delete u.appliedRevision:u.appliedRevision=r,{next:u,result:void 0}},void 0,e).catch(()=>{}),"retry"):"swept"}catch{return"skipped"}},ZB=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await ud(e.gateway,e.clientKey),n=await pd(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},dS=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??ZB)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>GB(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},Qe=async(e={})=>{if(hS())return"disabled";let t=e.now??Date.now,n=e.loadProfile??P,r=e.saveProfile??te,o=e.loadDevKey??Be,a=e.readState??Wt,s=e.writeState??vd,i=e.remint??an,c=e.heartbeat??hd,l=e.detectSeat??Dt,d=e.rewriteTools??KB,u=e.rewriteHookLaneTools??Kh,f=e.probeHookLane??ka,p=e.classifyBeacon??uc,h=e.probe??ke,m=e.installProxy??Lt,w=e.pickProxyPort??yc,g=e.force===!0,y=!1,b=!1,v=!1,S=!1;e.hookLaneRepair===!0&&(g=!0,S=!0);let E=async A=>{if(!S){A==="repaired"&&await lS("none",{now:t,readState:a,writeState:s});return}let I=A;if(A==="repaired"){let T=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));I=T.verdict==="live"?"repaired":T.verdict==="dark"?"repair_failed":"unverified"}await lS(I,{now:t,readState:a,writeState:s})},x=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let A;try{A=await n()}catch{return!1}return(e.ambientSelfcheck??(T=>VB(T,{now:t,readState:a,writeState:s},v)))(A).catch(()=>!1)};try{e.runAmbientSelfcheck&&(v=await cr().then(_=>_.some(L=>!dr(L.watcherPid))).catch(()=>!1),await YB({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??Vw)();let A=await n();if(y=!0,!A.gateway||!A.enrolledCert)return"not-enrolled";let I=A.gateway,T=A.enrolledCertExpiry?Date.parse(A.enrolledCertExpiry):Date.parse(A.enrolledCert.payload.expiresAt);if(!Number.isFinite(T)||T<=t())return"cert-expired";let B=await o();if(!B)return"not-enrolled";let X=await nm(A,B,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});A=X.profile;let V=X.outcome==="renewed",W=A.enrolledCert;if(!W)return"not-enrolled";let z=Date.parse(A.clientKeyExpiresAt??""),me=Number.isFinite(z)?z-t():0,De=await a(),ee=!A.clientKey||me<=ki(A),Fe=A.credentialProtocol!=="stable-heartbeat-v1"&&t()-(De.lastSuccessAt??0)>=RB;if(!g&&Hv(An(De.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,S=!0),A.credentialProtocol==="stable-heartbeat-v1"&&A.clientKey&&(g||ee)){let _=await ut(L=>{let H=t()-(L.lastAttemptAt??0);return H<rS?{result:"throttled"}:L.failureCount&&H<cS(L.failureCount,L.keyTtlMs)?{result:"backoff"}:{next:{...L,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(_!=="ok")return _;try{let L=await c(I,A.clientKey,W,B),H=await n().catch(()=>A);return H.clientKey!==A.clientKey||H.enrolledCert?.sig!==W.sig?"failed":(await r({...H,clientKeyExpiresAt:L.expiresAt}),await wi(({lastError:ye,...se})=>({...se,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:bi(A)??se.keyTtlMs}),{now:t,readState:a,writeState:s}),S&&await E(await jB(A,I,A.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(L){let H=L;if(L instanceof Cr&&L.status===404)try{let se=await i(I,W,B),we=await l().catch(()=>{}),We=ge({origin:I,clientKey:se.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:we,user:A.name,team:A.team}),ue=A.fallbackPort,ie=Number.isInteger(ue)&&ue>0&&ue<=65535?ue:await w();if(!(await m({port:ie,remoteOrigin:I})).ok||await h(ie)===null)throw new Error("key-refresh proxy recovery failed");let Ne=await n().catch(()=>A);if(!await qh(Ne,W.sig,B,o))throw new Error("enrollment changed during proxy recovery");if(await r({...Ne,clientKey:se.key,clientKeyExpiresAt:se.expiresAt??Ne.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:ie}),await d(vn(We,ie),We.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let ft=se.expiresAt?Date.parse(se.expiresAt):NaN,Ve=bi(A)??(Number.isFinite(ft)&&ft-t()>0?ft-t():void 0);return await wi(({lastError:Pr,...cn})=>({...cn,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ve??cn.keyTtlMs,ownKeys:zh(cn.ownKeys,W.sig,Ad(se.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(se){H=se}let ye=oS(H);return await wi(se=>({...se,lastAttemptAt:t(),failureCount:(se.failureCount??0)+1,lastError:{name:H instanceof Error?H.name:"Error",...ye!==void 0?{code:ye}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),H instanceof Cr?"cert-rejected":"failed"}}if(!g&&A.clientKey&&!ee&&!Fe){let _=await dS(A,e,n,h),L=await x();return _||L?"repaired":V?"cert-renewed":"not-due"}let xe=await ut(_=>{let L=t()-(_.lastAttemptAt??0);if(g)return L<IB(_.failureCount)?{result:"throttled"}:{next:{..._,lastAttemptAt:t()},result:"ok"};let H=_.lastError?.code!==void 0&&vB.has(_.lastError.code)?SB:rS;return L<H?{result:"throttled"}:_.failureCount&&L<cS(_.failureCount,_.keyTtlMs)?{result:"backoff"}:{next:{..._,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(xe!=="ok")return xe;try{let _=await i(I,W,B),L=await l().catch(()=>{}),H=ge({origin:I,clientKey:_.key,subscription:A.authMode==="subscription",placeholder:A.authMode==="placeholder",byoUpstream:A.byoUpstream,seat:L,user:A.name,team:A.team}),ye=H,se=H.origin;if(nt(A)){if(!Number.isInteger(A.fallbackPort)||A.fallbackPort<1||A.fallbackPort>65535)throw new Error("key-refresh proxy profile has no valid port");await h(A.fallbackPort)!==null&&(ye=vn(H,A.fallbackPort),se=`http://${ht}:${A.fallbackPort}`)}let we=await d(ye,se);if(A.directMigration==="pending"&&ye.viaLocalProxy===!0){let ft=await d(ye,H.origin);we=we!==!1&&ft!==!1}if(we===!1)throw new Error("one or more configured tools rejected the refreshed key");let We=await n().catch(()=>A),ue=null,ie;We.enrolledCert&&await qh(We,W.sig,B,o)&&(ie=Ad(_.key),ue={...We,clientKey:_.key,clientKeyExpiresAt:_.expiresAt??We.clientKeyExpiresAt},await r(ue));let Y=_.expiresAt?Date.parse(_.expiresAt):NaN,Ne=bi(A)??(Number.isFinite(Y)&&Y-t()>0?Y-t():void 0);return await wi(({lastError:ft,...Ve})=>({...Ve,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ne??Ve.keyTtlMs,...ie?{ownKeys:zh(Ve.ownKeys,W.sig,ie)}:{}}),{now:t,readState:a,writeState:s}),ue&&await dS(ue,e,n,h),await E(ue?"repaired":"repair_failed"),await x(),"refreshed"}catch(_){let L=oS(_);return await wi(H=>({...H,lastAttemptAt:t(),failureCount:(H.failureCount??0)+1,lastError:{name:_ instanceof Error?_.name:"Error",...L!==void 0?{code:L}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),_ instanceof It?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await x()}catch{}}};import{readFile as tU}from"node:fs/promises";import{isAbsolute as nU,posix as SS,win32 as am}from"node:path";var rm=1e4,XB=900*1e3,AS="tnt_",JB=/^\/sso\/([^/]+)\/?$/,zB=/^\/i\/([^/]+)\/?$/,qB=e=>{let t=e.match(JB);if(t)return t[1];let n=e.match(zB);return n?.[1].startsWith(AS)?n[1]:void 0},Rt=e=>{let t=e.trim();if(!t)return;let n;try{n=new URL(t)}catch{n=void 0}if(n){if(n.protocol!=="http:"&&n.protocol!=="https:")return;let r=qB(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(AS))return{cpOrigin:Gn(),tenantId:t}},ko=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Kt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},om=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await r(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:o.signal}),i={};try{i=await s.json()}catch{}return{status:s.status,json:i}}finally{clearTimeout(a)}},QB=e=>new Promise(t=>setTimeout(t,e)),Ed=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??fd)(),a;try{a=await om(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},rm,n)}catch(h){throw new ko("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${wt(h)}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new ko(h?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${m}). Ask your admin to confirm SSO is configured.`,a.status)}let s=a.json;if(!s.device_code||!s.user_code||!s.verification_uri_complete)throw new ko("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??XB,l=typeof s.expires_in=="number"&&s.expires_in>0?s.expires_in*1e3:c,d=typeof s.verification_uri=="string"?s.verification_uri:void 0,u=e.gatewayUrl??(typeof s.gateway_url=="string"?s.gateway_url:void 0),f={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:s.device_code,userCode:s.user_code,verificationUri:d,verificationUriComplete:s.verification_uri_complete,intervalMs:Math.max(1,s.interval||5)*1e3,grantExpiresAt:i+Math.min(c,l),startedAt:i,privateKeyPem:o,publicKeyPem:r,gatewayUrl:u},p=e.log??(()=>{});return p("To finish, sign in with your organization at:"),p(` ${f.verificationUriComplete}`),p(`Confirm this code matches your browser: ${f.userCode}`),eU(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},eU=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},xd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??QB,o=t.fetch??fetch,a=t.pollIntervalMs??e.intervalMs;for(;n()<e.grantExpiresAt&&(await r(Math.min(a,e.grantExpiresAt-n())),!(n()>=e.grantExpiresAt));){let s;try{s=await om(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},rm,o)}catch(c){throw new Kt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${wt(c)}`)}if(s.status===200&&s.json.cert)return{cert:s.json.cert,privateKeyPem:e.privateKeyPem,gatewayUrl:t.gatewayUrl??(typeof s.json.gatewayUrl=="string"?s.json.gatewayUrl:e.gatewayUrl),deploymentId:typeof s.json.deploymentId=="string"?s.json.deploymentId:""};let i=typeof s.json.error=="string"?s.json.error:"";if(i!=="authorization_pending"){if(i==="slow_down"){a+=5e3;continue}throw i==="expired_token"?new Kt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Kt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Kt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var kS="sdc_",CS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(kS))return{cpOrigin:Gn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!Wh(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(kS)))return{cpOrigin:n.origin,claim:r}},vS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??fd)(),o;try{o=await om(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},rm,t)}catch(s){throw new Kt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${wt(s)}`)}if(o.status===200&&o.json.cert)return{cert:o.json.cert,privateKeyPem:r,gatewayUrl:e.gatewayUrl??(typeof o.json.gatewayUrl=="string"?o.json.gatewayUrl:void 0),deploymentId:typeof o.json.deploymentId=="string"?o.json.deploymentId:"",...typeof o.json.ssoLink=="string"&&o.json.ssoLink?{ssoLink:o.json.ssoLink}:{}};let a=typeof o.json.error=="string"?o.json.error:"";throw a==="expired_token"?new Kt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Kt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Kt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};var Ai=(e=process.platform,t=process.env)=>e==="darwin"?SS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?am.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):SS.join("/etc","anyray","bootstrap.json"),rU=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ES=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(nU(e)||am.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),oU=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&!t.username&&!t.password}catch{return!1}},Gt=async(e=Ai())=>{try{let t=await tU(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!rU(n)||n.v!==1||typeof n.sso!="string")return;let r=Rt(n.sso);if(!r)return;let o=oU(n.gateway)?n.gateway:void 0,a=ES(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},xS=(e,t,n)=>{let r=Rt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!ES(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&am.isAbsolute(n)&&/^[A-Za-z]:\\/.test(n)&&!/^[A-Za-z]:\\Program Files( \(x86\))?\\/i.test(n))throw new Error("--bin on Windows must live under Program Files (admin-only writable)");return`${JSON.stringify({v:1,sso:`${r.cpOrigin}/sso/${r.tenantId}`,...t?{gateway:t}:{},...n?{bin:n}:{}},null,2)}
|
|
296
|
+
`};import{execFile as OU}from"node:child_process";import{chmod as aU,readFile as sU,rm as IS,writeFile as iU}from"node:fs/promises";import{join as cU}from"node:path";var sm=()=>cU(q(),"sso-gate.json"),lU=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=a=>t[a]===void 0||typeof t[a]=="number"&&Number.isFinite(t[a]),r=a=>t[a]===void 0||typeof t[a]=="string",o=new Set(["cp-unreachable","sso-unavailable","denied","expired","gateway-unreachable"]);return t.v===1&&(t.status===void 0||t.status==="pending")&&r("userCode")&&r("verificationUriComplete")&&n("grantExpiresAt")&&n("startedAt")&&n("pollerPid")&&n("lastAttemptAt")&&n("failureCount")&&(t.lastFailure===void 0||typeof t.lastFailure=="string"&&o.has(t.lastFailure))},Er=async()=>{try{let e=JSON.parse(await sU(sm(),"utf-8"));return lU(e)?e:null}catch{return null}},dU=0,Id=async e=>{await kt();let t=sm(),n=`${t}.${process.pid}.${dU++}.tmp`;try{await iU(n,`${JSON.stringify(e)}
|
|
297
|
+
`,{mode:384}),await aU(n,384),await fe(n,t)}catch(r){throw await IS(n,{force:!0}).catch(()=>{}),r}},RS=async()=>{await IS(sm(),{force:!0}).catch(()=>{})},OS=e=>{if(!e||!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}};import{spawn as fU}from"node:child_process";import{homedir as hU}from"node:os";import{join as mU}from"node:path";import{spawn as uU}from"node:child_process";import{platform as pU}from"node:os";var Ca=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=pU(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=uU(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var yU=3e4,gU=5*6e4,wU=30*6e4,bU=e=>{let t={};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--sso":t.sso=o();break;case"--gateway":t.gateway=o();break;case"--team":t.team=o();break;case"--session-start":t.sessionStart=!0;break;default:throw new Error("invalid SSO gate arguments")}}if(!t.sso)throw new Error("missing --sso");return t},kU=()=>mU(hU(),".claude","settings.json"),AU=async e=>{try{let n=(await M(kU())).env;if(!n)return!1;let r=un(e).env;for(let[o,a]of Object.entries(r))if(n[o]!==a)return!1;return n.ANTHROPIC_AUTH_TOKEN===void 0}catch{return!1}},CU=async e=>{await nr.apply(e,{dryRun:!1})},vU=()=>{let{command:e,args:t}=pn("__anyray-sso-poll");return{exe:e,args:t}},SU=()=>{let{exe:e,args:t}=vU(),n=fU(e,t,{detached:!0,stdio:["pipe","ignore","ignore"]});return n.on("error",()=>{}),n.unref(),n.stdin?.on("error",()=>{}),{pid:n.pid,handoff:r=>{n.stdin?.end(JSON.stringify(r))}}},EU=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},_S=(e,t,n,r)=>ge({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),va=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},TS=e=>`Anyray: one-time sign-in required to use AI tools on this device.
|
|
298
298
|
1. Open ${e.verificationUriComplete}
|
|
299
299
|
2. Confirm code ${e.userCode}
|
|
300
300
|
Your prompt was not sent \u2014 complete sign-in, then resubmit it.
|
|
301
|
-
`,
|
|
301
|
+
`,im=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
|
|
302
302
|
`:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
|
|
303
303
|
`:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
|
|
304
|
-
`,
|
|
305
|
-
`))}let z;await m();try{z=await d(A,b.enrolledCert,S,{timeoutMs:1e4})}catch(
|
|
306
|
-
`,{mode:384}),await
|
|
307
|
-
${t.stderr??""}`}},
|
|
308
|
-
${j(e)}`),
|
|
304
|
+
`,xU=e=>Math.min(gU,yU*2**Math.max(0,e-1)),IU=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?wU:xU(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Vn=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??P,o=t.saveProfile??te,a=t.loadDevKey??Be,s=t.readGateState??Er,i=t.writeGateState??Id,c=t.isProcessAlive??OS,l=t.startGrant??Ed,d=t.verify??an,u=t.routingIntact??AU,f=t.applyClaudeCode??CU,p=t.maybeSpawnRefresh??Sr,h=t.recordMint??Aa,m=t.reserveMint??bo,w=t.spawnPoller??SU,g=t.openBrowser??Ca;try{let y=Rt(e.sso);if(!y)return{exitCode:0};let b=await r(),v=await s(),S=b.enrolledCert?await a():void 0,E=EU(b),x=!!(b.enrolledCert&&S)&&Number.isFinite(E)&&E>n(),A=e.gateway??b.gateway;if(x&&b.enrolledCert&&S&&A){let V=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(V)&&V>n()&&b.clientKey){let me=_S(A,b,e.team,b.clientKey);return await u(me)?(V-n()<=tm()&&await p(),{exitCode:0}):(await f(me),va(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
|
|
305
|
+
`))}let z;await m();try{z=await d(A,b.enrolledCert,S,{timeoutMs:1e4})}catch(me){if(!(me instanceof It))return va(e,im("gateway-unreachable",y.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(z){let me={...b,gateway:A,name:z.user,team:e.team??z.team??b.team,clientKey:z.key,clientKeyExpiresAt:z.expiresAt,authMode:"subscription"};return await o(me),await h({expiresAt:z.expiresAt}),await f(_S(A,me,e.team,z.key)),{exitCode:0}}}if(v?.status==="pending"&&(v.userCode&&v.verificationUriComplete)&&(v.grantExpiresAt??0)>n()&&c(v.pollerPid)){if(e.sessionStart&&v.verificationUriComplete)try{g(v.verificationUriComplete)}catch{}return va(e,TS(v))}if(v){let V=IU(v,n());if(V)return va(e,im(V,y.cpOrigin))}let I;try{I=await l({cpOrigin:y.cpOrigin,tenantId:y.tenantId,gatewayUrl:e.gateway,now:n})}catch(V){let W=V instanceof ko?V.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:v?.lastFailure===W?(v.failureCount??0)+1:1,lastFailure:W}),va(e,im(W,y.cpOrigin))}let T={v:1,status:"pending",userCode:I.userCode,verificationUriComplete:I.verificationUriComplete,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,lastAttemptAt:n(),failureCount:0};await i(T);let B=w(),X={...T,pollerPid:B.pid};if(await i(X),B.handoff({deviceCode:I.deviceCode,privateKeyPem:I.privateKeyPem,publicKeyPem:I.publicKeyPem,cpOrigin:I.cpOrigin,tenantId:I.tenantId,intervalMs:I.intervalMs,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,gatewayUrl:I.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{g(I.verificationUriComplete)}catch{}return va(e,TS(X))}catch{return{exitCode:0}}},RU=async()=>{try{for await(let e of process.stdin);}catch{}},PS=async e=>{await RU();try{let t=await Vn(bU(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var _U=6e4,TU=10*6e4,Yn=(e,t)=>{let n=e[t];return typeof n=="string"?n:Array.isArray(n)?n[0]:void 0},PU=e=>{if(Yn(e,"x-anyray-api-key")?.trim())return!0;let t=Yn(e,"authorization")?.trim()??"";return/^bearer\s+\S+/i.test(t)?!0:(Yn(e,"x-api-key")?.trim()??"").startsWith("ark_")},DS=e=>{if(Yn(e,"x-anyray-api-key")?.trim())return!0;let t=Yn(e,"authorization")?.trim()??"";return/^bearer\s+ark_\S+/i.test(t)?!0:(Yn(e,"x-api-key")?.trim()??"").startsWith("ark_")},NS=e=>{let t=Yn(e,"x-anyray-api-key")?.trim();if(t?.startsWith("ark_"))return{key:t,slot:"x-anyray-api-key"};let r=(Yn(e,"authorization")?.trim()??"").match(/^bearer\s+(ark_\S+)/i);if(r)return{key:r[1],slot:"authorization"};let o=Yn(e,"x-api-key")?.trim()??"";return o.startsWith("ark_")?{key:o,slot:"x-api-key"}:void 0},LU=e=>e.split("?")[0].includes("/v1/"),LS=e=>e.replace(/[^\x20-\x7e]/g,"").replace(/["'`\\$]/g,"").slice(0,300),DU=(e,t,n=process.platform,r=OU)=>{let o=LS(e),a=LS(t);try{n==="darwin"?r("/usr/bin/osascript",["-e",`display notification "${a}" with title "${o}"`],{timeout:5e3},()=>{}):n==="linux"&&r("notify-send",["--app-name=Anyray",o,a],{timeout:5e3},()=>{})}catch{}},$S=(e={})=>{let t=e.readBootstrap??Gt,n=e.ssoGate??Vn,r=e.readState??Er,o=e.notify??DU,a=e.now??Date.now,s=0,i,c=0,l=!1,d=async()=>{let u=await t();if(!u||(await n({sso:u.sso,gateway:u.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}})).exitCode!==2)return;let p=await r();p?.status!=="pending"||!p.userCode||!p.verificationUriComplete||!(p.userCode!==i)&&a()-c<TU||(i=p.userCode,c=a(),o("Anyray \u2014 sign in to use AI tools",`Open ${p.verificationUriComplete} and enter code ${p.userCode}. Requests keep failing until sign-in completes.`))};return{onGatewayUnauthorized(u,f){try{if(!LU(u)||PU(f)||l||a()-s<_U)return;s=a(),l=!0,d().catch(()=>{}).finally(()=>{l=!1})}catch{}}}};import{watch as NU}from"node:fs";import{basename as $U,dirname as MU}from"node:path";var FU=2e3,BU=6e4,Sa=e=>e instanceof Error?e.name:"UnknownError",UU=(e,t,n)=>{let r=NU(e,{persistent:!1},(o,a)=>{t(a==null?null:a.toString())});return r.on("error",n),r},HU=async(e,t)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await _e(async()=>e,void 0,t);if(!r)return!1;let o=await Ar(n,r.toolOrigin);return o.length===0?!1:(await gt(o,r.target),!0)}catch{return!1}},MS=(e={})=>{let t=e.loadProfile??P,n=e.adapters??oe,r=e.probe??ke,o=e.repairDrift??(A=>HU(A,r)),a=e.resolveProfileFile??Io,s=e.watchDir??UU,i=e.debounceMs??FU,c=e.repairFloorMs??BU,l=e.now??Date.now,d=e.logError??(A=>console.error(`anyray refresh proxy: drift watcher ${A}`)),u=!1,f=0,p,h=Promise.resolve(),m=new Map,w=A=>{let I=m.get(A);if(I){m.delete(A);try{I.handle.close()}catch{}}},g=()=>{if(u)return;p!==void 0&&clearTimeout(p);let A=setTimeout(()=>{p=void 0,h=h.then(E).catch(()=>{})},i);A.unref?.(),p=A},y=A=>I=>{if(!u)try{let T=m.get(A);if(!T||I!==null&&!T.files.has(I))return;g()}catch(T){d(Sa(T))}},b=A=>I=>{d(Sa(I)),w(A),g()},v=async A=>{let I=[],T=new Set(A.managedTools??[]);for(let V of n)if(!(!T.has(V.id)||!V.watchPaths))try{I.push(...await V.watchPaths())}catch(W){d(Sa(W))}let B=await a().catch(()=>{});B&&I.push(B);let X=new Map;for(let V of I){let W=MU(V),z=X.get(W)??new Set;z.add($U(V)),X.set(W,z)}return X},S=async A=>{let I=await v(A);if(!u){for(let T of[...m.keys()])I.has(T)||w(T);for(let[T,B]of I){let X=m.get(T);if(X){X.files=B;continue}try{m.set(T,{handle:s(T,y(T),b(T)),files:B})}catch(V){d(Sa(V))}}}},E=async()=>{if(!u)try{let A=await t().catch(()=>({}));if(await S(A),u||l()-f<c)return;f=l(),await o(A).catch(()=>!1)}catch(A){d(Sa(A))}};return{ready:t().then(A=>S(A)).catch(A=>d(Sa(A))),stop:()=>{u=!0,p!==void 0&&(clearTimeout(p),p=void 0);for(let A of[...m.keys()])w(A)}}};import{randomBytes as WU}from"node:crypto";import{chmod as KU,readFile as GU,rm as US,writeFile as jU}from"node:fs/promises";import{join as VU}from"node:path";var YU=/^[A-Za-z0-9_-]{43}$/,ZU=3600*1e3,FS=3900,XU=1e4,cm=()=>VU(q(),"device-token.json"),JU=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&YU.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},HS=async()=>{try{let e=JSON.parse(await GU(cm(),"utf-8"));return JU(e)?e:null}catch{return null}},zU=0,qU=async e=>{await kt();let t=cm(),n=`${t}.${process.pid}.${zU++}.tmp`;try{await jU(n,`${JSON.stringify(e)}
|
|
306
|
+
`,{mode:384}),await KU(n,384),await fe(n,t)}catch(r){throw await US(n,{force:!0}).catch(()=>{}),r}},Rd=async()=>{await US(cm(),{force:!0}).catch(()=>{})},QU=()=>WU(32).toString("base64url"),e1=e=>e instanceof Error?e.name:"UnknownError",t1=(e,t)=>{let n=setInterval(e,t);return n.unref(),{stop:()=>clearInterval(n)}},BS=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??P)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=QU(),i=new AbortController,c=setTimeout(()=>i.abort(),XU),l;try{l=await n(`${o}/connect/device-token`,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":a},body:JSON.stringify({token:s,ttlSeconds:FS}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await qU({v:1,token:s,expiresAt:t()+FS*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${e1(r)}`),!1}},WS=(e={})=>{BS(e);let n=(e.scheduleRotation??t1)(()=>{BS(e)},ZU);return{stop:()=>n.stop()}};var r1=1800*1e3,KS=50,o1=15e3,a1=1e3,YS=as*1e3-1e4,GS=15*6e4,s1=75e3,i1=8e4,c1=async(e,t,n={})=>{let r=n.budgetMs??as*1e3,o=n.delayMs??250,a=Date.now()+r;for(;;)try{await new Promise((s,i)=>{let c=l=>i(l);e.once("error",c),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",c),s()})});return}catch(s){if(s.code!=="EADDRINUSE"||Date.now()+o>a)throw s;await dm(o)}},Od=e=>{let t=e instanceof Error?e.name:"unknown",n=e?.code;return typeof n=="string"?`${t} ${n}`:t},l1=(e,t={})=>{let n=t.exit??(f=>process.exit(f)),r=t.exitCode??0,o=t.hardCapMs??YS,a=t.inFlight,s=Date.now()+(t.ceilingMs??o),i=setInterval(()=>e.closeIdleConnections(),500);i.unref();let c,l=!1,d=()=>{l||(l=!0,clearInterval(i),clearTimeout(c),n(r))},u=f=>{c=setTimeout(()=>{let p=s-Date.now();if(a&&a()>0&&p>0){u(Math.min(o,p));return}d()},f),c.unref()};u(o),e.close(d),e.closeIdleConnections()},ZS=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),d1=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]),u1=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),p1=45*1e3,f1=600*1e3,h1=new Set(["host","connection","keep-alive","proxy-connection","content-length","transfer-encoding","upgrade"]),m1=new Set(["content-encoding","content-length","transfer-encoding","connection","keep-alive"]),y1=new Set(["missing_key","key_expired"]),g1=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object")return!1;let{status:n,code:r}=t;return n==="failure"&&typeof r=="string"&&y1.has(r)}catch{return!1}},w1=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(h1.has(n.toLowerCase())||(t[n.toLowerCase()]=Array.isArray(r)?r.join(", "):r));return t},b1=e=>new Promise((t,n)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>t(Buffer.concat(r))),e.on("error",o=>n(o))}),k1=(e,t)=>e?ZS.has(e)?!0:d1.has(e)&&u1.has(t.toUpperCase()):!1,A1=new Set(["127.0.0.1","localhost","[::1]","::1"]),C1=e=>{if(e[Gu]===void 0||e.origin!==void 0)return!1;let t=(e.host??"").replace(/:\d+$/,"");return A1.has(t)},v1=(e,t)=>{let n=(t??"").split("?")[0];return e==="GET"&&n==="/__anyray/health"||e==="POST"&&n==="/__anyray/shutdown"},S1=async(e,t,n,r)=>{try{return{res:await fetch(e,{method:t,headers:n,body:r.length?r:void 0,duplex:"half"})}}catch(o){return{failure:{kind:"transport-error",code:o?.cause?.code}}}},dm=e=>new Promise(t=>setTimeout(t,e)),jS=async(e,t,n,r,o,a=o1)=>{let s=Date.now()+a,i=KS,c=!1;for(;;){let l=await S1(e,t,n,r);if("res"in l||!o())return l;let d=l.failure.code;if(d!==void 0&&ZS.has(d)){if(Date.now()+i>s)return l;await dm(i),i=Math.min(i*2,a1)}else if(!c&&k1(d,t))c=!0,await dm(KS);else return l;if(!o())return l}},lm=async(e,t)=>{let n={};if(t.headers.forEach((s,i)=>{m1.has(i.toLowerCase())||(n[i]=s)}),e.writeHead(t.status,n),!t.body){e.end();return}let r=t.body.getReader(),o=()=>{r.cancel().catch(()=>{})};e.once("close",o);let a=!1;try{for(;;){let{done:s,value:i}=await r.read();if(s)break;if(i){if(e.destroyed){r.cancel().catch(()=>{});continue}e.write(i)||await new Promise(c=>{if(e.destroyed||e.writableEnded){c();return}let l=()=>{e.off("close",d),c()},d=()=>{e.off("drain",l),c()};e.once("drain",l),e.once("close",d)})}}}catch{a=!0}finally{e.off("close",o)}a&&!e.writableEnded?e.destroy():e.end()},VS=(e,t,n)=>{e.headersSent||e.destroyed||(e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify({error:{type:"anyray_proxy",message:n}})))},E1=e=>{let t=e.remoteOrigin.replace(/\/+$/,""),n=0,r=async(a,s)=>{let i=a.url??"/",c=a.method??"GET";if(c==="GET"&&i==="/__anyray/health"){s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({status:"ok",mode:"refresh-only",port:e.port,remoteOrigin:t,version:be,inFlight:n}));return}if(c==="POST"&&(i==="/__anyray/shutdown"||i.startsWith("/__anyray/shutdown?"))){if(!C1(a.headers)){s.writeHead(403,{"content-type":"application/json"}),s.end(JSON.stringify({error:"forbidden"}));return}let b=i.includes("?")?i.slice(i.indexOf("?")+1):"",v=new URLSearchParams(b).get("drain")==="idle"?"idle":void 0;s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({status:"stopping"})),e.onShutdown?.({drain:v});return}let l=await b1(a),d=w1(a.headers),u=NS(a.headers),f=b=>{if(!u){d["x-anyray-api-key"]=b;return}d[u.slot]=u.slot==="authorization"?`Bearer ${b}`:b},p,h=!1;if(e.resolveClientKey&&!DS(a.headers)){h=!0;try{p=await e.resolveClientKey(),p&&f(p)}catch{}}let m=await jS(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("failure"in m){VS(s,502,`gateway unreachable (${m.failure.code??"transport-error"})`);return}let w=()=>{if(!(m.res.status!==401||!e.onGatewayUnauthorized))try{e.onGatewayUnauthorized(i,a.headers)}catch{}},g=h;!g&&m.res.status===401&&u&&e.isOwnClientKey&&(g=await e.isOwnClientKey(u.key).catch(()=>!1));let y=g&&(h?!!e.recoverInjectedKey:!!e.resolveClientKey);if(m.res.status===401&&y){let b=await m.res.text().catch(()=>"");if(g1(b)){let v=h?await e.recoverInjectedKey().catch(()=>{}):await e.resolveClientKey().catch(()=>{}),S=p??u?.key;if(v!==void 0&&v!==S){f(v);let E=await jS(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("res"in E){E.res.status===401&&w(),await lm(s,E.res);return}}}w(),await lm(s,new Response(b,{status:m.res.status,headers:m.res.headers}));return}w(),await lm(s,m.res)},o=n1.createServer((a,s)=>{s.on("error",()=>{}),v1(a.method,a.url)||(n++,s.once("close",()=>{n--})),r(a,s).catch(i=>{console.error(`anyray refresh proxy: request error ${Od(i)}`),s.headersSent?s.end():VS(s,502,"anyray proxy internal error")})});return o.keepAliveTimeout=s1,o.headersTimeout=i1,o.on("error",a=>{a.code!=="EADDRINUSE"&&console.error(`anyray refresh proxy: server error ${Od(a)}`)}),{server:o,inFlight:()=>n}},XS=5e3,x1=2e3,I1=(e={})=>{let t=e.now??Date.now,n=e.loadProfile??P,r=e.refresh??(()=>Qe()),o=e.remintBudgetMs??XS,a,s=-1/0,i=3e4;return Object.assign(async()=>{let l=a===void 0?x1:i;if(t()-s<l)return a;let d=await n().catch(()=>({})),u=Date.parse(d.clientKeyExpiresAt??"");if(Number.isFinite(u)){let f=u-t();if(f<=0){await Promise.race([Promise.resolve().then(r).catch(()=>{}),new Promise(h=>setTimeout(h,o).unref?.())]),d=await n().catch(()=>d);let p=Date.parse(d.clientKeyExpiresAt??"");if(Number.isFinite(p)&&p-t()<=0)return a=void 0,s=t(),a}else f<=ki(d)&&Promise.resolve().then(r).catch(()=>{})}return a=d.clientKey,s=t(),a},{invalidate:()=>{a=void 0,s=-1/0}})},JS=async()=>{let e=await P(),t=e.fallbackPort,n=e.gateway?.replace(/\/+$/,"");if(!t||!n){let p=await Gt().catch(()=>{});p?.gateway&&(n??=p.gateway.replace(/\/+$/,""),t??=Ae)}if(!t||!n)return console.error("anyray refresh proxy: not configured (missing loopbackPort/gateway in ~/.anyray, and no fleet bootstrap with a gateway). Run `anyray-connect` first."),1;let r=$S(),o=I1(),a=E1({port:t,remoteOrigin:n,onGatewayUnauthorized:(p,h)=>r.onGatewayUnauthorized(p,h),resolveClientKey:o,recoverInjectedKey:async()=>(o.invalidate(),await Promise.race([Qe({force:!0}).catch(()=>{}),new Promise(p=>setTimeout(p,XS).unref?.())]),o()),isOwnClientKey:p=>fS(p),onShutdown:p=>f(0,{drain:p.drain})});Qe().catch(()=>{});let s=setInterval(()=>{Qe().catch(()=>{})},r1);s.unref();let i=MS(),c=WS(),l=Date.now();a.server.on("request",()=>{l=Date.now()});let d=setInterval(()=>{Date.now()-l>f1||fetch(`${n}/`,{method:"HEAD"}).catch(()=>{})},p1);d.unref();let u=!1,f=(p=0,h={})=>{if(u)return;u=!0,clearInterval(s),clearInterval(d),i.stop(),c.stop();let m=h.drain==="idle"?GS:YS;qg(Date.now()+m),l1(a.server,{exitCode:p,inFlight:a.inFlight,ceilingMs:h.drain==="idle"?GS:void 0,exit:w=>{Zu(),process.exit(w)}})};return process.once("SIGTERM",()=>f()),process.once("SIGINT",()=>f()),process.on("uncaughtException",p=>{console.error(`anyray refresh proxy: uncaught exception ${Od(p)}`),f(1)}),process.on("unhandledRejection",p=>{console.error(`anyray refresh proxy: unhandled rejection ${p instanceof Error?Od(p):typeof p}`),f(1)}),Zu(),await Yg(ns()).catch(()=>{}),await c1(a.server,t),console.error(`anyray refresh proxy listening on 127.0.0.1:${t} \u2192 ${n}`),await new Promise(()=>{}),0};import{platform as R1}from"node:os";import{stat as O1}from"node:fs/promises";import{spawnSync as _1}from"node:child_process";var zS="/Applications/Anyray Connect Tray.app",T1=new Set(["V53XMA78UF"]),P1="ai.anyray.connect-tray",L1=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,D1=e=>{let t=_1("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
307
|
+
${t.stderr??""}`}},N1=async e=>{try{return(await O1(e)).isDirectory()}catch{return!1}},$1=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},um=async(e,t={})=>{if((t.os??R1())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??N1)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??D1;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?$1(a.output):void 0;return s?T1.has(s)?L1(a.output)!==P1?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},Ao=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await um(n,t)).ok?"healthy":"gone"},pm=async(e={})=>{try{let t=e.load??P,n=await t(),r=await Ao(n,e);if(r!=="gone")return r;let o=e.installScheduler??sr,a=e.installDaemon??Lt;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await a({port:n.fallbackPort??Ae,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??te)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var M1={"not-macos":"persistence swap: macOS only \u2014 the LaunchAgents stay in place on this OS.","bad-path":"persistence swap: --app-path must point at a .app bundle.",missing:"persistence swap: tray app bundle not found \u2014 nothing changed.",unsigned:"persistence swap: tray app failed codesign verification \u2014 refusing to adopt (RFC 0010 invariant 5).","no-team-identifier":"persistence swap: tray app has no Developer ID TeamIdentifier (adhoc or unsigned) \u2014 refusing to adopt (RFC 0010 invariant 5).","untrusted-team":"persistence swap: tray app is signed by a Developer ID that is not Anyray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgents stay in place.","untrusted-bundle-id":"persistence swap: that bundle is not the Anyray Connect Tray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgents stay in place."},F1=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},B1=async(e,t)=>{let n=t.stderr??console.error,r=F1(e,"--app-path")??zS,o=await um(r,t);if(!o.ok)return n(M1[o.reason]),1;let s=await(t.load??P)();await(t.save??te)({...s,persistenceOwner:"tray",trayAppPath:r});let c=t.uninstallScheduler??ir,l=t.uninstallDaemon??Jt;return await c().catch(()=>{}),await l(s.fallbackPort).catch(()=>{}),0},U1=async e=>{let t=e.load??P,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??sr,o=e.installDaemon??Lt;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await o({port:n.fallbackPort??Ae,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??te)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},qS=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await B1(e,t):e.includes("--release-tray")?await U1(t):(n("persistence swap: expected --adopt-tray or --release-tray."),1)}catch(r){return n(`persistence swap: failed (${r instanceof Error?r.name:"Error"}).`),1}};import{homedir as QS,platform as eE}from"node:os";import{join as Ea}from"node:path";import{access as H1}from"node:fs/promises";var fm=(e=eE(),t=QS())=>{let n=a=>[Ea(t,"Library","LaunchAgents",`${a}.plist`)],r=Ea(t,".config","systemd","user"),o=a=>[Ea(t,".anyray","logs",a)];return e==="darwin"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:os,paths:n(os),dataPaths:o("connect-daemon.log")},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:us,paths:n(us),dataPaths:o("connect-refresh.log")}]:e==="linux"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:`${ar}.service`,paths:[Ea(r,`${ar}.service`)]},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:`${Wr}.timer`,paths:[Ea(r,`${Wr}.timer`),Ea(r,`${Wr}.service`)]}]:e==="win32"?[{kind:"scheduler",title:"key-refresh scheduler",supervisorName:kc,paths:[]}]:[]},tE=async e=>{try{return await H1(e),!0}catch{return!1}},Ci=async(e,t={})=>{let n=t.exists??tE;for(let r of fm(t.os,t.home))if(r.kind===e){for(let o of r.paths)if(await n(o))return!0}return!1},nE=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable)return t;let n=e.exists??tE,r=fm(e.os,e.home);for(let o of r)if(o.kind==="daemon"?e.daemonEnabled&&e.daemonHealthy===!1:e.schedulerEnabled&&!e.schedulerInstalled)for(let s of o.paths)await n(s)||(t.missingPaths.push(s),t.kinds.includes(o.kind)||t.kinds.push(o.kind));return t.suspected=t.missingPaths.length>0,t},W1=[os,`${ar}.service`,us,`${Wr}.timer`,`${Wr}.service`,kc],rE=(e,t=eE(),n=QS(),r=rr())=>{let o=["Anyray connect installs two per-user background services. Both are","unprivileged, run as the logged-in user, and exist only to re-mint the","seat's short-lived gateway key so a long AI-coding session doesn't 401.","","Executable (both services):",` ${r}`,""];for(let a of fm(t,n)){o.push(`${a.title} \u2014 supervisor name: ${a.supervisorName}`);for(let s of a.paths)o.push(` ${s}`);a.paths.length===0&&o.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let s of a.dataPaths??[])o.push(` ${s} (captured stdout/stderr \u2014 error names only)`);o.push("")}return o.push("Also spawns, detached and short-lived (same executable, hidden","subcommands \u2014 not a separate install):"," - Coding-tool MCP clients (Copilot Chat, Copilot CLI, OpenCode, etc.) run"," `anyray-connect __anyray-mcp-server` as a stdio server, which spawns a"," detached `anyray-connect __anyray-refresh`."," - The Anyray VS Code extension, on activation (including a remote/"," Codespace/dev-container extension host), spawns"," `anyray-connect __anyray-spawn-refresh` \u2014 a cheap gate that may itself"," spawn the same detached `anyray-connect __anyray-refresh`."," Both are throttled independently of the scheduler (up to ~6h between"," spawns) and serialized through the same refresh-state claim, so they can"," never double-mint against it. Neither listens itself; the tick can"," (re)install the loopback daemon disclosed above, whose port is covered"," under Network behavior.","","Network behavior:",` - The daemon listens on 127.0.0.1:${e} ONLY (loopback; it never binds a`," routable interface and accepts no remote connections)."," - Outbound: your org's Anyray gateway over HTTPS, nothing else."," - It relays your AI tools\u2019 requests byte-for-byte; its single mutation is"," filling in a freshly minted gateway key header.","","Why it looks like persistence to a heuristic scanner: the launchd agent is a","KeepAlive login item, which is the same shape a persistence implant uses. It","is a real login item, by design \u2014 that is what keeps keys fresh across","reboots. Allow-list the paths above, or run `anyray-connect --no-key-refresh`","to install no background service at all (tools then point straight at the","gateway, at the cost of a periodic re-run when the key lapses).","","Retired supervisor labels (endpoint v2): on a machine running Fleet\u2019s signed","fleetd, connect retires the services above \u2014 fleetd drives key refresh","instead. If you find any of these labels/units on a fleetd host, they are","orphans safe to remove; connect no longer installs or supervises them:",...W1.map(a=>` - ${a}`)),o};var hm=5e3,oE=3e4,K1=1440*60*1e3,G1=e=>new Promise(t=>setTimeout(t,e)),j1=async(e=P,t=Dt)=>(await _e(e,t))?.target,V1=e=>Ht(e)?.quitGated,aE=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??V1,o=t.readPending??Vc,a=t.clearPending??Op,s=t.targetFromProfile??j1,i=t.sleep??G1,c=t.now??Date.now,l=t.maxWaitMs??K1;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=hm;for(;;){let h=await o(n);if(!h||c()-f>l)return 0;if(d.isRunning()){await i(p),p=Math.min(oE,p*2);continue}let m;if(d.needsTarget?.(h.op)&&(m=await s(),!m)){if(await a(n,h)!=="superseded")return 0;await i(p),p=hm;continue}if((await u(h.op,m,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(p),p=Math.min(oE,p*2);continue}if(await a(n,h)!=="superseded")return 0;await i(p),p=hm}}catch{return 0}};import{writeFileSync as J1}from"node:fs";import{chmod as mm,stat as z1}from"node:fs/promises";import{platform as gm}from"node:os";import{dirname as lE,isAbsolute as q1}from"node:path";var xa=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,_d=xa(process.stdout,process.env),sE=xa(process.stderr,process.env),Ia=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,j=e=>Ia("1",e,_d),C=e=>Ia("2",e,_d),Y1=e=>Ia("32",e,_d),Z1=e=>Ia("33",e,sE),X1=e=>Ia("31",e,sE),et=e=>Ia("36",e,_d),k=e=>console.log(e),K=e=>console.log(`
|
|
308
|
+
${j(e)}`),F=e=>console.log(C(e)),$=e=>console.log(`${Y1("\u2713")} ${e}`),N=e=>console.error(`${Z1("!")} ${e}`),O=e=>console.error(`${X1("\u2717")} ${e}`);var ym=`${j("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
|
|
309
309
|
|
|
310
310
|
Emit or install the OS \`managed-settings.json\` that points a managed fleet's
|
|
311
311
|
Claude Code at the Anyray gateway. It reads at a HIGHER precedence than a user's
|
|
@@ -393,13 +393,13 @@ ${j("Examples")}
|
|
|
393
393
|
anyray-connect managed --print --tool jetbrains --bin /usr/local/bin/anyray-connect --npx /usr/local/bin/npx > acp.json
|
|
394
394
|
|
|
395
395
|
# Shell/SDK fleet snippet (base URLs only; keys stay per-user):
|
|
396
|
-
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,
|
|
397
|
-
`)},
|
|
398
|
-
`),
|
|
399
|
-
`),
|
|
400
|
-
`),
|
|
401
|
-
`+
|
|
402
|
-
`+
|
|
396
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,iE=["claude-code","jetbrains","shell","bootstrap","proxy"],Q1=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--print":t.mode="print";break;case"--write":t.mode="write";break;case"--revert":t.mode="revert";break;case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":throw new Error("--key is not valid for managed settings: fleet files never embed credentials; enroll each user instead");case"--scrub-direct-mode":t.scrubDirectMode=!0;break;case"--sso":t.sso=o();break;case"--bin":t.bin=o();break;case"--npx":t.npx=o();break;case"--loopback":t.loopback=!0;break;case"--out":t.out=o();break;case"--platform":{let a=o();if(a!=="launchd"&&a!=="systemd")throw new Error(`unknown --platform ${a} (expected launchd | systemd)`);t.servicePlatform=a;break}case"--tool":{let a=o();if(!iE.includes(a))throw new Error(`unknown --tool ${a} (expected ${iE.join(" | ")}; Codex fleets use \`anyray-connect desktop codex\`)`);t.tool=a;break}case"--subscription":throw new Error("--subscription cannot produce a valid credentialless managed file; use --sso <link> so each user enrolls and receives a personal gateway key");case"--placeholder":case"--org":throw new Error(`${r} is a legacy no-op for managed settings; omit it and enroll each user`);case"--yes":case"-y":break;case"--help":case"-h":t.help=!0;break;default:if(!r.startsWith("-")&&t.gateway===void 0)t.gateway=r;else throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r} (gateway already set to ${t.gateway})`)}}if(t.sso&&!Rt(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function Td(e,t,n={}){if(!t&&e.authMode==="subscription")throw new Error("subscription managed settings require deferred SSO; a seat OAuth token does not replace the required personal gateway key");if(t){let o=["__anyray-sso-gate","--sso",t.sso,...t.gateway?["--gateway",t.gateway]:[],...t.team?["--team",t.team]:[]];return{hooks:{PostToolUse:[En(Ja(t.binaryPath,[Ze]),{matcher:"*"})],UserPromptSubmit:[En(Ja(t.binaryPath,o),{timeout:30}),En(Ja(t.binaryPath,[qn]))],SessionStart:[En(Ja(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=un(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(xn.map(o=>[o.name,""])),...r}}:{env:r}}var eH=(e,t)=>{let n="env"in t||"hooks"in t?t:{env:t},r={...e};e.env&&typeof e.env=="object"&&(r.env={...e.env}),e.hooks&&typeof e.hooks=="object"&&(r.hooks=Object.fromEntries(Object.entries(e.hooks).map(([a,s])=>[a,Array.isArray(s)?[...s]:s])));let o=r.env??{};for(let a of Fr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,Du(r),n.env&&(r.env={...o,...n.env}),n.hooks){let a=r.hooks??{};for(let[s,i]of Object.entries(n.hooks)){let c=Array.isArray(a[s])?a[s]:[];a[s]=[...c,...i]}r.hooks=a}return r},tH=e=>{let t=e.env,n=Du(e);if(t){for(let r of Fr)r in t&&(delete t[r],n=!0);for(let{name:r}of xn)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},dE=async e=>{let t=async n=>{try{return(await z1(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(lE(e))!==void 0}},uE=async(e,t)=>(t.dirExisted||await mm(lE(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await mm(e,420),{mode:420,keptRestricted:!1}):(await mm(e,t.mode),{mode:t.mode,keptRestricted:!0})),pE=(e,t)=>{t.keptRestricted&&(N(`${e} was already restricted to mode ${t.mode.toString(8).padStart(3,"0")} and keeps it \u2014 widening it would expose whatever else that file holds to every local account.`),k(C(" Claude Code reads this file as the developer, so the routing will NOT take effect until it is readable. Move any secret out of it, then `chmod 644` it.")))},fE=()=>process.getuid?.()===0,Ce=e=>{process.stderr.write(`${e}
|
|
397
|
+
`)},Co=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}J1(e.out,t,"utf8"),Ce(C(`# Wrote ${e.out}`))},wm=e=>ge({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),Pd=e=>q1(e)||/^[A-Za-z]:[\\/]/.test(e),hE=e=>{if(!e.sso)return;let t=Rt(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??Oe();if(!e.bin&&!ce())throw new Error("--bin is required because the running binary path is temporary; use a fleet-stable path such as /usr/local/bin/anyray-connect");if(!Pd(n))throw new Error("--bin must be an absolute fleet-stable path");return{sso:`${t.cpOrigin}/sso/${t.tenantId}`,binaryPath:n,gateway:e.gateway,team:e.team}},mE=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${le(e.metadata)??"(none \u2014 pass --team)"}`],bm=(e,t)=>{try{let{hostname:n}=new URL(e.origin);["localhost","127.0.0.1","::1","0.0.0.0"].includes(n)&&t(`! Gateway is ${e.origin} \u2014 a fleet managed file almost certainly wants your real gateway URL (pass --gateway).`)}catch{}},nH=(e,t)=>({agent_servers:{[Wn]:{command:e,args:[Jl,"claude",t,"jetbrains"],env:{}},[Kn]:{command:e,args:[Jl,"codex",t,"jetbrains"],env:{}}}}),cE=e=>["# Managed by anyray-connect (fleet). Routes shell/SDK traffic through the Anyray gateway.","# Per-user keys come from enrollment (`anyray-connect --enroll/--sso`); never add a key here.",`export OPENAI_BASE_URL=${Se(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${Se(e.anthropicBaseUrl)}`,""].join(`
|
|
398
|
+
`),rH=e=>{if(e.sso||e.gateway||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool jetbrains takes only --bin and --npx: gateway, attribution, and auth all resolve from each user\u2019s own enrollment at agent launch");if(!e.bin)throw new Error("--bin <absolute path> is required (fleet-stable anyray-connect binary, e.g. /usr/local/bin/anyray-connect)");if(!Pd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");if(!e.npx)throw new Error("--npx <absolute path> is required (fleet-stable npx, e.g. /usr/local/bin/npx) \u2014 a fleet artifact must not absorb the admin machine\u2019s PATH");if(!Ql(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return Co(e,`${JSON.stringify(nH(e.bin,e.npx),null,2)}
|
|
399
|
+
`),Ce(C("# acp.json for ~/.jetbrains/acp.json (per user).")),Ce(C(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ce(C("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ce(C("# An MDM file drop REPLACES the file \u2014 deploy at provision time, or merge agent_servers in your config tool if devs add their own agents.")),0},oH=e=>{if(e.npx||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool bootstrap takes only --sso, --gateway, and --bin: it carries the enrollment link, never attribution");if(!e.sso)throw new Error("--sso <link> is required: the bootstrap file exists to hand the org SSO link to unenrolled machines");if(e.bin&&!Pd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return Co(e,xS(e.sso,e.gateway,e.bin)),Ce(C(`# Fleet bootstrap for ${Ai("linux")}`)),Ce(C(`# macOS: ${Ai("darwin")}`)),Ce(C(`# Windows: ${Ai("win32",{ProgramData:"C:\\ProgramData"})}`)),Ce(C("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},aH=e=>{if(e.sso||e.bin||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool shell takes only --gateway (or --loopback): the snippet carries base URLs only (keys and attribution ride each user\u2019s enrollment)");if(e.loopback){if(e.gateway)throw new Error("--loopback and --gateway are mutually exclusive: the daemon resolves the real gateway from the fleet bootstrap file");let n=ge({origin:`http://127.0.0.1:${Ae}`});return Co(e,cE(n)),Ce(C(`# Loopback shell snippet \u2014 pair with \`managed --tool proxy\` (daemon on :${Ae}) and \`--tool bootstrap\`.`)),0}let t=wm(e);return Co(e,cE(t)),Ce(C("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),bm(t,Ce),0},sH=e=>{if(e.sso||e.gateway||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session||e.loopback)throw new Error("--tool proxy takes only --bin and --platform: the daemon resolves the gateway and per-user auth at runtime (bootstrap file + profile)");if(!e.bin)throw new Error("--bin <absolute path> is required (fleet-stable anyray-connect binary, e.g. /usr/local/bin/anyray-connect)");if(!Pd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");let t=e.servicePlatform??(gm()==="darwin"?"launchd":"systemd"),n={command:e.bin,args:[Ku]};return t==="launchd"?(Co(e,is(n)),Ce(C("# launchd agent \u2014 deploy to /Library/LaunchAgents/ai.anyray.connect.fallback.plist (loads for every user at login)."))):(Co(e,cs(n)),Ce(C("# systemd user unit \u2014 deploy to /etc/systemd/user/anyray-fallback.service, then `systemctl --global enable anyray-fallback.service`."))),Ce(C(`# Pair with \`--tool bootstrap\` (the daemon's fleet boot needs it) and the \`--tool shell --loopback\` snippet (port ${Ae}).`)),Ce(C(`# Push the binary to ${e.bin} before this unit.`)),0},iH=e=>{let t=wm(e),n=hE(e),r=n?Td(t,n):Td(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(Co(e,`${JSON.stringify(r,null,2)}
|
|
400
|
+
`),Ce(C(`# managed-settings.json for ${Pt()}`)),n)Ce(C("# Deferred SSO: hooks only; no credential or managed env block.")),Ce(C(`# Push the binary to ${n.binaryPath} before this file.`)),Ce(C("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of mE(t))Ce(C(`# ${o}`));bm(t,Ce)}return 0},cH=async e=>{let t=gm();if(t!=="darwin"&&t!=="linux")return O("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!fE())return O("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),k(C(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=wm(e),r=hE(e);r||bm(n,u=>N(u.replace(/^!\s*/,"")));let o=Pt(t),a=await M(o),s=r?Td(n,r):Td(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?xn.filter(({name:u})=>{let f=a.env?.[u];return typeof f=="string"&&f.trim()!==""}):[],c=eH(a,s),l=await dE(o);await Z(o,c);let d=await uE(o,l);$(`Wrote ${o}`),pE(o,d);for(let{name:u,cloud:f}of i)N(`${u} was set in this file and is now pinned empty \u2014 Claude Code no longer talks to ${f} directly. The gateway serves it instead; re-add the key here to undo.`);if(r)k(C(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),k(C(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of mE(n))k(` ${C(u)}`);return k(C(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},lH=async()=>{let e=gm();if(e!=="darwin"&&e!=="linux")return O("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!fE())return O("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Pt(e);if(!await R(t))return k(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await M(t);if(!tH(n))return k(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await dE(t);await Z(t,n);let o=await uE(t,r);return $(`Removed Anyray-owned keys from ${t} (other keys left intact).`),pE(t,o),0},yE=async e=>{let t;try{t=Q1(e)}catch(n){return O(n instanceof Error?n.message:"invalid managed arguments"),k(`
|
|
401
|
+
`+ym),1}if(t.help||e.length===0&&!t.mode)return k(ym),0;if(!t.mode)return O("Specify a mode: --print, --write, or --revert."),k(`
|
|
402
|
+
`+ym),1;if(t.out!==void 0&&t.mode!=="print")return O(`--out is valid with --print only, not --${t.mode}.`),1;if(t.scrubDirectMode){let n=t.sso!==void 0?"--sso emits a hooks-only file with no env block":(t.tool??"claude-code")!=="claude-code"?`--tool ${t.tool} does not write Claude Code env`:t.mode==="revert"?"--revert already removes the pin (and leaves a truthy value alone)":void 0;if(n)return O(`--scrub-direct-mode cannot be combined with this mode: ${n}.`),1}try{let n=t.tool??"claude-code";return n!=="claude-code"?t.mode!=="print"?(O(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?rH(t):n==="bootstrap"?oH(t):n==="proxy"?sH(t):aH(t):t.mode==="print"?iH(t):t.mode==="write"?await cH(t):await lH()}catch(n){return O(n instanceof Error?n.message:"managed settings failed"),1}};var dH=`anyray-connect print-key [--json | --passthrough-headers]
|
|
403
403
|
|
|
404
404
|
Print the current short-lived Anyray client key for a consuming app.
|
|
405
405
|
|
|
@@ -411,10 +411,10 @@ Options:
|
|
|
411
411
|
"x-anyray-provider":"anthropic","x-anyray-metadata":"..."}).
|
|
412
412
|
Carries the client key, never the seat OAuth token.
|
|
413
413
|
--help Show this help.
|
|
414
|
-
`,
|
|
415
|
-
`);let s=o.passthroughHeaders?
|
|
414
|
+
`,uH=e=>{let t=!1,n=!1,r=!1;for(let o of e)if(o==="--json")t=!0;else if(o==="--passthrough-headers")n=!0;else if(o==="--help"||o==="-h")r=!0;else throw new Error(`Unknown option: ${o}`);if(t&&n)throw new Error("Use only one of --json or --passthrough-headers.");return{json:t,passthroughHeaders:n,help:r}},pH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=ki(e):!0},gE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},wE=(e,t)=>{if(!Ie(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},km=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,fH=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${km(t)}\`.`:"Enrollment certificate expired. Re-run `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"cert-rejected":return t.ssoLink?`Your SSO reconnect credential is no longer valid. Reconnect with \`${km(t)}\`.`:"Your enrollment certificate is no longer valid. Reconnect with `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${km(t)}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.";case"disabled":return"Automatic key refresh is disabled.";case"backoff":case"throttled":return"Key refresh is temporarily unavailable; retry shortly.";case"not-due":case"repaired":case"cert-renewed":case"heartbeat-refreshed":case"proxy-restored":case"refreshed":return""}},Am=async(e={})=>{let t=e.loadProfile??P,n=e.refreshIfDue??Qe,r=e.now??Date.now,o=await t();if(gE(o),!o.enrolledCert){if(!wE(o,r))throw new Error("No valid Anyray client key is stored. Set ANYRAY_CLIENT_KEY to a minted ark_ key or enroll this machine.");return{profile:o,token:o.clientKey}}let a;if(!o.clientKey||pH(o,r)){let i=fH(await n(),o);if(i){if(!wE(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(gE(s),!Ie(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},bE=e=>le({user:e.name,team:e.team}),hH=({profile:e,token:t})=>{let n={},r=bE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Cm=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=bE(e);return r&&(n["x-anyray-metadata"]=r),n},mH=e=>JSON.stringify(Cm(e)),kE=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=uH(e);if(o.help)return n.write(dH),0;let a=await Am(t);a.warning&&r.write(`${a.warning}
|
|
415
|
+
`);let s=o.passthroughHeaders?mH(a):o.json?hH(a):a.token;return n.write(`${s}
|
|
416
416
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
417
|
-
`),1}};var
|
|
417
|
+
`),1}};var AE=`anyray-connect models [<model-id>] [--json]
|
|
418
418
|
|
|
419
419
|
List the Copilot models your seat can run on the Anyray lane, or switch the
|
|
420
420
|
Copilot CLI's startup model. The CLI's own /models cannot list models on a
|
|
@@ -426,8 +426,8 @@ Options:
|
|
|
426
426
|
--json Emit {"origin","current","models":[{"id","wire",...caps}]} instead
|
|
427
427
|
of the table (listing only).
|
|
428
428
|
--help Show this help.
|
|
429
|
-
`,
|
|
430
|
-
`),0;k(j(`Copilot models your seat serves (via ${o.origin})`));for(let h of l){let m=h.id===p?"*":" ",w=
|
|
429
|
+
`,yH=e=>{let t={json:!1,help:!1};for(let n of e)n==="--help"||n==="-h"?t.help=!0:n==="--json"?t.json=!0:n.startsWith("-")?t.error=`unknown option: ${n}`:t.modelId?t.error=`unexpected argument: ${n}`:t.modelId=n;return t},gH=e=>{let t=oe.find(n=>n.id===Qr);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},wH=e=>{let t=r=>r>=1e3?`${Math.round(r/1e3)}k`:String(r);return[...e.maxPromptTokens?[`${t(e.maxPromptTokens)} in`]:[],...e.maxOutputTokens?[`${t(e.maxOutputTokens)} out`]:[]].join(" / ")},bH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Fs(t)}/${Pn(n)==="responses"?"responses":"chat/completions"}`,CE=async(e=[],t={})=>{let n=yH(e);if(n.help)return process.stdout.write(AE),0;if(n.error)return O(n.error),process.stdout.write(AE),1;let r=await(t.loadTarget??_e)();if(!r)return O("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??cl)({allowKeychainPrompt:!0});if(!a.token)return O("No Copilot sign-in Connect can read \u2014 run `copilot` once and `/login` (say YES to storing credentials locally), then retry."),1;let s=a.token.token,i=a.capiSegment??"default",c=await(t.fetchCatalog??Xo)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=cf(c);if(l.length===0)return O("Could not fetch your seat's model catalog from GitHub (offline, or the sign-in lost its Copilot seat)."),1;if(!n.modelId){let p=process.env.COPILOT_MODEL?.trim();if(n.json)return process.stdout.write(`${JSON.stringify({origin:o.origin,current:p??null,models:l.map(h=>({id:h.id,wire:Pn(h.id),...h.maxPromptTokens?{maxPromptTokens:h.maxPromptTokens}:{},...h.maxOutputTokens?{maxOutputTokens:h.maxOutputTokens}:{}}))})}
|
|
430
|
+
`),0;k(j(`Copilot models your seat serves (via ${o.origin})`));for(let h of l){let m=h.id===p?"*":" ",w=wH(h);k(` ${m} ${h.id.padEnd(24)}${w?C(w):""}`)}return F("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),F("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(p=>p.id===n.modelId);if(!d)return O(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??il)(bH(o,i,d.id),{...sf(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return O(`GitHub refuses chat as '${d.id}' for this sign-in (it is in the catalog, but chat entitlement is narrower). Pick another id from \`anyray-connect models\`.`),1;u==="unreachable"?N("Could not verify the model over the lane (offline?) \u2014 applying anyway."):$(`'${d.id}' answers on your lane.`);let f=process.env.ANYRAY_COPILOT_MODEL;process.env.ANYRAY_COPILOT_MODEL=d.id;try{let p=await(t.applyCopilotCli??gH)(o);if(p.status!=="configured"){for(let h of p.messages)k(h);return O("Apply did not complete \u2014 see above."),1}}finally{f===void 0?delete process.env.ANYRAY_COPILOT_MODEL:process.env.ANYRAY_COPILOT_MODEL=f}return $(`Copilot CLI startup model \u2192 ${d.id}`),F("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var kH=`anyray-connect copilot-login
|
|
431
431
|
|
|
432
432
|
Sign Anyray in to GitHub Copilot (device flow) so the Copilot CLI seat lane
|
|
433
433
|
can run your plan's current models. Opens no browser for you: it prints a
|
|
@@ -435,16 +435,16 @@ code to type at github.com/login/device.
|
|
|
435
435
|
|
|
436
436
|
Options:
|
|
437
437
|
--help Show this help.
|
|
438
|
-
`,
|
|
439
|
-
`),0)};import{join as
|
|
440
|
-
A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),
|
|
441
|
-
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;let s=e.revert?"remove Anyray project config for":"write committable project config for";if(!await
|
|
442
|
-
${s} ${n.length} tool(s)?`))return
|
|
443
|
-
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){K(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await
|
|
444
|
-
`),1;try{let o=await
|
|
438
|
+
`,vE=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(kH),0;k(j("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??hk)();if(!n)return O("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;k(` 1. Open ${et(n.verificationUri)}`),k(` 2. Enter the code: ${j(n.userCode)}`),F(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??mk)(n);if(r.status!=="ok")return O(r.status==="denied"?"Sign-in was declined in the browser.":r.status==="expired"?"The code expired before sign-in completed \u2014 run the command again.":"GitHub refused the sign-in. Run the command again."),1;let o=(t.now??(()=>new Date))().toISOString(),a=await(t.save??yk)(r.token,o);$(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??Qp)(r.token);if(s.verdict==="no-copilot")return O("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??_e)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??Xo)(r.token,{},s.capiSegment,c);return l.length===0?N("Signed in, but no model list came back \u2014 that is usually this machine or its network, not the sign-in. Continue with `anyray-connect --tools copilot-cli`; it verifies the model with a live check of its own."):$(`${l.length} models available (e.g. ${l[0].id}).`),F("Now run: anyray-connect --tools copilot-cli"),0};var SE=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??P)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=await(e.readState??HS)();return!s||s.expiresAt<=r()?(n.write("No live device token yet \u2014 start the daemon: run `anyray-connect`.\n"),1):(t.write(`${a}/device?dt=${s.token}
|
|
439
|
+
`),0)};import{join as PE,dirname as _H}from"node:path";import{mkdir as TH,readFile as Im,rm as LE,writeFile as DE}from"node:fs/promises";import{fstatSync as vH,openSync as SH,statSync as EH}from"node:fs";import{createInterface as xH}from"node:readline/promises";import{ReadStream as IH}from"node:tty";import{execFileSync as AH}from"node:child_process";import CH from"node:os";var Sm=e=>{try{return AH("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},EE=()=>{try{return CH.userInfo().username||void 0}catch{return}},xE=()=>Sm("user.name")??Sm("user.email")??EE()??"unknown",vm=e=>{try{return e()?.trim()||void 0}catch{return}},IE=(e={})=>{let t=e.gitConfig??Sm,n=vm(e.osUsername??EE),r=vm(()=>t("user.email"));return r||(vm(()=>t("user.name"))??n??"unknown")};var jt=()=>!!process.stdin.isTTY,RH=()=>{try{let e=vH(0);return e.isCharacterDevice()&&e.rdev===EH("/dev/tty").rdev}catch{return!1}},Em=()=>{if(RH()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new IH(SH(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},bt=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},RE=async(e,t)=>{let n=t.input??Em(),r=t.output??process.stdout,o=xH({input:n.stream,output:r});try{return await new Promise((a,s)=>{let i=!1,c=!1,l=d=>{i||(i=!0,d())};o.once("line",()=>{c=!0}),o.once("SIGINT",()=>o.close()),o.once("close",()=>{c||l(()=>s(new bt))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new bt)))})}finally{o.close(),n.close()}},Ra=async(e,t={})=>{let n=(await RE(`${e} ${C("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Oa=async(e,t,n={})=>{let r=t?` ${C(`[${t}]`)}`:"";return(await RE(`${e}${r}: `,n)).trim()||t},OE=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return F(`Your name: ${t} ${C("(cached \u2014 pass --user to change)")}`),t;let r=xE();return n||!jt()?(F(`Your name: ${r} ${C("(auto-detected \u2014 pass --user to change)")}`),r):Oa("? Your name",r)},_E=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return F(`Team: ${t} ${C("(cached \u2014 pass --team to change)")}`),t;if(!(n||!jt()))return Oa("? Team (optional)")},xr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return ln(e??n)},TE=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,_a="claude-desktop",vi=e=>e!=="cursor",Si=(e,t,n)=>vi(e)?n:t,Ld=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await br(e.runReg??Hn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Ut({home:e.home});return await R(s)?{authoritative:!0}:n("no-local-record")}if(t!=="darwin")return n("manual-platform");let r={home:e.home,managedPolicyPaths:e.managedPolicyPaths,readManagedPolicyKeys:e.readManagedPolicyKeys},o=tn(r);return await ao(o,r)?n("managed-policy"):(await ha({home:e.home,readClaudeAppVersion:e.readClaudeAppVersion,readClaudeAppBundle:e.readClaudeAppBundle})).supported?await R(o.journal)?{authoritative:!0}:n("no-local-record"):n("unverified-build")}catch{return n("no-local-record")}},Dd=e=>e.id!==_a||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",OH={"manual-platform":"Claude Desktop setup is manual on this platform","unverified-build":"this Claude Desktop build's automatic-setup seam is unverified","managed-policy":"Claude Desktop's inference settings are centrally managed on this machine","policy-unreadable":"Claude Desktop's Windows machine-policy ownership could not be read","no-local-record":"connect has no record of configuring Claude Desktop inference on this machine"},Nd=(e,t)=>{if(e==="not-routed")return{headline:"retrieval MCP server registered, but inference is not routed through the gateway \u2014 Claude Desktop model traffic is NOT optimized.",detail:["Fix: fully quit Claude Desktop, then run `anyray-connect desktop` and complete any printed inference steps."]};let n=OH[t.reason??"no-local-record"],r=t.mcpRegistered?`retrieval MCP server registered, but inference routing can't be verified (${n}).`:`inference routing can't be verified (${n}), and the retrieval MCP server is not registered.`;return t.reason==="managed-policy"?{headline:r,detail:["Managed policy is authoritative; Connect will not overwrite or auto-repair it. Update the organization MDM profile or bootstrap service.","Bootstrap changes need no MDM redeployment; Claude applies the refreshed configuration on the next app launch."]}:t.reason==="policy-unreadable"?{headline:r,detail:["Connect could not prove whether HKLM policy is authoritative, so it will not overwrite or auto-repair the per-user route.","Check the organization policy and registry-read permissions, then run `anyray-connect doctor` again."]}:{headline:r,detail:["If Claude Desktop's third-party inference setup was never completed, its traffic bypasses the gateway and is NOT optimized.","Check: Claude Desktop \u2192 Developer \u2192 Configure Third-Party Inference; re-run `anyray-connect desktop` to reprint the steps.",...t.mcpRegistered?[]:["Re-running from a durable install also registers the retrieval MCP server."]]}};var xm=["claude-code","codex"],PH="anyray-connect print-key",Rm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),LH=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:Wa,authMode:"placeholder",metadata:{}}),Om=e=>PE(e,".claude","settings.json"),DH=async(e,t,n)=>{let r=Om(e),o=await M(r),{env:a}=un(t,{includeAuthToken:!1,includeClientKey:!1}),s=Rm(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Ur(o)?i.push(`Kept the existing apiKeyHelper in ${r} \u2014 make sure it prints an Anyray client key, or remove it and re-run.`):o.apiKeyHelper=PH,n||await Z(r,o,{backup:!1}),i.unshift(`${n?"Would write":"Wrote"} ${r} \u2014 base URL + a PATH-resolved key helper (no credential, no identity).`),{messages:i,changedFiles:n?[]:[r]}},NE=async(e=process.cwd())=>{let t=[],n=Om(e);try{if(await R(n)){let o=await M(n),a=Rm(o.env)?o.env:{};(Fr.some(s=>s in a)||Ur(o))&&t.push(n)}}catch{}let r=_m(e);try{if(await R(r)){let o=await Im(r,"utf-8");pp(o)&&t.push(r)}}catch{}return t},NH=async(e,t)=>{let n=Om(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await M(n),o=!1;if(Rm(r.env)){let s={...r.env};for(let i of Fr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Ur(r)&&(delete r.apiKeyHelper,o=!0),!o)return{messages:[`No Anyray keys in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=Object.keys(r).length===0;return t||(a?await LE(n,{force:!0}):await Z(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},_m=e=>PE(e,".codex","config.toml"),$H=async(e,t,n)=>{let r=_m(e),o=await Im(r,"utf-8").catch(()=>""),a=Lc(o,ms(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await TH(_H(r),{recursive:!0}),await DE(r,a)),{messages:[`${n?"Would write":"Wrote"} ${r} \u2014 gateway provider with command-backed auth (no credential serialized).`,"Codex asks for project-config trust on first launch in a fresh checkout \u2014 that prompt is expected."],changedFiles:n?[]:[r]}},MH=async(e,t)=>{let n=_m(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Im(n,"utf-8"),o=Dc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await LE(n,{force:!0}):await DE(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},$E=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...xm],r=n.filter(s=>!xm.includes(s));if(r.length>0)return O(`--project supports ${xm.join(", ")} \u2014 not: ${r.join(", ")}. Other tools keep per-machine state (run anyray-connect without --project there).`),1;let o;if(!e.revert){let s=await P(),i=e.gateway??s.gateway;if(!i)return O("--project needs a gateway: pass --gateway <url>, or run `anyray-connect` once on this machine so it is cached."),1;try{let c=new URL(i.trim());if(c.protocol!=="http:"&&c.protocol!=="https:")throw new Error("not http(s)")}catch{return O(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=LH(Ye(i))}if(k(j(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),K("Project"),k(` Directory: ${t}`),o&&k(` Gateway: ${o.origin}`),k(` Tools: ${n.join(", ")}`),e.revert||(N(`
|
|
440
|
+
A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),F(" Each machine still needs `anyray-connect` on PATH and a one-time enrollment (--sso/--enroll); the files carry no credential and no identity.")),!e.yes&&!e.dryRun){if(!jt())return O(`
|
|
441
|
+
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;let s=e.revert?"remove Anyray project config for":"write committable project config for";if(!await Ra(`
|
|
442
|
+
${s} ${n.length} tool(s)?`))return F("Aborted. Nothing changed."),0}e.dryRun&&F(`
|
|
443
|
+
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){K(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await DH(t,o,e.dryRun):await $H(t,o,e.dryRun):s==="claude-code"?await NH(t,e.dryRun):await MH(t,e.dryRun);for(let c of i.messages)k(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(K("Next"),e.revert)$(" Project config removed. Commit the change to propagate it.");else{$(" Commit these files to route every checkout of this repo:");for(let s of a)k(` ${s}`);k(C(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as FH}from"node:child_process";var BH="/usr/bin/security",UH=["find-generic-password","-s","Claude Code-credentials","-w"],HH=1e4,WH=64*1024,KH=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,ME="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",GH=(e,t,n)=>new Promise((r,o)=>{FH(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),FE=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jH=e=>{let t=JSON.parse(e);if(!FE(t)||!FE(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!KH.test(n))throw new Error("unexpected keychain access token");return n},BE=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${ME}
|
|
444
|
+
`),1;try{let o=await Am(t),a=Cm(o),s=await(t.execSecurity??GH)(BH,[...UH],{encoding:"utf8",timeout:HH,maxBuffer:WH,shell:!1}),i=jH(s.stdout);return o.warning&&r.write(`${o.warning}
|
|
445
445
|
`),n.write(`${JSON.stringify({token:i,headers:a})}
|
|
446
|
-
`),0}catch{return r.write(`${
|
|
447
|
-
`),1}};import{mkdir as
|
|
446
|
+
`),0}catch{return r.write(`${ME}
|
|
447
|
+
`),1}};import{mkdir as bW,writeFile as kW}from"node:fs/promises";import{dirname as AW}from"node:path";import{Buffer as CW}from"node:buffer";import{constants as UE}from"node:fs";import{access as VH,chmod as YH,mkdir as ZH,open as XH,readFile as JH,realpath as zH,rm as qH,stat as KE,writeFile as QH}from"node:fs/promises";import{randomUUID as eW}from"node:crypto";import{platform as GE}from"node:os";import{dirname as tW,join as nW,posix as rW,win32 as jE}from"node:path";var $d="/usr/local/bin/anyray-credential-helper",Md="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Tm="Managed by anyray-connect desktop helper; do not edit.",oW=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
|
|
448
448
|
|
|
449
449
|
Create the credential helper required by Claude Desktop and Codex fleet
|
|
450
450
|
artifacts. The helper stores no key. It invokes a durable anyray-connect binary
|
|
@@ -461,8 +461,8 @@ Required:
|
|
|
461
461
|
Options:
|
|
462
462
|
--platform <target> posix or windows (default: current host).
|
|
463
463
|
--path <absolute> Helper destination. Defaults by target:
|
|
464
|
-
${
|
|
465
|
-
${
|
|
464
|
+
${$d}
|
|
465
|
+
${Md}
|
|
466
466
|
--help,-h Show this help.
|
|
467
467
|
|
|
468
468
|
Examples:
|
|
@@ -474,13 +474,13 @@ Examples:
|
|
|
474
474
|
|
|
475
475
|
anyray-connect desktop helper --print --platform posix \\
|
|
476
476
|
--bin /usr/local/bin/anyray-connect > anyray-credential-helper
|
|
477
|
-
`,
|
|
478
|
-
`);let r=
|
|
479
|
-
`)}
|
|
480
|
-
`),0;if(s!==
|
|
477
|
+
`,HE=(e=GE())=>e==="win32"?"windows":"posix",aW=e=>e==="windows"?Md:$d,WE=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},sW=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--write":WE(t,"write");break;case"--print":WE(t,"print");break;case"--bin":t.binaryPath=o();break;case"--path":t.helperPath=o();break;case"--platform":{let a=o();if(a!=="posix"&&a!=="windows")throw new Error("--platform must be posix or windows");t.targetPlatform=a;break}case"--help":case"-h":t.help=!0;break;default:throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r}`)}}return t},iW=e=>/[\0\r\n]/.test(e),cW=e=>/^[A-Za-z]:[\\/]/.test(e)&&jE.isAbsolute(e),Ei=(e,t)=>!iW(e)&&(t==="windows"?cW(e):rW.isAbsolute(e)),Pm=e=>e.replace(/\\/g,"/").toLowerCase(),VE=(e,t)=>{if(!Ei(e,t))return!1;let n=Pm(e);return!(/(^|\/)_npx(\/|$)/.test(n)||n==="/tmp"||n.startsWith("/tmp/")||n==="/private/tmp"||n.startsWith("/private/tmp/")||n==="/var/tmp"||n.startsWith("/var/tmp/")||n.startsWith("/var/folders/")||n.startsWith("/private/var/folders/")||/\/appdata\/local\/temp(\/|$)/.test(n)||t==="windows"&&(/[%!^&|<>()"]/.test(e)||!/\.exe$/i.test(e)))},Lm=(e,t)=>t==="windows"?jE.normalize(e):e,lW=e=>`'${e.replace(/'/g,`'"'"'`)}'`,dW=(e,t)=>{if(!VE(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Lm(t,e);if(e==="windows")return["@echo off",`REM ${Tm}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" print-key --json`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
478
|
+
`);let r=lW(n);return["#!/bin/sh",`# ${Tm}`,'if [ "$#" -eq 0 ]; then',` exec ${r} print-key --json`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
|
|
479
|
+
`)},Fd=(e,t)=>{if(!Ei(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Lm(t,e);if(e==="windows"){if(/[%!^&|<>()"]/.test(n)||!/\.cmd$/i.test(n))throw new Error("Windows --helper-path must be a safe absolute .cmd path without batch metacharacters");return{command:"C:\\Windows\\System32\\cmd.exe",args:["/d","/s","/c",`call "${n}" --token`]}}return{command:n,args:["--token"]}},uW=async e=>{try{return await JH(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},pW=async(e,t)=>{try{let n=await zH(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!VE(r,t))throw new Error;if(!(await KE(n)).isFile())throw new Error;await VH(n,t==="posix"?UE.X_OK:UE.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},fW=e=>e.slice(0,300).includes(Tm),hW=async(e,t,n)=>{let r=await uW(e);if(r!==void 0&&r!==t&&!fW(r))throw new Error(`refusing to replace non-Anyray file at ${e}; choose another --path`);if(r===t){if(n==="windows")return"unchanged";try{if(((await KE(e)).mode&511)===493)return"unchanged"}catch{}}let o=tW(e);try{await ZH(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=nW(o,`.anyray-credential-helper.${process.pid}.${eW()}.tmp`),s=!1;try{await QH(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await YH(a,493);let i=await XH(a,"r");try{await Ka(i)}finally{await i.close()}await fe(a,e),s=!0}catch{throw new Error(`could not install credential helper at ${e}`)}finally{s||await qH(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},YE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=sW(e);if(o.help)return n.write(oW),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");let a=(t.platform??GE)(),s=o.targetPlatform??HE(a),i=Lm(o.helperPath??aW(s),s);if(!Ei(i,s))throw new Error(`--path must be an absolute ${s} path`);if(s==="windows"&&Fd("windows",i),Pm(i)===Pm(o.binaryPath))throw new Error("--path must differ from --bin (the helper cannot invoke itself)");let c=dW(s,o.binaryPath);if(o.mode==="print")return n.write(c),r.write(`Deploy this wrapper at ${i} after deploying the binary at ${o.binaryPath}.
|
|
480
|
+
`),0;if(s!==HE(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await pW(o.binaryPath,s);let l=await hW(i,c,s);return r.write(l==="unchanged"?`Credential helper already current at ${i}.
|
|
481
481
|
`:`${l==="installed"?"Installed":"Updated"} credential helper at ${i}.
|
|
482
482
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
483
|
-
`),1}};var
|
|
483
|
+
`),1}};var mW=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),yW=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,gW=e=>{let t=e.toLowerCase();return t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),t.endsWith(".")&&(t=t.slice(0,-1)),t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")},wW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Bd=(e,t)=>{let n;try{n=new URL(e)}catch{throw new Error(`${t} must be a valid HTTPS URL.`)}if(n.protocol!=="https:"||n.username!==""||n.password!==""||n.hash!==""||gW(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ta=(e,t,n)=>{if(!(e===void 0&&!n)){if(typeof e!="string"||e.trim()==="")throw new Error(`--bootstrap-oidc ${t} must be a non-empty string.`);return e.trim()}},ZE=e=>{if(!wW(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!mW.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ta(e.clientId,"clientId",!0),r=Ta(e.scopes,"scopes",!0),o=Ta(e.issuer,"issuer",!1),a=Ta(e.authorizationUrl,"authorizationUrl",!1),s=Ta(e.tokenUrl,"tokenUrl",!1),i=Ta(e.additionalRedirectReferrerHosts,"additionalRedirectReferrerHosts",!1);if(!o&&!(a&&s))throw new Error("--bootstrap-oidc requires issuer, or both authorizationUrl and tokenUrl.");let c=e.redirectPort;if(c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<1||c>65535))throw new Error("--bootstrap-oidc redirectPort must be an integer from 1 to 65535.");return{clientId:n,scopes:r,...o?{issuer:Bd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Bd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Bd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},XE=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return ZE(t)},Dm=e=>{let t=Bd(e.url,"--bootstrap-url"),n=e.oidc?ZE(e.oidc):void 0,r;if(e.deploymentOrganizationUuid!==void 0&&(r=e.deploymentOrganizationUuid.trim(),!yW.test(r)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:t,...n?{bootstrapOidc:n}:{},...r?{deploymentOrganizationUuid:r}:{}}},Nm=e=>ta(Dm(e));var vW=`anyray-connect desktop [disconnect] [options]
|
|
484
484
|
|
|
485
485
|
The minimum Claude Desktop workflow:
|
|
486
486
|
anyray-connect desktop Connect this machine
|
|
@@ -522,8 +522,8 @@ Options:
|
|
|
522
522
|
|
|
523
523
|
Older flag-based Claude artifacts and Codex fleet output remain accepted for
|
|
524
524
|
compatibility, but are not part of the recommended Claude Desktop workflow.
|
|
525
|
-
`,
|
|
526
|
-
<string>${
|
|
525
|
+
`,SW=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",EW=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),xW=e=>{if(e[0]!=="fleet")return e;if(e.includes("--help")||e.includes("-h"))return["--help"];let t=e[1];if(t!=="bootstrap"&&t!=="static")throw new Error("desktop fleet requires bootstrap or static.");let n=e[2];if(n!=="macos"&&n!=="windows"&&n!=="linux")throw new Error("desktop fleet target must be macos, windows, or linux.");let r=e[3];if(!r||r.startsWith("-"))throw new Error(t==="bootstrap"?"desktop fleet bootstrap requires an HTTPS URL.":"desktop fleet static requires an absolute credential-helper path.");let o=e.slice(4),a=o[0]&&!o[0].startsWith("-")?o.shift():void 0;return[SW(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...EW(o)]},IW=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),$m=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>IW.has(r))||t.includes("--apply")&&t.includes("--revert")||n==="disconnect"&&t.includes("--apply")))return n==="disconnect"&&(t=["--revert",...t.slice(1)]),t=t.filter(r=>r!=="--apply"),[...t,"--tools","claude-desktop"]},Zn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),JE=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),RW=(e,t)=>` <key>${Zn(e)}</key>
|
|
526
|
+
<string>${Zn(t)}</string>`,Mm=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>RW(i,c)).join(`
|
|
527
527
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
528
528
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
529
529
|
<plist version="1.0">
|
|
@@ -532,15 +532,15 @@ compatibility, but are not part of the recommended Claude Desktop workflow.
|
|
|
532
532
|
<array>
|
|
533
533
|
<dict>
|
|
534
534
|
<key>PayloadType</key>
|
|
535
|
-
<string>${
|
|
535
|
+
<string>${Zn(e)}</string>
|
|
536
536
|
<key>PayloadVersion</key>
|
|
537
537
|
<integer>1</integer>
|
|
538
538
|
<key>PayloadIdentifier</key>
|
|
539
|
-
<string>${
|
|
539
|
+
<string>${Zn(t)}.payload</string>
|
|
540
540
|
<key>PayloadUUID</key>
|
|
541
|
-
<string>${
|
|
541
|
+
<string>${Zn(o)}</string>
|
|
542
542
|
<key>PayloadDisplayName</key>
|
|
543
|
-
<string>${
|
|
543
|
+
<string>${Zn(n)}</string>
|
|
544
544
|
${s}
|
|
545
545
|
</dict>
|
|
546
546
|
</array>
|
|
@@ -549,27 +549,27 @@ ${s}
|
|
|
549
549
|
<key>PayloadVersion</key>
|
|
550
550
|
<integer>1</integer>
|
|
551
551
|
<key>PayloadIdentifier</key>
|
|
552
|
-
<string>${
|
|
552
|
+
<string>${Zn(t)}</string>
|
|
553
553
|
<key>PayloadUUID</key>
|
|
554
|
-
<string>${
|
|
554
|
+
<string>${Zn(r)}</string>
|
|
555
555
|
<key>PayloadDisplayName</key>
|
|
556
|
-
<string>${
|
|
556
|
+
<string>${Zn(n)}</string>
|
|
557
557
|
</dict>
|
|
558
558
|
</plist>
|
|
559
|
-
`},
|
|
560
|
-
`,
|
|
561
|
-
`,
|
|
562
|
-
`),
|
|
559
|
+
`},OW=(e,t)=>Mm("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",ta(oo(e,t))),_W=(e,t)=>`${JSON.stringify(oo(e,t),null,2)}
|
|
560
|
+
`,TW=e=>Mm("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",Nm(e)),PW=e=>`${JSON.stringify(Dm(e),null,2)}
|
|
561
|
+
`,qE=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries(e).map(([n,r])=>`"${JE(n)}"="${JE(r)}"`),""].join(`
|
|
562
|
+
`),LW=(e,t)=>{let n=$l(e,t);return qE(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},DW=e=>qE(Nm(e)),NW=(e,t)=>{if(e.authMode==="subscription")throw new Error("Codex subscription managed config is not supported: ChatGPT OAuth still requires a personal gateway key in x-anyray-api-key; run per-user Connect enrollment instead");let n=/^[A-Za-z]:[\\/]/.test(t)?"windows":"posix",r=Fd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${ms(e,o).join(`
|
|
563
563
|
`)}
|
|
564
|
-
`}
|
|
564
|
+
`},$W=e=>Mm("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:CW.from(e,"utf-8").toString("base64")}),MW=e=>{let t={target:e[0]==="codex"?"codex":"claude",migrate:!1,allAccounts:!1,help:!1},n=e[0]==="codex"||e[0]==="claude"?1:0,r=()=>e[++n],o=()=>{let a=e[n+1];if(a&&!a.startsWith("-"))return n++,a};for(;n<e.length;n++){let a=e[n];switch(a){case"--mobileconfig":t.artifact="mobileconfig",t.path=o();break;case"--reg":t.artifact="reg",t.path=o();break;case"--json":t.artifact="json",t.path=o();break;case"--migrate":t.migrate=!0;break;case"--account":t.account=r();break;case"--all-accounts":t.allAccounts=!0;break;case"--gateway":t.gateway=r();break;case"--helper-path":t.helperPath=r()??"";break;case"--bootstrap-url":t.bootstrapUrl=r()??"";break;case"--bootstrap-oidc":t.bootstrapOidc=r()??"";break;case"--deployment-organization-uuid":t.deploymentOrganizationUuid=r()??"";break;case"--team":t.team=r();break;case"--intent":t.intent=r();break;case"--intent-label":t.intentLabel=r();break;case"--subscription":throw new Error("--subscription cannot produce a valid credentialless Codex fleet artifact; run normal per-user Connect enrollment so x-anyray-api-key is available");case"--placeholder":case"--org":throw new Error(`${a} is a legacy no-op for Codex fleet artifacts; omit it and enroll each user`);case"--help":case"-h":t.help=!0;break;default:throw new Error(a.startsWith("-")?`unknown option: ${a}`:`unexpected argument: ${a}`)}}return t},FW=e=>{if(!e.gateway?.trim())throw new Error("--gateway is required for static fleet artifacts; local profile and environment values are intentionally ignored.");let t=ln(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:Wa,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},zE=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??bW,o=n.writeFile??kW;await r(AW(t),{recursive:!0}),await o(t,e)},BW=(e,t,n,r,o)=>{o.write(`This artifact requires the credential helper at ${n}; the artifact does not install or update it. Deploy a stable anyray-connect binary through your software-distribution system first, then install/package the helper with:
|
|
565
565
|
`),o.write(r==="windows"?` anyray-connect desktop helper --write --platform windows --bin "C:\\Program Files\\Anyray\\anyray-connect.exe" --path "${n}"
|
|
566
566
|
`:` sudo anyray-connect desktop helper --write --platform posix --bin /usr/local/bin/anyray-connect --path '${n.replace(/'/g,`'"'"'`)}'
|
|
567
567
|
`),e==="codex"?o.write(`Non-MDM Codex fleets can place this TOML at /etc/codex/managed_config.toml on Unix or %ProgramData%\\OpenAI\\Codex\\managed_config.toml on Windows.
|
|
568
568
|
`):t==="json"&&o.write(`Deploy this file to /etc/claude-desktop/managed-settings.json.
|
|
569
|
-
`)},
|
|
569
|
+
`)},UW=e=>{e.write(`This artifact is a stable MDM trust anchor; it contains no inference credential. Claude Desktop authenticates the user and fetches the effective configuration from the bootstrap service at launch.
|
|
570
570
|
`),e.write(`Update the bootstrap response instead of redeploying MDM. Claude polls every 30 minutes, then applies changed values on the next Claude Desktop launch; no managed action is required for each policy update.
|
|
571
571
|
`),e.write(`Each bootstrap response replaces the allowed managed configuration; omitted keys are unset.
|
|
572
|
-
`)},
|
|
572
|
+
`)},HW=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??co)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
|
|
573
573
|
${o.remedy}
|
|
574
574
|
`),1;let a=o.lanes.reduce((c,l)=>c+l.migrated,0),s=o.portableAssets.reduce((c,l)=>c+l.migrated,0),i={code:"Claude Code sessions",cowork:"Cowork tasks"};for(let c of o.lanes){let l=[c.alreadyPresent>0?`${c.alreadyPresent} already there`:"",c.skippedNoTranscript>0?`${c.skippedNoTranscript} skipped, transcript no longer on disk`:"",c.failed>0?`${c.failed} failed`:""].filter(Boolean);n.write(` ${i[c.lane]}: ${c.migrated} migrated`+(l.length>0?` (${l.join("; ")})`:"")+`
|
|
575
575
|
`)}for(let c of o.portableAssets){let l=c.migrated+c.alreadyPresent,d=c.conflicts+c.invalid+c.failed;if(l+d===0)continue;let u=c.kind==="skill"?"User-created skills":c.kind==="plugin"?"User-installed plugins":"Local MCP servers";n.write(` ${u}: ${c.migrated} migrated`+(c.alreadyPresent>0?` (${c.alreadyPresent} already there)`:"")+(d>0?` (${d} preserved or skipped)`:"")+`
|
|
@@ -580,10 +580,10 @@ Reopen Claude Desktop \u2014 migrated ${c} available in the Anyray profile.
|
|
|
580
580
|
Your previous profile is untouched, so \`desktop disconnect\` still works.
|
|
581
581
|
`)}else n.write(`
|
|
582
582
|
Nothing new to migrate \u2014 no local sessions or portable local data needed copying.
|
|
583
|
-
`);return n.write(" claude.ai chats live on your account, not this machine: bring those\n over with `anyray-connect history restore <export.zip>`.\n"),0},
|
|
584
|
-
`),0}if(!a.helperPath?.trim())throw new Error(`--helper-path is required for fleet artifacts. Deploy it first with \`anyray-connect desktop helper --write\`; use ${
|
|
583
|
+
`);return n.write(" claude.ai chats live on your account, not this machine: bring those\n over with `anyray-connect history restore <export.zip>`.\n"),0},QE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=xW(e);if(o[0]==="helper")return YE(o.slice(1),t);let a=MW(o);if(a.help)return n.write(vW),0;let s=a.bootstrapUrl!==void 0||a.bootstrapOidc!==void 0||a.deploymentOrganizationUuid!==void 0;if(s){if(a.target!=="claude")throw new Error("--bootstrap-url is for Claude Desktop only.");if(a.migrate)throw new Error("Bootstrap options emit an MDM artifact; they cannot be combined with --migrate.");if(!a.artifact)throw new Error("--bootstrap-url requires --mobileconfig, --reg or --json to emit the trust anchor.");if(a.bootstrapUrl===void 0){let u=a.bootstrapOidc!==void 0?"--bootstrap-oidc":"--deployment-organization-uuid";throw new Error(`${u} requires --bootstrap-url.`)}if(a.helperPath!==void 0)throw new Error("--bootstrap-url cannot be combined with --helper-path; the bootstrap response supplies the effective inference configuration.");if(a.gateway!==void 0)throw new Error("--bootstrap-url cannot be combined with --gateway; return the inference gateway URL from the bootstrap response.");if(a.team!==void 0||a.intent!==void 0||a.intentLabel!==void 0)throw new Error("--bootstrap-url cannot be combined with --team or --intent flags; return per-user attribution from the bootstrap response.")}if(a.migrate){if(a.artifact)throw new Error("--migrate moves this machine's own sessions; drop --reg/--mobileconfig.");if(a.target==="codex")throw new Error("`desktop --migrate` applies only to Claude Desktop.");return await HW(a,t)}if(a.target==="codex"&&a.artifact==="reg")throw new Error("Codex fleet config does not use a Windows .reg file.");if(a.target==="codex"&&a.artifact==="json")throw new Error("Codex fleet config is managed_config.toml, not Claude's Linux managed-settings.json.");if(a.target==="claude"&&!a.artifact)throw new Error("Local Claude Desktop connect/disconnect is owned by the main Connect lifecycle.");if(s){let u={url:a.bootstrapUrl,...a.bootstrapOidc===void 0?{}:{oidc:XE(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?DW(u):a.artifact==="json"?PW(u):TW(u);return await zE(f,a.path,t),UW(r),a.path&&n.write(`Wrote ${a.path}
|
|
584
|
+
`),0}if(!a.helperPath?.trim())throw new Error(`--helper-path is required for fleet artifacts. Deploy it first with \`anyray-connect desktop helper --write\`; use ${$d} on macOS/Linux or ${Md} on Windows.`);if(a.target==="claude"&&(a.team!==void 0||a.intent!==void 0||a.intentLabel!==void 0))throw new Error("--team and --intent flags do not belong in a Claude Desktop static artifact; each user's enrolled profile supplies attribution.");let i=a.helperPath,c=a.artifact==="reg"||/^[A-Za-z]:[\\/]/.test(i)?"windows":"posix";if(!Ei(i,c))throw new Error(`--helper-path must be an absolute ${c} path for this artifact.`);if(a.artifact==="mobileconfig"&&c!=="posix")throw new Error("--mobileconfig requires a POSIX --helper-path.");a.artifact==="reg"&&Fd("windows",i);let l=FW(a),d;if(a.target==="claude")d=a.artifact==="reg"?LW(l,i):a.artifact==="json"?_W(l,i):OW(l,i);else{let u=NW(l,i);d=a.artifact==="mobileconfig"?$W(u):u}return await zE(d,a.path,t),BW(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
|
|
585
585
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
586
|
-
`),1}};var
|
|
586
|
+
`),1}};var WW=`anyray-connect retrieve <handle> [--source auto|claude|profile]
|
|
587
587
|
|
|
588
588
|
Print the original content Anyray externalized behind a "\xB7 retrieve ctx_\u2026"
|
|
589
589
|
marker. The content is written to stdout byte-for-byte (no trailing newline
|
|
@@ -593,7 +593,7 @@ Options:
|
|
|
593
593
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
594
594
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
595
595
|
--help Show this help.
|
|
596
|
-
`,
|
|
596
|
+
`,KW=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
|
|
597
597
|
|
|
598
598
|
Semantic search over your externalized tool outputs. Prints one match per line
|
|
599
599
|
to stdout as: handle<TAB>score<TAB>preview. Fetch a full original with
|
|
@@ -604,36 +604,36 @@ Options:
|
|
|
604
604
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
605
605
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
606
606
|
--help Show this help.
|
|
607
|
-
`,
|
|
608
|
-
`),1;let s=await(t.readTarget??rt)(o.source),i=await(t.retrieve??
|
|
607
|
+
`,e0=(e,t)=>{let n={source:"auto",help:!1};for(let r=0;r<e.length;r++){let o=e[r];if(o==="--help"||o==="-h")n.help=!0;else if(o==="--source"){let a=e[++r];if(a!=="auto"&&a!=="claude"&&a!=="profile")throw new Error("--source must be auto, claude, or profile.");n.source=a}else if(o==="--k"&&t){let a=Number(e[++r]);if(!Number.isInteger(a)||a<1||a>20)throw new Error("--k must be an integer between 1 and 20.");n.k=a}else if(!o.startsWith("-")&&n.positional===void 0)n.positional=o;else throw new Error(`Unknown option: ${o}`)}return n},GW=e=>e.replace(/[\t\r\n]+/g," ").trim(),t0=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=e0(e,!1);if(o.help)return n.write(WW),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
|
|
608
|
+
`),1;let s=await(t.readTarget??rt)(o.source),i=await(t.retrieve??ba)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
|
|
609
609
|
`),1)}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
610
|
-
`),1}},
|
|
611
|
-
`),1;let s=await(t.readTarget??rt)(o.source),i=await(t.recall??
|
|
610
|
+
`),1}},n0=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=e0(e,!0);if(o.help)return n.write(KW),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
|
|
611
|
+
`),1;let s=await(t.readTarget??rt)(o.source),i=await(t.recall??wd)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
|
|
612
612
|
`),1;if(i.matches.length===0)return r.write(`No matching externalized outputs found.
|
|
613
|
-
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${
|
|
613
|
+
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${GW(c.preview)}
|
|
614
614
|
`)}return r.write(`Fetch a full original: anyray-connect retrieve <handle>
|
|
615
615
|
`),0}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
616
|
-
`),1}};import{promises as
|
|
616
|
+
`),1}};import{promises as yK}from"node:fs";var Cn=e=>typeof e=="string"?e:"",jW=e=>{let t=Cn(e.text).trim();if(t)return t;let n=e.content;if(!Array.isArray(n))return"";let r=[];for(let o of n){if(!o||typeof o!="object")continue;let a=Cn(o.text).trim();a&&r.push(a)}return r.join(`
|
|
617
617
|
|
|
618
|
-
`).trim()},
|
|
618
|
+
`).trim()},VW=e=>{let t=Cn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},YW=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=jW(r);if(!o)continue;let a=Cn(r.created_at).trim();t.push({role:VW(r),text:o,...a?{createdAt:a}:{}})}return t},Ud=e=>{let t;try{t=JSON.parse(e)}catch{return{ok:!1,conversations:[],skipped:0,message:"the file is not valid JSON"}}let n=Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.conversations)?t.conversations:null;if(!n)return{ok:!1,conversations:[],skipped:0,message:"expected a list of conversations \u2014 is this the conversations.json from a Claude data export?"};let r=[],o=0;for(let a of n){if(!a||typeof a!="object"){o+=1;continue}let s=a,i=YW(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(Cn(s.uuid)||Cn(s.id)).trim(),l=(Cn(s.name)||Cn(s.title)).trim()||"Untitled conversation",d=Cn(s.created_at).trim(),u=Cn(s.updated_at).trim();r.push({uuid:c,title:l,...d?{createdAt:d}:{},...u?{updatedAt:u}:{},messages:i})}return{ok:!0,conversations:r,skipped:o}};import{createHash as dK}from"node:crypto";import{promises as Ii}from"node:fs";import{homedir as l0}from"node:os";import{join as Kd}from"node:path";import{promises as r0}from"node:fs";import Fm from"node:path";var ZW=4e4,XW=16*1024*1024,xi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Hd=async(e,t={})=>{let n=(e??"").trim();if(!n)return xi("","path is required");let r=t.cwd??process.cwd(),o=Fm.resolve(r,n),a=Fm.relative(r,o);if(a.startsWith("..")||Fm.isAbsolute(a))return xi(n,"path is outside the workspace");let s=t.maxBytes??ZW,i;try{let w=await r0.stat(o);if(!w.isFile())return xi(n,"not a regular file");let g=t.maxFileBytes??XW;if(w.size>g)return xi(n,`file too large to read (${w.size} bytes; limit ${g})`);i=await r0.readFile(o,"utf8")}catch(w){return xi(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
|
|
619
619
|
`),l=Math.max(1,t.startLine??1),d=Math.min(c.length,t.endLine??c.length),u=l<=d?c.slice(l-1,d):[],f=u.join(`
|
|
620
620
|
`),p=l<=d?d:l,h=!1,m=!1;if(Buffer.byteLength(f,"utf8")>s){let w=0,g=0;for(let y of u){let b=Buffer.byteLength(y,"utf8")+(g===0?0:1);if(w+b>s)break;w+=b,g+=1}g===0?(f=Buffer.from(u[0]??"","utf8").subarray(0,s).toString("utf8").replace(/\uFFFD$/,""),p=l,h=!0):(f=u.slice(0,g).join(`
|
|
621
|
-
`),p=l+g-1),m=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:m,span:{startLine:l,endLine:p,...h?{partialLine:!0}:{}}}},
|
|
621
|
+
`),p=l+g-1),m=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:m,span:{startLine:l,endLine:p,...h?{partialLine:!0}:{}}}},Bm=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
|
|
622
622
|
${e.content}`;let t=e.span?`lines ${e.span.startLine}-${e.span.endLine}`:"a prefix",n=e.span&&!e.span.partialLine&&e.span.endLine<e.lines?` Continue with anyray_read(path="${e.path}", startLine=${e.span.endLine+1}).`:"";return`${e.path} (truncated \u2014 showing ${t} of ${e.lines}).${n}
|
|
623
|
-
${e.content}`};import{spawn as
|
|
624
|
-
`)){if(r.length>=n)break;if(!o)continue;let a=o.indexOf(":");if(a<=0)continue;let s=o.indexOf(":",a+1);if(s<0)continue;let i=o.slice(0,a).replace(/^\.\//,""),c=Number(o.slice(a+1,s));if(!Number.isInteger(c)||c<=0)continue;let l=o.slice(s+1);r.push({file:i,line:c,text:
|
|
625
|
-
`);for(let S=0;S<v.length;S+=1){let E=c(v[S]);if(l.some(x=>E.includes(x))&&(u.push({file:
|
|
623
|
+
${e.content}`};import{spawn as JW}from"node:child_process";import{promises as Um}from"node:fs";import Hm from"node:path";var Wm=400,zW=240,qW=4e3,QW=4e3,eK=512*1024,tK=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),a0=(e,t)=>e.length>t?e.slice(0,t):e,nK=new Set(["a","about","an","and","are","as","at","be","been","but","by","can","could","did","do","does","for","from","had","has","have","here","how","if","in","is","it","me","my","of","on","or","our","should","so","that","the","their","there","this","to","us","was","we","were","what","when","where","which","who","why","with","would","you","your"]),rK=8,oK=2e3,aK=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],sK=e=>{let t=e.toLowerCase(),n=t.split(/[\\/]/).pop()??t;return/(^|[\\/])\.(ssh|aws|gnupg)([\\/]|$)/.test(t)||n.startsWith(".env")||n.startsWith("id_rsa")||n.startsWith("id_ed25519")||/\.(pem|key|p12|pfx)$/.test(n)?!0:n.includes("secret")||n.includes("credential")},s0=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!nK.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=rK))break}return n},i0=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},iK=(e,t,n)=>{if(t.length<2)return e;let r=n?t:t.map(a=>a.toLowerCase()),o=a=>{let s=n?a.text:a.text.toLowerCase(),i=0;for(let c of r)s.includes(c)&&(i+=1);return i};return e.map((a,s)=>({m:a,i:s,s:o(a)})).sort((a,s)=>s.s-a.s||a.i-s.i).map(a=>a.m)},o0=(e,t,n)=>{let r=[];for(let o of e.split(`
|
|
624
|
+
`)){if(r.length>=n)break;if(!o)continue;let a=o.indexOf(":");if(a<=0)continue;let s=o.indexOf(":",a+1);if(s<0)continue;let i=o.slice(0,a).replace(/^\.\//,""),c=Number(o.slice(a+1,s));if(!Number.isInteger(c)||c<=0)continue;let l=o.slice(s+1);r.push({file:i,line:c,text:a0(l,t)})}return r},cK=(e,t,n,r,o,a,s)=>new Promise(i=>{let c=["--line-number","--no-heading","--color","never","--max-columns",String(o),"--max-columns-preview","--smart-case","--max-count","20","--fixed-strings"];for(let h of n)c.push("-g",h);for(let h of aK)c.push("-g",h);if(s?.length){for(let h of s)c.push("-e",h);c.push("--",".")}else c.push("--",e,".");let l;try{l=JW("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,f=h=>{u||(u=!0,clearTimeout(p),i(h))},p=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let h=o0(d,o,r);f({ok:!0,matches:h,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",h=>{if(d+=h,d.length>r*(o+64))try{l.kill("SIGKILL")}catch{}}),l.on("error",()=>{f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"})}),l.on("close",h=>{if(typeof h=="number"&&h>=2){f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let m=o0(d,o,r+1),w=m.length>r;f({ok:!0,matches:w?m.slice(0,r):m,truncated:w,engine:"ripgrep"})})}),lK=async(e,t,n,r,o,a,s)=>{let i=i0(s?.length?s:e),c=m=>i?m:m.toLowerCase(),l=(s?.length?s:[e]).map(c),d=n.map(m=>m.replace(/^\*+/,"")).filter(m=>m.startsWith(".")),u=[],f=0,p=!1,h=async m=>{if(u.length>=r||Date.now()>a){p=!0;return}let w;try{w=await Um.readdir(m,{withFileTypes:!0})}catch{return}for(let g of w){if(u.length>=r||Date.now()>a){p=!0;return}let y=Hm.join(m,g.name);if(g.isDirectory()){if(tK.has(g.name))continue;await h(y)}else if(g.isFile()){if(f>=QW){p=!0;return}if(d.length&&!d.some(S=>g.name.endsWith(S))||sK(Hm.relative(t,y)))continue;f+=1;let b;try{if((await Um.stat(y)).size>eK)continue;b=await Um.readFile(y,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let v=b.split(`
|
|
625
|
+
`);for(let S=0;S<v.length;S+=1){let E=c(v[S]);if(l.some(x=>E.includes(x))&&(u.push({file:Hm.relative(t,y),line:S+1,text:a0(v[S],o)}),u.length>=r)){p=!0;return}}}}};return await h(t),{ok:!0,matches:u,truncated:p,engine:"walk"}},Wd=async(e,t={})=>{let n=e.trim();if(!n)return{ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"query is required"};let r=t.cwd??process.cwd(),o=t.globs??[],a=t.maxMatches??Wm,s=t.maxColumns??zW,i=t.timeoutMs??qW,c=Date.now()+i,l=s0(n),d=l.length>1,u=Math.min(a*4,oK),f=(g,y)=>lK(n,r,o,g,s,c,y),p=async g=>{let y=await g(u,l);if(!y.ok)return y;let b=iK(y.matches,l,i0(l)),v=b.length>a;return{...y,matches:v?b.slice(0,a):b,truncated:y.truncated||v,matched:"tokens",tokens:l}};if(t.engine==="walk"){let g=await f(a);return g.matches.length>0||!d?g:p((y,b)=>f(y,b))}let h=(g,y)=>cK(n,r,o,g,s,Math.max(0,c-Date.now()),y),m=await h(a);if(m.ok){if(m.matches.length>0||!d)return m;let g=await p((y,b)=>h(y,b));return g.ok?g:p((y,b)=>f(y,b))}let w=await f(a);return w.matches.length>0||!d?w:p((g,y)=>f(g,y))},c0=(e,t,n="full")=>{if(!t.ok)return`Search failed: ${t.message??"unknown error"}`;if(t.matches.length===0){if(t.truncated)return`Search for "${e}" hit its time limit before finishing, and found nothing in what it covered. This is NOT proof the term is absent \u2014 narrow it with globs (e.g. ["*.ts"]) and search again.`;let d=s0(e).length>1?" Searched the phrase and each word separately. Try one identifier on its own (a function, type, or error string), or narrow with globs.":" Try a shorter or differently-cased fragment, or narrow with globs.";return`No matches for "${e}".${d}`}let r=t.matched==="tokens"&&t.tokens?.length?`No line contains "${e}"; showing lines matching its terms (${t.tokens.join(", ")}), most complete first.
|
|
626
626
|
`:"";if(n==="paths"){let d=new Map;for(let f of t.matches)d.set(f.file,(d.get(f.file)??0)+1);let u=[...d].map(([f,p])=>`${f} (${p} match${p===1?"":"es"})`);return[`${r}${d.size}${t.truncated?"+":""} file${d.size===1?"":"s"} match "${e}":`,...u].join(`
|
|
627
627
|
`)}let o=`${r}${t.matches.length}${t.truncated?"+":""} matches for "${e}":`,a=t.matches.map(d=>n==="lines"?`${d.file}:${d.line}`:`${d.file}:${d.line}: ${d.text}`),s=d=>`\u2026 ${d} more match${d===1?"":"es"} not shown (output limit). Narrow with globs or a more specific query, or set resultShape:"paths" to see every file.`,i=s(a.length).length+1,c=o.length,l=0;for(let d of a){if(c+1+d.length+i>4e4)break;c+=1+d.length,l+=1}return l>=a.length?[o,...a].join(`
|
|
628
628
|
`):[o,...a.slice(0,Math.max(1,l)),s(a.length-Math.max(1,l))].join(`
|
|
629
|
-
`)};var
|
|
629
|
+
`)};var d0=448,uK=384,pK=4e4,Rr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=Kd(l0(),".anyray");try{if((await Ii.stat(t)).isDirectory())return Kd(t,"history")}catch{}return Kd(l0(),".anyray-history")},fK=e=>{let t=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),n=(e.createdAt??"").slice(0,10),r=(e.uuid||"").replace(/[^a-zA-Z0-9-]/g,"").slice(0,65),o=r.length>0&&r.length<=64?r:hK(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},hK=e=>{let t=dK("sha256");t.update(e.title),t.update("\0"),t.update(e.createdAt??""),t.update("\0");for(let n of e.messages)t.update(n.role),t.update("\0"),t.update(n.text),t.update("\0");return t.digest("hex").slice(0,16)},mK=e=>{let t=[`# ${e.title}`,"",e.createdAt?`- Created: ${e.createdAt}`:"",e.updatedAt?`- Updated: ${e.updatedAt}`:"",e.uuid?`- Claude conversation id: ${e.uuid}`:"",""].filter((r,o,a)=>!(r===""&&a[o-1]==="")),n=e.messages.map(r=>{let o=r.role==="user"?"User":"Claude",a=r.createdAt?` (${r.createdAt})`:"";return`## ${o}${a}
|
|
630
630
|
|
|
631
631
|
${r.text}
|
|
632
632
|
`});return[...t,...n].join(`
|
|
633
633
|
`).replace(/\n{3,}/g,`
|
|
634
634
|
|
|
635
635
|
`)+`
|
|
636
|
-
`},
|
|
636
|
+
`},Gd=async e=>{let t=await Rr();await Ii.mkdir(t,{recursive:!0,mode:d0});try{await Ii.chmod(t,d0)}catch{}let n=0,r=0;for(let o of e)try{await Ii.writeFile(Kd(t,fK(o)),mK(o),{mode:uK}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Pa=async()=>{try{let e=await Rr();return(await Ii.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},u0=async e=>{let t=await Rr();return Wd(e,{cwd:t,globs:["*.md"]})},p0=async e=>{let t=await Rr();return Hd(e,{cwd:t,maxBytes:pK})};var f0=`anyray-connect history <command>
|
|
637
637
|
|
|
638
638
|
Make past Claude conversations searchable from any Anyray-connected client.
|
|
639
639
|
|
|
@@ -654,7 +654,7 @@ Which one you want:
|
|
|
654
654
|
conversation into the chat when you ask for it. Recall, not a list.
|
|
655
655
|
|
|
656
656
|
Running both is fine, and gets you both.
|
|
657
|
-
`,
|
|
657
|
+
`,gK=async e=>{try{return{raw:await yK.readFile(e,"utf8")}}catch(t){let n=t?.code;return n==="ENOENT"?{error:`no such file: ${e}`}:n==="EACCES"?{error:`not readable: ${e}`}:n==="EISDIR"?{error:`${e} is a directory \u2014 point at the conversations.json inside it`}:{error:`could not read ${e} (${n??"read failed"})`}}},wK=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return O("Usage: anyray-connect history import <conversations.json>"),k(C("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await gK(t);if("error"in n)return O(n.error),1;let r=Ud(n.raw);if(!r.ok)return O(`Could not read that export: ${r.message??"unrecognized format"}`),k(C("Expected the conversations.json from a Claude data export (claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data).")),1;if(r.conversations.length===0)return O("That export contains no conversations with readable messages."),1;let o;try{o=await Gd(r.conversations)}catch(a){let s=a?.code;return O(`Could not create the history archive (${s??"write failed"}).`),k(C("Check that ~/.anyray is a writable directory, then try again.")),1}return $(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&k(C(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&N(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),k(""),k(j("Your history is now searchable from any Anyray-connected client.")),k(C(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),k(C(" and the assistant can search this archive and pull it up.")),k(C(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),k(C(" for them, they do not reappear as a clickable list in the app.")),0},bK=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return O("Usage: anyray-connect history restore <export.zip>"),k(C("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await Fl(t);return n.ok?($(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&k(C(` ${n.skipped} already present, left untouched.`)),n.failed>0&&N(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),k(""),k(j("Open Claude Desktop \u2014 they are in the sidebar again.")),k(C(" Anyray stays configured; this changed nothing about your routing.")),k(C(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),k(C(" undocumented. A future Desktop release could stop reading it \u2014 your export")),k(C(" file still works, and `history import` remains a second copy.")),0):(O(`Could not restore into Claude Desktop: ${n.reason}`),k(C(` ${n.remedy}`)),1)},kK=async()=>{let e=await Rr(),t=await Pa();return t===0?(k(`No conversations imported yet. Archive would live at ${e}`),k(C(" Import one with: anyray-connect history import <conversations.json>")),0):($(`${t} conversation${t===1?"":"s"} in ${e}`),0)},h0=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(f0),0):t==="import"?wK(e.slice(1)):t==="restore"?bK(e.slice(1)):t==="status"?kK():(O(`Unknown history command: ${t}`),console.log(f0),1)};import{promises as AK}from"node:fs";var CK=`anyray-connect migrate [options]
|
|
658
658
|
|
|
659
659
|
Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
|
|
660
660
|
|
|
@@ -683,48 +683,50 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
|
|
|
683
683
|
Open claude.ai -> Settings -> Privacy -> Export data. Anthropic emails a link.
|
|
684
684
|
Pass the .zip to --export, and the conversations.json inside it to
|
|
685
685
|
--conversations. Both are safe to re-run; they skip what is already there.
|
|
686
|
-
`,
|
|
687
|
-
`).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${
|
|
686
|
+
`,vK=e=>{let t={allAccounts:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--export")t.exportZip=e[++n];else if(r==="--conversations")t.conversations=e[++n];else if(r==="--account")t.account=e[++n];else if(r==="--all-accounts")t.allAccounts=!0;else if(r==="--help"||r==="-h")t.help=!0;else if(!(r==="--yes"||r==="-y"))if(!r.startsWith("-")&&!t.exportZip)r.endsWith(".json")?t.conversations=r:t.exportZip=r;else throw new Error(`unexpected argument: ${r}`)}return t},m0={code:"Claude Code sessions",cowork:"Cowork tasks"},SK=e=>{let t=[e.alreadyPresent>0?`${e.alreadyPresent} already there`:"",e.skippedNoTranscript>0?`${e.skippedNoTranscript} skipped, transcript no longer on disk`:"",e.failed>0?`${e.failed} failed`:""].filter(Boolean);return`${m0[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},EK=async(e,t)=>{k(j("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??co)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){O(` ${n.reason}`);for(let s of n.remedy.split(`
|
|
687
|
+
`).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${SK(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";k(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&N(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&N(` Claude Desktop has more than one target ${r.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run this again.`);let o=n.retryableAssets??[];o.length>0&&N(` ${o.length} portable configuration ${o.length===1?"type needs":"types need"} another local-copy attempt; no existing target entry was replaced.`);for(let s of n.blocked??[])N(` ${m0[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${bh(s.reason,s.lane,"anyray-connect migrate")}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&k(C(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},xK=async(e,t)=>{if(k(""),k(j("2. Your claude.ai chats")),t){k(C(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){k(" These live on your Claude account, not this machine, so they need"),k(" an export. Anyray cannot fetch them: the only credential that could"),k(" is your claude.ai session, which Connect never holds."),k(C(" claude.ai -> Settings -> Privacy -> Export data, then:")),k(C(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await Fl(e.exportZip);if(!n.ok){O(` ${n.reason}`),k(` ${n.remedy}`);return}$(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),k(C(" They are listed under Cowork \u2014 the Chat tab has no local store."));let r=n.projects;if(r.imported+r.alreadyPresent+r.skippedCollision+r.failed>0){let a=[r.alreadyPresent>0?`${r.alreadyPresent} already there`:"",r.skippedCollision>0?`${r.skippedCollision} skipped, a folder of that name already exists`:"",r.failed>0?`${r.failed} failed`:""].filter(Boolean);$(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&k(C(` Instructions and docs are in ${r.root}, listed under Projects.`))}},IK=async e=>{if(k(""),k(j("3. Searchable from every Anyray client")),!e.conversations){let o=await Pa();o>0?k(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(k(C(" Optional. Pass the conversations.json inside the export:")),k(C(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await AK.readFile(e.conversations,"utf8")}catch{O(` could not read ${e.conversations}`);return}let n=Ud(t);if(!n.ok){O(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Gd(n.conversations);$(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),k(C(` Ask any Anyray-connected client about a past chat. ${await Rr()}`))},RK=e=>{k(""),k(j("Next")),k(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||N(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),k(C(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},y0=async(e,t={})=>{let n;try{n=vK(e)}catch(o){return O(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(CK),0;k(j("Migrating Claude Desktop onto Anyray")),k(C("Claude Desktop must be fully quit.")),k("");let r=await EK(n,t);return await xK(n,!r),await IK(n),r?(RK(n),0):(k(""),N("Fix the item above and re-run to finish the migration."),1)};var OK=3e3,jd=async(e,t={})=>{let n=t.timeoutMs??OK,r=`${e}/`,o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await fetch(r,{method:"GET",signal:o.signal});return s.ok?{reachable:!0,detail:`responded ${s.status}`}:{reachable:!1,detail:`responded ${s.status} at ${r} \u2014 a healthy gateway answers 200 there`}}catch(s){return{reachable:!1,detail:s instanceof Error&&s.name==="AbortError"?`no response within ${n}ms`:wt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};var _K="enl_",TK="enp_",g0=e=>e.startsWith(_K)||e.startsWith(TK),PK=/^\/enroll\/([^/]+)\/?$/,LK=/^\/i\/([^/]+)\/?$/,w0=e=>{let t=e.match(PK);if(t)return t[1];let n=e.match(LK);return n&&g0(n[1])?n[1]:void 0},DK=1e4,Vd=e=>{let t=e.trim();if(!t)return;let n;try{n=new URL(t)}catch{n=void 0}if(n){if(n.protocol!=="http:"&&n.protocol!=="https:")return;let r=w0(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}return{cpOrigin:Gn(),token:t}},Oi=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:w0(n.pathname)!==void 0}catch{return g0(t)}},Ri=e=>typeof e=="string"&&e.trim()?e.trim():void 0,b0=async(e,t={})=>{let n=t.timeoutMs??DK,r=`${e.cpOrigin}/enroll-info/${e.token}`,o=new AbortController,a=setTimeout(()=>o.abort(),n),s;try{s=await fetch(r,{method:"GET",signal:o.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${n}ms.`:wt(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${f}`)}finally{clearTimeout(a)}if(!s.ok)throw new Error(`enrollment link lookup failed: ${e.cpOrigin} responded ${s.status} \u2014 the link may be expired or revoked; ask your admin for a fresh one.`);let i;try{i=await s.json()}catch{throw new Error(`enrollment link lookup failed: ${e.cpOrigin} returned a malformed response`)}let l=(Array.isArray(i?.gateways)?i.gateways:[]).find(u=>u!==null&&typeof u=="object"&&Ri(u.url)!==void 0),d=Ri(l?.url);if(!d)throw new Error(i.connected===!0?"this enrollment link's gateway is running but hasn't advertised its public URL yet \u2014 ask your admin to set ANYRAY_GATEWAY_PUBLIC_URL (Helm: gateway.publicUrl), then re-run.":"this enrollment link has no gateway configured yet \u2014 ask your admin to confirm the gateway is deployed, then re-run.");return{gatewayUrl:d,deploymentId:Ri(l?.deploymentId),org:Ri(i.org),email:Ri(i.email),seatMode:i.seatMode===!0}};var k0=()=>Em(),A0=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??k0)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},NK=e=>{let t=String(e),n=[];for(let r=0;r<t.length;r++)t[r]==="\x1B"&&t[r+1]==="["&&t[r+2]?(n.push(t.slice(r,r+3)),r+=2):n.push(t[r]);return n},C0=async(e,t={})=>{let n=(t.openInput??k0)(),r=n.stream,o=t.output??process.stderr;if(typeof r.setRawMode!="function")throw n.close(),new Error("raw terminal input is unavailable");let a=e.items.map(h=>h.selected===!0&&h.requiresExplicitChoice!==!0),s=0,i=0,c=xa(o,t.env??process.env),l=(h,m)=>c?`\x1B[${h}m${m}\x1B[0m`:m,d=()=>{let h=[l("1",e.title)];for(let m=0;m<e.items.length;m++){let w=e.items[m],g=m===s?l("36","\u276F"):" ",y=e.single?a[m]?"(\u25CF)":"(\u25CB)":a[m]?"[x]":"[ ]",b=w.hint?` ${l("2",w.hint)}`:"";h.push(`${g} ${y} ${w.label}${b}`)}h.push(l("2",e.single?"\u2191/\u2193 move \xB7 space choose \xB7 enter accept \xB7 q cancel":"\u2191/\u2193 move \xB7 space toggle \xB7 a toggle all \xB7 enter accept \xB7 q cancel")),i>0&&o.write(`\x1B[${i}A`),o.write(h.map(m=>`\r\x1B[2K${m}`).join(`
|
|
688
688
|
`)),o.write(`
|
|
689
689
|
`),i=h.length},u=()=>{i!==0&&(o.write(`\x1B[${i}A`),o.write(Array.from({length:i},()=>`\r\x1B[2K
|
|
690
|
-
`).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,p=!1;try{return p=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((h,m)=>{let w=()=>{r.off("data",S),r.off("end",b),r.off("close",b),r.off("error",v)},g=E=>{w(),h(E)},y=E=>{w(),m(E)},b=()=>g({kind:"cancelled"}),v=E=>y(E),S=E=>{try{for(let x of
|
|
691
|
-
`)&&g({kind:"ok",values:[]});continue}if(x==="\x1B[A"||x==="k")s=(s-1+e.items.length)%e.items.length,d();else if(x==="\x1B[B"||x==="j")s=(s+1)%e.items.length,d();else if(x===" "){if(e.single){let A=!a[s];a.fill(!1),a[s]=A}else a[s]=!a[s];d()}else if(x==="a"&&!e.single){let A=e.items.map((
|
|
692
|
-
`){g({kind:"ok",values:e.items.filter((A,I)=>a[I]).map(A=>A.value)});return}}}catch(x){y(x)}};r.on("data",S),r.on("end",b),r.on("close",b),r.on("error",v)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),p&&r.setRawMode(f)}catch{}n.close()}};var
|
|
693
|
-
`),t();let a=0,s=()=>{r.write(`\r${
|
|
694
|
-
`)){let[r,o]=n.trim().split(/\s+/);if(!r||!o)continue;if((o.startsWith("*")?o.slice(1):o)===t&&/^[0-9a-f]{64}$/i.test(r))return r.toLowerCase()}},w0=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&&La(e.current,e.minVersion)<0&&La(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},_K=e=>La(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}:{...w0(e),downgradeBlocked:!1},Da=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",PK=(e=process.execPath)=>{let t=Ru(e);return t?Or(t):Or(Or(e))},TK=async(e=mt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=pt(PK(e.execPath),"bin",Da());try{if(await Yd(t)!==await Yd(e.execPath))return}catch{return}return t},Zm=async(e=mt(),t=q())=>{let n=await TK(e);if(n)return{kind:"managed",root:Or(Or(n)),link:n,entryPath:Xn(e)};let r=Xn(e);return Pu(r,t)?{kind:"durable",root:t,entryPath:r}:Iu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},Xd=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)}},Xm=async(e=Zd)=>{let t=await Xd(`${m0}/latest`,e,{redirect:"manual"});return RK(t.headers.get("location"))},LK=async e=>{try{let t=await Xd(`${e}/connect-update.json`,Zd);if(!t.ok)return;let n=await t.json();if(!n||typeof n!="object")return;let r=n.minVersion;return typeof r=="string"&&/^\d+\.\d+\.\d+/.test(r)?r:void 0}catch{return}},Ri=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},Jm=async(e,t,n)=>{let r=await Xd(e,xK);if(!r.ok||!r.body)throw new Ri(r.status);let o=AK("sha256"),a=0;if(await vK(CK.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>EK)throw new Error("asset exceeds size cap");o.update(c),yield c}},mK(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},DK=e=>Wm(e)===Da()?Wm(Or(e)):Wm(e),NK=async e=>{let t=await Vm(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await It(pt(e,n),{force:!0}).catch(()=>{})},b0=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await It(r,{force:!0}).catch(()=>{});let o=!1;try{await Vd(e,r),o=!0}catch{}try{await Gm(t,e),await kK(Ya(e),DK(t))}catch(a){throw o&&await Vd(r,e).catch(()=>{}),a}await It(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await It(n,{force:!0}),await bK(t,n),await Vd(n,e)},$K=async(e,t={})=>{let n=pt(e.root,"bin"),r=pt(e.root,"versions"),o=pt(n,Da());await Ta(n,{recursive:!0,mode:448}),await Ta(r,{recursive:!0,mode:448});let a=pt(r,e.version),i=(await jm(a).catch(()=>{}))?.isFile()?a:pt(a,Da());if(!(await jm(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??Xd)(`${e.tagUrl}/SHA256SUMS`,Zd),d=l.ok?Ym(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await Ta(Or(i),{recursive:!0,mode:448}),await NK(Or(i));let u=`${i}.part-${process.pid}`;try{await(t.download??Jm)(`${e.tagUrl}/${e.asset}`,u,d),await gK(u,493),await Vd(u,i)}catch(f){throw await It(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??b0)(o,i),{link:o,target:i,versionsDir:r}},MK=async e=>{let t=yK(e,["--version"],{stdio:"ignore",timeout:Zd});return!t.error&&t.status===0},FK=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??ho)(n);if(r.length>0){let o=await(t.resolveTarget??_e)(async()=>e);if(!o||!(await(t.repair??gt)(r,o.target)).every(fo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??ar)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Pt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},BK=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 Vm(e).catch(()=>[]);for(let r of n)t.includes(r)||await It(pt(e,r),{force:!0,recursive:!0}).catch(()=>{})},HK=async e=>{let t=await Vm(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await It(pt(e,n),{force:!0}).catch(()=>{})},WK=async(e,t)=>{let n=async()=>{await It(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Ta(e,{recursive:!1}),n}catch{}let r=await wK(e).catch(()=>{});if(!(!r||t-r.mtimeMs<OK)){await n();try{return await Ta(e,{recursive:!1}),n}catch{return}}},Km=e=>pt(e,"update-state.json"),KK=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}},GK=1e3,jK=16*6e4,VK=e=>e.inFlight===0,YK=async(e,t,n={})=>{let r=n.probe??be,o=n.sleep??(i=>new Promise(c=>setTimeout(c,i))),a=n.now??Date.now,s=a()+(n.timeoutMs??jK);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&VK(i))return!0;if(a()>=s)return!1;await o(GK)}},_i=async(e={})=>{let t=e.now??Date.now,n=we;if(kt(yt(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??mt(),o=e.root??q(),a;try{let s=await Zm(r,o);if(o=s.root,s.kind==="unmanaged")return{outcome:"unmanaged",current:n};if(s.kind==="npm"&&!e.allowNpmMigration)return{outcome:"unmanaged",current:n};let i=s.kind!=="managed",c=g0(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Xm)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&La(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await KK(Km(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<IK)return{outcome:"failed",current:n,latest:l};let f=`${m0}/download/${y0}${l}`,p=await(e.load??T)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??LK)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?_K(w):{...w0(w),downgradeBlocked:!1};if(g.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:l};if(!g.apply)return{outcome:"disabled",current:n,latest:l};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:l,mandatory:g.mandatory};o===q()?await bt():await Ta(o,{recursive:!0,mode:448});let y=await WK(pt(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,v;try{await HK(pt(o,"bin"));let x=await Yd(pt(o,"versions")).catch(()=>{}),A=await Yd(pt(o,"bin",Da())).catch(()=>{}),I=A&&ec(A,x)?A:void 0,R=pt(o,"bin",Da());i&&process.platform==="win32"&&(await jm(R).catch(()=>{}))?.isFile()&&(v=`${R}.rollback-${process.pid}`,await Gm(R,v));let M=()=>(e.installBinary??$K)({root:o,version:l,asset:c,tagUrl:f});i?b=await BK({install:M,smoke:e.smoke,rollback:async({link:X,target:V})=>{v?(await Gm(v,X),await It(Ya(X),{force:!0}).catch(()=>{})):I&&I!==V?await b0(X,I):(await It(X,{force:!0}),await It(Ya(X),{force:!0}).catch(()=>{}))},repoint:async X=>e.repoint?e.repoint(p,X):FK(p),prune:async()=>{await(e.pruneDurable??(X=>tc(X)))(r)}}):b=await M(),await UK(b.versionsDir,[l,n]),await It(Km(o),{force:!0}).catch(()=>{})}finally{v&&await It(v,{force:!0}).catch(()=>{}),await y()}let S=e.bounceDaemon??ju,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let x=p.fallbackPort??ke,A=E?!0:await Zg().catch(()=>!0),I=await S(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!A&&p.gateway&&((I?await(e.waitForDaemon??YK)(x,l):!0)?await Pt({port:x,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??Jg)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await Z(Km(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},k0=async(e={})=>{let t=e.context??mt(),n=await Zm(t,e.root??q()),r=Ro(e.root??q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:we,managedPath:n.link??r}:_i({...e,context:t,allowNpmMigration:!0})},Co=async(e={})=>{let t=e.context??mt(),n=e.root??q(),r=await Zm(t,n),o=r.kind==="npm"||r.kind==="durable"?Ro(n):void 0,a=await(e.load??T)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!g0(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=kt(yt(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:we,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};var ZK=async(e,t)=>{if(!e.gateway||!e.clientKey)return;let n=await t().catch(()=>{});return ye({origin:e.gateway,clientKey:e.clientKey,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:n,user:e.name,team:e.team})},A0=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,XK=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},zm=async(e={})=>{let t=e.load??T,n=e.save??ee,r=e.mutate??(e.load||e.save?XK(t,n):og),o=e.loadDevKey??Fe,a=e.heartbeat??pd,s=e.detectSeat??Tt,i=e.rewriteTools??pi,c=e.uninstallProxy??Xt;try{let l=await t();if(l.credentialProtocol==="stable-heartbeat-v1"&&l.directMigration==="complete")return"already-direct";if(!l.keyRefreshEnabled&&!l.refreshSchedulerEnabled||!l.gateway||!l.clientKey||!l.enrolledCert)return"not-eligible";let d=l.enrolledCert.sig,u=await o();if(!u)return"not-eligible";let f;try{f=await a(l.gateway,l.clientKey,l.enrolledCert,u)}catch(y){return y instanceof Ar&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!A0(y,l))return{result:void 0};let b={...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"pending"};return{next:b,result:b}});if(!p)return"pending";let h=await ZK(p,s);if(!h)return"pending";let m=l.keyRefreshEnabled===!0,w=Number.isInteger(l.fallbackPort)&&l.fallbackPort>0&&l.fallbackPort<=65535?l.fallbackPort:ke;if(m){let y=`http://${ht}:${w}`;if(await i(h,y)===!1)return"pending"}return await r(y=>y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||y.credentialProtocol!=="stable-heartbeat-v1"||y.directMigration!=="pending"||!A0(y,p)?{result:!1}:{next:{...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"complete",keyRefreshEnabled:!1,fallbackPort:void 0},result:!0})?((m||l.fallbackPort!==void 0)&&await c(w).catch(()=>{}),"migrated"):"pending"}catch{return"pending"}};var JK=12e3,zK="anyray-wiring-probe-not-a-real-token",qK={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},Qm={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},vo=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},v0=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},ey=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},C0=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."],QK=e=>e.includes("no provider key configured for"),ty=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},ny=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>"]}),Pi=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."]}),eG=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:e===401||e===403?ty(t)?ny(e):ey(t)?Pi(e):v0(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${vo(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)."]}:QK(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${vo(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")?C0([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${vo(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).",...C0([" \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}: ${vo(t)}`,remedy:[]},tG=(e,t)=>{if(ey(t))return Pi(e);if(ty(t))return ny(e);if(v0(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}: ${vo(t)}`,remedy:[]}},nG=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),rG=(e,t)=>{if(ey(t))return Pi(e);if(ty(t))return ny(e);let n=t.toLowerCase();if(n.includes("bedrock"))return{kind:"routed-elsewhere",detail:"gateway routed to the org provider instead of the configured BYO upstream.",remedy:["Re-run anyray-connect with your --upstream URL and --upstream-key so","the custom-host pass-through pins are restored."]};if(n.includes("invalid custom host")||n.includes("custom_host_blocked")||n.includes("hostname is not authorized"))return{kind:"routed-elsewhere",detail:"gateway rejected the configured BYO upstream before routing to it.",remedy:["Ask the gateway admin to authorize this LiteLLM/upstream hostname in","ANYRAY_CUSTOM_HOST_ALLOWLIST (or TRUSTED_CUSTOM_HOSTS for an internal host)."]};if(e===401||e===403)return{kind:"provider-rejected",detail:`gateway accepted your personal key but the BYO upstream rejected its credential (HTTP ${e}).`,remedy:["Your Anyray enrollment key is fine. The configured personal upstream key","was rejected by the BYO upstream (for example, LiteLLM). Re-run","anyray-connect with a current --upstream-key."]};let r=e>=400&&e<500&&(n.includes("litellm")||nG(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}: ${vo(t)}`,remedy:[`The probe asks for a fixed model (${Qm.model}) your upstream`,"is not required to serve, so a model rejection here does not mean your","tools are broken. Check that the upstream serves it before chasing this."]}},qm=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),r);try{let s=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...t},body:JSON.stringify(n),signal:o.signal});return{status:s.status,bodyText:await s.text()}}finally{clearTimeout(a)}},oG=async(e,t)=>{if(!e.clientKey)return Pi(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?Pi(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${vo(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},aG=(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."]}},Ti=async(e,t={})=>{let n=t.timeoutMs??JK,r=le(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await oG(e,n);if(e.byoUpstream){let l={Authorization:`Bearer ${e.byoUpstream.key}`,"anthropic-version":"2023-06-01","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic","x-anyray-custom-host":e.byoUpstream.url};e.clientKey&&(l["x-anyray-api-key"]=e.clientKey),r&&(l["x-anyray-metadata"]=r);let{status:d,bodyText:u}=await qm(`${e.anthropicBaseUrl}/v1/messages`,l,Qm,n);return rG(d,u)}if(J(e,"anthropic")){let l={Authorization:`Bearer ${zK}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"};r&&(l["x-anyray-metadata"]=r),e.clientKey&&(l["x-anyray-api-key"]=e.clientKey);let{status:d,bodyText:u}=await qm(`${e.anthropicBaseUrl}/v1/messages`,l,Qm,n);return tG(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await qm(`${e.openaiBaseUrl}/chat/completions`,s,qK,n);return eG(i,c,t.tools??[])}catch(o){return aG(n,o)}};var S0=async e=>{let t=await T(),n;try{n=Er(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),B(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${et(n)}`),t.gateway?B(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?B(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||B(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??C("(not set)")}`),k(` Team: ${t.team??C("(not set)")}`);let r=yt();r&&(K("Environment"),k(` Remote dev context: ${rr(r)}`),kt(r)&&B(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),B(" VS Code tools configure the remote server variant backing this window.")),t.credentialProtocol==="stable-heartbeat-v1"&&(K("Credential renewal"),t.directMigration==="pending"?(k(" Stable-key heartbeat active; direct-routing migration is still completing."),B(" The local proxy remains available until every managed tool moves.")):($(" Direct gateway routing with a proof-backed stable-key heartbeat."),B(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(nt(t)&&t.fallbackPort),a=o?`http://${ht}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await be(t.fallbackPort)?$(` Running on 127.0.0.1:${t.fallbackPort} \u2192 ${n} `+C("(auto-refreshes your key so long sessions never 401)")):(N(` Enabled on 127.0.0.1:${t.fallbackPort} but NOT responding \u2014 your tools cannot reach any gateway until it's back.`),k(C(" Re-run `anyray-connect`, or check the service logs.")))),K("Tools");for(let s of re){if(!(await s.detect()).installed){B(` ${s.title}: not installed`);continue}if(!s.pointsAt){B(` ${s.title}: installed ${C("(status not introspectable)")}`);continue}let c=await s.pointsAt(vi(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){$(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(C(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}$(` ${s.title}: pointed at Anyray${o&&Ci(s.id)?C(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===Ra&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await Pd();l=Td({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:f.authoritative}),d={...f.authoritative?{}:{reason:f.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=Ld(l,d);N(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(C(` ${f}`))}else B(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as uG}from"node:fs";import{isAbsolute as pG}from"node:path";import{access as sG}from"node:fs/promises";import{constants as iG}from"node:fs";import{platform as cG}from"node:os";var lG=async e=>{try{return await sG(e,iG.F_OK),!0}catch{return!1}},dG=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"]:[],Na=async(e={})=>{let t=e.os??cG(),n=e.exists??lG;for(let r of dG(t))if(await n(r))return!0;return!1};var an="connect",ry=e=>e.replace(/-/g,"_"),E0=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:an,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:an,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:an,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:an,checkId:"fallback_proxy",status:e.fallbackProxy.healthy===!1?"fail":e.fallbackProxy.healthy===!0?"ok":"unknown"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:an,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:an,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=ry(e.retrieval.kind);t.push({tool:an,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":ry(e.verify.kind);t.push({tool:an,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:an,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:ry(e.hookLane.reason)}:{}})}t.push({tool:an,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:an,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function fG(){return we}var hG="ctx_doctor-probe-synthetic",mG=(e,t={mode:"unknown",ssoLink:null})=>{if(e.ok||e.kind==="not-found")return{kind:"ok",detail:"Retrieval loop healthy: gateway answered, key authorized, optimizer retrieval wired.",remedy:[]};switch(e.kind){case"auth":return{kind:"auth",detail:"The gateway rejected the retrieval call (no valid personal key).",remedy:[`Fix: ${sy(t.mode,t.ssoLink)}, or set ANYRAY_CLIENT_KEY.`,"Retrieval needs a personal key \u2014 the MCP server hits the same wall, so externalized output is unretrievable until this is fixed."]};case"unsupported":return{kind:"unsupported",detail:"The gateway has no /connect/retrieve route.",remedy:["Fix: update the gateway image \u2014 this one predates the retrieval loop."]};case"timeout":case"network":return{kind:"unreachable",detail:`Could not reach the gateway for the retrieval probe (${e.kind}).`,remedy:["Fix: check the gateway origin and network (see the Gateway section above)."]};default:return{kind:"unavailable",detail:e.message,remedy:["Fix: the gateway answered but retrieval is unavailable \u2014 usually the optimizer is down or ANYRAY_OPTIMIZER_URL is unset on the gateway. Check the optimizer service."]}}};function yG(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function gG(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function sy(e,t){let n=`\`anyray-connect --sso ${t??"<link>"}\``,r="`anyray-connect --enroll <link>`";switch(e){case"sso":return`enroll via SSO with ${n}`;case"passwordless":return`enroll with the link from your admin (${r})`;default:return`enroll \u2014 SSO org: use ${n}; passwordless org: use ${r} (link from your admin)`}}var x0=e=>Td({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),oy=e=>e.pointedAt===!1&&e.tombstoned!==!0&&x0(e)!=="unverifiable",I0=e=>e.registered&&e.command&&pG(e.command)?uG(e.command):null,ay=e=>(oy(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),wG=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,bG=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},O0=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},kG=(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(go),s=[],i=n(e.selfcheck?.adapters)?e.selfcheck.adapters:{};for(let[c,l]of Object.entries(i)){if(!o.has(c)||!n(l))continue;let d=n(l.lastRepaired)?l.lastRepaired:{},u=Object.entries(d).filter(w=>a.has(w[0])&&r(w[1])).map(([w,g])=>({checkId:w,at:g})),f=n(l.flapping)?l.flapping:void 0,p=Array.isArray(f?.checks)?f.checks.filter(w=>typeof w=="string"&&a.has(w)):[],h=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,m=f&&r(f.since)&&h&&p.length>0?{since:f.since,reason:h,checks:p}:void 0;(u.length>0||m)&&s.push({tool:c,repaired:u,...m?{flapping:m}:{}})}return s},AG=async(e,t,n,r,o,a,s=n,i=Ti,c=!0,l=ko,d=Co,u=Ut,f=ba)=>{let p=c?await Kd(e):null,h=!!(nt(t)&&t.fallbackPort),m=h?await be(t.fallbackPort):null,w=h?`http://${ht}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=t.enrolledCert?.payload,b=y?.expiresAt??t.enrolledCertExpiry??null,S=(await a())?.sso??null,E=gG({ssoLink:S,enrolledViaToken:!!t.enrolledTokenHash}),x=At(),A=await Ew(x),I=A?[]:_w(ye({origin:w})),R=[];for(let Y of r){let De=await Y.detect(),ft=null;if(De.installed&&Y.mcpStatus)try{let Tr=await Y.mcpStatus();ft={...Tr,commandOk:I0(Tr)}}catch{}let Ve=De.installed&&Y.id===Ra?await o():void 0,Pr=De.installed&&Y.pointsAt?await Y.pointsAt(vi(Y.id,e,w)):null,sn=await wG(Pr,Y,t.managedTools??[]),Wi=Pr===!1&&sn===null,Ba=sn===!1&&Y.routingPendingReload?await Y.routingPendingReload().catch(()=>!1):!1,Ki=De.installed?Y.runtimeDiagnostics?await Y.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:Y.routingOverrides?await Y.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Gi,claudeCodeHookPolicy:Ua}=Ki,pe=t.fleetToolPolicy,tt=pe?.enabled.includes(Y.id)?pe.tiers?.[Y.id]??ya:void 0;R.push({id:Y.id,title:Y.title,installed:De.installed,...De.detail?{detail:De.detail}:{},pointedAt:sn,...Wi?{routingHeld:!0}:{},...Ba?{routingPendingReload:!0}:{},...Gi.length?{routingOverrides:Gi}:{},...Ua===void 0?{}:{claudeCodeHookPolicy:Ua},mcp:ft,...tt?{policyTier:tt}:{},...t.revertedTools?.includes(Y.id)?{tombstoned:!0}:{},...Y.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...Ve===void 0?{}:{inferenceIntrospectable:Ve.authoritative,...Ve.authoritative?{}:{inferenceUnverifiableReason:Ve.reason}}})}let M=s?await(async()=>{let{kind:Y,detail:De,remedy:ft}=await i(ye({origin:e,clientKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey,subscription:t.authMode==="subscription",placeholder:t.authMode==="placeholder",byoUpstream:t.byoUpstream,...t.authMode==="auto"?{seat:{anthropic:!1,openai:!1,copilot:!1}}:{},user:t.name,team:t.team}),{tools:t.managedTools??[]});return{kind:Y,detail:De,remedy:ft}})():null,X=M?.kind==="provider-rejected"&&await bG(t.managedTools??[],r),V=M?{...M,...X?{notApplicableSubscription:!0}:{}}:null,W=n?mG(await wa({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:le({user:t.name,team:t.team})},hG,{probe:!0}),{mode:E,ssoLink:S}):null,z=await u().catch(()=>({})),ve=kn(z.hookLane),je=s?await O0(r):!1,oe=je?await(async()=>{let Y=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...Zh(Y,{hookRegistered:je,neverInvoked:Vh(ve,Date.now())}),lastInvokedAt:hd(ve)}})():null,Me=(await ir()).map(Y=>({adapter:Y.adapter,op:Y.op,requestedAt:Y.requestedAt,watcherAlive:lr(Y.watcherPid)})),xe=Me.find(Y=>Y.adapter==="cursor"),P=xe?{op:xe.op,requestedAt:xe.requestedAt,watcherAlive:xe.watcherAlive}:null,L=!!t.refreshSchedulerEnabled,H=await Ac(),me=await d(),se=t.persistenceOwner==="tray",ge=se?await l(t)==="healthy":null,He=await XS({daemonEnabled:h&&!se,daemonHealthy:h?!!m:null,schedulerEnabled:L&&!se,schedulerInstalled:H,binaryDurable:!Ke(nr())}),ue=await vu(),ie=0;p&&!p.reachable&&(ie+=1),h&&!m&&(ie+=1),se?L&&!ge&&(ie+=1):L&&!H&&(ie+=1);for(let Y of R)ie+=ay(Y);return V&&V.kind!=="ok"&&!V.notApplicableSubscription&&(ie+=1),W&&W.kind!=="ok"&&(ie+=1),oe?.verdict==="dark"&&(ie+=1),I.length>0&&(ie+=1),ie+=Me.filter(Y=>!Y.watcherAlive).length,ue.length>0&&(ie+=1),{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:fG(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:yt(),selfUpdate:{managed:me.managed,available:me.available,autoUpdate:me.autoUpdate,state:me.state}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},toolOrigin:w,fallbackProxy:{enabled:h,port:h?t.fallbackPort:null,healthy:h?!!m:null},refreshScheduler:{enabled:L,installed:H,owner:se?"tray":"os",...se?{trayHealthy:!!ge}:{}},serviceRemoval:He,retiredFallbackState:ue,fleetdPresent:await Na(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null},enrollment:{enrolled:!!y,deploymentId:y?.deploymentId??null,issuedAt:y?.issuedAt??null,expiresAt:b,expired:b?Date.parse(b)<Date.now():null,orgMode:E,ssoLink:S},shell:{profilePath:x,blockPresent:A,staleExports:I},tools:R,...t.fleetToolPolicy?{fleetPlan:id(t,t.fleetToolPolicy,!1)}:{},cursorQueue:P,pendingOps:Me,ambientRepairs:kG(z,r),verify:V,retrieval:W,hookLane:oe,problems:ie}},CG=e=>{if(e.serviceRemoval.suspected){K("Endpoint security"),N(" Anyray installed these background services, but their files are gone from disk \u2014"),N(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),N(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)k(C(` missing: ${t}`));k(C(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(C(" tools straight at the gateway (your key then needs a periodic re-run).")),k(C(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(C(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},vG=e=>{if(e.retiredFallbackState.length!==0){K("Retired fallback lane"),_(" A cached organization provider key from the removed --fallback lane is still on this machine.");for(let t of e.retiredFallbackState)k(C(` ${t}`));k(C(" Fix: `anyray-connect doctor --repair` deletes it (a normal `anyray-connect` run does too)."))}},SG=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${rr(e.connect.remoteContext)}`),kt(e.connect.remoteContext)&&k(C(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),K("CLI updates"),e.connect.selfUpdate.state){case"managed":$(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||N(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":N(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),k(C(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":N(" Self-update is unavailable on this platform because no standalone binary is published."),k(C(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(C(" This copy is externally managed; update it with the method that installed it."));break;case"container":k(C(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(K("Gateway"),e.gateway.reachable===null?k(C(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?$(` Reachable: ${e.gateway.origin} ${C(`(${e.gateway.detail})`)}`):(_(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),k(C(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.fallbackProxy.enabled&&(K("Local key-refresh proxy"),e.fallbackProxy.healthy?$(` Running on 127.0.0.1:${e.fallbackProxy.port} \u2192 ${e.gateway.origin} `+C("(auto-refreshes your key so long sessions never 401)")):(_(` Enabled on 127.0.0.1:${e.fallbackProxy.port} but NOT responding \u2014 your tools point at it and cannot reach any gateway until it's back.`),e.serviceRemoval.kinds.includes("daemon")||k(C(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to point tools straight at the gateway.")))),e.refreshScheduler.enabled&&(K("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?$(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh and supervises the daemon."):(_(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),k(C(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?$(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(_(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||k(C(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),CG(e),vG(e),K("Personal key"),yG(e)){case"env":$(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":$(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":N(" Enrolled, but no personal key is cached locally right now."),k(C(" Fix: re-run `anyray-connect` to re-mint it from your enrollment \u2014 no need to re-enroll. Claude Code and Codex are still attributed to you by name."));break;default:N(" Enrollment required \u2014 no personal gateway key is available."),k(C(` Fix: ${sy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?N(` Enrollment cert expired ${C(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):$(` Enrollment cert valid until ${e.enrollment.expiresAt} ${C(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(K("Shell"),_(" This terminal still exports Anyray, but the config is gone."),k(C(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(C(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(C(" Anything you start from this terminal keeps reaching the gateway with")),k(C(" no credential, and fails with 401.")),k(C(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(C(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(C(" reuses the environment it captured at launch, so a new terminal")),k(C(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};K("Claude Code hook policy"),_(` ${ic(c)}.`),k(C(` ${cc(c)}`))}K("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])_(` ${c.title}: ${l.problem}.`),k(C(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(_(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),k(C(" Fix: re-run `anyray-connect` to re-register the current binary."))):$(` ${c.title}: retrieval MCP server registered ${C("(anyray_retrieve / anyray_recall)")}`):(N(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),k(C(" Fix: re-run `anyray-connect` from a durable install (registration is skipped for one-off npx runs)."))))};for(let c of e.tools){if(!c.installed){k(C(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){k(C(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){$(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),k(C(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}$(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&Ci(c.id)?C(" (via key-refresh proxy)"):""}`),o(c),c.id==="claude-code"&&k(C(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===Ra&&k(C(` ${cA}`)),c.id==="codex"&&k(C(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=x0(c);if(l==="not-routed"||l==="unverifiable"){let d=Ld(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});N(` ${c.title}: ${d.headline}`);for(let u of d.detail)k(C(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(N(` ${c.title}: reverted locally against admin policy (out of compliance)`),k(C(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?N(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):k(C(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(_(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),k(C(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(_(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),k(C(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(N(" No tools are pointed at this gateway yet."),k(C(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){K("Queued operations");for(let c of e.pendingOps){let l=Bt(c.adapter)?.title??c.adapter;c.watcherAlive?N(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(_(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),k(C(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){K("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=Bt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:p,at:h})=>`${c(p)} ${new Date(h).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?N(f):k(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){K("Fleet policy");let c=l=>l.map(d=>Bt(d)?.title??d).join(", ");i.freshIds.length>0&&k(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&N(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(K("Auth probe"),e.verify.notApplicableSubscription)$(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")$(` ${e.verify.detail}`);else{_(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(C(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")$(` ${e.retrieval.detail}`);else{_(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(C(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")$(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(C(` ${c}`))}else{N(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(C(` ${c}`))}e.hookLane.lastInvokedAt!==null&&k(C(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}K("Summary"),e.problems===0?(e.verify?$(" No problems found."):$(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(C(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):_(` ${e.problems} problem(s) found \u2014 see fixes above.`)},EG=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}),xG=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Kh(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??ba,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Qe)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=kn((await(t.readRefreshState??Ut)().catch(()=>({}))).hookLane),l=Zh(i,{hookRegistered:await O0(t.adapters??re).catch(()=>!1),neverInvoked:Vh(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:hd(c)},note:d}},IG=async(e,t,n={})=>{let r=n.adapters??re,o=n.resolveTarget??_e,a=n.applyTools??gt,s=await xG(e,n).catch(()=>null),i=s&&e.hookLane?.verdict==="dark"&&s.hookLane?.verdict==="live"?1:0,c=s?{hookLane:s.hookLane,notes:[s.note]}:{notes:[]},l=e.tools.filter(y=>y.installed&&(oy(y)||y.mcp?.commandOk===!1||y.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t,void 0,be);if(!d)return{entries:l.map(y=>({id:y.id,title:y.title,status:"skipped-not-enrolled"})),remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,`Repair needs an enrolled personal key \u2014 ${sy(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],p=[...c.notes],h=[];for(let y of l){let b=r.find(v=>v.id===y.id);if(!u.has(y.id)||!b){f.push({id:y.id,title:y.title,status:"skipped-unmanaged"});continue}h.push(b)}f.length>0&&p.push("Drifted tools outside the managed record are never auto-repaired \u2014 run `anyray-connect` once to (re)configure and record them.");let m=await a(h,d.target),w=new Map,g=0;for(let y of m){if(f.push(y),!fo(y))continue;let b=e.tools.find(R=>R.id===y.id);if(!b)continue;let v=r.find(R=>R.id===y.id),S=b.mcp;if(v?.mcpStatus)try{let R=await v.mcpStatus();S={...R,commandOk:I0(R)}}catch{}let E=oy(b)?!0:b.pointedAt;if(v?.pointsAt&&b.pointedAt!==null)try{E=await v.pointsAt(vi(v.id,e.gateway.origin,e.toolOrigin))}catch{}let x=b.routingOverrides,A=b.claudeCodeHookPolicy;if(v?.runtimeDiagnostics)try{let R=await v.runtimeDiagnostics();x=R.routingOverrides.length?R.routingOverrides:void 0,A=R.claudeCodeHookPolicy}catch{}else if(v?.routingOverrides)try{let R=await v.routingOverrides();x=R.length?R:void 0}catch{}let I={...b,pointedAt:E,mcp:S,...x?{routingOverrides:x}:{},...A===void 0?{}:{claudeCodeHookPolicy:A}};x||delete I.routingOverrides,A===void 0&&delete I.claudeCodeHookPolicy,w.set(y.id,I),g+=ay(b)-ay(I)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},OG=e=>{K("Repair"),e.entries.length===0&&$(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?$(` ${t.title}: re-applied`):t.status==="queued"?$(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(C(` ${t.title}: ${t.status}`)):_(` ${t.title}: ${t.status}`);for(let t of e.notes)k(C(` ${t}`))},R0=async(e,t={})=>{let n=await T();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of JS(n.fallbackPort??ke))k(c?` ${c}`:"");return 0}let r;try{r=Er(e.gateway,n)}catch(c){return e.json?(console.log(JSON.stringify({error:c.message})),1):(k(j("Anyray connect \u2014 doctor")),_(` Gateway URL: ${c.message}`),k(C(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(k(j("Anyray connect \u2014 doctor")),_(" --quick skips the network probes; it cannot be combined with --verify.")),1;let o=!e.noVerify&&!e.quick,a=await AG(r,n,!!e.verify&&!e.quick,t.adapters??re,t.inferenceIntrospection??Pd,t.fleetBootstrap??Kt,o,t.verifyAuth??Ti,!e.quick,t.checkTray??ko,t.updateStatus??Co,t.readRefreshState??Ut,t.probeHookLane??ba);e.repair&&a.retiredFallbackState.length>0&&(await zi(),a.retiredFallbackState=await vu(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await IG(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;e.json?console.log(JSON.stringify(EG(i),null,2)):(SG(i),s&&OG(s));try{e.quick||await(t.reportHealth??Uv)(E0(i),i.connect.version)}catch{}return i.problems===0?0:1};var RG=()=>{let e=[];for(let t of re){let n=t.skillsDir?.();n&&e.push(n)}return e},_0=async e=>{let t=await T();k(j("Anyray connect \u2014 sync"));let n;try{n=Er(e.gateway,t)}catch(s){return _(s.message),1}B(`Gateway: ${n}`);let r=SE(t.clientKey,"anyray-placeholder"),o;try{o=await ld(n,r)}catch(s){return _(`Team policy sync failed: ${cd(s)}`),1}let a=RG();if(a.length===0)_G();else if(o.skills.length===0)B("No team skills published yet \u2014 nothing to sync.");else{let s=await Av(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?$(` ${i.name} ${C(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):B(` ${i.name} ${C(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await ee({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){B(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await dd(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(k(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&B(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){B(`Fleet policy reconcile skipped: ${cd(s)}`)}return 0},_G=()=>{B("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as Lj}from"node:zlib";import{promisify as Dj}from"node:util";var Rr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},iy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),P0=e=>`
|
|
690
|
+
`).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,p=!1;try{return p=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((h,m)=>{let w=()=>{r.off("data",S),r.off("end",b),r.off("close",b),r.off("error",v)},g=E=>{w(),h(E)},y=E=>{w(),m(E)},b=()=>g({kind:"cancelled"}),v=E=>y(E),S=E=>{try{for(let x of NK(E)){if(x===""||x==="\x1B"||x==="q"){g({kind:"cancelled"});return}if(e.items.length===0){(x==="\r"||x===`
|
|
691
|
+
`)&&g({kind:"ok",values:[]});continue}if(x==="\x1B[A"||x==="k")s=(s-1+e.items.length)%e.items.length,d();else if(x==="\x1B[B"||x==="j")s=(s+1)%e.items.length,d();else if(x===" "){if(e.single){let A=!a[s];a.fill(!1),a[s]=A}else a[s]=!a[s];d()}else if(x==="a"&&!e.single){let A=e.items.map((T,B)=>({item:T,index:B})).filter(({item:T})=>T.requiresExplicitChoice!==!0),I=!A.every(({index:T})=>a[T]);for(let{index:T}of A)a[T]=I;d()}else if(x==="\r"||x===`
|
|
692
|
+
`){g({kind:"ok",values:e.items.filter((A,I)=>a[I]).map(A=>A.value)});return}}}catch(x){y(x)}};r.on("data",S),r.on("end",b),r.on("close",b),r.on("error",v)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),p&&r.setRawMode(f)}catch{}n.close()}};var v0=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$K=80,_i=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&xa(r,n.env??process.env)))return r.write(`${e}
|
|
693
|
+
`),t();let a=0,s=()=>{r.write(`\r${v0[a++%v0.length]} ${e}`)};s();let i=setInterval(s,$K);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as MK}from"node:fs";import{spawnSync as FK}from"node:child_process";import{chmod as BK,copyFile as jm,lstat as Vm,mkdir as La,readdir as Ym,realpath as Zd,rename as Yd,rm as Ot,stat as UK,symlink as HK,writeFile as WK}from"node:fs/promises";import{createHash as KK}from"node:crypto";import{basename as Km,dirname as Or,join as pt}from"node:path";import{Readable as GK}from"node:stream";import{pipeline as jK}from"node:stream/promises";var S0="https://github.com/anyrayHQ/install/releases",E0="connect-v",VK=new RegExp(`/releases/tag/${E0}([0-9][0-9A-Za-z.-]*)$`),YK=300*1024*1024,Xd=1e4,ZK=5*6e4,XK=360*6e4,JK=30*6e4,Da=(e,t)=>{let n=s=>s.split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),r=n(e),o=n(t);for(let s=0;s<Math.max(r.length,o.length);s++){let i=(r[s]??0)-(o[s]??0);if(i!==0)return i<0?-1:1}let a=s=>s.includes("-")?0:1;return a(e)-a(t)},x0=(e,t)=>{let n=t==="arm64"?"arm64":t==="x64"?"x64":void 0;if(n){if(e==="darwin")return`anyray-connect-darwin-${n}`;if(e==="linux")return`anyray-connect-linux-${n}`;if(e==="win32")return"anyray-connect-windows-x64.exe"}},zK=e=>{if(e)return VK.exec(e.trim())?.[1]},Zm=(e,t)=>{for(let n of e.split(`
|
|
694
|
+
`)){let[r,o]=n.trim().split(/\s+/);if(!r||!o)continue;if((o.startsWith("*")?o.slice(1):o)===t&&/^[0-9a-f]{64}$/i.test(r))return r.toLowerCase()}},I0=e=>{if(e.latest===e.current)return{apply:!1,mandatory:!1};if(e.autoUpdate||e.forced)return{apply:!0,mandatory:!1};let t=!!e.minVersion&&Da(e.current,e.minVersion)<0&&Da(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},qK=e=>Da(e.latest,e.current)<0?{apply:!1,mandatory:!1,downgradeBlocked:!0}:e.latest===e.current?{apply:e.autoUpdate||e.forced===!0,mandatory:!1,downgradeBlocked:!1}:{...I0(e),downgradeBlocked:!1},Na=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",QK=(e=process.execPath)=>{let t=_u(e);return t?Or(t):Or(Or(e))},eG=async(e=mt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=pt(QK(e.execPath),"bin",Na());try{if(await Zd(t)!==await Zd(e.execPath))return}catch{return}return t},Xm=async(e=mt(),t=q())=>{let n=await eG(e);if(n)return{kind:"managed",root:Or(Or(n)),link:n,entryPath:Jn(e)};let r=Jn(e);return Pu(r,t)?{kind:"durable",root:t,entryPath:r}:Ru(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},Jd=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(o)}},Jm=async(e=Xd)=>{let t=await Jd(`${S0}/latest`,e,{redirect:"manual"});return zK(t.headers.get("location"))},tG=async e=>{try{let t=await Jd(`${e}/connect-update.json`,Xd);if(!t.ok)return;let n=await t.json();if(!n||typeof n!="object")return;let r=n.minVersion;return typeof r=="string"&&/^\d+\.\d+\.\d+/.test(r)?r:void 0}catch{return}},Ti=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},zm=async(e,t,n)=>{let r=await Jd(e,ZK);if(!r.ok||!r.body)throw new Ti(r.status);let o=KK("sha256"),a=0;if(await jK(GK.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>YK)throw new Error("asset exceeds size cap");o.update(c),yield c}},MK(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},nG=e=>Km(e)===Na()?Km(Or(e)):Km(e),rG=async e=>{let t=await Ym(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Ot(pt(e,n),{force:!0}).catch(()=>{})},R0=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Ot(r,{force:!0}).catch(()=>{});let o=!1;try{await Yd(e,r),o=!0}catch{}try{await jm(t,e),await WK(Za(e),nG(t))}catch(a){throw o&&await Yd(r,e).catch(()=>{}),a}await Ot(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Ot(n,{force:!0}),await HK(t,n),await Yd(n,e)},oG=async(e,t={})=>{let n=pt(e.root,"bin"),r=pt(e.root,"versions"),o=pt(n,Na());await La(n,{recursive:!0,mode:448}),await La(r,{recursive:!0,mode:448});let a=pt(r,e.version),i=(await Vm(a).catch(()=>{}))?.isFile()?a:pt(a,Na());if(!(await Vm(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??Jd)(`${e.tagUrl}/SHA256SUMS`,Xd),d=l.ok?Zm(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await La(Or(i),{recursive:!0,mode:448}),await rG(Or(i));let u=`${i}.part-${process.pid}`;try{await(t.download??zm)(`${e.tagUrl}/${e.asset}`,u,d),await BK(u,493),await Yd(u,i)}catch(f){throw await Ot(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??R0)(o,i),{link:o,target:i,versionsDir:r}},aG=async e=>{let t=FK(e,["--version"],{stdio:"ignore",timeout:Xd});return!t.error&&t.status===0},sG=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??mo)(n);if(r.length>0){let o=await(t.resolveTarget??_e)(async()=>e);if(!o||!(await(t.repair??gt)(r,o.target)).every(ho))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??sr)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Lt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},iG=async e=>{let t=await e.install();if(!await(e.smoke??aG)(t.target))throw await e.rollback?.(t),new Error("managed binary smoke test failed");if(!await e.repoint(t.link))throw new Error("persistent config repoint failed");return await e.prune(),t},cG=async(e,t)=>{let n=await Ym(e).catch(()=>[]);for(let r of n)t.includes(r)||await Ot(pt(e,r),{force:!0,recursive:!0}).catch(()=>{})},lG=async e=>{let t=await Ym(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Ot(pt(e,n),{force:!0}).catch(()=>{})},dG=async(e,t)=>{let n=async()=>{await Ot(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await La(e,{recursive:!1}),n}catch{}let r=await UK(e).catch(()=>{});if(!(!r||t-r.mtimeMs<JK)){await n();try{return await La(e,{recursive:!1}),n}catch{return}}},Gm=e=>pt(e,"update-state.json"),uG=async e=>{let t=await M(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},pG=1e3,fG=16*6e4,hG=e=>e.inFlight===0,mG=async(e,t,n={})=>{let r=n.probe??ke,o=n.sleep??(i=>new Promise(c=>setTimeout(c,i))),a=n.now??Date.now,s=a()+(n.timeoutMs??fG);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&hG(i))return!0;if(a()>=s)return!1;await o(pG)}},Pi=async(e={})=>{let t=e.now??Date.now,n=be;if(At(yt(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??mt(),o=e.root??q(),a;try{let s=await Xm(r,o);if(o=s.root,s.kind==="unmanaged")return{outcome:"unmanaged",current:n};if(s.kind==="npm"&&!e.allowNpmMigration)return{outcome:"unmanaged",current:n};let i=s.kind!=="managed",c=x0(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Jm)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&Da(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await uG(Gm(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<XK)return{outcome:"failed",current:n,latest:l};let f=`${S0}/download/${E0}${l}`,p=await(e.load??P)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??tG)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?qK(w):{...I0(w),downgradeBlocked:!1};if(g.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:l};if(!g.apply)return{outcome:"disabled",current:n,latest:l};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:l,mandatory:g.mandatory};o===q()?await kt():await La(o,{recursive:!0,mode:448});let y=await dG(pt(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,v;try{await lG(pt(o,"bin"));let x=await Zd(pt(o,"versions")).catch(()=>{}),A=await Zd(pt(o,"bin",Na())).catch(()=>{}),I=A&&nc(A,x)?A:void 0,T=pt(o,"bin",Na());i&&process.platform==="win32"&&(await Vm(T).catch(()=>{}))?.isFile()&&(v=`${T}.rollback-${process.pid}`,await jm(T,v));let B=()=>(e.installBinary??oG)({root:o,version:l,asset:c,tagUrl:f});i?b=await iG({install:B,smoke:e.smoke,rollback:async({link:X,target:V})=>{v?(await jm(v,X),await Ot(Za(X),{force:!0}).catch(()=>{})):I&&I!==V?await R0(X,I):(await Ot(X,{force:!0}),await Ot(Za(X),{force:!0}).catch(()=>{}))},repoint:async X=>e.repoint?e.repoint(p,X):sG(p),prune:async()=>{await(e.pruneDurable??(X=>rc(X)))(r)}}):b=await B(),await cG(b.versionsDir,[l,n]),await Ot(Gm(o),{force:!0}).catch(()=>{})}finally{v&&await Ot(v,{force:!0}).catch(()=>{}),await y()}let S=e.bounceDaemon??Vu,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let x=p.fallbackPort??Ae,A=E?!0:await Xg().catch(()=>!0),I=await S(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!A&&p.gateway&&((I?await(e.waitForDaemon??mG)(x,l):!0)?await Lt({port:x,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??zg)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await Z(Gm(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},O0=async(e={})=>{let t=e.context??mt(),n=await Xm(t,e.root??q()),r=_o(e.root??q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:be,managedPath:n.link??r}:Pi({...e,context:t,allowNpmMigration:!0})},vo=async(e={})=>{let t=e.context??mt(),n=e.root??q(),r=await Xm(t,n),o=r.kind==="npm"||r.kind==="durable"?_o(n):void 0,a=await(e.load??P)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!x0(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=At(yt(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:be,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};var yG=async(e,t)=>{if(!e.gateway||!e.clientKey)return;let n=await t().catch(()=>{});return ge({origin:e.gateway,clientKey:e.clientKey,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:n,user:e.name,team:e.team})},_0=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,gG=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},qm=async(e={})=>{let t=e.load??P,n=e.save??te,r=e.mutate??(e.load||e.save?gG(t,n):ag),o=e.loadDevKey??Be,a=e.heartbeat??hd,s=e.detectSeat??Dt,i=e.rewriteTools??fi,c=e.uninstallProxy??Jt;try{let l=await t();if(l.credentialProtocol==="stable-heartbeat-v1"&&l.directMigration==="complete")return"already-direct";if(!l.keyRefreshEnabled&&!l.refreshSchedulerEnabled||!l.gateway||!l.clientKey||!l.enrolledCert)return"not-eligible";let d=l.enrolledCert.sig,u=await o();if(!u)return"not-eligible";let f;try{f=await a(l.gateway,l.clientKey,l.enrolledCert,u)}catch(y){return y instanceof Cr&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!_0(y,l))return{result:void 0};let b={...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"pending"};return{next:b,result:b}});if(!p)return"pending";let h=await yG(p,s);if(!h)return"pending";let m=l.keyRefreshEnabled===!0,w=Number.isInteger(l.fallbackPort)&&l.fallbackPort>0&&l.fallbackPort<=65535?l.fallbackPort:Ae;if(m){let y=`http://${ht}:${w}`;if(await i(h,y)===!1)return"pending"}return await r(y=>y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||y.credentialProtocol!=="stable-heartbeat-v1"||y.directMigration!=="pending"||!_0(y,p)?{result:!1}:{next:{...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"complete",keyRefreshEnabled:!1,fallbackPort:void 0},result:!0})?((m||l.fallbackPort!==void 0)&&await c(w).catch(()=>{}),"migrated"):"pending"}catch{return"pending"}};var wG=12e3,bG="anyray-wiring-probe-not-a-real-token",kG={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},ey={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},So=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},P0=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},ty=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},T0=e=>["Note: OpenCode\u2019s Claude provider can ONLY use a server-side key \u2014 unlike","Claude Code, it has no personal-subscription path. For Claude, either:",...e," \u2022 use Claude Code with your own Claude subscription instead of OpenCode.","OpenCode ChatGPT OAuth uses a non-configurable endpoint. Use Codex for"," config-native ChatGPT subscription pass-through, or use an OpenCode"," API-key/Copilot provider that Connect can route."],AG=e=>e.includes("no provider key configured for"),ny=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},ry=e=>({kind:"enrollment-required",detail:`gateway requires per-developer enrollment (HTTP ${e}).`,remedy:["This gateway only serves enrolled developers. Re-run with your enrollment","link from your admin so connect can mint your personal key automatically:"," anyray-connect --enroll <link>"]}),Li=e=>({kind:"key-rejected",detail:`gateway rejected the client key (HTTP ${e}).`,remedy:["The gateway did not receive a usable personal key (missing, unknown, expired,","or revoked). Re-run `anyray-connect` to refresh an existing enrollment, or","use `--enroll` / `--sso` to enroll first."]}),CG=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:e===401||e===403?ny(t)?ry(e):ty(t)?Li(e):P0(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${So(t)}`,remedy:["The org provider rejected the request \u2014 check the gateway\u2019s provider","key/config (e.g. the model is enabled for that account)."]}:AG(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${So(t)}`,remedy:["Your enrollment key is fine \u2014 the gateway has NO server-side provider","key configured (org-key mode), so it refused to forward the request.","Fix: add a provider key in the console \u2192 Providers.",...n.includes("opencode")?T0([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${So(t)}`,remedy:n.includes("opencode")?["Your enrollment key is fine \u2014 the gateway forwarded the request and the","upstream model provider refused the credential it was given: this","gateway has no WORKING provider key for it (either none is configured,","or the configured one is wrong or revoked).",...T0([" \u2022 open the console \u2192 Providers and add a key for that provider, or"," replace the one already listed (fixes it for everyone), or"])]:["Your enrollment key is fine \u2014 the gateway forwarded the request and the","upstream model provider refused it.","Open the console \u2192 Providers: if no key is listed for that provider,","add one; if a key IS listed, it is wrong, revoked, or not entitled to","the model \u2014 replace it.","Either way this is gateway config, not your enrollment. Alternatively,","sign in with your own provider subscription instead of the org key.","If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]}:{kind:"unknown",detail:`gateway responded HTTP ${e}: ${So(t)}`,remedy:[]},vG=(e,t)=>{if(ty(t))return Li(e);if(ny(t))return ry(e);if(P0(t))return{kind:"routed-elsewhere",detail:"gateway sent the request to the org provider, not your subscription.",remedy:["Pass-through isn\u2019t being honored for this gateway \u2014 your seat token would","not be used. Check the gateway is current (subscription pass-through support)."]};let n=t.toLowerCase();return e===401||n.includes("authentication_error")||n.includes("invalid bearer")||n.includes('"provider":"anthropic"')?{kind:"ok",detail:"gateway passes your sign-in through to Anthropic \u2014 your Claude seat will be used.",remedy:[]}:e>=200&&e<300?{kind:"ok",detail:"gateway pass-through reached the provider \u2014 your seat will be used.",remedy:[]}:{kind:"unknown",detail:`seat-wiring probe got HTTP ${e}: ${So(t)}`,remedy:[]}},SG=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),EG=(e,t)=>{if(ty(t))return Li(e);if(ny(t))return ry(e);let n=t.toLowerCase();if(n.includes("bedrock"))return{kind:"routed-elsewhere",detail:"gateway routed to the org provider instead of the configured BYO upstream.",remedy:["Re-run anyray-connect with your --upstream URL and --upstream-key so","the custom-host pass-through pins are restored."]};if(n.includes("invalid custom host")||n.includes("custom_host_blocked")||n.includes("hostname is not authorized"))return{kind:"routed-elsewhere",detail:"gateway rejected the configured BYO upstream before routing to it.",remedy:["Ask the gateway admin to authorize this LiteLLM/upstream hostname in","ANYRAY_CUSTOM_HOST_ALLOWLIST (or TRUSTED_CUSTOM_HOSTS for an internal host)."]};if(e===401||e===403)return{kind:"provider-rejected",detail:`gateway accepted your personal key but the BYO upstream rejected its credential (HTTP ${e}).`,remedy:["Your Anyray enrollment key is fine. The configured personal upstream key","was rejected by the BYO upstream (for example, LiteLLM). Re-run","anyray-connect with a current --upstream-key."]};let r=e>=400&&e<500&&(n.includes("litellm")||SG(n));return e>=200&&e<300||r?{kind:"ok",detail:e>=200&&e<300?"gateway served a completion through the configured BYO upstream.":`gateway authenticated and reached the configured BYO upstream, which rejected this probe's fixed model (HTTP ${e}).`,remedy:[]}:{kind:"unknown",detail:`BYO-upstream probe got HTTP ${e}: ${So(t)}`,remedy:[`The probe asks for a fixed model (${ey.model}) your upstream`,"is not required to serve, so a model rejection here does not mean your","tools are broken. Check that the upstream serves it before chasing this."]}},Qm=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),r);try{let s=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...t},body:JSON.stringify(n),signal:o.signal});return{status:s.status,bodyText:await s.text()}}finally{clearTimeout(a)}},xG=async(e,t)=>{if(!e.clientKey)return Li(401);let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`${e.origin}/connect/savings`,{method:"GET",headers:{"x-anyray-api-key":e.clientKey},signal:n.signal}),a=await o.text();return o.ok?{kind:"ok",detail:"gateway accepted your personal key \u2014 Cursor hooks/MCP can report and retrieve.",remedy:[]}:o.status===401||o.status===403?Li(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${So(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},IG=(e,t)=>{let n=typeof t?.code=="string"?` ${t.code}`:"";return{kind:"unreachable",detail:`could not reach the gateway to verify (${t instanceof Error&&t.name==="AbortError"?`no response within ${e}ms`:t instanceof Error?`${t.name}${n}`:"unknown error"}).`,remedy:["Your config was still written \u2014 re-run the curl below once the gateway is reachable."]}},Di=async(e,t={})=>{let n=t.timeoutMs??wG,r=le(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await xG(e,n);if(e.byoUpstream){let l={Authorization:`Bearer ${e.byoUpstream.key}`,"anthropic-version":"2023-06-01","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic","x-anyray-custom-host":e.byoUpstream.url};e.clientKey&&(l["x-anyray-api-key"]=e.clientKey),r&&(l["x-anyray-metadata"]=r);let{status:d,bodyText:u}=await Qm(`${e.anthropicBaseUrl}/v1/messages`,l,ey,n);return EG(d,u)}if(J(e,"anthropic")){let l={Authorization:`Bearer ${bG}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"};r&&(l["x-anyray-metadata"]=r),e.clientKey&&(l["x-anyray-api-key"]=e.clientKey);let{status:d,bodyText:u}=await Qm(`${e.anthropicBaseUrl}/v1/messages`,l,ey,n);return vG(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await Qm(`${e.openaiBaseUrl}/chat/completions`,s,kG,n);return CG(i,c,t.tools??[])}catch(o){return IG(n,o)}};var L0=async e=>{let t=await P(),n;try{n=xr(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),F(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${et(n)}`),t.gateway?F(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?F(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||F(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??C("(not set)")}`),k(` Team: ${t.team??C("(not set)")}`);let r=yt();r&&(K("Environment"),k(` Remote dev context: ${or(r)}`),At(r)&&F(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),F(" VS Code tools configure the remote server variant backing this window.")),t.credentialProtocol==="stable-heartbeat-v1"&&(K("Credential renewal"),t.directMigration==="pending"?(k(" Stable-key heartbeat active; direct-routing migration is still completing."),F(" The local proxy remains available until every managed tool moves.")):($(" Direct gateway routing with a proof-backed stable-key heartbeat."),F(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(nt(t)&&t.fallbackPort),a=o?`http://${ht}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await ke(t.fallbackPort)?$(` Running on 127.0.0.1:${t.fallbackPort} \u2192 ${n} `+C("(auto-refreshes your key so long sessions never 401)")):(N(` Enabled on 127.0.0.1:${t.fallbackPort} but NOT responding \u2014 your tools cannot reach any gateway until it's back.`),k(C(" Re-run `anyray-connect`, or check the service logs.")))),K("Tools");for(let s of oe){if(!(await s.detect()).installed){F(` ${s.title}: not installed`);continue}if(!s.pointsAt){F(` ${s.title}: installed ${C("(status not introspectable)")}`);continue}let c=await s.pointsAt(Si(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){$(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(C(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}$(` ${s.title}: pointed at Anyray${o&&vi(s.id)?C(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===_a&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await Ld();l=Dd({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:f.authoritative}),d={...f.authoritative?{}:{reason:f.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=Nd(l,d);N(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(C(` ${f}`))}else F(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as LG}from"node:fs";import{isAbsolute as DG}from"node:path";import{access as RG}from"node:fs/promises";import{constants as OG}from"node:fs";import{platform as _G}from"node:os";var TG=async e=>{try{return await RG(e,OG.F_OK),!0}catch{return!1}},PG=e=>e==="darwin"?["/Library/LaunchDaemons/com.fleetdm.orbit.plist","/opt/orbit/bin/orbit"]:e==="linux"?["/etc/systemd/system/orbit.service","/usr/lib/systemd/system/orbit.service","/opt/orbit/bin/orbit"]:e==="win32"?["C:\\Program Files\\Orbit\\bin\\orbit\\orbit.exe"]:[],$a=async(e={})=>{let t=e.os??_G(),n=e.exists??TG;for(let r of PG(t))if(await n(r))return!0;return!1};var sn="connect",oy=e=>e.replace(/-/g,"_"),D0=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:sn,checkId:"gateway_reachable",status:e.gateway.reachable?"ok":"unreachable"});let n=Date.parse(e.report.generatedAt),r=Date.parse(e.enrollment.expiresAt??""),o=e.enrollment.enrolled&&e.enrollment.expired===!1&&Number.isFinite(n)&&Number.isFinite(r)&&r-n<=336*60*60*1e3;if(t.push({tool:sn,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:sn,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:sn,checkId:"fallback_proxy",status:e.fallbackProxy.healthy===!1?"fail":e.fallbackProxy.healthy===!0?"ok":"unknown"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:sn,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:sn,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=oy(e.retrieval.kind);t.push({tool:sn,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":oy(e.verify.kind);t.push({tool:sn,checkId:"auth_verify",status:c,...i?{errorClass:"verify_not_applicable_subscription"}:c==="ok"?{}:{errorClass:`verify_${c}`}})}for(let i of e.tools)!i.installed||i.claudeCodeHookPolicy===void 0||t.push({tool:i.id,checkId:"hook_policy",status:i.claudeCodeHookPolicy==="fine"?"ok":i.claudeCodeHookPolicy});if(e.hookLane&&e.hookLane.verdict!=="indeterminate"){let i=e.hookLane.verdict==="dark";t.push({tool:sn,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:oy(e.hookLane.reason)}:{}})}t.push({tool:sn,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:sn,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function NG(){return be}var $G="ctx_doctor-probe-synthetic",MG=(e,t={mode:"unknown",ssoLink:null})=>{if(e.ok||e.kind==="not-found")return{kind:"ok",detail:"Retrieval loop healthy: gateway answered, key authorized, optimizer retrieval wired.",remedy:[]};switch(e.kind){case"auth":return{kind:"auth",detail:"The gateway rejected the retrieval call (no valid personal key).",remedy:[`Fix: ${iy(t.mode,t.ssoLink)}, or set ANYRAY_CLIENT_KEY.`,"Retrieval needs a personal key \u2014 the MCP server hits the same wall, so externalized output is unretrievable until this is fixed."]};case"unsupported":return{kind:"unsupported",detail:"The gateway has no /connect/retrieve route.",remedy:["Fix: update the gateway image \u2014 this one predates the retrieval loop."]};case"timeout":case"network":return{kind:"unreachable",detail:`Could not reach the gateway for the retrieval probe (${e.kind}).`,remedy:["Fix: check the gateway origin and network (see the Gateway section above)."]};default:return{kind:"unavailable",detail:e.message,remedy:["Fix: the gateway answered but retrieval is unavailable \u2014 usually the optimizer is down or ANYRAY_OPTIMIZER_URL is unset on the gateway. Check the optimizer service."]}}};function FG(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function BG(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function iy(e,t){let n=`\`anyray-connect --sso ${t??"<link>"}\``,r="`anyray-connect --enroll <link>`";switch(e){case"sso":return`enroll via SSO with ${n}`;case"passwordless":return`enroll with the link from your admin (${r})`;default:return`enroll \u2014 SSO org: use ${n}; passwordless org: use ${r} (link from your admin)`}}var N0=e=>Dd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),ay=e=>e.pointedAt===!1&&e.tombstoned!==!0&&N0(e)!=="unverifiable",$0=e=>e.registered&&e.command&&DG(e.command)?LG(e.command):null,sy=e=>(ay(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),UG=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,HG=async(e,t)=>{if(e.length===0)return!1;for(let n of e){let r=t.find(a=>a.id===n);if(!r?.inferenceAuthLanes)return!1;let o=await r.inferenceAuthLanes().catch(()=>["unknown"]);if(o.length===0||o.some(a=>a!=="subscription"&&a!=="native"))return!1}return!0},M0=async e=>{for(let t of e)if(t.integrationStatus)try{if(!(await t.detect()).installed)continue;if((await t.integrationStatus()).hook_registration==="owned")return!0}catch{}return!1},WG=(e,t)=>{let n=c=>typeof c=="object"&&c!==null&&!Array.isArray(c),r=c=>typeof c=="number"&&Number.isSafeInteger(c)&&c>=0&&Number.isFinite(new Date(c).getTime()),o=new Set(t.map(c=>c.id)),a=new Set(wo),s=[],i=n(e.selfcheck?.adapters)?e.selfcheck.adapters:{};for(let[c,l]of Object.entries(i)){if(!o.has(c)||!n(l))continue;let d=n(l.lastRepaired)?l.lastRepaired:{},u=Object.entries(d).filter(w=>a.has(w[0])&&r(w[1])).map(([w,g])=>({checkId:w,at:g})),f=n(l.flapping)?l.flapping:void 0,p=Array.isArray(f?.checks)?f.checks.filter(w=>typeof w=="string"&&a.has(w)):[],h=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,m=f&&r(f.since)&&h&&p.length>0?{since:f.since,reason:h,checks:p}:void 0;(u.length>0||m)&&s.push({tool:c,repaired:u,...m?{flapping:m}:{}})}return s},KG=async(e,t,n,r,o,a,s=n,i=Di,c=!0,l=Ao,d=vo,u=Wt,f=ka)=>{let p=c?await jd(e):null,h=!!(nt(t)&&t.fallbackPort),m=h?await ke(t.fallbackPort):null,w=h?`http://${ht}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=t.enrolledCert?.payload,b=y?.expiresAt??t.enrolledCertExpiry??null,S=(await a())?.sso??null,E=BG({ssoLink:S,enrolledViaToken:!!t.enrolledTokenHash}),x=Ct(),A=await xw(x),I=A?[]:Tw(ge({origin:w})),T=[];for(let Y of r){let Ne=await Y.detect(),ft=null;if(Ne.installed&&Y.mcpStatus)try{let Lr=await Y.mcpStatus();ft={...Lr,commandOk:$0(Lr)}}catch{}let Ve=Ne.installed&&Y.id===_a?await o():void 0,Pr=Ne.installed&&Y.pointsAt?await Y.pointsAt(Si(Y.id,e,w)):null,cn=await UG(Pr,Y,t.managedTools??[]),Gi=Pr===!1&&cn===null,Ua=cn===!1&&Y.routingPendingReload?await Y.routingPendingReload().catch(()=>!1):!1,ji=Ne.installed?Y.runtimeDiagnostics?await Y.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:Y.routingOverrides?await Y.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Vi,claudeCodeHookPolicy:Ha}=ji,pe=t.fleetToolPolicy,tt=pe?.enabled.includes(Y.id)?pe.tiers?.[Y.id]??ga:void 0;T.push({id:Y.id,title:Y.title,installed:Ne.installed,...Ne.detail?{detail:Ne.detail}:{},pointedAt:cn,...Gi?{routingHeld:!0}:{},...Ua?{routingPendingReload:!0}:{},...Vi.length?{routingOverrides:Vi}:{},...Ha===void 0?{}:{claudeCodeHookPolicy:Ha},mcp:ft,...tt?{policyTier:tt}:{},...t.revertedTools?.includes(Y.id)?{tombstoned:!0}:{},...Y.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...Ve===void 0?{}:{inferenceIntrospectable:Ve.authoritative,...Ve.authoritative?{}:{inferenceUnverifiableReason:Ve.reason}}})}let B=s?await(async()=>{let{kind:Y,detail:Ne,remedy:ft}=await i(ge({origin:e,clientKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey,subscription:t.authMode==="subscription",placeholder:t.authMode==="placeholder",byoUpstream:t.byoUpstream,...t.authMode==="auto"?{seat:{anthropic:!1,openai:!1,copilot:!1}}:{},user:t.name,team:t.team}),{tools:t.managedTools??[]});return{kind:Y,detail:Ne,remedy:ft}})():null,X=B?.kind==="provider-rejected"&&await HG(t.managedTools??[],r),V=B?{...B,...X?{notApplicableSubscription:!0}:{}}:null,W=n?MG(await ba({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:le({user:t.name,team:t.team})},$G,{probe:!0}),{mode:E,ssoLink:S}):null,z=await u().catch(()=>({})),me=An(z.hookLane),De=s?await M0(r):!1,ee=De?await(async()=>{let Y=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...Xh(Y,{hookRegistered:De,neverInvoked:Yh(me,Date.now())}),lastInvokedAt:yd(me)}})():null,Fe=(await cr()).map(Y=>({adapter:Y.adapter,op:Y.op,requestedAt:Y.requestedAt,watcherAlive:dr(Y.watcherPid)})),xe=Fe.find(Y=>Y.adapter==="cursor"),_=xe?{op:xe.op,requestedAt:xe.requestedAt,watcherAlive:xe.watcherAlive}:null,L=!!t.refreshSchedulerEnabled,H=await vc(),ye=await d(),se=t.persistenceOwner==="tray",we=se?await l(t)==="healthy":null,We=await nE({daemonEnabled:h&&!se,daemonHealthy:h?!!m:null,schedulerEnabled:L&&!se,schedulerInstalled:H,binaryDurable:!Ge(rr())}),ue=await Su(),ie=0;p&&!p.reachable&&(ie+=1),h&&!m&&(ie+=1),se?L&&!we&&(ie+=1):L&&!H&&(ie+=1);for(let Y of T)ie+=sy(Y);return V&&V.kind!=="ok"&&!V.notApplicableSubscription&&(ie+=1),W&&W.kind!=="ok"&&(ie+=1),ee?.verdict==="dark"&&(ie+=1),I.length>0&&(ie+=1),ie+=Fe.filter(Y=>!Y.watcherAlive).length,ue.length>0&&(ie+=1),{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:NG(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:yt(),selfUpdate:{managed:ye.managed,available:ye.available,autoUpdate:ye.autoUpdate,state:ye.state}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},toolOrigin:w,fallbackProxy:{enabled:h,port:h?t.fallbackPort:null,healthy:h?!!m:null},refreshScheduler:{enabled:L,installed:H,owner:se?"tray":"os",...se?{trayHealthy:!!we}:{}},serviceRemoval:We,retiredFallbackState:ue,fleetdPresent:await $a(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null},enrollment:{enrolled:!!y,deploymentId:y?.deploymentId??null,issuedAt:y?.issuedAt??null,expiresAt:b,expired:b?Date.parse(b)<Date.now():null,orgMode:E,ssoLink:S},shell:{profilePath:x,blockPresent:A,staleExports:I},tools:T,...t.fleetToolPolicy?{fleetPlan:ld(t,t.fleetToolPolicy,!1)}:{},cursorQueue:_,pendingOps:Fe,ambientRepairs:WG(z,r),verify:V,retrieval:W,hookLane:ee,problems:ie}},GG=e=>{if(e.serviceRemoval.suspected){K("Endpoint security"),N(" Anyray installed these background services, but their files are gone from disk \u2014"),N(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),N(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)k(C(` missing: ${t}`));k(C(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(C(" tools straight at the gateway (your key then needs a periodic re-run).")),k(C(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(C(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},jG=e=>{if(e.retiredFallbackState.length!==0){K("Retired fallback lane"),O(" A cached organization provider key from the removed --fallback lane is still on this machine.");for(let t of e.retiredFallbackState)k(C(` ${t}`));k(C(" Fix: `anyray-connect doctor --repair` deletes it (a normal `anyray-connect` run does too)."))}},VG=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${or(e.connect.remoteContext)}`),At(e.connect.remoteContext)&&k(C(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),K("CLI updates"),e.connect.selfUpdate.state){case"managed":$(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||N(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":N(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),k(C(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":N(" Self-update is unavailable on this platform because no standalone binary is published."),k(C(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(C(" This copy is externally managed; update it with the method that installed it."));break;case"container":k(C(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(K("Gateway"),e.gateway.reachable===null?k(C(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?$(` Reachable: ${e.gateway.origin} ${C(`(${e.gateway.detail})`)}`):(O(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),k(C(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.fallbackProxy.enabled&&(K("Local key-refresh proxy"),e.fallbackProxy.healthy?$(` Running on 127.0.0.1:${e.fallbackProxy.port} \u2192 ${e.gateway.origin} `+C("(auto-refreshes your key so long sessions never 401)")):(O(` Enabled on 127.0.0.1:${e.fallbackProxy.port} but NOT responding \u2014 your tools point at it and cannot reach any gateway until it's back.`),e.serviceRemoval.kinds.includes("daemon")||k(C(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to point tools straight at the gateway.")))),e.refreshScheduler.enabled&&(K("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?$(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh and supervises the daemon."):(O(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),k(C(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?$(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(O(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||k(C(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),GG(e),jG(e),K("Personal key"),FG(e)){case"env":$(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":$(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":N(" Enrolled, but no personal key is cached locally right now."),k(C(" Fix: re-run `anyray-connect` to re-mint it from your enrollment \u2014 no need to re-enroll. Claude Code and Codex are still attributed to you by name."));break;default:N(" Enrollment required \u2014 no personal gateway key is available."),k(C(` Fix: ${iy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?N(` Enrollment cert expired ${C(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):$(` Enrollment cert valid until ${e.enrollment.expiresAt} ${C(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(K("Shell"),O(" This terminal still exports Anyray, but the config is gone."),k(C(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(C(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(C(" Anything you start from this terminal keeps reaching the gateway with")),k(C(" no credential, and fails with 401.")),k(C(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(C(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(C(" reuses the environment it captured at launch, so a new terminal")),k(C(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};K("Claude Code hook policy"),O(` ${lc(c)}.`),k(C(` ${dc(c)}`))}K("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])O(` ${c.title}: ${l.problem}.`),k(C(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(O(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),k(C(" Fix: re-run `anyray-connect` to re-register the current binary."))):$(` ${c.title}: retrieval MCP server registered ${C("(anyray_retrieve / anyray_recall)")}`):(N(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),k(C(" Fix: re-run `anyray-connect` from a durable install (registration is skipped for one-off npx runs)."))))};for(let c of e.tools){if(!c.installed){k(C(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){k(C(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){$(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),k(C(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}$(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&vi(c.id)?C(" (via key-refresh proxy)"):""}`),o(c),c.id==="claude-code"&&k(C(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===_a&&k(C(` ${lA}`)),c.id==="codex"&&k(C(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=N0(c);if(l==="not-routed"||l==="unverifiable"){let d=Nd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});N(` ${c.title}: ${d.headline}`);for(let u of d.detail)k(C(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(N(` ${c.title}: reverted locally against admin policy (out of compliance)`),k(C(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?N(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):k(C(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(O(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),k(C(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(O(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),k(C(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(N(" No tools are pointed at this gateway yet."),k(C(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){K("Queued operations");for(let c of e.pendingOps){let l=Ht(c.adapter)?.title??c.adapter;c.watcherAlive?N(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(O(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),k(C(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){K("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=Ht(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:p,at:h})=>`${c(p)} ${new Date(h).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?N(f):k(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){K("Fleet policy");let c=l=>l.map(d=>Ht(d)?.title??d).join(", ");i.freshIds.length>0&&k(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&N(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(K("Auth probe"),e.verify.notApplicableSubscription)$(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")$(` ${e.verify.detail}`);else{O(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(C(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")$(` ${e.retrieval.detail}`);else{O(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(C(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")$(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){O(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(C(` ${c}`))}else{N(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(C(` ${c}`))}e.hookLane.lastInvokedAt!==null&&k(C(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}K("Summary"),e.problems===0?(e.verify?$(" No problems found."):$(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(C(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):O(` ${e.problems} problem(s) found \u2014 see fixes above.`)},YG=e=>({...e,verify:e.verify?{kind:e.verify.kind,detail:"",remedy:e.verify.remedy,...e.verify.notApplicableSubscription?{notApplicableSubscription:!0}:{}}:null,retrieval:e.retrieval?{kind:e.retrieval.kind,detail:"",remedy:e.retrieval.remedy}:null}),ZG=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Gh(n.code))return{hookLane:n,note:`Hook lane: the gateway rejected this machine\u2019s key as '${n.code??"unclassified"}', which an automatic re-mint must never answer \u2014 no key was minted. Re-enroll (see the Hook lane fixes above).`};let r=t.probeHookLane??ka,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Qe)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=An((await(t.readRefreshState??Wt)().catch(()=>({}))).hookLane),l=Xh(i,{hookRegistered:await M0(t.adapters??oe).catch(()=>!1),neverInvoked:Yh(c,Date.now())}),d=s==="disabled"?"Hook lane: key refresh is disabled here (ANYRAY_REFRESH_DISABLE), so no key was minted and the finding stands.":l.verdict==="live"?"Hook lane: re-minted the personal key and rewrote the configured tools \u2014 the lane answers again.":l.verdict==="indeterminate"?`Hook lane: re-mint reported '${s}', but the confirming probe could not establish the lane's state \u2014 nothing is proven fixed and the finding stands.`:`Hook lane: re-mint reported '${s}' and the lane is still not live \u2014 re-enroll (see the Hook lane fixes above).`;return{hookLane:{...l,lastInvokedAt:yd(c)},note:d}},XG=async(e,t,n={})=>{let r=n.adapters??oe,o=n.resolveTarget??_e,a=n.applyTools??gt,s=await ZG(e,n).catch(()=>null),i=s&&e.hookLane?.verdict==="dark"&&s.hookLane?.verdict==="live"?1:0,c=s?{hookLane:s.hookLane,notes:[s.note]}:{notes:[]},l=e.tools.filter(y=>y.installed&&(ay(y)||y.mcp?.commandOk===!1||y.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t,void 0,ke);if(!d)return{entries:l.map(y=>({id:y.id,title:y.title,status:"skipped-not-enrolled"})),remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,`Repair needs an enrolled personal key \u2014 ${iy(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],p=[...c.notes],h=[];for(let y of l){let b=r.find(v=>v.id===y.id);if(!u.has(y.id)||!b){f.push({id:y.id,title:y.title,status:"skipped-unmanaged"});continue}h.push(b)}f.length>0&&p.push("Drifted tools outside the managed record are never auto-repaired \u2014 run `anyray-connect` once to (re)configure and record them.");let m=await a(h,d.target),w=new Map,g=0;for(let y of m){if(f.push(y),!ho(y))continue;let b=e.tools.find(T=>T.id===y.id);if(!b)continue;let v=r.find(T=>T.id===y.id),S=b.mcp;if(v?.mcpStatus)try{let T=await v.mcpStatus();S={...T,commandOk:$0(T)}}catch{}let E=ay(b)?!0:b.pointedAt;if(v?.pointsAt&&b.pointedAt!==null)try{E=await v.pointsAt(Si(v.id,e.gateway.origin,e.toolOrigin))}catch{}let x=b.routingOverrides,A=b.claudeCodeHookPolicy;if(v?.runtimeDiagnostics)try{let T=await v.runtimeDiagnostics();x=T.routingOverrides.length?T.routingOverrides:void 0,A=T.claudeCodeHookPolicy}catch{}else if(v?.routingOverrides)try{let T=await v.routingOverrides();x=T.length?T:void 0}catch{}let I={...b,pointedAt:E,mcp:S,...x?{routingOverrides:x}:{},...A===void 0?{}:{claudeCodeHookPolicy:A}};x||delete I.routingOverrides,A===void 0&&delete I.claudeCodeHookPolicy,w.set(y.id,I),g+=sy(b)-sy(I)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},JG=e=>{K("Repair"),e.entries.length===0&&$(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?$(` ${t.title}: re-applied`):t.status==="queued"?$(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(C(` ${t.title}: ${t.status}`)):O(` ${t.title}: ${t.status}`);for(let t of e.notes)k(C(` ${t}`))},F0=async(e,t={})=>{let n=await P();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of rE(n.fallbackPort??Ae))k(c?` ${c}`:"");return 0}let r;try{r=xr(e.gateway,n)}catch(c){return e.json?(console.log(JSON.stringify({error:c.message})),1):(k(j("Anyray connect \u2014 doctor")),O(` Gateway URL: ${c.message}`),k(C(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(k(j("Anyray connect \u2014 doctor")),O(" --quick skips the network probes; it cannot be combined with --verify.")),1;let o=!e.noVerify&&!e.quick,a=await KG(r,n,!!e.verify&&!e.quick,t.adapters??oe,t.inferenceIntrospection??Ld,t.fleetBootstrap??Gt,o,t.verifyAuth??Di,!e.quick,t.checkTray??Ao,t.updateStatus??vo,t.readRefreshState??Wt,t.probeHookLane??ka);e.repair&&a.retiredFallbackState.length>0&&(await Qi(),a.retiredFallbackState=await Su(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await XG(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;e.json?console.log(JSON.stringify(YG(i),null,2)):(VG(i),s&&JG(s));try{e.quick||await(t.reportHealth??Vv)(D0(i),i.connect.version)}catch{}return i.problems===0?0:1};var zG=()=>{let e=[];for(let t of oe){let n=t.skillsDir?.();n&&e.push(n)}return e},B0=async e=>{let t=await P();k(j("Anyray connect \u2014 sync"));let n;try{n=xr(e.gateway,t)}catch(s){return O(s.message),1}F(`Gateway: ${n}`);let r=TE(t.clientKey,"anyray-placeholder"),o;try{o=await ud(n,r)}catch(s){return O(`Team policy sync failed: ${dd(s)}`),1}let a=zG();if(a.length===0)qG();else if(o.skills.length===0)F("No team skills published yet \u2014 nothing to sync.");else{let s=await Iv(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?$(` ${i.name} ${C(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):F(` ${i.name} ${C(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await te({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){F(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await pd(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(k(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&F(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){F(`Fleet policy reconcile skipped: ${dd(s)}`)}return 0},qG=()=>{F("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as tV}from"node:zlib";import{promisify as nV}from"node:util";var _r={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},cy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),U0=e=>`
|
|
695
695
|
|
|
696
696
|
\u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
|
|
697
697
|
|
|
698
|
-
`,
|
|
698
|
+
`,zd=(e,t={})=>{if(typeof e!="string")return cy(String(e??""));let n=Math.max(1,t.maxChars??_r.maxChars);if(e.length<=n)return cy(e);let r=e.length,o=Math.max(0,t.headChars??_r.headChars),a=Math.max(0,t.tailChars??_r.tailChars),s=Math.max(0,t.middleWindows??_r.middleWindows),i=100*(s+2),c=Math.max(1,n-1-i);o+a>c&&(a=Math.min(a,c),o=Math.max(0,c-a));let l=o,d=r-a,u=[];o>0&&u.push([0,o]);let f=c-o-a;if(s>0&&f>0&&d>l){let g=d-l,y=Math.max(1,Math.floor(f/s));for(let b=0;b<s;b++){let v=l+Math.round((b+.5)/s*g),S=Math.min(d,Math.max(l,v)+Math.ceil(y/2)),E=Math.max(l,S-y),x=e.lastIndexOf(`
|
|
699
699
|
`,E);x>=l&&(E=x+1);let A=e.indexOf(`
|
|
700
|
-
`,S);A!==-1&&A<d&&(S=A),S>E&&u.push([E,S])}}a>0&&u.push([d,r]),u.sort((g,y)=>g[0]-y[0]);let p=[];for(let[g,y]of u){let b=p[p.length-1];b&&g<=b[1]?b[1]=Math.max(b[1],y):p.push([g,y])}let h="",m=0;for(let[g,y]of p)g>m&&(h+=
|
|
700
|
+
`,S);A!==-1&&A<d&&(S=A),S>E&&u.push([E,S])}}a>0&&u.push([d,r]),u.sort((g,y)=>g[0]-y[0]);let p=[];for(let[g,y]of u){let b=p[p.length-1];b&&g<=b[1]?b[1]=Math.max(b[1],y):p.push([g,y])}let h="",m=0;for(let[g,y]of p)g>m&&(h+=U0(g-m)),h+=e.slice(g,y),m=y;if(r>m&&(h+=U0(r-m)),h.length>=r)return cy(e);let w=r-h.length;return{text:h,trimmed:!0,originalChars:r,trimmedChars:h.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},QG=["stdout","content","output","text","result"],H0=e=>{if(typeof e=="string")return{body:e,rebuild:o=>o};if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(Array.isArray(t.content)){let o=t.content,a=[];for(let[i,c]of o.entries())c&&typeof c=="object"&&!Array.isArray(c)&&typeof c.text=="string"&&a.push({index:i,part:c,text:c.text});let s=Object.prototype.hasOwnProperty.call(t,"structuredContent")&&t.structuredContent!==void 0;if(a.length===1&&!s){let i=a[0];return{body:i.text,rebuild:c=>({...t,content:o.map((l,d)=>d===i.index?{...i.part,text:c}:l)})}}if(a.length>0||s){let i=a.map(({text:d},u)=>`--- MCP text part ${u+1} ---
|
|
701
701
|
${d}`);s&&i.push(`--- MCP structuredContent ---
|
|
702
702
|
${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
|
|
703
703
|
|
|
704
|
-
`),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((f,p)=>l.has(p)?p!==c?.index?[]:[{...c.part,text:d}]:[f]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=
|
|
705
|
-
`),s=0,i=0;for(let c of a)c.trim()&&(s++,
|
|
706
|
-
${e.slice(-
|
|
707
|
-
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},
|
|
708
|
-
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},
|
|
709
|
-
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},
|
|
710
|
-
`).filter(s=>s.trim()!==""),r=
|
|
704
|
+
`),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((f,p)=>l.has(p)?p!==c?.index?[]:[{...c.part,text:d}]:[f]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=QG.find(o=>typeof t[o]=="string");if(!n){let o=-1;for(let[a,s]of Object.entries(t))typeof s=="string"&&s.length>o&&(n=a,o=s.length)}if(!n)return null;let r=n;return{body:t[r],rebuild:o=>({...t,[r]:o})}};var ej=e=>{let t=e.trim();return t?t.length>=200&&!/\s/.test(t.slice(0,200).replace(/[{}[\],":]/g,""))?!0:/^\[?\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/.test(t)||/^\[?\d{2}:\d{2}:\d{2}/.test(t)||/^(ERROR|WARN|WARNING|INFO|DEBUG|TRACE|FATAL)\b/i.test(t)||/^\s*at\s+\S+\s+\(/.test(e)||/^\s*File ".+", line \d+/.test(e)||/^Traceback \(most recent call last\)/.test(t)||/^[{}[\]]/.test(t)||/[}\]],?$/.test(t)||/^"?[\w.-]+"?\s*[:=]\s+\S/.test(t):!1},Ni={minChars:8e3,minDataLineRatio:.6,minDataLines:20},qd=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Ni.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Ni.minDataLineRatio,o=t.minDataLines??Ni.minDataLines,a=e.split(`
|
|
705
|
+
`),s=0,i=0;for(let c of a)c.trim()&&(s++,ej(c)&&i++);return s===0||i<o?!1:i/s>=r};var $i=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,Qd={pytest:"test-run",jest:"test-run",vitest:"test-run",mocha:"test-run",cargo:"test-run",go:"test-run",rg:"grep",grep:"grep",egrep:"grep",fgrep:"grep",ag:"grep",ack:"grep"},G0=new Set(["npm","pnpm","yarn","bun"]),eu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},tj=e=>{let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return null;let o=eu(r[0]);if(o in Qd)return Qd[o];if((o==="npx"||o==="bunx")&&r[1]){let a=eu(r[1]);if(a in Qd)return Qd[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||G0.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},dy=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=tj(t);if(n)return n}return null},nj={git:new Set(["log","diff","show","blame","shortlog","whatchanged"]),docker:new Set(["logs","ps","images","inspect","history","diff"]),podman:new Set(["logs","ps","images","inspect","history","diff"]),kubectl:new Set(["logs","get","describe"]),journalctl:null,dmesg:null,tsc:null,make:null,gradle:null,mvn:null,bazel:null},rj=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,oj=(e,t,n)=>{let r=(...o)=>n.some(a=>o.includes(a));return(e==="docker"||e==="podman"||e==="kubectl")&&t==="logs"||e==="journalctl"?r("-f","--follow"):e==="kubectl"&&t==="get"||e==="tsc"?r("-w","--watch"):!1},j0=e=>{if(typeof e!="string"||!e.trim())return!1;let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;let r=t.slice(n);if(r.length===0)return!1;let o=eu(r[0]);if(G0.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&rj.test(i)}let a=r[1]?eu(r[1]):void 0;if(oj(o,a,r))return!1;let s=nj[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},aj=e=>{let t=e.trim();if(t.length<2)return!1;let n=t[0],r=t[t.length-1];return n==="{"&&r==="}"||n==="["&&r==="]"},sj=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},ij=e=>{let t=e.trim();if(t==="")return!1;let n=!0;for(let o=0;o<t.length;o++){let a=t[o];if(a!=="{"&&a!=="}"&&a!=="["&&a!=="]"&&a!==","){n=!1;break}}if(n)return!0;if(t[0]!=='"')return!1;let r=sj(t);return r>0&&t[r+1]===":"},cj=80,lj=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/cj),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,ij(e[o])&&r++;return n>0&&r/n>.3},dj=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,uj=e=>{let t=e.slice(0,80);if(t.length===0)return!1;let n=0;for(let r of t){let o=r.trim();(dj.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},pj=[/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b.*\bin\s+[\d.]+\s*s/i,/^=+ FAILURES =+/m,/^=+ short test summary/im,/test session starts/i,/^Test Suites:\s+\d+/m,/^Tests:\s+\d+\s+(failed|passed|total)/m,/^test result:\s+(ok|FAILED)\b/m,/^running \d+ tests?$/m,/^--- (FAIL|PASS): /m,/^(ok|FAIL)\s+\S+\s+[\d.]+s/m],ly=8192,fj=e=>{let t=e.length>2*ly?`${e.slice(0,ly)}
|
|
706
|
+
${e.slice(-ly)}`:e;return pj.some(n=>n.test(t))},hj=e=>/^[=~_—-]{4,}$/.test(e)||/^=+ .* =+$/.test(e)||/test session starts/i.test(e)||/^platform /i.test(e)||/^(rootdir|cachedir|configfile|plugins):/i.test(e)||/^collected \d+ items?/i.test(e)||/^Ran all test suites/.test(e)||/^(Snapshots|Time):/.test(e)||/^running \d+ tests?$/.test(e)||/^=== RUN /.test(e),mj=e=>/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b/i.test(e)&&/\bin\s+[\d.]+\s*s/i.test(e)||/^Test Suites:\s+\d+/.test(e)||/^Tests:\s+\d+/.test(e)||/^test result:\s+(ok|FAILED)\b/.test(e)||/^FAIL\s+\S+\s+[\d.]+s$/.test(e),yj=e=>{let t=/^_{2,}\s*(.+?)\s*_{2,}$/.exec(e);return t?`FAIL: ${t[1]}`:/^FAIL\s+\S+/.test(e)&&!/\s[\d.]+s$/.test(e)||/^--- FAIL: /.test(e)||/^---- .+ (stdout|stderr) ----$/.test(e)?e:null},gj=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),W0=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(mj(i)){t.push($i(i));continue}let c=yj(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push($i(c)),o=12;continue}hj(i)||gj(i)||o>0&&(t.push($i(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
|
|
707
|
+
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},wj=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,V0=e=>{let t=wj.exec(e);return t&&/[/.]/.test(t[1])?t:null},bj=/^([^\s:]+)-(\d+)-/,kj=e=>{if(e==="--")return!0;let t=bj.exec(e);return t!=null&&/[/.]/.test(t[1])},Aj=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>V0(r)!=null).length;return n>=3&&n/t.length>=.7},K0=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=V0(c);if(!l){if(kj(c))return null;r++;continue}o++;let d=n.get(l[1])??[];d.push({line:l[2],content:l[3]}),n.set(l[1],d)}if(o===0||o/(o+r)<t)return null;let a=[`${o} matches in ${n.size} files:`],s=0,i=!1;for(let[c,l]of n){if(s>=200){i=!0;break}a.push("",`${c}:`);let d=Math.min(l.length,25,200-s);for(let u of l.slice(0,d))a.push($i(` ${u.line}: ${u.content.trim()}`)),s++;l.length>d&&a.push(` \u2026+${l.length-d} more in this file`)}return i&&a.push("",`\u2026+${o-s} more matches elided`),{text:a.join(`
|
|
708
|
+
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},Cj=e=>e.replace(/\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d(?:\.\d+)?Z?/g,"<TS>").replace(/\b\d\d:\d\d:\d\d\b/g,"<TS>").replace(/\b[0-9a-f]{2,}(?:-[0-9a-f]{2,}){2,}\b/gi,"<ID>").replace(/\b0x[0-9a-f]+\b/gi,"<HEX>").replace(/\b\d{8,}\b/g,"<NUM>").trim(),vj=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=Cj(o),s=t.get(a);s?s.n++:(t.set(a,{first:o,n:1}),n.push(a))}return n.length/e.length>.6?null:{text:n.map(o=>{let{first:a,n:s}=t.get(o),i=$i(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
|
|
709
|
+
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},Y0=(e,t)=>{if(typeof t!="string"||t.length===0||aj(t))return null;let n=t.split(`
|
|
710
|
+
`).filter(s=>s.trim()!==""),r=dy(e),o=fj(t),a=null;return r==="test-run"&&o?a=W0(n):r==="grep"&&(a=K0(n,.5)),a||(o?a=W0(n):Aj(n)?a=K0(n,.7):!uj(n)&&!lj(n)&&(a=vj(n))),!a||a.text.length>=t.length?null:a},uy=(e,t)=>t?`
|
|
711
711
|
|
|
712
712
|
\u2026[anyray-hook digest \u2014 ${e}; full output: ${t}]\u2026`:`
|
|
713
713
|
|
|
714
|
-
\u2026[anyray-hook digest \u2014 ${e}]\u2026
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
`);
|
|
718
|
-
`)
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
714
|
+
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,Z0=e=>`
|
|
715
|
+
|
|
716
|
+
\u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as Sj}from"node:crypto";import{homedir as Ej}from"node:os";import{join as tu}from"node:path";import{mkdir as xj,readdir as Ij,stat as py,unlink as X0,writeFile as Rj}from"node:fs/promises";var Oj=1440*60*1e3,J0=50,_j=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",Tj=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=q();try{if((await py(t)).isDirectory())return tu(t,"hook-tee")}catch{}return tu(Ej(),".anyray-hook-tee")},Pj=async e=>{try{let t=Date.now(),n=[];for(let r of await Ij(e)){let o=tu(e,r);try{let a=await py(o);if(!a.isFile())continue;t-a.mtimeMs>Oj?await X0(o):n.push({path:o,mtimeMs:a.mtimeMs})}catch{}}if(n.length>J0){n.sort((r,o)=>r.mtimeMs-o.mtimeMs);for(let r of n.slice(0,n.length-J0))await X0(r.path).catch(()=>{})}}catch{}},z0=async e=>{if(_j())return null;try{let t=await Tj();await xj(t,{recursive:!0,mode:448});let n=`${Sj("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=tu(t,n);try{if((await py(r)).isFile())return r}catch{}return await Rj(r,e,{mode:384}),await Pj(t),r}catch{return null}};import{createHash as Lj}from"node:crypto";import{homedir as q0}from"node:os";import{join as fy}from"node:path";import{readFile as Dj,writeFile as Nj,chmod as $j,stat as Mj,unlink as Fj}from"node:fs/promises";var Bj=200,Uj=1440*60*1e3,Hj=4e6,Q0=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",ex=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},Wj=()=>ex("ANYRAY_HOOK_CACHE_MAX_ENTRIES",Bj),tx=()=>ex("ANYRAY_HOOK_CACHE_TTL_MS",Uj),nx=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=fy(q0(),".anyray");try{if((await Mj(t)).isDirectory())return fy(t,"hook-cache.json")}catch{}return fy(q0(),".anyray-hook-cache.json")},rx=(e,t,n)=>Lj("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),ox=async e=>{try{let t=JSON.parse(await Dj(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},ax=async e=>{if(Q0())return null;try{let n=(await ox(await nx())).entries[e];return!n||Date.now()-n.at>tx()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},Kj=e=>{let t=Date.now(),n=tx(),r=Object.entries(e).filter(([,i])=>t-i.at<=n);r.sort((i,c)=>c[1].at-i[1].at);let o=[],a=0,s=Wj();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>Hj&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},sx=async(e,t)=>{if(Q0())return;let n;try{let r=await nx(),o=await ox(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=Kj(o.entries),n=`${r}.${process.pid}.tmp`,await Nj(n,JSON.stringify(o),{mode:384}),await $j(n,384),await fe(n,r)}catch{if(n)try{await Fj(n)}catch{}}};import{open as Gj,stat as jj}from"node:fs/promises";var ix=600,Vj=3,Yj=256e3,Zj=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
717
|
+
`):"",Xj=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),Jj=e=>{let t=[];for(let n of e)if(!(!n||!n.trim()))try{let r=JSON.parse(n);r&&typeof r=="object"&&!Array.isArray(r)&&t.push(r)}catch{}return t},zj=e=>{let t=[],n=0;for(let r=e.length-1;r>=0;r--){let o=e[r];if(!o||o.type!=="user"||o.isMeta||o.isSidechain)continue;let a=Zj(o.message?.content).trim();if(!(!a||Xj(a))&&(t.unshift(a),n+=a.length,t.length>=Vj||n>=ix))break}return t.join(`
|
|
718
|
+
`).slice(0,ix)};var qj=e=>/(^|[\\/])subagents[\\/]/i.test(e),Qj=e=>/\.jsonl$/i.test(e),eV=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),cx=async e=>{let t={intent:"",kind:"unknown"};if(!e||!Qj(e))return t;let n;try{let{size:r}=await jj(e),o=Math.max(0,r-Yj),a=r-o;if(a<=0)return t;n=await Gj(e,"r");let s=new Uint8Array(a);await n.read(s,0,a,o);let i=new TextDecoder().decode(s);if(o>0){let l=i.indexOf(`
|
|
719
|
+
`);i=l>=0?i.slice(l+1):""}let c=Jj(i.split(`
|
|
720
|
+
`));return eV(c)?{intent:zj(c),kind:qj(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var rV=3e3,oV=1500,aV=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:rV},sV={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},iV=new Set(["claude","opencode"]),cV=(e,t)=>{let n={};if(e)try{let r=JSON.parse(e);r&&typeof r=="object"&&!Array.isArray(r)&&(n=r)}catch{}return JSON.stringify({...n,tool:sV[t]})},lV={cacheGet:async()=>null,cachePut:async()=>{}},dV=(e,t={cacheGet:ax,cachePut:sx,tee:z0})=>e==="claude"?t:lV,uV=1e3,pV=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),nu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),fV=e=>{try{let t=JSON.parse(e);if(!nu(t)||typeof t.tool_name!="string"||!t.tool_name.startsWith("MCP:")||typeof t.tool_output!="string")return;let n=JSON.parse(t.tool_output);return nu(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},hV=e=>{try{let t=JSON.parse(e);return nu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},mV=e=>nu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
721
|
+
`:"",hy=e=>Math.round(Math.max(0,e)/4),lx=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",yV=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),gV=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),wV=["tool_output","tool_response","tool_result"],bV=e=>{for(let t of wV)if(t in e)return e[t]},kV=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},AV=120,CV=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??uV))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=uy(r.stat,null).length+AV;if(r.text.length+o>=n.length)return null;let a=null;if(e.tee)try{a=await e.tee(n)}catch{a=null}let s=uy(r.stat,a);return r.text.length+s.length>=n.length?null:{body:r.text,marker:s,teePath:a,decision:{router:r.router,kept:r.kept,total:r.total,teed:a!=null}}},vV=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let E=JSON.parse(e);if(!E||typeof E!="object")return n;r=E}catch{return n}let o=typeof r.tool_name=="string"?r.tool_name:"unknown";if(yV.has(o)||gV(o))return n;let a=H0(bV(r));if(!a)return n;let s=async E=>{try{await t.beacon(o,E)}catch{}},i=a.body,c=typeof r.transcript_path=="string"?r.transcript_path:"",l={intent:"",retrievalContext:t.defaultRetrievalContext??"unknown"};if(t.readContext&&c)try{l=await t.readContext(c)}catch{l={intent:"",retrievalContext:"unknown"}}if(dx(o)&&l.retrievalContext!=="available")return n;let d=await CV(t,kV(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!qd(i,{minChars:oV})))return n;let p=i.length-u.length-f.length,h=async(E,x,A=E.length+f.length)=>{let I=d?.teePath??null;if(!I&&t.tee)try{I=await t.tee(i)}catch{I=null}let T=I?E.replaceAll("; not retrievable in this context]","]"):E,B=I&&!f?Z0(I):"",X=T+f+B,V=B.length,W=X;if(t.finalizeOutput)try{let ee=t.finalizeOutput(X);ee.length<=X.length&&(W=ee)}catch{W=X}let z=X.length-W.length,me=hy(Math.max(0,p-V))+x+hy(z);me>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,A+V-z),estTokensSaved:me,...d&&{digest:d.decision}});let De=a.rebuild(W);return{stdout:pV(De),replacement:De}},m=async()=>d?h(u,0):n;if(d&&u.length<=t.sizeGate)return h(u,0);let w=l.intent?`${l.intent}
|
|
722
|
+
${lx(r.tool_input)}`:lx(r.tool_input),g=rx(o,w,u),y=async E=>{try{await t.cachePut(g,E)}catch{}},b=null;try{b=await t.cacheGet(g)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?h(b.output,b.tokensSaved):m();let v=null;try{v=OV(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{v=null}if(v&&!v.handled&&(v=null),v)return v.optimized&&v.output.length<u.length?(await y({optimized:!0,output:v.output,tokensSaved:hy(u.length-v.output.length)}),h(v.output,0,u.length+f.length)):(await y({optimized:!1}),m());let S;try{S=t.localTrim(u)}catch{return m()}return S.trimmed?h(S.text,S.estTokensSaved):m()},Mi=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},SV=()=>{let e=n=>{let r=process.env[n];if(!r)return;let o=Number(r);return Number.isFinite(o)&&o>0?o:void 0},t=n=>{let r=process.env[n];if(!r)return;let o=Number(r);return Number.isFinite(o)&&o>=0?Math.floor(o):void 0};return{maxChars:e("ANYRAY_HOOK_MAX_CHARS"),headChars:e("ANYRAY_HOOK_HEAD_CHARS"),tailChars:e("ANYRAY_HOOK_TAIL_CHARS"),middleWindows:t("ANYRAY_HOOK_MIDDLE_WINDOWS")}},EV=nV(tV),xV=async e=>{try{let t=await EV(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},dx=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),IV=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},RV=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),OV=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),_V=2048,TV=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,_V),n=md(t);if(!n)return;await gS({at:Date.now(),status:e.status,code:n})}catch{}},PV=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),aV());try{let c=await xV(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...dx(t)||IV(t)&&a==="available"?{reversible:!0}:{},...RV(t)?{semanticRerank:!0}:{},output:r})),l=Xt(e);c.encoding&&(l["content-encoding"]=c.encoding);let d=await fetch(`${e.origin}/connect/optimize-output`,{method:"POST",headers:l,body:c.body,signal:s.signal});if(!d.ok)return(d.status===401||d.status===403)&&await TV(d),null;let u=await d.json();return{optimized:u?.optimized===!0&&typeof u?.output=="string",output:typeof u?.output=="string"?u.output:r,handled:u?.handled===!0}}catch{return null}finally{clearTimeout(i)}},ux=async(e="claude")=>{let t=await Mi();if(e!=="cursor"&&hV(t))return 0;let n=e==="cursor"?fV(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await my(n,e);if(e==="cursor"){let a=mV(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},my=async(e,t="claude",n)=>{await Sr(),await yS(t);let r=SV(),o=await rt(),a=o&&{...o,metadata:cV(o.metadata,t)},s=dV(t);return vV(e,{optimize:(i,c,l,d,u)=>PV(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await cx(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>zd(i,r),beacon:(i,c)=>pc(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??_r.maxChars,digestCommand:Y0,tee:s.tee,mediumBand:iV.has(t),finalizeOutput:n})};var px=async()=>0;var LV=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let a=JSON.parse(e);if(!a||typeof a!="object")return n;let s=a.prompt;if(typeof s!="string"||!s)return n;r=s}catch{return n}if(!t.isPaste(r))return n;let o=null;try{o=t.measure(r)}catch{o=null}if(!o||o.estTokensSaved<=0)return n;try{await t.beacon(o)}catch{}return n},DV=async(e,t={})=>{try{if(!e.trim())return;let n;try{n=JSON.parse(e)?.hook_event_name}catch{return}if(n!=="beforeSubmitPrompt")return;let r=await(t.readBootstrap??Gt)();if(!r)return;let o=await(t.ssoGate??Vn)({sso:r.sso,gateway:r.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(o.exitCode!==2||!o.stderr)return;let a=o.stderr.trim().replace(/Your prompt was not sent — complete sign-in, then resubmit it\.?/,"This request will fail until sign-in completes \u2014 then just continue chatting.");return`${JSON.stringify({continue:!0,user_message:a})}
|
|
723
|
+
`}catch{return}},NV=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},$V=()=>{let e=t=>{let n=process.env[t];if(!n)return;let r=Number(n);return Number.isFinite(r)&&r>0?r:void 0};return{minChars:e("ANYRAY_PROMPT_PASTE_MIN_CHARS"),minDataLines:e("ANYRAY_PROMPT_PASTE_MIN_LINES")}},MV=(e,t)=>{let n=t.minChars??Ni.minChars,r={maxChars:Math.min(_r.maxChars,n)},o=zd(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},fx=async()=>{let e=await NV(),t=await DV(e);t&&process.stdout.write(t);let n=$V(),r=await rt();return await LV(e,{isPaste:o=>qd(o,n),measure:o=>MV(o,n),beacon:o=>pc(r,"prompt",o)}),0};import{spawn as FV}from"node:child_process";var hx=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),BV=/[|&;<>`$()\n]/,mx=e=>{if(BV.test(e))return null;let t=[],n="",r=!1,o=null;for(let a of e){if(o){if(a===o)o=null;else{if(o==='"'&&a==="\\")return null;n+=a,r=!0}continue}if(a==='"'||a==="'"){o=a,r=!0;continue}if(a===" "||a===" "){r&&(t.push(n),n="",r=!1);continue}if("*?[]{}~#\\".includes(a))return null;n+=a,r=!0}return o||(r&&t.push(n),!t.length)||/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0])?null:t},UV=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!hx(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!hx(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(Nu)||!t.isRecognized(o)||mx(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},HV=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?mx(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
|
|
722
724
|
`),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
|
|
723
|
-
`),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},k2=16*1024*1024,A2=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=y2(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>k2){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)}}),C2=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await hy(n,"cursor");return typeof r=="string"?r:t},sx=e=>{let t=e[0]==="--b64"?e[1]:void 0;return b2(t,{exec:A2,trim:C2,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},ix=async()=>{let e=await Ni();if(process.platform==="win32")return 0;let t=w2(e,{isRecognized:n=>ly(n)!==null||$0(n),wrap:n=>Rt(Du,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as v2}from"node:crypto";import{homedir as cx}from"node:os";import{extname as S2,isAbsolute as E2,join as my,resolve as $i,sep as lx}from"node:path";import{chmod as x2,readFile as I2,stat as hx,unlink as O2,writeFile as R2}from"node:fs/promises";var gy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_2=16*1024,dx=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],P2=["pattern","query","regex","search"],T2=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"]),L2=720*60*1e3,D2=512,yy=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},N2=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],ux=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(lx)?n:n+lx)),$2=(e,t,n)=>E2(e)?[$i(e)]:[...new Set([$i(t,e),...n.map(r=>$i(r,e))])],px=(e,t,n)=>v2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),fx=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),M2=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!gy(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!gy(o))return"";let a=N2(n.workspace_roots).map(d=>$i(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=yy(o,P2);if(!d)return"";let u=yy(o,dx);return u&&!ux($i(s,u),a)||!await t.remember(px(i,"Grep",d))?"":fx(`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=yy(o,dx);if(!c||T2.has(S2(c).toLowerCase()))return"";let l=await t.resolveFile($2(c,s,a));return!l||l.bytes<_2||!ux(l.path,a)||!await t.remember(px(i,"Read",l.path))?"":fx(`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.`)},F2=async e=>{for(let t of e)try{let n=await hx(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},B2=async()=>{let e=my(cx(),".anyray");try{if((await hx(e)).isDirectory())return my(e,"cursor-redirects.json")}catch{}return my(cx(),".anyray-cursor-redirects.json")},U2=async e=>{let t;try{let n=await B2(),r=Date.now(),o={};try{let s=JSON.parse(await I2(n,"utf-8"));if(s?.v===1&&gy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=L2&&(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,D2);return t=`${n}.${process.pid}.tmp`,await R2(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await x2(t,384),await fe(t,n),!0}catch{if(t)try{await O2(t)}catch{}return!1}},mx=async()=>{let e=await Ni(),t="";try{t=await M2(e,{resolveFile:F2,remember:U2})}catch{t=""}return t&&process.stdout.write(t),0};var Mi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},wy=e=>typeof e=="string"&&e.trim()?e.trim():void 0,H2=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Mi(n,"deviceCode"),o=Mi(n,"privateKeyPem"),a=Mi(n,"publicKeyPem"),s=Mi(n,"cpOrigin"),i=Mi(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=wy(n.gatewayUrl),f=wy(n.gatewayOverride),p=wy(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...f?{gatewayOverride:f}:{},...p?{team:p}:{}}}catch{return null}},W2=e=>new Promise(t=>setTimeout(t,e)),K2=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})},G2=async(e,t={})=>{let n=t.poll??Sd,r=t.verify??on,o=t.loadProfile??T,a=t.saveProfile??ee,s=t.saveDevKey??Xi,i=t.readGateState??Sr,c=t.writeGateState??Ed,l=t.clearGateState??AS,d=t.sleep??W2,u=t.now??Date.now,f=t.recordMint??ka,p=t.reserveMint??wo,h=t.applyClaudeCode??(async x=>{await tr.apply(x,{dryRun:!1})}),m=x=>K2(x,{readGateState:i,writeGateState:c,now:u}),w={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g;try{g=await n(w,{gatewayUrl:e.gatewayOverride})}catch(x){let A=x instanceof Ht?x.kind:"cp-unreachable";return await m(A),A}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),v={...b,gateway:y??b.gateway,name:g.cert.payload.user||b.name,team:e.team??g.cert.payload.team??b.team,enrolledCert:g.cert,enrolledCertExpiry:g.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(g.privateKeyPem),await a(v)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let S;await p();for(let x=0;x<3;x++)try{S=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(A){if(A instanceof xt||x===2)break;await d(1e3)}if(!S)return await m("gateway-unreachable"),"gateway-unreachable";let E={...v,gateway:y,name:S.user,team:e.team??S.team??v.team,clientKey:S.key,clientKeyExpiresAt:S.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:S.expiresAt});let x=ye({origin:y,clientKey:S.key,subscription:!0,user:E.name,team:E.team});return await h(x),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},j2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},yx=async()=>{let e=H2(await j2());if(e)try{await G2(e)}catch{}return 0};var V2=1e4,by=/^[\w.:-]{1,64}$/,jt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},ky=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,gx=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),V2);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new jt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},Y2=e=>{let t=ky(e);if(!t)return;let n=t.browser_url;try{if(typeof n!="string")return;let r=new URL(n);if(r.protocol!=="http:"&&r.protocol!=="https:")return}catch{return}if(!(typeof t.id!="string"||!t.id||typeof t.user_code!="string"||!t.user_code||typeof t.poll_secret!="string"||!t.poll_secret||typeof t.interval!="number"||!Number.isFinite(t.interval)||t.interval<=0||typeof t.expires_in!="number"||!Number.isFinite(t.expires_in)||t.expires_in<=0))return{id:t.id,browser_url:n,user_code:t.user_code,poll_secret:t.poll_secret,interval:t.interval,expires_in:t.expires_in}},Z2=e=>{let t=ky(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&by.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&by.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},X2=e=>{let t=ky(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ie(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!by.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}}},J2=e=>new Promise(t=>setTimeout(t,e)),z2=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new jt("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}k("Available teams:"),e.forEach((i,c)=>k(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Oa("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new jt("invalid-team","Choose one of the teams shown above.");return s},q2=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??J2,a=t.loadProfile??T,s=t.saveProfile??ee,i=t.clearDevKey??ja,c=t.chooseTeam??z2,l=t.apply??(async g=>{await tr.apply(g,{dryRun:!1})}),d=t.log??B,u=await a(),f=Er(e.gateway,u),p=await gx(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=Y2(p.body);if(p.status!==200||!h)throw new jt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${h.browser_url}`),d(`Enter this code in the browser: ${h.user_code}`),(t.openBrowser??Aa)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await gx(`${f}/sso/cli/poll/${encodeURIComponent(h.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":h.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(g.status===202){await o(h.interval*1e3);continue}if(g.status===401)throw new jt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new jt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=Z2(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new jt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??Gt());continue}let b=X2(g.body);if(g.status!==200||!b)throw new jt("login-failed","SSO login could not be completed.");let v={...u,gateway:f,name:b.user,team:b.team,clientKey:b.key,clientKeyExpiresAt:b.expires_at,enrolledCert:void 0,enrolledCertExpiry:void 0,enrolledTokenHash:void 0,ssoLink:void 0,authMode:"subscription"};return await i(),await s(v),await l(ye({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new jt("expired","SSO login expired before it completed. Run anyray-connect login again.")},Q2=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
725
|
+
`),1}if(o.alreadyWritten)return o.code;let a=o.output;try{a=await t.trim(n,o.output)}catch{a=o.output}return t.write(a),o.code},WV=16*1024*1024,KV=e=>new Promise(t=>{let n=[],r=0,o=!1,a=!1,s=new Map,i=c=>{if(!a){a=!0;for(let[l,d]of s)process.off(l,d);t({output:o?"":Buffer.concat(n).toString("utf8"),code:c,...o?{alreadyWritten:!0}:{}})}};try{let c=FV(e[0],e.slice(1),{stdio:["inherit","pipe","pipe"]});for(let d of["SIGINT","SIGTERM","SIGHUP"]){let u=()=>{if(c.exitCode===null&&c.signalCode===null)try{c.kill(d)}catch{}};s.set(d,u),process.on(d,u)}let l=d=>{if(o){process.stdout.write(d);return}if(r+d.byteLength>WV){for(let u of n)process.stdout.write(u);n.length=0,process.stdout.write(d),o=!0;return}n.push(d),r+=d.byteLength};c.stdout?.on("data",l),c.stderr?.on("data",l),c.on("error",()=>i(1)),c.on("close",(d,u)=>i(typeof d=="number"?d:u?1:0))}catch{i(1)}}),GV=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await my(n,"cursor");return typeof r=="string"?r:t},yx=e=>{let t=e[0]==="--b64"?e[1]:void 0;return HV(t,{exec:KV,trim:GV,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},gx=async()=>{let e=await Mi();if(process.platform==="win32")return 0;let t=UV(e,{isRecognized:n=>dy(n)!==null||j0(n),wrap:n=>Tt(Nu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as jV}from"node:crypto";import{homedir as wx}from"node:os";import{extname as VV,isAbsolute as YV,join as yy,resolve as Fi,sep as bx}from"node:path";import{chmod as ZV,readFile as XV,stat as Sx,unlink as JV,writeFile as zV}from"node:fs/promises";var wy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qV=16*1024,kx=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],QV=["pattern","query","regex","search"],e2=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".pdf",".zip",".gz",".tar",".tgz",".woff",".woff2",".ttf",".otf",".mp3",".mp4",".mov",".wasm",".so",".dylib",".dll",".exe",".bin",".parquet",".sqlite",".db"]),t2=720*60*1e3,n2=512,gy=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},r2=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],Ax=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(bx)?n:n+bx)),o2=(e,t,n)=>YV(e)?[Fi(e)]:[...new Set([Fi(t,e),...n.map(r=>Fi(r,e))])],Cx=(e,t,n)=>jV("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),vx=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),a2=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!wy(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!wy(o))return"";let a=r2(n.workspace_roots).map(d=>Fi(d));if(!a.length)return"";let s=typeof n.cwd=="string"&&n.cwd?n.cwd:a[0],i=typeof n.conversation_id=="string"&&n.conversation_id||typeof n.session_id=="string"&&n.session_id||"";if(r==="Grep"){let d=gy(o,QV);if(!d)return"";let u=gy(o,kx);return u&&!Ax(Fi(s,u),a)||!await t.remember(Cx(i,"Grep",d))?"":vx(`Anyray: run this search with the anyray_search MCP tool instead of the built-in search. anyray_search ranks the matches by relevance and drops the noise, so the hits that answer the task reach you without the rest. Call anyray_search with query ${JSON.stringify(d)} now; do not retry the built-in search.`)}let c=gy(o,kx);if(!c||e2.has(VV(c).toLowerCase()))return"";let l=await t.resolveFile(o2(c,s,a));return!l||l.bytes<qV||!Ax(l.path,a)||!await t.remember(Cx(i,"Read",l.path))?"":vx(`Anyray: ${JSON.stringify(l.path)} is ${Math.round(l.bytes/1024)} KB \u2014 read it with the anyray_read MCP tool instead of the built-in read. anyray_read returns the part of the file that answers the task plus a retrieve handle (ctx_\u2026) you can pass to anyray_retrieve for any detail it elided, so the whole file never enters the context. Call anyray_read now; do not retry the built-in read.`)},s2=async e=>{for(let t of e)try{let n=await Sx(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},i2=async()=>{let e=yy(wx(),".anyray");try{if((await Sx(e)).isDirectory())return yy(e,"cursor-redirects.json")}catch{}return yy(wx(),".anyray-cursor-redirects.json")},c2=async e=>{let t;try{let n=await i2(),r=Date.now(),o={};try{let s=JSON.parse(await XV(n,"utf-8"));if(s?.v===1&&wy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=t2&&(o[i]=c)}catch{}if(o[e]!==void 0)return!1;o[e]=r;let a=Object.entries(o).sort((s,i)=>i[1]-s[1]).slice(0,n2);return t=`${n}.${process.pid}.tmp`,await zV(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await ZV(t,384),await fe(t,n),!0}catch{if(t)try{await JV(t)}catch{}return!1}},Ex=async()=>{let e=await Mi(),t="";try{t=await a2(e,{resolveFile:s2,remember:c2})}catch{t=""}return t&&process.stdout.write(t),0};var Bi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},by=e=>typeof e=="string"&&e.trim()?e.trim():void 0,l2=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Bi(n,"deviceCode"),o=Bi(n,"privateKeyPem"),a=Bi(n,"publicKeyPem"),s=Bi(n,"cpOrigin"),i=Bi(n,"tenantId"),c=n.intervalMs,l=n.grantExpiresAt,d=n.startedAt;if(!r||!o||!a||!s||!i||typeof c!="number"||!Number.isFinite(c)||typeof l!="number"||!Number.isFinite(l)||typeof d!="number"||!Number.isFinite(d))return null;let u=by(n.gatewayUrl),f=by(n.gatewayOverride),p=by(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...f?{gatewayOverride:f}:{},...p?{team:p}:{}}}catch{return null}},d2=e=>new Promise(t=>setTimeout(t,e)),u2=async(e,t)=>{let n=await t.readGateState()??{v:1};await t.writeGateState({v:1,lastAttemptAt:t.now(),failureCount:(n.failureCount??0)+1,lastFailure:e})},p2=async(e,t={})=>{let n=t.poll??xd,r=t.verify??an,o=t.loadProfile??P,a=t.saveProfile??te,s=t.saveDevKey??zi,i=t.readGateState??Er,c=t.writeGateState??Id,l=t.clearGateState??RS,d=t.sleep??d2,u=t.now??Date.now,f=t.recordMint??Aa,p=t.reserveMint??bo,h=t.applyClaudeCode??(async x=>{await nr.apply(x,{dryRun:!1})}),m=x=>u2(x,{readGateState:i,writeGateState:c,now:u}),w={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g;try{g=await n(w,{gatewayUrl:e.gatewayOverride})}catch(x){let A=x instanceof Kt?x.kind:"cp-unreachable";return await m(A),A}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),v={...b,gateway:y??b.gateway,name:g.cert.payload.user||b.name,team:e.team??g.cert.payload.team??b.team,enrolledCert:g.cert,enrolledCertExpiry:g.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(g.privateKeyPem),await a(v)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let S;await p();for(let x=0;x<3;x++)try{S=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(A){if(A instanceof It||x===2)break;await d(1e3)}if(!S)return await m("gateway-unreachable"),"gateway-unreachable";let E={...v,gateway:y,name:S.user,team:e.team??S.team??v.team,clientKey:S.key,clientKeyExpiresAt:S.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:S.expiresAt});let x=ge({origin:y,clientKey:S.key,subscription:!0,user:E.name,team:E.team});return await h(x),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},f2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},xx=async()=>{let e=l2(await f2());if(e)try{await p2(e)}catch{}return 0};var h2=1e4,ky=/^[\w.:-]{1,64}$/,Vt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Ay=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,Ix=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),h2);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new Vt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},m2=e=>{let t=Ay(e);if(!t)return;let n=t.browser_url;try{if(typeof n!="string")return;let r=new URL(n);if(r.protocol!=="http:"&&r.protocol!=="https:")return}catch{return}if(!(typeof t.id!="string"||!t.id||typeof t.user_code!="string"||!t.user_code||typeof t.poll_secret!="string"||!t.poll_secret||typeof t.interval!="number"||!Number.isFinite(t.interval)||t.interval<=0||typeof t.expires_in!="number"||!Number.isFinite(t.expires_in)||t.expires_in<=0))return{id:t.id,browser_url:n,user_code:t.user_code,poll_secret:t.poll_secret,interval:t.interval,expires_in:t.expires_in}},y2=e=>{let t=Ay(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&ky.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&ky.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},g2=e=>{let t=Ay(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ie(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!ky.test(t.team)))return{status:"complete",key:t.key,user:t.user,team:t.team,...typeof t.expires_at=="string"&&{expires_at:t.expires_at}}},w2=e=>new Promise(t=>setTimeout(t,e)),b2=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Vt("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}k("Available teams:"),e.forEach((i,c)=>k(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Oa("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Vt("invalid-team","Choose one of the teams shown above.");return s},k2=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??w2,a=t.loadProfile??P,s=t.saveProfile??te,i=t.clearDevKey??Va,c=t.chooseTeam??b2,l=t.apply??(async g=>{await nr.apply(g,{dryRun:!1})}),d=t.log??F,u=await a(),f=xr(e.gateway,u),p=await Ix(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=m2(p.body);if(p.status!==200||!h)throw new Vt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${h.browser_url}`),d(`Enter this code in the browser: ${h.user_code}`),(t.openBrowser??Ca)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await Ix(`${f}/sso/cli/poll/${encodeURIComponent(h.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":h.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(g.status===202){await o(h.interval*1e3);continue}if(g.status===401)throw new Vt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new Vt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=y2(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new Vt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??jt());continue}let b=g2(g.body);if(g.status!==200||!b)throw new Vt("login-failed","SSO login could not be completed.");let v={...u,gateway:f,name:b.user,team:b.team,clientKey:b.key,clientKeyExpiresAt:b.expires_at,enrolledCert:void 0,enrolledCertExpiry:void 0,enrolledTokenHash:void 0,ssoLink:void 0,authMode:"subscription"};return await i(),await s(v),await l(ge({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Vt("expired","SSO login expired before it completed. Run anyray-connect login again.")},A2=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
724
726
|
|
|
725
727
|
Start browser SSO, choose a team, mint a personal gateway key, and configure
|
|
726
728
|
the subscription-backed Connect lane. In a non-interactive shell, --team may be
|
|
727
|
-
omitted only when the identity authority supplies a default or sole team.`,
|
|
729
|
+
omitted only when the identity authority supplies a default or sole team.`,Rx=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return k(A2),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return O(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return O(`unknown login option: ${a}`),1}try{let o=await k2({gateway:n,team:r},t);return $(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof bt)throw o;return O(o instanceof Vt?o.message:"SSO login failed."),1}};var Ox=`anyray-connect update [--check] [--auto on|off] [--json]
|
|
728
730
|
|
|
729
731
|
Keep this machine's anyray-connect binary on the published release. Runs
|
|
730
732
|
automatically about every 30 minutes; this command forces it now.
|
|
@@ -735,32 +737,32 @@ Options:
|
|
|
735
737
|
Off still accepts a release the Anyray team marks mandatory.
|
|
736
738
|
--json Emit the result as JSON.
|
|
737
739
|
--help Show this help.
|
|
738
|
-
`,
|
|
739
|
-
`),0}let n=await
|
|
740
|
-
`),n.outcome==="failed"?1:0}let r=
|
|
741
|
-
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&
|
|
740
|
+
`,C2=e=>{let t={check:!1,json:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--check")t.check=!0;else if(r==="--json")t.json=!0;else if(r==="--help"||r==="-h")t.help=!0;else if(r==="--auto"){let o=e[++n];if(o!=="on"&&o!=="off")throw new Error("--auto takes `on` or `off`.");t.auto=o==="on"}else throw new Error(`Unknown option: ${r}`)}return t},v2=e=>{switch(e.outcome){case"current":return`Already on the published version (${e.current}).`;case"available":return`Version ${e.latest} is published; this machine is on ${e.current}.`;case"updated":return`Updated ${e.current} \u2192 ${e.latest}. New commands run it immediately.`;case"migrated":return`Installed the managed ${e.latest} binary at ${e.managedPath}.`;case"migration-available":return`Version ${e.latest} will migrate this npm runtime to the managed standalone binary.`;case"migration-deferred":return`The published standalone binary (${e.latest}) is older than this npm runtime (${e.current}); migration was deferred.`;case"disabled":return`Automatic updates are off. Version ${e.latest} is published; this machine is on ${e.current}.`;case"unmanaged":return"This copy is not an Anyray-managed or npm runtime, so it updates elsewhere.";case"container":return"Self-update is skipped inside a container \u2014 it updates by rebuild, not by download-and-swap.";case"platform-unsupported":return"Self-update is unavailable because this platform has no published standalone binary.";case"unavailable":return"Could not reach the release feed to check for a newer version.";case"failed":return`Could not install ${e.latest??"the published version"} \u2014 staying on ${e.current}.`}},_x=async e=>{let t;try{t=C2(e)}catch(o){return O(o.message),process.stderr.write(Ox),1}if(t.help)return process.stdout.write(Ox),0;if(t.auto!==void 0){let o=await P();if(o.autoUpdate!==!1!==t.auto&&await te({...o,autoUpdate:t.auto}),t.json||($(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||k("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!t.auto)return t.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
|
|
741
|
+
`),0}let n=await Pi({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await vo();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state},null,2)}
|
|
742
|
+
`),n.outcome==="failed"?1:0}let r=v2(n);switch(n.outcome){case"updated":case"migrated":$(r);break;case"current":$(r);break;case"available":case"migration-available":k(r),t.check&&k(`Run ${j("anyray-connect update")} to install it.`);break;case"migration-deferred":N(r),k(C("Use the newer npm runtime until that standalone release is published."));break;case"disabled":N(r),k(`Run ${j("anyray-connect update")} to install it now, or ${j("--auto on")} to resume.`);break;case"unmanaged":k(r),k(C("A copy your IT team placed is theirs to roll."));break;case"container":k(r);break;case"platform-unsupported":N(r),k(C("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":N(r);break;case"failed":return O(r),1}return 0};var S2=3e3,Tx=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>Jm(S2)),o=e.updateStatus??vo;t(`anyray-connect ${be}
|
|
743
|
+
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&Da(a,be)>0){let i="Run `anyray-connect update` to install the latest version.";s?.state==="will-migrate"?i="Run `anyray-connect update` to install the managed standalone binary.":s?.state==="container"?i="Self-update is off in this container; updates arrive when it is rebuilt.":s?.state==="platform-unsupported"?i="Self-update is unavailable on this platform; run `npx anyray-connect@latest`.":s?.state==="unmanaged"&&(i="Update this copy with the method that installed it."),n(`Update available: ${be} \u2192 ${a}
|
|
742
744
|
${i}
|
|
743
|
-
`)}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
|
|
744
|
-
`),0};var
|
|
745
|
-
`)}
|
|
746
|
-
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,
|
|
745
|
+
`)}else s?.state==="will-migrate"?n("This npm runtime will migrate to the managed standalone binary on the next persistent setup change.\nRun `anyray-connect update` to migrate now.\n"):s?.state==="container"?n("Self-update and the npm-to-managed-binary migration are off in this container.\nUpdates arrive when the container is rebuilt, not via `anyray-connect update`.\n"):s?.state==="platform-unsupported"&&n("Self-update is unavailable on this platform; use `npx anyray-connect@latest` to stay current.\n");return 0};var E2=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},x2=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),I2=async(e={})=>{try{let t=await(e.readBootstrap??Gt)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??Qe)().catch(()=>{});let n=await(e.loadProfile??P)();if(Ie(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Vn)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??P)(),Ie(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Er)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!E2(a)||!x2(s))return{status:"noop"};let i=r.stderr.trim().replace(/Your prompt was not sent — complete sign-in, then resubmit it\.?/,"Anyray chat models appear after sign-in completes.");return{status:"blocked",url:a,code:s,message:i}}catch{return{status:"noop"}}},Px=async(e={})=>{let t=await I2(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
746
|
+
`),0};var R2="2025-06-18",O2={name:"anyray",version:"1"},Lx={name:"anyray_retrieve",description:'Read back the full original of a tool output Anyray shortened. Whenever you see a marker like "\xB7 retrieve ctx_\u2026 via anyray_retrieve" or "[anyray: \u2026 ctx_\u2026]" and you need what it replaced, call this with that ctx_\u2026 handle. It is a fast lookup of bytes Anyray already stored, so prefer it over re-running the tool, re-reading the file, or searching for the same content again \u2014 those cost far more and may not reproduce it. For large outputs pass grep or startLine/endLine to fetch just the part you need; no extra params returns the full content.',inputSchema:{type:"object",properties:{handle:{type:"string",description:"The ctx_\u2026 handle from an Anyray externalized/trimmed output marker."},startLine:{type:"integer",minimum:1,description:"First line to return (1-based)."},endLine:{type:"integer",minimum:1,description:"Last line to return (inclusive)."},grep:{type:"string",maxLength:256,description:"Literal text; returns matching lines with context."}},required:["handle"],additionalProperties:!1}},_2=20,Dx={name:"anyray_recall",description:'Find an earlier tool output Anyray stashed, by meaning rather than by an exact handle. Pass a natural-language query (e.g. "the failing pytest run"); returns ranked ctx_\u2026 handles with short previews to pass to anyray_retrieve. Use when detail was elided earlier but its ctx_\u2026 marker has scrolled out of view. Matches may include the line range to pass to anyray_retrieve.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Natural-language description of the stashed output to find."},k:{type:"number",description:"Max number of matches to return (default 5)."}},required:["query"],additionalProperties:!1}},Fx=Wm,T2=e=>{if(e==null||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return;let n=Math.round(t);return n<1?1:Math.min(n,Fx)},P2=e=>e==="paths"||e==="lines"||e==="full"?e:"full",Nx={name:"anyray_search",description:"Search the workspace for a string; returns matching file:line results. Use it for broad or noisy searches where relevance ranking is useful: Anyray ranks the matches by relevance to the task and trims the noise, so you get the pertinent hits instead of a raw dump. Pass an exact identifier, or a phrase \u2014 if no line contains the whole phrase the search widens to its terms and ranks the lines carrying most of them. Narrow with globs, and set maxResults when you only need the top few.",inputSchema:{type:"object",properties:{query:{type:"string",description:"What to find: an identifier, a phrase, or error text. Matched literally first; a phrase with no exact hit falls back to its terms. Lowercase matches any case."},globs:{type:"array",items:{type:"string"},description:'Optional include globs to restrict the search (e.g. ["*.ts"]).'},maxResults:{type:"number",description:`Cap matches returned (1-${Fx}). Ask for fewer when you only need the top hits.`},resultShape:{type:"string",enum:["paths","lines","full"],description:"'paths' = matching files + counts; 'lines' = file:line only; 'full' (default) = file:line plus the matched text. Prefer 'paths' when you only need to know WHERE something lives."}},required:["query"],additionalProperties:!1}},$x={name:"anyray_read",description:"Read a workspace file. Prefer this over the built-in file read, especially for large files: Anyray returns the task-relevant portion plus a `retrieve ctx_\u2026` handle for anyray_retrieve, so you spend context on the pertinent lines without losing access to the rest. Pass a path inside the workspace; optionally a 1-based line range.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path to read (workspace-relative or absolute)."},startLine:{type:"number",description:"Optional 1-based inclusive start line."},endLine:{type:"number",description:"Optional 1-based inclusive end line."},focus:{type:"string",description:'What you need from this file, in your own words (e.g. "the exported symbols", "where the retry budget is applied"). Anyray ranks the returned slice against it, so you get the pertinent lines rather than the head of the file.'}},required:["path"],additionalProperties:!1}},L2=8,D2=3,Mx={name:"anyray_history",description:'Search the user\'s imported Claude conversation history (past chats from their Claude account, imported with `anyray-connect history import`). Use whenever the user refers to an earlier conversation you cannot see ("what did we decide about X?"), especially in a client whose own history is unavailable. Call with `query` to find conversations, then `open` (a filename from those results) to read one in full.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Words to look for in past conversations (topic, name, phrase)."},open:{type:"string",description:"Filename from a previous result, to read that conversation in full."}},additionalProperties:!1}},N2=e=>{if(e.length===0)return"No matching stashed outputs found.";let t=e.map((n,r)=>`${r+1}. ${n.handle} (score ${n.score.toFixed(2)})`+(typeof n.startLine=="number"&&typeof n.endLine=="number"?` (lines ${n.startLine}-${n.endLine})`:"")+(n.preview?` \u2014 ${n.preview}`:""));return[`Found ${e.length} matching stashed output${e.length===1?"":"s"} (ranked by relevance):`,...t,"Call anyray_retrieve with a handle above \u2014 pass its lines (startLine/endLine) to fetch just the matching part, or no extra params for the full original."].join(`
|
|
747
|
+
`)},$2=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
748
|
+
If the user expected one, their export may predate it, or no export has been imported yet (\`anyray-connect history import <conversations.json>\`).`;let n=new Map;for(let a of t.matches){let s=n.get(a.file)??[];s.push(a),n.set(a.file,s)}let r=[...n.entries()].slice(0,L2).map(([a,s])=>{let i=s.slice(0,D2).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
747
749
|
`)});return[t.matched==="tokens"&&t.tokens?.length?`No imported conversation contains "${e}"; ${n.size} mention${n.size===1?"s":""} some of its terms (${t.tokens.join(", ")}):`:`${n.size} imported conversation${n.size===1?"":"s"} mention "${e}":`,...r,'Call anyray_history({open: "<filename>"}) to read one in full.'].join(`
|
|
748
|
-
`)},Le=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),
|
|
750
|
+
`)},Le=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),Cy=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),ve=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
|
|
749
751
|
|
|
750
752
|
[anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
|
|
751
753
|
|
|
752
754
|
[anyray: output cut to fit the tool-result limit \u2014 ${n.length} chars total. Re-run narrowed (globs, a line range, or grep) to see the rest.]`,o=n.slice(0,4e4-r.length),a=o.lastIndexOf(`
|
|
753
|
-
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},
|
|
754
|
-
${p.content}`))}return Le(n??null,
|
|
755
|
-
`)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let h;try{h=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let m;try{m=await
|
|
756
|
-
`))>=0;){let h=u.slice(0,p);u=u.slice(p+1),await l(h)}}u.trim()&&await l(u)}catch(f){console.error("anyray mcp: stdin error",f instanceof Error?f.message:f)}finally{clearInterval(d)}return 0};import{spawn as
|
|
755
|
+
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},M2=async(e,t)=>{let n=e?.id,r=n===void 0,o=typeof e?.method=="string"?e.method:"";switch(o){case"initialize":try{t.heartbeat?.()}catch{}return Le(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:R2,capabilities:{tools:{}},serverInfo:O2});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Le(n??null,{});case"tools/list":{let a=[Lx,Dx];t.advertiseContextTools!==!1&&a.push(Nx,$x);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(Mx),Le(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===Lx.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Le(n??null,ve("handle is required",!0));let c=m=>{if(m!==void 0)return typeof m!="number"||!Number.isFinite(m)?null:Math.max(Math.round(m),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return Le(n??null,ve("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return Le(n??null,ve("grep must be non-empty",!0));if(s.grep.length>256)return Le(n??null,ve("grep is limited to 256 characters",!0));u=s.grep}let f=l!==void 0||d!==void 0||u!==void 0,p;try{p=await t.retrieve(i,f?{startLine:l,endLine:d,grep:u}:void 0)}catch(m){p={ok:!1,message:m instanceof Error?m.message:"retrieve failed"}}let h="this gateway does not support partial retrieval yet \u2014 call again without startLine/endLine/grep for the full content";if(!p.ok)return Le(n??null,ve(p.kind==="slice-unsupported"?h:p.message,!0));if(f&&(p.partial===void 0||typeof p.totalLines!="number"))return Le(n??null,ve(h,!0));if(p.partial===!0&&typeof p.totalLines=="number"){let m=p.grepMatches!==void 0?`[anyray: partial \u2014 ${p.grepMatches} matching line(s) in lines ${p.startLine}-${p.endLine} of ${p.totalLines}`+(p.grepTruncated?`, windows around the first ${_2} matches shown \u2014 narrow the range or grep`:"")+` \xB7 retrieve ${i} again with startLine/endLine, another grep, or no params for full]`:`[anyray: partial \u2014 lines ${p.startLine}-${p.endLine} of ${p.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return Le(n??null,ve(`${m}
|
|
756
|
+
${p.content}`))}return Le(n??null,ve(p.content))}if(a.name===Dx.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Le(n??null,ve("query is required",!0));let c=typeof s.k=="number"?s.k:void 0,l;try{l=await t.recall(i,c)}catch(d){l={ok:!1,message:d instanceof Error?d.message:"recall failed"}}return Le(n??null,l.ok?ve(N2(l.matches)):ve(l.message,!0))}if(a.name===Nx.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Le(n??null,ve("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=T2(s.maxResults),d=P2(s.resultShape),u;try{u=await t.search(i,c,l)}catch(f){u={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:f instanceof Error?f.message:"search failed"}}return Le(n??null,u.ok?ve(c0(i,u,d)):ve(u.message??"search failed",!0))}if(a.name===Mx.name){let i=typeof s.open=="string"?s.open.trim():"";if(i){let d;try{d=await t.historyOpen(i)}catch(u){d={ok:!1,content:"",path:i,lines:0,truncated:!1,message:u instanceof Error?u.message:"history open failed"}}return Le(n??null,d.ok?ve(Bm(d)):ve(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Le(n??null,ve("query (or open) is required",!0));let l;try{l=await t.historySearch(c)}catch(d){l={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:d instanceof Error?d.message:"history search failed"}}return Le(n??null,l.ok?ve($2(c,l)):ve(l.message??"history search failed",!0))}if(a.name===$x.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Le(n??null,ve("path is required",!0));let c={startLine:typeof s.startLine=="number"?s.startLine:void 0,endLine:typeof s.endLine=="number"?s.endLine:void 0},l;try{l=await t.read(i,c)}catch(d){l={ok:!1,content:"",path:i,lines:0,truncated:!1,message:d instanceof Error?d.message:"read failed"}}return Le(n??null,l.ok?ve(Bm(l)):ve(l.message??"read failed",!0))}return Cy(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Cy(n??null,-32601,`method not found: ${o}`)}},F2=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),gd);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Xt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},B2=(e,t=!0)=>({retrieve:async(n,r)=>ba(await e(),n,r),recall:async(n,r)=>wd(await e(),n,r),search:(n,r,o)=>Wd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Hd(n,r),historySearch:n=>u0(n),historyOpen:n=>p0(n),historyAvailable:async()=>await Pa()>0,advertiseContextTools:t,heartbeat:()=>{e().then(F2).catch(()=>{})}}),Bx=async(e="auto",t={})=>{let n=B2(()=>rt(e),e!=="claude"),r=t.stdin??process.stdin,o=t.stdout??process.stdout,a=0,s=t.refreshTick??(()=>{let f=Date.now();f<a||(a=f+6e4,Sr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=f=>{try{o.write(JSON.stringify(f)+`
|
|
757
|
+
`)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let h;try{h=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let m;try{m=await M2(h,n)}catch(w){console.error("anyray mcp: dispatch error",w instanceof Error?w.message:w),m=h?.id===void 0?null:Cy(h.id,-32603,"internal error")}m&&c(m),i()};i();let d=setInterval(i,30*6e4);d.unref?.();let u="";try{for await(let f of r){u+=f.toString("utf-8");let p;for(;(p=u.indexOf(`
|
|
758
|
+
`))>=0;){let h=u.slice(0,p);u=u.slice(p+1),await l(h)}}u.trim()&&await l(u)}catch(f){console.error("anyray mcp: stdin error",f instanceof Error?f.message:f)}finally{clearInterval(d)}return 0};import{spawn as U2}from"node:child_process";var H2=e=>e==="jetbrains"||e==="windsurf"?e:void 0,W2=async(e,t,n,r=1e4)=>{let o=await new Promise(a=>{let s="",i=!1,c=p=>{i||(i=!0,clearTimeout(l),t.off("data",d),t.off("error",u),t.off("end",f),a(p))},l=setTimeout(()=>c(void 0),r),d=p=>{s+=p.toString();let h=s.indexOf(`
|
|
757
759
|
`);h!==-1?c(s.slice(0,h)):s.length>65536&&c(void 0)},u=()=>c(void 0),f=()=>c(s.length>0?s:void 0);t.on("data",d),t.once("error",u),t.once("end",f)});if(o===void 0)return!1;try{let s=JSON.parse(o)?.id;return typeof s!="number"&&typeof s!="string"?!1:(n.write(`${JSON.stringify({jsonrpc:"2.0",id:s,error:{code:-32e3,message:e}})}
|
|
758
|
-
`),!0)}catch{return!1}},
|
|
759
|
-
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!
|
|
760
|
-
`),1;await(n.refreshIfDue??Qe)().catch(()=>{});let s=await(n.loadProfile??
|
|
761
|
-
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??
|
|
762
|
-
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",g=["/d","/s","/c",`"${h.command}" ${h.args.join(" ")}`]}return await new Promise(y=>{let b=
|
|
763
|
-
`),y(1)}),v.once("exit",(S,E)=>{y(typeof S=="number"?S:E?1:0)})})};import{createReadStream as
|
|
760
|
+
`),!0)}catch{return!1}},K2={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},G2=(e,t,n)=>{let r=new Set(K2[e].map(s=>s.toUpperCase())),o=new Set(Object.keys(n).map(s=>s.toUpperCase())),a={...t};for(let s of Object.keys(a)){let i=s.toUpperCase();(r.has(i)||o.has(i)||i==="APP_SERVER_LOGS")&&delete a[s]}return{...a,...n}},Ux=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
761
|
+
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!Ql(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
762
|
+
`),1;await(n.refreshIfDue??Qe)().catch(()=>{});let s=await(n.loadProfile??P)(),i=await(n.readBootstrap??Gt)().catch(()=>{});if(i){let y=await(n.ssoGate??Vn)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(y.exitCode===2&&y.stderr)return await W2(y.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(y.stderr),1;s=await(n.loadProfile??P)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
|
|
763
|
+
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??Dt)():void 0,d=ge({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=H2(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",p=(n.hookBinaryIsDurable??ce)(),h=av(d,t,{mcpServer:p?je("profile"):void 0})[f],m=n.spawn??U2,w=h.command,g=h.args;if(o==="win32"){if(!h.args.every(y=>y==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(y)))return r.write(`Anyray ACP adapter arguments are invalid.
|
|
764
|
+
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",g=["/d","/s","/c",`"${h.command}" ${h.args.join(" ")}`]}return await new Promise(y=>{let b=G2(e,a,h.env),v=m(w,g,{env:b,stdio:"inherit",windowsHide:!0});v.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
|
|
765
|
+
`),y(1)}),v.once("exit",(S,E)=>{y(typeof S=="number"?S:E?1:0)})})};import{createReadStream as j2}from"node:fs";import{spawnSync as qx}from"node:child_process";import{createHash as V2}from"node:crypto";import{access as Qx,chmod as Ey,copyFile as Y2,lstat as Z2,mkdir as X2,mkdtemp as eI,readFile as iu,rename as J2,rm as Tr,stat as z2,writeFile as q2}from"node:fs/promises";import{constants as tI}from"node:fs";import{platform as cu,tmpdir as Q2}from"node:os";import{dirname as eY,isAbsolute as tY,join as ou}from"node:path";import{z as Me}from"zod";var nY="fleetd-installer-v4.89.2",Hx=`https://github.com/anyrayHQ/install/releases/download/${nY}`,rY=1e4,oY=1e4,Wx=31,aY=1500,nI=20*1024,vy=20,sY="0.25",iY="/var/tmp",Fa="/Library/LaunchDaemons/com.fleetdm.orbit.plist",au="/etc/default/orbit",Hi="/opt/orbit/anyray-enroll-secret.txt",rI="/opt/orbit/secret-orbit-node-key.txt",cY="/opt/orbit/bin/orbit/orbit",Wi="C:\\Program Files\\Orbit",lY=`${Wi}\\bin\\orbit`,oI=`${Wi}\\secret-orbit-node-key.txt`,Ui=`${Wi}\\secret.txt`,dY=`${Wi}\\fleet_url.txt`,aI=`${Wi}\\anyray-managed.txt`,su="Fleet osquery",xy="C:\\Windows\\System32\\sc.exe",uY="C:\\Windows\\System32\\whoami.exe",ru="C:\\Windows\\System32\\icacls.exe",pY="C:\\Windows\\System32\\msiexec.exe",Iy="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",Kx=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],fY=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],hY=`anyray-connect endpoint install
|
|
764
766
|
|
|
765
767
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
766
768
|
|
|
@@ -768,11 +770,11 @@ Supported on macOS, Linux and Windows.
|
|
|
768
770
|
|
|
769
771
|
The command uses the current seat's stored gateway key. Administrator access is
|
|
770
772
|
required: on macOS and Linux Connect asks through sudo once when /dev/tty is
|
|
771
|
-
available; on Windows, run it from a shell started as Administrator.`,
|
|
772
|
-
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",
|
|
773
|
-
`&&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},
|
|
773
|
+
available; on Windows, run it from a shell started as Administrator.`,sI=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),ae=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},mY=Me.object({kind:Me.enum(["pkg","deb","rpm","msi"]),path:Me.string().min(1).refine(tY),sha256:Me.string().regex(/^[0-9a-f]{64}$/)}).strict(),yY=Me.object({action:Me.literal("restart"),os:Me.enum(["darwin","linux","win32"])}).strict(),gY=Me.object({action:Me.literal("configure"),os:Me.enum(["darwin","linux","win32"]),fleetUrl:Me.string().min(1).max(2048),enrollSecret:Me.string().min(1).max(4096),package:mY.optional()}).strict(),wY=Me.discriminatedUnion("action",[yY,gY]),Ki=(e,t)=>{let n=qx(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},_y=async e=>{try{return await Qx(e,tI.F_OK),!0}catch{return!1}},bY=async e=>{try{let t=await z2(e);return t.isFile()&&t.size>0}catch{return!1}},Ty=(e,t)=>{for(let n=0;;){let r=e.indexOf("<key>",n);if(r<0)return null;let o=e.indexOf("</key>",r);if(o<0)return null;if(e.slice(r+5,o).trim()===t)return{start:r,end:o+6};n=o+6}},Sy=(e,t)=>Ty(e,t)!==null,Gx=e=>e==="win32"?Ui:Hi,kY=e=>e==="win32"?oI:rI,AY=e=>Sy(e,"ORBIT_FLEET_URL")&&Sy(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Hi}</string>`)&&!Sy(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),CY=e=>{let t=(n,r)=>e.split(`
|
|
774
|
+
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Hi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Ry=(e,t)=>{if(e==="win32"){let a="--fleet-url ",s=t.indexOf(a);if(s<0)return;let i=t.slice(s+a.length),c;if(i.startsWith('"')){let d=i.indexOf('"',1);if(d<0)return;c=i.slice(1,d)}else{let d=i.indexOf(" ");c=d<0?i:i.slice(0,d)}let l=c.trim();return l.length>0?l:void 0}if(e==="darwin"){let a=t.indexOf("<key>ORBIT_FLEET_URL</key>");if(a<0)return;let s=t.indexOf("<string>",a),i=t.indexOf("</string>",s);return s<0||i<0?void 0:t.slice(s+8,i).replace(/</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()},iI=e=>{let t=e(xy,["qc",su,"8192"]);return t.status===0?t.stdout:""},Oy=e=>{let t=e(Iy,fY(su)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},vY=async e=>{try{return e==="win32"?Ry(e,iI(Ki)):Ry(e,await iu(e==="darwin"?Fa:au,"utf8"))}catch{return}},SY=async e=>{try{if(e==="win32")return await _y(aI)&&Ry(e,iI(Ki))!==void 0;let n=await iu(e==="darwin"?Fa:au,"utf8");return e==="darwin"?AY(n):CY(n)}catch{return!1}},cI=async(e,t={})=>{let n=t.exists??_y,r=t.command??Ki,o,a="absent";if(e==="win32")a=Oy(r),o=await n(lY)&&a!=="absent";else{let l=e==="darwin"?await n(Fa):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(cY)&&l}let s=await(t.configured??SY)(e),i=await(t.hasNodeKey??(()=>bY(kY(e))))(),c=!1;if(o)if(e==="darwin"){let l=r("/bin/launchctl",["print","system/com.fleetdm.orbit"]);c=l.status===0&&/\bstate\s*=\s*running\b/.test(l.stdout)}else e==="linux"?c=r("systemctl",["is-active","--quiet","orbit"]).status===0:c=a==="Running";return{installed:o,configured:s,running:c,checkedIn:i}},EY=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),lI=(e,t)=>{let n=Ty(e,t);if(!n)return null;let r=n.start;for(;r>0&&(e[r-1]===" "||e[r-1]===" ");)r--;r>0&&e[r-1]===`
|
|
775
|
+
`&&r--;let o=n.end;for(;o<e.length&&/\s/.test(e[o]);)o++;if(e.startsWith("<string>",o)){let a=e.indexOf("</string>",o);return a<0?null:{start:r,end:a+9}}if(e.startsWith("<true",o)||e.startsWith("<false",o)){let a=e.indexOf("/>",o);return a<0?null:{start:r,end:a+2}}return null},xY=(e,t)=>{let n=lI(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},jx=(e,t,n)=>{let r=`
|
|
774
776
|
<key>${t}</key>
|
|
775
|
-
<string>${
|
|
777
|
+
<string>${EY(n)}</string>`,o=lI(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Ty(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new ae("The installed Orbit LaunchDaemon has no EnvironmentVariables dictionary; it was left unchanged.");let i=s+6;return e.slice(0,i)+r+e.slice(i)},IY=(e,t,n=Hi)=>{let r=xY(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=jx(r,"ORBIT_FLEET_URL",t),jx(r,"ORBIT_ENROLL_SECRET_PATH",n)},RY=(e,t,n=Hi)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
|
|
776
778
|
`).filter(a=>{let s=a.indexOf("=");return s<0?!0:!r.has(a.slice(0,s).trim())}).filter((a,s,i)=>a.trim()!==""||i[s-1]?.trim()!=="").join(`
|
|
777
779
|
`).trimEnd()}
|
|
778
780
|
|
|
@@ -782,13 +784,13 @@ available; on Windows, run it from a shell started as Administrator.`,Jx=e=>!!(e
|
|
|
782
784
|
# file, never in this world-readable one.
|
|
783
785
|
ORBIT_FLEET_URL=${t}
|
|
784
786
|
ORBIT_ENROLL_SECRET_PATH=${n}
|
|
785
|
-
`},
|
|
786
|
-
`,384);e.os!=="win32"&&await
|
|
787
|
-
`,384),e.os==="win32"&&
|
|
788
|
-
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??
|
|
789
|
-
sudo anyray-connect endpoint install`),"deferred"},
|
|
790
|
-
`;if(Buffer.byteLength(t)>
|
|
791
|
-
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=
|
|
787
|
+
`},dI=e=>{if(/[\u0000-\u0020\u007f]/.test(e)||/["'`\\^<>|{}]/.test(e))return!1;try{let t=new URL(e);return t.username||t.password?!1:t.protocol==="https:"?!0:t.protocol==="http:"&&(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1")}catch{return!1}},OY=Me.object({code:Me.string().min(1).optional(),message:Me.string().min(1).optional()}).passthrough(),Vx=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},_Y=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=OY.safeParse(t);if(!r.success)return n;let o=Vx(r.data.message??""),a=Vx(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},Yx=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??oY),a;try{a=await(n.fetchResponse??fetch)(`${e}/connect/endpoint-enrollment`,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":be},body:"{}",signal:r.signal})}catch{throw new ae("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new ae("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new ae(_Y(a.status,c))}let s;try{s=await a.json()}catch{throw new ae("The gateway returned malformed endpoint enrollment data.")}let i=Me.object({fleetUrl:Me.string().min(1).max(2048),enrollSecret:Me.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!dI(i.data.fleetUrl))throw new ae("The gateway returned invalid endpoint enrollment data.");return i.data},TY=async(e={})=>{let t=e.exists??_y;if(await t("/usr/bin/dpkg")||await t("/bin/dpkg"))return"deb";if(await t("/usr/bin/rpm")||await t("/bin/rpm"))return"rpm";throw new ae("Linux endpoint installation requires either dpkg or rpm.")},PY=async e=>e==="darwin"?"pkg":e==="win32"?"msi":TY(),Py=e=>`fleetd.${e}`,LY=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",DY=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),rY);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},NY=async(e,t={})=>{let n=Py(e),r=t.fetchResponse??fetch,o;try{o=await DY(`${Hx}/SHA256SUMS`,r)}catch{throw new ae("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new ae(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=Zm(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await eI(ou(Q2(),"anyray-endpoint-")),i=ou(s,n);try{await Ey(s,448),await(t.download??zm)(`${Hx}/${n}`,i,a)}catch(c){if(await Tr(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Ti&&c.status===404)return;throw new ae("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Tr(s,{recursive:!0,force:!0})}},$Y=async(e,t,n)=>{await X2(eY(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Tr(r,{force:!0});try{await q2(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await J2(r,e)}catch(o){throw await Tr(r,{force:!0}).catch(()=>{}),o}},Zx=async e=>{let t=V2("sha256");for await(let n of j2(e))t.update(n);return t.digest("hex")},MY=async(e,t={})=>{let n=await Z2(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new ae("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await Zx(e.path)!==e.sha256)throw new ae("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await eI(ou(iY,"anyray-endpoint-root-")),o=ou(r,Py(e.kind));try{if(await Ey(r,448),await Y2(e.path,o),await Ey(o,384),await Zx(o)!==e.sha256)throw new ae("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Tr(r,{recursive:!0,force:!0})}}catch(a){throw await Tr(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ma=(e,t)=>{if(e.status!==0)throw new ae(t)},Xx="com.fleetdm.fleetd.config",FY="com.fleetdm.fleetd.enroll.secret",BY=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",rI],UY=[dY,oI],HY=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(Xx))throw new ae(`This machine already receives its endpoint configuration from an MDM profile (${Xx}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},Jx=async(e,t,n)=>{let r=n.removeFile??(o=>Tr(o,{force:!0}));for(let o of e==="win32"?UY:BY)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",FY,"/Library/Keychains/System.keychain"])},WY=e=>{e(ru,[Ui,"/inheritance:r"]),e(ru,[Ui,"/grant:r","*S-1-5-18:(F)"]),e(ru,[Ui,"/grant:r","*S-1-5-32-544:(F)"]),e(ru,[Ui,"/remove:g","*S-1-5-32-545"])},KY=(e,t,n)=>{if(e.kind==="pkg"){Ma(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ma(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ma(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ma(t(pY,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},GY=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<vy;r++){if(n=t("/bin/launchctl",["bootstrap","system",Fa]),n.status===0)return;t("/bin/sleep",[sY])}throw new ae(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(xy,["stop",su]);for(let n=0;n<vy;n++){let r=Oy(t);if(r==="Stopped"||r==="absent")break;t(Iy,Kx)}for(let n=0;n<vy;n++){if(t(xy,["start",su]).status===0||Oy(t)==="Running")return;t(Iy,Kx)}throw new ae("Orbit was configured, but the Windows service could not be started.")}Ma(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ma(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},jY=e=>new Promise(t=>setTimeout(t,e)),uI=async(e,t={})=>{let n=t.command??Ki,r=t.readText??(c=>iu(c,"utf8")),o=t.writeText??$Y,a=t.removeSecret??(()=>Tr(Gx(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&HY(n),e.package&&!LY(e.os,e.package.kind))throw new ae("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new ae("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await Jx(e.os,n,t),e.package){let d=await(t.preparePackage??MY)(e.package);i=d.cleanup,KY(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Fa);await o(Fa,IY(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(au);await o(au,RY(d,e.fleetUrl),420)}else await o(aI,`anyray
|
|
788
|
+
`,384);e.os!=="win32"&&await Jx(e.os,n,t),await o(Gx(e.os),`${e.enrollSecret}
|
|
789
|
+
`,384),e.os==="win32"&&WY(n),s=e.os!=="win32"}GY(e.os,n);let c=t.checkIn??(async d=>{let u=await cI(d);return u.running&&u.checkedIn}),l=t.wait??jY;for(let d=0;d<(t.attempts??Wx);d++){if(await c(e.os))return;d+1<(t.attempts??Wx)&&await l(aY)}throw new ae("The endpoint agent did not check in after restart. The package command succeeded, but enrollment was not confirmed.")}finally{s&&await a().catch(()=>{}),await i?.().catch(()=>{})}},VY=async()=>{try{return await Qx("/dev/tty",tI.R_OK),!0}catch{return!1}},YY=12288,ZY=e=>{let t=e(uY,["/groups"]);if(t.status!==0)return!1;let n=-1;for(let r=0;;){let o=t.stdout.indexOf("S-1-16-",r);if(o<0)break;r=o+7;let a=r;for(;a<t.stdout.length&&t.stdout[a]>="0"&&t.stdout[a]<="9";)a++;a>r&&(n=Math.max(n,Number(t.stdout.slice(r,a)))),r=a}return n>=YY},XY=async(e,t={})=>{if((t.os??cu())==="win32")return(t.elevated??(()=>ZY(t.command??Ki)))()?(await e(),"direct"):((t.print??k)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
790
|
+
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??VY)()){if(await(t.reexec??(async()=>1))()!==0)throw new ae("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??k)(`Administrator access is required. Run:
|
|
791
|
+
sudo anyray-connect endpoint install`),"deferred"},JY=async e=>{let t=`${JSON.stringify(e)}
|
|
792
|
+
`;if(Buffer.byteLength(t)>nI)throw new ae("The privileged endpoint plan is unexpectedly large.");let n=dn(["__anyray-endpoint-install"]);return qx("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},zY=async(e,t={})=>(t.withRoot??XY)(()=>(t.apply??uI)(e),{...t.root,reexec:()=>(t.sudo??JY)(e)}),zx=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return P();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return P();let t;try{let s=(await iu("/etc/passwd","utf8")).split(`
|
|
793
|
+
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=cu()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await P()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},pI=async(e={},t={})=>{let n=t.os??cu();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new ae("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??cI)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??zx)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??vY)(r);if(!l||!d||u===void 0)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};let f=await(t.fetchEnrollment??Yx)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};F("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new ae("This machine is already enrolled in a different Fleet configuration; it was left unchanged.");let s,i;if(o.installed&&o.configured&&o.checkedIn&&!a)s={action:"restart",os:r};else{let c=e.gateway&&e.clientKey?void 0:await(t.profile??zx)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new ae("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??Yx)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>PY(r)))();if(i=await(t.stagePackage??NY)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${Py(f)} is not published yet; skipping.`}}s={action:"configure",os:r,...u,...i?{package:{kind:i.kind,path:i.path,sha256:i.sha256}}:{}}}try{return await(t.execute??zY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},Ly=e=>e instanceof ae?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",fI=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return k(hY),0;if(e.length!==1||e[0]!=="install")return O("Usage: anyray-connect endpoint install"),1;try{let t=await pI();return t.message&&(t.outcome==="installed"?$(t.message):F(t.message)),0}catch(t){return O(Ly(t)),1}},qY=async()=>{let e=[],t=0;for await(let o of process.stdin){let a=Buffer.isBuffer(o)?o:Buffer.from(o);if(t+=a.length,t>nI)throw new ae("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new ae("The privileged endpoint plan is malformed.")}let r=wY.safeParse(n);if(!r.success||r.data.os!==cu()||r.data.action==="configure"&&!dI(r.data.fleetUrl))throw new ae("The privileged endpoint plan is invalid.");return r.data},hI=async e=>{if((process.getuid?.()??-1)!==0)return O("The privileged endpoint step must run as root."),1;if(e.length!==0)return O("The privileged endpoint step does not accept arguments."),1;try{return await uI(await qY()),0}catch(t){return O(Ly(t)),1}},mI=async(e,t=pI)=>{try{let n=await t(e);n.message&&(n.outcome==="installed"?$(n.message):F(n.message))}catch(n){F(`Endpoint agent: ${Ly(n)} Tool routing remains configured.`)}};import{execSync as Dy}from"node:child_process";import{hostname as QY}from"node:os";var eZ=e=>{try{if(e==="darwin"){let t=Dy("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=Dy('reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid',{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/MachineGuid\s+REG_SZ\s+([\w-]+)/.exec(t)?.[1]??""}return Dy("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},lu=(e={platform:process.platform,read:()=>eZ(process.platform),hostname:QY})=>e.read().trim()||e.hostname().trim();var tZ=(e,t=Date.now())=>e.credentialProtocol==="stable-heartbeat-v1"||!Cd(e,void 0,t),yI=async(e,t={})=>{if(!await(t.fleetdPresent??$a)())return{retired:!1,reason:"no-fleetd",messages:[]};if(!tZ(e,t.now??Date.now()))return{retired:!1,reason:"seat-could-lapse",messages:[]};let r=[],o=await(t.uninstallScheduler??ir)();r.push(...o.messages);let a=await(t.uninstallProxy??Jt)();return r.push(...a.messages),{retired:!0,messages:r}};var gI=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();return t?t.toLowerCase():(e.platform??process.platform)==="darwin"?(e.readMacUuid??(()=>lu()))().trim().toLowerCase():""};var wI=["reapply_config","remint","revert","revert_tool"],nZ=/^[a-z0-9][a-z0-9-]{0,31}$/;var rZ=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||t.id.length===0||typeof t.kind!="string"||!wI.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&nZ.test(t.tool):t.tool===void 0},Ny=e=>e?.name??"error",bI=async(e,t,n)=>{let r=n.fetchImpl??fetch,o=e.replace(/\/$/,""),a;try{let i=await r(`${o}/connect/directive`,{method:"GET",headers:{"x-anyray-api-key":t,"x-anyray-directive-kinds":wI.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!rZ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",Ny(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",Ny(i)),s="failed"}try{await r(`${o}/connect/directive/ack`,{method:"POST",headers:{"x-anyray-api-key":t,"content-type":"application/json"},body:JSON.stringify({id:a.id,result:s}),signal:AbortSignal.timeout(1e4)})}catch(i){console.error("connect directive ack skipped:",Ny(i))}return a.kind};var oZ=1e4,Ba=e=>e?.name??"Error",$y=async(e,t=fetch)=>{let n=e.gateway?.replace(/\/+$/,""),r=e.clientKey;if(!(!n||!r))try{await t(`${n}/connect/offboard`,{method:"POST",headers:{"x-anyray-api-key":r},signal:AbortSignal.timeout(oZ)})}catch(o){console.error(`anyray seat offboard report: ${Ba(o)}`)}},aZ=e=>e==="reverted"||e==="queued",kI=async(e={})=>{let t=e.loadProfile??P,n=e.clearDeviceTokenState??Rd,r=e.reportSeatOffboarded??$y,o=e.clearEnrollment??qi,a=e.recordManagedTools??Xn,s=e.markSeatOffboarded??ec,i=e.adapterById??Ht,c=e.uninstallProxy??Jt,l=e.uninstallScheduler??ir,d=e.unitsPresent??Ci,u=e.saveProfile??te,f=await t(),p=f.managedTools??[];await r(f).catch(()=>{}),await n().catch(()=>{});let h=!1,m=!1;try{h=await o()}catch(E){m=!0,console.error(`anyray offboard: clearing enrollment: ${Ba(E)}`)}let w=[],g=[],y=[];for(let E of p){let x=i(E);if(!x){y.push(E);continue}try{let A=await x.revert({dryRun:!1,fullRevert:!0});w.push({id:E,status:A.status}),aZ(A.status)?g.push(E):y.push(E)}catch(A){console.error(`anyray offboard: reverting ${E}: ${Ba(A)}`),y.push(E)}}let b=!0;try{await a(w,!0,!0)}catch(E){b=!1,console.error(`anyray offboard: recording managed tools: ${Ba(E)}`)}let v=y.length===0&&b,S=!1;if(v)try{await s(),S=!0}catch(E){console.error(`anyray offboard: stamping offboard: ${Ba(E)}`)}try{let E=await t();(E.fallbackPort||await d("daemon"))&&await c(E.fallbackPort),(E.refreshSchedulerEnabled||await d("scheduler"))&&await l(),await u({...await t(),keyRefreshEnabled:!1,fallbackPort:void 0,refreshSchedulerEnabled:!1})}catch(E){console.error(`anyray offboard: unit teardown: ${Ba(E)}`)}return{reverted:g,unresolved:y,enrollmentCleared:h,credentialHeld:m,recordPersisted:b,offboardMarked:S,ok:y.length===0&&!m&&b&&S}};var AI=e=>e?.name??"Error",CI=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??P,r=t.recordManagedTools??Xn,o=t.adapterById??Ht,a=t.isLocked??ui,s=await n().catch(()=>{});if(!s)return"failed";if(!(s.managedTools??[]).includes(e))return"ok";if(a(s,e))return console.error(`anyray revert-tool: ${e} is locked by fleet policy`),"failed";let i=o(e);if(!i)return"failed";let c;try{c=(await i.revert({dryRun:!1,fullRevert:!1})).status}catch(l){return console.error(`anyray revert-tool: reverting ${e}: ${AI(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${AI(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as iZ}from"node:os";var EI=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
792
794
|
|
|
793
795
|
${j("Usage")}
|
|
794
796
|
npx anyray-connect [options]
|
|
@@ -808,7 +810,7 @@ ${j("Options")}
|
|
|
808
810
|
--enroll <link> Connect with a passwordless enrollment link or token
|
|
809
811
|
--sso <link> Connect with an enterprise SSO link or tenant id
|
|
810
812
|
--claim <code> Redeem the one-time code from your org's Anyray sign-in page
|
|
811
|
-
--tools <ids> Comma-separated subset: ${
|
|
813
|
+
--tools <ids> Comma-separated subset: ${oe.map(e=>e.id).join(", ")}
|
|
812
814
|
--user <id> Attribute spend to this user
|
|
813
815
|
--team <id> Attribute spend to this team
|
|
814
816
|
--dry-run Show what would change without writing anything
|
|
@@ -825,7 +827,7 @@ ${j("What it does")}
|
|
|
825
827
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
826
828
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
827
829
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
828
|
-
per-skill versions ${C("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
830
|
+
per-skill versions ${C("sync")} last wrote \u2014 for zero-question re-runs.`,xI=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
829
831
|
|
|
830
832
|
${j("Usage")}
|
|
831
833
|
npx anyray-connect <gateway-url> [options]
|
|
@@ -910,8 +912,9 @@ ${j("Options")}
|
|
|
910
912
|
--key <value> Legacy placeholder value for config compatibility. It does
|
|
911
913
|
not authenticate /v1 requests; enrollment is still required.
|
|
912
914
|
--enroll <link> Passwordless enrollment. Paste the https://\u2026/enroll/<token>
|
|
913
|
-
link your admin minted
|
|
914
|
-
|
|
915
|
+
link your admin minted \u2014 the short https://\u2026/i/<token> form
|
|
916
|
+
and a bare token also work. connect resolves the gateway
|
|
917
|
+
from the link, generates an Ed25519
|
|
915
918
|
keypair, enrolls the public key at the control plane for a
|
|
916
919
|
signed cert, then mints a short-lived personal gateway key
|
|
917
920
|
from it \u2014 no SSO, no need to also pass --gateway. The cert +
|
|
@@ -923,8 +926,9 @@ ${j("Options")}
|
|
|
923
926
|
loopback host) to point a bare token at a
|
|
924
927
|
non-default control plane.
|
|
925
928
|
--sso <link> Enterprise SSO enrollment. Paste the https://\u2026/sso/<tenantId>
|
|
926
|
-
link your admin shared
|
|
927
|
-
|
|
929
|
+
link your admin shared \u2014 the short https://\u2026/i/<tenantId>
|
|
930
|
+
form and a bare tnt_ id also work. connect generates an
|
|
931
|
+
Ed25519 keypair, starts a device sign-in, opens
|
|
928
932
|
(or prints) a URL where you authenticate with your company IdP
|
|
929
933
|
(Okta / Entra / Google Workspace / Ping\u2026), then mints a
|
|
930
934
|
short-lived personal gateway key from the IdP-verified
|
|
@@ -970,7 +974,7 @@ ${j("Options")}
|
|
|
970
974
|
Your personal key for the --upstream endpoint (e.g. your
|
|
971
975
|
LiteLLM virtual key). Stored locally (mode 600) and in the
|
|
972
976
|
tool config, never sent to Anyray's control plane.
|
|
973
|
-
--tools <ids> Comma-separated subset: ${
|
|
977
|
+
--tools <ids> Comma-separated subset: ${oe.map(e=>e.id).join(", ")}
|
|
974
978
|
--project Write committable, credential-free routing config into the
|
|
975
979
|
CURRENT repo (.claude/settings.json + .codex/config.toml)
|
|
976
980
|
instead of this machine's user config \u2014 so devcontainers,
|
|
@@ -1019,22 +1023,22 @@ ${j("What it does")}
|
|
|
1019
1023
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1020
1024
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1021
1025
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1022
|
-
per-skill versions ${C("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
1023
|
-
${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?`}`,
|
|
1024
|
-
${o} ${n} tool target(s)?`;return await(r.confirm??Ia)(a)?"proceed":"declined"},fZ=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return tx(n)}if(e[0]==="__anyray-codex-hook")return nx();if(e[0]==="__anyray-prompt-hook")return rx();if(e[0]==="__anyray-shell-pretool")return ix();if(e[0]==="__anyray-shell-run")return sx(e.slice(1));if(e[0]==="__anyray-read-pretool")return mx();if(e[0]==="__anyray-sso-gate")return ES(e.slice(1));if(e[0]==="__anyray-sso-poll")return yx();if(e[0]==="__anyray-vscode-gate")return Cx();if(e[0]==="__anyray-spawn-refresh")return await vr(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return Rx(n)}if(e[0]==="__anyray-acp-agent")return _x(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return oI(e.slice(1));if(e[0]==="__anyray-refresh"){await zm(),await Qe({runAmbientSelfcheck:!0}),await um(),await aZ(),await pS(),await fS();let n=await T().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await ee(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await Na().catch(()=>!1);if(await sI(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=iI(),i=n.enrolledCert;if(s&&i){let l=await Fe().catch(()=>{});l&&await Sv(o,a,i,l,s).catch(()=>{})}await lI(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await Qe({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?pI(d):(await dI()).ok?"ok":"failed"}).catch(()=>{})}}return await _i(),0}if(e[0]==="__anyray-fallback-proxy")return KS();if(e[0]==="__anyray-persistence")return jS(e.slice(1));if(e[0]==="__anyray-quit-watch")return qS(e.slice(1));if(e[0]===Ys)return TE(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return Ax();try{let n=await fg(e);if(n!==void 0)return n}catch(n){return _(`Could not persist anyray-connect for long-lived integrations: ${n instanceof Error?n.message:String(n)}`),1}if(uZ(e)){let n=dZ(await k0());n?.level==="warn"?N(n.message):n&&console.error(n.message)}if(e[0]==="managed")return lE(e.slice(1));if(e[0]==="endpoint")return rI(e.slice(1));if(e[0]==="print-key")return fE(e.slice(1));if(e[0]==="models")return mE(e.slice(1));if(e[0]==="copilot-login")return yE(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=Nm(n);return r?$y(r,!1):VE(n)}if(e[0]==="retrieve")return ZE(e.slice(1));if(e[0]==="recall")return XE(e.slice(1));if(e[0]==="history")return i0(e.slice(1));if(e[0]==="migrate")return l0(e.slice(1));if(e[0]==="login")return wx(e.slice(1));if(e[0]==="update")return kx(e.slice(1));let t=e[0];if(t&&cZ.has(t)){let n=e.slice(1),r;try{r=gI(n)}catch(o){return _(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?yI:mI),0):t==="status"?S0({gateway:r.gateway}):t==="doctor"?R0({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?_0({gateway:r.gateway}):t==="device-url"?gE():$y(n,!0)}return $y(e,!1)},wI=async e=>{try{return await fZ(e)}catch(t){if(t instanceof wt)return console.error(C("Cancelled.")),130;throw t}},hZ=async(e,t,n={})=>{let r=n.isInteractive??Gt,o;try{o=gI(e)}catch(P){return _(P.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?yI:mI),0;if(o.revert&&(o.sso||o.enroll||o.claim))return _("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(_("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):RE({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return _("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return _("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let P;try{P=new URL(o.upstream.trim())}catch{return _(`invalid --upstream URL: "${o.upstream}"`),1}if(P.protocol!=="http:"&&P.protocol!=="https:")return _(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let L=o.upstreamKey.trim();if(!L)return _("--upstream-key must not be empty."),1;a={url:Ye(o.upstream),key:L}}let s=await T();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let P=await zm();(P==="migrated"||P==="already-direct")&&(s=await T())}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream),o.retiredFallbackFlag&&N("--fallback/--no-fallback are retired and ignored: the local daemon no longer routes around the gateway to the provider. Seamless key refresh is on by default (--no-key-refresh opts out).");let i=!t&&Gt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??QY)(o,s),c=!0);let l;try{l=HY(o.tools)}catch(P){return _(P.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&jd(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,k("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,f=!1;if(o.enroll&&(!o.gateway||s.enrolledCert)){let P=Gd(o.enroll);if(P)try{let L=await Oi("Resolving enrollment link\u2026",()=>d0(P)),H=!o.gateway;H&&(o.gateway=L.gatewayUrl),d=L.deploymentId,u=L.email,f=!0,H&&B(`Enrollment link${L.org?` for ${L.org}`:""}: gateway ${L.gatewayUrl}`),L.seatMode&&!o.subscription&&(o.subscription=!0,B("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(L){let H=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(H)B(`Could not resolve the gateway from the enrollment link \u2014 using ${H}.`);else return _(L instanceof Error?L.message:String(L)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)B("dry run: not enrolled (skipped redeeming the enrollment link).");else{let P=mS(o.claim);if(!P)return _("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let L=await Oi("Connecting this machine\u2026",()=>yS({cpOrigin:P.cpOrigin,claim:P.claim,gatewayUrl:o.gateway}));p={cert:L.cert,privateKeyPem:L.privateKeyPem},L.deploymentId&&(d=L.deploymentId),!o.gateway&&L.gatewayUrl&&(o.gateway=L.gatewayUrl),h=L.ssoLink}catch(L){return _(L instanceof Error?L.message:String(L)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)B("dry run: not enrolled via SSO (skipped minting a personal key).");else{let P=Wt(o.sso);if(!P)return _("invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let L=await vd({cpOrigin:P.cpOrigin,tenantId:P.tenantId,gatewayUrl:o.gateway,log:me=>B(me),open:r()?Aa:void 0}),H=await Oi("Waiting for SSO sign-in\u2026",()=>Sd(L,{gatewayUrl:o.gateway}));p={cert:H.cert,privateKeyPem:H.privateKeyPem},H.deploymentId&&(d=H.deploymentId),!o.gateway&&H.gatewayUrl&&(o.gateway=H.gatewayUrl)}catch(L){return _(L instanceof Error?L.message:String(L)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=cn(o.gateway)}catch(P){return _(P.message),1}let g,y;m&&!o.revert&&B(`Gateway: ${w} ${C("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&Fy(w)&&N(`${w} is plaintext http over a network \u2014 connections can be reset by firewalls/VPNs and traffic is unencrypted. Prefer an https:// gateway URL (front it with the TLS edge).`);let b=process.env.ANYRAY_CLIENT_KEY?.trim(),v=b||KY(s),S,E,x,A,I,R,M=s.credentialProtocol==="stable-heartbeat-v1",X=async P=>{await wo();let L=vv(P.token),H=Ev(s.enrolledCert,s.enrolledCertExpiry,P.deploymentId,Date.now(),L,s.enrolledTokenHash,P.expectedUser),me=H?await Fe():void 0,se=H&&me&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:me,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,ge=ie=>xv({cpOrigin:P.cpOrigin,token:P.token,gatewayOrigin:w,email:P.email,team:P.team,machineId:P.machineId,deploymentId:P.deploymentId,reuse:ie?se:void 0}),He=!!se,ue=await(async()=>{try{return await ge(He)}catch(ie){if(se&&ie instanceof xt)return B("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),He=!1,await ge(!1);throw ie}})();v=ue.clientKey,o.user||=ue.user,o.team||=ue.team,S=ue.cert,E=ue.cert.payload.expiresAt,R=ue.expiresAt,M=ue.capabilities?.includes(ui)===!0,I=void 0,He||(x=ue.privateKeyPem),He||(A=L),$(`Enrolled${ue.user?` as ${ue.user}`:""}${He?" (reused your saved cert)":""} \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)};if(o.enroll&&!o.revert)if(o.dryRun)B("dry run: not enrolled (skipped minting a personal key).");else{let P=Gd(o.enroll);if(!P)return _("invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1;try{let L=o.machine?cu():void 0,H=u??UY(o.user),me=o.machine?`machine:${L}`:f?H:void 0;await X({cpOrigin:P.cpOrigin,token:P.token,email:H,team:o.team,machineId:L,deploymentId:d,expectedUser:me})}catch(L){return _(L instanceof Error?L.message:String(L)),L instanceof xt&&B("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),1}}if(p){await wo();try{let P=await on(w,p.cert,p.privateKeyPem);v=P.key,o.user||=P.user,o.team||=P.team,S=p.cert,E=p.cert.payload.expiresAt,x=p.privateKeyPem,R=P.expiresAt,M=P.capabilities?.includes(ui)===!0;let L=o.sso?Wt(o.sso):void 0;I=L?`${L.cpOrigin}/sso/${L.tenantId}`:h,$(`Enrolled${P.user?` as ${P.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(P){return _(P instanceof Error?P.message:String(P)),P instanceof xt&&B("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}if(!o.revert){let P=o.yes;g=await CE(o.user,s.name,P),y=await vE(o.team,s.team,P)}let V;!o.revert&&!o.subscription&&!o.placeholder&&(V=await Tt(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):V.anthropic?et("signed in \u2192 your subscription"):C("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${V.openai?et("signed in \u2192 your subscription"):C("not signed in \u2192 org key")}`),!V.anthropic&&!V.openai&&!V.copilot&&es()&&(N(" No subscription sign-ins found on this host. Sign-ins do not cross the"),N(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),N(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),N(" and re-run, or everything below routes on the org key instead.")));let W=ye({origin:w,placeholderKey:o.key,clientKey:v,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:V,user:g,team:y,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),z=o.revert===!0&&(o.tools?.length??0)===0,ve={dryRun:o.dryRun,fullRevert:z};if(!o.revert&&W.clientKey&&!Ie(W.clientKey))return _("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!W.clientKey){K("Enrollment required");let P="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(N(` ${P}`),B(" Dry run only \u2014 no placeholder configuration will be written."),await fI(l,"after-enrollment"),B(`
|
|
1025
|
-
Dry run complete \u2014 no files were written.`),0):(
|
|
1026
|
-
Dry run \u2014 no files will be written.`);let
|
|
1027
|
-
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(
|
|
1028
|
-
Gateway ${W.origin} is not reachable (${
|
|
1026
|
+
per-skill versions ${C("sync")} last wrote \u2014 for zero-question re-runs.`,cZ=e=>{let t=e?.trim();return t||IE()},II=e=>{let t={subscription:!1,placeholder:!1,dryRun:!1,yes:!1,revert:!1,force:!1,skipVerify:!1,verbose:!1,help:!1,helpAll:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>e[++n];switch(r){case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":t.key=o();break;case"--enroll":t.enroll=o();break;case"--sso":t.sso=o();break;case"--claim":t.claim=o();break;case"--machine":t.machine=!0;break;case"--subscription":t.subscription=!0;break;case"--placeholder":case"--org":t.placeholder=!0;break;case"--upstream":t.upstream=o();break;case"--upstream-key":t.upstreamKey=o();break;case"--tools":t.tools=(o()??"").split(",").map(a=>a.trim()).filter(Boolean);break;case"--project":t.project=!0;break;case"--dry-run":t.dryRun=!0;break;case"--yes":case"-y":t.yes=!0;break;case"--force":t.force=!0;break;case"--skip-verify":t.skipVerify=!0;break;case"--fallback":case"--no-fallback":t.retiredFallbackFlag=!0;break;case"--no-key-refresh":t.noKeyRefresh=!0;break;case"--quit-apps":t.quitApps=!0;break;case"--no-quit-apps":t.noQuitApps=!0;break;case"--endpoint":t.endpoint=!0;break;case"--no-endpoint":t.noEndpoint=!0;break;case"--revert":t.revert=!0;break;case"--json":t.json=!0;break;case"--verify":t.verify=!0;break;case"--no-verify":t.noVerify=!0;break;case"--quick":t.quick=!0;break;case"--repair":t.repair=!0;break;case"--security-review":t.securityReview=!0;break;case"--verbose":t.verbose=!0;break;case"--help":case"-h":t.help=!0;break;case"--help-all":t.help=!0,t.helpAll=!0;break;case"--all":if(!e.includes("--help")&&!e.includes("-h"))throw new Error(`unknown option: ${r}`);t.helpAll=!0;break;default:if(!r.startsWith("-")&&t.gateway===void 0)t.gateway=r;else throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r} (gateway already set to ${t.gateway})`)}}return t},lZ=e=>!e||e.length===0?oe:e.map(t=>{let n=Ht(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${oe.map(r=>r.id).join(", ")}`);return n}),dZ=(e,t)=>{if(K("Gateway target"),k(` Origin: ${et(e.origin)}`),e.byoUpstream)k(` Auth: BYO upstream key ${C(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&k(` Client key: personal gateway key (${Nt(e.clientKey)}) ${C("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=J(e,"anthropic")?et("your subscription"):"org key",r=J(e,"openai")?et("your subscription"):"org key";k(` Auth: auto ${C("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&k(` Client key: personal gateway key (${Nt(e.clientKey)})`)}else e.authMode==="subscription"?(k(` Auth: subscription pass-through ${C("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&k(` Client key: personal gateway key (${Nt(e.clientKey)}) ${C("rides x-anyray-api-key")}`)):e.clientKey?k(` Auth: personal gateway key (${Nt(e.clientKey)}) ${C("(replaces the placeholder)")}`):k(` Enrollment: ${C("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&k(` Cursor: ${et("native Team subscription")} ${C("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(J(e,"anthropic")?(k(` Claude Desktop: ${et("subscription-backed Gateway lane")} ${C("(verified macOS builds; Windows fails closed)")}`),k(` ${C("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(k(` Claude Desktop: ${et("third-party API lane")} ${C("(API-billed; switches the active local inference profile)")}`),k(` ${C("The first-party Claude subscription remains untouched.")}`))),k(` Attribution: ${le(e.metadata)??C("(none \u2014 pass --user)")}`)},vI=async(e,t)=>{K("Selected tools");for(let n of e){let r=await n.detect();r.installed?k(` ${n.title} ${C(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):F(` ${n.title} ${C(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},uZ=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Ie(n))return;let r=e.clientKeyExpiresAt?.trim();if(!r)return n;let o=Date.parse(r);return Number.isFinite(o)&&o>t?n:void 0},pZ={loadDevKey:Be,saveDevKey:zi,clearDevKey:Va,saveProfile:te},fZ=async(e,t,n,r=pZ,o=!1)=>{let a=!!n||o,s=a?await r.loadDevKey():void 0,i=!1,c=!1;try{a&&(i=!0,n?await r.saveDevKey(n):await r.clearDevKey()),c=!0,await r.saveProfile(t)}catch(l){throw i&&(s!==void 0?await r.saveDevKey(s).catch(()=>{}):await r.clearDevKey().catch(()=>{})),c&&await r.saveProfile(e).catch(()=>{}),l}},hZ=async(e,t,n,r,o)=>{n.dryRun||await Qi();let a=0,s=[],i=[],c=[],l=[],d=[];for(let u of e){if(!(await u.detect()).installed&&!r){d.push(u.title);continue}K(`${u.title} ${C(`(${u.id})`)}`);try{let p=r?await u.revert(n):await u.apply(t,{...n,explicit:o?.has(u.id)===!0,reportsToUser:!0});for(let h of p.messages)k(` ${h}`);a+=p.changedFiles?.length??0,l.push({id:u.id,status:p.status}),p.status==="configured"||p.status==="reverted"?$(` ${p.status}`):p.status==="manual"?(s.push(u.title),p.manualAudience==="admin"?(i.push(u.title),c.push(u.id),N(" blocked by machine policy \u2014 your IT team owns this one")):N(" manual step required (see above)")):p.status==="held"?F(" left on its own plan (no change)"):F(` ${p.status}`)}catch(p){l.push({id:u.id,status:"failed"}),O(` failed: ${p instanceof Error?p.message:String(p)}`)}}if(d.length>0&&F(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await rc().catch(()=>[]);u.length&&F(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},mZ=(e,t=[],n)=>{if(e.length===0)return[];if(t.length===e.length)return[`${e.length===1?`${e[0]} is`:`${e.join(", ")} are`} controlled by a machine policy your organization manages, so local setup cannot change it.`,...n==="darwin"?["Admin next step: on an unmanaged admin Mac, open Claude Desktop \u2192 Developer \u2192 Configure Third-Party Inference, complete and test the Anyray connection, connectors, and plugin marketplaces, then Export \u2192 .mobileconfig and deploy that complete profile through MDM.","The configuration window is read-only on managed endpoints; Connect will not create an incomplete replacement profile or supplement the managed source locally."]:n?["Your administrator must create and test the complete Claude Desktop third-party policy through Anthropic's enterprise configuration flow, then deploy it through your organization's device-management system.","Connect will not create an incomplete replacement policy or supplement the managed source locally."]:["Your Anyray administrator can see this state in the console's Connect coverage view."],"Everything else on this machine is configured and routing normally."];let o=[`${e.length===1?`${e[0]} needs`:`${e.length} tools need`} a remaining app action \u2014 Connect may already have written its automatic config.`,`Review and complete the steps shown above for: ${e.join(", ")}.`,"Then restart or reload the app as instructed; use `npx anyray-connect status` for the available route checks."];return t.length>0&&o.push(`Not yours to fix: ${t.join(", ")} \u2014 a machine policy your organization manages. Flagged for your Anyray administrator.`),o},yZ=async(e,t,n=iZ())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!eb(i,n)||!Qw(i,n))continue;let c=zw(i,n);if(!o.has(c)){try{if(!(await a.detect()).installed||!s.isRunning()||await a.pointsAt?.(t)===!0)continue}catch{continue}o.add(c),r.push({id:a.id,title:qw(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},gZ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,wZ=e=>`
|
|
1027
|
+
${e.length===1?`${e[0]} is open and won't pick this up until it restarts. Quit it now?`:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]} are open and won't pick this up until they restart. Quit them now?`}`,bZ=async(e,t={})=>{let n=t.requestQuit??(a=>nb(a)),r=t.waitFor??(a=>rb(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),$(` Closed ${a.title}.`);continue}N(` ${a.title} is still open \u2014 leaving it alone.`),F(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},kZ=(e,t={})=>{let n=t.relaunch??(o=>ob(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),$(` Reopened ${o.title}.`)):N(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},du=e=>e.changesBilling!==!0,AZ=async(e,t,n={})=>{let r=n.hasEnrollment??vu,o=n.canMultiSelect??A0,a=n.multiSelect??C0,s=n.prompt??Oa,i=n.registry??oe;if(k(j("Anyray connect \u2014 guided setup")),k(C("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())k("Stored enrollment will be reused. Run with --revert to clear it.");else if(!e.enroll&&!e.sso&&!e.gateway){K("How do you want to connect?");let c;for(let l=0;l<3&&!c;l++){if(o()){let d=await a({title:"Choose a connection method",single:!0,items:[{value:"enroll",label:"Paste an enrollment link",selected:!0},{value:"sso",label:"Sign in with SSO"},{value:"gateway",label:"I already have a gateway URL"}]});if(d.kind==="cancelled")throw new bt;c=d.values[0]}else{k(" 1. Paste an enrollment link"),k(" 2. Sign in with SSO"),k(" 3. I already have a gateway URL");let d=await s("? Connection method (1-3)","1");c=d==="1"?"enroll":d==="2"?"sso":d==="3"?"gateway":void 0}c||N("Choose one of the three connection methods.")}if(!c)throw new bt;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&Oi(d)&&Vd(d)){e.enroll=d;break}N("That is not a valid enrollment link or token. Try again.")}else if(c==="sso"){let d=await s("? SSO link or tenant id");if(d&&Rt(d)){e.sso=d;break}N("That is not a valid SSO link or tenant id. Try again.")}else{let d=await s("? Gateway URL",t.gateway||process.env.ANYRAY_GATEWAY_URL);if(d&&Oi(d)){e.enroll=d,k("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=ln(d);break}catch{N("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new bt}if(!e.tools||e.tools.length===0){K("Tools detected");let c=[],l=[];for(let u of i){if(!(await u.detect()).installed){l.push(u);continue}c.push(u)}let d=c.filter(u=>du(u)).map(u=>u.id);if(c.length>0){for(let u=0;u<3&&!e.tools;u++){let f;if(o()){let p=await a({title:"Tools to configure",items:c.map(h=>({value:h.id,label:`${h.title} (${h.id})`,hint:du(h)?void 0:"moves inference spend from your subscription to the org API bill",selected:du(h),requiresExplicitChoice:!du(h)}))});if(p.kind==="cancelled")throw new bt;f=p.values}else{f=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(w=>w.trim()).filter(Boolean);let h=new Set(c.map(w=>w.id)),m=f.filter(w=>!h.has(w));if(m.length>0){N(`Unknown or unavailable tool id${m.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(f.length===0){N("Choose at least one installed tool.");continue}e.tools=f}if(!e.tools)throw new bt}l.length>0&&F(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},CZ=async(e,t)=>{K("Verifying the connection");let n=await _i("Checking the gateway\u2026",()=>Di(e,{tools:t}));n.kind==="ok"?$(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?N(` ${n.detail}`):O(` ${n.detail}`);for(let r of n.remedy)k(C(` ${r}`))},vZ=5e3,SZ=500,SI=3,EZ=600*1e3,xZ=async()=>{try{let e=await sZ(await Io());return Date.now()-e.mtimeMs}catch{return Number.POSITIVE_INFINITY}},IZ=async(e={})=>{try{let t=await(e.load??P)();if(t.keyRefreshEnabled!==!0){if((e.draining??Xu)()||!await(e.unitExists??Zg)()||await(e.profileAgeMs??xZ)()<EZ)return;await(e.uninstall??Jt)(t.fallbackPort??Ae);return}if(!t.gateway||t.persistenceOwner==="tray"&&await(e.checkTray??Ao)(t)==="healthy")return;let n=t.fallbackPort??Ae,r=e.probe??ke,o=e.probeGapMs??SZ;for(let s=0;s<SI;s++){if(await r(n,s===0?void 0:vZ)!==null)return;s<SI-1&&o>0&&await new Promise(c=>setTimeout(c,o))}if((e.draining??Xu)())return;let a=await(e.install??Lt)({port:n,remoteOrigin:new URL(t.gateway).origin});if(!a.ok)for(let s of a.messages)console.error(s)}catch{}},RZ=async(e,t,n={})=>{let r=n.install??Lt,o=n.probe??ke,a=n.pollDelayMs??300;K("Seamless key refresh");let s=n.trayManaged?{ok:!0,messages:["Launch-at-login is managed by the Anyray Connect app \u2014 not re-registering the login service."]}:await r({port:t,remoteOrigin:e.origin});for(let l of s.messages)k(` ${l}`);let i=s.ok?10:1,c=null;for(let l=0;l<i&&!c;l++)c=await o(t),!c&&l<i-1&&await new Promise(d=>setTimeout(d,a));return c?($(` Running on 127.0.0.1:${t} \u2192 ${e.origin} \u2014 your key refreshes automatically, no restart needed.`),vn(e,t)):(N(" Key-refresh proxy did not come up \u2014 pointing tools directly at the gateway for now."),k(C(s.ok?" It will retry on the next run; check the service logs if it persists.":At(yt())?" In a container the key refreshes via Claude Code's helper and on each `anyray-connect` run instead.":" Your key still refreshes on a schedule \u2014 no daemon needed here.")),e)},OZ=async(e,t={})=>{if(e.dryRun)return;let n=t.install??sr,r=t.uninstall??ir;if(e.want&&e.trayManaged){e.announcePrimary&&(K("Automatic key refresh"),$(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."));return}if(e.want){let o=await n();if(e.announcePrimary){K("Automatic key refresh");for(let a of o.messages)k(` ${a}`);o.ok&&$(" Your gateway key now re-mints every ~30 min \u2014 no tool will 401 on a stale key mid-session.")}o.ok||await te({...await P(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){K("Automatic key refresh");let o=await r();for(let a of o.messages)k(` ${a}`);await te({...await P(),refreshSchedulerEnabled:!1}),$(" Removed the automatic key-refresh schedule.")}},_Z=new Set(["login","wizard","status","doctor","sync","device-url"]),TZ=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),PZ=e=>{if(e.outcome==="migrated"&&e.managedPath)return{level:"info",message:`Installed managed anyray-connect at ${e.managedPath}.`};if(e.outcome==="platform-unsupported")return{level:"warn",message:"Self-update is unavailable on this platform; keeping the durable npm runtime for persistent integrations."};if(e.outcome==="migration-deferred")return{level:"warn",message:`Managed install deferred because the published binary (${e.latest}) is older than this npm runtime (${e.current}).`};if(!(e.outcome==="current"||e.outcome==="unmanaged"||e.outcome==="updated"||e.outcome==="disabled"||e.outcome==="container"))return{level:"warn",message:"Could not install the managed anyray-connect binary; continuing with the current runtime \u2014 it migrates automatically on a later refresh."}},LZ=e=>{if(e.includes("--help")||e.includes("--help-all")||e.includes("-h"))return!1;if(e[0]==="managed")return e.includes("--write")&&!e.includes("--revert");if(e[0]==="desktop"){let t=$m(e.slice(1));return!!(t&&!t.includes("--dry-run")&&!t.includes("--revert"))}return e.includes("--dry-run")||e.includes("--revert")||e.includes("--project")?!1:e[0]==="doctor"?e.includes("--repair"):e[0]==="models"?e.slice(1).some(t=>!t.startsWith("-")):!e[0]||!TZ.has(e[0])},My=async(e,t)=>{try{return await $Z(e,t)}catch(n){if(n instanceof bt)return console.error(C("Cancelled \u2014 nothing was written.")),130;throw n}},DZ=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??jt)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
|
|
1028
|
+
${o} ${n} tool target(s)?`;return await(r.confirm??Ra)(a)?"proceed":"declined"},NZ=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return ux(n)}if(e[0]==="__anyray-codex-hook")return px();if(e[0]==="__anyray-prompt-hook")return fx();if(e[0]==="__anyray-shell-pretool")return gx();if(e[0]==="__anyray-shell-run")return yx(e.slice(1));if(e[0]==="__anyray-read-pretool")return Ex();if(e[0]==="__anyray-sso-gate")return PS(e.slice(1));if(e[0]==="__anyray-sso-poll")return xx();if(e[0]==="__anyray-vscode-gate")return Px();if(e[0]==="__anyray-spawn-refresh")return await Sr(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return Bx(n)}if(e[0]==="__anyray-acp-agent")return Ux(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return hI(e.slice(1));if(e[0]==="__anyray-refresh"){await qm(),await Qe({runAmbientSelfcheck:!0}),await pm(),await IZ(),await wS(),await bS();let n=await P().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await te(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await $a().catch(()=>!1);if(await yI(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=gI(),i=n.enrolledCert;if(s&&i){let l=await Be().catch(()=>{});l&&await _v(o,a,i,l,s).catch(()=>{})}await bI(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await Qe({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?CI(d):(await kI()).ok?"ok":"failed"}).catch(()=>{})}}return await Pi(),0}if(e[0]==="__anyray-fallback-proxy")return JS();if(e[0]==="__anyray-persistence")return qS(e.slice(1));if(e[0]==="__anyray-quit-watch")return aE(e.slice(1));if(e[0]===Zs)return BE(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return Tx();try{let n=await hg(e);if(n!==void 0)return n}catch(n){return O(`Could not persist anyray-connect for long-lived integrations: ${n instanceof Error?n.message:String(n)}`),1}if(LZ(e)){let n=PZ(await O0());n?.level==="warn"?N(n.message):n&&console.error(n.message)}if(e[0]==="managed")return yE(e.slice(1));if(e[0]==="endpoint")return fI(e.slice(1));if(e[0]==="print-key")return kE(e.slice(1));if(e[0]==="models")return CE(e.slice(1));if(e[0]==="copilot-login")return vE(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=$m(n);return r?My(r,!1):QE(n)}if(e[0]==="retrieve")return t0(e.slice(1));if(e[0]==="recall")return n0(e.slice(1));if(e[0]==="history")return h0(e.slice(1));if(e[0]==="migrate")return y0(e.slice(1));if(e[0]==="login")return Rx(e.slice(1));if(e[0]==="update")return _x(e.slice(1));let t=e[0];if(t&&_Z.has(t)){let n=e.slice(1),r;try{r=II(n)}catch(o){return O(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?xI:EI),0):t==="status"?L0({gateway:r.gateway}):t==="doctor"?F0({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?B0({gateway:r.gateway}):t==="device-url"?SE():My(n,!0)}return My(e,!1)},RI=async e=>{try{return await NZ(e)}catch(t){if(t instanceof bt)return console.error(C("Cancelled.")),130;throw t}},$Z=async(e,t,n={})=>{let r=n.isInteractive??jt,o;try{o=II(e)}catch(_){return O(_.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?xI:EI),0;if(o.revert&&(o.sso||o.enroll||o.claim))return O("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(O("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):$E({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return O("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return O("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let _;try{_=new URL(o.upstream.trim())}catch{return O(`invalid --upstream URL: "${o.upstream}"`),1}if(_.protocol!=="http:"&&_.protocol!=="https:")return O(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let L=o.upstreamKey.trim();if(!L)return O("--upstream-key must not be empty."),1;a={url:Ye(o.upstream),key:L}}let s=await P();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let _=await qm();(_==="migrated"||_==="already-direct")&&(s=await P())}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream),o.retiredFallbackFlag&&N("--fallback/--no-fallback are retired and ignored: the local daemon no longer routes around the gateway to the provider. Seamless key refresh is on by default (--no-key-refresh opts out).");let i=!t&&jt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??AZ)(o,s),c=!0);let l;try{l=lZ(o.tools)}catch(_){return O(_.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&Oi(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,k("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,f=!1;if(o.enroll&&(!o.gateway||s.enrolledCert)){let _=Vd(o.enroll);if(_)try{let L=await _i("Resolving enrollment link\u2026",()=>b0(_)),H=!o.gateway;H&&(o.gateway=L.gatewayUrl),d=L.deploymentId,u=L.email,f=!0,H&&F(`Enrollment link${L.org?` for ${L.org}`:""}: gateway ${L.gatewayUrl}`),L.seatMode&&!o.subscription&&(o.subscription=!0,F("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(L){let H=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(H)F(`Could not resolve the gateway from the enrollment link \u2014 using ${H}.`);else return O(L instanceof Error?L.message:String(L)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)F("dry run: not enrolled (skipped redeeming the enrollment link).");else{let _=CS(o.claim);if(!_)return O("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let L=await _i("Connecting this machine\u2026",()=>vS({cpOrigin:_.cpOrigin,claim:_.claim,gatewayUrl:o.gateway}));p={cert:L.cert,privateKeyPem:L.privateKeyPem},L.deploymentId&&(d=L.deploymentId),!o.gateway&&L.gatewayUrl&&(o.gateway=L.gatewayUrl),h=L.ssoLink}catch(L){return O(L instanceof Error?L.message:String(L)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)F("dry run: not enrolled via SSO (skipped minting a personal key).");else{let _=Rt(o.sso);if(!_)return O(Oi(o.sso)?"that is an enrollment link, not an SSO link \u2014 re-run with --enroll instead of --sso.":"invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let L=await Ed({cpOrigin:_.cpOrigin,tenantId:_.tenantId,gatewayUrl:o.gateway,log:ye=>F(ye),open:r()?Ca:void 0}),H=await _i("Waiting for SSO sign-in\u2026",()=>xd(L,{gatewayUrl:o.gateway}));p={cert:H.cert,privateKeyPem:H.privateKeyPem},H.deploymentId&&(d=H.deploymentId),!o.gateway&&H.gatewayUrl&&(o.gateway=H.gatewayUrl)}catch(L){return O(L instanceof Error?L.message:String(L)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=ln(o.gateway)}catch(_){return O(_.message),1}let g,y;m&&!o.revert&&F(`Gateway: ${w} ${C("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&By(w)&&N(`${w} is plaintext http over a network \u2014 connections can be reset by firewalls/VPNs and traffic is unencrypted. Prefer an https:// gateway URL (front it with the TLS edge).`);let b=process.env.ANYRAY_CLIENT_KEY?.trim(),v=b||uZ(s),S,E,x,A,I,T,B=s.credentialProtocol==="stable-heartbeat-v1",X=async _=>{await bo();let L=Ov(_.token),H=Tv(s.enrolledCert,s.enrolledCertExpiry,_.deploymentId,Date.now(),L,s.enrolledTokenHash,_.expectedUser),ye=H?await Be():void 0,se=H&&ye&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:ye,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,we=ie=>Pv({cpOrigin:_.cpOrigin,token:_.token,gatewayOrigin:w,email:_.email,team:_.team,machineId:_.machineId,deploymentId:_.deploymentId,reuse:ie?se:void 0}),We=!!se,ue=await(async()=>{try{return await we(We)}catch(ie){if(se&&ie instanceof It)return F("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),We=!1,await we(!1);throw ie}})();v=ue.clientKey,o.user||=ue.user,o.team||=ue.team,S=ue.cert,E=ue.cert.payload.expiresAt,T=ue.expiresAt,B=ue.capabilities?.includes(pi)===!0,I=void 0,We||(x=ue.privateKeyPem),We||(A=L),$(`Enrolled${ue.user?` as ${ue.user}`:""}${We?" (reused your saved cert)":""} \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)};if(o.enroll&&!o.revert)if(o.dryRun)F("dry run: not enrolled (skipped minting a personal key).");else{let _=Vd(o.enroll);if(!_)return O(Rt(o.enroll)?"that is an SSO link, not an enrollment link \u2014 re-run with --sso instead of --enroll.":"invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1;try{let L=o.machine?lu():void 0,H=u??cZ(o.user),ye=o.machine?`machine:${L}`:f?H:void 0;await X({cpOrigin:_.cpOrigin,token:_.token,email:H,team:o.team,machineId:L,deploymentId:d,expectedUser:ye})}catch(L){return O(L instanceof Error?L.message:String(L)),L instanceof It&&F("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),1}}if(p){await bo();try{let _=await an(w,p.cert,p.privateKeyPem);v=_.key,o.user||=_.user,o.team||=_.team,S=p.cert,E=p.cert.payload.expiresAt,x=p.privateKeyPem,T=_.expiresAt,B=_.capabilities?.includes(pi)===!0;let L=o.sso?Rt(o.sso):void 0;I=L?`${L.cpOrigin}/sso/${L.tenantId}`:h,$(`Enrolled${_.user?` as ${_.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(_){return O(_ instanceof Error?_.message:String(_)),_ instanceof It&&F("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}if(!o.revert){let _=o.yes;g=await OE(o.user,s.name,_),y=await _E(o.team,s.team,_)}let V;!o.revert&&!o.subscription&&!o.placeholder&&(V=await Dt(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):V.anthropic?et("signed in \u2192 your subscription"):C("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${V.openai?et("signed in \u2192 your subscription"):C("not signed in \u2192 org key")}`),!V.anthropic&&!V.openai&&!V.copilot&&ts()&&(N(" No subscription sign-ins found on this host. Sign-ins do not cross the"),N(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),N(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),N(" and re-run, or everything below routes on the org key instead.")));let W=ge({origin:w,placeholderKey:o.key,clientKey:v,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:V,user:g,team:y,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),z=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:z};if(!o.revert&&W.clientKey&&!Ie(W.clientKey))return O("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!W.clientKey){K("Enrollment required");let _="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(N(` ${_}`),F(" Dry run only \u2014 no placeholder configuration will be written."),await vI(l,"after-enrollment"),F(`
|
|
1029
|
+
Dry run complete \u2014 no files were written.`),0):(O(` ${_}`),1)}o.revert||dZ(W,l),c&&!o.revert&&await vI(l,"plan"),o.dryRun&&F(`
|
|
1030
|
+
Dry run \u2014 no files will be written.`);let De=await DZ(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(De==="non-interactive")return O(`
|
|
1031
|
+
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(De==="declined")return F(c?"Nothing was written. Re-run `npx anyray-connect wizard` when you're ready.":"Aborted. Nothing changed."),0;if(!o.dryRun&&!o.revert&&!o.force){let _=await jd(W.origin);if(!_.reachable)return O(`
|
|
1032
|
+
Gateway ${W.origin} is not reachable (${_.detail}).`),k(C(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1029
1033
|
that would break them until you re-run with --revert.`)),k(`
|
|
1030
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1;$(`Gateway reachable (${
|
|
1031
|
-
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let
|
|
1032
|
-
Remove them from the repo (then commit):`),k(C(" anyray-connect --project --revert")));let tt=[W,...s.fallbackPort?[
|
|
1033
|
-
Fix this terminal:`),k(C(` unset ${
|
|
1034
|
-
Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if($(`Done (${
|
|
1035
|
-
Skipped the connection smoke test (--skip-verify).`):await
|
|
1034
|
+
Start the gateway and try again, or pass --force to configure anyway.`),1;$(`Gateway reachable (${_.detail}).`)}let ee=o.revert?[]:await yZ(l,W.origin),Fe=[],xe=()=>{Fe.length!==0&&(K("Reopening"),kZ(Fe),Fe=[])};if(ee.length>0){let _=ee.map(H=>H.title),L=_.length===1?"it":"them";if(K("Open apps"),gZ(o,jt()))o.quitApps===!0||await Ra(wZ(_))?Fe=await bZ(ee):F(` Leaving ${L} open \u2014 restart when convenient.`);else{let H=o.noQuitApps===!0?"":" (or pass --quit-apps)";F(o.dryRun?` Would offer to quit ${_.join(", ")} \u2014 dry run, nothing was closed.`:` ${_.join(", ")} ${_.length===1?"is":"are"} open; restart ${L} to pick this up${H}.`)}}try{if(!o.dryRun)try{await kt()}catch{return O("Could not prepare the owner-only Anyray state directory."),1}let _=l.some(pe=>pe.id==="claude-code")&&J(W,"anthropic")||l.some(pe=>pe.id==="codex")&&J(W,"openai"),L=Cd(s,T),H=!o.revert&&o.noKeyRefresh!==!0&&_&&L&&!B,se=!o.revert&&(o.tools?.length??0)>0&&o.noKeyRefresh!==!0&&!!s.keyRefreshEnabled,we=!!(b&&W.clientKey===b&&!S),We=!we&&!!(S??s.enrolledCert),ue=l.some(pe=>mS.has(pe.id)),ie=!o.revert&&o.noKeyRefresh!==!0&&We&&(L||!ue),Y=o.dryRun?await Ao(s):await pm(),Ne=Y==="healthy";Y==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath);let ft=W,Ve=H||se,Pr=Ve?s.fallbackPort:void 0;if(H&&!o.dryRun&&(Pr=s.fallbackPort??await yc()),!o.revert&&!o.dryRun){let pe={...s,gateway:W.origin,name:g,team:y,clientKey:W.clientKey??s.clientKey,enrolledCert:we?void 0:S??s.enrolledCert,enrolledCertExpiry:we?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:we?void 0:A??s.enrolledTokenHash,ssoLink:we?void 0:p?I:S?void 0:s.ssoLink,clientKeyExpiresAt:we?void 0:T??(W.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:W.authMode,byoUpstream:W.byoUpstream,credentialProtocol:we?void 0:Ve?"rotating-proxy-v1":B?"stable-heartbeat-v1":s.credentialProtocol,directMigration:we?void 0:Ve?"pending":B?"complete":s.directMigration,keyRefreshEnabled:Ve,refreshSchedulerEnabled:ie,fallbackPort:Pr};try{await fZ(s,pe,x,void 0,we)}catch{return O("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}T&&!we&&await Aa({expiresAt:T})}if(H&&!o.dryRun&&(ft=await RZ(W,Pr,{trayManaged:Ne})),z)if(o.dryRun)await vu()&&(K("Enrollment"),k(" would remove the stored gateway credential"));else{await $y(s),await Rd().catch(()=>{});try{await qi()&&(K("Enrollment"),$(" Removed the stored gateway credential."),F(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(pe){K("Enrollment"),N(" Could not remove the stored gateway credential."),N(` Delete ${q()} by hand, or the key-refresh hook may restore your tool config.`)}}else o.revert&&!o.dryRun&&(k(`
|
|
1035
|
+
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let cn=l;if(o.revert&&!z){let pe=l.filter(tt=>ui(s,tt.id));if(pe.length>0){K("Fleet policy");for(let tt of pe)N(` ${tt.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);cn=l.filter(tt=>!ui(s,tt.id))}}let{changes:Gi,manual:Ua,manualAdminOnly:ji,manualAdminOnlyIds:Vi,results:Ha}=await hZ(cn,ft,me,o.revert,new Set(o.tools??[]));if(sI(o)){K("Endpoint agent");try{await(n.installEndpointAfterEnrollment??mI)({gateway:w,clientKey:W.clientKey})}catch{F("Endpoint agent setup did not complete. Tool routing remains configured.")}}if(o.dryRun||(await Xn(Ha,o.revert,z).catch(()=>{}),z&&await ec().catch(()=>{})),!Ve&&!o.dryRun&&(nt(s)||s.fallbackPort||await Ci("daemon"))){K("Local loopback proxy");let pe=await Jt(s.fallbackPort);for(let tt of pe.messages)k(` ${tt}`);await te({...await P(),keyRefreshEnabled:!1,fallbackPort:void 0}),$(" Removed the local loopback proxy.")}if(await OZ({want:ie,announcePrimary:!H,scopedRevert:!!o.revert&&!z,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!ie&&await Ci("scheduler"),trayManaged:Ne}),!o.revert&&!o.dryRun&&!we){let pe=x??await Be();pe&&await nm(await P(),pe).catch(()=>{})}if(xe(),K("Summary"),o.dryRun)F("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){$(`Reverted (${Gi} file(s) touched).`),F("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let pe=await NE();pe.length>0&&(K("This repo carries its own Anyray routing"),N(` Committed here: ${pe.join(", ")}`),N(" Those are tracked files, so they route every checkout of this"),N(" repo \u2014 this machine included, and your teammates' too. This"),N(" revert only removed THIS machine's own configuration."),k(`
|
|
1036
|
+
Remove them from the repo (then commit):`),k(C(" anyray-connect --project --revert")));let tt=[W,...s.fallbackPort?[vn(W,s.fallbackPort)]:[]],Lr=Cp(tt);Lr.length>0&&(K("This terminal still points at the gateway"),N(` Still exported here: ${Lr.join(", ")}`),N(" Removing the block from your shell profile cannot reach a shell"),N(" that already ran it. Until these are gone, your tools keep"),N(" reaching the gateway and now fail with 401."),k(`
|
|
1037
|
+
Fix this terminal:`),k(C(` unset ${Lr.join(" ")}`)),k(`
|
|
1038
|
+
Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if($(`Done (${Gi} file(s) written).`),Ua.length>0){let _t=ji.length===Ua.length;K(_t?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let Fy of mZ(Ua,ji,Vi.includes("claude-desktop")?process.platform:void 0))N(Fy);jt()&&!o.yes&&!_t&&(await Ra("Have you applied the manual settings shown above?")?$("Acknowledged."):N("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?F(`
|
|
1039
|
+
Skipped the connection smoke test (--skip-verify).`):await CZ(W,l.map(_t=>_t.id)),K("What's next");let pe=new Set(Ha.filter(_t=>_t.status==="configured").map(_t=>_t.id)),tt=l.filter(_t=>pe.has(_t.id)).map(_t=>_t.title);if(k(tt.length>0?` Connected: ${tt.join(", ")}`:" Connected: no tools completed automatic configuration."),k(" Restart any editor that was already running \u2014 it loaded our config at startup."),k(" If something looks wrong: npx anyray-connect doctor"),!o.verbose)return 0;k(`
|
|
1036
1040
|
Re-test by hand any time:`),W.authMode!=="placeholder"&&l.length===1&&l[0]?.id==="cursor"?(k(C(` curl -sS ${W.origin}/connect/savings \\
|
|
1037
1041
|
-H "x-anyray-api-key: $(anyray-connect print-key)"`)),k(C(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):k(C(` curl -sS ${W.openaiBaseUrl}/chat/completions \\
|
|
1038
1042
|
-H "Content-Type: application/json" \\
|
|
1039
|
-
-H "Authorization: Bearer ${W.clientKey?`<your personal key (${
|
|
1040
|
-
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(C(" Revert: npx anyray-connect --revert"))}return 0}finally{xe()}};
|
|
1043
|
+
-H "Authorization: Bearer ${W.clientKey?`<your personal key (${Nt(W.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
|
|
1044
|
+
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(C(" Revert: npx anyray-connect --revert"))}return 0}finally{xe()}};RI(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
|