anyray-connect 0.11.178 → 0.11.180
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 +217 -214
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`;if(a||n.tombstoneAbsent!==!1)try{await
|
|
4
|
-
`),await he(o,e),await
|
|
5
|
-
`,{mode:384})}catch(s){throw await Do(t,{recursive:!0,force:!0}).catch(()=>{}),s}return async()=>{try{JSON.parse(await rs(n,"utf-8")).nonce===o&&await Do(t,{recursive:!0,force:!0})}catch{}}}catch(s){if(s.code!=="EEXIST")throw s}if(!(await
|
|
6
|
-
`,{mode:384}),await
|
|
7
|
-
`)},rn=(e,t={})=>{let n=e.byoUpstream,r=!n&&ee(e,"anthropic"),o=fe({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1,s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=
|
|
8
|
-
`)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},Cw=async()=>{try{let e=await P();return e.gateway?{origin:new URL(e.gateway).origin,metadata:fe({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},tt=async(e="auto")=>e==="profile"?Cw():e==="claude"?Aw():await Aw()??await Cw(),fc=async(e={})=>{let t=e.readTarget??tt,n=e.loadProfile??P,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a;try{a=new URL(r.gateway).origin}catch{return"unreadable"}return a===o.origin?"owned":"foreign"},jt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},mc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),oT);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:jt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var tr=()=>gc(yc(),".claude","settings.json"),hc=()=>gc(yc(),".claude.json"),aT=lc,xn="anyray",sT=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),nr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iT=e=>e instanceof Error?e.name:"UnknownError",cT={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},lT=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${xn} is not owned by Anyray Connect, so it was left untouched. Rename or remove that entry, then re-run anyray-connect.`;case"unreadable":return`Could not read ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is readable.`;case"unwritable":return`Could not write ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is writable.`;case"not-persisted":return`Registered the Anyray retrieval MCP server in ${t}, but the entry was gone when re-read \u2014 Claude Code rewrites that file wholesale while it runs. Fully quit Claude Code, then re-run anyray-connect.`}},dT={readJson:M,writeJson:(e,t)=>J(e,t)},uT=async(e,t=dT)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(pT(r)==="conflict")return{outcome:"failed",failure:"foreign"};try{await t.writeJson(e,r)}catch{return{outcome:"failed",failure:"unwritable"}}let o;try{o=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}let a=o.mcpServers,s=nr(a)?a[xn]:void 0;if(s&&Tt(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},pT=e=>{if("mcpServers"in e&&!nr(e.mcpServers))return"conflict";let t=nr(e.mcpServers)?{...e.mcpServers}:{},n=t[xn];return n!==void 0&&!Tt(n,"claude")?"conflict":(t[xn]=sT(),e.mcpServers=t,"installed")},kw=e=>{let t=e.mcpServers;return!t||!(xn in t)||!Tt(t[xn],"claude")?!1:(delete t[xn],Object.keys(t).length===0&&delete e.mcpServers,!0)},fT=e=>{sc(e,"PostToolUse",Ye,En(Ot(Ye),{matcher:"*"})),sc(e,"UserPromptSubmit",qn,En(Ot(qn)))},mT=e=>{sc(e,"SessionStart",Qn,En(Ot(Qn),{async:!0}))},Ew=e=>Mo(e,"SessionStart",Qn),vw=e=>{let t=Mo(e,"PostToolUse",Ye),n=Mo(e,"UserPromptSubmit",qn),r=Ew(e);return t||n||r},hT="print-key",yT=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(_e()),Ur=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===hT&&yT(t)},gT=async(e,t)=>{let n=(await $r(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of aT){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},wT=e=>typeof e.apiKeyHelper=="string"&&!Ur(e),Iw=async e=>{let t=await rp(),n=async()=>t,[r,o,a]=await Promise.all([uw({userSettings:e,readManaged:n}),gw({userSettings:e,readManaged:n}).catch(()=>[]),yw({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},Sw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await Iw(e),o=np(t),a=bw(n);return{routingOverrides:[...t.map(i=>({problem:tp(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:ww(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},rr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=gc(yc(),".claude"),t=await x(e);return{installed:t,detail:t?tr():"no ~/.claude directory"}},async apply(e,t){let n=tr(),r=await M(n),o=sw(r),a=await iw(e.origin,e.clientKey,o),s=cw(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=rn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await Iw(r),m=f.filter(T=>!T.repairable),y=f.filter(T=>T.repairable),g=[...m.map(T=>`WARNING: ${tp(T)}.`),...m.length?[np(m)]:[],...p.state==="fine"?[]:[`WARNING: ${uc(p)}.`,pc(p)],...y.map(T=>pw(T)),`${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:g};s.model!==void 0&&(r.model=s.model);let h=r.env??{};r.env={...h,...i};let w=r.env;for(let{name:T}of In)y.some(U=>U.name===T)?w[T]="":w[T]===""&&(process.env[T]??"").trim()===""&&delete w[T];if(u||delete w.ANTHROPIC_CUSTOM_HEADERS,c&&(h.ANTHROPIC_AUTH_TOKEN&&g.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete w.ANTHROPIC_AUTH_TOKEN),l)for(let T of aw)delete w[T];let b=!!e.clientKey,k=ne(),C=wT(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=ow(),w.ANTHROPIC_AUTH_TOKEN="",g.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,C&&!c&&!l&&b&&k&&g.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&k?(mT(r),g.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Ew(r),ne()?(fT(r),g.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(vw(r),g.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${_e()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await J(n,r);let E=[n],I=hc(),O;if(ne()){let T=await uT(I);T.outcome==="registered"?(E.push(I),g.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.")):(g.push(lT(T.failure,I)),O=cT[T.failure])}else try{let T=await M(I);kw(T)&&(await J(I,T),E.push(I))}catch(T){g.push(`Could not clean up a stale Anyray MCP registration in ${I} (${iT(T)}).`)}return{status:"configured",messages:g,changedFiles:E,...O?{errorClass:O}:{}}},skillsDir(){return gc(yc(),".claude","skills")},async pointsAt(e){let t=tr();if(!await x(t))return!1;try{let o=(await M(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await M(tr()).catch(()=>({}));return Sw(e)},async routingOverrides(){let e=await M(tr()).catch(()=>({}));return(await Sw(e)).routingOverrides},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=hc();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await M(e)).mcpServers?.[xn];return r?Tt(r,"claude")?{registered:!0,command:typeof r.command=="string"?r.command:null}:{registered:!1,command:null,reason:"foreign"}:{registered:!1,command:null,reason:"absent"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=tr();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!nr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>zn(c,Ye))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>zn(c,Ye)&&nr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>nr(l)&&ic(l.command,Ye))))}}catch{e="unreadable"}let r,o=!0,a=hc();if(!await x(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!nr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[xn];r=i===void 0?"missing":Tt(i,"claude")?"owned":"foreign",r==="owned"&&(o=cc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Fr()?"owned":"missing",beacon_target:await fc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(tr()),t=nr(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=tr();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await M(t),r=n.env,o=vw(n),a=Ur(n);a&&delete n.apiKeyHelper;let s=r?await gT(t,r):[],i=lw(typeof n.model=="string"?n.model:void 0,(await $r(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await J(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=hc();try{let d=await M(l);kw(d)&&(await J(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await ce(t),{status:"reverted",messages:c,changedFiles:[t]}}};var or=e=>{let{command:t,args:n}=nn([e]);return{command:t,args:n}},Bo=()=>Br();import{rm as bT,stat as AT}from"node:fs/promises";import{homedir as xw,platform as CT}from"node:os";import{join as kT}from"node:path";var op="Anyray",vT=(e=xw())=>kT(e,"Applications",`${op}.app`),ap=async(e={})=>{if((e.os??CT())!=="darwin")return{ok:!0,messages:[]};let n=vT(e.home??xw());try{return await AT(n).then(()=>!0,()=>!1)?(await bT(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed the legacy ${op}.app background item from ~/Applications.`]}):{ok:!0,messages:[]}}catch(r){return{ok:!1,messages:[`Could not remove the legacy ${op}.app background item (${r?.name??"Error"}).`]}}};import{homedir as Rw,userInfo as ST}from"node:os";var Ow=()=>{try{return Rw()!==ST().homedir}catch{return!1}},sp=e=>[`Skipped ${e} \u2014 HOME (${Rw()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var on=(e=process.env)=>e.CODESPACES==="true"||e.CODESPACE_NAME?"codespaces":e.REMOTE_CONTAINERS==="true"||e.REMOTE_CONTAINERS_IPC||e.DEVCONTAINER?"devcontainer":e.SSH_CONNECTION||e.SSH_TTY?"ssh":null,Hr=(e=process.env)=>on(e)!==null,Rn=e=>e==="codespaces"||e==="devcontainer",Fo=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var Tw=()=>Vr(Cc(),".anyray","logs"),lp=()=>Vr(Tw(),"connect-refresh.log"),Ac=1800,kc="ai.anyray.connect.refresh",ms="anyray-refresh",up="\\AnyrayConnectKeyRefresh",vc=kc,hs=ms,fs=up,RT=String(Ac/60),pp=(e,t)=>{let n=xT(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},fp=()=>Vr(Cc(),"Library","LaunchAgents",`${vc}.plist`),mp=()=>Vr(Cc(),".config","systemd","user"),_w=()=>Vr(mp(),`${hs}.service`),bc=()=>Vr(mp(),`${hs}.timer`),cp=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Sc=()=>or(Qn),OT=(e=Sc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${cp(o)}</string>`).join(`
|
|
2
|
+
var XR="http://localhost:8787",ts="anyray-placeholder",be=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Gt=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},Ou=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,zR=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),xg=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!zR.has(n)}catch{return!1}},Vt=e=>{let t=Gt(e||process.env.ANYRAY_GATEWAY_URL||XR),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},Oe=(e={})=>{let t=Vt(e.origin),n=e.placeholderKey?.trim()||ts,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:Ou(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:Ou(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:Ou(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 Cc,platform as up}from"node:os";import{join as Vr}from"node:path";import{mkdir as cp,readFile as xT,rename as RT,writeFile as wc,rm as Gr}from"node:fs/promises";import{spawnSync as OT}from"node:child_process";import{homedir as yc}from"node:os";import{join as gc}from"node:path";import{access as aO,chmod as sO,mkdir as _u,open as $u,readFile as Ng,rm as Kt,stat as Tg,utimes as iO}from"node:fs/promises";import{createHash as cO,randomUUID as $g}from"node:crypto";import{dirname as Mu,join as lO}from"node:path";import{isDeepStrictEqual as _o}from"node:util";import{randomUUID as qR}from"node:crypto";import{lstat as QR,open as eO,readFile as Tu,rename as Xi,rm as tO,writeFile as nO}from"node:fs/promises";import{platform as Rg}from"node:os";var Og=e=>e?.code==="ENOENT",rO=new Set(["EBUSY","EXDEV","ETXTBSY"]),Yn=async(e,t=Rg())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},oO=async(e,t,n={})=>{let r=await Tu(e),o;try{o=await Tu(t)}catch(s){if(!Og(s))throw s;await nO(t,r);return}let a=async s=>{let i=await eO(t,"r+");try{await i.write(s,0,s.length,0),await i.truncate(s.length),await Yn(i)}finally{await i.close()}};try{if(await a(r),await n.corruptAfterWrite?.(t),!(await Tu(t)).equals(r))throw Object.assign(new Error("in-place publication did not persist"),{code:"EIO"})}catch(s){throw await a(o).catch(()=>{}),s}},he=async(e,t,n=Rg(),r={})=>{let o=r.rename??Xi;if(n!=="win32"){try{await o(e,t)}catch(i){if(!rO.has(i?.code??""))throw i;await oO(e,t,r)}return}let a=`${t}.anyray-old-${process.pid}-${qR()}`,s=!1;try{let i=await QR(t);if(!i.isFile()&&!i.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await Xi(t,a),s=!0}catch(i){if(!Og(i))throw i}try{await Xi(e,t)}catch(i){if(s)try{await Xi(a,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${a}`)}throw i}s&&await tO(a,{force:!0})};var ns=e=>`${e}.anyray-bak`,Mg=async e=>{let t;try{t=await $u(Mu(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},_g=async(e,t)=>{let n,r;try{n=await $u(e,"wx",384),await n.writeFile(t,"utf-8"),await Yn(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Kt(e,{force:!0}).catch(()=>{}),r;await Mg(e)},dO=async e=>{let t;try{t=await $u(e,"r"),await Yn(t)}finally{await t?.close().catch(()=>{})}await Mg(e)},x=async e=>{try{return await aO(e),!0}catch{return!1}},M=async e=>{if(!await x(e))return{};let t=await Ng(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},J=async(e,t,n={})=>{await _u(Mu(e),{recursive:!0,mode:448});let r=ns(e);if(n.backup!==!1&&!await x(r)){let a=await x(e),s=a?await Ng(e,"utf-8"):`{}
|
|
3
|
+
`;if(a||n.tombstoneAbsent!==!1)try{await _g(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${$g()}`;try{await _g(o,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`),await he(o,e),await sO(e,384),await dO(e)}finally{await Kt(o,{force:!0}).catch(()=>{})}},Bg=1,Pg=3e4,uO=5e3,pO=/^[a-f0-9]{64}$/,Fg=e=>`${e}.pending`,fO=e=>`${e}.lock`,Pu=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=>Pu(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Pu(t[n])}`).join(",")}}`},Du=(e,t)=>({exists:e,sha256:cO("sha256").update(Pu(t)).digest("hex")}),Lu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Dg=e=>Lu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&pO.test(e.sha256),mO=e=>Lu(e)&&e.transactionVersion===Bg&&Dg(e.before)&&Dg(e.after)&&Lu(e.journal),Nu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,Po=async(e,t)=>{try{return await M(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},hO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Wg=async e=>{let t=fO(e),n=lO(t,"owner.json");await _u(Mu(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=$g();try{await _u(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await Po(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 Tg(n)).mtimeMs;i=!hO(c.pid)||l>Pg}catch{try{i=Date.now()-(await Tg(t)).mtimeMs>Pg}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Kt(t,{recursive:!0,force:!0});continue}try{await J(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Kt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await Po(n,"ownership journal")).nonce!==o)return;let i=new Date;await iO(n,i,i)}catch{}})()},uO);return a.unref(),async()=>{clearInterval(a);try{(await Po(n,"ownership journal")).nonce===o&&await Kt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},Ug=async e=>{let t=await x(e),n={};if(t)try{n=await M(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:Du(t,n)}},Hg=async(e,t)=>{let n=Fg(t);if(!await x(n))return;let r=await Po(n,"prepared ownership transaction");if(!mO(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await Ug(e),a=await x(t),s=await x(ns(e)),i=Nu(o.fingerprint,r.before),c=Nu(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await J(t,r.journal,{backup:!1}),await Kt(n,{force:!0});return}if(i){await Kt(n,{force:!0}),a||await ce(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},zi=async(e,t,n)=>{let r=await Wg(t);try{return await Hg(e,t),await n()}finally{await r()}},Lg=async(e,t,n,r)=>{if(!await x(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await Po(e,"ownership journal");if(!(n&&_o(a,t))){if(!_o(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await J(e,t,{backup:!1}):await Kt(e,{force:!0})}},qi=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await Wg(a);try{await Hg(n,a);let l=await Ug(n),d=Du(i,r),u=await x(a),f=u?await Po(a,"ownership journal"):void 0,p=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!Nu(l.fingerprint,d)){if(_o(l.value,o)&&f&&_o(f,p))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&_o(l.value,o)&&f&&_o(f,p))return;let m=await x(ns(n));if(f?.fileExisted===!0&&!m)throw new Error("ownership backup is missing; configuration was left unchanged");if(m&&!f)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let h=Fg(a),g={transactionVersion:Bg,before:l.fingerprint,after:Du(!0,o),journal:p};await J(h,g,{backup:!1});try{await J(n,o,f?{backup:!1}:{tombstoneAbsent:!1}),await(t.writeJournal??J)(a,p,{backup:!1}),await Kt(h,{force:!0})}catch(y){try{await Lg(n,l.value,l.exists,o)}catch(w){throw new AggregateError([y,w],"ownership journal publication failed and config rollback was incomplete")}try{await Lg(a,f??{},u,p),await Kt(h,{force:!0}),!m&&!f&&await ce(n)}catch(w){throw new AggregateError([y,w],"ownership journal publication failed after config rollback")}throw y}}finally{await c()}},$r=async e=>{try{return await M(ns(e))}catch{return{}}},ce=async e=>{await Kt(ns(e),{force:!0}).catch(()=>{})};import{access as WO}from"node:fs/promises";import{spawnSync as EO}from"node:child_process";import{readFileSync as IO,realpathSync as ss,statSync as zg}from"node:fs";import{access as xO,cp as qg,mkdir as Jg,readdir as RO,readFile as ju,realpath as OO,rename as TO,rm as Vu,writeFile as _O}from"node:fs/promises";import{tmpdir as PO}from"node:os";import{basename as Lo,dirname as He,join as Te,resolve as DO}from"node:path";import{writeFile as Qi,readFile as rs,chmod as Wu,stat as Uu,mkdir as Kg,rm as Do}from"node:fs/promises";import{AsyncLocalStorage as yO}from"node:async_hooks";import{randomUUID as gO}from"node:crypto";import{homedir as jg}from"node:os";import{join as Mr}from"node:path";var Q=()=>Mr(jg(),".anyray"),Zg=async()=>{let e=Q();try{if((await Uu(e)).isDirectory())return Mr(e,"connect.json")}catch{}return e},Hu=()=>Mr(Q(),"dev-key.pem"),Qe=async()=>{let e=Q(),t;try{if(!(await Uu(e)).isDirectory())t=await rs(e,"utf-8").catch(()=>{}),await Do(e,{force:!0});else return}catch{}if(await Kg(e,{recursive:!0,mode:448}),t!==void 0){let n=Mr(e,"connect.json");await Qi(n,t,{mode:384}),await Wu(n,384)}},ec=async e=>{await Qe();let t=Hu();await Qi(t,e,{mode:384}),await Wu(t,384)},Be=async()=>{try{let e=await rs(Hu(),"utf-8");return e.trim()?e:void 0}catch{return}},os=async()=>{await Do(Hu(),{force:!0}).catch(()=>{})},P=async()=>{try{let e=await rs(await Zg(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}},wO=0,bO=3e4,AO=5e3,CO=25,kO=()=>Mr(jg(),".anyray-connect-profile.lock"),Bu=new yO,vO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},SO=async e=>{try{let t=JSON.parse(await rs(Mr(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!vO(t.pid)}catch{}return Date.now()-(await Uu(e)).mtimeMs>bO},Yg=async(e=AO)=>{let t=kO(),n=Mr(t,"owner.json"),r=Date.now()+e;for(;;){let o=gO();try{await Kg(t,{mode:448});try{await Qi(n,`${JSON.stringify({pid:process.pid,nonce:o})}
|
|
5
|
+
`,{mode:384})}catch(s){throw await Do(t,{recursive:!0,force:!0}).catch(()=>{}),s}return async()=>{try{JSON.parse(await rs(n,"utf-8")).nonce===o&&await Do(t,{recursive:!0,force:!0})}catch{}}}catch(s){if(s.code!=="EEXIST")throw s}if(!(await SO(t).catch(()=>!1)&&await Do(t,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=r)throw new Error("connect profile is busy; retry the command");await new Promise(s=>setTimeout(s,CO))}}},as=async(e,t={})=>{if(Bu.getStore()===!0)return e();let n=await Yg(t.waitMs);try{return await Bu.run(!0,e)}finally{await n()}},Gg=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Zg(),r=`${n}.${process.pid}.${wO++}.tmp`;await Qi(r,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,{mode:384}),await Wu(r,384);try{await he(r,n)}catch(o){throw await Do(r,{force:!0}).catch(()=>{}),o}},le=async e=>{if(Bu.getStore()===!0){await Gg(e);return}let t=await Yg();try{await Gg(e)}finally{await t()}};var Fu=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],Vg="ssoLink",Gu=async()=>{let e=await P();return Fu.some(t=>e[t]!==void 0)?!0:await Be()!==void 0},tc=async()=>{let e=await P(),t=Fu.some(a=>e[a]!==void 0),n=e[Vg]!==void 0,r=e.byoUpstream!==void 0,o=await Be()!==void 0;if(t||n||r||e.managedEnrollmentDisabled!==!0){let a={...e};for(let s of Fu)delete a[s];delete a[Vg],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,delete a.anyrayFleetManaged,await le(a)}if(await os(),await Be())throw new Error(`could not remove the dev key from ${Q()}`);return t||n||r||o},Jn=async(e,t,n=!1)=>{let r=await P(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let m of e){let h=m.status==="configured"||m.status==="queued";!t&&h&&(o.add(m.id),a.delete(m.id),s=void 0),t&&(m.status==="reverted"||m.status==="queued")&&(o.delete(m.id),a.add(m.id))}n&&o.clear();let i=[...o].sort(),c=[...r.managedTools??[]].sort(),l=[...a].sort(),d=[...r.revertedTools??[]].sort();if(i.length===c.length&&i.every((m,h)=>m===c[h])&&r.revertedTools!=null&&l.length===d.length&&l.every((m,h)=>m===d[h])&&s===r.offboardedAt)return;let{offboardedAt:f,...p}=r;await le({...p,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},nc=async(e=new Date().toISOString())=>{await le({...await P(),offboardedAt:e})};var No=e=>DO(e).replace(/\\/g,"/").toLowerCase(),Ku=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",is=e=>`${e}.source`,Qg=e=>/(^|\/)_npx(\/|$)/.test(No(e)),Zu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(No(e)),Yu=e=>{let t=No(e),n=[PO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(No);return Qg(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},dt=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),cs=e=>/[\\/](node|node\.exe)$/i.test(e),Xn=(e=dt())=>cs(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,Xg=e=>{try{let t=zg(e);return t.isFile()?t.size:void 0}catch{return}},Ju=e=>{let t=He(e);if(Lo(t)==="versions")return t;let n=He(t);return Lo(n)==="versions"?n:void 0},oc=(e,t)=>t!==void 0&&(He(e)===t||He(He(e))===t),LO=e=>{let t=Ju(e);if(!t)return;let n=Te(He(t),"bin",Ku());try{let r=ss(n);return r===ss(e)||oc(r,ss(t))?n:void 0}catch{return}},$o=(e=Q(),t=process.platform)=>{let n=Te(e,"bin",Ku(t));try{let r=ss(n),o=ss(Te(e,"versions"));if(oc(r,o))return n;if(t==="win32"){let a=IO(is(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=Xg(Te(o,a,Ku(t)))??Xg(Te(o,a));if(s!==void 0&&s===zg(n).size)return n}}catch{return}},Br=(e=dt())=>{let t=Xn(e),n=Zu(t)||zu(t)?$o():void 0;return LO(e.execPath)??n??t},ew=(e=dt())=>Br(e)!==Xn(e),nn=(e,t=dt())=>{let n=Br(t);return cs(t.execPath)&&t.scriptPath!==void 0&&n===Xn(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},tw=(e=dt())=>{let t=Br(e);return!cs(e.execPath)&&!Yu(t)?He(t):Te(Q(),"bin")},rc=async e=>{try{return await xO(e),!0}catch{return!1}},NO=async e=>{let t=await OO(e),n=He(t),r=He(n),o=Te(r,"package.json"),a=await ju(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 rc(Te(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},$O=async(e,t)=>{let n=t;for(;;){let r=Te(n,"node_modules",e);if(await rc(Te(r,"package.json")))return r;let o=He(n);if(o===n)return;n=o}},MO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await ju(Te(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await $O(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await qg(i,Te(t,s),{recursive:!0}),r.push(i)}}},BO=async(e=dt())=>{let t=$o();if(t)return{command:t,args:[],entryPath:t};if(!cs(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await NO(e.scriptPath);await Qe();let r=Te(Q(),"bin",`connect-runtime-${n.version}`),o=Te(r,"dist","index.js");if(!await rc(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Vu(a,{recursive:!0,force:!0}),await Jg(a,{recursive:!0,mode:448});try{await qg(n.dist,Te(a,"dist"),{recursive:!0}),await _O(Te(a,"package.json"),await ju(n.packageJson),{mode:384}),await MO(n.root,Te(a,"node_modules")),await Jg(He(r),{recursive:!0,mode:448});try{await TO(a,r)}catch(s){if(!await rc(o))throw s}}finally{await Vu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Xu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,FO=e=>{let t=Lo(He(He(e)));return Xu.test(t)?t:void 0},zu=(e,t=Q())=>{let n=He(He(e));return No(He(n))===No(Te(t,"bin"))&&Xu.test(Lo(n))&&Lo(He(e))==="dist"&&Lo(e)==="index.js"},ac=async(e=dt())=>{let t=Te(Q(),"bin"),n=FO(Xn(e)),r=[];for(let o of await RO(t).catch(()=>[])){if(!Xu.test(o)||o===n)continue;let a=Te(t,o);await Vu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},nw=async(e,t=dt())=>{let n=Xn(t);if(!cs(t.execPath)||!Qg(n)||$o())return;let r=await BO(t),o=EO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var qu=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,ls=(e,t)=>[e,...t].map(qu).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))},sc=(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},Mo=(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)},Qu=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 Ye="__anyray-hook",rw="__anyray-codex-hook",qn="__anyray-prompt-hook",ow="__anyray-shell-pretool",ep="__anyray-shell-run",aw="__anyray-read-pretool",Qn="__anyray-refresh",ds=(e,t=[])=>{let{command:n,args:r}=nn([e,...t]);return{command:n,args:r}},Ot=(e,t=[])=>{let n=ds(e,t);return[n.command,...n.args].map(qu).join(" ")},ic=(e,t,n=[])=>typeof e=="string"&&e.trim()===Ot(t,n),sw=()=>Ot("print-key"),_e=()=>Br(),et=Yu,ne=()=>!et(_e()),Fr=async()=>{if(!ne())return!1;try{return await WO(_e()),!0}catch{return!1}},er="__anyray-mcp-server",Ge=e=>ds(er,[e]),UO=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),cc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ge(t);return n.command===r.command&&UO(n.args,r.args)},Tt=(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 ee=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,fe=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Wr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],iw=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],lc=[...Wr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],HO=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
|
|
7
|
+
`)},rn=(e,t={})=>{let n=e.byoUpstream,r=!n&&ee(e,"anthropic"),o=fe({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1,s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=HO(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 tp}from"zod";var GO=5e3,VO=1e3,KO=1e8,jO=tp.object({modelContext:tp.object({contextTokens:tp.number().int().min(VO).max(KO)}).optional()}),cw=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},lw=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??GO,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=jO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var ZO=1e6,us="[1m]",YO=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},dw=(e,t)=>!e||t===void 0?{}:YO(e)?{envTokens:t}:t<ZO?{}:e.toLowerCase().endsWith(us)?{}:{model:`${e}${us}`},uw=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(us))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(us))return e.slice(0,-us.length)};import{platform as JO}from"node:os";var _t=(e=JO())=>{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 In=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],dc=e=>typeof e=="string"&&e.trim()!=="",XO=(e,t)=>typeof e[t]=="string"&&!dc(e[t]),pw=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},zO=()=>M(_t()).catch(()=>({})),fw=async(e={})=>{let t=e.env??process.env,n=pw(e.userSettings??{}),r=pw(await(e.readManaged??zO)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of In)dc(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${_t()})`,repairable:!1}):dc(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!XO(n,a)&&dc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},np=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`,rp=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.",mw=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 qO=In.map(e=>e.name),QO=lc.filter(e=>!qO.includes(e)),hw=e=>typeof e=="string"&&e.trim()!=="",yw=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},eT=(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)},tT=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},op=()=>M(_t()).catch(()=>({})),gw=op,nT=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,Ye))},ww=async(e={})=>{let t=await(e.readManaged??gw)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!nT(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},uc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${_t()}) \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 (${_t()}), 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",pc=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.",bw=async(e={})=>{let t=yw(e.userSettings??{}),n=yw(await(e.readManaged??gw)().catch(()=>({}))),r=[];for(let o of QO){if(!hw(n[o])||!hw(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(eT(n[o],t[o],a))continue;let s=a?tT(n[o]):void 0;r.push({name:o,source:`managed settings (${_t()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},Aw=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`,Cw=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 rT}from"node:os";import{join as oT}from"node:path";import{readFile as aT}from"node:fs/promises";var sT=400,kw=async()=>{try{let e=oT(rT(),".claude","settings.json"),n=JSON.parse(await aT(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
|
|
8
|
+
`)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},vw=async()=>{try{let e=await P();return e.gateway?{origin:new URL(e.gateway).origin,metadata:fe({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},tt=async(e="auto")=>e==="profile"?vw():e==="claude"?kw():await kw()??await vw(),fc=async(e={})=>{let t=e.readTarget??tt,n=e.loadProfile??P,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a;try{a=new URL(r.gateway).origin}catch{return"unreadable"}return a===o.origin?"owned":"foreign"},jt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},mc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),sT);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:jt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var tr=()=>gc(yc(),".claude","settings.json"),hc=()=>gc(yc(),".claude.json"),iT=lc,xn="anyray",cT=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),nr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lT=e=>e instanceof Error?e.name:"UnknownError",dT={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},uT=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${xn} is not owned by Anyray Connect, so it was left untouched. Rename or remove that entry, then re-run anyray-connect.`;case"unreadable":return`Could not read ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is readable.`;case"unwritable":return`Could not write ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is writable.`;case"not-persisted":return`Registered the Anyray retrieval MCP server in ${t}, but the entry was gone when re-read \u2014 Claude Code rewrites that file wholesale while it runs. Fully quit Claude Code, then re-run anyray-connect.`}},pT={readJson:M,writeJson:(e,t)=>J(e,t)},fT=async(e,t=pT)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(mT(r)==="conflict")return{outcome:"failed",failure:"foreign"};try{await t.writeJson(e,r)}catch{return{outcome:"failed",failure:"unwritable"}}let o;try{o=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}let a=o.mcpServers,s=nr(a)?a[xn]:void 0;if(s&&Tt(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},mT=e=>{if("mcpServers"in e&&!nr(e.mcpServers))return"conflict";let t=nr(e.mcpServers)?{...e.mcpServers}:{},n=t[xn];return n!==void 0&&!Tt(n,"claude")?"conflict":(t[xn]=cT(),e.mcpServers=t,"installed")},Sw=e=>{let t=e.mcpServers;return!t||!(xn in t)||!Tt(t[xn],"claude")?!1:(delete t[xn],Object.keys(t).length===0&&delete e.mcpServers,!0)},hT=e=>{sc(e,"PostToolUse",Ye,En(Ot(Ye),{matcher:"*"})),sc(e,"UserPromptSubmit",qn,En(Ot(qn)))},yT=e=>{sc(e,"SessionStart",Qn,En(Ot(Qn),{async:!0}))},xw=e=>Mo(e,"SessionStart",Qn),Ew=e=>{let t=Mo(e,"PostToolUse",Ye),n=Mo(e,"UserPromptSubmit",qn),r=xw(e);return t||n||r},gT="print-key",wT=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(_e()),Ur=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===gT&&wT(t)},bT=async(e,t)=>{let n=(await $r(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of iT){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},AT=e=>typeof e.apiKeyHelper=="string"&&!Ur(e),Rw=async e=>{let t=await op(),n=async()=>t,[r,o,a]=await Promise.all([fw({userSettings:e,readManaged:n}),bw({userSettings:e,readManaged:n}).catch(()=>[]),ww({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},Iw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await Rw(e),o=rp(t),a=Cw(n);return{routingOverrides:[...t.map(i=>({problem:np(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:Aw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},rr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=gc(yc(),".claude"),t=await x(e);return{installed:t,detail:t?tr():"no ~/.claude directory"}},async apply(e,t){let n=tr(),r=await M(n),o=cw(r),a=await lw(e.origin,e.clientKey,o),s=dw(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=rn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await Rw(r),m=f.filter(T=>!T.repairable),h=f.filter(T=>T.repairable),g=[...m.map(T=>`WARNING: ${np(T)}.`),...m.length?[rp(m)]:[],...p.state==="fine"?[]:[`WARNING: ${uc(p)}.`,pc(p)],...h.map(T=>mw(T)),`${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:g};s.model!==void 0&&(r.model=s.model);let y=r.env??{};r.env={...y,...i};let w=r.env;for(let{name:T}of In)h.some(U=>U.name===T)?w[T]="":w[T]===""&&(process.env[T]??"").trim()===""&&delete w[T];if(u||delete w.ANTHROPIC_CUSTOM_HEADERS,c&&(y.ANTHROPIC_AUTH_TOKEN&&g.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete w.ANTHROPIC_AUTH_TOKEN),l)for(let T of iw)delete w[T];let b=!!e.clientKey,k=ne(),C=AT(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=sw(),w.ANTHROPIC_AUTH_TOKEN="",g.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,C&&!c&&!l&&b&&k&&g.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&k?(yT(r),g.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):xw(r),ne()?(hT(r),g.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(Ew(r),g.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${_e()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await J(n,r);let E=[n],I=hc(),O;if(ne()){let T=await fT(I);T.outcome==="registered"?(E.push(I),g.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.")):(g.push(uT(T.failure,I)),O=dT[T.failure])}else try{let T=await M(I);Sw(T)&&(await J(I,T),E.push(I))}catch(T){g.push(`Could not clean up a stale Anyray MCP registration in ${I} (${lT(T)}).`)}return{status:"configured",messages:g,changedFiles:E,...O?{errorClass:O}:{}}},skillsDir(){return gc(yc(),".claude","skills")},async pointsAt(e){let t=tr();if(!await x(t))return!1;try{let o=(await M(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await M(tr()).catch(()=>({}));return Iw(e)},async routingOverrides(){let e=await M(tr()).catch(()=>({}));return(await Iw(e)).routingOverrides},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=hc();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await M(e)).mcpServers?.[xn];return r?Tt(r,"claude")?{registered:!0,command:typeof r.command=="string"?r.command:null}:{registered:!1,command:null,reason:"foreign"}:{registered:!1,command:null,reason:"absent"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=tr();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!nr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>zn(c,Ye))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>zn(c,Ye)&&nr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>nr(l)&&ic(l.command,Ye))))}}catch{e="unreadable"}let r,o=!0,a=hc();if(!await x(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!nr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[xn];r=i===void 0?"missing":Tt(i,"claude")?"owned":"foreign",r==="owned"&&(o=cc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Fr()?"owned":"missing",beacon_target:await fc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(tr()),t=nr(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=tr();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await M(t),r=n.env,o=Ew(n),a=Ur(n);a&&delete n.apiKeyHelper;let s=r?await bT(t,r):[],i=uw(typeof n.model=="string"?n.model:void 0,(await $r(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await J(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=hc();try{let d=await M(l);Sw(d)&&(await J(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await ce(t),{status:"reverted",messages:c,changedFiles:[t]}}};var or=e=>{let{command:t,args:n}=nn([e]);return{command:t,args:n}},Bo=()=>Br();import{rm as CT,stat as kT}from"node:fs/promises";import{homedir as Ow,platform as vT}from"node:os";import{join as ST}from"node:path";var ap="Anyray",ET=(e=Ow())=>ST(e,"Applications",`${ap}.app`),sp=async(e={})=>{if((e.os??vT())!=="darwin")return{ok:!0,messages:[]};let n=ET(e.home??Ow());try{return await kT(n).then(()=>!0,()=>!1)?(await CT(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed the legacy ${ap}.app background item from ~/Applications.`]}):{ok:!0,messages:[]}}catch(r){return{ok:!1,messages:[`Could not remove the legacy ${ap}.app background item (${r?.name??"Error"}).`]}}};import{homedir as Tw,userInfo as IT}from"node:os";var _w=()=>{try{return Tw()!==IT().homedir}catch{return!1}},ip=e=>[`Skipped ${e} \u2014 HOME (${Tw()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var on=(e=process.env)=>e.CODESPACES==="true"||e.CODESPACE_NAME?"codespaces":e.REMOTE_CONTAINERS==="true"||e.REMOTE_CONTAINERS_IPC||e.DEVCONTAINER?"devcontainer":e.SSH_CONNECTION||e.SSH_TTY?"ssh":null,Hr=(e=process.env)=>on(e)!==null,Rn=e=>e==="codespaces"||e==="devcontainer",Fo=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var Pw=()=>Vr(Cc(),".anyray","logs"),dp=()=>Vr(Pw(),"connect-refresh.log"),Ac=1800,kc="ai.anyray.connect.refresh",ms="anyray-refresh",pp="\\AnyrayConnectKeyRefresh",vc=kc,hs=ms,fs=pp,TT=String(Ac/60),fp=(e,t)=>{let n=OT(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},mp=()=>Vr(Cc(),"Library","LaunchAgents",`${vc}.plist`),hp=()=>Vr(Cc(),".config","systemd","user"),Dw=()=>Vr(hp(),`${hs}.service`),bc=()=>Vr(hp(),`${hs}.timer`),lp=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Sc=()=>or(Qn),_T=(e=Sc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${lp(o)}</string>`).join(`
|
|
9
9
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
10
10
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
11
11
|
<plist version="1.0">
|
|
@@ -19,18 +19,18 @@ ${r}
|
|
|
19
19
|
<key>RunAtLoad</key><true/>
|
|
20
20
|
<key>ProcessType</key><string>Background</string>
|
|
21
21
|
<key>LowPriorityIO</key><true/>
|
|
22
|
-
<key>StandardOutPath</key><string>${
|
|
23
|
-
<key>StandardErrorPath</key><string>${
|
|
22
|
+
<key>StandardOutPath</key><string>${lp(dp())}</string>
|
|
23
|
+
<key>StandardErrorPath</key><string>${lp(dp())}</string>
|
|
24
24
|
</dict>
|
|
25
25
|
</plist>
|
|
26
|
-
`},
|
|
26
|
+
`},PT=(e=Sc())=>{let{command:t,args:n}=e;return`[Unit]
|
|
27
27
|
Description=Anyray connect gateway key refresh
|
|
28
28
|
After=network-online.target
|
|
29
29
|
|
|
30
30
|
[Service]
|
|
31
31
|
Type=oneshot
|
|
32
32
|
ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
|
|
33
|
-
`},
|
|
33
|
+
`},DT=()=>`[Unit]
|
|
34
34
|
Description=Anyray connect gateway key refresh (every ${Ac/60}m)
|
|
35
35
|
|
|
36
36
|
[Timer]
|
|
@@ -40,65 +40,65 @@ Persistent=true
|
|
|
40
40
|
|
|
41
41
|
[Install]
|
|
42
42
|
WantedBy=timers.target
|
|
43
|
-
`,
|
|
44
|
-
${t.stderr??""}`}},
|
|
45
|
-
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},
|
|
46
|
-
`),o=xc(r),a=
|
|
47
|
-
`),s=xc(a),i=
|
|
48
|
-
`),
|
|
49
|
-
`),g=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${
|
|
50
|
-
`);return[m.replace(/\s*$/,""),h
|
|
43
|
+
`,LT=(e=Sc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),ps=e=>["Auto-refresh scheduling is not wired for this OS. To keep your gateway","key from expiring mid-session, run this on a ~30-min schedule yourself","(e.g. cron / Task Scheduler), or just re-run connect when a tool 401s:",` ${[e.command,...e.args].map(n=>/\s/.test(n)?JSON.stringify(n):n).join(" ")}`],Lw=e=>!e.run&&_w(),NT=async(e,t)=>await xT(mp(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",vc]).ok,ar=async(e={})=>{let t=e.os??up(),n=e.invocation??Sc(),r=e.run??fp,o=e.binaryPath??Bo();if(et(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(Lw(e))return{ok:!1,messages:ip("auto-refresh scheduling")};let a=on(e.env??(e.run?{}:process.env));if(Rn(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${Fo(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=mp(),i=_T(n),c=await sp({os:t});if(await NT(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`,...c.messages]};await cp(Pw(),{recursive:!0,mode:448}),await cp(Vr(Cc(),"Library","LaunchAgents"),{recursive:!0});let l=String(process.getuid?.()??""),d=`${s}.new-${process.pid}`;await Gr(d,{force:!0}).catch(()=>{}),await wc(d,i),r("launchctl",["bootout",`gui/${l}`,s]),await Gr(s,{force:!0}).catch(()=>{});try{await RT(d,s)}catch{await wc(s,i),await Gr(d,{force:!0}).catch(()=>{})}return r("launchctl",["bootstrap",`gui/${l}`,s]).ok||r("launchctl",["load","-w",s]).ok?{ok:!0,messages:[`Scheduled auto-refresh via launchd (${s}).`,...c.messages]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...ps(n)]}}if(t==="linux")return await cp(hp(),{recursive:!0}),await wc(Dw(),PT(n)),await wc(bc(),DT()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${hs}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${bc()}).`]}:{ok:!1,messages:[`Wrote ${bc()} but \`systemctl --user enable --now\` failed.`,...ps(n)]};if(t==="win32"){let s=LT(n);return r("schtasks",["/Create","/TN",fs,"/TR",s,"/SC","MINUTE","/MO",TT,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",fs]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${fs}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...ps(n)]}}return{ok:!1,messages:ps(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...ps(n)]}}},sr=async(e={})=>{await Gr(dp(),{force:!0}).catch(()=>{});let t=e.os??up(),n=e.run??fp,r=[];if(Lw(e))return{ok:!0,messages:ip("scheduler teardown")};try{if(t==="darwin"){let o=mp(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Gr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.");let s=await sp({os:t});r.push(...s.messages)}else t==="linux"?(n("systemctl",["--user","disable","--now",`${hs}.timer`]),await Gr(bc(),{force:!0}),await Gr(Dw(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",fs,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Wo=async(e=up(),t=fp)=>e==="win32"?t("schtasks",["/Query","/TN",fs]).ok:e==="darwin"?t("launchctl",["list",vc]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${hs}.timer`]).ok:!1;import{platform as $T}from"node:os";import{stat as MT}from"node:fs/promises";import{spawnSync as BT}from"node:child_process";var Nw="/Applications/Anyray Connect Tray.app",FT=new Set(["V53XMA78UF"]),WT="ai.anyray.connect-tray",UT=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,HT=e=>{let t=BT("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
44
|
+
${t.stderr??""}`}},GT=async e=>{try{return(await MT(e)).isDirectory()}catch{return!1}},VT=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},yp=async(e,t={})=>{if((t.os??$T())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??GT)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??HT;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?VT(a.output):void 0;return s?FT.has(s)?UT(a.output)!==WT?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},Uo=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await yp(n,t)).ok?"healthy":"gone"},gp=async(e={})=>{try{let t=e.load??P,n=await t(),r=await Uo(n,e);if(r!=="gone")return r;let o=e.installScheduler??ar;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),await(e.save??le)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var KT={"not-macos":"persistence swap: macOS only \u2014 the LaunchAgent stays in place on this OS.","bad-path":"persistence swap: --app-path must point at a .app bundle.",missing:"persistence swap: tray app bundle not found \u2014 nothing changed.",unsigned:"persistence swap: tray app failed codesign verification \u2014 refusing to adopt (RFC 0010 invariant 5).","no-team-identifier":"persistence swap: tray app has no Developer ID TeamIdentifier (adhoc or unsigned) \u2014 refusing to adopt (RFC 0010 invariant 5).","untrusted-team":"persistence swap: tray app is signed by a Developer ID that is not Anyray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgent stays in place.","untrusted-bundle-id":"persistence swap: that bundle is not the Anyray Connect Tray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgent stays in place."},jT=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},ZT=async(e,t)=>{let n=t.stderr??console.error,r=jT(e,"--app-path")??Nw,o=await yp(r,t);if(!o.ok)return n(KT[o.reason]),1;let s=await(t.load??P)();return await(t.save??le)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??sr)().catch(()=>{}),0},YT=async e=>{let t=e.load??P,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??ar;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),await(e.save??le)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},$w=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await ZT(e,t):e.includes("--release-tray")?await YT(t):(n("persistence swap: expected --adopt-tray or --release-tray."),1)}catch(r){return n(`persistence swap: failed (${r instanceof Error?r.name:"Error"}).`),1}};import{access as JT}from"node:fs/promises";import{homedir as Ww,platform as Ap}from"node:os";import{join as an}from"node:path";import{basename as Mw,dirname as wp,join as Ho}from"node:path";var ir="https://github.com/anyrayHQ/install/releases",Kr="connect-v",Bw="release-assets.githubusercontent.com",bp=".anyray",jr="__anyray-refresh-desktop-helpers",Zr=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",cr=(e,t=process.platform)=>({launcher:Ho(e,"bin",Zr(t)),binDir:Ho(e,"bin"),versionsDir:Ho(e,"versions"),lock:Ho(e,"update.lock"),state:Ho(e,"update-state.json")}),ys=(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"}},Fw=(e,t,n=process.platform)=>Mw(e)===Zr(n)&&Mw(wp(e))==="bin"?wp(wp(e)):Ho(t,bp);var Cp=(e=Ap(),t=Ww())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:kc,paths:[an(t,"Library","LaunchAgents",`${kc}.plist`)],dataPaths:[an(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=an(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${ms}.timer`,paths:[an(n,`${ms}.timer`),an(n,`${ms}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:pp,paths:[]}]:[]},Uw=async e=>{try{return await JT(e),!0}catch{return!1}},Ec=async(e={})=>{let t=e.os??Ap(),n=e.exists??Uw;for(let r of Cp(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await Wo(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},Hw=async e=>{let t={suspected:!1,missingPaths:[],kinds:[],removed:!1};if(!e.binaryDurable||!e.schedulerEnabled||e.schedulerInstalled||e.trayManaged===!0)return t;let n=e.exists??Uw;for(let r of Cp(e.os,e.home))for(let o of r.paths)await n(o)||(t.missingPaths.push(o),t.kinds.includes(r.kind)||t.kinds.push(r.kind));return t.suspected=t.missingPaths.length>0,t.removed=t.suspected&&e.schedulerInstalledOnce===!0,t},Gw=(e=Ap(),t=Ww(),n=Bo(),r=process.arch)=>{let o=cr(Fw(n,t,e),e),a=Zr(e),s=ys(e,r),i=s?[` ${ir}/download/${Kr}<version>/${s}`]:[" (no binary is published for this OS/architecture \u2014 nothing here"," downloads a release asset)"],c=["Anyray connect can install one per-user background scheduler. It is","unprivileged, runs as the logged-in user, and renews the seat gateway key","so a long AI-coding session does not lose access.","","Executable:",` ${n}`,""];for(let l of Cp(e,t)){c.push(`${l.title} \u2014 supervisor name: ${l.supervisorName}`);for(let d of l.paths)c.push(` ${d}`);l.paths.length===0&&c.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let d of l.dataPaths??[])c.push(` ${d} (captured stdout/stderr \u2014 error names only)`);c.push("")}return c.push("Also spawns, detached and short-lived (same executable, hidden","subcommands \u2014 not a separate install):"," - Coding-tool MCP clients run `anyray-connect __anyray-mcp-server` as a"," stdio server, which may spawn `anyray-connect __anyray-refresh`."," - The Anyray VS Code extension may spawn"," `anyray-connect __anyray-spawn-refresh` on activation."," These triggers are throttled and serialized with the scheduler.","","Network behavior:"," - Outbound: your org's Anyray gateway and endpoint-control APIs over HTTPS."," - Outbound: github.com, for the self-update below. Asset downloads",` redirect to ${Bw}.`," - No inbound listener, no proxy, no CA certificate, no DNS change.","","Self-update:"," The installed binary keeps itself on the published version, on the same"," tick as key renewal. Every file it downloads is SHA-256 verified against"," the release's published SHA256SUMS before anything is activated; a"," mismatch is deleted and the running version stays.",""," Fetches over HTTPS, unauthenticated, no request body:",` ${ir}/latest`," (the redirect target alone names the published version)",` ${ir}/download/${Kr}<version>/connect-update.json`,` ${ir}/download/${Kr}<version>/SHA256SUMS`,...i,""," Writes:",` ${an(o.versionsDir,"<version>",a)}`," (the downloaded binary; the version it replaces is kept for rollback)",` ${o.launcher}`," (the stable path above, pointed at the new version)",` ${o.lock}`,` ${o.state}`,` ${an(o.versionsDir,"<version>",`${a}.part-<pid>`)}`,...e==="win32"?[` ${an(o.binDir,`${a}.old-<pid>`)}`,` ${an(o.binDir,`${a}.rollback-<pid>`)}`]:[` ${an(o.binDir,`${a}.new-<pid>`)}`]," (transient: a partial download and the staged swap, removed as the"," swap completes or on the next run)",...e==="win32"?[""," Windows cannot overwrite a running .exe, so activation renames the"," live copy aside, copies the new one into place, and records the",` active version in \`${a}.source\` beside it.`]:[],""," Runs the newly downloaded binary directly, around the swap:"," - `--version`, as a smoke test when it replaces a non-managed runtime;"," a failure puts the previous version back.",` - \`anyray-connect ${jr}\`, which rewrites an`," already-installed Anyray credential-helper script to name the new"," path. It writes nothing where no such helper exists.","","Why it looks like persistence to a heuristic scanner: it is a real login","item, by design, so key renewal survives reboots. Allow-list the paths above","or let Fleet provide the refresh trigger instead."),c};import{homedir as r_}from"node:os";import{join as Dc}from"node:path";import{chmod as o_,readFile as gs,rm as Jw,copyFile as a_}from"node:fs/promises";var Yr="# >>> anyray connect >>>",Rc="# <<< anyray connect <<<",kp="# restore: ",Vw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Oc=e=>{let t=new RegExp(`\\n*${Vw(Yr)}[\\s\\S]*?${Vw(Rc)}\\n?`,"g");return e.replace(t,"")},vp=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,Kw=e=>Ic(e,"[")-Ic(e,"]"),XT=e=>e.replace(/^['"]|['"]$/g,""),xc=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+Kw(vp(a))),t.push({kind:"other"});continue}let s=a.trim();if(s===""||s.startsWith("#")){t.push({kind:"other"});continue}if(s.startsWith("[")){t.push({kind:"table"});continue}let i=a.indexOf("="),c=i>=0?XT(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=vp(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+Kw(l)))}return t},Sp=e=>e.findIndex(t=>t.kind==="table"),Ep=e=>e.includes(Yr),jw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
45
|
+
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},Ip=(e,t)=>jw(Oc(e),t),xp=e=>{let t=e.indexOf(Yr);if(t<0)return;let n=e.indexOf(Rc,t+Yr.length);if(!(n<0))return e.slice(t,n)},Zw=(e,t)=>{let n=e.indexOf(Yr);if(n<0)return!1;let r=e.indexOf(Rc,n+Yr.length);return r<0?!1:jw(e.slice(n,r),t)},Rp=(e,t)=>{let r=Oc(e).split(`
|
|
46
|
+
`),o=xc(r),a=Sp(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=vp(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}},Tc=(e,t,n)=>{let r=Yw(e),a=Oc(e).split(`
|
|
47
|
+
`),s=xc(a),i=Sp(s),c=new Set(n),l=i===-1?a.length:i,d=[],u=new Map(r);for(let b=0;b<a.length;b++){let k=s[b];if(b<l&&k.kind==="key"&&c.has(k.key)){u.has(k.key)||u.set(k.key,a[b].trim());continue}d.push(a[b])}let f=xc(d),p=Sp(f),m=(p===-1?d:d.slice(0,p)).join(`
|
|
48
|
+
`),h=p===-1?"":d.slice(p).join(`
|
|
49
|
+
`),g=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${kp}${b}`),y=[Yr,...g,...t,Rc].join(`
|
|
50
|
+
`);return[m.replace(/\s*$/,""),y,h.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
|
|
51
51
|
|
|
52
52
|
`).replace(/\s*$/,"")+`
|
|
53
|
-
`},
|
|
54
|
-
`)){let o=r.trim();if(!o.startsWith(
|
|
53
|
+
`},Yw=e=>{let t=new Map,n=xp(e);if(n===void 0)return t;for(let r of n.split(`
|
|
54
|
+
`)){let o=r.trim();if(!o.startsWith(kp))continue;let a=o.slice(kp.length).trim(),[s]=xc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},_c=e=>{if(!Ep(e))return null;let t=[...Yw(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Oc(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
|
|
55
55
|
`),n].filter(a=>a.length>0).join(`
|
|
56
56
|
|
|
57
57
|
`);return o.length>0?o+`
|
|
58
|
-
`:""};import{randomUUID as
|
|
58
|
+
`:""};import{randomUUID as zT}from"node:crypto";import{chmod as qT,mkdir as QT,rm as e_,writeFile as t_}from"node:fs/promises";import{dirname as n_}from"node:path";var we=async(e,t)=>{await QT(n_(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${zT()}`;try{await t_(n,t,{flag:"wx",mode:384}),await he(n,e),await qT(e,384)}finally{await e_(n,{force:!0}).catch(()=>{})}};var s_="codex",i_="Codex app / CLI / IDE",c_="https://chatgpt.com/backend-api/codex",l_="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",d_="x-anyray-client-context-window",u_="x-anyray-client-auto-compact-limit",Lc=()=>process.env.CODEX_HOME?.trim()||Dc(r_(),".codex"),Jr=()=>Dc(Lc(),"config.toml"),Pc=()=>`${Jr()}.anyray-bak`,Op=()=>Dc(Lc(),"hooks.json"),On=()=>Dc(Lc(),"anyray.config.toml"),Xw=e=>Mo(e,"PostToolUse",rw),zw=(e,t=!1)=>fe({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||s_,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||i_}),nt=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Tp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,ws=(e,t={})=>{let n=zw(e,t.ignoreEnv),r=ee(e,"openai"),o=t.auth==="command"&&!r,a=r?"openai":t.ignoreEnv?void 0:process.env.ANYRAY_CODEX_PROVIDER?.trim(),s=t.ignoreEnv?void 0:Tp(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${nt(c_)}`,`"x-anyray-forward-headers" = ${nt(l_)}`,...i?[`"x-anyray-api-key" = ${nt(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${nt(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${nt(n)}`),a&&c.push(`"x-anyray-provider" = ${nt(a)}`),t.modelContextWindow&&c.push(`"${d_}" = ${nt(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${u_}" = ${nt(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 = ${nt(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${nt(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${nt(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>nt(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${nt(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(nt).join(", ")}]`]:[]]},p_=()=>Tp()?["model_provider","model"]:["model_provider"],qw={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=Lc(),t=await x(e);return{installed:t,detail:t?Jr():`no ${e} directory`}},async apply(e,t){let n=Jr(),r=Op(),o=zw(e),a=ee(e,"openai"),s=Tp(),i=ne(),c={},l=await x(r);try{l&&(c=await M(r))}catch(k){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${k instanceof Error?k.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run Connect so the retired Anyray PostToolUse entry can be removed safely.`]}}let d=Xw(c),u=await x(n),f=u?await gs(n,"utf-8"):"";if(Ip(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=Ip(f,"mcp_servers.anyray"),m=Rp(f,"model_context_window"),h=Rp(f,"model_auto_compact_token_limit"),g=[`${n} \u2190 always-on default route (model_provider = anyray)`,`Base URL: ${e.openaiBaseUrl}/responses (wire_api = responses)`,"Plain `codex` now routes through the gateway \u2014 no --profile needed.","Codex app, CLI, and IDE extension share this config.toml route.",a?"Subscription mode: Codex keeps your ChatGPT sign-in; its OAuth token passes through the gateway to the ChatGPT backend (never stored). Requires being signed in with ChatGPT, not an API key.":`Auth: ${e.clientKey?"personal gateway key (written to the config, not shown here)":"placeholder token (gateway swaps in the server-held key)"}`,s?`Model: ${s} (pinned via ANYRAY_CODEX_MODEL)`:"Model: inherits your existing default. If the desktop or IDE model picker ignores custom providers, re-run with ANYRAY_CODEX_MODEL pinned.",h?`Context budget: follows model_auto_compact_token_limit=${h}.`:m?`Context budget: follows model_context_window=${m}.`:"Context budget: follows the request model; unknown models use the safe fallback.",`Attribution: ${o??"(none \u2014 pass --user)"}`,"Codex cloud/web tasks run on OpenAI infrastructure and cannot route through a local gateway."];if(t.dryRun)return g.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:g};let y=[];d?(await J(r,c,{backup:!1}),await ce(r),y.push(r),g.push(`Removed the retired Anyray Codex PostToolUse hook from ${r}; Codex does not expose a safe pre-transcript replacement seam for side-effecting tools.`)):g.push("Codex source-side tool-output trimming is not installed because its blocking PostToolUse result can turn a completed side effect into an apparent failure."),u&&!await x(Pc())&&(await a_(n,Pc()),await o_(Pc(),384),g.push(`Backed up your original config to ${Pc()}.`));let w=i&&!p?Ge("profile"):void 0;g.push(p?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:w?"Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.":`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${_e()}). Re-run via the installer or a global install to enable retrieval.`);let b=Tc(f,ws(e,{mcpServer:w,modelContextWindow:m,modelAutoCompactTokenLimit:h}),p_());return await we(n,b),y.push(n),await x(On())&&(await Jw(On(),{force:!0}),y.push(On()),g.push(`Removed the old opt-in profile ${On()} (the default route replaces it).`)),{status:"configured",messages:g,changedFiles:y}},async pointsAt(e){let t=Jr();if(!await x(t))return!1;try{let n=await gs(t,"utf-8"),r=`base_url = ${nt(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Jr();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await gs(e,"utf-8");if(!Zw(t,"mcp_servers.anyray"))return{registered:!1,command:null,reason:"absent"};let n=t.match(/\[mcp_servers\.anyray\]\r?\ncommand = ("(?:[^"\\]|\\.)*")/),r=null;if(n)try{r=JSON.parse(n[1])}catch{r=null}return{registered:!0,command:r}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async inferenceAuthLanes(){try{let e=await gs(Jr(),"utf-8"),t=xp(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 x(t),r=await x(On()),o=await x(Op());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=Op(),c;try{c=await M(i)}catch(l){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${i} (${l instanceof Error?l.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run --revert.`]}}Xw(c)&&(e.dryRun||(await J(i,c,{backup:!1}),await ce(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=_c(await gs(t,"utf-8"));i!==null&&(e.dryRun||await we(t,i),s.push(t),a.push(e.dryRun?`would remove the Anyray default route from ${t}`:`removed the Anyray default route from ${t}`))}return r&&(e.dryRun||await Jw(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 ce(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as w_}from"node:os";import{join as b_}from"node:path";import{readFile as nb,rm as Pp}from"node:fs/promises";import{readFile as f_,writeFile as Qw,access as m_}from"node:fs/promises";import{homedir as h_}from"node:os";import{join as _p}from"node:path";var y_="# >>> anyray connect >>>",g_="# <<< anyray connect <<<",bs=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:y_,end:g_},wt=()=>{let e=h_(),t=process.env.SHELL||"";return t.includes("zsh")?_p(e,".zshrc"):t.includes("bash")?_p(e,".bashrc"):_p(e,".profile")},Nc=async e=>{try{return await m_(e),await f_(e,"utf-8")}catch{return""}},eb=(e,t)=>{let{begin:n,end:r}=bs(t),o=e.indexOf(n);if(o===-1)return e;let a=e.indexOf(r,o+n.length);if(a===-1)return e;let s=o;for(;s>0&&e[s-1]===`
|
|
59
59
|
`;)s-=1;let i=a+r.length;return e[i]===`
|
|
60
|
-
`&&(i+=1),e.slice(0,s)+e.slice(i)},$c=async(e,t,n)=>{let r=await Nc(e),{begin:o,end:a}=bs(n),s=
|
|
60
|
+
`&&(i+=1),e.slice(0,s)+e.slice(i)},$c=async(e,t,n)=>{let r=await Nc(e),{begin:o,end:a}=bs(n),s=eb(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
|
|
61
61
|
`),c=s?`${s}
|
|
62
62
|
|
|
63
63
|
${i}
|
|
64
64
|
`:`${i}
|
|
65
|
-
`;return await
|
|
66
|
-
`).filter(c=>c.trim().length>0)},
|
|
67
|
-
`),!0):!1};var Pt=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,"'\\''")}'`,
|
|
68
|
-
`)):g&&w&&await
|
|
65
|
+
`;return await Qw(e,c),e},Mc=async(e,t)=>{let n=await Nc(e),{begin:r,end:o}=bs(t),a=n.indexOf(r);if(a===-1)return;let s=a+r.length,i=n.indexOf(o,s);if(i!==-1)return n.slice(s,i).split(`
|
|
66
|
+
`).filter(c=>c.trim().length>0)},tb=async(e,t)=>(await Nc(e)).includes(bs(t).begin),As=async(e,t)=>{let n=await Nc(e);return n.includes(bs(t).begin)?(await Qw(e,eb(n,t).replace(/\s*$/,"")+`
|
|
67
|
+
`),!0):!1};var Pt=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var Se=e=>`'${e.replace(/'/g,"'\\''")}'`,A_=e=>{let t=Se(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},rb=(e,t,n,r)=>[`export OPENAI_BASE_URL=${Se(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${Se(t)}`],`export ANTHROPIC_BASE_URL=${Se(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${Se(t)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]],C_=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],k_=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],Dp=()=>b_(w_(),".anyray","shell-env.sh"),ab="# Managed by anyray-connect. Do not source this file anywhere else.",ob=e=>e.split(/\r?\n/,1)[0]===ab,Lp=e=>k_.some(t=>e.startsWith(`export ${t}=`)),Bc=(e,t=process.env)=>t.ANTHROPIC_BASE_URL===e.anthropicBaseUrl||t.OPENAI_BASE_URL===e.openaiBaseUrl?C_.filter(r=>(t[r]??"")!==""):[],sb={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=wt();return{installed:!0,detail:await x(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await Mc(wt());return e?e.some(n=>Lp(n)||n.includes(Dp()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=wt(),r=ee(e,"openai"),o=ee(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=rb(e,s,r,o),c=i.filter(Lp),l=i.filter(b=>!Lp(b)),d=Dp(),u=tw(),f=[A_(u),...l,...c.length>0?[`[ -r ${Se(d)} ] && . ${Se(d)}`]:[]],p=e.clientKey?rb(e,Pt(e.clientKey),r,o):i,m=r&&o?"either family":r?"OpenAI":"Anthropic",h=[`${n} \u2190 managed Anyray block`,` ${u} added to PATH (so \`anyray-connect\` runs from a new shell)`,...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 ${m} \u2014 your seat-based tool keeps`,"its own sign-in (a placeholder here would override it). Raw SDK/script","calls on a seat need your own key."]:["Note: standard SDK env vars carry no per-user header, so attribution","for these falls back to the gateway default."]],g=await x(d),y=g?await nb(d,"utf8"):void 0,w=y===void 0||ob(y);if(c.length>0&&!w)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(w||h.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:h};try{c.length>0?await we(d,[ab,...c,""].join(`
|
|
68
|
+
`)):g&&w&&await Pp(d,{force:!0}),await $c(n,f)}catch(b){try{y!==void 0&&w?await we(d,y):w&&await Pp(d,{force:!0})}catch{throw new Error("shell environment update failed and credential rollback could not be completed")}throw b}return{status:"configured",messages:h,changedFiles:[n,...c.length>0||g&&w?[d]:[]]}},async revert(e){let t=wt(),n=Dp(),r=await x(n),o=r?ob(await nb(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 As(t);o&&await Pp(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 aP}from"node:child_process";import{closeSync as sP,copyFileSync as iP,existsSync as Ce,mkdirSync as cP,openSync as lP,readFileSync as Bb,readSync as dP,renameSync as uP,rmSync as sn,writeFileSync as Yp}from"node:fs";import{homedir as Fb,platform as pP}from"node:os";import{dirname as Wb,join as jo,resolve as fP}from"node:path";import{isIP as Hp}from"node:net";import{homedir as v_,platform as S_}from"node:os";import{join as Fc}from"node:path";var Le=e=>{let t=v_();switch(S_()){case"darwin":return Fc(t,"Library","Application Support",e);case"win32":return Fc(process.env.APPDATA??Fc(t,"AppData","Roaming"),e);default:return Fc(t,".config",e)}};import{execFileSync as Hc}from"node:child_process";import{mkdtempSync as E_,rmSync as I_,writeFileSync as x_}from"node:fs";import{createRequire as R_}from"node:module";import{tmpdir as O_}from"node:os";import{join as ib}from"node:path";var Cs=class extends Error{},ks=e=>e instanceof Cs?`: ${e.message}`:"",cb=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new Cs("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new Cs(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},lb=()=>{try{return Hc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},$p=64*1024*1024,T_=$p*2+64,Uc=e=>`'${e.replace(/'/g,"''")}'`,__=(e,t)=>Hc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:T_,stdio:["ignore","pipe","pipe"]}),P_=(e,t)=>Hc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:$p,stdio:["pipe","pipe","pipe"]}),db=(e,t,n=__)=>{let r=Uc(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
|
|
69
69
|
`)?a.slice(0,-2):a.endsWith(`
|
|
70
|
-
`)?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")},
|
|
70
|
+
`)?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")},ub=(e,t=P_)=>{let r=t(e,`.bail on
|
|
71
71
|
.timeout 5000
|
|
72
72
|
PRAGMA wal_checkpoint(TRUNCATE);
|
|
73
|
-
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");
|
|
74
|
-
`);Hc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer
|
|
75
|
-
`,{mode:384}),await he(n,t)},
|
|
76
|
-
`),
|
|
77
|
-
`,{encoding:"utf-8",flag:"wx",mode:384})},
|
|
78
|
-
`,{encoding:"utf-8",flag:"wx",mode:384});try{lP(n,e)}catch(r){throw sn(n,{force:!0}),r}},RP=(e,t)=>{let n=Go(e);Gb(e,{...n,lastWritten:t})},se=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Lb=e=>se(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Go=e=>{let t=$b(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(se(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||se(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(!se(n)||n.version!==1||!se(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Ve],o=n.rows[ot];if(!Lb(r)||!Lb(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}},Nb=e=>{let t=Buffer.alloc(16),n=iP(e,"r");try{return cP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{oP(n)}},OP=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return se(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Vb=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(".")&&Up(t)===0||t==="0.0.0.0")return!0;if(Up(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(Up(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 Vb(`${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},Kb=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Vb(t.hostname)}catch{return!1}},TP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${Wb}`}catch{}return{...e,openaiBaseUrl:t}},Vo=["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."],Gp=()=>{let e=mr();if(!Ce(e))return"clear";let t=lr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ve)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return se(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},_P=(e,t)=>{if(!Kb(e))return{routed:!1,problem:"gateway-not-public-https"};let n=mr();if(!Ce(n))return{routed:!1,problem:"state-db-missing"};let r=lr();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Ve),a=r.readItem(n,ot)}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(!se(s))return{routed:!1,problem:"settings-malformed"};let i=`${Gt(e)}/v1${Wb}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!be(a)||!be(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},PP=()=>{let e=mr();if(!Ce(e))return"unverifiable";let t=lr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ve)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!se(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},DP=(e,t=[])=>({command:Ot(e,[...t,qc])}),Jp=(e,t,n)=>{if(!se(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Ot(t,[...n,qc])||r===Ot(t,n)||r.endsWith(` ${qc}`)&&r.includes(` ${t} `)},LP=(e,t)=>se(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),jb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Jp(a,t,n)){r=!0;continue}if(!se(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!LP(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}},Xp=(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},Zb=(e,t,n,r,o)=>se(e.hooks)&&Xp(e.hooks,t).some(a=>se(a)&&a.matcher===o&&Jp(a,n,r)),NP=(e,t,n,r,o)=>se(e.hooks)&&Xp(e.hooks,t).some(a=>se(a)&&a.matcher===o&&Jp(a,n,r)&&ic(a.command,n,[...r,qc])),Yb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!se(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=se(e.hooks)?{...e.hooks}:{},{entries:s}=jb(Xp(a,t),n,r);return s.push({...DP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},$P=(e,t,n,r=[])=>{if(!se(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=jb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},MP=async()=>{let e=cn();if(!ne()){let t=await Xb();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${_e()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await M(e);for(let n of zr)t=Yb(t,n.event,n.flag,n.trailingArgs,n.matcher);return await J(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}}},zc=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,Hb]}},Vp=e=>se(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===zc().command&&e.args.length===zc().args.length&&e.args.every((t,n)=>t===zc().args[n]),BP=e=>{if(!se(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")||et(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!et(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=>se(e)&&Array.isArray(e.args)&&e.args.at(-1)===Hb||BP(e),FP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,WP=async()=>{if(!ne())return Jb();let e=ln();try{let t=await M(e);if(t.mcpServers!==void 0&&!se(t.mcpServers))throw new Error("mcpServers is not an object");let n=se(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]=zc(),await J(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}}},Jb=async()=>{let e=ln();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!se(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 J(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}}},Xb=async()=>{let e=cn();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e),n=t;for(let r of zr)n=$P(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await J(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}}},UP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=hP(e);if(!n)return t;let r=jo(n,Is),o=mP();try{if(Ce(r)){let a=$b(r,"utf8");if(a===o)return t;if(!a.includes(Ub))return{...t,messages:[`Left ${Is} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Yp}"`]}}return sP(Bb(r),{recursive:!0}),Zp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Is} so Cursor agents in this repo default to Anyray's tools (that is what produces gateway traces \u2014 Cursor's built-in search and read never reach Anyray). Commit it to share with the team.`],complete:!0}}catch{return{...t,messages:[`Could not write ${Is} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},zb=async()=>{let e=await MP(),t=await WP(),n=await UP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Kp=async()=>{let e=await Xb(),t=await Jb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},qb=async()=>{if(!ne()){let e=await Kp();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${_e()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await M(cn());for(let r of zr)e=Yb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(ln());if(t.mcpServers!==void 0&&!se(t.mcpServers))throw new Error("mcpServers is not an object");let n=se(t.mcpServers)?t.mcpServers[Dt]:void 0;return n!==void 0&&!Qc(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${ln()} 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 ${cn()} and ${ln()}, then re-run Connect.`],complete:!1}}},HP=async()=>{if(!ne())return!1;try{let e=await M(cn());if(!se(e.hooks)||!zr.every(r=>Zb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(ln()),n=se(t.mcpServers)?t.mcpServers[Dt]:void 0;return Vp(n)}catch{return!1}},Qb=["openAIBaseUrl","useOpenAIKey"],Rs=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!se(t))throw new Error("Cursor application-user settings are not an object");return t},GP=(e,t,n)=>{let r=Rs(e),o=Rs(t??void 0),a=n===void 0?void 0:Rs(n),s={...r},i=[];for(let c of Qb){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:Ve}:{key:Ve,value:JSON.stringify(s)},conflicts:i}},Hp=(e,t)=>{let n=Rs(e),r=Rs(t??void 0),o={...n};for(let a of Qb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Ve}:{key:Ve,value:JSON.stringify(o)}},Yc=e=>typeof e=="string"&&e.startsWith("ark_"),Jc=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);se(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}},rt=(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.",...Vo];let n=fe(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.",...Vo]},jp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ne())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await Ss("cursor",e)}catch{return n}return{status:"queued",messages:[`Cursor is running \u2014 ${o} queued. It completes automatically the next time Cursor fully quits; relaunch Cursor afterwards to pick it up.`,a.alreadyWatching?"A queue watcher was already waiting; it will run the latest queued operation.":a.watcherPid?"A background watcher is now waiting for Cursor to quit.":"The queue was saved, but a background watcher could not be started; the next Connect run will service it.",...r]}},VP=async(e,t)=>{if(!be(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 ur("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 qb();if(!n.complete)return{status:"manual",messages:n.messages};let r=Ce(xs())||Ce(Ko());if(r&&Xc())return jp("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=Gp();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Ce(Ko())?Ko():xs()}, 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 ${cn()}, and register the Anyray retrieval MCP server in ${ln()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Os.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 zb(),s=[];if(!t.preservePendingOp)try{await ur("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 -- "${Yp}" (connect already writes ${Is} when run inside a repo, which covers that repo once committed; see docs/integrations/cursor.md).`,"Restart Cursor so its MCP registration is loaded; hooks.json itself is watched and reloads automatically."]}},Os={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>Xc(),quitTarget:pP,needsTarget:e=>e!=="revert",async complete(e,t,n){return fP(e)?e!=="revert"&&t?Os.apply(t,n):Os.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=Ce(e);return{installed:t,detail:t?mr():"Cursor user dir not found"}},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=ln();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await M(e),n=se(t.mcpServers)?t.mcpServers[Dt]:void 0;return Vp(n)?{registered:!0,command:FP(n)}:{registered:!1,command:null,reason:n===void 0?"absent":"foreign"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=cn();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!se(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=>Zb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=zr.every(c=>NP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=ln();if(!await x(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!se(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Dt];r=i===void 0?"missing":Qc(i)?"owned":"foreign",r==="owned"&&(o=Vp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Fr()?"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(yP(e))return VP(e,t);let n=TP(e),r=mr(),o=xs(),a=Ko();if(!be(e.clientKey))return{status:"manual",messages:rt(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let s={changedFiles:[],messages:[],complete:!0},i=h=>{let w=h.status==="configured"&&!s.complete;return{...h,status:w?"manual":h.status,changedFiles:[...h.changedFiles??[],...s.changedFiles],messages:[...h.messages,...s.messages,...w?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Kb(n.openaiBaseUrl))return i({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach private or LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect.",...Vo]});let c=await qb();if(!c.complete)return{status:"manual",messages:c.messages};let l=lr();if(!l)return i({status:"manual",messages:rt(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Ce(r))return i({status:"manual",messages:rt(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Ce(a)){if(Ce(o))return i({status:"manual",messages:rt(n,`Both a legacy Cursor Anyray backup (${a}) and a current value backup (${o}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{Nb(a)?d="sqlite":(Go(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:rt(n,`Legacy Cursor Anyray backup at ${a} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let f;if(Ce(o))try{f=Go(o)}catch{return i({status:"manual",messages:rt(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(Xc())return i(await jp("apply",t,{status:"manual",messages:rt(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Vo,...d?[`The legacy Anyray backup at ${a} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...d?[`Would migrate the legacy Anyray backup at ${a}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${r}, ${Ce(o)?`retain the original value backup at ${o}`:`create a mode-0600 value backup at ${o}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${cn()}, and register the Anyray retrieval MCP server in ${ln()}.`,...Vo]};if(d){try{l.checkpointWal(r)}catch(w){return i({status:"manual",messages:rt(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${ks(w)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let h;try{if(d==="sqlite")h=Jc(l.readItem(a,Ve)??null,l.readItem(a,ot)??null);else{let w=Go(a);h=Jc(w.applicationUser,w.openAIKey)}}catch{return i({status:"manual",messages:rt(n,`Couldn't read the legacy Anyray backup at ${a} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{l.mutateRows(r,[Hp(l.readItem(r,Ve),h.applicationUser),h.openAIKey===null?{key:ot}:{key:ot,value:h.openAIKey}])}catch{return i({status:"manual",messages:rt(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${a} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{sn(a,{force:!0}),sn(`${a}-wal`,{force:!0}),sn(`${a}-shm`,{force:!0}),u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held and removed it.`}catch{u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{l.checkpointWal(r)}catch(h){return i({status:"manual",messages:rt(n,`Couldn't checkpoint Cursor's state DB at ${r}${ks(h)} \u2014 refusing to write; set it by hand:`)})}let p;try{p=l.readItem(r,Ve)}catch{return i({status:"manual",messages:rt(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=OP(p,n);if(!m)return i({status:"manual",messages:rt(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let y={applicationUser:m.value,openAIKey:e.clientKey};if(Ce(o))try{RP(o,y)}catch{return i({status:"manual",messages:rt(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{xP(l,o,r,y)}catch{return i({status:"manual",messages:rt(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:Ve,value:m.value},{key:ot,value:e.clientKey}])}catch{let h=!0;if(f)try{Gb(o,f)}catch{h=!1}return i({status:"manual",messages:[h?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${o}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${o} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}s=await zb();let g=[];if(!t.preservePendingOp)try{await ur("cursor")}catch{g.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return i({status:"configured",changedFiles:[r],messages:[...u?[u]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${o}).`,"Stored the API key in Cursor's credential row (not shown here).",...g,...Vo,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await P().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Ce(xs())||Ce(Ko())||Gp()!=="clear"?!1:HP():_P(e,n).routed},async routingOverrides(){return Gp()!=="active"?[]:PP()!=="none"?[]:[{problem:"no custom model is registered against Cursor\u2019s API-key lane, so every model in the picker still runs on Cursor-hosted inference and no request reaches the gateway",fix:"Cursor \u2192 Settings \u2192 Models: add a custom model named `anyray-default` (or an admin-registered alias) and enable it, quit Cursor fully, reopen, then select it in Ask, Plan, or Agent.",repairable:!1}]},async revert(e){let t=mr(),n=xs(),r=Ko(),o=Ce(n),a=Ce(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${cn()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${cn()} and unregister its owned retrieval MCP server.`]};if((o||a)&&Xc()){if(e.fullRevert){let m=await Kp(),y=!0;try{await ur("cursor")}catch{y=!1}return{status:"manual",changedFiles:m.changedFiles,messages:[...m.messages,...y?[]:["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 jp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=lr(),i=!1,c=!1,l,d=[];if(a)try{if(Nb(r))if(Ce(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let m=Jc(s.readItem(r,Ve)??null,s.readItem(r,ot)??null);s.mutateRows(t,[Hp(s.readItem(t,Ve),m.applicationUser),m.openAIKey===null?{key:ot}:{key:ot,value:m.openAIKey}]),c=!0}else i=!0,aP(r,t),sn(`${t}-wal`,{force:!0}),sn(`${t}-shm`,{force:!0});else{let m=Go(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ce(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let y=Jc(m.applicationUser,m.openAIKey);s.mutateRows(t,[Hp(s.readItem(t,Ve),y.applicationUser),y.openAIKey===null?{key:ot}:{key:ot,value:y.openAIKey}]),c=!0}}catch(m){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${ks(m)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Go(n)}catch{return{status:"manual",messages:[`Couldn't read a supported Cursor value backup from ${n}; the backup was retained.`]}}if(l){if(!l.lastWritten)return{status:"manual",messages:[`The Cursor backup at ${n} predates three-way ownership, so Connect cannot prove which current values are still its own. The backup was retained and no hook or MCP cleanup was attempted.`]};if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ce(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let m=GP(s.readItem(t,Ve),l.applicationUser,l.lastWritten?.applicationUser);d.push(...m.conflicts);let y=[m.mutation],g=s.readItem(t,ot);l.lastWritten&&g===l.lastWritten.openAIKey?y.push(l.openAIKey===null?{key:ot}:{key:ot,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,y)}catch(m){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${ks(m)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{sn(r,{force:!0}),sn(`${r}-wal`,{force:!0}),sn(`${r}-shm`,{force:!0}),sn(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 ur("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await Kp();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 ZD,mkdir as YD,readFile as MA,rm as JD,writeFile as XD}from"node:fs/promises";import{randomUUID as zD}from"node:crypto";import{dirname as qD,join as BA}from"node:path";import{constants as ZP,chmod as YP,copyFile as JP,readFile as eA}from"node:fs/promises";import{applyEdits as XP,modify as zP}from"jsonc-parser";var KP=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]!==`
|
|
79
|
-
`;)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},
|
|
80
|
-
`,r=n.trim()?bt(n):{};if(!el(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},
|
|
73
|
+
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");cb(o?.slice(1).map(Number))},D_=(e,t)=>{let n=E_(ib(O_(),"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=${Uc(a.key)};`;let i=ib(n,`value-${s}`);return x_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${Uc(a.key)}, CAST(readfile(${Uc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
|
|
74
|
+
`);Hc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:$p,stdio:["pipe","ignore","pipe"]})}finally{try{I_(n,{recursive:!0,force:!0})}catch{}}},L_={kind:"sqlite3-cli",readItem:(e,t)=>db(e,t),checkpointWal:e=>ub(e),mutateRows:D_},N_=()=>{try{let t=R_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Np=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},$_=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),M_=e=>({kind:"node-sqlite",readItem:(t,n)=>Np(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:$_(o.value)}),checkpointWal:t=>Np(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);cb(o)}),mutateRows:(t,n)=>Np(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}})}),Wc,lr=()=>{if(Wc!==void 0)return Wc;let e=N_();return Wc=e?M_(e):lb()?L_:null,Wc};import{spawn as B_}from"node:child_process";import{randomUUID as pb}from"node:crypto";import{constants as fb}from"node:fs";import{chmod as F_,copyFile as mb,mkdir as W_,readdir as U_,readFile as H_,rename as G_,rm as vs,writeFile as V_}from"node:fs/promises";import{join as Mp}from"node:path";var Bp=/^[a-z0-9][a-z0-9-]{0,31}$/,K_=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,hb=/^[a-z0-9][a-z0-9-]{0,31}$/,j_=/^[0-9TZ:.+-]{1,40}$/,Fp=()=>Mp(Q(),"pending"),Vc=e=>{if(!Bp.test(e)||K_.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Mp(Fp(),`${e}.json`)},yb=()=>Mp(Q(),"cursor-pending.json"),Z_=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Y_=(e,t)=>{if(!Z_(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Bp.test(n)||typeof e.op!="string"||!hb.test(e.op)||typeof e.requestedAt!="string"||!j_.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}:{}}},Wp=async(e,t)=>{try{return Y_(JSON.parse(await H_(e,"utf-8")),t)}catch{return}},gb=async()=>{let e=yb(),t=await Wp(e,"cursor");if(!t)return;let n=!1;try{await wb(),await mb(e,Vc("cursor"),fb.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await vs(e,{force:!0})}catch{}return t},Kc=async e=>{let t=await Wp(Vc(e),e);return t||(e==="cursor"?gb():void 0)},dr=async()=>{let e;try{e=await U_(Fp())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Bp.test(r))continue;let o=await Kc(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await gb();n&&t.push(n)}return t},wb=async()=>{await Qe();let e=Fp();await W_(e,{recursive:!0,mode:448});try{await F_(e,448)}catch{}},Gc=async e=>{await wb();let t=Vc(e.adapter),n=`${t}.${process.pid}.tmp`;await V_(n,`${JSON.stringify(e)}
|
|
75
|
+
`,{mode:384}),await he(n,t)},J_=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,ur=async(e,t)=>await Up(e,t)==="claimed",Up=async(e,t)=>{let n=Vc(e);if(t){let o=`${n}.${process.pid}.${pb()}.claimed`;try{await G_(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Wp(o,e);if(a&&J_(a,t))return await vs(o,{force:!0}),"claimed";let s=!1;try{await mb(o,n,fb.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await vs(o,{force:!0})}return"superseded"}let r=!1;try{await vs(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await vs(yb(),{force:!0})}catch{}return r?"claimed":"absent"},pr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},X_=e=>{let{command:t,args:n}=or("__anyray-quit-watch");return{exe:t,args:[...n,e]}},z_=e=>{let{exe:t,args:n}=X_(e),r=B_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},bb=z_;var Ab=async()=>{let e=[],t;try{t=await dr()}catch{return e}for(let n of t)if(!pr(n.watcherPid))try{let r=bb(n.adapter);if(!r)continue;await Gc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},Ss=async(e,t)=>{if(!hb.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await Kc(e),r=new Date().toISOString(),o=pb();if(n&&pr(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=bb(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 q_,spawnSync as kb}from"node:child_process";import{existsSync as jc}from"node:fs";import{homedir as Q_,platform as fr}from"node:os";import{join as vb,win32 as Cb}from"node:path";var Sb=(e,t={})=>{let n=t.env??process.env,r=t.exists??jc,o=(t.home??Q_)(),a={localAppData:n.LOCALAPPDATA??Cb.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=Cb.join(i,s.path);if(r(c))return c}},Xr=/^[A-Za-z0-9 ._-]{1,64}$/,eP=/^[A-Za-z0-9.-]{1,128}$/,Zc=e=>e.darwinBundleId&&eP.test(e.darwinBundleId)?e.darwinBundleId:void 0,Eb=(e,t=fr())=>t==="darwin"?Zc(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",Ib=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",xb=(e,t=fr(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return Sb(e,r)!==void 0;let o=e.linuxProcess;return!o||!Xr.test(o)?!1:n.split(":").filter(Boolean).some(a=>jc(vb(a,o)))},Rb=(e,t=fr())=>{if(t==="darwin"&&Zc(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Xr.test(n))},Ob=1e4,Es=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=vb(t,"System32",e);return jc(n)?n:e},tP=e=>{let t=`/usr/bin/${e}`;return jc(t)?t:e},nP=(e,t)=>{try{let n=kb(e,t,{encoding:"utf-8",timeout:Ob,windowsHide:!0,...fr()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:fr()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},rP=e=>new Promise(t=>setTimeout(t,e)),Tb=(e,t={})=>{let n=t.runtimePlatform??fr(),r=t.run??nP;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||!Xr.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||!Xr.test(a)?!1:r(Es("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Xr.test(o)?!1:r(tP("pkill"),["-TERM","-o","-x",o])},_b=async(e,t=2e4,n={})=>{let r=n.sleep??rP,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},oP=(e,t,n={})=>{let r=fr();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=kb(e,t,{stdio:"ignore",timeout:Ob,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=q_(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},Pb=(e,t={})=>{let n=t.runtimePlatform??fr(),r=t.launch??oP;if(n==="darwin"){let a=Zc(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Xr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=Sb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Xr.test(o)?!1:r(o,[])};var mP={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"}]},hP=e=>e==="apply"||e==="native"||e==="revert",Ub=()=>Le("Cursor"),mr=()=>jo(Ub(),"User","globalStorage","state.vscdb"),xs=()=>`${mr()}.anyray-bak.json`,Ko=()=>`${mr()}.anyray-bak`,Ve="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",ot="cursorAuth/openAIKey";var Hb="/seat/cursor",Jp="Prefer the anyray_search and anyray_read tools over the built-in codebase search and file read. anyray_search returns relevance-filtered matches; anyray_read returns the pertinent slice of a file plus a retrieve handle you can pass to anyray_retrieve to recover any elided detail. Use them when finding or reading code.",Is=jo(".cursor","rules","anyray.mdc"),Gb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",yP=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",Gb,"",Jp,""].join(`
|
|
76
|
+
`),gP=e=>{let t=fP(e);for(;;){if(Ce(jo(t,".git")))return t;let n=Wb(t);if(n===t)return null;t=n}},wP=e=>e.authMode!=="placeholder",cn=()=>jo(Fb(),".cursor","hooks.json"),ln=()=>jo(Fb(),".cursor","mcp.json"),Dt="anyray",Vb="--anyray-owner=cursor-v1",bP="postToolUse",AP="beforeSubmitPrompt",Db="preToolUse",CP="^MCP:",kP="UserPromptSubmit",vP="Shell",SP="^(Read|Grep)$",qc="--anyray-owner=cursor-hook-v1",zr=[{event:bP,flag:Ye,trailingArgs:["cursor"],matcher:CP},{event:AP,flag:qn,trailingArgs:[],matcher:kP},{event:Db,flag:ow,trailingArgs:[],matcher:vP},{event:Db,flag:aw,trailingArgs:[],matcher:SP}];var Lb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},EP=(e,t,n)=>aP(e,t,n),Nb=EP,IP,xP=()=>{let e=IP??pP();if(e==="win32"){let t=Nb(Es("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],Lb);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=Nb("pgrep",["-x",t],Lb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},RP=xP,Xc=()=>RP();var OP=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Ve)??null,openAIKey:e.readItem(n,ot)??null,lastWritten:r};Yp(t,`${JSON.stringify(o,null,2)}
|
|
77
|
+
`,{encoding:"utf-8",flag:"wx",mode:384})},Kb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Yp(n,`${JSON.stringify(t,null,2)}
|
|
78
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{uP(n,e)}catch(r){throw sn(n,{force:!0}),r}},TP=(e,t)=>{let n=Go(e);Kb(e,{...n,lastWritten:t})},se=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),$b=e=>se(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Go=e=>{let t=Bb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(se(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||se(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(!se(n)||n.version!==1||!se(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Ve],o=n.rows[ot];if(!$b(r)||!$b(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}},Mb=e=>{let t=Buffer.alloc(16),n=lP(e,"r");try{return dP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{sP(n)}},_P=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return se(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var jb=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(".")&&Hp(t)===0||t==="0.0.0.0")return!0;if(Hp(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(Hp(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 jb(`${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},Zb=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!jb(t.hostname)}catch{return!1}},PP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${Hb}`}catch{}return{...e,openaiBaseUrl:t}},Vo=["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."],Vp=()=>{let e=mr();if(!Ce(e))return"clear";let t=lr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ve)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return se(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},DP=(e,t)=>{if(!Zb(e))return{routed:!1,problem:"gateway-not-public-https"};let n=mr();if(!Ce(n))return{routed:!1,problem:"state-db-missing"};let r=lr();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Ve),a=r.readItem(n,ot)}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(!se(s))return{routed:!1,problem:"settings-malformed"};let i=`${Gt(e)}/v1${Hb}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!be(a)||!be(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},LP=()=>{let e=mr();if(!Ce(e))return"unverifiable";let t=lr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ve)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!se(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},NP=(e,t=[])=>({command:Ot(e,[...t,qc])}),Xp=(e,t,n)=>{if(!se(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Ot(t,[...n,qc])||r===Ot(t,n)||r.endsWith(` ${qc}`)&&r.includes(` ${t} `)},$P=(e,t)=>se(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Yb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Xp(a,t,n)){r=!0;continue}if(!se(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!$P(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}},zp=(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},Jb=(e,t,n,r,o)=>se(e.hooks)&&zp(e.hooks,t).some(a=>se(a)&&a.matcher===o&&Xp(a,n,r)),MP=(e,t,n,r,o)=>se(e.hooks)&&zp(e.hooks,t).some(a=>se(a)&&a.matcher===o&&Xp(a,n,r)&&ic(a.command,n,[...r,qc])),Xb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!se(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=se(e.hooks)?{...e.hooks}:{},{entries:s}=Yb(zp(a,t),n,r);return s.push({...NP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},BP=(e,t,n,r=[])=>{if(!se(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Yb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},FP=async()=>{let e=cn();if(!ne()){let t=await qb();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${_e()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await M(e);for(let n of zr)t=Xb(t,n.event,n.flag,n.trailingArgs,n.matcher);return await J(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}}},zc=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,Vb]}},Kp=e=>se(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===zc().command&&e.args.length===zc().args.length&&e.args.every((t,n)=>t===zc().args[n]),WP=e=>{if(!se(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")||et(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!et(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=>se(e)&&Array.isArray(e.args)&&e.args.at(-1)===Vb||WP(e),UP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,HP=async()=>{if(!ne())return zb();let e=ln();try{let t=await M(e);if(t.mcpServers!==void 0&&!se(t.mcpServers))throw new Error("mcpServers is not an object");let n=se(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]=zc(),await J(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}}},zb=async()=>{let e=ln();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!se(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 J(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}}},qb=async()=>{let e=cn();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e),n=t;for(let r of zr)n=BP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await J(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}}},GP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=gP(e);if(!n)return t;let r=jo(n,Is),o=yP();try{if(Ce(r)){let a=Bb(r,"utf8");if(a===o)return t;if(!a.includes(Gb))return{...t,messages:[`Left ${Is} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Jp}"`]}}return cP(Wb(r),{recursive:!0}),Yp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Is} so Cursor agents in this repo default to Anyray's tools (that is what produces gateway traces \u2014 Cursor's built-in search and read never reach Anyray). Commit it to share with the team.`],complete:!0}}catch{return{...t,messages:[`Could not write ${Is} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Qb=async()=>{let e=await FP(),t=await HP(),n=await GP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},jp=async()=>{let e=await qb(),t=await zb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},eA=async()=>{if(!ne()){let e=await jp();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${_e()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await M(cn());for(let r of zr)e=Xb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(ln());if(t.mcpServers!==void 0&&!se(t.mcpServers))throw new Error("mcpServers is not an object");let n=se(t.mcpServers)?t.mcpServers[Dt]:void 0;return n!==void 0&&!Qc(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${ln()} 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 ${cn()} and ${ln()}, then re-run Connect.`],complete:!1}}},VP=async()=>{if(!ne())return!1;try{let e=await M(cn());if(!se(e.hooks)||!zr.every(r=>Jb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(ln()),n=se(t.mcpServers)?t.mcpServers[Dt]:void 0;return Kp(n)}catch{return!1}},tA=["openAIBaseUrl","useOpenAIKey"],Rs=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!se(t))throw new Error("Cursor application-user settings are not an object");return t},KP=(e,t,n)=>{let r=Rs(e),o=Rs(t??void 0),a=n===void 0?void 0:Rs(n),s={...r},i=[];for(let c of tA){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:Ve}:{key:Ve,value:JSON.stringify(s)},conflicts:i}},Gp=(e,t)=>{let n=Rs(e),r=Rs(t??void 0),o={...n};for(let a of tA)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Ve}:{key:Ve,value:JSON.stringify(o)}},Yc=e=>typeof e=="string"&&e.startsWith("ark_"),Jc=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);se(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}},rt=(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.",...Vo];let n=fe(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.",...Vo]},Zp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ne())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await Ss("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]}},jP=async(e,t)=>{if(!be(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 ur("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 eA();if(!n.complete)return{status:"manual",messages:n.messages};let r=Ce(xs())||Ce(Ko());if(r&&Xc())return Zp("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=Vp();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Ce(Ko())?Ko():xs()}, 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 ${cn()}, and register the Anyray retrieval MCP server in ${ln()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Os.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 Qb(),s=[];if(!t.preservePendingOp)try{await ur("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 -- "${Jp}" (connect already writes ${Is} when run inside a repo, which covers that repo once committed; see docs/integrations/cursor.md).`,"Restart Cursor so its MCP registration is loaded; hooks.json itself is watched and reloads automatically."]}},Os={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>Xc(),quitTarget:mP,needsTarget:e=>e!=="revert",async complete(e,t,n){return hP(e)?e!=="revert"&&t?Os.apply(t,n):Os.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=Ub(),t=Ce(e);return{installed:t,detail:t?mr():"Cursor user dir not found"}},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=ln();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await M(e),n=se(t.mcpServers)?t.mcpServers[Dt]:void 0;return Kp(n)?{registered:!0,command:UP(n)}:{registered:!1,command:null,reason:n===void 0?"absent":"foreign"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=cn();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!se(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=>Jb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=zr.every(c=>MP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=ln();if(!await x(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!se(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Dt];r=i===void 0?"missing":Qc(i)?"owned":"foreign",r==="owned"&&(o=Kp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Fr()?"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(wP(e))return jP(e,t);let n=PP(e),r=mr(),o=xs(),a=Ko();if(!be(e.clientKey))return{status:"manual",messages:rt(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let s={changedFiles:[],messages:[],complete:!0},i=y=>{let w=y.status==="configured"&&!s.complete;return{...y,status:w?"manual":y.status,changedFiles:[...y.changedFiles??[],...s.changedFiles],messages:[...y.messages,...s.messages,...w?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Zb(n.openaiBaseUrl))return i({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach private or LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect.",...Vo]});let c=await eA();if(!c.complete)return{status:"manual",messages:c.messages};let l=lr();if(!l)return i({status:"manual",messages:rt(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Ce(r))return i({status:"manual",messages:rt(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Ce(a)){if(Ce(o))return i({status:"manual",messages:rt(n,`Both a legacy Cursor Anyray backup (${a}) and a current value backup (${o}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{Mb(a)?d="sqlite":(Go(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:rt(n,`Legacy Cursor Anyray backup at ${a} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let f;if(Ce(o))try{f=Go(o)}catch{return i({status:"manual",messages:rt(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(Xc())return i(await Zp("apply",t,{status:"manual",messages:rt(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Vo,...d?[`The legacy Anyray backup at ${a} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...d?[`Would migrate the legacy Anyray backup at ${a}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${r}, ${Ce(o)?`retain the original value backup at ${o}`:`create a mode-0600 value backup at ${o}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${cn()}, and register the Anyray retrieval MCP server in ${ln()}.`,...Vo]};if(d){try{l.checkpointWal(r)}catch(w){return i({status:"manual",messages:rt(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${ks(w)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=Jc(l.readItem(a,Ve)??null,l.readItem(a,ot)??null);else{let w=Go(a);y=Jc(w.applicationUser,w.openAIKey)}}catch{return i({status:"manual",messages:rt(n,`Couldn't read the legacy Anyray backup at ${a} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{l.mutateRows(r,[Gp(l.readItem(r,Ve),y.applicationUser),y.openAIKey===null?{key:ot}:{key:ot,value:y.openAIKey}])}catch{return i({status:"manual",messages:rt(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${a} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{sn(a,{force:!0}),sn(`${a}-wal`,{force:!0}),sn(`${a}-shm`,{force:!0}),u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held and removed it.`}catch{u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{l.checkpointWal(r)}catch(y){return i({status:"manual",messages:rt(n,`Couldn't checkpoint Cursor's state DB at ${r}${ks(y)} \u2014 refusing to write; set it by hand:`)})}let p;try{p=l.readItem(r,Ve)}catch{return i({status:"manual",messages:rt(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=_P(p,n);if(!m)return i({status:"manual",messages:rt(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let h={applicationUser:m.value,openAIKey:e.clientKey};if(Ce(o))try{TP(o,h)}catch{return i({status:"manual",messages:rt(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{OP(l,o,r,h)}catch{return i({status:"manual",messages:rt(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:Ve,value:m.value},{key:ot,value:e.clientKey}])}catch{let y=!0;if(f)try{Kb(o,f)}catch{y=!1}return i({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${o}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${o} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}s=await Qb();let g=[];if(!t.preservePendingOp)try{await ur("cursor")}catch{g.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return i({status:"configured",changedFiles:[r],messages:[...u?[u]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${o}).`,"Stored the API key in Cursor's credential row (not shown here).",...g,...Vo,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await P().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Ce(xs())||Ce(Ko())||Vp()!=="clear"?!1:VP():DP(e,n).routed},async routingOverrides(){return Vp()!=="active"?[]:LP()!=="none"?[]:[{problem:"no custom model is registered against Cursor\u2019s API-key lane, so every model in the picker still runs on Cursor-hosted inference and no request reaches the gateway",fix:"Cursor \u2192 Settings \u2192 Models: add a custom model named `anyray-default` (or an admin-registered alias) and enable it, quit Cursor fully, reopen, then select it in Ask, Plan, or Agent.",repairable:!1}]},async revert(e){let t=mr(),n=xs(),r=Ko(),o=Ce(n),a=Ce(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${cn()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${cn()} and unregister its owned retrieval MCP server.`]};if((o||a)&&Xc()){if(e.fullRevert){let m=await jp(),h=!0;try{await ur("cursor")}catch{h=!1}return{status:"manual",changedFiles:m.changedFiles,messages:[...m.messages,...h?[]:["Could not clear Cursor's stale queue marker."],`Cursor is running, so its saved settings in ${a?r:n} were left in place and nothing was queued. Quit Cursor and re-run --revert to restore them.`]}}return Zp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=lr(),i=!1,c=!1,l,d=[];if(a)try{if(Mb(r))if(Ce(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let m=Jc(s.readItem(r,Ve)??null,s.readItem(r,ot)??null);s.mutateRows(t,[Gp(s.readItem(t,Ve),m.applicationUser),m.openAIKey===null?{key:ot}:{key:ot,value:m.openAIKey}]),c=!0}else i=!0,iP(r,t),sn(`${t}-wal`,{force:!0}),sn(`${t}-shm`,{force:!0});else{let m=Go(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ce(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let h=Jc(m.applicationUser,m.openAIKey);s.mutateRows(t,[Gp(s.readItem(t,Ve),h.applicationUser),h.openAIKey===null?{key:ot}:{key:ot,value:h.openAIKey}]),c=!0}}catch(m){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${ks(m)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Go(n)}catch{return{status:"manual",messages:[`Couldn't read a supported Cursor value backup from ${n}; the backup was retained.`]}}if(l){if(!l.lastWritten)return{status:"manual",messages:[`The Cursor backup at ${n} predates three-way ownership, so Connect cannot prove which current values are still its own. The backup was retained and no hook or MCP cleanup was attempted.`]};if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ce(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let m=KP(s.readItem(t,Ve),l.applicationUser,l.lastWritten?.applicationUser);d.push(...m.conflicts);let h=[m.mutation],g=s.readItem(t,ot);l.lastWritten&&g===l.lastWritten.openAIKey?h.push(l.openAIKey===null?{key:ot}:{key:ot,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,h)}catch(m){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${ks(m)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{sn(r,{force:!0}),sn(`${r}-wal`,{force:!0}),sn(`${r}-shm`,{force:!0}),sn(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 ur("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await jp();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 JD,mkdir as XD,readFile as FA,rm as zD,writeFile as qD}from"node:fs/promises";import{randomUUID as QD}from"node:crypto";import{dirname as eL,join as WA}from"node:path";import{constants as JP,chmod as XP,copyFile as zP,readFile as nA}from"node:fs/promises";import{applyEdits as qP,modify as QP}from"jsonc-parser";var ZP=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]!==`
|
|
79
|
+
`;)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},YP=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},bt=e=>JSON.parse(YP(ZP(e)));var el=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ke=async e=>{let t=await x(e),n=t?await nA(e,"utf8"):`{}
|
|
80
|
+
`,r=n.trim()?bt(n):{};if(!el(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},rA=(e,t,n=[])=>{if(el(e)&&el(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...rA(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}]},dn=async(e,t,n,r)=>{let o=rA(t.data,n);if(o.length===0)return!1;if(r&&!await x(`${e}.anyray-bak`))if(t.existed)try{await zP(e,`${e}.anyray-bak`,JP.COPYFILE_EXCL),await XP(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await we(`${e}.anyray-bak`,`{}
|
|
81
81
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
82
82
|
`)?`\r
|
|
83
83
|
`:`
|
|
84
|
-
`},s=t.raw;for(let i of o)s=
|
|
84
|
+
`},s=t.raw;for(let i of o)s=qP(s,QP(s,i.path,i.value,{formattingOptions:a}));return await we(e,s.endsWith(`
|
|
85
85
|
`)?s:`${s}
|
|
86
|
-
`),!0},Zo=async e=>{try{let t=bt(await
|
|
87
|
-
`;)t+=1;continue}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);if(r===-1)return-1;t=r+2;continue}return n==="{"?t:-1}return-1},
|
|
86
|
+
`),!0},Zo=async e=>{try{let t=bt(await nA(`${e}.anyray-bak`,"utf8"));return el(t)?t:void 0}catch{return}};import{readFile as MD,writeFile as BD}from"node:fs/promises";import{dirname as FD,join as WD}from"node:path";import{mkdir as UD}from"node:fs/promises";var oA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eD=e=>{let t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t+=1;continue}if(n==="/"&&e[t+1]==="/"){for(;t<e.length&&e[t]!==`
|
|
87
|
+
`;)t+=1;continue}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);if(r===-1)return-1;t=r+2;continue}return n==="{"?t:-1}return-1},tD=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},nD=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},qp=(e,t,n)=>{let r;try{r=bt(e)}catch{return{ok:!1,reason:"unsupported"}}if(!oA(r))return{ok:!1,reason:"unsupported"};if(t in r)return{ok:!1,reason:"key-present"};let o=eD(e);if(o===-1)return{ok:!1,reason:"unsupported"};let a=tD(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=nD(e,o)?`
|
|
88
88
|
${a}${s}
|
|
89
89
|
`:`
|
|
90
|
-
${a}${s},`,d=`${i}${l}${c}`;try{let u=bt(d);if(!nA(u))return{ok:!1,reason:"unsupported"};for(let[f,p]of Object.entries(r))if(JSON.stringify(u[f])!==JSON.stringify(p))return{ok:!1,reason:"unsupported"};if(JSON.stringify(u[t])!==JSON.stringify(n))return{ok:!1,reason:"unsupported"}}catch{return{ok:!1,reason:"unsupported"}}return{ok:!0,text:d}};import{execFile as iD}from"node:child_process";import{readdirSync as cD,statSync as lD}from"node:fs";import{createHash as gA,randomBytes as dD,randomUUID as wA}from"node:crypto";import{chmod as uD,lstat as af,mkdir as sf,readdir as bA,readFile as pn,rm as AA,unlink as ol,writeFile as cf}from"node:fs/promises";import{homedir as zo,platform as lf}from"node:os";import{dirname as nf,join as At,posix as mA,win32 as pD}from"node:path";import{promisify as fD}from"node:util";var un="0.1.29";var hr="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",tl="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",rA="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfi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AAHAAcA1gEAAGdXAAAAAA==";import{readFile as sA}from"node:fs/promises";import{homedir as qr,platform as Yo}from"node:os";import{join as Tn,posix as tD,win32 as nD}from"node:path";var Qr=["Code","Code - Insiders","VSCodium"],qp="1.121.0",oA=1,rD=121,iA="1.102.0",aA=1,oD=102,aD={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},nl=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},Qp=e=>{let t=nl(e);return t?t.major!==oA?t.major>oA:t.minor>=rD:!1},cA=e=>{let t=nl(e);return t?t.major!==aA?t.major>aA:t.minor>=oD:!1},sD=async e=>{if(Yo()!=="darwin")return;let t=Tn("/Applications",`${aD[e]}.app`,"Contents","Resources","app","package.json");if(await x(t))try{let n=JSON.parse(await sA(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},rl=(e,t=Yo(),n=qr(),r=process.env)=>{switch(t){case"darwin":return Tn(n,"Library","Application Support",e);case"win32":return Tn(r.APPDATA??Tn(n,"AppData","Roaming"),e);default:return Tn(n,".config",e)}},ef=(e,t)=>e?t==="win32"?nD.join:tD.join:Tn,Jo=(e,t=!1,n=Yo(),r=qr(),o=process.env)=>t?ef(t,n)(r,Ts[e],"data","User"):Tn(rl(e,n,r,o),"User"),lA=async(e,t=!1,n=Yo(),r=qr(),o=process.env)=>{try{let a=ef(t,n)(Jo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await sA(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[]}},dA=async(e,t=Yo(),n=qr(),r=process.env)=>{let a=(await lA(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},uA=async(e,t=!1,n=Yo(),r=qr(),o=process.env)=>{let a=ef(t,n),s=Jo(e,t,n,r,o),i=await lA(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Xo=async()=>{for(let e of Qr)if(await x(rl(e)))return e},Ts={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},pA=(e,t=qr())=>Tn(t,Ts[e],"extensions"),tf=async(e=qr())=>{for(let t of Qr)if(await x(Tn(e,Ts[t])))return t},fA=async e=>{let t=e??await Xo();if(!t)return{status:"unknown"};let n=await sD(t);return n?{variant:t,version:n,status:Qp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var q="anyray.anyray-vscode",df="vscode-handoffs",CA="vscode-receipts",_s=2,mD=fD(iD),_n={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"]}},hD={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"}},yD=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),kA=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&yD(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ps=e=>{if(kA(e))try{return new URL(e.trim()).origin}catch{return}},gD=(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)},wD=e=>{try{return cD(e)}catch{return[]}},bD=e=>{try{return lD(e).mtimeMs}catch{return}},AD=(e,t,n,r,o)=>{if(!Hr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=_n[e].commands[0],s=At(t,Ts[e]),i=[];for(let{directory:c,suffix:l}of[{directory:At(s,"bin"),suffix:["bin","remote-cli"]},{directory:At(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=At(c,d,...l,a),f=o(u);f!==void 0&&i.push({path:u,mtime:f})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},CD=(e,t,n)=>{let{macAppName:r,commands:o}=_n[e],a=o[0],s=[];for(let i of["/Applications",mA.join(t,"Applications")])for(let c of n(i))gD(c,r)&&s.push(mA.join(i,c,"Contents/Resources/app/bin",a));return s},kD=(e,t=lf(),n=zo(),r=process.env,o=wD,a=bD)=>{let s=AD(e,n,r,o,a);if(t==="darwin")return[...new Set([..._n[e].commands,...CD(e,n,o),...s])];if(t!=="win32"){let u=_n[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=hD[e],c=pD.join,l=r.LOCALAPPDATA??c(n,"AppData","Local"),d=[c(l,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(u=>!!u);return[...new Set([...d.map(u=>c(u,i.directory,i.executable)),_n[e].commands[0],...s])]},vA={run:async(e,t)=>({stdout:(await mD(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>dD(24).toString("base64url"),home:"",commandCandidates:e=>kD(e)},eo=(e,t)=>At(e,".anyray",CA,`${t}.json`),uf=(e,t)=>At(e,".anyray",CA,`${t}.applied.json`),SA=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&nl(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},rf=async(e,t,n)=>{try{let r=await t.run(e,[...n===void 0?[]:["--profile",n],"--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===q.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===un}catch{return}},EA=async(e,t)=>{let n=await SA(e,t);if(n)return rf(n.command,t)},vD=async(e,t,n)=>{let r=At(e,".anyray",df);for(let o of n){if(!o.endsWith(".json"))continue;let a=At(r,o);try{if(!(await af(a)).isFile()||JSON.parse(await pn(a,"utf8")).variant!==t)continue;await ol(a)}catch{}}},SD=async(e,t)=>{let n=At(e,".anyray",df),r;try{r=await bA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=At(n,o);try{if(!(await af(a)).isFile()||JSON.parse(await pn(a,"utf8")).variant!==t)continue;await ol(a)}catch{}}},ED=async(e,t)=>{try{let n=JSON.parse(await pn(eo(e,t),"utf8"));return n.extensionVersion===un&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==hr}catch{return!1}},IA=250,ID=9e4,xD=ID/IA,RD=async(e,t,n,r)=>{for(let o=0;o<xD;o++){try{let a=JSON.parse(await pn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===_s&&a.action===n?"confirmed":a.extensionVersion!==un||a.extensionDistSha256!==hr?"reload-required":a.version===_s&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(IA)}return"timeout"},OD=200,hA=(e,t)=>{let n=e,r=[typeof n?.name=="string"&&n.name?n.name:"Error"];typeof n?.code=="number"?r.push(`exit ${n.code}`):typeof n?.code=="string"&&n.code&&r.push(n.code);let a=(typeof n?.stderr=="string"?n.stderr:"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0);if(a){let s=a;t&&(s=s.replaceAll(t,"<nonce>")),s=s.replace(/\b(ark_|sk-|adt_|enl_)[A-Za-z0-9_-]+/g,"$1\u2026"),r.push(s.slice(0,OD))}return r.join(": ")},TD=async e=>{try{let t=await af(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},yA=e=>gA("sha256").update(e).digest("hex"),_D=async(e=zo())=>{let t=Buffer.from(rA,"base64");if(t.length<4||t[0]!==80||t[1]!==75||yA(t)!==tl)throw new Error("bundled VS Code extension failed integrity validation");let n=At(e,".anyray","vscode-extension"),r=At(n,`anyray-vscode-${un}-${tl.slice(0,12)}.vsix`);try{if(yA(await pn(r))===tl)return r}catch{}await sf(n,{recursive:!0,mode:448});let o=`${r}.${wA()}.tmp`;try{await cf(o,t,{mode:384}),await he(o,r),lf()!=="win32"&&await uD(r,384)}finally{await AA(o,{force:!0})}return r},of=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=>of(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${of(t[n])}`).join(",")}}`},xA=(e,t,n)=>gA("sha256").update(of({gatewayUrl:Ps(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:un,extensionDistSha256:hr,profiles:[...n].sort()})).digest("hex"),PD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await pn(uf(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==xA(t,n,r))return!1;let i=JSON.parse(await pn(eo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===un&&i.extensionDistSha256===hr&&i.gatewayUrl===Ps(t.origin)?await EA(e,a)===!0:!1},DD=async(e,t,n,r)=>{let o=uf(e,t),a=`${o}.${wA()}.tmp`;try{await sf(nf(o),{recursive:!0,mode:448}),await cf(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
91
|
-
`,{mode:384}),await he(a,o)}catch{}finally{await
|
|
92
|
-
`,{mode:384}),await
|
|
93
|
-
`,{flag:"wx",mode:384}),await he(n,e),await ZD(e,384)}finally{await JD(n,{force:!0}).catch(()=>{})}},ff=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!==yr||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!==UA(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}})},mf=e=>{let t=e.filter(n=>!ff(n));return{next:t,removed:t.length!==e.length}},tL=async(e,t)=>{let n=Ns(e),r=await cl(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 "${yr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=mf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${yr}" Custom Endpoint from ${n}.`]};try{return await HA(n,o),await ce(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${yr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${yr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},nL=async e=>{try{let t=bt(await MA(e,"utf-8"));if(Ct(t))return WA(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${$s}.${ll} in ${e}, which uses JSONC that Connect will not rewrite; remove it manually.`]}:{changedFiles:[],messages:[],manual:!1}}catch{}return{changedFiles:[],manual:!0,messages:[`Could not parse ${e}; remove an old Anyray ${$s}.${ll} value manually if present.`]}},GA=async(e,t)=>{let n=QD(e),r;try{r=await M(n)}catch{return nL(n)}let{next:o,removed:a}=WA(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 J(n,o,{backup:!1}),await ce(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.`]}}},rL=async(e,t)=>{let n=await tL(e,t),r=await GA(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},VA=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,FA]}},KA=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},jA=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),oL=e=>Array.isArray(e.args)&&e.args.at(-1)===FA,ZA=(e,t)=>{if(!t.hookBinaryIsDurable()||!Ct(e)||!KA(e,["type","command","args"]))return!1;let n=VA(t);return e.type==="stdio"&&e.command===n.command&&jA(e.args,n.args)},aL=(e,t)=>{if(!Ct(e)||!KA(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&&jA(e.args,n.args))return!0;if(et(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!et(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},dl=(e,t)=>ZA(e,t)?"exact":Ct(e)&&oL(e)||aL(e,t)?"stale-owned":"foreign",LA=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.`,sL=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 m=await Ke(p),y=m.data;if(i){if("servers"in y&&!Ct(y.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 b=Ct(y.servers)?{...y.servers}:{},k=VA(o),C=b[hn],S=C===void 0?void 0:dl(C,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(LA(p));continue}if(t){d+=1;continue}b[hn]=k,f.push({path:p,document:m,next:{...y,servers:b},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!Ct(y.servers)||!(hn in y.servers))continue;if(dl(y.servers[hn],o)==="foreign"){u=!0,l.push(LA(p));continue}if(t)continue;let h={...y.servers};delete h[hn];let w={...y};Object.keys(h).length===0?delete w.servers:w.servers=h,f.push({path:p,document:m,next:w,backup:!1,clearBackupAfter:!0})}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${p} (${m instanceof Error?m.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let p of f)try{await dn(p.path,p.document,p.next,p.backup),p.clearBackupAfter&&await ce(p.path),c.push(p.path),i&&(d+=1)}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${p.path} (${m instanceof Error?m.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`);break}return i?l.unshift(t?d===a.length?`Would register the Anyray retrieval MCP server in ${a.length} VS Code user profile config(s).`:`Would register the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); resolve the conflicts below first.`:d===a.length?`Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) in ${a.length} VS Code user profile config(s).`:`Registered the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); see the profile-specific errors below.`):n?l.unshift(t?`Would skip the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary.`:`Skipped the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary; removed any stale owned registration. Re-run via the installer or a global install to enable retrieval.`):l.unshift(`${t?"Would skip":"Skipped"} the Anyray retrieval MCP server because this VS Code build predates profile-scoped mcp.json support (${iA}+).`),{changedFiles:c,messages:l,manual:u}},iL=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await x(c))try{let l=await Ke(c),d=l.data;if(!Ct(d.servers)||!(hn in d.servers)||dl(d.servers[hn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[hn];let f={...d};Object.keys(u).length===0?delete f.servers:f.servers=u,await dn(c,l,f,!1),await ce(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}},YA=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.`]:[]],JA=()=>`${q} 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.)`,NA=e=>[`${q} 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."],XA=(e,t,n,r)=>({runMcp:o=>sL(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):rL(e,o)}),zA=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${q} VSIX${a}. Nothing was configured. Run \`${n?"code":t.toLowerCase()} --install-extension\` by hand on that VSIX to see the full error.`;case"handoff-undeliverable":return n?`Installed ${q} and staged its configuration, but could not hand it over${a}. A remote VS Code server's command-line launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\`. Reload the VS Code window attached to this machine (Developer: Reload Window): the extension applies the staged configuration as it loads, so there is nothing to re-run.`:`Installed ${q} and staged its configuration, but could not hand it to ${t}${a}. Reload ${t} (quit and reopen): the extension applies the staged configuration as it loads, so there is nothing to re-run.`;case"reload-required":return`A newer ${q} build was installed, but ${t} is still running the previous build. Reload VS Code completely \u2014 the new build applies the staged configuration as it loads, so there is nothing to re-run.`;case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher on this machine. Run anyray-connect from the integrated terminal of the VS Code window attached here (Terminal \u2192 New Terminal in that window) \u2014 a plain SSH shell has no "code" on PATH and cannot hand the key to a running window. No VS Code configuration was written.`:`The ${t} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`;case"unsupported-version":return`The Anyray language-model provider requires VS Code ${qp} or newer. Upgrade ${t}, then re-run anyray-connect; no extension configuration was written.`;case"unsafe-gateway":return"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.";case"extension-missing":return`This anyray-connect installation is missing its bundled ${q} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${q} installed and VS Code accepted the ${r}, but its extension host never confirmed. Reload the VS Code window attached to this machine (Developer: Reload Window): the staged configuration applies as it loads.`:`${q} installed and ${t} accepted the ${r}, but its extension host never confirmed. Reload ${t} completely (quit and reopen): the staged configuration applies as it loads.`;default:return n?`VS Code did not confirm the one-time ${q} ${r}${a}. The configuration is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension applies it as it loads.`:`VS Code did not confirm the one-time ${q} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},cL=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${q} still holds its SecretStorage configuration`;switch(e){case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher, so Anyray could not ask ${q} to clear its SecretStorage configuration. Re-run revert from the integrated terminal of the VS Code window attached to this machine.`:`The ${t} command-line launcher was not found, so Anyray could not ask ${q} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${q} reset to VS Code${o}, so ${a} until it reloads. A remote VS Code server's launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\` \u2014 but the reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`Could not hand the ${q} reset to ${t}${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;case"activation-timeout":return n?`VS Code accepted the ${q} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`${t} accepted the ${q} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;default:return n?`VS Code did not confirm the ${q} reset${o}, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`VS Code did not confirm the ${q} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},lL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=XA(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let m=await c(!0),y=await i(!0);return{status:m.manual||y.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...NA(t),a?pf({status:"enabled",changed:!0},!0):`Would enable the VS Code Agents window in ${e}'s settings.json (two keys, each added only if absent).`,...y.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${q}; 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:[zA(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),f=await i(!1),p=a?void 0:await _A(e).catch(()=>({status:"manual",reason:"the settings file could not be read"}));return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles,...p?.status==="enabled"&&p.changed?[Ds(e)]:[]],messages:[...d.alreadyCurrent?[JA()]:[],...NA(t),pf(p??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:YA(d.profiles),...f.messages,...u.messages]}},$A=e=>[`${q} 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: ${Bs().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."],dL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=XA(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),m=await i(!0);return{status:p.manual||m.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...$A(t),...m.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${q}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Bs().map(p=>({id:p,name:UA(p)}))});if(!d.ok)return{status:"manual",messages:[zA(d.reason,e,a,"gateway API configuration",d.detail)]};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?[JA()]:[],...$A(t),...d.alreadyCurrent?[]:YA(d.profiles),...f.messages,...u.messages]}},uL=async(e,t,n)=>{if(!n.hookBinaryIsDurable())return{registered:!1,command:null,reason:"ephemeral-runtime"};let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null,reason:"no-config"};let o=[];for(let s of r){if(!await x(s))return{registered:!1,command:null,reason:"no-config"};try{let{data:i}=await Ke(s),c=Ct(i.servers)?i.servers[hn]:void 0;if(!ZA(c,n))return{registered:!1,command:null,reason:c===void 0?"absent":dl(c,n)==="stale-owned"?"stale":"foreign"};o.push(c.command)}catch{return{registered:!1,command:null,reason:"unreadable"}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var pL=async(e={installedVariant:Xo,remoteServerVariant:tf,isRemoteDevContext:Hr})=>{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}},fL={installedVariant:Xo,remoteServerVariant:tf,detectVscodeLmProviderEligibility:fA,configureVscodeExtension:RA,vscodeExtensionPointsAt:OA,vscodeExtensionAwaitingReload:al,vscodeExtensionReceiptMode:sl,hookBinaryIsDurable:ne,hookBinaryPath:_e,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:uA,isRemoteDevContext:Hr},mL=(e={})=>{let t={...fL,...e},n=()=>pL(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Ls,quitTarget:il},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Jo(r,!0)}`:Ns(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!be(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 ${qp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||cA(i.version);return ee(r,"copilot")?lL(a,r,o,t.configureVscodeExtension,c,s,t):dL(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?uL(r,o,t):{registered:!1,command:null,reason:"no-config"}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ps(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await cl(Ns(o));if(s.kind==="array"){let c=s.entries.find(ff)?.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 cl(Ns(r));if(o.kind==="array"&&o.entries.some(ff))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 iL(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await GA(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${q} to clear its global configuration and SecretStorage key`);else{let w=await t.configureVscodeExtension(o,void 0,"reset");w.ok?(c=!0,d=w.receipt,u.push(`Cleared ${q} gateway configuration and secret.`)):(l=!0,u.push(cL(w.reason,o,a,w.detail)))}let f=Ns(o),p=await cl(f),m=p.kind==="missing"||p.kind==="array"&&!mf(p.entries).removed,y=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),m)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:y.length?y:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:y.length?y:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:y,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(p.kind==="unrecognized")return{status:"manual",changedFiles:y.length?y:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${yr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:g}=mf(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${yr} Custom Endpoint from ${f}`]};await HA(f,g);let h=[...u,`Removed the ${yr} Custom Endpoint from ${f}.`];return await ce(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...y,f],messages:h}}}},qA=mL();import{accessSync as VL,constants as pC,statSync as KL}from"node:fs";import{readFile as fC,rm as Ws}from"node:fs/promises";import{homedir as Sf,platform as CC}from"node:os";import{delimiter as jL,join as Ef,resolve as ZL}from"node:path";import{execFile as bL}from"node:child_process";import{readFile as AL}from"node:fs/promises";import{homedir as gf,platform as CL}from"node:os";import{join as Fs}from"node:path";import{join as hL}from"node:path";var hf="Iv1.b507a08c87ecfe98",yL="https://github.com/login/device/code",gL="https://github.com/login/oauth/access_token",wL="read:user",QA=1e4,qo=()=>hL(Q(),"copilot-seat-login.json"),eC={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},yf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tC=async(e={})=>{let t={...eC,...e};try{let n=await t.fetch(yL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:hf,scope:wL}),signal:AbortSignal.timeout(QA)});if(!n.ok)return;let r=await n.json();if(!yf(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}},nC=async(e,t={})=>{let n={...eC,...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(gL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:hf,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(QA)})).json();if(!yf(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"}},rC=async(e,t)=>{let n=qo();return await we(n,`${JSON.stringify({token:e,clientId:hf,mintedAtIso:t},null,2)}
|
|
94
|
-
`),n},ul=async()=>{try{let e=await M(qo());if(!
|
|
95
|
-
`))}`]:[],`export ${gl}=${Se(n)}`]},
|
|
96
|
-
`).map(
|
|
97
|
-
`)):K&&ae&&await Ws(U,{force:!0}),await $c(c,z,gn)}catch(te){try{oe!==void 0&&ae?await we(U,oe):ae&&await Ws(U,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw te}return{status:"configured",messages:F,changedFiles:[c,...O.length>0||K&&ae?[U]:[],...Y?[Pn()]:[]]}},d=await r(),u=d!==void 0&&!
|
|
90
|
+
${a}${s},`,d=`${i}${l}${c}`;try{let u=bt(d);if(!oA(u))return{ok:!1,reason:"unsupported"};for(let[f,p]of Object.entries(r))if(JSON.stringify(u[f])!==JSON.stringify(p))return{ok:!1,reason:"unsupported"};if(JSON.stringify(u[t])!==JSON.stringify(n))return{ok:!1,reason:"unsupported"}}catch{return{ok:!1,reason:"unsupported"}}return{ok:!0,text:d}};import{execFile as lD}from"node:child_process";import{readdirSync as dD,statSync as uD}from"node:fs";import{createHash as bA,randomBytes as pD,randomUUID as AA}from"node:crypto";import{chmod as fD,lstat as sf,mkdir as cf,readdir as CA,readFile as pn,rm as kA,unlink as ol,writeFile as lf}from"node:fs/promises";import{homedir as zo,platform as df}from"node:os";import{dirname as rf,join as At,posix as yA,win32 as mD}from"node:path";import{promisify as hD}from"node:util";var un="0.1.29";var hr="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",tl="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",aA="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwI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hhdpzIc9AM5AAAjqQAAGwAAAAAAAAAAAAAApIEbHgAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAHAAcA1gEAAGdXAAAAAA==";import{readFile as cA}from"node:fs/promises";import{homedir as qr,platform as Yo}from"node:os";import{join as Tn,posix as rD,win32 as oD}from"node:path";var Qr=["Code","Code - Insiders","VSCodium"],Qp="1.121.0",sA=1,aD=121,lA="1.102.0",iA=1,sD=102,iD={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},nl=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},ef=e=>{let t=nl(e);return t?t.major!==sA?t.major>sA:t.minor>=aD:!1},dA=e=>{let t=nl(e);return t?t.major!==iA?t.major>iA:t.minor>=sD:!1},cD=async e=>{if(Yo()!=="darwin")return;let t=Tn("/Applications",`${iD[e]}.app`,"Contents","Resources","app","package.json");if(await x(t))try{let n=JSON.parse(await cA(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},rl=(e,t=Yo(),n=qr(),r=process.env)=>{switch(t){case"darwin":return Tn(n,"Library","Application Support",e);case"win32":return Tn(r.APPDATA??Tn(n,"AppData","Roaming"),e);default:return Tn(n,".config",e)}},tf=(e,t)=>e?t==="win32"?oD.join:rD.join:Tn,Jo=(e,t=!1,n=Yo(),r=qr(),o=process.env)=>t?tf(t,n)(r,Ts[e],"data","User"):Tn(rl(e,n,r,o),"User"),uA=async(e,t=!1,n=Yo(),r=qr(),o=process.env)=>{try{let a=tf(t,n)(Jo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await cA(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[]}},pA=async(e,t=Yo(),n=qr(),r=process.env)=>{let a=(await uA(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},fA=async(e,t=!1,n=Yo(),r=qr(),o=process.env)=>{let a=tf(t,n),s=Jo(e,t,n,r,o),i=await uA(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Xo=async()=>{for(let e of Qr)if(await x(rl(e)))return e},Ts={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},mA=(e,t=qr())=>Tn(t,Ts[e],"extensions"),nf=async(e=qr())=>{for(let t of Qr)if(await x(Tn(e,Ts[t])))return t},hA=async e=>{let t=e??await Xo();if(!t)return{status:"unknown"};let n=await cD(t);return n?{variant:t,version:n,status:ef(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var q="anyray.anyray-vscode",uf="vscode-handoffs",vA="vscode-receipts",_s=2,yD=hD(lD),_n={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"]}},gD={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"}},wD=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),SA=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&wD(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ps=e=>{if(SA(e))try{return new URL(e.trim()).origin}catch{return}},bD=(e,t)=>{if(!e.endsWith(".app"))return!1;let n=e.slice(0,-4);if(n===t)return!0;if(!n.startsWith(`${t} `))return!1;let r=n.slice(t.length+1);return r.length>0&&/^\d+$/.test(r)},AD=e=>{try{return dD(e)}catch{return[]}},CD=e=>{try{return uD(e).mtimeMs}catch{return}},kD=(e,t,n,r,o)=>{if(!Hr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=_n[e].commands[0],s=At(t,Ts[e]),i=[];for(let{directory:c,suffix:l}of[{directory:At(s,"bin"),suffix:["bin","remote-cli"]},{directory:At(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=At(c,d,...l,a),f=o(u);f!==void 0&&i.push({path:u,mtime:f})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},vD=(e,t,n)=>{let{macAppName:r,commands:o}=_n[e],a=o[0],s=[];for(let i of["/Applications",yA.join(t,"Applications")])for(let c of n(i))bD(c,r)&&s.push(yA.join(i,c,"Contents/Resources/app/bin",a));return s},SD=(e,t=df(),n=zo(),r=process.env,o=AD,a=CD)=>{let s=kD(e,n,r,o,a);if(t==="darwin")return[...new Set([..._n[e].commands,...vD(e,n,o),...s])];if(t!=="win32"){let u=_n[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=gD[e],c=mD.join,l=r.LOCALAPPDATA??c(n,"AppData","Local"),d=[c(l,"Programs"),r.ProgramFiles,r["ProgramFiles(x86)"]].filter(u=>!!u);return[...new Set([...d.map(u=>c(u,i.directory,i.executable)),_n[e].commands[0],...s])]},EA={run:async(e,t)=>({stdout:(await yD(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>pD(24).toString("base64url"),home:"",commandCandidates:e=>SD(e)},eo=(e,t)=>At(e,".anyray",vA,`${t}.json`),pf=(e,t)=>At(e,".anyray",vA,`${t}.applied.json`),IA=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&nl(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},of=async(e,t,n)=>{try{let r=await t.run(e,[...n===void 0?[]:["--profile",n],"--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===q.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===un}catch{return}},xA=async(e,t)=>{let n=await IA(e,t);if(n)return of(n.command,t)},ED=async(e,t,n)=>{let r=At(e,".anyray",uf);for(let o of n){if(!o.endsWith(".json"))continue;let a=At(r,o);try{if(!(await sf(a)).isFile()||JSON.parse(await pn(a,"utf8")).variant!==t)continue;await ol(a)}catch{}}},ID=async(e,t)=>{let n=At(e,".anyray",uf),r;try{r=await CA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=At(n,o);try{if(!(await sf(a)).isFile()||JSON.parse(await pn(a,"utf8")).variant!==t)continue;await ol(a)}catch{}}},xD=async(e,t)=>{try{let n=JSON.parse(await pn(eo(e,t),"utf8"));return n.extensionVersion===un&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==hr}catch{return!1}},RA=250,RD=9e4,OD=RD/RA,TD=async(e,t,n,r)=>{for(let o=0;o<OD;o++){try{let a=JSON.parse(await pn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===_s&&a.action===n?"confirmed":a.extensionVersion!==un||a.extensionDistSha256!==hr?"reload-required":a.version===_s&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(RA)}return"timeout"},_D=200,gA=(e,t)=>{let n=e,r=[typeof n?.name=="string"&&n.name?n.name:"Error"];typeof n?.code=="number"?r.push(`exit ${n.code}`):typeof n?.code=="string"&&n.code&&r.push(n.code);let a=(typeof n?.stderr=="string"?n.stderr:"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0);if(a){let s=a;t&&(s=s.replaceAll(t,"<nonce>")),s=s.replace(/\b(ark_|sk-|adt_|enl_)[A-Za-z0-9_-]+/g,"$1\u2026"),r.push(s.slice(0,_D))}return r.join(": ")},PD=async e=>{try{let t=await sf(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},wA=e=>bA("sha256").update(e).digest("hex"),DD=async(e=zo())=>{let t=Buffer.from(aA,"base64");if(t.length<4||t[0]!==80||t[1]!==75||wA(t)!==tl)throw new Error("bundled VS Code extension failed integrity validation");let n=At(e,".anyray","vscode-extension"),r=At(n,`anyray-vscode-${un}-${tl.slice(0,12)}.vsix`);try{if(wA(await pn(r))===tl)return r}catch{}await cf(n,{recursive:!0,mode:448});let o=`${r}.${AA()}.tmp`;try{await lf(o,t,{mode:384}),await he(o,r),df()!=="win32"&&await fD(r,384)}finally{await kA(o,{force:!0})}return r},af=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=>af(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${af(t[n])}`).join(",")}}`},OA=(e,t,n)=>bA("sha256").update(af({gatewayUrl:Ps(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:un,extensionDistSha256:hr,profiles:[...n].sort()})).digest("hex"),LD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await pn(pf(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==OA(t,n,r))return!1;let i=JSON.parse(await pn(eo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===un&&i.extensionDistSha256===hr&&i.gatewayUrl===Ps(t.origin)?await xA(e,a)===!0:!1},ND=async(e,t,n,r)=>{let o=pf(e,t),a=`${o}.${AA()}.tmp`;try{await cf(rf(o),{recursive:!0,mode:448}),await lf(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
91
|
+
`,{mode:384}),await he(a,o)}catch{}finally{await kA(a,{force:!0})}},$D=async(e,t)=>{await ol(pf(e,t)).catch(()=>{})},TA=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...EA,...r,home:r.home??zo()},s=_n[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!SA(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,k,C)=>typeof b.id=="string"&&b.id.length>0&&b.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.id)&&typeof b.name=="string"&&b.name.length>0&&b.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.name)&&C.findIndex(S=>S.id===b.id)===k);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await IA(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!ef(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>pA(b,df(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await LD(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:eo(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let f=a.extensionPath;if(n==="configure"){try{f??=await DD(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await PD(f))return{ok:!1,reason:"extension-missing"}}let p=a.nonce(),m=At(a.home,".anyray",uf,`${p}.json`),h=eo(a.home,s.slug);await cf(rf(m),{recursive:!0,mode:448});let g=await CA(rf(m)).catch(()=>[]);await lf(m,`${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:un,expectedExtensionDistSha256:hr})}
|
|
92
|
+
`,{mode:384}),await ED(a.home,s.slug,g).catch(()=>{});let y={installed:[],failed:[]},w=!1;try{if(n==="configure"){let k=await xD(a.home,s.slug);if(k||await of(l,a)!==!0)try{await a.run(l,["--install-extension",f,"--force"])}catch(C){return w=!0,{ok:!1,reason:"install-failed",detail:gA(C,p)}}for(let C of u)try{(k||await of(l,a,C)!==!0)&&await a.run(l,["--profile",C,"--install-extension",f,"--force"]),y.installed.push(C)}catch{y.failed.push(C)}}try{await a.run(l,["--open-url",`${s.scheme}://${q}/configure?nonce=${encodeURIComponent(p)}`])}catch(k){return{ok:!1,reason:"handoff-undeliverable",detail:gA(k,p)}}let b=await TD(h,p,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(w=!0,n==="configure")y.failed.length===0&&await ND(a.home,s.slug,OA(t,o,u),p);else{await $D(a.home,s.slug),await ID(a.home,s.slug).catch(()=>{});for(let k of[void 0,...u])try{await a.run(l,[...k?["--profile",k]:[],"--uninstall-extension",q])}catch{}}return{ok:!0,receipt:h,profiles:y}}catch{return{ok:!1,reason:"failed"}}finally{w&&await ol(m).catch(()=>{})}},al=async(e,t=zo())=>{try{let n=JSON.parse(await pn(eo(t,_n[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==un||n.extensionDistSha256!==hr)}catch{return!1}},sl=async(e,t=zo())=>{try{let n=JSON.parse(await pn(eo(t,_n[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}},_A=async(e,t,n=zo(),r={})=>{try{let o=Ps(t);if(!o)return!1;let a=JSON.parse(await pn(eo(n,_n[e].slug),"utf8"));if(!(a.version===_s&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===un&&a.extensionDistSha256===hr))return!1;let i={...EA,...r,home:n};return await xA(e,i)===!0}catch{return!1}};var fn="extensions.supportAgentsWindow",mn="chat.agentHost.byokModels.enabled",Ds=e=>WD(Le(e),"User","settings.json"),PA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),HD=e=>PA(e)&&e[q]===!0,DA=async(e,t={})=>{let n=Ds(e),r=t.read??(p=>MD(p,"utf-8")),o=t.exists??x,a=t.write??(async(p,m)=>{await UD(FD(p),{recursive:!0}),await BD(p,m,"utf-8")}),s=await o(n)?await r(n).catch(()=>{}):"{}";if(s===void 0)return{status:"manual",reason:`could not read ${n}`};s.trim()===""&&(s="{}");let i;try{i=bt(s)}catch{return{status:"manual",reason:`${n} is not valid JSON/JSONC, so it was left untouched`}}if(!PA(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(fn in i)){let p=qp(c,fn,{[q]:!0});if(!p.ok)return{status:"manual",reason:`could not add ${fn} to ${n} without rewriting it`};c=p.text,l=!0}if(!(mn in i)){let p=qp(c,mn,!0);if(!p.ok)return{status:"manual",reason:`could not add ${mn} to ${n} without rewriting it`};c=p.text,l=!0}l&&await a(n,c);let d=l?bt(c):i,u=HD(d[fn]),f=d[mn]===!0;return!u||!f?{status:"manual",reason:`${n} already sets ${u?mn:fn} to something else; left as it is`}:{status:"enabled",changed:l}},ff=(e,t)=>t?"Agents window: it runs on your laptop with the extensions installed there, and VS Code registers no model bridge while the agent host is remote, so this run cannot reach it. Run anyray-connect on your laptop too. Chat in this window is already routed.":e.status==="manual"?`Agents window: not enabled (${e.reason}). Add "${fn}": {"${q}": true} and "${mn}": true to that file to use Anyray models there.`:e.changed?"Agents window: enabled. It takes effect the next time VS Code starts.":"Agents window: already enabled.";import{spawnSync as GD}from"node:child_process";import{platform as VD}from"node:os";var LA={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},KD=(e,t,n)=>GD(e,t,n),NA=KD,jD,ZD=()=>{let e=jD??VD();if(e==="win32"){let n=NA(Es("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],LA);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=NA("pgrep",[n,r],LA);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},YD=ZD,Ls=()=>YD();var il={darwinAppName:"Visual Studio Code",darwinBundleId:"com.microsoft.VSCode",win32Image:"Code.exe",linuxProcess:"code",win32Install:[{root:"localAppData",path:"Programs\\Microsoft VS Code\\Code.exe"},{root:"programFiles",path:"Microsoft VS Code\\Code.exe"},{root:"programFilesX86",path:"Microsoft VS Code\\Code.exe"}]};var yr="Anyray",hn="anyray",UA="--anyray-owner=vscode-profile-v1",Ns=e=>WA(Le(e),"User","chatLanguageModels.json"),tL=e=>WA(Le(e),"User","settings.json"),$s="github.copilot.advanced",ll="debug.overrideCapiUrl",Ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nL=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}},HA=e=>{let t=e[$s];if(!Ct(t)||!nL(t[ll]))return{next:e,removed:!1};let n={...t};delete n[ll];let r={...e};return Object.keys(n).length>0?r[$s]=n:delete r[$s],{next:r,removed:!0}},Ms="anyray-default",Bs=()=>{let e=(process.env.ANYRAY_COPILOT_MODEL??"").split(",").map(t=>t.trim()).filter(t=>t.length>0&&t.length<=200&&!/[\u0000-\u001f\u007f]/.test(t)).filter((t,n,r)=>r.indexOf(t)===n).slice(0,64);return e.length?e:[Ms]},GA=e=>e===Ms?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),cl=async e=>{if(!await x(e))return{kind:"missing"};try{let t=await FA(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"}}},VA=async(e,t)=>{await XD(eL(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${QD()}`;try{await qD(n,`${JSON.stringify(t,null,2)}
|
|
93
|
+
`,{flag:"wx",mode:384}),await he(n,e),await JD(e,384)}finally{await zD(n,{force:!0}).catch(()=>{})}},mf=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!==yr||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!==GA(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}})},hf=e=>{let t=e.filter(n=>!mf(n));return{next:t,removed:t.length!==e.length}},rL=async(e,t)=>{let n=Ns(e),r=await cl(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 "${yr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=hf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${yr}" Custom Endpoint from ${n}.`]};try{return await VA(n,o),await ce(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${yr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${yr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},oL=async e=>{try{let t=bt(await FA(e,"utf-8"));if(Ct(t))return HA(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${$s}.${ll} in ${e}, which uses JSONC that Connect will not rewrite; remove it manually.`]}:{changedFiles:[],messages:[],manual:!1}}catch{}return{changedFiles:[],manual:!0,messages:[`Could not parse ${e}; remove an old Anyray ${$s}.${ll} value manually if present.`]}},KA=async(e,t)=>{let n=tL(e),r;try{r=await M(n)}catch{return oL(n)}let{next:o,removed:a}=HA(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 J(n,o,{backup:!1}),await ce(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.`]}}},aL=async(e,t)=>{let n=await rL(e,t),r=await KA(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},jA=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,UA]}},ZA=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},YA=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),sL=e=>Array.isArray(e.args)&&e.args.at(-1)===UA,JA=(e,t)=>{if(!t.hookBinaryIsDurable()||!Ct(e)||!ZA(e,["type","command","args"]))return!1;let n=jA(t);return e.type==="stdio"&&e.command===n.command&&YA(e.args,n.args)},iL=(e,t)=>{if(!Ct(e)||!ZA(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&&YA(e.args,n.args))return!0;if(et(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!et(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},dl=(e,t)=>JA(e,t)?"exact":Ct(e)&&sL(e)||iL(e,t)?"stale-owned":"foreign",$A=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.`,cL=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 m=await Ke(p),h=m.data;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 b=Ct(h.servers)?{...h.servers}:{},k=jA(o),C=b[hn],S=C===void 0?void 0:dl(C,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push($A(p));continue}if(t){d+=1;continue}b[hn]=k,f.push({path:p,document:m,next:{...h,servers:b},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!Ct(h.servers)||!(hn in h.servers))continue;if(dl(h.servers[hn],o)==="foreign"){u=!0,l.push($A(p));continue}if(t)continue;let y={...h.servers};delete y[hn];let w={...h};Object.keys(y).length===0?delete w.servers:w.servers=y,f.push({path:p,document:m,next:w,backup:!1,clearBackupAfter:!0})}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${p} (${m instanceof Error?m.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let p of f)try{await dn(p.path,p.document,p.next,p.backup),p.clearBackupAfter&&await ce(p.path),c.push(p.path),i&&(d+=1)}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${p.path} (${m instanceof Error?m.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`);break}return i?l.unshift(t?d===a.length?`Would register the Anyray retrieval MCP server in ${a.length} VS Code user profile config(s).`:`Would register the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); resolve the conflicts below first.`:d===a.length?`Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) in ${a.length} VS Code user profile config(s).`:`Registered the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); see the profile-specific errors below.`):n?l.unshift(t?`Would skip the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary.`:`Skipped the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary; removed any stale owned registration. Re-run via the installer or a global install to enable retrieval.`):l.unshift(`${t?"Would skip":"Skipped"} the Anyray retrieval MCP server because this VS Code build predates profile-scoped mcp.json support (${lA}+).`),{changedFiles:c,messages:l,manual:u}},lL=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await x(c))try{let l=await Ke(c),d=l.data;if(!Ct(d.servers)||!(hn in d.servers)||dl(d.servers[hn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[hn];let f={...d};Object.keys(u).length===0?delete f.servers:f.servers=u,await dn(c,l,f,!1),await ce(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}},XA=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.`]:[]],zA=()=>`${q} 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.)`,MA=e=>[`${q} 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."],qA=(e,t,n,r)=>({runMcp:o=>cL(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):aL(e,o)}),QA=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${q} VSIX${a}. Nothing was configured. Run \`${n?"code":t.toLowerCase()} --install-extension\` by hand on that VSIX to see the full error.`;case"handoff-undeliverable":return n?`Installed ${q} and staged its configuration, but could not hand it over${a}. A remote VS Code server's command-line launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\`. Reload the VS Code window attached to this machine (Developer: Reload Window): the extension applies the staged configuration as it loads, so there is nothing to re-run.`:`Installed ${q} and staged its configuration, but could not hand it to ${t}${a}. Reload ${t} (quit and reopen): the extension applies the staged configuration as it loads, so there is nothing to re-run.`;case"reload-required":return`A newer ${q} build was installed, but ${t} is still running the previous build. Reload VS Code completely \u2014 the new build applies the staged configuration as it loads, so there is nothing to re-run.`;case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher on this machine. Run anyray-connect from the integrated terminal of the VS Code window attached here (Terminal \u2192 New Terminal in that window) \u2014 a plain SSH shell has no "code" on PATH and cannot hand the key to a running window. No VS Code configuration was written.`:`The ${t} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`;case"unsupported-version":return`The Anyray language-model provider requires VS Code ${Qp} or newer. Upgrade ${t}, then re-run anyray-connect; no extension configuration was written.`;case"unsafe-gateway":return"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.";case"extension-missing":return`This anyray-connect installation is missing its bundled ${q} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${q} installed and VS Code accepted the ${r}, but its extension host never confirmed. Reload the VS Code window attached to this machine (Developer: Reload Window): the staged configuration applies as it loads.`:`${q} installed and ${t} accepted the ${r}, but its extension host never confirmed. Reload ${t} completely (quit and reopen): the staged configuration applies as it loads.`;default:return n?`VS Code did not confirm the one-time ${q} ${r}${a}. The configuration is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension applies it as it loads.`:`VS Code did not confirm the one-time ${q} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},dL=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${q} still holds its SecretStorage configuration`;switch(e){case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher, so Anyray could not ask ${q} to clear its SecretStorage configuration. Re-run revert from the integrated terminal of the VS Code window attached to this machine.`:`The ${t} command-line launcher was not found, so Anyray could not ask ${q} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${q} reset to VS Code${o}, so ${a} until it reloads. A remote VS Code server's launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\` \u2014 but the reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`Could not hand the ${q} reset to ${t}${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;case"activation-timeout":return n?`VS Code accepted the ${q} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`${t} accepted the ${q} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;default:return n?`VS Code did not confirm the ${q} reset${o}, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`VS Code did not confirm the ${q} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},uL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=qA(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let m=await c(!0),h=await i(!0);return{status:m.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...MA(t),a?ff({status:"enabled",changed:!0},!0):`Would enable the VS Code Agents window in ${e}'s settings.json (two keys, each added only if absent).`,...h.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${q}; 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:[QA(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),f=await i(!1),p=a?void 0:await DA(e).catch(()=>({status:"manual",reason:"the settings file could not be read"}));return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles,...p?.status==="enabled"&&p.changed?[Ds(e)]:[]],messages:[...d.alreadyCurrent?[zA()]:[],...MA(t),ff(p??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:XA(d.profiles),...f.messages,...u.messages]}},BA=e=>[`${q} 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: ${Bs().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."],pL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=qA(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),m=await i(!0);return{status:p.manual||m.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...BA(t),...m.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${q}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Bs().map(p=>({id:p,name:GA(p)}))});if(!d.ok)return{status:"manual",messages:[QA(d.reason,e,a,"gateway API configuration",d.detail)]};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?[zA()]:[],...BA(t),...d.alreadyCurrent?[]:XA(d.profiles),...f.messages,...u.messages]}},fL=async(e,t,n)=>{if(!n.hookBinaryIsDurable())return{registered:!1,command:null,reason:"ephemeral-runtime"};let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null,reason:"no-config"};let o=[];for(let s of r){if(!await x(s))return{registered:!1,command:null,reason:"no-config"};try{let{data:i}=await Ke(s),c=Ct(i.servers)?i.servers[hn]:void 0;if(!JA(c,n))return{registered:!1,command:null,reason:c===void 0?"absent":dl(c,n)==="stale-owned"?"stale":"foreign"};o.push(c.command)}catch{return{registered:!1,command:null,reason:"unreadable"}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var mL=async(e={installedVariant:Xo,remoteServerVariant:nf,isRemoteDevContext:Hr})=>{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}},hL={installedVariant:Xo,remoteServerVariant:nf,detectVscodeLmProviderEligibility:hA,configureVscodeExtension:TA,vscodeExtensionPointsAt:_A,vscodeExtensionAwaitingReload:al,vscodeExtensionReceiptMode:sl,hookBinaryIsDurable:ne,hookBinaryPath:_e,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:fA,isRemoteDevContext:Hr},yL=(e={})=>{let t={...hL,...e},n=()=>mL(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Ls,quitTarget:il},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Jo(r,!0)}`:Ns(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!be(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 ${Qp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||dA(i.version);return ee(r,"copilot")?uL(a,r,o,t.configureVscodeExtension,c,s,t):pL(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?fL(r,o,t):{registered:!1,command:null,reason:"no-config"}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ps(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await cl(Ns(o));if(s.kind==="array"){let c=s.entries.find(mf)?.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 cl(Ns(r));if(o.kind==="array"&&o.entries.some(mf))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 lL(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await KA(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${q} to clear its global configuration and SecretStorage key`);else{let w=await t.configureVscodeExtension(o,void 0,"reset");w.ok?(c=!0,d=w.receipt,u.push(`Cleared ${q} gateway configuration and secret.`)):(l=!0,u.push(dL(w.reason,o,a,w.detail)))}let f=Ns(o),p=await cl(f),m=p.kind==="missing"||p.kind==="array"&&!hf(p.entries).removed,h=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),m)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:h.length?h:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:h.length?h:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:h,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(p.kind==="unrecognized")return{status:"manual",changedFiles:h.length?h:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${yr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:g}=hf(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${yr} Custom Endpoint from ${f}`]};await VA(f,g);let y=[...u,`Removed the ${yr} Custom Endpoint from ${f}.`];return await ce(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,f],messages:y}}}},eC=yL();import{accessSync as jL,constants as mC,statSync as ZL}from"node:fs";import{readFile as hC,rm as Ws}from"node:fs/promises";import{homedir as Ef,platform as vC}from"node:os";import{delimiter as YL,join as If,resolve as JL}from"node:path";import{execFile as CL}from"node:child_process";import{readFile as kL}from"node:fs/promises";import{homedir as wf,platform as vL}from"node:os";import{join as Fs}from"node:path";import{join as gL}from"node:path";var yf="Iv1.b507a08c87ecfe98",wL="https://github.com/login/device/code",bL="https://github.com/login/oauth/access_token",AL="read:user",tC=1e4,qo=()=>gL(Q(),"copilot-seat-login.json"),nC={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},gf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rC=async(e={})=>{let t={...nC,...e};try{let n=await t.fetch(wL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:yf,scope:AL}),signal:AbortSignal.timeout(tC)});if(!n.ok)return;let r=await n.json();if(!gf(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}},oC=async(e,t={})=>{let n={...nC,...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(bL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:yf,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(tC)})).json();if(!gf(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"}},aC=async(e,t)=>{let n=qo();return await we(n,`${JSON.stringify({token:e,clientId:yf,mintedAtIso:t},null,2)}
|
|
94
|
+
`),n},ul=async()=>{try{let e=await M(qo());if(!gf(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var SL=5e3,bf=5e3,EL=["copilot-cli","CopilotCLI"],IL="https://api.github.com/copilot_internal/user",iC="~/.copilot/config.json",cC="macOS Keychain (Copilot CLI)",lC=e=>e===iC||e===cC,Qo=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),Zt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xL=()=>process.env.XDG_CONFIG_HOME?.trim()||Fs(wf(),".config"),RL=()=>process.env.XDG_DATA_HOME?.trim()||Fs(wf(),".local","share"),OL=async()=>{try{let e=await kL(Fs(wf(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return Qo(t)?t:void 0}catch{}},TL=async e=>{try{let t=await M(Fs(xL(),"github-copilot",e));if(!Zt(t))return;for(let n of Object.values(t))if(Zt(n)&&Qo(n.oauth_token))return n.oauth_token}catch{}},_L=async()=>{try{let e=await M(Fs(RL(),"opencode","auth.json")),t=Zt(e)?e["github-copilot"]:void 0;if(!Zt(t)||t.type!=="oauth")return;if(Qo(t.access))return t.access;if(Qo(t.refresh))return t.refresh}catch{}},PL=(e,t)=>new Promise((n,r)=>{try{CL(e,[...t],{timeout:SL},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),DL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return Qo(r)?r:void 0}catch{return}},LL=async(e=PL)=>{for(let t of EL){let n=await DL(t,e);if(n)return n}};var pl={env:process.env,platform:vL,tokenFromDeviceLogin:ul,tokenFromCopilotCliConfig:OL,tokenFromSharedConfig:TL,tokenFromOpenCode:_L,tokenFromKeychain:LL,fetch:(...e)=>fetch(...e)},NL=new Set([401,403,404]),fl=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,dC=e=>{let t=e?.trim().toLowerCase()??"";return t&&t!=="default"&&fl.test(t)?t:"default"},$L=e=>e!=="default"&&fl.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",ML=e=>{if(typeof e!="string")return"default";let t=e.trim().match(/^https:\/\/api\.([a-z0-9-]{1,63})\.githubcopilot\.com\/?$/)?.[1];return t&&fl.test(t)?t:"default"},Af=async(e,t={})=>{let n={...pl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),bf);try{let a=await n.fetch(IL,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=Zt(i)&&Zt(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:ML(s)}}return{verdict:NL.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var ea=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${fl.test(n)?n:"default"}/header/models`,a=await sC(o,e,r.clientKey,t);if(a.length>0)return a}return sC(`${$L(n)}/models`,e,void 0,t)},sC=async(e,t,n,r={})=>{let o={...pl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),bf);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=Zt(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!Zt(u))continue;let f=u.id;if(typeof f!="string"||f.length===0||u.model_picker_enabled!==!0)continue;let p=u.policy;if(Zt(p)&&p.state!=="enabled")continue;let m=u.supported_endpoints,h=Array.isArray(m)?m.filter(S=>typeof S=="string"):[],g=u.capabilities,y=Zt(g)?g.limits:void 0,w=S=>{let E=Zt(y)?y[S]:void 0;return typeof E=="number"&&Number.isFinite(E)&&E>0?Math.floor(E):void 0},b={id:f,endpoints:h},k=w("max_prompt_tokens"),C=w("max_output_tokens");k!==void 0&&(b.maxPromptTokens=k),C!==void 0&&(b.maxOutputTokens=C),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},ml=async(e,t,n,r={})=>{let o={...pl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),bf);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)}},hl=async(e={},t={})=>{let n={...pl,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return Qo(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:cC,read:()=>n.tokenFromKeychain()}]:[],{source:iC,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await Af(s,t);if(i.verdict==="no-copilot"){o.push(a.source);continue}return{token:{token:s,source:a.source},rejected:o,capiSegment:i.capiSegment}}return{rejected:o}};import{homedir as yl,platform as pC}from"node:os";import{join as at}from"node:path";import{execFile as BL}from"node:child_process";import{readFile as FL,readdir as WL}from"node:fs/promises";var UL=3e3,HL="Claude Code-credentials",GL=["copilot-cli","CopilotCLI"],fC=e=>new Promise(t=>{try{BL("security",["find-generic-password","-s",e],{timeout:UL},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),VL=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=at(yl(),".claude");return!!(await x(at(e,".oauth_token"))||await x(at(e,".credentials.json"))||pC()==="darwin"&&await fC(HL))},KL=async()=>{let e=at(process.env.CODEX_HOME?.trim()||at(yl(),".codex"),"auth.json");if(!await x(e))return!1;try{let t=JSON.parse(await FL(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},uC=async e=>{try{return(await WL(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},Cf=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of Qr){let n=at(Le(t),"User","globalStorage");if(await x(at(n,"github.copilot-chat"))||await x(at(n,"github.copilot")))return!0}let e=at(yl(),".config","github-copilot");if(await x(at(e,"apps.json"))||await x(at(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await uC(at(yl(),t,"extensions")))return!0;for(let t of Qr){if(await uC(mA(t)))return!0;let n=at(Jo(t,!0),"globalStorage");if(await x(at(n,"github.copilot-chat"))||await x(at(n,"github.copilot")))return!0}if(pC()==="darwin"){for(let t of GL)if(await fC(t))return!0}return!1},yn=async()=>{let[e,t,n]=await Promise.all([VL(),KL(),Cf()]);return{anthropic:e,openai:t,copilot:n}};var ro="copilot-cli",gn="copilot-cli",XL=Ls,zL=()=>XL()?["VS Code is open \u2014 its Copilot CLI runs inside the extension host, which","captured your shell environment when the editor launched. Restart VS Code,","or its CLI chat and Autopilot sessions stay on native GitHub traffic and","never reach the gateway (no spend, no traces) even though this block is set."]:[],SC=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],xf=()=>Object.fromEntries(SC.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),yC=()=>If(Ef(),".anyray","copilot-cli.sh"),EC="# Managed by anyray-connect. Do not source this file anywhere else.",gC=e=>e.split(/\r?\n/,1)[0]===EC,qL=["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"],gl="COPILOT_PROVIDER_API_KEY",wC=e=>e.startsWith(`export ${gl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Dn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",QL=()=>Bs()[0],Us=(e="default")=>`/copilot/${e}/header`,Zq=Us(),to=e=>e.replace(/\/+$/,""),eN=(e,t="default")=>`${to(e.openaiBaseUrl)}${Us(t)}`,kf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),Sf="claude-sonnet-5",tN=()=>{let e=Bs()[0];return e===Ms?Sf:e},IC=e=>e.endpoints.includes(Dn(e.id)==="responses"?"/responses":"/chat/completions"),Rf=e=>{let t=e.filter(IC),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)=>bC(a.version,s.version)?-1:bC(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var bC=(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},AC=(e,t,n,r,o,a="default")=>{let s=fe({...e.metadata,tool:ro}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...SC];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Se(eN(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Dn(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(`
|
|
95
|
+
`))}`]:[],`export ${gl}=${Se(n)}`]},vf=(e,t,n)=>{let r=fe({...e.metadata,tool:ro});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Se(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Dn(t)}'`,`export COPILOT_MODEL=${Se(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${Se(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${gl}=${Se(n)}`]:[]]},nN=(e,t)=>t||!ee(e,"copilot"),CC=()=>{let e=qL.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).`]},kC=(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 ${ro}\`), 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`."],rN=(e=process.env.PATH,t=vC())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(YL)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=JL(o,n);try{if(!ZL(a).isFile())continue;return jL(a,t==="win32"?mC.F_OK:mC.X_OK),a}catch{}}},oN=()=>If(Ef(),".copilot","config.json"),Pn=()=>If(Ef(),".copilot","mcp-config.json"),no="anyray",aN=()=>({type:"local",...Ge("profile"),tools:["*"]}),gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sN=async()=>{let e=Pn(),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&&!gr(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=(gr(t.mcpServers)?t.mcpServers:{})[no];return r!==void 0&&!Tt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${no} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},iN=async e=>{let t=Pn(),n=e.json,r=gr(n.mcpServers)?n.mcpServers:{};r[no]=aN(),n.mcpServers=r,await J(t,n)},cN=async()=>{let e=Pn(),t;try{let r=await M(e);if(!gr(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!gr(n)||!(no in n)||!Tt(n[no],"profile")?!1:(delete n[no],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Ws(e,{force:!0}):await J(e,t,{backup:!1}),await ce(e),!0)},lN={resolveCopilotCommand:rN,platform:vC,detectCopilotSeat:Cf,discoverSeatToken:hl,readDeviceLoginToken:ul,fetchSeatModelCatalog:ea,probeSeatChatModel:ml},dN=e=>`'${e.replace(/'/g,"''")}'`,uN=e=>e.split(`
|
|
96
|
+
`).map(dN).join(" + [Environment]::NewLine + "),pN=(e={})=>{let t={...lN,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Mc(wt(),gn))?.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&&to(s)===`${to(i)}/v1`,a=(s,i)=>s!==void 0&&kf(s)&&to(s).startsWith(`${to(i)}/v1/copilot/`);return{id:ro,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Ls,quitTarget:il},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=oN();return await x(i)?{installed:!0,detail:i}:{installed:!1,detail:"no `copilot` on PATH and no ~/.copilot state"}},async apply(s,i){let c=wt(),l=async(S,E,I)=>{let O=S.filter(wC),T=S.filter(te=>!wC(te)),U=yC(),z=[...T,...O.length>0?[`[ -r ${Se(U)} ] && . ${Se(U)}`]:[]],K=await x(U),oe=K?await hC(U,"utf8"):void 0,ae=oe===void 0||gC(oe);if(O.length>0&&!ae)return{status:"manual",messages:[`Refused to overwrite user-managed ${U}; move or rename that file, then run Connect again.`]};let Z=ne(),ie=Z?await sN():void 0,F=[`${c} \u2190 managed Anyray block (${gn})`,...E.map(te=>` ${te}`),...O.length>0?[`${U} \u2190 owner-only credential (mode 0600)`]:[],...I,ie?.status==="skipped"?ie.message:Z?`${Pn()} \u2190 Anyray retrieval MCP server (anyray_retrieve / anyray_recall)`:`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${_e()}). Re-run via the installer or a global install to enable retrieval.`,"Inline `copilot` completions and GitHub-hosted features stay native GitHub traffic.",`Run \`source ${c}\` or open a new terminal to apply.`,...zL()];if(i.dryRun)return{status:"configured",messages:F};let Y=!1;ie?.status==="installable"&&(await iN(ie),Y=!0);try{O.length>0?await we(U,[EC,...O,""].join(`
|
|
97
|
+
`)):K&&ae&&await Ws(U,{force:!0}),await $c(c,z,gn)}catch(te){try{oe!==void 0&&ae?await we(U,oe):ae&&await Ws(U,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw te}return{status:"configured",messages:F,changedFiles:[c,...O.length>0||K&&ae?[U]:[],...Y?[Pn()]:[]]}},d=await r(),u=d!==void 0&&!kf(d),f=s.authMode==="placeholder",p=u,m=u&&(!p||!ee(s,"copilot")),h=f?void 0:await t.readDeviceLoginToken().catch(()=>{}),g=f||m&&!h?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),y=g.token,w=g.rejected;if(y){let S=g.capiSegment??"default",E=tN(),I=E!==Sf||!!process.env.ANYRAY_COPILOT_MODEL,O=await t.fetchSeatModelCatalog(y.token,{},S,{laneOrigin:to(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),T=O.find(F=>F.id===E);if(!I){let F=Rf(O);if(T=F[0],!i.dryRun&&F.length>0){let Y=ge=>`${to(s.origin)}/v1${Us(S)}/${Dn(ge)==="responses"?"responses":"chat/completions"}`,te={...xf(),authorization:`Bearer ${y.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},Ue=new Set,ve;for(let ge of F.slice(0,4)){let Ht=await t.probeSeatChatModel(Y(ge.id),te,ge.id);if(Ht==="ok"){ve=ge;break}if(Ht==="unreachable")break;Ue.add(ge.id)}T=ve??F.find(ge=>!Ue.has(ge.id))??F[0]}E=T?.id??Sf}let U=s.clientKey??s.placeholderKey,z=U&&s.clientKey?Pt(U):U,K=AC(s,E,y.token,U,T,S),oe=AC(s,E,Pt(y.token),z,T,S),ae=Dn(E),Z=O.filter(F=>IC(F)&&Dn(F.id)===ae).map(F=>F.id).filter(F=>F!==E),ie=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${y.source}).`,`Model: ${E}${I?" (pinned via ANYRAY_COPILOT_MODEL)":O.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...O.length===0&&lC(y.source)?["GitHub served no current models for this sign-in \u2014 the Copilot CLI's own login is","entitled to legacy models only. Fix it with: `anyray-connect copilot-login`","(one browser step), then re-run this command."]:[],...Z.length>0?[`Your plan also serves: ${Z.slice(0,8).join(", ")}${Z.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",...oe.map(F=>{let Y=F.indexOf("="),te=F.slice(7,Y),Ue=F.slice(Y+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${te}', ${uN(Ue)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${y.source}, and the gateway key from \`anyray-connect print-key\`.)`,...ie]}:l(K,oe,ie)}if(!nN(s,m)){if(p&&!i.dryRun){let S=wt();if(await As(S,gn))return{status:"reverted",changedFiles:[S],messages:[`removed a stale Anyray ${gn} block from ${S}`,"It routed the CLI on ORG API billing, which predates the Copilot","seat lane and is not a lane you chose. Nothing replaces it yet:",...kC(t.platform(),w),...CC()]}}return{status:"held",messages:[...p&&i.dryRun?[`would remove a stale Anyray ${gn} block from ${wt()} (org lane, not chosen)`]:[],...kC(t.platform(),w)]}}let b=QL(),k=s.clientKey??s.placeholderKey,C=k&&s.clientKey?Pt(k):k;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...vf(s,b,C).map(S=>{let[E,...I]=S.replace(/^export /,"").split("=");return` setx ${E} "${I.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${gl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(vf(s,b,k),vf(s,b,C),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===Ms?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=wt(),c=yC(),l=await x(c),d=l?gC(await hC(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${gn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Pn()} if registered`,...await x(qo())?[`would remove the Copilot sign-in Connect minted (${qo()})`]:[]]};let u=await As(i,gn);d&&await Ws(c,{force:!0});let f=await cN(),p=qo(),m=await x(p);m&&await Ws(p,{force:!0});let h=[...u?[i]:[],...d?[c]:[],...f?[Pn()]:[],...m?[p]:[]];return{status:h.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${gn} block from ${i}`:`no Anyray ${gn} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...m?[`removed the Copilot sign-in Connect minted (${p})`]:[],...f?[`removed the Anyray MCP server from ${Pn()}`]:[],...CC()],changedFiles:h.length>0?h:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let s=Pn();if(!await x(s))return{registered:!1,command:null,reason:"no-config"};try{let i=await M(s),c=gr(i)?i.mcpServers:void 0,l=gr(c)?c[no]:void 0;return!gr(l)||!Tt(l,"profile")?{registered:!1,command:null,reason:l===void 0?"absent":"foreign"}:{registered:!0,command:typeof l.command=="string"?l.command:null}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async inferenceAuthLanes(){try{let s=await r();return s===void 0?["native"]:kf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(ro)?!0:!await t.detectCopilotSeat()}}},xC=pN();import{homedir as LC}from"node:os";import{join as br}from"node:path";import{readFile as NC}from"node:fs/promises";import{readFile as RC,rm as fN}from"node:fs/promises";var OC="// Managed by anyray-connect: OpenCode trim carrier v1",mN=5e3,Of=e=>`${OC}
|
|
98
98
|
import { spawn } from "node:child_process"
|
|
99
99
|
|
|
100
100
|
const hookCommand = ${JSON.stringify([e.command,...e.args])}
|
|
101
|
-
const hookTimeoutMs = ${
|
|
101
|
+
const hookTimeoutMs = ${mN}
|
|
102
102
|
|
|
103
103
|
const invokeHook = (payload) =>
|
|
104
104
|
new Promise((resolve) => {
|
|
@@ -165,24 +165,24 @@ export const AnyrayTrimPlugin = async () => ({
|
|
|
165
165
|
}
|
|
166
166
|
},
|
|
167
167
|
})
|
|
168
|
-
`,Hs=async e=>await x(e)?(await
|
|
169
|
-
`)?"owned":"foreign":"absent",RC=async(e,t)=>{let n=Rf(t),r=await Hs(e);return r==="foreign"?"foreign":r==="owned"&&await IC(e,"utf-8")===n?"unchanged":(await we(e,n),"installed")},Of=async e=>{let t=await Hs(e);return t!=="owned"?t:(await uN(e,{force:!0}),"removed")};var Tf="https://opencode.ai/config.json",$n="x-anyray-metadata",Lt="x-anyray-api-key",_f=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Ln="Authorization",wr=["anthropic","openai"],Mn="github-copilot",fN="header",Nn="anyray",mN=()=>process.env.XDG_CONFIG_HOME?.trim()||br(PC(),".config"),hN=()=>process.env.XDG_DATA_HOME?.trim()||br(PC(),".local","share"),Al=()=>br(mN(),"opencode"),wl=()=>br(Al(),"plugins","anyrayTrim.js"),LC=()=>br(hN(),"opencode"),NC=async()=>{try{let e=await DC(br(LC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return W(t)?{chatGptOAuth:W(t.openai)&&t.openai.type==="oauth",readable:!0}:{chatGptOAuth:!1,readable:!1}}catch(e){return e.code==="ENOENT"?{chatGptOAuth:!1,readable:!0}:{chatGptOAuth:!1,readable:!1}}},OC=async()=>(await NC()).chatGptOAuth,yN=["opencode.jsonc","opencode.json","config.json"],ta=async()=>{let e=Al(),t=[];for(let n of yN){let r=br(e,n);await x(r)&&t.push(r)}return t},TC=async()=>(await ta())[0]??br(Al(),"opencode.json"),Pf=()=>cC(process.env.ANYRAY_COPILOT_PLAN),Df=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Pf()}/${fN}`,W=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}/`)},gN=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===wr[0]||n===wr[1]||n===Mn?[]:W(r)&&W(r.options)&&Bf(r.options.baseURL,t)?[n]:[]),Lf=/claude/i,Ff=["model","small_model"],$C=(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)||!Lf.test(o)))return`${wr[0]}/${o}`},Nf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Nf(n,t);return t}if(!W(e))return t;for(let[n,r]of Object.entries(e))Ff.includes(n)&&typeof r=="string"?t.push(r):Nf(r,t);return t},wN=(e,t,n)=>{if(!W(e)||!W(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Lf.test(a)))return!1;let o=`${n}/`;return Nf(t).filter(a=>a.startsWith(o)).every(a=>Lf.test(a.slice(o.length)))},$f=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>$f(o,t,n));if(!W(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Ff.includes(o)?$C(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=$f(a,t,n)}return r},Mf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Mf(o,t[a],n));if(!W(e)||!W(t))return e;let r={};for(let[o,a]of Object.entries(e))Ff.includes(o)&&typeof a=="string"&&$C(t[o],n)===a?r[o]=t[o]:r[o]=Mf(a,t[o],n);return r},bN=e=>{if(W(e))for(let t of wr){let n=e[t];if(W(n)&&W(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Gs=e=>{if(!W(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Tt({command:t,args:n},"profile")},bl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),AN=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return W(t)&&t.tool==="opencode"}catch{return!1}},Wf=e=>ee(e,"copilot")&&!!e.clientKey,CN=e=>e.byoUpstream?[]:ee(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],kN=(e,t)=>ee(e,"openai")?[`OpenAI subscription: OpenCode's built-in ChatGPT Pro/Plus OAuth is ${t?"detected":"not signed in yet (run `opencode auth login`)"}. Its Codex endpoint is hard-coded to chatgpt.com, so provider.baseURL cannot redirect it. Connect leaves machine networking untouched. Use the Codex app/CLI/IDE for ChatGPT subscription pass-through, or sign OpenCode into an API-key/Copilot provider that Connect can route.`]:[],vN=e=>Wf(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."]:[],SN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Tf);let o=!1;if(n)if("mcp"in r&&!W(r.mcp))o=!0;else{let w=W(r.mcp)?{...r.mcp}:{},b=w[Nn];b!==void 0&&!Gs(b)?o=!0:(w[Nn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=w)}else if(W(r.mcp)&&Gs(r.mcp[Nn])){let w={...r.mcp};delete w[Nn],Object.keys(w).length===0?delete r.mcp:r.mcp=w}let a=W(r.provider)?{...r.provider}:{},s=gN(a,t.origin),i=s.every(w=>wN(a[w],e,w))?s:[],c=s.filter(w=>!i.includes(w)),l=[];if(i.length>0){for(let w of i)delete a[w];r=$f(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,m=fe({...t.metadata,tool:"opencode"});for(let w of c){let b={...a[w]},k={...b.options};if("headers"in k&&!W(k.headers)){u.push(w);continue}let C=W(k.headers)?{...k.headers}:{},S=!1;for(let[E,I]of[[Lt,p],...m?[[$n,m]]:[]])E in C?(typeof C[E]!="string"||C[E].trim()==="")&&u.push(`${w}.${E}`):(C[E]=I,d.push(`${w}.${E}`),S=!0);S&&(k.headers=C,b.options=k,a[w]=b)}let y=c.length>0?[]:wr.filter(w=>w!=="openai"||!ee(t,"openai")),g=t.byoUpstream;for(let w of y){let b=W(a[w])?{...a[w]}:{},k=W(b.options)?{...b.options}:{};k.baseURL=f;let C=W(k.headers)?{...k.headers}:{};if(w==="anthropic"&&g)k.apiKey=g.key,C[Ln]=`Bearer ${g.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=g.url;else{k.apiKey=p,"x-anyray-custom-host"in C&&delete C[Ln];for(let S of _f)delete C[S]}C[Lt]=p,m&&(C[$n]=m),k.headers=C,b.options=k,a[w]=b}let h=c.length===0&&Wf(t);if(h){let w=W(a[Mn])?{...a[Mn]}:{},b=W(w.options)?{...w.options}:{};b.baseURL=Df(t);let k=W(b.headers)?{...b.headers}:{};k[Lt]=t.clientKey,m&&(k[$n]=m),b.headers=k,w.options=b,a[Mn]=w}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:h,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},EN=["baseURL","apiKey"],_C=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!W(s)||!W(s.options))return!1;let i={...s},c={...s.options},l=!1;if(n){let d=typeof c.baseURL=="string"&&c.baseURL.includes("/v1/copilot/"),u=W(c.headers)?{...c.headers}:void 0,f=u?.[Lt],p=bl(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let m=u,y=W(r)?r.options:void 0,g=W(y)&&W(y.headers)?y.headers:void 0;for(let h of[Lt,$n])g&&h in g?m[h]!==g[h]&&(m[h]=g[h],l=!0):h in m&&(delete m[h],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}else{let d=W(r)?r.options:void 0,u=W(d)?d:{},f=W(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Lt]=="string"||typeof f[$n]=="string"||_f.some(m=>m in f);if(!o&&!p)return!1;for(let m of EN)m in u?c[m]!==u[m]&&(c[m]=u[m],l=!0):m in c&&(delete c[m],l=!0);if(W(c.headers)){let m={...c.headers},y=W(u.headers)?u.headers:{};"x-anyray-custom-host"in m&&Ln in m&&(Ln in y?m[Ln]!==y[Ln]&&(m[Ln]=y[Ln],l=!0):(delete m[Ln],l=!0));for(let g of[Lt,$n,..._f])g in y?m[g]!==y[g]&&(m[g]=y[g],l=!0):g in m&&(delete m[g],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}return l?(Object.keys(c).length===0?delete i.options:i.options=c,Object.keys(i).length===0?delete e[t]:e[t]=i,!0):!1},IN=(e,t,n)=>{let r=e[t];if(!W(r)||!W(r.options)||!W(n)||!W(n.options))return!1;let o={...r.options};if(!W(o.headers)||"headers"in n.options&&!W(n.options.headers))return!1;let a={...o.headers},s=W(n.options.headers)?n.options.headers:{},i=!1;return!(Lt in s)&&bl(a[Lt])&&(delete a[Lt],i=!0),!($n in s)&&AN(a[$n])&&(delete a[$n],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},xN=(e,t)=>{let n={...e},r=!1,o=bN(e.provider);if(W(n.mcp)&&Gs(n.mcp[Nn])){let c={...n.mcp};delete c[Nn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!W(n.provider))return{next:n,removed:r};let a={...n.provider},s=W(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Tf&&wr.every(c=>{let l=a[c];return W(l)&&W(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of wr)_C(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...wr,Mn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;IN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&W(u)&&W(u.options)&&Bf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Mf(n,t,l))}return _C(a,Mn,!0,s[Mn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Tf&&(delete n.$schema,r=!0),{next:n,removed:r}},MC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=Al(),t=LC(),n=await x(e)||await x(t),r=n&&await OC();return{installed:n,detail:n?`${await TC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await TC(),r=e.openaiBaseUrl,o=fe({...e.metadata,tool:"opencode"}),a=Wf(e),s=ee(e,"openai"),i=await OC(),c;try{c=await Ke(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(Df(e))}, "headers": { "${Lt}": "<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 Fr()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:m,customHeaderConflicts:y,mcpConflict:g}=SN(c.data,e,l),h=u.length>0,w=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(I=>`provider.${I}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...p.length>0?[`Updated model references: ${p.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=h?[`${n} already routes through ${e.origin} via ${u.map(I=>`provider.${I}`).join(", ")}; existing provider values were preserved.`,m.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${m.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...y.length>0?[`Could not safely add required headers at ${y.join(", ")} because the existing values have incompatible shapes. Fix those values manually; no existing value was replaced.`]:[],"Canonical anthropic, openai, and github-copilot provider blocks were left untouched.","Restart OpenCode (or start a new session) to pick up the change."]:[...w,s?`${n} \u2192 provider.anthropic options.baseURL = ${r}; provider.openai left untouched because OpenCode's ChatGPT OAuth loader has no configurable endpoint.`:`${n} \u2192 provider.anthropic + provider.openai options.baseURL = ${r}`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${o??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...CN(e),...kN(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Df(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).",...vN(e),"Restart OpenCode (or start a new session) to pick up the change."];g?b.push(`MCP name conflict in ${n}: mcp.${Nn} is not owned by Anyray Connect, so it was left untouched.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let k=y.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let S=await dn(n,c,d,!0)?[n]:[],E=wl();if(ne())try{let I=await RC(E,ds(Ye,["opencode"]));I==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${E} already exists and is not owned by Anyray.`):(I==="installed"&&S.push(E),b.push(`The OpenCode tool.execute.after carrier is active in ${E}; 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 ${E}. Gateway-side optimization remains active.`)}else{try{await Of(E)==="removed"&&S.push(E)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${_e()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:k,messages:b,changedFiles:S}},async pointsAt(e){for(let t of await ta())try{let{data:n}=await Ke(t);if(!W(n.provider))continue;for(let r of Object.values(n.provider))if(!(!W(r)||!W(r.options))&&Bf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await ta();if(e.length===0)return{registered:!1,command:null,reason:"no-config"};let t=!1,n=!1;for(let r of e)try{let{data:o}=await Ke(r);if(!W(o.mcp))continue;let a=o.mcp[Nn];if(!Gs(a)||!W(a)){a!==void 0&&(t=!0);continue}return{registered:!0,command:Array.isArray(a.command)&&typeof a.command[0]=="string"?a.command[0]:null}}catch{n=!0}return{registered:!1,command:null,reason:t?"foreign":n?"unreadable":"absent"}},async integrationStatus(){let e,t=!0;try{let i=await Hs(wl());e=i==="absent"?"missing":i,e==="owned"&&(t=await DC(wl(),"utf-8")===Rf(ds(Ye,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await ta()){let c;try{c=await Ke(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!W(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Nn];if(l!==void 0)if(Gs(l))if(n=!0,!W(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;cc({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 Fr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await NC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await ta()){let{data:o}=await Ke(r);if(W(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!W(s)||!W(s.options)){e.add("unknown");continue}let i=s.options,c=W(i.headers)?i.headers:{};if(a===Mn&&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===Mn&&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(bl(c[Lt])||bl(i.apiKey)||typeof i.apiKey=="string"&&i.apiKey.length>0||typeof c.Authorization=="string"&&c.Authorization.length>0){e.add("api_key");continue}e.add("unknown")}}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=await ta(),n=wl(),r="absent";try{r=await Hs(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 Ke(i)}catch{s.push(i);continue}let{next:l,removed:d}=xN(c.data,await Zo(i));d&&(await dn(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await ce(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 Of(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 Zf}from"node:os";import{join as Il}from"node:path";import{homedir as RN}from"node:os";import{dirname as ON,join as Ar}from"node:path";import{mkdir as TN,readdir as _N,readFile as FC,rm as WC}from"node:fs/promises";var Uf="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",BC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsY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CA9PT0gJ3N0cmluZycgPyBvcHRzLnNlc3Npb25JZCA6IHVuZGVmaW5lZDsKICAgIGNvbnN0IGNhbGxlck9uUGF5bG9hZCA9IG9wdHMub25QYXlsb2FkOwogICAgb3B0cy5vblBheWxvYWQgPSBhc3luYyAocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA9PiB7CiAgICAgIGlmIChwYXlsb2FkICYmIHR5cGVvZiBwYXlsb2FkID09PSAnb2JqZWN0JyAmJiAhQXJyYXkuaXNBcnJheShwYXlsb2FkKSkgewogICAgICAgIHBhdGNoUGF5bG9hZFNlc3Npb25JZGVudGl0eSgKICAgICAgICAgIHBheWxvYWQgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4sCiAgICAgICAgICBzZXNzaW9uSWQKICAgICAgICApOwogICAgICB9CiAgICAgIHJldHVybiBjYWxsZXJPblBheWxvYWQgPyBjYWxsZXJPblBheWxvYWQocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Hf=".anyray-source-sha",wn=()=>Ar(RN(),".anyray","openclaw-plugin"),UC=async(e=wn())=>{try{if((await FC(Ar(e,Hf),"utf8")).trim()===Uf)return"current"}catch{}for(let t of BC){let n=Ar(e,t.path);await TN(ON(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(Ar(e,Hf),`${Uf}
|
|
170
|
-
`),"installed"},Vs=async(e,t=[])=>{let n=[],r=async a=>{let s=Ar(a,"plugins","anyray","catalog.json");try{await WC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await _N(Ar(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(Ar(e,"agents",a,"agent"));return n},Cl=async(e=wn())=>{try{await FC(Ar(e,Hf),"utf8")}catch{return!1}return await WC(e,{recursive:!0,force:!0}),!0};var Vf="x-anyray-metadata",oa="x-anyray-api-key",Kf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],oo="Authorization",ao="anthropic-beta",vl="interleaved-thinking-2025-05-14",Sl=["anthropic","openai"],GC="short",Yf="anthropic-messages",Jf=32e3,El="anthropic/claude-sonnet-4-5",Xf=["anthropic/claude-haiku-4-5"],zf="anyray/claude-sonnet-4-5",qf=["anyray/claude-haiku-4-5"],PN=[El,zf],DN=[Xf,qf],Je="anyray",Cr="ANYRAY_API_KEY",Ks="openclaw",ra=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Il(Zf(),".openclaw"),na=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Il(ra(),"openclaw.json"),L=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),HC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},jf=e=>{if(!L(e))return{};let t=e.models;return!L(t)||!L(t.providers)?{}:t.providers},LN=e=>e==="~"||e.startsWith("~/")?Il(Zf(),e.slice(1)):e,kl=e=>{if(!L(e))return[];let t=e.agents;if(!L(t)||!Array.isArray(t.list))return[];let n=[];for(let r of t.list){if(!L(r))continue;let o=typeof r.agentDir=="string"?r.agentDir.trim():"";o&&n.push(LN(o))}return n},NN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=fe({...t.metadata,tool:Ks}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!L(l.models)&&d.push("models");let u=L(l.models)?{...l.models}:{};if("providers"in u&&!L(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=L(u.providers)?{...u.providers}:{},p=!1;if(n){let C=L(l.plugins)?{...l.plugins}:{},S=L(C.load)?{...C.load}:{},E=L(C.entries)?{...C.entries}:{},I=L(E[Je])?{...E[Je]}:{},O=L(I.config)?{...I.config}:{};if("plugins"in l&&!L(l.plugins)||"load"in C&&!L(C.load)||"paths"in S&&!Array.isArray(S.paths)||"entries"in C&&!L(C.entries)||Je in E&&!L(E[Je])||"config"in I&&!L(I.config)||"env"in l&&!L(l.env))d.push("plugins");else{let T=Array.isArray(S.paths)?[...S.paths]:[];T.includes(n)||T.push(n),S.paths=T,C.load=S,I.enabled=!0,O.gatewayUrl=t.anthropicBaseUrl,O.apiKey=r;let U=t.metadata.user,z=t.metadata.team;U&&(O.user=U),z&&(O.team=z),I.config=O,E[Je]=I,C.entries=E,l.plugins=C;let K=L(l.env)?{...l.env}:{};K[Cr]=r,l.env=K,p=!0}}let m=Sl.filter(C=>C!=="openai"||!ee(t,"openai"));for(let C of m){if(C in f&&!L(f[C])){d.push(`models.providers.${C}`);continue}let S=L(f[C])?{...f[C]}:{};if("headers"in S&&!L(S.headers)){i.push(C);continue}let E=L(S.headers)?{...S.headers}:{};if(S.baseUrl=C==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,C==="anthropic"&&(S.api=Yf,(typeof S.maxTokens!="number"||S.maxTokens<=0)&&(S.maxTokens=Jf)),C==="anthropic"&&a)S.apiKey=a.key,E[oo]=`Bearer ${a.key}`,E["x-anyray-provider"]="anthropic",E["x-anyray-auth-mode"]="passthrough",E["x-anyray-custom-host"]=a.url;else{S.apiKey=r,"x-anyray-custom-host"in E&&delete E[oo];for(let I of Kf)delete E[I]}E[oa]=r,o&&(E[Vf]=o),C==="anthropic"&&(ao in E?c=E[ao]!==vl:E[ao]=vl),S.headers=E,f[C]=S,s.push(C)}u.providers=f,l.models=u;let y=!1,g=!1,h=!1,w,b=[],k="agents"in l&&!L(l.agents)||L(l.agents)&&"defaults"in l.agents&&!L(l.agents.defaults)||L(l.agents)&&L(l.agents.defaults)&&("params"in l.agents.defaults&&!L(l.agents.defaults.params)||"model"in l.agents.defaults&&!L(l.agents.defaults.model));if(k&&d.push("agents.defaults"),s.includes("anthropic")&&!k){let C=L(l.agents)?{...l.agents}:{},S=L(C.defaults)?{...C.defaults}:{},E=L(S.params)?{...S.params}:{};"cacheRetention"in E||(E.cacheRetention=GC,y=!0,S.params=E);let I=L(S.model)?{...S.model}:{},O=p?[...s,Je]:s,T=U=>typeof U=="string"&&O.some(z=>U.startsWith(`${z}/`));typeof I.primary!="string"||I.primary.trim()===""?(I.primary=p?zf:El,g=!0,S.model=I,"fallbacks"in I||(I.fallbacks=p?[...qf]:[...Xf],h=!0)):T(I.primary)||(w=I.primary),b=(Array.isArray(I.fallbacks)?I.fallbacks:[]).filter(U=>typeof U=="string"&&!T(U)),(y||g)&&(C.defaults=S,l.agents=C)}return{next:l,routed:s,cacheRetentionSeeded:y,betaPreserved:c,headerConflicts:i,primarySeeded:g,fallbacksSeeded:h,unroutedPrimary:w,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},$N=["baseUrl","apiKey","api","maxTokens"],Gf=(e,t,n=Sl,r)=>{let o={...e},a=!("models"in o)||L(o.models)&&(!("providers"in o.models)||L(o.models.providers)),s=L(o.models)?{...o.models}:{},i=L(s.providers)?{...s.providers}:{},c=jf(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!L(f))continue;let p={...f},m=L(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof m[oa]=="string"||typeof m[Vf]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Kf.some(C=>C in m)))continue;let g=L(c[u])?c[u]:{},h=L(g.headers)?g.headers:{},w="x-anyray-custom-host"in m,b=C=>C==="api"?p.api===Yf:C==="maxTokens"?p.maxTokens===Jf:C==="apiKey"?w||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let C of $N)b(C)&&(C in g?p[C]!==g[C]&&(p[C]=g[C],l=!0):C in p&&(delete p[C],l=!0));let k=[oa,Vf,...Kf,..."x-anyray-custom-host"in m?[oo]:[]];m[ao]===vl&&k.push(ao);for(let C of k)C in h?m[C]!==h[C]&&(m[C]=h[C],l=!0):C in m&&(delete m[C],l=!0);oo in h&&!(oo in m)&&(m[oo]=h[oo],l=!0),Object.keys(m).length===0?delete p.headers:p.headers=m,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=L(o.plugins)?{...o.plugins}:{},f=L(u.load)?{...u.load}:{},p=L(u.entries)?{...u.entries}:{};if((!("plugins"in o)||L(o.plugins))&&(!("load"in u)||L(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||L(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let g=f.paths.filter(h=>h!==r);g.length===0?delete f.paths:f.paths=g,l=!0}let y=p[Je];if(L(y)){let g=L(y.config)?y.config:{};if(t!==void 0||typeof g.apiKey=="string"&&g.apiKey.startsWith("ark_")){let w=L(t?.plugins)?t.plugins:{},b=L(w.entries)?w.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,L(o.env)){let g={...o.env},h=g[Cr];if(typeof h=="string"&&h.startsWith("ark_")){let w=L(t?.env)?t.env:{};Cr in w?g[Cr]!==w[Cr]&&(g[Cr]=w[Cr],l=!0):(delete g[Cr],l=!0),Object.keys(g).length===0?delete o.env:o.env=g}}}}let d=!("agents"in o)||L(o.agents)&&(!("defaults"in o.agents)||L(o.agents.defaults)&&(!("params"in o.agents.defaults)||L(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||L(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=L(o.agents)?{...o.agents}:{},f=L(u.defaults)?{...u.defaults}:{},p=L(f.params)?{...f.params}:{},m=L(t.agents)?t.agents:{},y=L(m.defaults)?m.defaults:{},g=L(y.params)?y.params:{};p.cacheRetention===GC&&("cacheRetention"in g?p.cacheRetention!==g.cacheRetention&&(p.cacheRetention=g.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let h=L(f.model)?{...f.model}:{},w=L(y.model)?y.model:{};PN.includes(h.primary)&&("primary"in w?h.primary!==w.primary&&(h.primary=w.primary,l=!0):(delete h.primary,l=!0)),DN.some(b=>JSON.stringify(h.fallbacks)===JSON.stringify(b))&&("fallbacks"in w?JSON.stringify(h.fallbacks)!==JSON.stringify(w.fallbacks)&&(h.fallbacks=w.fallbacks,l=!0):(delete h.fallbacks,l=!0)),Object.keys(h).length===0?delete f.model:f.model=h,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}},VC={id:Ks,title:"OpenClaw",automatic:!0,async detect(){let e=await x(na())||await x(ra());return{installed:e,detail:e?na():`no ${Il(Zf(),".openclaw")} state dir`}},async apply(e,t){let n=na();if(!e.byoUpstream&&ee(e,"anthropic")){let S=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${Ks}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],E;try{E=await Ke(n)}catch{return{status:"held",messages:S}}let{next:I,removed:O}=Gf(E.data,await Zo(n),Sl,wn());return O?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...S]}:(await dn(n,E,I,!1),await ce(n),await Cl(),await Vs(ra(),kl(I)),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...S]}):(t.dryRun||(await Cl(),await Vs(ra(),kl(I))),{status:"held",messages:S})}let r=wn(),o=!1;if(!t.dryRun)try{await UC(r)}catch{r=void 0,o=!0}let a;try{a=await Ke(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Yf}", "maxTokens": ${Jf}, "apiKey": "<your personal ark_ key>", "headers": { "${oa}": "<your personal ark_ key>", "${ao}": "${vl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${oa}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${El}") 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:m,structureConflicts:y,pluginConfigured:g}=NN(a.data,e,r),h=s,w=!1;if(!i.includes("openai")){let S=Gf(h,await Zo(n),["openai"]);S.removed&&(h=S.next,w=!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: ${fe({...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 ${ao} 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 = ${g?zf:El} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(g?qf:Xf).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.`]:[],...m.length>0?[`Fallback model(s) ${m.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...w?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...g?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${wn()}) 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 ${wn()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...y.length>0?[`Left ${y.join(", ")} untouched: the existing value has the wrong shape (array or null where an object belongs), and OpenClaw's strict schema will refuse it as-is. Fix the shape and re-run.`]:[],"OpenClaw hot-reloads model config; run `openclaw config validate` to confirm the merged config passes its strict schema."],k=d.length>0||y.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let C=await dn(n,a,h,!0);return g&&await Vs(ra(),kl(h)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await Ke(na());for(let a of Object.values(jf(t)))if(L(a)&&HC(a.baseUrl,e))return!0;let n=L(t.plugins)?t.plugins:{},o=(L(n.entries)?n.entries:{})[Je];if(L(o)&&L(o.config)&&HC(o.config.gatewayUrl,e))return!0}catch{}return!1},async routingExpected(e){return e.includes(Ks)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Ke(na());for(let a of Object.values(jf(t))){if(!L(a))continue;let s=L(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[oa]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=L(t.plugins)?t.plugins:{},o=(L(n.entries)?n.entries:{})[Je];if(L(o)&&L(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=na();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Ke(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}=Gf(n.data,await Zo(t),Sl,wn()),a=await Cl();return await Vs(ra(),kl(r)),o?(await dn(t,n,r,!1),await ce(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${wn()}`]:[]],changedFiles:[t]}):(await ce(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${wn()}`]:[]]})}};import{execFile as IB}from"node:child_process";import{readFile as xB}from"node:fs/promises";import{homedir as di,platform as Er}from"node:os";import{join as kn}from"node:path";import{isDeepStrictEqual as Bm,promisify as RB}from"node:util";var js=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},xl=(e,t)=>{let n=js(e),r=js(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 GM}from"node:crypto";import{promises as nv}from"node:fs";import{platform as VM,tmpdir as KM}from"node:os";import{join as Kl}from"node:path";import{execFile as MN}from"node:child_process";import{promises as Zs}from"node:fs";import{homedir as BN,platform as FN}from"node:os";import{delimiter as WN,join as Rl}from"node:path";import{promisify as UN}from"node:util";var HN=UN(MN),GN=15*6e4,VN=64*1024*1024,KN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],KC=async(e={})=>{let t=(e.home??BN)(),n=e.env??process.env,r=KN(e.runtimePlatform??FN()),o=[Rl(t,".local","bin"),Rl(t,".claude","local"),...(n.PATH??"").split(WN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Rl(a,`claude${s}`);try{return await Zs.access(i),i}catch{}}return null},jN=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},ZN=async e=>{let t=Rl(e,"projects"),n;try{n=(await Zs.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return[]}let r=[];for(let o of n){let a=o.slice(-36);if(!XN.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},YN=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:jN(n.projectList)}},JN=async e=>{let t,n;try{let r=await Zs.readFile(e,"utf8");for(let o of r.split(`
|
|
171
|
-
`)){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}},
|
|
172
|
-
`).filter(d=>d.trim().length>0),i=YN(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 JN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await ZN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as QN}from"node:crypto";import{promises as Bn}from"node:fs";import{homedir as e$,platform as t$}from"node:os";import{join as kt}from"node:path";var ZC=448,Fn="local_",n$="local-agent-mode-sessions",Qf="-3p",r$="cowork_account_settings.json",so=(e={})=>{let t=(e.home??e$)(),n=e.runtimePlatform??t$(),r=e.env??process.env;if(n==="darwin")return kt(t,"Library","Application Support",`Claude${Qf}`);if(n==="win32"){let o=r.LOCALAPPDATA??kt(t,"AppData","Local");return kt(o,`Claude${Qf}`)}return null},Ys=(e={})=>{let t=so(e);return t?t.slice(0,-Qf.length):null},em=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)}`},Ol=async e=>{let t=kt(e,n$),n;try{n=(await Bn.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 Bn.readdir(kt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=kt(t,o,s);try{await Bn.access(kt(i,r$)),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]}},tm=async e=>{try{let t=await Bn.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}},aa=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),o$=async(e,t)=>{let n=`${Fn}${t.sessionId}`,r=kt(e,n),o=kt(r,"outputs"),a=kt(r,".claude"),s=kt(a,"projects",em(o));await Bn.mkdir(o,{recursive:!0,mode:ZC}),await Bn.mkdir(s,{recursive:!0,mode:ZC});let i=kt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${QN()}`;await Bn.copyFile(t.transcriptPath,c),await Bn.chmod(c,384),await Bn.rename(c,i);let l=t.createdAt??Date.now();await J(kt(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})},YC=async(e,t)=>{let n=await tm(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!aa(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await o$(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as sa}from"node:fs";import{homedir as a$}from"node:os";import{dirname as s$,join as Js}from"node:path";var i$=448,c$=["Documents","Claude","Projects"],l$="spaces.json",d$=(e={})=>Js((e.home??a$)(),...c$),u$=async e=>{try{let t=JSON.parse(await sa.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}}},p$=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},nm=async e=>{try{return await sa.access(e),!0}catch{return!1}},f$=async(e,t,n)=>{let r=Js(t,p$(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await nm(r)?o:r;return a===o&&await nm(o)?null:(await sa.mkdir(s$(a),{recursive:!0}),await sa.cp(e,a,{recursive:!0}),a)},m$=async e=>{try{let t=(await sa.readFile(Js(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},JC=async e=>{let t=d$({home:e.home}),n={imported:0,alreadyPresent:0,skippedCollision:0,failed:0,root:t},r=e.projects??[];if(r.length===0)return n;let o=Js(e.storageDir,l$),{spaces:a,readable:s}=await u$(o);if(!s)return n.failed=r.length,n;let i=new Set(a.map(l=>l.id)),c=[];for(let l of r){if(i.has(l.uuid)){n.alreadyPresent+=1;continue}let d=Js(e.stagedProjectsDir,l.dirName);try{if(!await nm(d)){n.failed+=1;continue}let u=await f$(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await m$(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 sa.mkdir(e.storageDir,{recursive:!0,mode:i$}),await J(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as w$}from"node:crypto";import{execFile as b$,spawnSync as sk}from"node:child_process";import{constants as ik}from"node:fs";import{access as Nl,chmod as A$,mkdir as C$,readdir as k$,readFile as om,rename as v$,rm as ia,stat as ck,writeFile as S$}from"node:fs/promises";import{homedir as E$,platform as I$,userInfo as x$}from"node:os";import{basename as R$,dirname as lk,isAbsolute as ca,join as Nt,resolve as ek}from"node:path";import{isDeepStrictEqual as zs,promisify as O$}from"node:util";var kr="__anyray-claude-desktop-credential",Xs="__anyray-claude-desktop-bootstrap-headers";var Tl=["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>`."],_l=["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."],XC="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 Pl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],zC=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapHeaders","bootstrapHeadersHelper","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],h$=new Set(zC),y$=new Set(zC.map(e=>e.toLowerCase())),g$=new Set(Pl.map(e=>e.toLowerCase())),Dl=(e,t=!1)=>(t?y$:h$).has(t?e.toLowerCase():e),qC=(e,t=!1)=>t?g$.has(e.toLowerCase()):Pl.some(n=>n===e),QC=["*"],io=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...QC]}),vr=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var qs=/^[a-f0-9-]{36}$/,dk="Anyray",am=4,ti=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],ni=["deploymentMode","awaitingSignIn"],uk=[...ti,...ni,"configLibrary","_meta.json"],bn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),st=e=>structuredClone(e),Qs=async e=>{try{return await Nl(e),!0}catch{return!1}},T$=async e=>{try{let t=await k$(lk(e)),n=R$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},_$=async e=>{try{return await Nl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":T$(e)}},Yt=(e={})=>{let t=(e.home??E$)(),n=(e.username??(()=>x$().username))(),r=Nt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Nt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Nt(r,"configLibrary"),meta:Nt(r,"configLibrary","_meta.json"),appConfig:Nt(r,"claude_desktop_config.json"),helper:Nt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Nt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},$l=()=>{let e=sk("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},pk=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],P$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...pk(t)]}},sm=(e="json")=>{let t=nn(pk(e)),n=ek(t.command),r=ek(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ne()&&(!o||r!==n)}},D$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,im=e=>[e.command,...e.args].map(D$).join(" "),L$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ca(e.command))throw new Error("the credential helper executable is not absolute")},fk=(e,t)=>{L$(e);let n=Ml(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!ca(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},mk=e=>(fk(e,"--json"),`#!/bin/sh
|
|
173
|
-
exec ${
|
|
174
|
-
`),
|
|
175
|
-
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,
|
|
176
|
-
`)}
|
|
168
|
+
`,Hs=async e=>await x(e)?(await RC(e,"utf-8")).startsWith(`${OC}
|
|
169
|
+
`)?"owned":"foreign":"absent",TC=async(e,t)=>{let n=Of(t),r=await Hs(e);return r==="foreign"?"foreign":r==="owned"&&await RC(e,"utf-8")===n?"unchanged":(await we(e,n),"installed")},Tf=async e=>{let t=await Hs(e);return t!=="owned"?t:(await fN(e,{force:!0}),"removed")};var _f="https://opencode.ai/config.json",$n="x-anyray-metadata",Lt="x-anyray-api-key",Pf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Ln="Authorization",wr=["anthropic","openai"],Mn="github-copilot",hN="header",Nn="anyray",yN=()=>process.env.XDG_CONFIG_HOME?.trim()||br(LC(),".config"),gN=()=>process.env.XDG_DATA_HOME?.trim()||br(LC(),".local","share"),Al=()=>br(yN(),"opencode"),wl=()=>br(Al(),"plugins","anyrayTrim.js"),$C=()=>br(gN(),"opencode"),MC=async()=>{try{let e=await NC(br($C(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return W(t)?{chatGptOAuth:W(t.openai)&&t.openai.type==="oauth",readable:!0}:{chatGptOAuth:!1,readable:!1}}catch(e){return e.code==="ENOENT"?{chatGptOAuth:!1,readable:!0}:{chatGptOAuth:!1,readable:!1}}},_C=async()=>(await MC()).chatGptOAuth,wN=["opencode.jsonc","opencode.json","config.json"],ta=async()=>{let e=Al(),t=[];for(let n of wN){let r=br(e,n);await x(r)&&t.push(r)}return t},PC=async()=>(await ta())[0]??br(Al(),"opencode.json"),Df=()=>dC(process.env.ANYRAY_COPILOT_PLAN),Lf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Df()}/${hN}`,W=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ff=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},bN=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===wr[0]||n===wr[1]||n===Mn?[]:W(r)&&W(r.options)&&Ff(r.options.baseURL,t)?[n]:[]),Nf=/claude/i,Wf=["model","small_model"],BC=(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)||!Nf.test(o)))return`${wr[0]}/${o}`},$f=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)$f(n,t);return t}if(!W(e))return t;for(let[n,r]of Object.entries(e))Wf.includes(n)&&typeof r=="string"?t.push(r):$f(r,t);return t},AN=(e,t,n)=>{if(!W(e)||!W(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Nf.test(a)))return!1;let o=`${n}/`;return $f(t).filter(a=>a.startsWith(o)).every(a=>Nf.test(a.slice(o.length)))},Mf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Mf(o,t,n));if(!W(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Wf.includes(o)?BC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Mf(a,t,n)}return r},Bf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Bf(o,t[a],n));if(!W(e)||!W(t))return e;let r={};for(let[o,a]of Object.entries(e))Wf.includes(o)&&typeof a=="string"&&BC(t[o],n)===a?r[o]=t[o]:r[o]=Bf(a,t[o],n);return r},CN=e=>{if(W(e))for(let t of wr){let n=e[t];if(W(n)&&W(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Gs=e=>{if(!W(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Tt({command:t,args:n},"profile")},bl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),kN=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return W(t)&&t.tool==="opencode"}catch{return!1}},Uf=e=>ee(e,"copilot")&&!!e.clientKey,vN=e=>e.byoUpstream?[]:ee(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],SN=(e,t)=>ee(e,"openai")?[`OpenAI subscription: OpenCode's built-in ChatGPT Pro/Plus OAuth is ${t?"detected":"not signed in yet (run `opencode auth login`)"}. Its Codex endpoint is hard-coded to chatgpt.com, so provider.baseURL cannot redirect it. Connect leaves machine networking untouched. Use the Codex app/CLI/IDE for ChatGPT subscription pass-through, or sign OpenCode into an API-key/Copilot provider that Connect can route.`]:[],EN=e=>Uf(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."]:[],IN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=_f);let o=!1;if(n)if("mcp"in r&&!W(r.mcp))o=!0;else{let w=W(r.mcp)?{...r.mcp}:{},b=w[Nn];b!==void 0&&!Gs(b)?o=!0:(w[Nn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=w)}else if(W(r.mcp)&&Gs(r.mcp[Nn])){let w={...r.mcp};delete w[Nn],Object.keys(w).length===0?delete r.mcp:r.mcp=w}let a=W(r.provider)?{...r.provider}:{},s=bN(a,t.origin),i=s.every(w=>AN(a[w],e,w))?s:[],c=s.filter(w=>!i.includes(w)),l=[];if(i.length>0){for(let w of i)delete a[w];r=Mf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,m=fe({...t.metadata,tool:"opencode"});for(let w of c){let b={...a[w]},k={...b.options};if("headers"in k&&!W(k.headers)){u.push(w);continue}let C=W(k.headers)?{...k.headers}:{},S=!1;for(let[E,I]of[[Lt,p],...m?[[$n,m]]:[]])E in C?(typeof C[E]!="string"||C[E].trim()==="")&&u.push(`${w}.${E}`):(C[E]=I,d.push(`${w}.${E}`),S=!0);S&&(k.headers=C,b.options=k,a[w]=b)}let h=c.length>0?[]:wr.filter(w=>w!=="openai"||!ee(t,"openai")),g=t.byoUpstream;for(let w of h){let b=W(a[w])?{...a[w]}:{},k=W(b.options)?{...b.options}:{};k.baseURL=f;let C=W(k.headers)?{...k.headers}:{};if(w==="anthropic"&&g)k.apiKey=g.key,C[Ln]=`Bearer ${g.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=g.url;else{k.apiKey=p,"x-anyray-custom-host"in C&&delete C[Ln];for(let S of Pf)delete C[S]}C[Lt]=p,m&&(C[$n]=m),k.headers=C,b.options=k,a[w]=b}let y=c.length===0&&Uf(t);if(y){let w=W(a[Mn])?{...a[Mn]}:{},b=W(w.options)?{...w.options}:{};b.baseURL=Lf(t);let k=W(b.headers)?{...b.headers}:{};k[Lt]=t.clientKey,m&&(k[$n]=m),b.headers=k,w.options=b,a[Mn]=w}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:y,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},xN=["baseURL","apiKey"],DC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!W(s)||!W(s.options))return!1;let i={...s},c={...s.options},l=!1;if(n){let d=typeof c.baseURL=="string"&&c.baseURL.includes("/v1/copilot/"),u=W(c.headers)?{...c.headers}:void 0,f=u?.[Lt],p=bl(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let m=u,h=W(r)?r.options:void 0,g=W(h)&&W(h.headers)?h.headers:void 0;for(let y of[Lt,$n])g&&y in g?m[y]!==g[y]&&(m[y]=g[y],l=!0):y in m&&(delete m[y],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}else{let d=W(r)?r.options:void 0,u=W(d)?d:{},f=W(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Lt]=="string"||typeof f[$n]=="string"||Pf.some(m=>m in f);if(!o&&!p)return!1;for(let m of xN)m in u?c[m]!==u[m]&&(c[m]=u[m],l=!0):m in c&&(delete c[m],l=!0);if(W(c.headers)){let m={...c.headers},h=W(u.headers)?u.headers:{};"x-anyray-custom-host"in m&&Ln in m&&(Ln in h?m[Ln]!==h[Ln]&&(m[Ln]=h[Ln],l=!0):(delete m[Ln],l=!0));for(let g of[Lt,$n,...Pf])g in h?m[g]!==h[g]&&(m[g]=h[g],l=!0):g in m&&(delete m[g],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}return l?(Object.keys(c).length===0?delete i.options:i.options=c,Object.keys(i).length===0?delete e[t]:e[t]=i,!0):!1},RN=(e,t,n)=>{let r=e[t];if(!W(r)||!W(r.options)||!W(n)||!W(n.options))return!1;let o={...r.options};if(!W(o.headers)||"headers"in n.options&&!W(n.options.headers))return!1;let a={...o.headers},s=W(n.options.headers)?n.options.headers:{},i=!1;return!(Lt in s)&&bl(a[Lt])&&(delete a[Lt],i=!0),!($n in s)&&kN(a[$n])&&(delete a[$n],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},ON=(e,t)=>{let n={...e},r=!1,o=CN(e.provider);if(W(n.mcp)&&Gs(n.mcp[Nn])){let c={...n.mcp};delete c[Nn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!W(n.provider))return{next:n,removed:r};let a={...n.provider},s=W(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===_f&&wr.every(c=>{let l=a[c];return W(l)&&W(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of wr)DC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...wr,Mn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;RN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&W(u)&&W(u.options)&&Ff(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Bf(n,t,l))}return DC(a,Mn,!0,s[Mn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===_f&&(delete n.$schema,r=!0),{next:n,removed:r}},FC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=Al(),t=$C(),n=await x(e)||await x(t),r=n&&await _C();return{installed:n,detail:n?`${await PC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await PC(),r=e.openaiBaseUrl,o=fe({...e.metadata,tool:"opencode"}),a=Uf(e),s=ee(e,"openai"),i=await _C(),c;try{c=await Ke(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(Lf(e))}, "headers": { "${Lt}": "<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 Fr()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:m,customHeaderConflicts:h,mcpConflict:g}=IN(c.data,e,l),y=u.length>0,w=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(I=>`provider.${I}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...p.length>0?[`Updated model references: ${p.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=y?[`${n} already routes through ${e.origin} via ${u.map(I=>`provider.${I}`).join(", ")}; existing provider values were preserved.`,m.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${m.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...h.length>0?[`Could not safely add required headers at ${h.join(", ")} because the existing values have incompatible shapes. Fix those values manually; no existing value was replaced.`]:[],"Canonical anthropic, openai, and github-copilot provider blocks were left untouched.","Restart OpenCode (or start a new session) to pick up the change."]:[...w,s?`${n} \u2192 provider.anthropic options.baseURL = ${r}; provider.openai left untouched because OpenCode's ChatGPT OAuth loader has no configurable endpoint.`:`${n} \u2192 provider.anthropic + provider.openai options.baseURL = ${r}`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${o??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...vN(e),...SN(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Lf(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. ${Df()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Df()} 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).",...EN(e),"Restart OpenCode (or start a new session) to pick up the change."];g?b.push(`MCP name conflict in ${n}: mcp.${Nn} is not owned by Anyray Connect, so it was left untouched.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let k=h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let S=await dn(n,c,d,!0)?[n]:[],E=wl();if(ne())try{let I=await TC(E,ds(Ye,["opencode"]));I==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${E} already exists and is not owned by Anyray.`):(I==="installed"&&S.push(E),b.push(`The OpenCode tool.execute.after carrier is active in ${E}; 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 ${E}. Gateway-side optimization remains active.`)}else{try{await Tf(E)==="removed"&&S.push(E)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${_e()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:k,messages:b,changedFiles:S}},async pointsAt(e){for(let t of await ta())try{let{data:n}=await Ke(t);if(!W(n.provider))continue;for(let r of Object.values(n.provider))if(!(!W(r)||!W(r.options))&&Ff(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){if(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await ta();if(e.length===0)return{registered:!1,command:null,reason:"no-config"};let t=!1,n=!1;for(let r of e)try{let{data:o}=await Ke(r);if(!W(o.mcp))continue;let a=o.mcp[Nn];if(!Gs(a)||!W(a)){a!==void 0&&(t=!0);continue}return{registered:!0,command:Array.isArray(a.command)&&typeof a.command[0]=="string"?a.command[0]:null}}catch{n=!0}return{registered:!1,command:null,reason:t?"foreign":n?"unreadable":"absent"}},async integrationStatus(){let e,t=!0;try{let i=await Hs(wl());e=i==="absent"?"missing":i,e==="owned"&&(t=await NC(wl(),"utf-8")===Of(ds(Ye,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await ta()){let c;try{c=await Ke(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!W(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Nn];if(l!==void 0)if(Gs(l))if(n=!0,!W(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;cc({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 Fr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await MC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await ta()){let{data:o}=await Ke(r);if(W(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!W(s)||!W(s.options)){e.add("unknown");continue}let i=s.options,c=W(i.headers)?i.headers:{};if(a===Mn&&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===Mn&&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(bl(c[Lt])||bl(i.apiKey)||typeof i.apiKey=="string"&&i.apiKey.length>0||typeof c.Authorization=="string"&&c.Authorization.length>0){e.add("api_key");continue}e.add("unknown")}}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=await ta(),n=wl(),r="absent";try{r=await Hs(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 Ke(i)}catch{s.push(i);continue}let{next:l,removed:d}=ON(c.data,await Zo(i));d&&(await dn(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await ce(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 Tf(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 Yf}from"node:os";import{join as Il}from"node:path";import{homedir as TN}from"node:os";import{dirname as _N,join as Ar}from"node:path";import{mkdir as PN,readdir as DN,readFile as UC,rm as HC}from"node:fs/promises";var Hf="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",WC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2U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aW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJEZXBlbmRlbmNpZXMiOiB7CiAgICAib3BlbmNsYXciOiAiPj0yMDI2LjcuMSIKICB9LAogICJkZXZEZXBlbmRlbmNpZXMiOiB7CiAgICAidHN4IjogIl40LjIzLjEyIiwKICAgICJ0eXBlc2NyaXB0Ijog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iB1bmRlZmluZWQ7CiAgICBpZiAoZ2F0ZXdheVByb3ZpZGVyICYmIGhlYWRlcnNbJ3gtYW55cmF5LXByb3ZpZGVyJ10gPT09IHVuZGVmaW5lZCkgewogICAgICBoZWFkZXJzWyd4LWFueXJheS1wcm92aWRlciddID0gZ2F0ZXdheVByb3ZpZGVyOwogICAgfQogICAgb3B0cy5oZWFkZXJzID0gaGVhZGVyczsKICAgIGNvbnN0IHNlc3Npb25JZCA9CiAgICAgIHR5cGVvZiBvcHRzLnNlc3Npb25JZCA9PT0gJ3N0cmluZycgPyBvcHRzLnNlc3Npb25JZCA6IHVuZGVmaW5lZDsKICAgIGNvbnN0IGNhbGxlck9uUGF5bG9hZCA9IG9wdHMub25QYXlsb2FkOwogICAgb3B0cy5vblBheWxvYWQgPSBhc3luYyAocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA9PiB7CiAgICAgIGlmIChwYXlsb2FkICYmIHR5cGVvZiBwYXlsb2FkID09PSAnb2JqZWN0JyAmJiAhQXJyYXkuaXNBcnJheShwYXlsb2FkKSkgewogICAgICAgIHBhdGNoUGF5bG9hZFNlc3Npb25JZGVudGl0eSgKICAgICAgICAgIHBheWxvYWQgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4sCiAgICAgICAgICBzZXNzaW9uSWQKICAgICAgICApOwogICAgICB9CiAgICAgIHJldHVybiBjYWxsZXJPblBheWxvYWQgPyBjYWxsZXJPblBheWxvYWQocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Gf=".anyray-source-sha",wn=()=>Ar(TN(),".anyray","openclaw-plugin"),GC=async(e=wn())=>{try{if((await UC(Ar(e,Gf),"utf8")).trim()===Hf)return"current"}catch{}for(let t of WC){let n=Ar(e,t.path);await PN(_N(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(Ar(e,Gf),`${Hf}
|
|
170
|
+
`),"installed"},Vs=async(e,t=[])=>{let n=[],r=async a=>{let s=Ar(a,"plugins","anyray","catalog.json");try{await HC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await DN(Ar(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(Ar(e,"agents",a,"agent"));return n},Cl=async(e=wn())=>{try{await UC(Ar(e,Gf),"utf8")}catch{return!1}return await HC(e,{recursive:!0,force:!0}),!0};var Kf="x-anyray-metadata",oa="x-anyray-api-key",jf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],oo="Authorization",ao="anthropic-beta",vl="interleaved-thinking-2025-05-14",Sl=["anthropic","openai"],KC="short",Jf="anthropic-messages",Xf=32e3,El="anthropic/claude-sonnet-4-5",zf=["anthropic/claude-haiku-4-5"],qf="anyray/claude-sonnet-4-5",Qf=["anyray/claude-haiku-4-5"],LN=[El,qf],NN=[zf,Qf],Je="anyray",Cr="ANYRAY_API_KEY",Ks="openclaw",ra=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Il(Yf(),".openclaw"),na=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Il(ra(),"openclaw.json"),L=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),VC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Zf=e=>{if(!L(e))return{};let t=e.models;return!L(t)||!L(t.providers)?{}:t.providers},$N=e=>e==="~"||e.startsWith("~/")?Il(Yf(),e.slice(1)):e,kl=e=>{if(!L(e))return[];let t=e.agents;if(!L(t)||!Array.isArray(t.list))return[];let n=[];for(let r of t.list){if(!L(r))continue;let o=typeof r.agentDir=="string"?r.agentDir.trim():"";o&&n.push($N(o))}return n},MN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=fe({...t.metadata,tool:Ks}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!L(l.models)&&d.push("models");let u=L(l.models)?{...l.models}:{};if("providers"in u&&!L(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=L(u.providers)?{...u.providers}:{},p=!1;if(n){let C=L(l.plugins)?{...l.plugins}:{},S=L(C.load)?{...C.load}:{},E=L(C.entries)?{...C.entries}:{},I=L(E[Je])?{...E[Je]}:{},O=L(I.config)?{...I.config}:{};if("plugins"in l&&!L(l.plugins)||"load"in C&&!L(C.load)||"paths"in S&&!Array.isArray(S.paths)||"entries"in C&&!L(C.entries)||Je in E&&!L(E[Je])||"config"in I&&!L(I.config)||"env"in l&&!L(l.env))d.push("plugins");else{let T=Array.isArray(S.paths)?[...S.paths]:[];T.includes(n)||T.push(n),S.paths=T,C.load=S,I.enabled=!0,O.gatewayUrl=t.anthropicBaseUrl,O.apiKey=r;let U=t.metadata.user,z=t.metadata.team;U&&(O.user=U),z&&(O.team=z),I.config=O,E[Je]=I,C.entries=E,l.plugins=C;let K=L(l.env)?{...l.env}:{};K[Cr]=r,l.env=K,p=!0}}let m=Sl.filter(C=>C!=="openai"||!ee(t,"openai"));for(let C of m){if(C in f&&!L(f[C])){d.push(`models.providers.${C}`);continue}let S=L(f[C])?{...f[C]}:{};if("headers"in S&&!L(S.headers)){i.push(C);continue}let E=L(S.headers)?{...S.headers}:{};if(S.baseUrl=C==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,C==="anthropic"&&(S.api=Jf,(typeof S.maxTokens!="number"||S.maxTokens<=0)&&(S.maxTokens=Xf)),C==="anthropic"&&a)S.apiKey=a.key,E[oo]=`Bearer ${a.key}`,E["x-anyray-provider"]="anthropic",E["x-anyray-auth-mode"]="passthrough",E["x-anyray-custom-host"]=a.url;else{S.apiKey=r,"x-anyray-custom-host"in E&&delete E[oo];for(let I of jf)delete E[I]}E[oa]=r,o&&(E[Kf]=o),C==="anthropic"&&(ao in E?c=E[ao]!==vl:E[ao]=vl),S.headers=E,f[C]=S,s.push(C)}u.providers=f,l.models=u;let h=!1,g=!1,y=!1,w,b=[],k="agents"in l&&!L(l.agents)||L(l.agents)&&"defaults"in l.agents&&!L(l.agents.defaults)||L(l.agents)&&L(l.agents.defaults)&&("params"in l.agents.defaults&&!L(l.agents.defaults.params)||"model"in l.agents.defaults&&!L(l.agents.defaults.model));if(k&&d.push("agents.defaults"),s.includes("anthropic")&&!k){let C=L(l.agents)?{...l.agents}:{},S=L(C.defaults)?{...C.defaults}:{},E=L(S.params)?{...S.params}:{};"cacheRetention"in E||(E.cacheRetention=KC,h=!0,S.params=E);let I=L(S.model)?{...S.model}:{},O=p?[...s,Je]:s,T=U=>typeof U=="string"&&O.some(z=>U.startsWith(`${z}/`));typeof I.primary!="string"||I.primary.trim()===""?(I.primary=p?qf:El,g=!0,S.model=I,"fallbacks"in I||(I.fallbacks=p?[...Qf]:[...zf],y=!0)):T(I.primary)||(w=I.primary),b=(Array.isArray(I.fallbacks)?I.fallbacks:[]).filter(U=>typeof U=="string"&&!T(U)),(h||g)&&(C.defaults=S,l.agents=C)}return{next:l,routed:s,cacheRetentionSeeded:h,betaPreserved:c,headerConflicts:i,primarySeeded:g,fallbacksSeeded:y,unroutedPrimary:w,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},BN=["baseUrl","apiKey","api","maxTokens"],Vf=(e,t,n=Sl,r)=>{let o={...e},a=!("models"in o)||L(o.models)&&(!("providers"in o.models)||L(o.models.providers)),s=L(o.models)?{...o.models}:{},i=L(s.providers)?{...s.providers}:{},c=Zf(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!L(f))continue;let p={...f},m=L(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof m[oa]=="string"||typeof m[Kf]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||jf.some(C=>C in m)))continue;let g=L(c[u])?c[u]:{},y=L(g.headers)?g.headers:{},w="x-anyray-custom-host"in m,b=C=>C==="api"?p.api===Jf:C==="maxTokens"?p.maxTokens===Xf:C==="apiKey"?w||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let C of BN)b(C)&&(C in g?p[C]!==g[C]&&(p[C]=g[C],l=!0):C in p&&(delete p[C],l=!0));let k=[oa,Kf,...jf,..."x-anyray-custom-host"in m?[oo]:[]];m[ao]===vl&&k.push(ao);for(let C of k)C in y?m[C]!==y[C]&&(m[C]=y[C],l=!0):C in m&&(delete m[C],l=!0);oo in y&&!(oo in m)&&(m[oo]=y[oo],l=!0),Object.keys(m).length===0?delete p.headers:p.headers=m,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=L(o.plugins)?{...o.plugins}:{},f=L(u.load)?{...u.load}:{},p=L(u.entries)?{...u.entries}:{};if((!("plugins"in o)||L(o.plugins))&&(!("load"in u)||L(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||L(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let g=f.paths.filter(y=>y!==r);g.length===0?delete f.paths:f.paths=g,l=!0}let h=p[Je];if(L(h)){let g=L(h.config)?h.config:{};if(t!==void 0||typeof g.apiKey=="string"&&g.apiKey.startsWith("ark_")){let w=L(t?.plugins)?t.plugins:{},b=L(w.entries)?w.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,L(o.env)){let g={...o.env},y=g[Cr];if(typeof y=="string"&&y.startsWith("ark_")){let w=L(t?.env)?t.env:{};Cr in w?g[Cr]!==w[Cr]&&(g[Cr]=w[Cr],l=!0):(delete g[Cr],l=!0),Object.keys(g).length===0?delete o.env:o.env=g}}}}let d=!("agents"in o)||L(o.agents)&&(!("defaults"in o.agents)||L(o.agents.defaults)&&(!("params"in o.agents.defaults)||L(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||L(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=L(o.agents)?{...o.agents}:{},f=L(u.defaults)?{...u.defaults}:{},p=L(f.params)?{...f.params}:{},m=L(t.agents)?t.agents:{},h=L(m.defaults)?m.defaults:{},g=L(h.params)?h.params:{};p.cacheRetention===KC&&("cacheRetention"in g?p.cacheRetention!==g.cacheRetention&&(p.cacheRetention=g.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let y=L(f.model)?{...f.model}:{},w=L(h.model)?h.model:{};LN.includes(y.primary)&&("primary"in w?y.primary!==w.primary&&(y.primary=w.primary,l=!0):(delete y.primary,l=!0)),NN.some(b=>JSON.stringify(y.fallbacks)===JSON.stringify(b))&&("fallbacks"in w?JSON.stringify(y.fallbacks)!==JSON.stringify(w.fallbacks)&&(y.fallbacks=w.fallbacks,l=!0):(delete y.fallbacks,l=!0)),Object.keys(y).length===0?delete f.model:f.model=y,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}},jC={id:Ks,title:"OpenClaw",automatic:!0,async detect(){let e=await x(na())||await x(ra());return{installed:e,detail:e?na():`no ${Il(Yf(),".openclaw")} state dir`}},async apply(e,t){let n=na();if(!e.byoUpstream&&ee(e,"anthropic")){let S=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${Ks}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],E;try{E=await Ke(n)}catch{return{status:"held",messages:S}}let{next:I,removed:O}=Vf(E.data,await Zo(n),Sl,wn());return O?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...S]}:(await dn(n,E,I,!1),await ce(n),await Cl(),await Vs(ra(),kl(I)),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...S]}):(t.dryRun||(await Cl(),await Vs(ra(),kl(I))),{status:"held",messages:S})}let r=wn(),o=!1;if(!t.dryRun)try{await GC(r)}catch{r=void 0,o=!0}let a;try{a=await Ke(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Jf}", "maxTokens": ${Xf}, "apiKey": "<your personal ark_ key>", "headers": { "${oa}": "<your personal ark_ key>", "${ao}": "${vl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${oa}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${El}") 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:m,structureConflicts:h,pluginConfigured:g}=MN(a.data,e,r),y=s,w=!1;if(!i.includes("openai")){let S=Vf(y,await Zo(n),["openai"]);S.removed&&(y=S.next,w=!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: ${fe({...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 ${ao} 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 = ${g?qf:El} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(g?Qf:zf).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.`]:[],...m.length>0?[`Fallback model(s) ${m.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...w?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...g?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${wn()}) 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 ${wn()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...h.length>0?[`Left ${h.join(", ")} untouched: the existing value has the wrong shape (array or null where an object belongs), and OpenClaw's strict schema will refuse it as-is. Fix the shape and re-run.`]:[],"OpenClaw hot-reloads model config; run `openclaw config validate` to confirm the merged config passes its strict schema."],k=d.length>0||h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let C=await dn(n,a,y,!0);return g&&await Vs(ra(),kl(y)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await Ke(na());for(let a of Object.values(Zf(t)))if(L(a)&&VC(a.baseUrl,e))return!0;let n=L(t.plugins)?t.plugins:{},o=(L(n.entries)?n.entries:{})[Je];if(L(o)&&L(o.config)&&VC(o.config.gatewayUrl,e))return!0}catch{}return!1},async routingExpected(e){return e.includes(Ks)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Ke(na());for(let a of Object.values(Zf(t))){if(!L(a))continue;let s=L(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[oa]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=L(t.plugins)?t.plugins:{},o=(L(n.entries)?n.entries:{})[Je];if(L(o)&&L(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=na();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Ke(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}=Vf(n.data,await Zo(t),Sl,wn()),a=await Cl();return await Vs(ra(),kl(r)),o?(await dn(t,n,r,!1),await ce(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${wn()}`]:[]],changedFiles:[t]}):(await ce(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${wn()}`]:[]]})}};import{execFile as RB}from"node:child_process";import{readFile as OB}from"node:fs/promises";import{homedir as di,platform as Er}from"node:os";import{join as kn}from"node:path";import{isDeepStrictEqual as Fm,promisify as TB}from"node:util";var js=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},xl=(e,t)=>{let n=js(e),r=js(t);if(!(!n||!r)){for(let o=0;o<Math.max(n.length,r.length);o+=1){let a=(n[o]??0)-(r[o]??0);if(a!==0)return a}return 0}};import{randomUUID as KM}from"node:crypto";import{promises as ov}from"node:fs";import{platform as jM,tmpdir as ZM}from"node:os";import{join as Kl}from"node:path";import{execFile as FN}from"node:child_process";import{promises as Zs}from"node:fs";import{homedir as WN,platform as UN}from"node:os";import{delimiter as HN,join as Rl}from"node:path";import{promisify as GN}from"node:util";var VN=GN(FN),KN=15*6e4,jN=64*1024*1024,ZN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],ZC=async(e={})=>{let t=(e.home??WN)(),n=e.env??process.env,r=ZN(e.runtimePlatform??UN()),o=[Rl(t,".local","bin"),Rl(t,".claude","local"),...(n.PATH??"").split(HN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Rl(a,`claude${s}`);try{return await Zs.access(i),i}catch{}}return null},YN=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},JN=async e=>{let t=Rl(e,"projects"),n;try{n=(await Zs.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return[]}let r=[];for(let o of n){let a=o.slice(-36);if(!qN.test(a))continue;let s=o.slice(0,-37).split("-").filter(i=>i.length>0).map(i=>i[0].toUpperCase()+i.slice(1)).join(" ");r.push({uuid:a,name:s.length>0?s:"Project",dirName:o})}return r},XN=e=>{if(!e||!e.startsWith("{"))return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.sessionIds,o=n.jsonlPaths;if(!Array.isArray(r)||!Array.isArray(o))return null;let a=Array.isArray(n.titles)?n.titles:[],s=Array.isArray(n.createdAts)?n.createdAts:[],i=Array.isArray(n.updatedAts)?n.updatedAts:[],c=d=>typeof d=="number"&&Number.isFinite(d)?d:void 0,l=[];for(let d=0;d<r.length;d+=1){let u=r[d],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:YN(n.projectList)}},zN=async e=>{let t,n;try{let r=await Zs.readFile(e,"utf8");for(let o of r.split(`
|
|
171
|
+
`)){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}},qN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,QN=/\.(?:cmd|bat)$/i,e$=(e,t)=>QN.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},YC=async(e,t={})=>{let n=t.exec??VN,r=["import-conversations",e.exportPath,"--cwd",e.workDir];if([e.binary,...r].some(d=>d.includes('"')))return{ok:!1,reason:"the export path contains an unsupported character"};await Zs.mkdir(e.configDir,{recursive:!0,mode:448}),await Zs.mkdir(e.workDir,{recursive:!0,mode:448});let o=e$(e.binary,r),a;try{a=(await n(o.file,o.args,{env:{...process.env,CLAUDE_IMPORT_CONVERSATIONS:"1",CLAUDE_CONFIG_DIR:e.configDir},timeout:KN,maxBuffer:jN,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(`
|
|
172
|
+
`).filter(d=>d.trim().length>0),i=XN(s.at(-1));if(!i)return{ok:!1,reason:"the Claude Code importer produced no readable summary"};let c=await Promise.all(i.conversations.map(async d=>{if(d.createdAt!==void 0)return d;let u=await zN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await JN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as t$}from"node:crypto";import{promises as Bn}from"node:fs";import{homedir as n$,platform as r$}from"node:os";import{join as kt}from"node:path";var JC=448,Fn="local_",o$="local-agent-mode-sessions",em="-3p",a$="cowork_account_settings.json",so=(e={})=>{let t=(e.home??n$)(),n=e.runtimePlatform??r$(),r=e.env??process.env;if(n==="darwin")return kt(t,"Library","Application Support",`Claude${em}`);if(n==="win32"){let o=r.LOCALAPPDATA??kt(t,"AppData","Local");return kt(o,`Claude${em}`)}return null},Ys=(e={})=>{let t=so(e);return t?t.slice(0,-em.length):null},tm=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)}`},Ol=async e=>{let t=kt(e,o$),n;try{n=(await Bn.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 Bn.readdir(kt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=kt(t,o,s);try{await Bn.access(kt(i,a$)),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]}},nm=async e=>{try{let t=await Bn.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}},aa=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),s$=async(e,t)=>{let n=`${Fn}${t.sessionId}`,r=kt(e,n),o=kt(r,"outputs"),a=kt(r,".claude"),s=kt(a,"projects",tm(o));await Bn.mkdir(o,{recursive:!0,mode:JC}),await Bn.mkdir(s,{recursive:!0,mode:JC});let i=kt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${t$()}`;await Bn.copyFile(t.transcriptPath,c),await Bn.chmod(c,384),await Bn.rename(c,i);let l=t.createdAt??Date.now();await J(kt(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})},XC=async(e,t)=>{let n=await nm(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!aa(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await s$(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as sa}from"node:fs";import{homedir as i$}from"node:os";import{dirname as c$,join as Js}from"node:path";var l$=448,d$=["Documents","Claude","Projects"],u$="spaces.json",p$=(e={})=>Js((e.home??i$)(),...d$),f$=async e=>{try{let t=JSON.parse(await sa.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}}},m$=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},rm=async e=>{try{return await sa.access(e),!0}catch{return!1}},h$=async(e,t,n)=>{let r=Js(t,m$(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await rm(r)?o:r;return a===o&&await rm(o)?null:(await sa.mkdir(c$(a),{recursive:!0}),await sa.cp(e,a,{recursive:!0}),a)},y$=async e=>{try{let t=(await sa.readFile(Js(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},zC=async e=>{let t=p$({home:e.home}),n={imported:0,alreadyPresent:0,skippedCollision:0,failed:0,root:t},r=e.projects??[];if(r.length===0)return n;let o=Js(e.storageDir,u$),{spaces:a,readable:s}=await f$(o);if(!s)return n.failed=r.length,n;let i=new Set(a.map(l=>l.id)),c=[];for(let l of r){if(i.has(l.uuid)){n.alreadyPresent+=1;continue}let d=Js(e.stagedProjectsDir,l.dirName);try{if(!await rm(d)){n.failed+=1;continue}let u=await h$(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await y$(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 sa.mkdir(e.storageDir,{recursive:!0,mode:l$}),await J(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as A$}from"node:crypto";import{execFile as C$,spawnSync as ck}from"node:child_process";import{constants as lk}from"node:fs";import{access as Nl,chmod as k$,mkdir as v$,readdir as S$,readFile as am,rename as E$,rm as ia,stat as dk,writeFile as I$}from"node:fs/promises";import{homedir as x$,platform as R$,userInfo as O$}from"node:os";import{basename as T$,dirname as uk,isAbsolute as ca,join as Nt,resolve as nk}from"node:path";import{isDeepStrictEqual as zs,promisify as _$}from"node:util";var kr="__anyray-claude-desktop-credential",Xs="__anyray-claude-desktop-bootstrap-headers";var Tl=["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>`."],_l=["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."],qC="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 Pl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],QC=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapHeaders","bootstrapHeadersHelper","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],g$=new Set(QC),w$=new Set(QC.map(e=>e.toLowerCase())),b$=new Set(Pl.map(e=>e.toLowerCase())),Dl=(e,t=!1)=>(t?w$:g$).has(t?e.toLowerCase():e),ek=(e,t=!1)=>t?b$.has(e.toLowerCase()):Pl.some(n=>n===e),tk=["*"],io=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...tk]}),vr=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var qs=/^[a-f0-9-]{36}$/,pk="Anyray",sm=4,ti=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],ni=["deploymentMode","awaitingSignIn"],fk=[...ti,...ni,"configLibrary","_meta.json"],bn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),st=e=>structuredClone(e),Qs=async e=>{try{return await Nl(e),!0}catch{return!1}},P$=async e=>{try{let t=await S$(uk(e)),n=T$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},D$=async e=>{try{return await Nl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":P$(e)}},Yt=(e={})=>{let t=(e.home??x$)(),n=(e.username??(()=>O$().username))(),r=Nt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Nt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Nt(r,"configLibrary"),meta:Nt(r,"configLibrary","_meta.json"),appConfig:Nt(r,"claude_desktop_config.json"),helper:Nt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Nt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},$l=()=>{let e=ck("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},mk=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],L$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...mk(t)]}},im=(e="json")=>{let t=nn(mk(e)),n=nk(t.command),r=nk(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ne()&&(!o||r!==n)}},N$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,cm=e=>[e.command,...e.args].map(N$).join(" "),$$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ca(e.command))throw new Error("the credential helper executable is not absolute")},hk=(e,t)=>{$$(e);let n=Ml(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!ca(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},yk=e=>(hk(e,"--json"),`#!/bin/sh
|
|
173
|
+
exec ${cm(e)}
|
|
174
|
+
`),M$=`#!/bin/sh
|
|
175
|
+
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,gk=e=>{hk(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),kr]};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 ${cm(t)}`,""].join(`
|
|
176
|
+
`)},B$=e=>e.args.at(-1)==="--passthrough-headers"?gk(e):yk(e),Ml=e=>/[\\/](node|node\.exe)$/i.test(e),lm=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++}},F$=e=>{let t=`#!/bin/sh
|
|
177
177
|
exec `;if(!e.startsWith(t)||!e.endsWith(`
|
|
178
178
|
`))return;let n=e.slice(t.length,-1);if(n.includes(`
|
|
179
|
-
`)||n.includes("\r"))return;let r=
|
|
180
|
-
# Anyray subscription pass-through credential helper`,
|
|
181
|
-
`)},
|
|
182
|
-
`,384)},An=async e=>{if(!await Qs(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await
|
|
183
|
-
`,384)},ei=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!qs.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!bn(o)||typeof o.id!="string"||!qs.test(o.id)||typeof o.name!="string"||r.has(o.id))throw new Error("Claude config-library metadata has an invalid entry");r.add(o.id)}if(!r.has(t))throw new Error("Claude config-library appliedId is not in entries");return t},Q$=async(e,t,n)=>{let r=await An(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:st(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[st(t.metaEntry)]}}}let c=ei(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:st(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...st(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=ei(r.value);let c=Nt(e.library,`${o}.json`);if(!await Qs(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=st(r.value.entries)}let s=n();if(!qs.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await Qs(Nt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:dk};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?st(r.value):{},appliedId:s,entries:[...a,i]}}},eM=(e,t)=>{let n=io(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},wk=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),tM=async(e,t,n,r,o,a,s)=>{let i=wk(),c=Object.fromEntries(ti.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(ni.map(d=>[d,{original:s?.deployment[d].original??gk(r.value,d),lastWritten:i[d]}]));return{version:am,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??st(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await ri(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Ll=e=>({status:"manual",messages:[e]}),nM=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}`)]}},rM=O$(b$),oM=new Set(Pl),aM=async e=>{try{let{stdout:t}=await rM("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return bn(n)?Object.keys(n):void 0}catch{return}},co=async(e,t={})=>{let n=t.readManagedPolicyKeys??aM;for(let r of e.managedPolicies){let o=await _$(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=>Dl(i)&&!oM.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},um=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.`},pm=e=>(e.platform??I$)()==="darwin",bk=async(e,t,n={})=>{if(!pm(n))return Ll("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??$l)()&&r.push({audience:"user",message:"Claude Desktop is running. Fully quit it, then re-run connect so its cached state cannot overwrite the change."});let o=Yt(n),a=await co(o,n);if(a&&r.push({audience:"admin",message:um(a)}),r.length>0)return nM(r);let s=!1,i=!1,c=[o.journal];try{let l=ee(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??H$)())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=P$((n.credentialCommand??(()=>sm(d)))(),d),f=$$(u),p=await dm(o),m=await ri(o.helper);if(p&&m.present&&m.content!==p.helper.lastWritten&&m.content!==p.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!p&&m.present&&m.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let y=await Q$(o,p,n.randomUUID??w$),g=Nt(o.library,`${y.configId}.json`);c=[o.journal,o.helper,g,...y.metaToWrite?[o.meta]:[],o.appConfig];let h=await An(g),w=await An(o.appConfig),b=eM(e,o.helper),k=await tM(o,y,h,w,f,b,p);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${y.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 ok(o.journal,k),i=!0,await Bl(o.helper,f,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await ok(o.journal,k));let C=st(h.value);for(let I of ti)rm(C,I,b[I]);await Wn(g,C),y.metaToWrite&&await Wn(o.meta,y.metaToWrite);let S=st(w.value),E=wk();for(let I of ni)rm(S,I,E[I]);return await Wn(o.appConfig,S),{status:"configured",changedFiles:[o.journal,o.helper,g,...y.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.",...Tl]}}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.`]}:Ll(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},ak=(e,t,n,r)=>{let o=st(e);for(let a of n){let s=t[a];zs(gk(e,a),s.lastWritten)?rm(o,a,s.original):r.push(a)}return o},Ak=async(e,t={})=>{if(!pm(t))return{status:"not-found",messages:[]};if((t.appRunning??$l)())return Ll("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=Yt(t);try{let r=await dm(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Nt(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 An(o),i=s.value;s.present&&(i=ak(s.value,r.config,ti,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await An(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let m=ei(l.value),y=st(l.value.entries),g=y.findIndex(b=>b.id===r.configId),h=g>=0?y[g]:void 0,w=h!==void 0&&zs(h,r.metaEntry);if(h!==void 0&&!w&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=st(l.value),m===r.configId){let b=r.originalAppliedId;b&&y.some(k=>k.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&w?(y.splice(g,1),d.entries=y):c&&h===void 0&&(d.entries=y)}else{let b=zs(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&m!==r.configId?(w&&y.splice(g,1),d={...st(l.value),entries:y}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await ia(o,{force:!0}):await Wn(o,i)),l.present&&(u?await ia(n.meta,{force:!0}):zs(l.value,d)||await Wn(n.meta,d));let f=await An(n.appConfig);if(f.present){let m=ak(f.value,r.deployment,ni,a);!r.deploymentFileExisted&&Object.keys(m).length===0?await ia(n.appConfig,{force:!0}):await Wn(n.appConfig,m)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await ri(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Bl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await ia(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await ia(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?[]:_l]}}catch(r){return Ll(`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.`)}},fm=async(e,t={})=>{if(!pm(t))return!1;let n=Yt(t);if(await co(n,t))return!1;try{let r=await An(n.meta);if(!r.present)return!1;let o=ei(r.value),a=await An(Nt(n.library,`${o}.json`)),s=await An(n.appConfig);if(!a.present||!s.present)return!1;await Nl(n.helper,ik.X_OK);let i=Gt(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}},Ck=async(e={})=>{try{let t=Yt(e),n=await ri(t.helper);if(!n.present||typeof n.content!="string")return;let r=yk(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},kk=async(e,t={})=>{if(!await fm(e,t))return!1;let n=Yt(t);try{let r=await dm(n);if(!r)return!1;let o=await An(n.meta);if(!o.present||ei(o.value)!==r.configId)return!1;let a=await ri(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=yk(a.content??"");return s?await(t.helperLauncherAvailable??G$)(s):!1}catch{return!1}};import{createHash as Bk,randomUUID as Fk}from"node:crypto";import{spawn as sM,spawnSync as iM}from"node:child_process";import{link as Am,mkdir as mm,open as Wk,readFile as hm,readdir as Uk,rename as Hk,rm as Jt,stat as Gk}from"node:fs/promises";import{homedir as Cm}from"node:os";import{basename as Vk,dirname as ai,join as ha,win32 as cM}from"node:path";import{isDeepStrictEqual as la}from"node:util";var Pe="HKCU\\SOFTWARE\\Policies\\Claude",oi="HKLM\\SOFTWARE\\Policies\\Claude",Hl=5,ya="inferenceGatewayApiKey",Ne=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ya],vk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ya],Sk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ya],Ek=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ya],Kk="Managed by anyray-connect; dynamic credential only.",lM=e=>/^[A-Za-z]:[\\/]/.test(e)&&cM.isAbsolute(e),Ik=e=>{if(!lM(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)},jk=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!Ik(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&&!Ik(e.args[0]))throw new Error("the credential helper does not use print-key --json")},km=(e={})=>ha((e.home??Cm)(),".anyray","bin","claude-desktop-credential-helper.cmd"),dM=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},uM=e=>(jk(e),["@echo off",`REM ${Kk}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(dM).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
184
|
-
`)),
|
|
185
|
-
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${
|
|
179
|
+
`)||n.includes("\r"))return;let r=lm(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Ml(o);if(!ca(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!ca(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return yk(i)===e?i:void 0}catch{return}},W$=e=>{if(!e.startsWith(M$))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=lm(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==kr)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return gk(a)===e?a:void 0}catch{return}},U$=`#!/bin/sh
|
|
180
|
+
# Anyray subscription pass-through credential helper`,H$=e=>{let t=Ml(e.command);if(!(!ca(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!ca(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=$(${cm(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(`
|
|
181
|
+
`)},G$=e=>{if(!e.startsWith(U$))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=lm(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return H$(a)===e?a:void 0},wk=e=>F$(e)??W$(e)??G$(e),V$=async()=>{let e=ck("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},K$=async e=>{let t=[e.command,...Ml(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>dk(r)))).every(r=>r.isFile())?(await Nl(e.command,lk.X_OK),!0):!1}catch{return!1}},j$=0,Bl=async(e,t,n)=>{await v$(uk(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${j$++}.tmp`;try{await I$(r,t,{mode:n}),await k$(r,n),await E$(r,e)}catch(o){throw await ia(r,{force:!0}).catch(()=>{}),o}},Wn=async(e,t)=>{await Bl(e,`${JSON.stringify(t,null,2)}
|
|
182
|
+
`,384)},An=async e=>{if(!await Qs(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await am(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!bn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},ri=async e=>{if(!await Qs(e))return{present:!1};let t=await dk(e);return{present:!0,content:await am(e,"utf-8"),mode:t.mode&511}},bk=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:st(e[t])}:{present:!1},om=(e,t,n)=>{n.present?e[t]=st(n.value):delete e[t]},rk=e=>bn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),Z$=e=>bn(e)&&rk(e.original)&&rk(e.lastWritten),Y$=e=>bn(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),ok=(e,t)=>bn(e)&&t.every(n=>Z$(e[n])),J$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],X$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],dm=(e,t,n,r)=>!(!bn(e)||e.version!==n||typeof e.configId!="string"||!qs.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!qs.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!bn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==pk||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!ok(e.config,r)||r.some(o=>e.config[o].original.present)||!ok(e.deployment,ni)||!bn(e.helper)||e.helper.path!==t.helper||!Y$(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),z$=(e,t)=>dm(e,t,sm,ti),q$=(e,t)=>dm(e,t,2,J$),Q$=(e,t)=>dm(e,t,3,X$),eM=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),ak=e=>({...e,version:sm,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),um=async e=>{if(!await Qs(e.journal))return;let t;try{t=JSON.parse(await am(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(z$(t,e))return t;if(Q$(t,e))return ak(t);if(q$(t,e))return ak(eM(t));throw new Error(`${e.journal} is not a valid ownership journal`)},sk=async(e,t)=>{await Bl(e,`${JSON.stringify(t,null,2)}
|
|
183
|
+
`,384)},ei=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!qs.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!bn(o)||typeof o.id!="string"||!qs.test(o.id)||typeof o.name!="string"||r.has(o.id))throw new Error("Claude config-library metadata has an invalid entry");r.add(o.id)}if(!r.has(t))throw new Error("Claude config-library appliedId is not in entries");return t},tM=async(e,t,n)=>{let r=await An(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:st(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[st(t.metaEntry)]}}}let c=ei(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:st(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...st(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=ei(r.value);let c=Nt(e.library,`${o}.json`);if(!await Qs(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=st(r.value.entries)}let s=n();if(!qs.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await Qs(Nt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:pk};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?st(r.value):{},appliedId:s,entries:[...a,i]}}},nM=(e,t)=>{let n=io(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},Ak=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),rM=async(e,t,n,r,o,a,s)=>{let i=Ak(),c=Object.fromEntries(ti.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(ni.map(d=>[d,{original:s?.deployment[d].original??bk(r.value,d),lastWritten:i[d]}]));return{version:sm,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??st(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await ri(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Ll=e=>({status:"manual",messages:[e]}),oM=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}`)]}},aM=_$(C$),sM=new Set(Pl),iM=async e=>{try{let{stdout:t}=await aM("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return bn(n)?Object.keys(n):void 0}catch{return}},co=async(e,t={})=>{let n=t.readManagedPolicyKeys??iM;for(let r of e.managedPolicies){let o=await D$(r);if(o==="absent")continue;if(o==="unreadable")return{path:r,keys:[],unreadable:!0};let a=await n(r);if(a===void 0)return{path:r,keys:[],unreadable:!0};let s=a.filter(i=>Dl(i)&&!sM.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},pm=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.`},fm=e=>(e.platform??R$)()==="darwin",Ck=async(e,t,n={})=>{if(!fm(n))return Ll("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??$l)()&&r.push({audience:"user",message:"Claude Desktop is running. Fully quit it, then re-run connect so its cached state cannot overwrite the change."});let o=Yt(n),a=await co(o,n);if(a&&r.push({audience:"admin",message:pm(a)}),r.length>0)return oM(r);let s=!1,i=!1,c=[o.journal];try{let l=ee(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??V$)())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=L$((n.credentialCommand??(()=>im(d)))(),d),f=B$(u),p=await um(o),m=await ri(o.helper);if(p&&m.present&&m.content!==p.helper.lastWritten&&m.content!==p.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!p&&m.present&&m.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let h=await tM(o,p,n.randomUUID??A$),g=Nt(o.library,`${h.configId}.json`);c=[o.journal,o.helper,g,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await An(g),w=await An(o.appConfig),b=nM(e,o.helper),k=await rM(o,h,y,w,f,b,p);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${h.configId} for ${e.anthropicBaseUrl}, activate it in third-party mode, and install a ${l?"subscription pass-through":"dynamic API-billed"} credential helper at ${o.helper}.`]};s=!0,await sk(o.journal,k),i=!0,await Bl(o.helper,f,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await sk(o.journal,k));let C=st(y.value);for(let I of ti)om(C,I,b[I]);await Wn(g,C),h.metaToWrite&&await Wn(o.meta,h.metaToWrite);let S=st(w.value),E=Ak();for(let I of ni)om(S,I,E[I]);return await Wn(o.appConfig,S),{status:"configured",changedFiles:[o.journal,o.helper,g,...h.metaToWrite?[o.meta]:[],o.appConfig],messages:[`Configured Claude Desktop's native local gateway profile \u2192 ${e.anthropicBaseUrl}.`,l?`Installed a subscription pass-through credential helper at ${o.helper}; the helper reads your Claude Code subscription token on demand and no credential is stored in Claude's config.`:`Installed a dynamic credential helper at ${o.helper}; no gateway key is stored in Claude's config.`,l?"Claude Desktop Gateway requests now ride your Claude subscription through Anyray for content-free metering and optimization. Stay signed in to Claude Code so the token remains available.":"Claude Desktop uses its API-billed third-party inference lane; its first-party subscription remains separate.","Fully quit and reopen Claude Desktop to load the change.",...Tl]}}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.`]}:Ll(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},ik=(e,t,n,r)=>{let o=st(e);for(let a of n){let s=t[a];zs(bk(e,a),s.lastWritten)?om(o,a,s.original):r.push(a)}return o},kk=async(e,t={})=>{if(!fm(t))return{status:"not-found",messages:[]};if((t.appRunning??$l)())return Ll("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=Yt(t);try{let r=await um(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Nt(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 An(o),i=s.value;s.present&&(i=ik(s.value,r.config,ti,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await An(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let m=ei(l.value),h=st(l.value.entries),g=h.findIndex(b=>b.id===r.configId),y=g>=0?h[g]:void 0,w=y!==void 0&&zs(y,r.metaEntry);if(y!==void 0&&!w&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=st(l.value),m===r.configId){let b=r.originalAppliedId;b&&h.some(k=>k.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&w?(h.splice(g,1),d.entries=h):c&&y===void 0&&(d.entries=h)}else{let b=zs(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&m!==r.configId?(w&&h.splice(g,1),d={...st(l.value),entries:h}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await ia(o,{force:!0}):await Wn(o,i)),l.present&&(u?await ia(n.meta,{force:!0}):zs(l.value,d)||await Wn(n.meta,d));let f=await An(n.appConfig);if(f.present){let m=ik(f.value,r.deployment,ni,a);!r.deploymentFileExisted&&Object.keys(m).length===0?await ia(n.appConfig,{force:!0}):await Wn(n.appConfig,m)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await ri(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Bl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await ia(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await ia(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?[]:_l]}}catch(r){return Ll(`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.`)}},mm=async(e,t={})=>{if(!fm(t))return!1;let n=Yt(t);if(await co(n,t))return!1;try{let r=await An(n.meta);if(!r.present)return!1;let o=ei(r.value),a=await An(Nt(n.library,`${o}.json`)),s=await An(n.appConfig);if(!a.present||!s.present)return!1;await Nl(n.helper,lk.X_OK);let i=Gt(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}},vk=async(e={})=>{try{let t=Yt(e),n=await ri(t.helper);if(!n.present||typeof n.content!="string")return;let r=wk(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},Sk=async(e,t={})=>{if(!await mm(e,t))return!1;let n=Yt(t);try{let r=await um(n);if(!r)return!1;let o=await An(n.meta);if(!o.present||ei(o.value)!==r.configId)return!1;let a=await ri(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=wk(a.content??"");return s?await(t.helperLauncherAvailable??K$)(s):!1}catch{return!1}};import{createHash as Wk,randomUUID as Uk}from"node:crypto";import{spawn as cM,spawnSync as lM}from"node:child_process";import{link as Cm,mkdir as hm,open as Hk,readFile as ym,readdir as Gk,rename as Vk,rm as Jt,stat as Kk}from"node:fs/promises";import{homedir as km}from"node:os";import{basename as jk,dirname as ai,join as ha,win32 as dM}from"node:path";import{isDeepStrictEqual as la}from"node:util";var Pe="HKCU\\SOFTWARE\\Policies\\Claude",oi="HKLM\\SOFTWARE\\Policies\\Claude",Hl=5,ya="inferenceGatewayApiKey",Ne=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ya],Ek=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ya],Ik=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ya],xk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ya],Zk="Managed by anyray-connect; dynamic credential only.",uM=e=>/^[A-Za-z]:[\\/]/.test(e)&&dM.isAbsolute(e),Rk=e=>{if(!uM(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)},Yk=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!Rk(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&&!Rk(e.args[0]))throw new Error("the credential helper does not use print-key --json")},vm=(e={})=>ha((e.home??km)(),".anyray","bin","claude-desktop-credential-helper.cmd"),pM=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},fM=e=>(Yk(e),["@echo off",`REM ${Zk}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(pM).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
184
|
+
`)),mM=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},Jk=e=>{let t=e.split(`\r
|
|
185
|
+
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${Zk}`||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(mM);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return Yk(s),s}catch{return}},hM=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>Kk(r)))).every(r=>r.isFile())}catch{return!1}},yM=async(e,t)=>{let n=Jk(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??hM)(n)}catch{return!1}},gm=e=>({sha256:lo(e),content:e}),Ok=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return $t(t,["sha256","content"])&&SM(t.sha256)&&typeof t.content=="string"&&lo(t.content)===t.sha256&&Jk(t.content)!==void 0},Sm=()=>{let e=lM("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??"")},gM=async(e,t)=>{await hm(ai(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await Hk(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await Cm(n,e)}finally{await Jt(n,{force:!0}).catch(()=>{})}},wM=e=>`${jk(e)}.anyray-old-`,bM=e=>`${e}.anyray-old-${process.pid}-${Uk()}`,Xk=async(e,t)=>{try{await Cm(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await Jt(t,{force:!0}),!0},Wl=async(e,t,n,r,o)=>{let a=bM(e),s=n===void 0?void 0:lo(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${Uk()}`,c=!1;try{if(i&&n!==void 0){let d=await Hk(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 Vk(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await fa(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await Cm(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await ma(e)!==s))throw new Error("credential helper publication verification failed");await Jt(a,{force:!0}),c=!1}catch(l){throw c&&await Xk(e,a).catch(()=>!1),l}finally{i&&await Jt(i,{force:!0}).catch(()=>{})}},wm=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,AM=String.raw`
|
|
186
186
|
$ErrorActionPreference = 'Stop'
|
|
187
187
|
try {
|
|
188
188
|
$request = ConvertFrom-Json ([Console]::In.ReadToEnd())
|
|
@@ -251,16 +251,16 @@ try {
|
|
|
251
251
|
exit 5
|
|
252
252
|
} catch {
|
|
253
253
|
exit 6
|
|
254
|
-
}`,Hn=async e=>new Promise((t,n)=>{let r=
|
|
255
|
-
`)}catch(a){if(a.code!=="EEXIST")throw await Jt(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await
|
|
256
|
-
`;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},TM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,_M=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),PM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),DM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),LM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===DM(t).toUpperCase(),$k=(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},NM=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,$M=(e,t)=>{if(!Dl(e,!0))return!1;let n=NM(t);if(PM.has(n))return!1;if(_M.has(n))return n==="REG_EXPAND_SZ"?!0:!qC(e,!0)},MM=(e,t)=>{let n=Jk(),r=!1,o=!1,a=!1,s=t.toUpperCase()===oi.toUpperCase(),i=(l,d)=>{if(!s)return;let u=$M(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),$k(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||LM(d,t))continue;let u=TM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),$k(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:Jk(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return MM(n.stdout,t)},Sr=async e=>{let t=await Un(e,oi);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...Ne.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},Rm=e=>e.unparsed?`This machine may have a Claude policy under ${oi} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${oi} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${oi} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Vl=(e,t)=>vr(io(e,t)),Xk=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],BM=(e,t)=>{let n=Vl(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}]}))},FM=(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}}),WM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,wm=e=>Object.fromEntries(Ne.map(t=>[t,CM(t,e[t])])),Mk=(e,t,n,r)=>({version:Hl,registryKey:Pe,keyExisted:e,lastWritten:wm(t),helper:{path:n,lastWritten:ym(r)}}),UM=(e,t,n,r,o,a)=>({version:Hl,registryKey:Pe,keyExisted:e,lastWritten:wm(t),pending:wm(n),helper:{path:r,...o?{lastWritten:ym(o)}:{},pending:ym(a)}}),bm=(e,t,n)=>da(n,e.lastWritten[t])||e.pending!==void 0&&da(n,e.pending[t]),fa=async e=>{try{let t=await hm(e,"utf8");return{content:t,sha256:lo(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ma=async e=>(await fa(e))?.sha256,ua=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Ul=async(e,t)=>{let n=yM(e),r;try{r=await Uk(ai(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>ha(ai(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([fa(e),fa(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ua(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await Yk(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ua(t,s.sha256)&&ua(t,i.sha256)){await Jt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Om=async(e,t,n)=>(n.present?await e(Xk(Pe,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Pe,"/v",t,"/f"])).code===0,HM=async(e,t,n)=>{let r=!0,o=await Un(e);for(let a of Ne)if(!la(o.values[a],t[a])){if(!la(o.values[a],n[a])){r=!1;continue}await Om(e,a,t[a])||(r=!1),o=await Un(e)}return r&&Ne.every(a=>la(o.values[a],t[a]))},Xe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Mt(n)]}}),zk=async(e,t,n,r={})=>{if(!be(t))return Xe("A valid personal ark_ gateway key is required.",!1,r);let o=km(r),a;try{a=uM((r.credentialCommand??sm)())}catch{return Xe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=lo(a),i=r.runReg??Hn,c=Mt(r),l;if(!n.dryRun)try{l=await Sm(r)}catch(y){return Xe(y instanceof pa?"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,m=!1;try{let y=await Sr(i);if(y)return Xe(Rm(y),!1,r);let g=await xm(r,!n.dryRun);n.dryRun||await Ul(o,g);let h=await Un(i),w=BM(e,o),b=await fa(o),k=b?.sha256,C=!1;if(d=g,u=h,f=w,g){let I=Ne.find(O=>!bm(g,O,h.values[O]));if(I)return Xe(`Claude's ${I} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!ua(g,k))return Xe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=WM(g)}else{if(k!==void 0&&k!==s)return Xe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let I=h.foreignState||Ne.some(U=>h.values[U].present),O=Ne.every(U=>la(h.values[U],w[U])),T=Ne.every(U=>la(h.values[U],FM(e,t.trim())[U]));if(I&&!O&&!T)return Xe(`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(C=T,O&&k===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 Fl(Mk(h.keyPresent,w,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Pe} into the ownership journal.`]})}if(C){let I=!0;try{I=(r.appRunning??vm)()}catch{}if(I)return Xe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let S=UM(g?.keyExisted??h.keyPresent,h.values,w,o,b?.content,a);if(p=S,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 Fl(S,r),m=!0;for(let I of Ne){let O=await Un(i);if(!da(O.values[I],S.lastWritten[I])&&!da(O.values[I],S.pending[I]))throw new Error("registry value changed during apply");if(!la(O.values[I],w[I])&&!await Om(i,I,w[I]))throw new Error("registry write failed")}let E=await Un(i);if(!Ne.every(I=>da(E.values[I],S.pending[I])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await hM(o,a):await Wl(o,k,a,"apply",r)),await ma(o)!==s)throw new Error("credential helper verification failed");return await Fl(Mk(S.keyExisted,w,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.",...Tl]}}catch{if(!m||!u||!f||!p)return Xe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Ul(o,p);let y=!0,g=await fa(o),h=p.helper.pending;if(g?.sha256!==p.helper.lastWritten?.sha256&&(h!==void 0&&g?.sha256===h.sha256?p.helper.lastWritten?(await Wl(o,h.sha256,p.helper.lastWritten.content,"rollback",r),y=await ma(o)===p.helper.lastWritten.sha256):await Wl(o,h.sha256,void 0,"rollback",r):y=g===void 0&&p.helper.lastWritten===void 0),y&&await HM(i,u.values,f))return d?await Fl(d,r):await Jt(c,{force:!0}),Xe("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return Xe("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},qk=async(e,t={})=>{let n=t.runReg??Hn,r=Mt(t),o;if(!e.dryRun)try{o=await Sm(t)}catch(a){return Xe(a instanceof pa?"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 xm(t,!e.dryRun);a&&!e.dryRun&&await Ul(a.helper.path,a);let s=await Un(n);if(!a)return Ne.filter(m=>s.values[m].present).length>0?Xe(`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=Ne.filter(p=>s.values[p].present&&!bm(a,p,s.values[p])),c=await ma(a.helper.path),l=c!==void 0&&!ua(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 Ne){let y=(await Un(n)).values[p];if(y.present){if(!bm(a,p,y)){u.add(p);continue}await Om(n,p,{present:!1})||(d=!0)}}let f=await ma(a.helper.path);if(f!==void 0)if(ua(a,f))try{await Wl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?Xe(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await Jt(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?[]:_l]})}catch{return Xe(`Could not safely inspect or revert ${Pe}; no unproven value was removed.`,!1,t)}finally{await o?.()}},Qk=async(e,t={})=>{let n=t.runReg??Hn;if(!await x(Mt(t)))return;let r;try{r=await Sm(t);let o=await xm(t);if(o&&await Ul(o.helper.path,o),!o||o.pending||await Sr(n)!==void 0)return;let a=await Un(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Gt(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Ne.every(l=>da(a.values[l],o.lastWritten[l]))))return;let i=await ma(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 mM(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?.()}},ev=async(e,t={})=>await Qk(e,t)!==void 0,tv=async(e,t={})=>await Qk(e,t)==="dynamic";var ga=(e=VM())=>e==="win32"?vm:$l,Tm="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",jl=async(e,t={})=>{let n=(t.profileRoot??so)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Tm};if((t.appRunning??ga(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await nv.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 Ol(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 "+Tm}:{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??KC)();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=Kl(t.stagingRoot??KM(),`anyray-history-${process.pid}-${GM()}`);try{let s=await(t.runImporter??jC)({binary:o,exportPath:e,configDir:Kl(a,"config"),workDir:Kl(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. "+Tm};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 YC(r.dir,s.conversations),c=await JC({stagedProjectsDir:Kl(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 nv.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as St}from"node:fs";import{homedir as fB}from"node:os";import{join as zt,sep as mB}from"node:path";import{isDeepStrictEqual as Xl}from"node:util";import{constants as jM}from"node:fs";import{promises as V}from"node:fs";import{dirname as wa,isAbsolute as Pm,join as re,relative as Zl,resolve as Xt,sep as si}from"node:path";import{randomUUID as zl}from"node:crypto";var Cn=448,ii=384,sv=448,ZM=4,Dm=3e4,iv=5e3,YM=10*6e4,_m=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),it=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ci=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),cv=(e,t)=>{let n=Zl(Xt(e),Xt(t));return n===""||!n.startsWith(`..${si}`)&&n!==".."&&!Pm(n)},uo=async e=>{try{let t=await V.readFile(e,"utf8"),n=JSON.parse(t);return it(n)?{raw:t,value:n}:void 0}catch(t){return vt(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},vt=e=>e instanceof Error&&"code"in e,JM=e=>{try{return process.kill(e,0),!0}catch(t){return vt(t)&&t.code==="EPERM"}},lv=e=>e===0?"owner.json":`owner.${e}.json`,Yl=async e=>{let t;try{t=await V.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=re(e,r.name),a,s,i;try{let d=JSON.parse(await V.readFile(o,"utf8"));it(d)&&typeof d.pid=="number"&&Number.isSafeInteger(d.pid)&&d.pid>0&&typeof d.nonce=="string"&&d.nonce.length>0&&(a=d.pid,s=d.nonce,typeof d.createdAt=="number"&&Number.isFinite(d.createdAt)&&d.createdAt>=0&&(i=d.createdAt))}catch{}let c=await V.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}},dv=e=>{if(e.pid===void 0||!JM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Dm&&t-e.createdAtMs>YM},XM=async e=>{let t=`${e}.anyray-lock`;await V.mkdir(wa(t),{recursive:!0,mode:Cn});let n=zl(),r,o=!1;try{await V.mkdir(t,{mode:Cn}),o=!0}catch(i){if(!vt(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Yl(t);if(d){if(!dv(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await V.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=Dm)return}let l=re(t,lv(c));try{await V.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
257
|
-
`,{flag:"wx",mode:ii}),r=l}catch(d){if(vt(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await V.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await V.readFile(a,"utf8"));if(!it(i)||i.nonce!==n)return;let c=new Date;await V.utimes(a,c,c)}catch{}})()},
|
|
258
|
-
`,{mode:ii,flag:"wx"}),await V.rename(a,e)}catch(s){try{await V.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},ql=async(e,t)=>{for(let n=0;n<
|
|
259
|
-
`,{flag:"wx",mode:ii}),o=u}catch(f){if(vt(f)&&f.code==="EEXIST"){n=!1;continue}n&&await V.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await V.readFile(a,"utf8"));if(!it(l)||l.nonce!==r)return;let d=new Date;await V.utimes(a,d,d)}catch{}})()},
|
|
260
|
-
`)}},$m=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),vv=async e=>{let t=[];for(let n of gB)t.push({lane:n,sources:await bB(e,n)});return t},Sv=async(e={})=>{let t=(e.firstPartyRoot??(()=>Ys()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([vv(t),Lm(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=$m(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}},po=async(e={})=>{let t=(e.home??fB)(),n=(e.firstPartyRoot??(()=>Ys()))(),r=(e.thirdPartyRoot??(()=>so()))();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??ga())())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([vv(n),Lm(n)]),s;if(e.account){let p=e.account;for(let g of o)g.sources=g.sources.filter(h=>h.account.startsWith(p));let m=a.accounts.filter(g=>g.startsWith(p));if(o.every(g=>g.sources.length===0)&&m.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 y=$m(o);for(let g of m)y.add(g);if(y.size>1)return Av(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${y.size} accounts`,m);s=[...y]}else if(!e.allAccounts){let p=$m(o);for(let m of a.accounts)p.add(m);if(p.size>1)return Av(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 hB(r),l=await wv(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:m}of o){if(m.length===0){d.push(Nm(p));continue}let y=await AB(r,p);if("missing"in y){u.push({lane:p,reason:y.missing,waiting:m.reduce((g,h)=>g+h.ids.length,0)}),d.push(Nm(p));continue}d.push(await vB(p,m,y.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:Mm(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 EB=e=>[Le(e)],Ev=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...EB(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await x(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var Iv="1.21459.0",OB=RB(IB),TB=async e=>{try{let{stdout:t}=await OB("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},_B=async e=>{try{return await xB(e)}catch{return}},xv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",PB=["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."],ba=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(Rv??=Ov({}),Rv):Ov(e),Rv,Ov=async e=>{let t=(e.home??di)(),n=["/Applications/Claude.app",kn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??TB,o=e.readClaudeAppBundle??_B;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} ${xv}`}),c=xl(s,Iv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${Iv} or newer.`);let l=await o(kn(a,"Contents","Resources","app.asar"));return l?uk.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. ${xv}`}},ed="anyray",Pv="--anyray-owner=claude-desktop-v1",td=(e={})=>{let t=(e.platform??Er)(),n=(e.home??di)();return t==="darwin"?Yt(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")},Hm=(e={})=>kn((e.home??di)(),"Library","Application Support","Claude","claude_desktop_config.json"),Dv=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,Pv]}},fo=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Lv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},DB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),LB=e=>{if(!fo(e)||!Lv(e,["command","args"]))return!1;let t=Dv();return e.command===t.command&&DB(e.args,t.args)},NB=e=>fo(e)&&Array.isArray(e.args)&&e.args.at(-1)===Pv,$B=e=>{if(!fo(e)||!Lv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||et(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!et(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},MB=e=>e===void 0?"absent":LB(e)?"exact":NB(e)||$B(e)?"stale-owned":"foreign",Fe=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},mo=async e=>{let t=await x(e),n;try{n=await M(e)}catch{throw new Fe(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!fo(n.mcpServers))throw new Fe(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(fo(n.mcpServers)?n.mcpServers:void 0)?.[ed];return{path:e,fileExisted:t,json:n,entry:o,ownership:MB(o)}},nd=e=>{if(e.ownership==="foreign")throw new Fe(`MCP name conflict in ${e.path}: mcpServers.${ed} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},Nv=(e,t)=>{let n={...e},r=fo(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[ed]:r[ed]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Fm=async(e,t)=>{if(Bm(e.entry,t))return;let n=await mo(e.path);if(!Bm(n.entry,e.entry))throw new Fe(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Wn(e.path,Nv(n.json,t)),{reading:e,afterEntry:t}},Wm=async e=>{let t=await mo(e.reading.path);if(!Bm(t.entry,e.afterEntry))throw new Fe(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=Nv(t.json,e.reading.entry);await Wn(e.reading.path,n)},BB=async e=>{if(!ne())throw new Fe(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${_e()} is temporary); no inference setting was changed.`);let t=await mo(td(e));nd(t);let n=Hm(e),r=(e.platform??Er)()==="darwin"&&n!==t.path?await mo(n):void 0;return r&&nd(r),{active:t,...r?{legacy:r}:{}}},Tv=async e=>{let t=await mo(td(e));nd(t);let n=Hm(e),r=(e.platform??Er)()==="darwin"&&n!==t.path?await mo(n):void 0;return r&&nd(r),{active:t,...r?{legacy:r}:{}}},FB=async e=>{let t=[];try{let n=await Fm(e.active,Dv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Fm(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Wm(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Fe(`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 Wm(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Fe(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},WB=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Fm(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Wm(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Fe(`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)},_v=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)."]},UB={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},rd="claude-desktop",Um="migrate",$v=new Set(["app-running","store-missing"]),HB={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},GB={skill:{one:"user-created skill",many:"user-created skills"},plugin:{one:"user-installed plugin",many:"user-installed plugins"},"local-mcp":{one:"local MCP server",many:"local MCP servers"}},VB="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",Mv=e=>{let t=(e.platform??Er)(),n=e.home??di;return{home:n,appRunning:e.appRunning??ga(t),firstPartyRoot:()=>Ys({home:n,runtimePlatform:t}),thirdPartyRoot:()=>so({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Bv=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=HB[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.`:"")},Fv=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=GB[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.`:"")},li=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=Mv(e),r=await(e.pendingDesktopMigrationCount??Sv)(n),o=r.userSkills+r.userPlugins+r.localMcpServers;if(r.sessions+o===0)return[];if(t.dryRun)return[`Would bring ${[r.sessions>0?`${r.sessions} existing Claude Desktop session${r.sessions===1?"":"s"}`:"",o>0?`${o} portable configuration ${o===1?"entry":"entries"}`:""].filter(Boolean).join(" and ")} into Claude Desktop's third-party profile, now or automatically the next time Claude Desktop is fully quit.`];let a=await(e.migrateDesktopProfile??po)(n);if(a.ok){let c=Bv(a.lanes),l=Fv(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(w=>w.reason!=="ambiguous"),p=a.blockedAssets??[],m=a.retryableAssets??[];if(f.length===0&&p.length===0&&m.length===0)return[c,l,u].filter(w=>!!w);if(t.preservePendingOp)return[c,l,u].filter(w=>!!w);await Ss(rd,Um);let y=f.reduce((w,b)=>w+b.waiting,0),g=[y>0?`${y} more session${y===1?"":"s"}`:"",p.length>0?`${p.length} extension ${p.length===1?"store":"stores"}`:""].filter(Boolean),h=[...g.length>0?[`Queued: ${g.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...m.length>0?[`Queued: ${m.length} portable configuration ${m.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...h]}if(!$v.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
261
|
-
${a.remedy}`];if(t.preservePendingOp)return[];await Ss(rd,Um);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."]}},KB=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await ur(rd),[]}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."]}},jB=e=>Ev({id:rd,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Er)(),n=(e.home??di)();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=>ee(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",..._v(t)]:["Claude desktop org/API lane:",..._v(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`."]}),ZB=(e={})=>{let t=jB(e),n=()=>(e.platform??Er)()==="darwin",r=()=>(e.platform??Er)()==="win32",o=(s,i)=>n()?bk(s,i,e):zk(s,s.clientKey??"",i,e),a=s=>n()?Ak(s,e):qk(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ga((e.platform??Er)()))(),quitTarget:UB,needsTarget:()=>!1,async complete(s){if(s!==Um)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??po)(Mv(e));if(i.ok){let c=Bv(i.lanes),l=Fv(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(y=>y.reason!=="ambiguous"),p=i.blockedAssets??[],m=i.retryableAssets??[];return f.length>0||p.length>0||m.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."]:[],...m.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(y=>!!y):["No portable Claude Desktop data was left to bring across."]}}return $v.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?kk(s,e):r()?tv(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=Yt(e),p=await co(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[um(p),...await li(e,i)]}}if(r()){let f;try{f=await Sr(e.runReg??Hn)}catch{return{status:"manual",manualAudience:"admin",messages:[VB,...await li(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[Rm(f),...await li(e,i)]}}if(r()&&ee(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let f=await ba(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await BB(e)}catch(f){let p=f instanceof Fe?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Fe?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 li(e,i)]}}let d;try{d=await FB(c)}catch(f){let p=f instanceof Fe?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Fe?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 li(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?PB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=td(e),c=await KB(s),l=y=>c.length===0?y:{...y,messages:[...y.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await Tv(e)}catch(y){return l({status:"manual",messages:[y instanceof Fe?y.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 y=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...y&&y.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${y.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let y=r()?Mt(e):void 0;if(!(y!==void 0&&f.changedFiles?.includes(y)===!0&&!await x(y)))return l(f)}let p;try{p=await WB(await Tv(e))}catch(y){let g=y instanceof Fe?y.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...g])],messages:[...f.messages,y instanceof Fe?y.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await ce(i);let m=Hm(e);return n()&&m!==i&&await ce(m),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(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await mo(td(e));return s.ownership!=="exact"||!fo(s.entry)?{registered:!1,command:null,reason:s.fileExisted?s.ownership==="absent"?"absent":s.ownership==="stale-owned"?"stale":"foreign":"no-config"}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async pointsAt(s){return n()?(await ba(e)).supported?fm(s,e):!1:r()?ev(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await ba(e)).supported)return["unknown"];let s=await Ck(e);return s?[s]:["unknown"]}if(r())return await x(Mt(e))?await Sr(e.runReg??Hn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=Yt(e);return!await x(s.journal)||await co(s,e)?!1:(await ba(e)).supported}return r()&&await x(Mt(e))?!await Sr(e.runReg??Hn):!1}catch{return!1}}}},Wv=ZB();import{homedir as CF}from"node:os";import{join as kF}from"node:path";import{rm as pd}from"node:fs/promises";import{constants as Uv,accessSync as YB,statSync as JB}from"node:fs";import{platform as Gm}from"node:os";import{delimiter as XB,posix as zB,resolve as qB,win32 as QB}from"node:path";var eF="0.59.0",tF="1.1.4",Gn="Anyray \xB7 Claude",Vn="Anyray \xB7 Codex",od="__anyray-acp-agent",Hv=(e,t,n)=>{let{command:r,args:o}=nn([od,e,t,n]);return{command:r,args:o,env:{}}},ad=(e=Gm())=>e==="win32"?"npx.cmd":"npx",sd=(e=process.env.PATH,t=Gm())=>{if(!e)return;let n=ad(t);for(let r of e.split(XB)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=qB(o,n);try{if(!JB(a).isFile())continue;return YB(a,t==="win32"?Uv.F_OK:Uv.X_OK),a}catch{}}},id=(e,t=Gm())=>{let n=t==="win32"?QB:zB;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==ad(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},nF="https://chatgpt.com/backend-api/codex",rF="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Gv="ANYRAY_ACP_CODEX_AUTHORIZATION",Vv="ANYRAY_ACP_CODEX_CLIENT_KEY",Kv="ANYRAY_ACP_CODEX_METADATA",jv=e=>fe({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),oF=(e,t={})=>{let n=ee(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":nF,"x-anyray-forward-headers":rF}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Vv}:{}}:{Authorization:Gv};return jv(e)&&(o["x-anyray-metadata"]=Kv),{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}}}:{}}},aF=e=>{let t=ee(e,"openai"),n=jv(e);return{...t?e.clientKey?{[Vv]:e.clientKey}:{}:{[Gv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[Kv]:n}:{}}},Zv=(e,t=ad(),n={})=>({[Gn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${eF}`],env:rn(e).env},[Vn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${tF}`],env:{CODEX_CONFIG:JSON.stringify(oF(e,n)),...aF(e)}}}),ui=(e=ad(),t="jetbrains")=>({[Gn]:Hv("claude",e,t),[Vn]:Hv("codex",e,t)}),ho=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as sF}from"node:zlib";import{open as iF,readFile as Ym,readdir as ud}from"node:fs/promises";import{dirname as Yv,join as me}from"node:path";import{homedir as qv,platform as Jm}from"node:os";var ld="2025.3.2",Aa="253.30387.147",pi="com.intellij.ml.llm",Vm=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),cF=1e4,lF=256*1024*1024,dF=16*1024*1024,Km=1024*1024,jm=22,uF=jm+65535,Zm=xl,pF=()=>{let e=qv(),t=me(e,".cache","JetBrains","RemoteDev");switch(Jm()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:me(e,"Applications"),layout:"app-bundles"},{path:me(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:me(process.env.LOCALAPPDATA??me(e,"AppData","Local"),"Programs"),layout:"children"},{path:me(process.env.LOCALAPPDATA??me(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:me(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:me(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},fF=()=>Jm()==="linux"?me(qv(),".local","share","JetBrains"):Le("JetBrains"),mF=()=>Jm()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),hF=async(e,t=cF)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await ud(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=me(r.path,i.name),l=r.layout==="app-bundles"?me(c,"Contents","Resources","product-info.json"):me(c,"product-info.json");await x(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=me(s,"product-info.json"),l=me(s,"Contents","Resources","product-info.json");if(await x(c)){n.push(c);return}if(await x(l)){n.push(l);return}let d;try{d=await ud(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=me(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)]},yF=e=>{let t=Yv(e);return t.endsWith(`${me("Contents","Resources")}`)?Yv(t):t},gF=async e=>{try{let t=JSON.parse(await Ym(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!js(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:yF(e)}}catch{return}},dd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},wF=async(e,t)=>{let n;try{n=await iF(e,"r");let{size:r}=await n.stat();if(r<jm||r>lF)return;let o=Math.min(r,uF),a=await dd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-jm;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>dF||c+i>r)return;let l=await dd(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),m=l.readUInt16LE(d+28),y=l.readUInt16LE(d+30),g=l.readUInt16LE(d+32),h=l.readUInt32LE(d+42),w=d+46+m+y+g;if(w>l.length)return;let b=l.subarray(d+46,d+46+m).toString("utf8");if(d=w,b!==t)continue;if(f===4294967295||p===4294967295||f>Km||p>Km)return;let k=await dd(n,30,h);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),E=await dd(n,f,h+30+C+S);return E?u===0?E.toString("utf8"):u===8?sF(E,{maxOutputLength:Km}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},Jv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!js(n)))return{id:t,version:n}},bF=async(e,t)=>{let n=me(e,"META-INF","plugin.xml");if(await x(n))try{let o=Jv(await Ym(n,"utf8"));return{present:o?.id===pi||t,descriptor:o?.id===pi?o:void 0}}catch{return{present:t}}let r=[];try{r=(await ud(me(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=>me(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await wF(o,"META-INF/plugin.xml"),s=a?Jv(a):void 0;if(s?.id===pi)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Xv=async e=>{let t;try{t=await ud(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Vm.has(o.name.toLowerCase()),i=Vm.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Vm.has(o.name.toLowerCase());if(!a){let i=me(e,o.name,"META-INF","plugin.xml");if(!await x(i))continue}let s=await bF(me(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},AF=async e=>{try{return(await Ym(me(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(pi)}catch{return!1}},zv=e=>e.reduce((t,n)=>t?(Zm(n,t)??-1)>0?n:t:n,void 0),Qv=async(e={})=>{let t=e.configRoot??Le("JetBrains"),n=e.userPluginsRoot??fF(),r=await hF(e.productRoots?e.productRoots.map(m=>({path:m,layout:"recursive"})):pF(),e.scanBudget),o=(await Promise.all(r.map(m=>gF(m)))).filter(m=>m!==void 0),a=o.length>0||await x(t);if(e.wsl??mF())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(m=>(Zm(m.version,ld)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let m of s){let y=me(t,m.dataDirectoryName);if(!await x(y)){d=!0;continue}let g=[me(y,"plugins"),me(n,m.dataDirectoryName),me(n,m.dataDirectoryName,"plugins")],h;for(let w of[...new Set(g)]){let b=await Xv(w);if(b.present){h=b;break}}if(h??=await Xv(me(m.root,"plugins")),h.present&&!h.descriptor){l=!0;continue}if(!(!h.descriptor||h.descriptor.id!==pi)){if(i.push(h.descriptor.version),await AF(y)){c=!0;continue}if(!((Zm(h.descriptor.version,Aa)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${m.version}; AI Assistant ${h.descriptor.version}; ACP supported`,ideVersion:m.version,pluginVersion:h.descriptor.version}}}let u=zv(o.map(m=>m.version)),f=zv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${ld}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${ld}+ once, enable AI Assistant ${Aa}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${Aa}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${Aa}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${Aa}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${Aa}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${ld}+ 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 vF=[Gn,Vn],Xm=()=>kF(CF(),".jetbrains","acp.json"),yo=()=>`${Xm()}.anyray-state`,SF=(e,t,n="npx")=>{let r=ho(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,ui(n,"jetbrains")),{...e,agent_servers:r}},EF=(e,t,n)=>{if(!ho(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=ho(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of vF)if(c in r){if(!cd(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}},IF=(e=Qv)=>({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=Xm(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=sd();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await x(r),c;try{c=await M(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=ui(a,"jetbrains");return await qi({configPath:r,current:c,next:SF(c,t,a),journalPath:yo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,yo()]}},async revert(t){let n=Xm(),r=async()=>{if(!await x(n))return t.dryRun||(await ce(n),await pd(yo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await ce(n),await pd(yo(),{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(yo());(u.version===1||u.version===2)&&ho(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await x(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await M(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await $r(n);let l=EF(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 pd(n,{force:!0}):await J(n,l.next,{backup:!1})),t.dryRun||(await ce(n),await pd(yo(),{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,yo(),r)}}),eS=IF();import{homedir as md}from"node:os";import{join as hd}from"node:path";import{rm as zm}from"node:fs/promises";var qm="1.0.0",yd=["anyray-claude-acp","anyray-codex-acp"],xF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Qm=()=>hd(md(),".windsurf","acp","registry.json"),eh=()=>hd(md(),".windsurf-next","acp","registry.json"),Ca=e=>`${e}.anyray-state`,tS=e=>({binary:Object.fromEntries(xF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),rS=(e="npx")=>{let t=ui(e,"windsurf");return[{id:yd[0],name:Gn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:tS(t[Gn])},{id:yd[1],name:Vn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:tS(t[Vn])}]},fd=e=>!Array.isArray(e)||e.some(t=>!ho(t)||typeof t.id!="string")?null:e,RF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==qm||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:fd(e.agents);if(!n)return null;let r=new Set(yd);return{...e,version:typeof e.version=="string"?e.version:qm,agents:[...n.filter(o=>!r.has(o.id)),...rS(t)],extensions:e.extensions??[]}},OF=(e,t,n)=>{let r=fd(e.agents);if(!r)return null;let o=fd(t.agents)??[],a=new Map((fd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!yd.includes(u.id)){l.push(u);continue}if(!cd(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===qm&&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}},nS=async()=>{let e=[];return(await x(eh())||await x(hd(md(),".windsurf-next")))&&e.push(eh()),(await x(Qm())||await x(hd(md(),".windsurf"))||await x(Le("Devin"))||await x(Le("Windsurf")))&&e.push(Qm()),e},oS={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await nS();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await nS();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=sd();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=RF(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await x(s),d=rS(r);await qi({configPath:s,current:i,next:c,journalPath:Ca(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Ca(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=[Qm(),eh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await ce(a),await zm(Ca(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(Ca(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 x(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 $r(a);let f=OF(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 zm(a,{force:!0}):await J(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 ce(a),await zm(Ca(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await zi(a,Ca(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var pe=[rr,Xw,Os,qA,EC,MC,VC,eS,Wv,oS,ob],ut=e=>pe.find(t=>t.id===e);var We=async(e=P,t=yn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:Oe({origin:n.gateway,clientKey:n.clientKey,subscription:n.authMode==="subscription",placeholder:n.authMode==="placeholder",byoUpstream:n.byoUpstream,seat:r,user:n.name,team:n.team})}};var th=5e3,aS=3e4,TF=1440*60*1e3,_F=e=>new Promise(t=>setTimeout(t,e)),PF=async(e=P,t=yn)=>(await We(e,t))?.target,DF=e=>ut(e)?.quitGated,sS=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??DF,o=t.readPending??Kc,a=t.clearPending??Wp,s=t.targetFromProfile??PF,i=t.sleep??_F,c=t.now??Date.now,l=t.maxWaitMs??TF;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=th;for(;;){let m=await o(n);if(!m||c()-f>l)return 0;if(d.isRunning()){await i(p),p=Math.min(aS,p*2);continue}let y;if(d.needsTarget?.(m.op)&&(y=await s(),!y)){if(await a(n,m)!=="superseded")return 0;await i(p),p=th;continue}if((await u(m.op,y,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(p),p=Math.min(aS,p*2);continue}if(await a(n,m)!=="superseded")return 0;await i(p),p=th}}catch{return 0}};import{writeFileSync as CW}from"node:fs";import{chmod as fh,stat as kW}from"node:fs/promises";import{platform as MS}from"node:os";import{dirname as BS,isAbsolute as vW}from"node:path";var LF="https://app.anyray.ai",NF=new Set(["localhost","::1","[::1]"]),$F=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,MF=e=>NF.has(e)||$F.test(e),nh=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&MF(t.hostname)},BF=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||!nh(e)?LF:BF(e)};import{createHash as zF,generateKeyPairSync as qF,randomBytes as ah}from"node:crypto";import{createPrivateKey as FF,sign as WF}from"node:crypto";var Ir=async(e,t)=>{let n=FF(t);return WF(null,new TextEncoder().encode(e),n).toString("base64url")};var UF=["HTTPS_PROXY","https_proxy"],iS=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"]),cS=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),lS=new Set(["ENOTFOUND","EAI_AGAIN"]),dS=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),uS=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),HF=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 GF(e)},GF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...iS,...cS,...lS,...dS,...uS])if(t.includes(n))return n}},VF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",KF=e=>UF.filter(t=>(e[t]??"").trim()!==""),jF=(e,t=process.env)=>{let n=HF(e),r=KF(t);return{kind:n&&iS.has(n)?"tls-unknown-issuer":n&&cS.has(n)?"tls-invalid-cert":n&&lS.has(n)?"dns":VF(e)||n&&uS.has(n)?"timeout":n&&dS.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},ZF=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}},pt=(e,t=process.env)=>ZF(jF(e,t));var YF="enl_",pS="enp_",fS=e=>e.startsWith(YF)||e.startsWith(pS),rh=e=>e.startsWith(pS),JF=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],oh=e=>JF.find(t=>e.startsWith(t.prefix)),mS=/^\/enroll\/([^/]+)\/?$/,hS=/^\/i\/([^/]+)\/?$/,yS=e=>{let t=e.match(mS);if(t)return oh(t[1])?void 0:t[1];let n=e.match(hS);return n&&fS(n[1])?n[1]:void 0},XF=1e4,gd=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=yS(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!oh(t))return{cpOrigin:Kn(),token:t}},gS=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(mS)??o.pathname.match(hS);if(!a)return;n=a[1]}catch{}let r=oh(n);return r?{flag:r.flag,what:r.what}:void 0},mi=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:yS(n.pathname)!==void 0}catch{return fS(t)}},ka=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},fi=e=>typeof e=="string"&&e.trim()?e.trim():void 0,wS=async(e,t={})=>{let n=t.timeoutMs??XF,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.`:pt(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${f}`)}finally{clearTimeout(a)}if(!s.ok){let u=`enrollment link lookup failed: ${e.cpOrigin} responded ${s.status} \u2014 the link may be expired or revoked; ask your admin for a fresh one.`;throw s.status>=400&&s.status<500&&s.status!==429?new ka(u):new Error(u)}let i;try{i=await s.json()}catch{throw new Error(`enrollment link lookup failed: ${e.cpOrigin} returned a malformed response`)}let l=(Array.isArray(i?.gateways)?i.gateways:[]).find(u=>u!==null&&typeof u=="object"&&fi(u.url)!==void 0),d=fi(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:fi(l?.deploymentId),org:fi(i.org),email:fi(i.email),seatMode:i.seatMode===!0,...i.provisioningKind==="manual"||i.provisioningKind==="mdm"?{provisioningKind:i.provisioningKind}:{},...i.provisioningProofMode==="managed-preference"?{provisioningProofMode:i.provisioningProofMode}:{},...Array.isArray(i.allowedDomains)?{allowedDomains:i.allowedDomains.filter(u=>typeof u=="string"&&u.length>0)}:{}}};var ke="0.11.178";var sh=1e4,go=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(go).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${go(e[n])}`).join(",")}}`,bS="stable-key-heartbeat-v1",AS="key-heartbeat",QF=["reapply_config","remint","revert"],ih=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var CS=e=>zF("sha256").update(e).digest("hex"),je=e=>typeof e=="string"&&e.trim()?e.trim():void 0,eW=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],kS={no_mdm_server_registered:"no MDM server is registered in the Anyray console",agent_missing:"the Anyray endpoint agent is not reporting for this machine",mdm_not_verified:"this machine is not enrolled in the registered MDM",endpoint_unreachable:"the endpoint service could not be reached"},tW=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${kS[e]}. Ask your IT admin.`,nW=e=>typeof e=="string"&&e in kS,ch=async e=>{try{let t=await e.json(),n=je(t?.message),r=je(t?.error),o=nW(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:tW(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},rW=async e=>(await ch(e)).message,ct=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this enrollment (HTTP ${t}): ${r.message}`),this.name="GatewayVerifyError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},vS=e=>e instanceof ka||e instanceof ct&&e.policyCode==="sso_required",va=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this credential heartbeat (HTTP ${t}): ${r.message}`),this.name="GatewayHeartbeatError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},lh=async(e,t,n,r)=>{try{return await r(go(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},wd=()=>{let{publicKey:e,privateKey:t}=qF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},qt=async(e,t,n,r={})=>{let o=r.timeoutMs??sh,a=`${e}/connect/verify`,s=je(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:ah(16).toString("hex"),...ih(t,r.machineUuid)},c=await lh(i,n,"verification",r.signer??Ir),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":ke},body:JSON.stringify({cert:t,challenge:i,sig:c,...r.health?{health:r.health}:{},...r.ack?{ack:r.ack}:{},...r.telemetryOnly?{telemetryOnly:!0}:{}}),signal:l.signal})}catch(w){let b=w instanceof Error&&w.name==="AbortError"?` no response within ${o}ms.`:pt(w);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:w})}finally{clearTimeout(d)}if(!u.ok)throw new ct(u.status,await ch(u));let f;try{f=await u.text()}catch{f=""}let p;try{p=JSON.parse(f)}catch{let w=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(w)||/^\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 m=je(p?.key);if(!m)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(m))throw new Error("developer verification failed: the gateway returned a malformed key");let y=je(p.user);if(!y)throw new Error("developer verification failed: the gateway response is missing the user");let g=oW(p.directive),h=eW(p.capabilities);return{key:m,user:y,team:je(p.team),expiresAt:je(p.expiresAt),...h.length>0?{capabilities:h}:{},...g?{directive:g}:{}}},SS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??sh,s=`${e}/connect/key/heartbeat`,i=je(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:ah(16).toString("hex"),purpose:AS,...ih(n,o.machineUuid)},l=await lh(c,r,"heartbeat",o.signer??Ir),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":ke},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(y){let g=y instanceof Error&&y.name==="AbortError"?` no response within ${a}ms.`:pt(y);throw new Error(`could not reach the gateway at ${s}.${g}`,{cause:y})}finally{clearTimeout(u)}if(!f.ok)throw new va(f.status,await ch(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let m=je(p.expiresAt);if(!m||!Number.isFinite(Date.parse(m))||p.credentialMode!==bS||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:m,credentialMode:bS}},ES=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??sh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=je(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:ah(16).toString("hex"),purpose:AS,...ih(n,o)},d=await lh(l,r,"heartbeat",a.signer??Ir),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":ke},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)}},oW=e=>{if(e===null||typeof e!="object")return null;let t=e,n=je(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!QF.includes(r)?null:{id:n,kind:r}},aW=1e4,sW=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!je(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!je(r.deploymentId)&&!!je(r.user)&&!!je(r.devPublicKey)&&!!je(r.issuedAt)&&!!je(r.expiresAt)},iW=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??aW,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.`:pt(u);throw new Error(`could not reach the control plane at ${s}.${f}`)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await rW(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new ka(u):new Error(u)}let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!sW(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},IS=(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())},xS=async e=>{let t={timeoutMs:e.timeoutMs,machineUuid:e.machineUuid,signer:e.signer},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=wd();return{cert:await iW(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await qt(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};var dh=1e4,cW=900*1e3,OS="tnt_",lW=/^\/sso\/([^/]+)\/?$/,dW=/^\/i\/([^/]+)\/?$/,uW=e=>{let t=e.match(lW);if(t)return t[1];let n=e.match(dW);return n?.[1].startsWith(OS)?n[1]:void 0},Et=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=uW(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(OS))return{cpOrigin:Kn(),tenantId:t}},wo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Bt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},uh=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)}},pW=e=>new Promise(t=>setTimeout(t,e)),bd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??wd)(),a;try{a=await uh(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},dh,n)}catch(m){throw new wo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${pt(m)}`)}if(a.status!==200){let m=a.status===404,y=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new wo(m?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${y}). Ask your admin to confirm SSO is configured.`,a.status)}let s=a.json;if(!s.device_code||!s.user_code||!s.verification_uri_complete)throw new wo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??cW,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}`),fW(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},fW=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Ad=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??pW,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 uh(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},dh,o)}catch(c){throw new Bt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${pt(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 Bt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Bt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Bt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var RS="sdc_",TS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(RS))return{cpOrigin:Kn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!nh(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(RS)))return{cpOrigin:n.origin,claim:r}},_S=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??wd)(),o;try{o=await uh(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},dh,t)}catch(s){throw new Bt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${pt(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 Bt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Bt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Bt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};import{readFile as mW}from"node:fs/promises";import{isAbsolute as hW,posix as PS,win32 as ph}from"node:path";var hi=(e=process.platform,t=process.env)=>e==="darwin"?PS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?ph.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):PS.join("/etc","anyray","bootstrap.json"),yW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),DS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(hW(e)||ph.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),gW=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}},xr=async(e=hi())=>{try{let t=await mW(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!yW(n)||n.v!==1||typeof n.sso!="string")return;let r=Et(n.sso);if(!r)return;let o=gW(n.gateway)?n.gateway:void 0,a=DS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},LS=(e,t,n)=>{let r=Et(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!DS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&ph.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)}
|
|
262
|
-
`};var Sa=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Cd=Sa(process.stdout,process.env),
|
|
263
|
-
${j(e)}`),N=e=>console.log(v(e)),B=e=>console.log(`${
|
|
254
|
+
}`,Hn=async e=>new Promise((t,n)=>{let r=cM("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",AM],{windowsHide:!0,stdio:["pipe","pipe","pipe"]}),o="",a=!1,s=!1;r.stdout.setEncoding("utf8"),r.stdout.on("data",i=>{o+=i,o.length>1024*1024&&(a=!0,r.kill())}),r.stderr.resume(),r.on("error",i=>{s||(s=!0,n(new Error(wm(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(wm({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Mt=(e={})=>ha((e.home??km)(),".anyray","claude-desktop-windows.json"),CM=e=>ha((e.home??km)(),".anyray","claude-desktop-windows.lock"),pa=class extends Error{},kM=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Em=async e=>{let t=CM(e);await hm(ai(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=Wk("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=ha(t,"owner.json");try{await hm(t,{mode:448}),await we(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
255
|
+
`)}catch(a){if(a.code!=="EEXIST")throw await Jt(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await ym(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!kM(i.pid)}catch{try{s=Date.now()-(await Kk(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new pa;await Jt(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await ym(o,"utf8")).nonce===r&&await Jt(t,{recursive:!0,force:!0})}catch{}}}throw new pa},zk=()=>Object.fromEntries(Ne.map(e=>[e,{present:!1}])),lo=e=>Wk("sha256").update(e).digest("hex"),vM=(e,t)=>t.present?e===ya?{present:!0,type:t.type,sha256:lo(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},da=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?lo(e.value??"")===t.sha256:e.value===t.value:!0,$t=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Gl=(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===ya?$t(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:$t(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},Tk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&$t(e,Ne)&&Ne.every(t=>Gl(e[t],t)),_k=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&$t(e,Ek)&&Ek.every(t=>Gl(e[t],t)),SM=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),Im=(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 $t(n,r)&&n.path===vm(t)&&(n.lastWritten===void 0||Ok(n.lastWritten))&&(n.pending===void 0||Ok(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},EM=(e,t)=>$t(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Hl&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&Tk(e.lastWritten)&&(e.pending===void 0||Tk(e.pending))&&Im(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),IM=e=>$t(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Pe&&typeof e.keyExisted=="boolean"&&_k(e.lastWritten)&&(e.pending===void 0||_k(e.pending)),Pk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&$t(e,Ik)&&Ik.every(t=>Gl(e[t],t)),xM=(e,t)=>$t(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"&&Pk(e.lastWritten)&&(e.pending===void 0||Pk(e.pending))&&Im(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),Dk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&$t(e,xk)&&xk.every(t=>Gl(e[t],t)),RM=(e,t)=>$t(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"&&Dk(e.lastWritten)&&(e.pending===void 0||Dk(e.pending))&&Im(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),Lk=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),xm=e=>{let{pending:t,...n}=e;return{...n,version:Hl,lastWritten:Lk(e.lastWritten),...t?{pending:Lk(t)}:{}}},Nk=e=>({...e,chatTabEnabled:{present:!1}}),OM=e=>{let{pending:t,...n}=e;return xm({...n,version:4,lastWritten:Nk(e.lastWritten),...t?{pending:Nk(t)}:{}})},$k=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),TM=(e,t)=>xm({version:4,registryKey:Pe,keyExisted:e.keyExisted,lastWritten:$k(e.lastWritten),...e.pending?{pending:$k(e.pending)}:{},helper:{path:vm(t)}}),Rm=async(e,t=!0)=>{let n=Mt(e),r=ai(n),o=`${jk(n)}.anyray-old-`,a=(await Gk(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>ha(r,l)),s=n;if(!await x(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await Vk(a[0],n):s=a[0]}let i=await M(s),c=IM(i)?TM(i,e):xM(i,e)?OM(i):RM(i,e)?xm(i):EM(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>Jt(l,{force:!0}))),c},Mk=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),_M=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Pe,keyExisted:e.keyExisted,lastWritten:Mk(e.lastWritten),...e.pending?{pending:Mk(e.pending)}:{}}:e,Fl=async(e,t)=>{let n=Mt(t),r=`${JSON.stringify(_M(e),null,2)}
|
|
256
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},PM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,DM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),LM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),NM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),$M=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===NM(t).toUpperCase(),Bk=(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},MM=e=>e==="String"?"REG_SZ":e==="ExpandString"?"REG_EXPAND_SZ":e==="DWord"?"REG_DWORD":e==="QWord"?"REG_QWORD":e==="MultiString"?"REG_MULTI_SZ":e==="Binary"?"REG_BINARY":e==="None"?"REG_NONE":e,BM=(e,t)=>{if(!Dl(e,!0))return!1;let n=MM(t);if(LM.has(n))return!1;if(DM.has(n))return n==="REG_EXPAND_SZ"?!0:!ek(e,!0)},FM=(e,t)=>{let n=zk(),r=!1,o=!1,a=!1,s=t.toUpperCase()===oi.toUpperCase(),i=(l,d)=>{if(!s)return;let u=BM(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),Bk(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||$M(d,t))continue;let u=PM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),Bk(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:zk(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return FM(n.stdout,t)},Sr=async e=>{let t=await Un(e,oi);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...Ne.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},Om=e=>e.unparsed?`This machine may have a Claude policy under ${oi} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${oi} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${oi} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Vl=(e,t)=>vr(io(e,t)),qk=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],WM=(e,t)=>{let n=Vl(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}]}))},UM=(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}}),HM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,bm=e=>Object.fromEntries(Ne.map(t=>[t,vM(t,e[t])])),Fk=(e,t,n,r)=>({version:Hl,registryKey:Pe,keyExisted:e,lastWritten:bm(t),helper:{path:n,lastWritten:gm(r)}}),GM=(e,t,n,r,o,a)=>({version:Hl,registryKey:Pe,keyExisted:e,lastWritten:bm(t),pending:bm(n),helper:{path:r,...o?{lastWritten:gm(o)}:{},pending:gm(a)}}),Am=(e,t,n)=>da(n,e.lastWritten[t])||e.pending!==void 0&&da(n,e.pending[t]),fa=async e=>{try{let t=await ym(e,"utf8");return{content:t,sha256:lo(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ma=async e=>(await fa(e))?.sha256,ua=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Ul=async(e,t)=>{let n=wM(e),r;try{r=await Gk(ai(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>ha(ai(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([fa(e),fa(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ua(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await Xk(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ua(t,s.sha256)&&ua(t,i.sha256)){await Jt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Tm=async(e,t,n)=>(n.present?await e(qk(Pe,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Pe,"/v",t,"/f"])).code===0,VM=async(e,t,n)=>{let r=!0,o=await Un(e);for(let a of Ne)if(!la(o.values[a],t[a])){if(!la(o.values[a],n[a])){r=!1;continue}await Tm(e,a,t[a])||(r=!1),o=await Un(e)}return r&&Ne.every(a=>la(o.values[a],t[a]))},Xe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Mt(n)]}}),Qk=async(e,t,n,r={})=>{if(!be(t))return Xe("A valid personal ark_ gateway key is required.",!1,r);let o=vm(r),a;try{a=fM((r.credentialCommand??im)())}catch{return Xe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=lo(a),i=r.runReg??Hn,c=Mt(r),l;if(!n.dryRun)try{l=await Em(r)}catch(h){return Xe(h instanceof pa?"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,m=!1;try{let h=await Sr(i);if(h)return Xe(Om(h),!1,r);let g=await Rm(r,!n.dryRun);n.dryRun||await Ul(o,g);let y=await Un(i),w=WM(e,o),b=await fa(o),k=b?.sha256,C=!1;if(d=g,u=y,f=w,g){let I=Ne.find(O=>!Am(g,O,y.values[O]));if(I)return Xe(`Claude's ${I} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!ua(g,k))return Xe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=HM(g)}else{if(k!==void 0&&k!==s)return Xe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let I=y.foreignState||Ne.some(U=>y.values[U].present),O=Ne.every(U=>la(y.values[U],w[U])),T=Ne.every(U=>la(y.values[U],UM(e,t.trim())[U]));if(I&&!O&&!T)return Xe(`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(C=T,O&&k===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 Fl(Fk(y.keyPresent,w,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Pe} into the ownership journal.`]})}if(C){let I=!0;try{I=(r.appRunning??Sm)()}catch{}if(I)return Xe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let S=GM(g?.keyExisted??y.keyPresent,y.values,w,o,b?.content,a);if(p=S,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 Fl(S,r),m=!0;for(let I of Ne){let O=await Un(i);if(!da(O.values[I],S.lastWritten[I])&&!da(O.values[I],S.pending[I]))throw new Error("registry value changed during apply");if(!la(O.values[I],w[I])&&!await Tm(i,I,w[I]))throw new Error("registry write failed")}let E=await Un(i);if(!Ne.every(I=>da(E.values[I],S.pending[I])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await gM(o,a):await Wl(o,k,a,"apply",r)),await ma(o)!==s)throw new Error("credential helper verification failed");return await Fl(Fk(S.keyExisted,w,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.",...Tl]}}catch{if(!m||!u||!f||!p)return Xe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Ul(o,p);let h=!0,g=await fa(o),y=p.helper.pending;if(g?.sha256!==p.helper.lastWritten?.sha256&&(y!==void 0&&g?.sha256===y.sha256?p.helper.lastWritten?(await Wl(o,y.sha256,p.helper.lastWritten.content,"rollback",r),h=await ma(o)===p.helper.lastWritten.sha256):await Wl(o,y.sha256,void 0,"rollback",r):h=g===void 0&&p.helper.lastWritten===void 0),h&&await VM(i,u.values,f))return d?await Fl(d,r):await Jt(c,{force:!0}),Xe("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return Xe("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},ev=async(e,t={})=>{let n=t.runReg??Hn,r=Mt(t),o;if(!e.dryRun)try{o=await Em(t)}catch(a){return Xe(a instanceof pa?"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 Rm(t,!e.dryRun);a&&!e.dryRun&&await Ul(a.helper.path,a);let s=await Un(n);if(!a)return Ne.filter(m=>s.values[m].present).length>0?Xe(`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=Ne.filter(p=>s.values[p].present&&!Am(a,p,s.values[p])),c=await ma(a.helper.path),l=c!==void 0&&!ua(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 Ne){let h=(await Un(n)).values[p];if(h.present){if(!Am(a,p,h)){u.add(p);continue}await Tm(n,p,{present:!1})||(d=!0)}}let f=await ma(a.helper.path);if(f!==void 0)if(ua(a,f))try{await Wl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?Xe(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await Jt(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?[]:_l]})}catch{return Xe(`Could not safely inspect or revert ${Pe}; no unproven value was removed.`,!1,t)}finally{await o?.()}},tv=async(e,t={})=>{let n=t.runReg??Hn;if(!await x(Mt(t)))return;let r;try{r=await Em(t);let o=await Rm(t);if(o&&await Ul(o.helper.path,o),!o||o.pending||await Sr(n)!==void 0)return;let a=await Un(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Gt(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Ne.every(l=>da(a.values[l],o.lastWritten[l]))))return;let i=await ma(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 yM(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?.()}},nv=async(e,t={})=>await tv(e,t)!==void 0,rv=async(e,t={})=>await tv(e,t)==="dynamic";var ga=(e=jM())=>e==="win32"?Sm:$l,_m="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",jl=async(e,t={})=>{let n=(t.profileRoot??so)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:_m};if((t.appRunning??ga(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await ov.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 Ol(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 "+_m}:{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??ZC)();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=Kl(t.stagingRoot??ZM(),`anyray-history-${process.pid}-${KM()}`);try{let s=await(t.runImporter??YC)({binary:o,exportPath:e,configDir:Kl(a,"config"),workDir:Kl(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. "+_m};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 XC(r.dir,s.conversations),c=await zC({stagedProjectsDir:Kl(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 ov.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as St}from"node:fs";import{homedir as hB}from"node:os";import{join as zt,sep as yB}from"node:path";import{isDeepStrictEqual as Xl}from"node:util";import{constants as YM}from"node:fs";import{promises as V}from"node:fs";import{dirname as wa,isAbsolute as Dm,join as re,relative as Zl,resolve as Xt,sep as si}from"node:path";import{randomUUID as zl}from"node:crypto";var Cn=448,ii=384,cv=448,JM=4,Lm=3e4,lv=5e3,XM=10*6e4,Pm=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),it=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ci=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),dv=(e,t)=>{let n=Zl(Xt(e),Xt(t));return n===""||!n.startsWith(`..${si}`)&&n!==".."&&!Dm(n)},uo=async e=>{try{let t=await V.readFile(e,"utf8"),n=JSON.parse(t);return it(n)?{raw:t,value:n}:void 0}catch(t){return vt(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},vt=e=>e instanceof Error&&"code"in e,zM=e=>{try{return process.kill(e,0),!0}catch(t){return vt(t)&&t.code==="EPERM"}},uv=e=>e===0?"owner.json":`owner.${e}.json`,Yl=async e=>{let t;try{t=await V.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=re(e,r.name),a,s,i;try{let d=JSON.parse(await V.readFile(o,"utf8"));it(d)&&typeof d.pid=="number"&&Number.isSafeInteger(d.pid)&&d.pid>0&&typeof d.nonce=="string"&&d.nonce.length>0&&(a=d.pid,s=d.nonce,typeof d.createdAt=="number"&&Number.isFinite(d.createdAt)&&d.createdAt>=0&&(i=d.createdAt))}catch{}let c=await V.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}},pv=e=>{if(e.pid===void 0||!zM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Lm&&t-e.createdAtMs>XM},qM=async e=>{let t=`${e}.anyray-lock`;await V.mkdir(wa(t),{recursive:!0,mode:Cn});let n=zl(),r,o=!1;try{await V.mkdir(t,{mode:Cn}),o=!0}catch(i){if(!vt(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Yl(t);if(d){if(!pv(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await V.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=Lm)return}let l=re(t,uv(c));try{await V.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
257
|
+
`,{flag:"wx",mode:ii}),r=l}catch(d){if(vt(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await V.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await V.readFile(a,"utf8"));if(!it(i)||i.nonce!==n)return;let c=new Date;await V.utimes(a,c,c)}catch{}})()},lv);return s.unref(),async()=>{clearInterval(s);try{(await Yl(t))?.nonce===n&&await V.rm(t,{recursive:!0,force:!0})}catch{}}},QM=async(e,t,n)=>{await V.mkdir(wa(e),{recursive:!0,mode:Cn});let r=await qM(e);if(!r)return!1;try{let o;try{o=await V.readFile(e,"utf8")}catch(s){if(!vt(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${zl()}`;try{await V.writeFile(a,`${JSON.stringify(n,null,2)}
|
|
258
|
+
`,{mode:ii,flag:"wx"}),await V.rename(a,e)}catch(s){try{await V.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},ql=async(e,t)=>{for(let n=0;n<JM;n+=1){let r=await uo(e);if(!r)return"failed";let o=t(r.value);if(!o||Xl(o,r.value))return"unchanged";try{if(await QM(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},av=async e=>{try{return(await V.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},Ql=async e=>{let t=[];for(let n of await av(e))for(let r of await av(re(e,n)))t.push(re(e,n,r));return t},eB=e=>Array.isArray(e.skills)?e.skills.filter(t=>it(t)&&ci(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],tB=async e=>{let t=re(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await Ql(t)){let o=await uo(re(r,"manifest.json"));if(!o)continue;let a=r.split(si).at(-1)??"";for(let s of eB(o.value))n.push({account:a,packageDir:r,entry:s})}return n},nB=async e=>{let t=await uo(re(e,".claude-plugin","plugin.json"));return!!t&&ci(t.value.name)},rB=(e,t)=>{let n=Dm(t)?Xt(t):Xt(e,t);if(!dv(e,n)||n===Xt(e))return;let r=Zl(Xt(e),n);return r.length>0?{absolute:n,relative:r}:void 0},oB=async e=>{let t=await Ql(re(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(si).includes("skills-plugin"))continue;let o=re(r,"cowork_plugins"),a=await uo(re(o,"installed_plugins.json"));if(!a||!it(a.value.plugins))continue;let s=r.split(si).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!ci(i)||!Array.isArray(c)))for(let l of c){if(!it(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=rB(o,l.installPath);!d||!await nB(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:re(r,"cowork_account_settings.json")})}}return n},aB=async e=>{let t=await uo(re(e,"claude_desktop_config.json"));return!t||!it(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>ci(n)&&n.toLowerCase()!=="anyray"&&it(r)))},fv=async e=>{let[t,n,r]=await Promise.all([tB(e),oB(e),aB(e)]);return{skills:t,plugins:n,localMcpServers:r}},Nm=async e=>{let t=await fv(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)}},sv=async e=>{try{let n=await V.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())return!1}catch{return!1}let t=async n=>{let r;try{r=await V.readdir(n,{withFileTypes:!0})}catch{return!1}for(let o of r){if(!ci(o.name))return!1;let a=re(n,o.name);if(o.isSymbolicLink())return!1;if(o.isDirectory()){if(!await t(a))return!1}else if(!o.isFile())return!1}return!0};return t(e)},sB=async e=>{let t=async n=>{let r=await V.readdir(n,{withFileTypes:!0});for(let o of r){let a=re(n,o.name);if(o.isDirectory())await t(a),await V.chmod(a,Cn);else if(o.isFile()){let s=await V.stat(a);await V.chmod(a,(s.mode&73)!==0?cv:ii)}}};await t(e),await V.chmod(e,Cn)},mv=async(e,t)=>{try{let[n,r]=await Promise.all([V.readFile(e),V.readFile(t)]);return n.equals(r)}catch{return!1}},Jl=async(e,t)=>{try{let[n,r]=await Promise.all([V.readdir(e,{withFileTypes:!0}),V.readdir(t,{withFileTypes:!0})]),o=n.map(s=>s.name).sort(),a=r.map(s=>s.name).sort();if(!Xl(o,a))return!1;for(let s of o){let i=n.find(l=>l.name===s),c=r.find(l=>l.name===s);if(!i||!c||i.isDirectory()!==c.isDirectory()||i.isFile()!==c.isFile())return!1;if(i.isDirectory()){if(!await Jl(re(e,s),re(t,s)))return!1}else if(!i.isFile()||!await mv(re(e,s),re(t,s)))return!1}return!0}catch{return!1}},hv=e=>`${e}.anyray-incomplete`,yv=async(e,t)=>{let n=!1;if(t){await V.mkdir(wa(e),{recursive:!0,mode:Cn});try{await V.mkdir(e,{mode:Cn}),n=!0}catch(l){if(!vt(l)||l.code!=="EEXIST")return}}else try{let l=await V.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=zl(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await Yl(e)}catch{return}if(f){if(!pv(f)||!Number.isSafeInteger(f.generation+1))return;d=f.generation+1}else if(await V.stat(e).then(m=>Date.now()-m.mtimeMs).catch(()=>0)<=Lm)return}let u=re(e,uv(d));try{await V.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
259
|
+
`,{flag:"wx",mode:ii}),o=u}catch(f){if(vt(f)&&f.code==="EEXIST"){n=!1;continue}n&&await V.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await V.readFile(a,"utf8"));if(!it(l)||l.nonce!==r)return;let d=new Date;await V.utimes(a,d,d)}catch{}})()},lv);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Yl(e))?.nonce===r&&await V.rm(e,{recursive:!0,force:!0})}catch{}}}},gv=async e=>{let t=await yv(e,!1);t&&await t.complete()},iB=async(e,t,n)=>{let r=hv(t),o=!1;try{let c=await V.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Jl(e,t))return await gv(r),"present"}catch(c){if(!vt(c)||c.code!=="ENOENT")return"failed"}if(o)try{let c=await V.lstat(r);if(!c.isDirectory()||c.isSymbolicLink())return"conflict"}catch{return"conflict"}let a=await yv(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await V.mkdir(t,{mode:Cn})}catch(c){if(!vt(c)||c.code!=="EEXIST")return a.abandon(),"failed";try{let l=await V.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 V.readdir(c,{withFileTypes:!0})}catch{return"failed"}for(let u of d){let f=re(c,u.name),p=re(l,u.name);try{if(u.isDirectory()){try{await V.mkdir(p,{mode:Cn})}catch(h){if(!vt(h)||h.code!=="EEXIST")throw h;let g=await V.lstat(p);if(!g.isDirectory()||g.isSymbolicLink())return"conflict"}let m=await s(f,p);if(m!=="copied")return m}else if(u.isFile())try{await V.copyFile(f,p,YM.COPYFILE_EXCL);let m=await V.stat(f);await V.chmod(p,(m.mode&73)!==0?cv:ii)}catch(m){if(!vt(m)||m.code!=="EEXIST")throw m;if(!await mv(f,p))return"conflict"}else return"failed"}catch(m){return vt(m)&&m.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await Jl(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},wv=async(e,t,n,r)=>{if(!await sv(e))return"invalid";try{let a=await V.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Jl(e,t))return await gv(hv(t)),"present"}catch(a){if(!vt(a)||a.code!=="ENOENT")return"failed"}await V.mkdir(wa(t),{recursive:!0,mode:Cn});let o=re(wa(t),`.anyray-stage-${zl()}`);try{return await V.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await sv(o)?(await sB(o),await n?.(t),await iB(o,t,r)):"invalid"}catch{return"failed"}finally{try{await V.rm(o,{recursive:!0,force:!0})}catch{}}},iv=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),cB=async e=>{let t=await Ql(re(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await uo(re(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},lB=async e=>{let t=await Ql(re(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(si).includes("skills-plugin"))try{await V.access(re(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},dB=async(e,t,n,r,o)=>{let a=re(t,"manifest.json");for(let s of e){let i=re(s.packageDir,"skills",s.entry.name);try{await V.access(re(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=re(t,"skills",s.entry.name),l=await wv(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 ql(a,f=>{let p=Array.isArray(f.skills)?f.skills:[];if(p.find(h=>it(h)&&typeof h.name=="string"&&h.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}},bv=(e,t)=>({...e,installPath:t}),uB=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=Dm(r.installPath)?Xt(r.installPath):Xt(o,r.installPath),s=bv(e,Zl(Xt(t),Xt(n))),i={...r,installPath:Zl(Xt(o),a)};return Xl(s,i)},pB=async(e,t,n)=>{let r=await uo(e);if(!r||!it(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":ql(t,a=>{let s=it(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},fB=async(e,t,n,r,o)=>{let a=re(t,"cowork_plugins"),s=re(a,"installed_plugins.json"),i=re(t,"cowork_account_settings.json");for(let c of e){let l=re(a,c.relativeInstallPath);if(!dv(a,l)){n.invalid+=1;continue}let d=await wv(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 ql(s,m=>{let h=it(m.plugins)?m.plugins:{},g=h[c.id],y=Array.isArray(g)?g:[],w=y.find(k=>it(k)&&k.scope==="user");if(w){u=uB(c.entry,wa(c.settingsFile),c.packageDir,w,t),f=!u;return}let b=bv(c.entry,l);return{...m,version:typeof m.version=="number"?m.version:2,plugins:{...h,[c.id]:[...y,b]}}})==="failed"?n.failed+=1:f?n.conflicts+=1:await pB(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},mB=async(e,t,n)=>{let r=re(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await ql(r,c=>{let l=it(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=Xl(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}},Av=async(e,t,n={})=>{let r=await fv(e),o=Pm("skill"),a=Pm("plugin"),s=Pm("local-mcp"),i=[],c=[],l=iv(r.skills,n.account,n.allAccounts),d=iv(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let f=new Set(n.allowedAccounts);if([...new Set([...l.map(m=>m.account),...d.map(m=>m.account)])].some(m=>!f.has(m)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,sourceChanged:!0,retryable:[]}}if(l.length>0){let f=await cB(t);f.state==="found"?await dB(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 lB(t);f.state==="found"?await fB(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await mB(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 gB=async e=>{try{return await St.access(e),!0}catch{return!1}},Cv=448,wB=384,vv={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},bB=["code","cowork"],Bm=(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.",$m=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),Sv=async e=>{let t;try{t=(await St.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&aa(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await St.readdir(zt(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&aa(a.name)).map(a=>a.name);for(let a of o)n.push(zt(e,r,a))}catch{}return n},AB=async e=>{try{return(await St.readdir(e)).filter(t=>t.startsWith(Fn)&&t.endsWith(".json")).map(t=>t.slice(Fn.length,-5)).filter(aa)}catch{return[]}},CB=async(e,t)=>{let n=await Sv(zt(e,vv[t])),r=[];for(let o of n){let a=await AB(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(yB).slice(-2)[0]})}return r},kB=async(e,t)=>{if(t==="cowork"){let r=await Ol(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await Sv(zt(e,vv.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},vB=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await St.copyFile(e,n),await St.chmod(n,wB),await St.rename(n,t)},SB=async(e,t)=>{try{let n=JSON.parse(await St.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||!aa(o)?!1:(await St.access(zt(t,".claude","projects",tm(r),`${o}.jsonl`)),!0)}catch{return!1}},EB=async(e,t,n,r)=>{let o=$m(e),a=await nm(n);for(let s of t)await IB(e,s,n,r,a,o);return o},IB=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=zt(t.dir,i);try{if(e==="code"){if(!await SB(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=zt(t.dir,`${Fn}${s}`),d=zt(n,`${Fn}${s}`),u=await St.readdir(l);await St.mkdir(d,{mode:Cv});for(let f of u)await St.cp(zt(l,f),zt(d,f),{recursive:!0,force:!1,errorOnExist:!0});await St.chmod(d,Cv)}await vB(c,zt(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},kv=(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(`
|
|
260
|
+
`)}},Mm=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),Ev=async e=>{let t=[];for(let n of bB)t.push({lane:n,sources:await CB(e,n)});return t},Iv=async(e={})=>{let t=(e.firstPartyRoot??(()=>Ys()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([Ev(t),Nm(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Mm(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}},po=async(e={})=>{let t=(e.home??hB)(),n=(e.firstPartyRoot??(()=>Ys()))(),r=(e.thirdPartyRoot??(()=>so()))();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??ga())())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([Ev(n),Nm(n)]),s;if(e.account){let p=e.account;for(let g of o)g.sources=g.sources.filter(y=>y.account.startsWith(p));let m=a.accounts.filter(g=>g.startsWith(p));if(o.every(g=>g.sources.length===0)&&m.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 h=Mm(o);for(let g of m)h.add(g);if(h.size>1)return kv(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${h.size} accounts`,m);s=[...h]}else if(!e.allAccounts){let p=Mm(o);for(let m of a.accounts)p.add(m);if(p.size>1)return kv(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 gB(r),l=await Av(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:m}of o){if(m.length===0){d.push($m(p));continue}let h=await kB(r,p);if("missing"in h){u.push({lane:p,reason:h.missing,waiting:m.reduce((g,y)=>g+y.ids.length,0)}),d.push($m(p));continue}d.push(await EB(p,m,h.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:Bm(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 xB=e=>[Le(e)],xv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...xB(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await x(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var Rv="1.21459.0",_B=TB(RB),PB=async e=>{try{let{stdout:t}=await _B("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},DB=async e=>{try{return await OB(e)}catch{return}},Ov="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",LB=["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."],ba=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(Tv??=_v({}),Tv):_v(e),Tv,_v=async e=>{let t=(e.home??di)(),n=["/Applications/Claude.app",kn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??PB,o=e.readClaudeAppBundle??DB;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} ${Ov}`}),c=xl(s,Rv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${Rv} or newer.`);let l=await o(kn(a,"Contents","Resources","app.asar"));return l?fk.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. ${Ov}`}},ed="anyray",Lv="--anyray-owner=claude-desktop-v1",td=(e={})=>{let t=(e.platform??Er)(),n=(e.home??di)();return t==="darwin"?Yt(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")},Gm=(e={})=>kn((e.home??di)(),"Library","Application Support","Claude","claude_desktop_config.json"),Nv=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,Lv]}},fo=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),$v=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},NB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),$B=e=>{if(!fo(e)||!$v(e,["command","args"]))return!1;let t=Nv();return e.command===t.command&&NB(e.args,t.args)},MB=e=>fo(e)&&Array.isArray(e.args)&&e.args.at(-1)===Lv,BB=e=>{if(!fo(e)||!$v(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||et(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!et(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},FB=e=>e===void 0?"absent":$B(e)?"exact":MB(e)||BB(e)?"stale-owned":"foreign",Fe=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},mo=async e=>{let t=await x(e),n;try{n=await M(e)}catch{throw new Fe(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!fo(n.mcpServers))throw new Fe(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(fo(n.mcpServers)?n.mcpServers:void 0)?.[ed];return{path:e,fileExisted:t,json:n,entry:o,ownership:FB(o)}},nd=e=>{if(e.ownership==="foreign")throw new Fe(`MCP name conflict in ${e.path}: mcpServers.${ed} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},Mv=(e,t)=>{let n={...e},r=fo(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[ed]:r[ed]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Wm=async(e,t)=>{if(Fm(e.entry,t))return;let n=await mo(e.path);if(!Fm(n.entry,e.entry))throw new Fe(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Wn(e.path,Mv(n.json,t)),{reading:e,afterEntry:t}},Um=async e=>{let t=await mo(e.reading.path);if(!Fm(t.entry,e.afterEntry))throw new Fe(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=Mv(t.json,e.reading.entry);await Wn(e.reading.path,n)},WB=async e=>{if(!ne())throw new Fe(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${_e()} is temporary); no inference setting was changed.`);let t=await mo(td(e));nd(t);let n=Gm(e),r=(e.platform??Er)()==="darwin"&&n!==t.path?await mo(n):void 0;return r&&nd(r),{active:t,...r?{legacy:r}:{}}},Pv=async e=>{let t=await mo(td(e));nd(t);let n=Gm(e),r=(e.platform??Er)()==="darwin"&&n!==t.path?await mo(n):void 0;return r&&nd(r),{active:t,...r?{legacy:r}:{}}},UB=async e=>{let t=[];try{let n=await Wm(e.active,Nv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Wm(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Um(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Fe(`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 Um(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Fe(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},HB=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Wm(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Um(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Fe(`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)},Dv=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)."]},GB={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},rd="claude-desktop",Hm="migrate",Bv=new Set(["app-running","store-missing"]),VB={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},KB={skill:{one:"user-created skill",many:"user-created skills"},plugin:{one:"user-installed plugin",many:"user-installed plugins"},"local-mcp":{one:"local MCP server",many:"local MCP servers"}},jB="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",Fv=e=>{let t=(e.platform??Er)(),n=e.home??di;return{home:n,appRunning:e.appRunning??ga(t),firstPartyRoot:()=>Ys({home:n,runtimePlatform:t}),thirdPartyRoot:()=>so({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Wv=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=VB[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.`:"")},Uv=e=>{let t=e.filter(s=>s.migrated>0),n=e.reduce((s,i)=>s+i.conflicts,0),r=e.reduce((s,i)=>s+i.invalid,0),o=e.reduce((s,i)=>s+i.failed,0);if(t.length===0&&n+r+o===0)return;let a=t.map(s=>{let i=KB[s.kind];return`${s.migrated} ${s.migrated===1?i.one:i.many}`});return(a.length>0?`Brought your portable Claude Desktop configuration across: ${a.join(", ")}.`:"Portable Claude Desktop configuration was checked; existing target entries were kept.")+(n>0?` ${n} conflicting target ${n===1?"entry was":"entries were"} preserved.`:"")+(r>0?` ${r} unsafe or incomplete ${r===1?"entry was":"entries were"} skipped.`:"")+(o>0?` ${o} could not be copied.`:"")},li=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=Fv(e),r=await(e.pendingDesktopMigrationCount??Iv)(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??po)(n);if(a.ok){let c=Wv(a.lanes),l=Uv(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(w=>w.reason!=="ambiguous"),p=a.blockedAssets??[],m=a.retryableAssets??[];if(f.length===0&&p.length===0&&m.length===0)return[c,l,u].filter(w=>!!w);if(t.preservePendingOp)return[c,l,u].filter(w=>!!w);await Ss(rd,Hm);let h=f.reduce((w,b)=>w+b.waiting,0),g=[h>0?`${h} more session${h===1?"":"s"}`:"",p.length>0?`${p.length} extension ${p.length===1?"store":"stores"}`:""].filter(Boolean),y=[...g.length>0?[`Queued: ${g.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...m.length>0?[`Queued: ${m.length} portable configuration ${m.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...y]}if(!Bv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
261
|
+
${a.remedy}`];if(t.preservePendingOp)return[];await Ss(rd,Hm);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."]}},ZB=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await ur(rd),[]}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."]}},YB=e=>xv({id:rd,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Er)(),n=(e.home??di)();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=>ee(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",...Dv(t)]:["Claude desktop org/API lane:",...Dv(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`."]}),JB=(e={})=>{let t=YB(e),n=()=>(e.platform??Er)()==="darwin",r=()=>(e.platform??Er)()==="win32",o=(s,i)=>n()?Ck(s,i,e):Qk(s,s.clientKey??"",i,e),a=s=>n()?kk(s,e):ev(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ga((e.platform??Er)()))(),quitTarget:GB,needsTarget:()=>!1,async complete(s){if(s!==Hm)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??po)(Fv(e));if(i.ok){let c=Wv(i.lanes),l=Uv(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(h=>h.reason!=="ambiguous"),p=i.blockedAssets??[],m=i.retryableAssets??[];return f.length>0||p.length>0||m.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."]:[],...m.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(h=>!!h):["No portable Claude Desktop data was left to bring across."]}}return Bv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?Sk(s,e):r()?rv(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=Yt(e),p=await co(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[pm(p),...await li(e,i)]}}if(r()){let f;try{f=await Sr(e.runReg??Hn)}catch{return{status:"manual",manualAudience:"admin",messages:[jB,...await li(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[Om(f),...await li(e,i)]}}if(r()&&ee(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let f=await ba(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await WB(e)}catch(f){let p=f instanceof Fe?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Fe?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 li(e,i)]}}let d;try{d=await UB(c)}catch(f){let p=f instanceof Fe?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Fe?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 li(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?LB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=td(e),c=await ZB(s),l=h=>c.length===0?h:{...h,messages:[...h.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await Pv(e)}catch(h){return l({status:"manual",messages:[h instanceof Fe?h.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let h=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...h&&h.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${h.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let h=r()?Mt(e):void 0;if(!(h!==void 0&&f.changedFiles?.includes(h)===!0&&!await x(h)))return l(f)}let p;try{p=await HB(await Pv(e))}catch(h){let g=h instanceof Fe?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...g])],messages:[...f.messages,h instanceof Fe?h.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await ce(i);let m=Gm(e);return n()&&m!==i&&await ce(m),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(!ne())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await mo(td(e));return s.ownership!=="exact"||!fo(s.entry)?{registered:!1,command:null,reason:s.fileExisted?s.ownership==="absent"?"absent":s.ownership==="stale-owned"?"stale":"foreign":"no-config"}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async pointsAt(s){return n()?(await ba(e)).supported?mm(s,e):!1:r()?nv(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await ba(e)).supported)return["unknown"];let s=await vk(e);return s?[s]:["unknown"]}if(r())return await x(Mt(e))?await Sr(e.runReg??Hn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=Yt(e);return!await x(s.journal)||await co(s,e)?!1:(await ba(e)).supported}return r()&&await x(Mt(e))?!await Sr(e.runReg??Hn):!1}catch{return!1}}}},Hv=JB();import{homedir as vF}from"node:os";import{join as SF}from"node:path";import{rm as pd}from"node:fs/promises";import{constants as Gv,accessSync as XB,statSync as zB}from"node:fs";import{platform as Vm}from"node:os";import{delimiter as qB,posix as QB,resolve as eF,win32 as tF}from"node:path";var nF="0.59.0",rF="1.1.4",Gn="Anyray \xB7 Claude",Vn="Anyray \xB7 Codex",od="__anyray-acp-agent",Vv=(e,t,n)=>{let{command:r,args:o}=nn([od,e,t,n]);return{command:r,args:o,env:{}}},ad=(e=Vm())=>e==="win32"?"npx.cmd":"npx",sd=(e=process.env.PATH,t=Vm())=>{if(!e)return;let n=ad(t);for(let r of e.split(qB)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=eF(o,n);try{if(!zB(a).isFile())continue;return XB(a,t==="win32"?Gv.F_OK:Gv.X_OK),a}catch{}}},id=(e,t=Vm())=>{let n=t==="win32"?tF:QB;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==ad(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},oF="https://chatgpt.com/backend-api/codex",aF="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Kv="ANYRAY_ACP_CODEX_AUTHORIZATION",jv="ANYRAY_ACP_CODEX_CLIENT_KEY",Zv="ANYRAY_ACP_CODEX_METADATA",Yv=e=>fe({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),sF=(e,t={})=>{let n=ee(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":oF,"x-anyray-forward-headers":aF}:{},o=n?{...e.clientKey?{"x-anyray-api-key":jv}:{}}:{Authorization:Kv};return Yv(e)&&(o["x-anyray-metadata"]=Zv),{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}}}:{}}},iF=e=>{let t=ee(e,"openai"),n=Yv(e);return{...t?e.clientKey?{[jv]:e.clientKey}:{}:{[Kv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[Zv]:n}:{}}},Jv=(e,t=ad(),n={})=>({[Gn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${nF}`],env:rn(e).env},[Vn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${rF}`],env:{CODEX_CONFIG:JSON.stringify(sF(e,n)),...iF(e)}}}),ui=(e=ad(),t="jetbrains")=>({[Gn]:Vv("claude",e,t),[Vn]:Vv("codex",e,t)}),ho=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as cF}from"node:zlib";import{open as lF,readFile as Jm,readdir as ud}from"node:fs/promises";import{dirname as Xv,join as me}from"node:path";import{homedir as eS,platform as Xm}from"node:os";var ld="2025.3.2",Aa="253.30387.147",pi="com.intellij.ml.llm",Km=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),dF=1e4,uF=256*1024*1024,pF=16*1024*1024,jm=1024*1024,Zm=22,fF=Zm+65535,Ym=xl,mF=()=>{let e=eS(),t=me(e,".cache","JetBrains","RemoteDev");switch(Xm()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:me(e,"Applications"),layout:"app-bundles"},{path:me(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:me(process.env.LOCALAPPDATA??me(e,"AppData","Local"),"Programs"),layout:"children"},{path:me(process.env.LOCALAPPDATA??me(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:me(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:me(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},hF=()=>Xm()==="linux"?me(eS(),".local","share","JetBrains"):Le("JetBrains"),yF=()=>Xm()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),gF=async(e,t=dF)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await ud(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=me(r.path,i.name),l=r.layout==="app-bundles"?me(c,"Contents","Resources","product-info.json"):me(c,"product-info.json");await x(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=me(s,"product-info.json"),l=me(s,"Contents","Resources","product-info.json");if(await x(c)){n.push(c);return}if(await x(l)){n.push(l);return}let d;try{d=await ud(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=me(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)]},wF=e=>{let t=Xv(e);return t.endsWith(`${me("Contents","Resources")}`)?Xv(t):t},bF=async e=>{try{let t=JSON.parse(await Jm(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!js(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:wF(e)}}catch{return}},dd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},AF=async(e,t)=>{let n;try{n=await lF(e,"r");let{size:r}=await n.stat();if(r<Zm||r>uF)return;let o=Math.min(r,fF),a=await dd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Zm;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>pF||c+i>r)return;let l=await dd(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),m=l.readUInt16LE(d+28),h=l.readUInt16LE(d+30),g=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),w=d+46+m+h+g;if(w>l.length)return;let b=l.subarray(d+46,d+46+m).toString("utf8");if(d=w,b!==t)continue;if(f===4294967295||p===4294967295||f>jm||p>jm)return;let k=await dd(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),E=await dd(n,f,y+30+C+S);return E?u===0?E.toString("utf8"):u===8?cF(E,{maxOutputLength:jm}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},zv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!js(n)))return{id:t,version:n}},CF=async(e,t)=>{let n=me(e,"META-INF","plugin.xml");if(await x(n))try{let o=zv(await Jm(n,"utf8"));return{present:o?.id===pi||t,descriptor:o?.id===pi?o:void 0}}catch{return{present:t}}let r=[];try{r=(await ud(me(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=>me(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await AF(o,"META-INF/plugin.xml"),s=a?zv(a):void 0;if(s?.id===pi)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},qv=async e=>{let t;try{t=await ud(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Km.has(o.name.toLowerCase()),i=Km.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Km.has(o.name.toLowerCase());if(!a){let i=me(e,o.name,"META-INF","plugin.xml");if(!await x(i))continue}let s=await CF(me(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},kF=async e=>{try{return(await Jm(me(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(pi)}catch{return!1}},Qv=e=>e.reduce((t,n)=>t?(Ym(n,t)??-1)>0?n:t:n,void 0),tS=async(e={})=>{let t=e.configRoot??Le("JetBrains"),n=e.userPluginsRoot??hF(),r=await gF(e.productRoots?e.productRoots.map(m=>({path:m,layout:"recursive"})):mF(),e.scanBudget),o=(await Promise.all(r.map(m=>bF(m)))).filter(m=>m!==void 0),a=o.length>0||await x(t);if(e.wsl??yF())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(m=>(Ym(m.version,ld)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let m of s){let h=me(t,m.dataDirectoryName);if(!await x(h)){d=!0;continue}let g=[me(h,"plugins"),me(n,m.dataDirectoryName),me(n,m.dataDirectoryName,"plugins")],y;for(let w of[...new Set(g)]){let b=await qv(w);if(b.present){y=b;break}}if(y??=await qv(me(m.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==pi)){if(i.push(y.descriptor.version),await kF(h)){c=!0;continue}if(!((Ym(y.descriptor.version,Aa)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${m.version}; AI Assistant ${y.descriptor.version}; ACP supported`,ideVersion:m.version,pluginVersion:y.descriptor.version}}}let u=Qv(o.map(m=>m.version)),f=Qv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${ld}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${ld}+ once, enable AI Assistant ${Aa}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${Aa}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${Aa}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${Aa}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${Aa}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${ld}+ 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 EF=[Gn,Vn],zm=()=>SF(vF(),".jetbrains","acp.json"),yo=()=>`${zm()}.anyray-state`,IF=(e,t,n="npx")=>{let r=ho(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,ui(n,"jetbrains")),{...e,agent_servers:r}},xF=(e,t,n)=>{if(!ho(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=ho(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of EF)if(c in r){if(!cd(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}},RF=(e=tS)=>({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=zm(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=sd();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await x(r),c;try{c=await M(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=ui(a,"jetbrains");return await qi({configPath:r,current:c,next:IF(c,t,a),journalPath:yo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,yo()]}},async revert(t){let n=zm(),r=async()=>{if(!await x(n))return t.dryRun||(await ce(n),await pd(yo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await ce(n),await pd(yo(),{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(yo());(u.version===1||u.version===2)&&ho(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await x(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await M(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await $r(n);let l=xF(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 pd(n,{force:!0}):await J(n,l.next,{backup:!1})),t.dryRun||(await ce(n),await pd(yo(),{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,yo(),r)}}),nS=RF();import{homedir as md}from"node:os";import{join as hd}from"node:path";import{rm as qm}from"node:fs/promises";var Qm="1.0.0",yd=["anyray-claude-acp","anyray-codex-acp"],OF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],eh=()=>hd(md(),".windsurf","acp","registry.json"),th=()=>hd(md(),".windsurf-next","acp","registry.json"),Ca=e=>`${e}.anyray-state`,rS=e=>({binary:Object.fromEntries(OF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),aS=(e="npx")=>{let t=ui(e,"windsurf");return[{id:yd[0],name:Gn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:rS(t[Gn])},{id:yd[1],name:Vn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:rS(t[Vn])}]},fd=e=>!Array.isArray(e)||e.some(t=>!ho(t)||typeof t.id!="string")?null:e,TF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Qm||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:fd(e.agents);if(!n)return null;let r=new Set(yd);return{...e,version:typeof e.version=="string"?e.version:Qm,agents:[...n.filter(o=>!r.has(o.id)),...aS(t)],extensions:e.extensions??[]}},_F=(e,t,n)=>{let r=fd(e.agents);if(!r)return null;let o=fd(t.agents)??[],a=new Map((fd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!yd.includes(u.id)){l.push(u);continue}if(!cd(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===Qm&&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}},oS=async()=>{let e=[];return(await x(th())||await x(hd(md(),".windsurf-next")))&&e.push(th()),(await x(eh())||await x(hd(md(),".windsurf"))||await x(Le("Devin"))||await x(Le("Windsurf")))&&e.push(eh()),e},sS={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await oS();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await oS();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=sd();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=TF(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await x(s),d=aS(r);await qi({configPath:s,current:i,next:c,journalPath:Ca(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Ca(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=[eh(),th()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await ce(a),await qm(Ca(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(Ca(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 x(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 $r(a);let f=_F(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 qm(a,{force:!0}):await J(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 ce(a),await qm(Ca(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await zi(a,Ca(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var pe=[rr,qw,Os,eC,xC,FC,jC,nS,Hv,sS,sb],ut=e=>pe.find(t=>t.id===e);var We=async(e=P,t=yn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:Oe({origin:n.gateway,clientKey:n.clientKey,subscription:n.authMode==="subscription",placeholder:n.authMode==="placeholder",byoUpstream:n.byoUpstream,seat:r,user:n.name,team:n.team})}};var nh=5e3,iS=3e4,PF=1440*60*1e3,DF=e=>new Promise(t=>setTimeout(t,e)),LF=async(e=P,t=yn)=>(await We(e,t))?.target,NF=e=>ut(e)?.quitGated,cS=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??NF,o=t.readPending??Kc,a=t.clearPending??Up,s=t.targetFromProfile??LF,i=t.sleep??DF,c=t.now??Date.now,l=t.maxWaitMs??PF;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=nh;for(;;){let m=await o(n);if(!m||c()-f>l)return 0;if(d.isRunning()){await i(p),p=Math.min(iS,p*2);continue}let h;if(d.needsTarget?.(m.op)&&(h=await s(),!h)){if(await a(n,m)!=="superseded")return 0;await i(p),p=nh;continue}if((await u(m.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(p),p=Math.min(iS,p*2);continue}if(await a(n,m)!=="superseded")return 0;await i(p),p=nh}}catch{return 0}};import{writeFileSync as vW}from"node:fs";import{chmod as mh,stat as SW}from"node:fs/promises";import{platform as FS}from"node:os";import{dirname as WS,isAbsolute as EW}from"node:path";var $F="https://app.anyray.ai",MF=new Set(["localhost","::1","[::1]"]),BF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,FF=e=>MF.has(e)||BF.test(e),rh=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&FF(t.hostname)},WF=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||!rh(e)?$F:WF(e)};import{createHash as QF,generateKeyPairSync as eW,randomBytes as sh}from"node:crypto";import{createPrivateKey as UF,sign as HF}from"node:crypto";var Ir=async(e,t)=>{let n=UF(t);return HF(null,new TextEncoder().encode(e),n).toString("base64url")};var GF=["HTTPS_PROXY","https_proxy"],lS=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"]),dS=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),uS=new Set(["ENOTFOUND","EAI_AGAIN"]),pS=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),fS=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),VF=e=>{let t=e;for(let n=0;n<5&&t;n++){let r=t.code;if(typeof r=="string"&&r)return r;t=t.cause}return KF(e)},KF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...lS,...dS,...uS,...pS,...fS])if(t.includes(n))return n}},jF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",ZF=e=>GF.filter(t=>(e[t]??"").trim()!==""),YF=(e,t=process.env)=>{let n=VF(e),r=ZF(t);return{kind:n&&lS.has(n)?"tls-unknown-issuer":n&&dS.has(n)?"tls-invalid-cert":n&&uS.has(n)?"dns":jF(e)||n&&fS.has(n)?"timeout":n&&pS.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},JF=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}},pt=(e,t=process.env)=>JF(YF(e,t));var XF="enl_",mS="enp_",hS=e=>e.startsWith(XF)||e.startsWith(mS),oh=e=>e.startsWith(mS),zF=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],ah=e=>zF.find(t=>e.startsWith(t.prefix)),yS=/^\/enroll\/([^/]+)\/?$/,gS=/^\/i\/([^/]+)\/?$/,wS=e=>{let t=e.match(yS);if(t)return ah(t[1])?void 0:t[1];let n=e.match(gS);return n&&hS(n[1])?n[1]:void 0},qF=1e4,gd=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=wS(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!ah(t))return{cpOrigin:Kn(),token:t}},bS=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(yS)??o.pathname.match(gS);if(!a)return;n=a[1]}catch{}let r=ah(n);return r?{flag:r.flag,what:r.what}:void 0},mi=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:wS(n.pathname)!==void 0}catch{return hS(t)}},ka=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},fi=e=>typeof e=="string"&&e.trim()?e.trim():void 0,AS=async(e,t={})=>{let n=t.timeoutMs??qF,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.`:pt(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${f}`)}finally{clearTimeout(a)}if(!s.ok){let u=`enrollment link lookup failed: ${e.cpOrigin} responded ${s.status} \u2014 the link may be expired or revoked; ask your admin for a fresh one.`;throw s.status>=400&&s.status<500&&s.status!==429?new ka(u):new Error(u)}let i;try{i=await s.json()}catch{throw new Error(`enrollment link lookup failed: ${e.cpOrigin} returned a malformed response`)}let l=(Array.isArray(i?.gateways)?i.gateways:[]).find(u=>u!==null&&typeof u=="object"&&fi(u.url)!==void 0),d=fi(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:fi(l?.deploymentId),org:fi(i.org),email:fi(i.email),seatMode:i.seatMode===!0,...i.provisioningKind==="manual"||i.provisioningKind==="mdm"?{provisioningKind:i.provisioningKind}:{},...i.provisioningProofMode==="managed-preference"?{provisioningProofMode:i.provisioningProofMode}:{},...Array.isArray(i.allowedDomains)?{allowedDomains:i.allowedDomains.filter(u=>typeof u=="string"&&u.length>0)}:{}}};var ke="0.11.180";var ih=1e4,go=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(go).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${go(e[n])}`).join(",")}}`,CS="stable-key-heartbeat-v1",kS="key-heartbeat",tW=["reapply_config","remint","revert"],ch=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var vS=e=>QF("sha256").update(e).digest("hex"),je=e=>typeof e=="string"&&e.trim()?e.trim():void 0,nW=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],SS={no_mdm_server_registered:"no MDM server is registered in the Anyray console",agent_missing:"the Anyray endpoint agent is not reporting for this machine",mdm_not_verified:"this machine is not enrolled in the registered MDM",endpoint_unreachable:"the endpoint service could not be reached"},rW=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${SS[e]}. Ask your IT admin.`,oW=e=>typeof e=="string"&&e in SS,lh=async e=>{try{let t=await e.json(),n=je(t?.message),r=je(t?.error),o=oW(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:rW(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},aW=async e=>(await lh(e)).message,ct=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this enrollment (HTTP ${t}): ${r.message}`),this.name="GatewayVerifyError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},ES=e=>e instanceof ka||e instanceof ct&&e.policyCode==="sso_required",va=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this credential heartbeat (HTTP ${t}): ${r.message}`),this.name="GatewayHeartbeatError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},dh=async(e,t,n,r)=>{try{return await r(go(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},wd=()=>{let{publicKey:e,privateKey:t}=eW("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},qt=async(e,t,n,r={})=>{let o=r.timeoutMs??ih,a=`${e}/connect/verify`,s=je(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:sh(16).toString("hex"),...ch(t,r.machineUuid)},c=await dh(i,n,"verification",r.signer??Ir),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":ke},body:JSON.stringify({cert:t,challenge:i,sig:c,...r.health?{health:r.health}:{},...r.ack?{ack:r.ack}:{},...r.telemetryOnly?{telemetryOnly:!0}:{}}),signal:l.signal})}catch(w){let b=w instanceof Error&&w.name==="AbortError"?` no response within ${o}ms.`:pt(w);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:w})}finally{clearTimeout(d)}if(!u.ok)throw new ct(u.status,await lh(u));let f;try{f=await u.text()}catch{f=""}let p;try{p=JSON.parse(f)}catch{let w=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(w)||/^\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 m=je(p?.key);if(!m)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(m))throw new Error("developer verification failed: the gateway returned a malformed key");let h=je(p.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let g=sW(p.directive),y=nW(p.capabilities);return{key:m,user:h,team:je(p.team),expiresAt:je(p.expiresAt),...y.length>0?{capabilities:y}:{},...g?{directive:g}:{}}},IS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??ih,s=`${e}/connect/key/heartbeat`,i=je(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:sh(16).toString("hex"),purpose:kS,...ch(n,o.machineUuid)},l=await dh(c,r,"heartbeat",o.signer??Ir),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":ke},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(h){let g=h instanceof Error&&h.name==="AbortError"?` no response within ${a}ms.`:pt(h);throw new Error(`could not reach the gateway at ${s}.${g}`,{cause:h})}finally{clearTimeout(u)}if(!f.ok)throw new va(f.status,await lh(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let m=je(p.expiresAt);if(!m||!Number.isFinite(Date.parse(m))||p.credentialMode!==CS||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:m,credentialMode:CS}},xS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??ih,i=`${e.replace(/\/$/,"")}/connect/machine`,c=je(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:sh(16).toString("hex"),purpose:kS,...ch(n,o)},d=await dh(l,r,"heartbeat",a.signer??Ir),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":ke},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)}},sW=e=>{if(e===null||typeof e!="object")return null;let t=e,n=je(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!tW.includes(r)?null:{id:n,kind:r}},iW=1e4,cW=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!je(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!je(r.deploymentId)&&!!je(r.user)&&!!je(r.devPublicKey)&&!!je(r.issuedAt)&&!!je(r.expiresAt)},lW=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??iW,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.`:pt(u);throw new Error(`could not reach the control plane at ${s}.${f}`)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await aW(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new ka(u):new Error(u)}let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!cW(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},RS=(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())},OS=async e=>{let t={timeoutMs:e.timeoutMs,machineUuid:e.machineUuid,signer:e.signer},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=wd();return{cert:await lW(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await qt(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};var uh=1e4,dW=900*1e3,_S="tnt_",uW=/^\/sso\/([^/]+)\/?$/,pW=/^\/i\/([^/]+)\/?$/,fW=e=>{let t=e.match(uW);if(t)return t[1];let n=e.match(pW);return n?.[1].startsWith(_S)?n[1]:void 0},Et=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=fW(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(_S))return{cpOrigin:Kn(),tenantId:t}},wo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Bt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},ph=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)}},mW=e=>new Promise(t=>setTimeout(t,e)),bd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??wd)(),a;try{a=await ph(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},uh,n)}catch(m){throw new wo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${pt(m)}`)}if(a.status!==200){let m=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new wo(m?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${h}). Ask your admin to confirm SSO is configured.`,a.status)}let s=a.json;if(!s.device_code||!s.user_code||!s.verification_uri_complete)throw new wo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??dW,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}`),hW(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},hW=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Ad=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??mW,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 ph(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},uh,o)}catch(c){throw new Bt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${pt(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 Bt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Bt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Bt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var TS="sdc_",PS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(TS))return{cpOrigin:Kn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!rh(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(TS)))return{cpOrigin:n.origin,claim:r}},DS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??wd)(),o;try{o=await ph(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},uh,t)}catch(s){throw new Bt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${pt(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 Bt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Bt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Bt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};import{readFile as yW}from"node:fs/promises";import{isAbsolute as gW,posix as LS,win32 as fh}from"node:path";var hi=(e=process.platform,t=process.env)=>e==="darwin"?LS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?fh.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):LS.join("/etc","anyray","bootstrap.json"),wW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),NS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(gW(e)||fh.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),bW=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}},xr=async(e=hi())=>{try{let t=await yW(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!wW(n)||n.v!==1||typeof n.sso!="string")return;let r=Et(n.sso);if(!r)return;let o=bW(n.gateway)?n.gateway:void 0,a=NS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},$S=(e,t,n)=>{let r=Et(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!NS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&fh.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)}
|
|
262
|
+
`};var Sa=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Cd=Sa(process.stdout,process.env),MS=Sa(process.stderr,process.env),Ea=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,j=e=>Ea("1",e,Cd),v=e=>Ea("2",e,Cd),AW=e=>Ea("32",e,Cd),CW=e=>Ea("33",e,MS),kW=e=>Ea("31",e,MS),ze=e=>Ea("36",e,Cd),A=e=>console.log(e),H=e=>console.log(`
|
|
263
|
+
${j(e)}`),N=e=>console.log(v(e)),B=e=>console.log(`${AW("\u2713")} ${e}`),_=e=>console.error(`${CW("!")} ${e}`),R=e=>console.error(`${kW("\u2717")} ${e}`);var hh=`${j("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
|
|
264
264
|
|
|
265
265
|
Emit or install the OS \`managed-settings.json\` that points a managed fleet's
|
|
266
266
|
Claude Code at the Anyray gateway. It reads at a HIGHER precedence than a user's
|
|
@@ -343,15 +343,15 @@ ${j("Examples")}
|
|
|
343
343
|
anyray-connect managed --print --tool jetbrains --bin /usr/local/bin/anyray-connect --npx /usr/local/bin/npx > acp.json
|
|
344
344
|
|
|
345
345
|
# Shell/SDK fleet snippet (base URLs only; keys stay per-user):
|
|
346
|
-
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d
|
|
347
|
-
`)},vd=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}
|
|
348
|
-
`),
|
|
349
|
-
`),Ze(v("# acp.json for ~/.jetbrains/acp.json (per user).")),Ze(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ze(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ze(v("# An MDM file drop REPLACES the file \u2014 deploy at provision time, or merge agent_servers in your config tool if devs add their own agents.")),0},
|
|
350
|
-
`),Ze(v(`# managed-settings.json for ${_t()}`)),n)Ze(v("# Deferred SSO: hooks only; no credential or managed env block.")),Ze(v(`# Push the binary to ${n.binaryPath} before this file.`)),Ze(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of
|
|
351
|
-
`+
|
|
352
|
-
`+
|
|
346
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,BS=["claude-code","jetbrains","shell","bootstrap"],IW=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--print":t.mode="print";break;case"--write":t.mode="write";break;case"--revert":t.mode="revert";break;case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":throw new Error("--key is not valid for managed settings: fleet files never embed credentials; enroll each user instead");case"--scrub-direct-mode":t.scrubDirectMode=!0;break;case"--sso":t.sso=o();break;case"--bin":t.bin=o();break;case"--npx":t.npx=o();break;case"--out":t.out=o();break;case"--tool":{let a=o();if(!BS.includes(a))throw new Error(`unknown --tool ${a} (expected ${BS.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&&!Et(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function kd(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(ls(t.binaryPath,[Ye]),{matcher:"*"})],UserPromptSubmit:[En(ls(t.binaryPath,o),{timeout:30}),En(ls(t.binaryPath,[qn]))],SessionStart:[En(ls(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=rn(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(In.map(o=>[o.name,""])),...r}}:{env:r}}var xW=(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 Wr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,Qu(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},RW=e=>{let t=e.env,n=Qu(e);if(t){for(let r of Wr)r in t&&(delete t[r],n=!0);for(let{name:r}of In)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},US=async e=>{let t=async n=>{try{return(await SW(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(WS(e))!==void 0}},HS=async(e,t)=>(t.dirExisted||await mh(WS(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await mh(e,420),{mode:420,keptRestricted:!1}):(await mh(e,t.mode),{mode:t.mode,keptRestricted:!0})),GS=(e,t)=>{t.keptRestricted&&(_(`${e} was already restricted to mode ${t.mode.toString(8).padStart(3,"0")} and keeps it \u2014 widening it would expose whatever else that file holds to every local account.`),A(v(" Claude Code reads this file as the developer, so the routing will NOT take effect until it is readable. Move any secret out of it, then `chmod 644` it.")))},VS=()=>process.getuid?.()===0,Ze=e=>{process.stderr.write(`${e}
|
|
347
|
+
`)},vd=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}vW(e.out,t,"utf8"),Ze(v(`# Wrote ${e.out}`))},yh=e=>Oe({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),gh=e=>EW(e)||/^[A-Za-z]:[\\/]/.test(e),KS=e=>{if(!e.sso)return;let t=Et(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??_e();if(!e.bin&&!ne())throw new Error("--bin is required because the running binary path is temporary; use a fleet-stable path such as /usr/local/bin/anyray-connect");if(!gh(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}},jS=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${fe(e.metadata)??"(none \u2014 pass --team)"}`],wh=(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{}},OW=(e,t)=>({agent_servers:{[Gn]:{command:e,args:[od,"claude",t,"jetbrains"],env:{}},[Vn]:{command:e,args:[od,"codex",t,"jetbrains"],env:{}}}}),TW=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(`
|
|
348
|
+
`),_W=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(!gh(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(!id(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return vd(e,`${JSON.stringify(OW(e.bin,e.npx),null,2)}
|
|
349
|
+
`),Ze(v("# acp.json for ~/.jetbrains/acp.json (per user).")),Ze(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ze(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ze(v("# An MDM file drop REPLACES the file \u2014 deploy at provision time, or merge agent_servers in your config tool if devs add their own agents.")),0},PW=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&&!gh(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return vd(e,$S(e.sso,e.gateway,e.bin)),Ze(v(`# Fleet bootstrap for ${hi("linux")}`)),Ze(v(`# macOS: ${hi("darwin")}`)),Ze(v(`# Windows: ${hi("win32",{ProgramData:"C:\\ProgramData"})}`)),Ze(v("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},DW=e=>{if(e.sso||e.bin||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool shell takes only --gateway: the snippet carries base URLs only (keys and attribution ride each user\u2019s enrollment)");let t=yh(e);return vd(e,TW(t)),Ze(v("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),wh(t,Ze),0},LW=e=>{let t=yh(e),n=KS(e),r=n?kd(t,n):kd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(vd(e,`${JSON.stringify(r,null,2)}
|
|
350
|
+
`),Ze(v(`# managed-settings.json for ${_t()}`)),n)Ze(v("# Deferred SSO: hooks only; no credential or managed env block.")),Ze(v(`# Push the binary to ${n.binaryPath} before this file.`)),Ze(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of jS(t))Ze(v(`# ${o}`));wh(t,Ze)}return 0},NW=async e=>{let t=FS();if(t!=="darwin"&&t!=="linux")return R("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!VS())return R("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),A(v(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=yh(e),r=KS(e);r||wh(n,u=>_(u.replace(/^!\s*/,"")));let o=_t(t),a=await M(o),s=r?kd(n,r):kd(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?In.filter(({name:u})=>{let f=a.env?.[u];return typeof f=="string"&&f.trim()!==""}):[],c=xW(a,s),l=await US(o);await J(o,c);let d=await HS(o,l);B(`Wrote ${o}`),GS(o,d);for(let{name:u,cloud:f}of i)_(`${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)A(v(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),A(v(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of jS(n))A(` ${v(u)}`);return A(v(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},$W=async()=>{let e=FS();if(e!=="darwin"&&e!=="linux")return R("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!VS())return R("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=_t(e);if(!await x(t))return A(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await M(t);if(!RW(n))return A(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await US(t);await J(t,n);let o=await HS(t,r);return B(`Removed Anyray-owned keys from ${t} (other keys left intact).`),GS(t,o),0},ZS=async e=>{let t;try{t=IW(e)}catch(n){return R(n instanceof Error?n.message:"invalid managed arguments"),A(`
|
|
351
|
+
`+hh),1}if(t.help||e.length===0&&!t.mode)return A(hh),0;if(!t.mode)return R("Specify a mode: --print, --write, or --revert."),A(`
|
|
352
|
+
`+hh),1;if(t.out!==void 0&&t.mode!=="print")return R(`--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 R(`--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"?(R(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?_W(t):n==="bootstrap"?PW(t):DW(t):t.mode==="print"?LW(t):t.mode==="write"?await NW(t):await $W()}catch(n){return R(n instanceof Error?n.message:"managed settings failed"),1}};import{spawn as VU}from"node:child_process";import{homedir as KU}from"node:os";import{join as PE}from"node:path";import{readFile as jU,writeFile as DE,chmod as ZU,stat as YU,unlink as kE}from"node:fs/promises";var MW=["hook_registration","mcp_registration","hook_binary","beacon_target"],bo=e=>e.status==="configured"||e.status==="queued",Ao=async(e,t=pe)=>{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},Ia=async(e,t,n=pe)=>{let r=[];for(let o of await Ao(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},bh=async(e,t=pe)=>{let n=[];for(let r of await Ao(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(MW.map(o=>[o,"unreadable"]))})}return n},YS=e=>e.filter(t=>!t.integrationStatus),BW=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},Ft=async(e,t)=>{let n=[];for(let r of e)try{let o=await r.apply(t,{dryRun:!1});n.push({id:r.id,title:r.title,status:o.status,...o.errorClass?{errorClass:o.errorClass}:{}})}catch(o){let a=BW(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 WW,writeFile as UW}from"node:fs/promises";import{join as XS}from"node:path";import{z as Ee}from"zod";var xa="required",FW=e=>e==="subscription"?"subscription":"placeholder",JS=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?FW(t.lane):void 0,a=o!=null&&o!==e.authMode;return{routingUpdated:n,teamUpdated:r,laneUpdated:a,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{},...a?{authMode:o}:{}}},Sd=(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]??xa,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 HW=1e4,GW=1,VW=Ee.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),KW=Ee.object({id:VW,name:Ee.string().min(1),version:Ee.string().min(1),body:Ee.string()}),jW=Ee.object({version:Ee.literal(GW).optional(),skills:Ee.array(KW),updatedAt:Ee.string().min(1).optional(),routing:Ee.object({origin:Ee.string().min(1)}).optional(),team:Ee.string().min(1).optional(),lane:Ee.enum(["subscription","org"]).optional().catch(void 0),tools:Ee.object({enabled:Ee.array(Ee.string().min(1)),tiers:Ee.record(Ee.string().min(1),Ee.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional(),updates:Ee.object({mode:Ee.enum(["auto","directed","off"]).catch("directed")}).optional()}),Ra=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},Ah=e=>e instanceof Ra&&e.kind==="auth",ZW=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",Ch=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",Oa=async(e,t,n={})=>{let r=n.timeoutMs??HW,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.`:pt(l);throw new Ra("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Ra(i.status===401||i.status===403?"auth":"unavailable",`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch{throw new Ra("malformed","team policy fetch failed: the gateway returned a malformed response")}return jW.parse(c)},zS=/^[a-z0-9][a-z0-9-]{0,31}$/,qS=64,YW=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>zS.test(o)).slice(0,qS).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>zS.test(o)).slice(0,qS).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},JW=e=>e.updates?{mode:e.updates.mode}:void 0,yi=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??xa)==="locked":!1},Ta=async(e,t={})=>{let n=t.loadProfile??P,r=t.saveProfile??le,o=t.targetFromProfile??We,a=t.adapters??pe,s=t.repairTools??Ft,i=t.recordManaged??Jn,c=await n(),l={...c},d=JS(c,{routingOrigin:e.routing?.origin?Vt(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:u,teamUpdated:f,laneUpdated:p}=d;(u||f||p)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),d.authMode!=null&&(l.authMode=d.authMode),await r(l));let m=Sd(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f||p),{candidateIds:h,freshIds:g}=m,y=0,w=0,b=0;if(h.length>0||g.length>0){let O=await o(async()=>l);if(O){let T;if(u||f||p){let K=new Set(h);T=[];for(let oe of a)if(K.has(oe.id))try{(await oe.detect()).installed&&T.push(oe)}catch{}}else T=await Ia(h,O.target.origin,a);let U=new Set(g),z=[];for(let K of a)if(U.has(K.id))try{(await K.detect()).installed&&z.push(K)}catch{}if(y=T.length+z.length,y>0){let K=await s([...T,...z],O.target);w=K.filter(bo).length;let oe=K.filter(ae=>U.has(ae.id));if(b=oe.filter(bo).length,oe.length>0)try{await i(oe,!1)}catch{}}}}let k=YW(e),C=JW(e),S=await n(),E=JSON.stringify(k??null)!==JSON.stringify(S.fleetToolPolicy??null),I=JSON.stringify(C??null)!==JSON.stringify(S.fleetUpdatePolicy??null);if(E||I){let{fleetToolPolicy:O,fleetUpdatePolicy:T,...U}=S;await r({...U,...k?{fleetToolPolicy:k}:{},...C?{fleetUpdatePolicy:C}:{}})}return{routingUpdated:u,teamUpdated:f,laneUpdated:p,toolsRequested:y,toolsApplied:w,toolsEnrolled:b,toolsTombstoned:m.tombstonedIds,profileUpdated:u||f||p,updatesMode:C?.mode??"auto",updatesUpdated:I}},QS=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!ZW(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=XS(d,i.id),f=XS(u,"SKILL.md");await WW(u,{recursive:!0}),await UW(f,XW(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}},XW=e=>e.endsWith(`
|
|
353
353
|
`)?e:`${e}
|
|
354
|
-
`;import{randomBytes as JW}from"node:crypto";var XW=1e4,zW="machine:",qS=e=>e.startsWith(zW),qW="cert-renew",QW=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)},QS=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:JW(16).toString("hex"),purpose:qW},c;try{c=await(n.signer??Ir)(go(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),XW),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 QW(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var Ch=async(e,t=e.origin,n=pe)=>{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}},kh=async(e,t=e.origin,n=pe)=>(await Ch(e,t,n)).complete;var eU=["claude","codex","cursor","opencode"],tU=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],nU=new Set(["missing_key","key_expired"]);var rU=600*1e3,oU=600*1e3,eE=1440*60*1e3,aU=1440*60*1e3,sU=10080*60*1e3,iU=3600*1e3,cU=720*60*1e3,lU=e=>Math.min(cU,iU*2**Math.max(0,e-1)),gi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_a=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,tE=e=>typeof e=="string"&&tU.includes(e),vn=e=>{if(!gi(e))return{};let t={};if(_a(e.watchSince)&&(t.watchSince=e.watchSince),gi(e.invoked)){let n={};for(let r of eU){let o=e.invoked[r];_a(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return gi(e.authFailure)&&_a(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...tE(e.authFailure.code)?{code:e.authFailure.code}:{}}),gi(e.repair)&&_a(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,..._a(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Ed=e=>{try{let n=JSON.parse(e);if(gi(n)&&tE(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"},vh=e=>e!==void 0&&nU.has(e),Sh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=rU},nE=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),Eh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=oU},rE=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),oE=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,aE=(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},sE=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>eE||!vh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<lU(r.failures??1))},Id=e=>{let t=Object.values(e?.invoked??{}).filter(_a);return t.length>0?Math.max(...t):null},Ih=(e,t)=>{if(Id(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=sU},iE=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=aU)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=eE)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var xh="x-anyray-retrieve-probe",xd=8e3,dU=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",cE=(e,t)=>{let n=jt(e);return t?.probe&&(n[xh]="1"),n},Pa=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(),xd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:cE(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=dU(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)}},Rd=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(),xd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:cE(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 uU=5e3,pU=2048,fU=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}"`))},Da=async(e={})=>{let t=e.readTarget??tt,n=e.fetch??fetch,r=e.timeoutMs??uU,o=null;try{o=await t()}catch{o=null}if(!o)return{verdict:"dark",reason:"target_null"};let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let i=jt(o);i["content-type"]="application/json",i[xh]="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,pU);if(!fU(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Ed(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)}},Rh=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{randomBytes as yU}from"node:crypto";import{execSync as Oh}from"node:child_process";import{hostname as mU}from"node:os";var hU=e=>{try{if(e==="darwin"){let t=Oh("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=Oh('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 Oh("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Od=(e={platform:process.platform,read:()=>hU(process.platform),hostname:mU})=>e.read().trim()||e.hostname().trim();var Wt=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();if(t)return t.toLowerCase();if((e.platform??process.platform)==="darwin"){let r=e.readMacUuid??(()=>Od());try{return r().trim().toLowerCase()}catch{return""}}return""};var gU=500,lE=2e3,wU=2e3,bU=250,dE=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),gU);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)}},AU=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},CU=e=>new Promise(t=>setTimeout(t,e)),kU=async(e,t,n=CU)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),lE),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=AU(i)??bU,s>wU))return!1}finally{clearTimeout(a)}await n(s)}},vU=async(e,t={})=>{try{let r=(await(t.loadProfile??P)()).enrolledCert,o=await(t.loadDevKey??Be)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:yU(16).toString("hex"),events:e},i;try{i=await(t.signer??Ir)(go(s),o)}catch{return!1}return await(t.post??kU)(`${t.origin??Kn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},SU=async(e,t,n={})=>{try{let o=(await(n.loadProfile??P)()).enrolledCert,a=await(n.loadDevKey??Be)();if(!o||!a)return;await(n.verify??qt)(e,o,a,{timeoutMs:lE,machineUuid:(n.machineUuid??Wt)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},uE=async(e,t)=>{if(e.length!==0)try{let n=await tt(),r=n&&await dE(n.origin,jt(n),e,t);if(n&&await SU(n.origin,e),r)return;await vU(e)}catch{}},Th=async(e,t,n={readTarget:()=>tt("profile"),post:dE})=>{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 ko=["hook_registration","mcp_registration","hook_binary","beacon_target"];var fE=128,mE=300*1e3,EU=["repaired","repair_failed","flapping","pending"],IU=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],hE=["rebroke_same_day","repeat_days"],yE=new Set(pe.map(e=>e.id)),Co=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),gE=e=>bi(e,ko),Td=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},Rr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,wi=e=>{if(!(!Array.isArray(e)||!e.every(gE)))return jn(e)},xU=e=>{if(!Co(e))return;let t=wi(e.checks);if(!(!Rr(e.since)||!bi(e.reason,hE)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},RU=e=>{if(!Co(e))return;let t={};Td(e.day)&&(t.day=e.day),Rr(e.attempts)&&(t.attempts=e.attempts);let n=wi(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=wi(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=wi(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=wi(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Td(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Rr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),Co(e.lastRepaired)){let i={};for(let c of ko){let l=e.lastRepaired[c];Rr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=xU(e.flapping);return s&&(t.flapping=s),t},OU=e=>{if(!Co(e)||!Td(e.day)||!Rr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!yE.has(e.tool)||!gE(e.checkId)||!bi(e.status,EU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!bi(e.errorClass,IU))return;t=e.errorClass}else if(e.status==="flapping"){if(!bi(e.errorClass,hE))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,...Rr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},pE=e=>{if(!Co(e))return{};let t={};if(Co(e.adapters)){let n={};for(let r of yE){let o=RU(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(OU).filter(n=>n!==void 0).slice(-fE)),Rr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Co(e.report)&&Td(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Rr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},TU=e=>new Date(e).toISOString().slice(0,10),_U=(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)],_d=(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}:{}}},Ai=(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(-fE),nextSequence:r}},PU=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),DU=async e=>await We(async()=>e)??null,LU=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=_d(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)},wE=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:_U(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}},NU=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=_d(d,n),f=u.awaiting??[],p=a.get(l);if(f.length===0||t.has(l)||!p){c[l]=u;continue}let m=f.filter(w=>p.checks[w]==="owned"),y=f.filter(w=>{let b=p.checks[w];return b==="missing"||b==="foreign"}),g=f.filter(w=>{let b=p.checks[w];return b===void 0||b==="unreadable"}),h=wE(u,m,n,r);c[l]={...h.adapter,awaiting:g.length>0?g:void 0},i=Ai(i,n,[...m.map(w=>({tool:l,checkId:w,status:"repaired"})),...y.map(w=>({tool:l,checkId:w,status:"repair_failed",errorClass:"apply_unconfirmed"})),...h.slowFlap?m.map(w=>({tool:l,checkId:w,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},$U=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=_d(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(h=>!d.includes(h)||u.includes(h)),p=f.filter(h=>u.includes(h)),m=l.attempts??0;if(m>=2||f.length===0&&!n){let h=p.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(h.length===0)return{result:void 0};let w=l.flapping;return c[e]={...l,brokenReportedChecks:jn([...l.brokenReportedChecks??[],...h]),flapping:{since:w?.since??a,reason:"rebroke_same_day",checks:jn([...w?.checks??[],...h])}},{next:Ai({...i,adapters:c},o,h.map(k=>({tool:e,checkId:k,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let y=l.flapping;return c[e]={...l,attempts:m+1,attemptedChecks:jn([...d,...f]),confirmedChecks:u.filter(h=>!f.includes(h)),brokenReportedChecks:jn([...l.brokenReportedChecks??[],...p]),...p.length>0?{flapping:{since:y?.since??a,reason:"rebroke_same_day",checks:jn([...y?.checks??[],...p])}}:{}},{next:Ai({...i,adapters:c},o,p.map(h=>({tool:e,checkId:h,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),MU=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=_d(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:jn([...l.awaiting??[],...t])},{next:Ai({...i,adapters:c},o,t.map(m=>({tool:e,checkId:m,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(m=>r[m]==="owned"):[],u=n.status==="configured"&&r?t.filter(m=>{let y=r[m];return y==="missing"||y==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=wE(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"apply_unconfirmed";return{next:Ai({...i,adapters:c},o,[...d.map(m=>({tool:e,checkId:m,status:"repaired"})),...u.map(m=>({tool:e,checkId:m,status:"repair_failed",errorClass:p})),...f.slowFlap?d.map(m=>({tool:e,checkId:m,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},BU=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>=mE));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??Th)(o.map(PU),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)},FU=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 m of ko){let y=f[m];if(!y||y==="unreadable")continue;let g,h;p?.awaiting?.includes(m)&&c.has(u.id)?g="pending":y==="missing"&&p?.flapping?.checks.includes(m)?(g="flapping",h=p.flapping.reason):g=y==="owned"?"ok":y,g!=="ok"&&g!=="pending"&&(i=!0),s.push({tool:u.id,checkId:m,status:g,...h?{errorClass:h}:{}})}}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??Wo)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??pr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=iE(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},WU=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<mE?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await FU(e,t,n,c,o,s);await(s.report??Th)(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)},bE=async(e,t,n)=>{let r=n.now??Date.now,o=TU(r()),a=e.managedTools??[],s={...n,readState:async()=>pE(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(pE(l)),c)};try{let i=await(s.findIntegrations??wh)(a);await LU(i,o,s);let c=await(s.listPending??dr)().catch(()=>[]),l=new Set(c.map(h=>h.adapter));await NU(i,l,o,r(),s);let d=await(s.resolveTarget??DU)(e),u=d?await(s.findDrifted??Ia)(a,d.target.origin):[],f=new Set(u.map(h=>h.id)),p=new Map(i.map(h=>[h.adapter.id,h]));for(let h of u)p.has(h.id)||p.set(h.id,{adapter:h,checks:{}});let m=!1,y=(s.runtimeDurable??ne)();if(d)for(let{adapter:h,checks:w}of p.values()){let b=y?ko.filter(T=>w[T]==="missing"):[];if(b.length===0&&!f.has(h.id))continue;let k=w;if(h.integrationStatus)try{k=await h.integrationStatus()}catch{k=Object.fromEntries(ko.map(T=>[T,"unreadable"]))}let C=b.filter(T=>k[T]==="missing"),S=f.has(h.id);if(S&&h.pointsAt&&(S=!await h.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!S)continue;let E=await $U(h.id,C,S,l.has(h.id),o,r(),s);if(!E)continue;let[I]=await(s.repair??Ft)([h],d.target);if(!I)continue;m=!0;let O;I.status==="configured"&&h.integrationStatus&&(O=await h.integrationStatus().catch(()=>{})),await MU(h.id,E.checks,I,O,o,r(),s)}await BU(o,r(),t,s),i=await(s.findIntegrations??wh)(a);let g=await(s.listPending??dr)().catch(()=>[]);return await WU(e,i,g,o,r(),t,s),m}catch{return!1}};var ZU=14,YU=.35,JU=900*1e3,CE=360*60*1e3,XU=.2,zU=1800*1e3,kE=3600*1e3,qU=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),QU=300*1e3,eH=30*1e3,tH=900*1e3,nH=(e=0)=>Math.min(tH,eH*2**Math.max(0,e)),vE=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}},SE=1440*60*1e3,rH=300*1e3,oH=.25,aH=.5,EE=3600*1e3,sH=720*60*60*1e3,iH=360*60*1e3,cH=1440*60*1e3,lH=()=>TE(GU(),".anyray"),_h=()=>TE(lH(),"refresh-state.json"),Ph=e=>process.env?.[e],PE=()=>Ph("ANYRAY_REFRESH_DISABLE")==="true",Dh=()=>{let e=Ph("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:ZU)*cH},Dd=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},DE=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),dH=10080*60*1e3,LE=(e,t,n=Date.now())=>{let r=[],o=Dd(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)<=dH},Lh=e=>{let t=Dh(),n=e?Dd(e):void 0;if(!n)return t;let r=Math.max(JU,Math.round(n*YU));return Math.min(t,r)},uH=e=>{let t=Ph("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(CE,Math.max(zU,Math.round(e*XU))):CE},It=async()=>{try{let e=await VU(_h(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Ld=async e=>{try{let t=_h(),n=`${t}.${process.pid}.tmp`;await _E(n,JSON.stringify(e),{mode:384}),await he(n,t),await KU(t,384).catch(()=>{})}catch{}},pH=3e4,fH=()=>`${_h()}.lock`,IE=async e=>{try{return await _E(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},lt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??It,a=n.writeState??Ld,s=fH(),i=!1;try{if(i=await IE(s),!i){if(await jU(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<pH)return t;await AE(s).catch(()=>{}),i=await IE(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await AE(s).catch(()=>{})}},Pd=async(e,t={})=>{await lt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},La=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0);await lt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},vo=async(e={})=>{let t=e.now??Date.now;await lt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},mH=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(sH,Math.max(EE,Math.round(o*aH))):EE},NE=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Nh=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??le,a=n.loadProfile??P,s=n.loadDevKey??Be,i=n.renew??QS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(qS(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()>mH(e))return{outcome:"not-due",profile:e};if(!await lt(g=>r()-(g.lastCertRenewAt??0)<iH?{result:!1}:{next:{...g,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await NE(f,c.sig,t,s))return{outcome:"superseded",profile:f};let p=u.cert.payload.expiresAt,m=Date.parse(p)-r(),y={...f,enrolledCert:u.cert,enrolledCertExpiry:p,...Number.isFinite(m)&&m>0?{enrolledCertLifetimeMs:m}:{}};return await o(y),{outcome:"renewed",profile:y}},xE=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*oH):SE,r=Math.min(SE,n);return Math.min(r,rH*2**Math.max(0,e-1))},hH=()=>{let{command:e,args:t}=or(Qn);return{exe:e,args:t}},Or=async(e={})=>{if(PE())return;let t=e.now??Date.now,n=e.readState??It,r=e.writeState??Ld,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=hH();HU(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await lt(s=>t()-(s.lastSpawnAt??0)<uH(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},yH=kh,gH=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await We(async()=>e);if(!r)return!1;let o=await Ia(n,r.target.origin),a=t?jS(o):o;return a.length===0?!1:(await Ft(a,r.target),!0)}catch{return!1}},wH=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=pe.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=Oe({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:i,user:e.name,team:e.team}),l=await o(c,c.origin,s);return l.matched>0&&l.complete}catch{return!1}},bH=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??It,a=t.writeState??Ld;return bE(e,ke,{now:r,deadWatcherObserved:n,readHookLane:()=>Nd({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>lt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Nd=async(e={})=>{let n=await(e.readState??It)().catch(()=>({}));return vn(n.hookLane)},$E=async(e,t={})=>{try{let n=t.now??Date.now,r=await Nd(t);if(!Sh(r,e,n()))return;await lt(o=>{let a=vn(o.hookLane);return Sh(a,e,n())?{next:{...o,hookLane:nE(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},ME=async(e,t={})=>{try{let n=t.now??Date.now,r=await Nd(t);if(!Eh(r,n()))return;await lt(o=>{let a=vn(o.hookLane);return Eh(a,n())?{next:{...o,hookLane:rE(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},AH=async(e={})=>{try{let t=e.now??Date.now;if((await Nd(e)).watchSince!==void 0)return;await lt(n=>{let r=vn(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:oE(r,t())},result:void 0}},void 0,e)}catch{}},RE=async(e,t={})=>{try{let n=t.now??Date.now;await lt(r=>{let o=vn(r.hookLane),a=aE(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},BE=async(e={})=>{try{if((await(e.readState??It)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>lt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??qg)())return await r()?"stamped":"skipped";let o=await(e.load??P)(),s=await(e.findTools??Ao)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await We(async()=>o);return!i||!await r()?"skipped":(await(e.repair??Ft)(s,i.target),"repathed")}catch{return"skipped"}},FE=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??It)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>lt(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??Ao)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await We(async()=>a);return!c||!await o()?"skipped":(await(e.repair??Ft)(i,c.target)).some(d=>d.status==="failed")?(await lt(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"}},CH=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await Oa(e.gateway,e.clientKey),n=await Ta(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},OE=async(e,t,n)=>{let o=await(t.reconcilePolicy??CH)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>gH(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},Qt=async(e={})=>{if(PE())return"disabled";let t=e.now??Date.now,n=e.loadProfile??P,r=e.saveProfile??le,o=e.loadDevKey??Be,a=e.readState??It,s=e.writeState??Ld,i=e.remint??qt,c=e.heartbeat??SS,l=e.detectSeat??yn,d=e.rewriteTools??yH,u=e.rewriteHookLaneTools??Ch,f=e.probeHookLane??Da,p=e.classifyBeacon??fc,m=e.force===!0,y=!1,g=!1,h=!1,w=!1;e.hookLaneRepair===!0&&(m=!0,w=!0);let b=async C=>{if(!w){C==="repaired"&&await RE("none",{now:t,readState:a,writeState:s});return}let S=C;if(C==="repaired"){let E=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));S=E.verdict==="live"?"repaired":E.verdict==="dark"?"repair_failed":"unverified"}await RE(S,{now:t,readState:a,writeState:s})},k=async()=>{if(!e.runAmbientSelfcheck||g||!y)return!1;g=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(E=>bH(E,{now:t,readState:a,writeState:s},h)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(h=await dr().then(F=>F.some(Y=>!pr(Y.watcherPid))).catch(()=>!1),await AH({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??wb)();let C=await n();if(y=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let S=C.gateway,E=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(E)||E<=t())return"cert-expired";let I=await o();if(!I)return"not-enrolled";let O=(e.resolveMachineUuid??Wt)()||void 0,T=await Nh(C,I,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=T.profile;let U=T.outcome==="renewed",z=C.enrolledCert;if(!z)return"not-enrolled";let K=Date.parse(C.clientKeyExpiresAt??""),oe=Number.isFinite(K)?K-t():0,ae=await a(),Z=!C.clientKey||oe<=Lh(C);if(!m&&sE(vn(ae.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(m=!0,w=!0),C.clientKey&&(m||Z)){let F=await lt(Y=>{let te=t()-(Y.lastAttemptAt??0);return te<kE?{result:"throttled"}:Y.failureCount&&te<xE(Y.failureCount,Y.keyTtlMs)?{result:"backoff"}:{next:{...Y,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(F!=="ok")return F;try{let Y=await c(S,C.clientKey,z,I,{machineUuid:O}),te=await n().catch(()=>C);return te.clientKey!==C.clientKey||te.enrolledCert?.sig!==z.sig?"failed":(await r({...te,clientKeyExpiresAt:Y.expiresAt}),await Pd(({lastError:Ue,...ve})=>({...ve,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Dd(C)??ve.keyTtlMs}),{now:t,readState:a,writeState:s}),w?await b(await wH(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Y){let te=vE(Y);return await Pd(Ue=>({...Ue,lastAttemptAt:t(),failureCount:(Ue.failureCount??0)+1,lastError:{name:Y instanceof Error?Y.name:"Error",...te!==void 0?{code:te}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Y instanceof va&&Y.policyCode==="managed_device_required"&&console.error(Y.message),Y instanceof va?Y.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!m&&C.clientKey&&!Z){let F=await OE(C,e,n),Y=await k();return F||Y?"repaired":U?"cert-renewed":"not-due"}let ie=await lt(F=>{let Y=t()-(F.lastAttemptAt??0);if(m)return Y<nH(F.failureCount)?{result:"throttled"}:{next:{...F,lastAttemptAt:t()},result:"ok"};let te=F.lastError?.code!==void 0&&qU.has(F.lastError.code)?QU:kE;return Y<te?{result:"throttled"}:F.failureCount&&Y<xE(F.failureCount,F.keyTtlMs)?{result:"backoff"}:{next:{...F,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(ie!=="ok")return ie;try{let F=await i(S,z,I,{machineUuid:O}),Y=await l().catch(()=>{}),te=Oe({origin:S,clientKey:F.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Y,user:C.name,team:C.team});if(await d(te,te.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let ve=await n().catch(()=>C),ge=null;ve.enrolledCert&&await NE(ve,z.sig,I,o)&&(ge={...ve,clientKey:F.key,clientKeyExpiresAt:F.expiresAt??ve.clientKeyExpiresAt},await r(ge));let Ht=F.expiresAt?Date.parse(F.expiresAt):NaN,$=Dd(C)??(Number.isFinite(Ht)&&Ht-t()>0?Ht-t():void 0);return await Pd(({lastError:D,...X})=>({...X,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:$??X.keyTtlMs}),{now:t,readState:a,writeState:s}),ge&&await OE(ge,e,n),await b(ge?"repaired":"repair_failed"),await k(),"refreshed"}catch(F){let Y=vE(F);return await Pd(te=>({...te,lastAttemptAt:t(),failureCount:(te.failureCount??0)+1,lastError:{name:F instanceof Error?F.name:"Error",...Y!==void 0?{code:Y}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),F instanceof ct&&F.policyCode==="managed_device_required"&&console.error(F.message),F instanceof ct?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var kH=`anyray-connect print-key [--json | --passthrough-headers]
|
|
354
|
+
`;import{randomBytes as zW}from"node:crypto";var qW=1e4,QW="machine:",eE=e=>e.startsWith(QW),eU="cert-renew",tU=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)},tE=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:zW(16).toString("hex"),purpose:eU},c;try{c=await(n.signer??Ir)(go(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),qW),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 tU(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var kh=async(e,t=e.origin,n=pe)=>{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}},vh=async(e,t=e.origin,n=pe)=>(await kh(e,t,n)).complete;var nU=["claude","codex","cursor","opencode"],rU=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],oU=new Set(["missing_key","key_expired"]);var aU=600*1e3,sU=600*1e3,nE=1440*60*1e3,iU=1440*60*1e3,cU=10080*60*1e3,lU=3600*1e3,dU=720*60*1e3,uU=e=>Math.min(dU,lU*2**Math.max(0,e-1)),gi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_a=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,rE=e=>typeof e=="string"&&rU.includes(e),vn=e=>{if(!gi(e))return{};let t={};if(_a(e.watchSince)&&(t.watchSince=e.watchSince),gi(e.invoked)){let n={};for(let r of nU){let o=e.invoked[r];_a(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return gi(e.authFailure)&&_a(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...rE(e.authFailure.code)?{code:e.authFailure.code}:{}}),gi(e.repair)&&_a(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,..._a(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Ed=e=>{try{let n=JSON.parse(e);if(gi(n)&&rE(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"},Sh=e=>e!==void 0&&oU.has(e),Eh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=aU},oE=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),Ih=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=sU},aE=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),sE=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,iE=(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},cE=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>nE||!Sh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<uU(r.failures??1))},Id=e=>{let t=Object.values(e?.invoked??{}).filter(_a);return t.length>0?Math.max(...t):null},xh=(e,t)=>{if(Id(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=cU},lE=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=iU)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=nE)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var Rh="x-anyray-retrieve-probe",xd=8e3,pU=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",dE=(e,t)=>{let n=jt(e);return t?.probe&&(n[Rh]="1"),n},Pa=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(),xd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:dE(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=pU(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)}},Rd=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(),xd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:dE(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 fU=5e3,mU=2048,hU=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}"`))},Da=async(e={})=>{let t=e.readTarget??tt,n=e.fetch??fetch,r=e.timeoutMs??fU,o=null;try{o=await t()}catch{o=null}if(!o)return{verdict:"dark",reason:"target_null"};let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let i=jt(o);i["content-type"]="application/json",i[Rh]="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,mU);if(!hU(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Ed(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)}},Oh=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{randomBytes as wU}from"node:crypto";import{execSync as Th}from"node:child_process";import{hostname as yU}from"node:os";var gU=e=>{try{if(e==="darwin"){let t=Th("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=Th('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 Th("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Od=(e={platform:process.platform,read:()=>gU(process.platform),hostname:yU})=>e.read().trim()||e.hostname().trim();var Wt=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();if(t)return t.toLowerCase();if((e.platform??process.platform)==="darwin"){let r=e.readMacUuid??(()=>Od());try{return r().trim().toLowerCase()}catch{return""}}return""};var bU=500,uE=2e3,AU=2e3,CU=250,pE=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),bU);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)}},kU=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},vU=e=>new Promise(t=>setTimeout(t,e)),SU=async(e,t,n=vU)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),uE),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=kU(i)??CU,s>AU))return!1}finally{clearTimeout(a)}await n(s)}},EU=async(e,t={})=>{try{let r=(await(t.loadProfile??P)()).enrolledCert,o=await(t.loadDevKey??Be)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:wU(16).toString("hex"),events:e},i;try{i=await(t.signer??Ir)(go(s),o)}catch{return!1}return await(t.post??SU)(`${t.origin??Kn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},IU=async(e,t,n={})=>{try{let o=(await(n.loadProfile??P)()).enrolledCert,a=await(n.loadDevKey??Be)();if(!o||!a)return;await(n.verify??qt)(e,o,a,{timeoutMs:uE,machineUuid:(n.machineUuid??Wt)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},fE=async(e,t)=>{if(e.length!==0)try{let n=await tt(),r=n&&await pE(n.origin,jt(n),e,t);if(n&&await IU(n.origin,e),r)return;await EU(e)}catch{}},_h=async(e,t,n={readTarget:()=>tt("profile"),post:pE})=>{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 ko=["hook_registration","mcp_registration","hook_binary","beacon_target"];var hE=128,yE=300*1e3,xU=["repaired","repair_failed","flapping","pending"],RU=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],gE=["rebroke_same_day","repeat_days"],wE=new Set(pe.map(e=>e.id)),Co=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),bE=e=>bi(e,ko),Td=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},Rr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,wi=e=>{if(!(!Array.isArray(e)||!e.every(bE)))return jn(e)},OU=e=>{if(!Co(e))return;let t=wi(e.checks);if(!(!Rr(e.since)||!bi(e.reason,gE)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},TU=e=>{if(!Co(e))return;let t={};Td(e.day)&&(t.day=e.day),Rr(e.attempts)&&(t.attempts=e.attempts);let n=wi(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=wi(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=wi(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=wi(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Td(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Rr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),Co(e.lastRepaired)){let i={};for(let c of ko){let l=e.lastRepaired[c];Rr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=OU(e.flapping);return s&&(t.flapping=s),t},_U=e=>{if(!Co(e)||!Td(e.day)||!Rr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!wE.has(e.tool)||!bE(e.checkId)||!bi(e.status,xU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!bi(e.errorClass,RU))return;t=e.errorClass}else if(e.status==="flapping"){if(!bi(e.errorClass,gE))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,...Rr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},mE=e=>{if(!Co(e))return{};let t={};if(Co(e.adapters)){let n={};for(let r of wE){let o=TU(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(_U).filter(n=>n!==void 0).slice(-hE)),Rr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Co(e.report)&&Td(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Rr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},PU=e=>new Date(e).toISOString().slice(0,10),DU=(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)],_d=(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}:{}}},Ai=(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(-hE),nextSequence:r}},LU=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),NU=async e=>await We(async()=>e)??null,$U=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=_d(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)},AE=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:DU(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}},MU=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=_d(d,n),f=u.awaiting??[],p=a.get(l);if(f.length===0||t.has(l)||!p){c[l]=u;continue}let m=f.filter(w=>p.checks[w]==="owned"),h=f.filter(w=>{let b=p.checks[w];return b==="missing"||b==="foreign"}),g=f.filter(w=>{let b=p.checks[w];return b===void 0||b==="unreadable"}),y=AE(u,m,n,r);c[l]={...y.adapter,awaiting:g.length>0?g:void 0},i=Ai(i,n,[...m.map(w=>({tool:l,checkId:w,status:"repaired"})),...h.map(w=>({tool:l,checkId:w,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?m.map(w=>({tool:l,checkId:w,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},BU=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=_d(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(y=>!d.includes(y)||u.includes(y)),p=f.filter(y=>u.includes(y)),m=l.attempts??0;if(m>=2||f.length===0&&!n){let y=p.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(y.length===0)return{result:void 0};let w=l.flapping;return c[e]={...l,brokenReportedChecks:jn([...l.brokenReportedChecks??[],...y]),flapping:{since:w?.since??a,reason:"rebroke_same_day",checks:jn([...w?.checks??[],...y])}},{next:Ai({...i,adapters:c},o,y.map(k=>({tool:e,checkId:k,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let h=l.flapping;return c[e]={...l,attempts:m+1,attemptedChecks:jn([...d,...f]),confirmedChecks:u.filter(y=>!f.includes(y)),brokenReportedChecks:jn([...l.brokenReportedChecks??[],...p]),...p.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:jn([...h?.checks??[],...p])}}:{}},{next:Ai({...i,adapters:c},o,p.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),FU=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=_d(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:jn([...l.awaiting??[],...t])},{next:Ai({...i,adapters:c},o,t.map(m=>({tool:e,checkId:m,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(m=>r[m]==="owned"):[],u=n.status==="configured"&&r?t.filter(m=>{let h=r[m];return h==="missing"||h==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=AE(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"apply_unconfirmed";return{next:Ai({...i,adapters:c},o,[...d.map(m=>({tool:e,checkId:m,status:"repaired"})),...u.map(m=>({tool:e,checkId:m,status:"repair_failed",errorClass:p})),...f.slowFlap?d.map(m=>({tool:e,checkId:m,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},WU=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>=yE));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??_h)(o.map(LU),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)},UU=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 m of ko){let h=f[m];if(!h||h==="unreadable")continue;let g,y;p?.awaiting?.includes(m)&&c.has(u.id)?g="pending":h==="missing"&&p?.flapping?.checks.includes(m)?(g="flapping",y=p.flapping.reason):g=h==="owned"?"ok":h,g!=="ok"&&g!=="pending"&&(i=!0),s.push({tool:u.id,checkId:m,status:g,...y?{errorClass:y}:{}})}}let l=Date.parse(e.enrolledCert?.payload.expiresAt??e.enrolledCertExpiry??"");e.enrolledCert&&Number.isFinite(l)&&(l<=o?(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"expired"})):l-o<=336*60*60*1e3&&(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"problems",errorClass:"cert_expiring"}))),e.refreshSchedulerEnabled&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Wo)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??pr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=lE(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},HU=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<yE?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await UU(e,t,n,c,o,s);await(s.report??_h)(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)},CE=async(e,t,n)=>{let r=n.now??Date.now,o=PU(r()),a=e.managedTools??[],s={...n,readState:async()=>mE(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(mE(l)),c)};try{let i=await(s.findIntegrations??bh)(a);await $U(i,o,s);let c=await(s.listPending??dr)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await MU(i,l,o,r(),s);let d=await(s.resolveTarget??NU)(e),u=d?await(s.findDrifted??Ia)(a,d.target.origin):[],f=new Set(u.map(y=>y.id)),p=new Map(i.map(y=>[y.adapter.id,y]));for(let y of u)p.has(y.id)||p.set(y.id,{adapter:y,checks:{}});let m=!1,h=(s.runtimeDurable??ne)();if(d)for(let{adapter:y,checks:w}of p.values()){let b=h?ko.filter(T=>w[T]==="missing"):[];if(b.length===0&&!f.has(y.id))continue;let k=w;if(y.integrationStatus)try{k=await y.integrationStatus()}catch{k=Object.fromEntries(ko.map(T=>[T,"unreadable"]))}let C=b.filter(T=>k[T]==="missing"),S=f.has(y.id);if(S&&y.pointsAt&&(S=!await y.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!S)continue;let E=await BU(y.id,C,S,l.has(y.id),o,r(),s);if(!E)continue;let[I]=await(s.repair??Ft)([y],d.target);if(!I)continue;m=!0;let O;I.status==="configured"&&y.integrationStatus&&(O=await y.integrationStatus().catch(()=>{})),await FU(y.id,E.checks,I,O,o,r(),s)}await WU(o,r(),t,s),i=await(s.findIntegrations??bh)(a);let g=await(s.listPending??dr)().catch(()=>[]);return await HU(e,i,g,o,r(),t,s),m}catch{return!1}};var JU=14,XU=.35,zU=900*1e3,vE=360*60*1e3,qU=.2,QU=1800*1e3,SE=3600*1e3,eH=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),tH=300*1e3,nH=30*1e3,rH=900*1e3,oH=(e=0)=>Math.min(rH,nH*2**Math.max(0,e)),EE=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}},IE=1440*60*1e3,aH=300*1e3,sH=.25,iH=.5,xE=3600*1e3,cH=720*60*60*1e3,lH=360*60*1e3,dH=1440*60*1e3,uH=()=>PE(KU(),".anyray"),Ph=()=>PE(uH(),"refresh-state.json"),Dh=e=>process.env?.[e],LE=()=>Dh("ANYRAY_REFRESH_DISABLE")==="true",Lh=()=>{let e=Dh("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:JU)*dH},Dd=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},NE=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),pH=10080*60*1e3,$E=(e,t,n=Date.now())=>{let r=[],o=Dd(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)<=pH},Nh=e=>{let t=Lh(),n=e?Dd(e):void 0;if(!n)return t;let r=Math.max(zU,Math.round(n*XU));return Math.min(t,r)},fH=e=>{let t=Dh("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(vE,Math.max(QU,Math.round(e*qU))):vE},It=async()=>{try{let e=await jU(Ph(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Ld=async e=>{try{let t=Ph(),n=`${t}.${process.pid}.tmp`;await DE(n,JSON.stringify(e),{mode:384}),await he(n,t),await ZU(t,384).catch(()=>{})}catch{}},mH=3e4,hH=()=>`${Ph()}.lock`,RE=async e=>{try{return await DE(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},lt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??It,a=n.writeState??Ld,s=hH(),i=!1;try{if(i=await RE(s),!i){if(await YU(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<mH)return t;await kE(s).catch(()=>{}),i=await RE(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await kE(s).catch(()=>{})}},Pd=async(e,t={})=>{await lt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},La=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0);await lt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},vo=async(e={})=>{let t=e.now??Date.now;await lt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},yH=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(cH,Math.max(xE,Math.round(o*iH))):xE},ME=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,$h=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??le,a=n.loadProfile??P,s=n.loadDevKey??Be,i=n.renew??tE,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(eE(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()>yH(e))return{outcome:"not-due",profile:e};if(!await lt(g=>r()-(g.lastCertRenewAt??0)<lH?{result:!1}:{next:{...g,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await ME(f,c.sig,t,s))return{outcome:"superseded",profile:f};let p=u.cert.payload.expiresAt,m=Date.parse(p)-r(),h={...f,enrolledCert:u.cert,enrolledCertExpiry:p,...Number.isFinite(m)&&m>0?{enrolledCertLifetimeMs:m}:{}};return await o(h),{outcome:"renewed",profile:h}},OE=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*sH):IE,r=Math.min(IE,n);return Math.min(r,aH*2**Math.max(0,e-1))},gH=()=>{let{command:e,args:t}=or(Qn);return{exe:e,args:t}},Or=async(e={})=>{if(LE())return;let t=e.now??Date.now,n=e.readState??It,r=e.writeState??Ld,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=gH();VU(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await lt(s=>t()-(s.lastSpawnAt??0)<fH(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},wH=vh,bH=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await We(async()=>e);if(!r)return!1;let o=await Ia(n,r.target.origin),a=t?YS(o):o;return a.length===0?!1:(await Ft(a,r.target),!0)}catch{return!1}},AH=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=pe.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=Oe({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:i,user:e.name,team:e.team}),l=await o(c,c.origin,s);return l.matched>0&&l.complete}catch{return!1}},CH=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??It,a=t.writeState??Ld;return CE(e,ke,{now:r,deadWatcherObserved:n,readHookLane:()=>Nd({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>lt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Nd=async(e={})=>{let n=await(e.readState??It)().catch(()=>({}));return vn(n.hookLane)},BE=async(e,t={})=>{try{let n=t.now??Date.now,r=await Nd(t);if(!Eh(r,e,n()))return;await lt(o=>{let a=vn(o.hookLane);return Eh(a,e,n())?{next:{...o,hookLane:oE(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},FE=async(e,t={})=>{try{let n=t.now??Date.now,r=await Nd(t);if(!Ih(r,n()))return;await lt(o=>{let a=vn(o.hookLane);return Ih(a,n())?{next:{...o,hookLane:aE(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},kH=async(e={})=>{try{let t=e.now??Date.now;if((await Nd(e)).watchSince!==void 0)return;await lt(n=>{let r=vn(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:sE(r,t())},result:void 0}},void 0,e)}catch{}},TE=async(e,t={})=>{try{let n=t.now??Date.now;await lt(r=>{let o=vn(r.hookLane),a=iE(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},WE=async(e={})=>{try{if((await(e.readState??It)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>lt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??ew)())return await r()?"stamped":"skipped";let o=await(e.load??P)(),s=await(e.findTools??Ao)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await We(async()=>o);return!i||!await r()?"skipped":(await(e.repair??Ft)(s,i.target),"repathed")}catch{return"skipped"}},UE=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??It)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>lt(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??Ao)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await We(async()=>a);return!c||!await o()?"skipped":(await(e.repair??Ft)(i,c.target)).some(d=>d.status==="failed")?(await lt(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"}},vH=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await Oa(e.gateway,e.clientKey),n=await Ta(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},_E=async(e,t,n)=>{let o=await(t.reconcilePolicy??vH)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>bH(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},Qt=async(e={})=>{if(LE())return"disabled";let t=e.now??Date.now,n=e.loadProfile??P,r=e.saveProfile??le,o=e.loadDevKey??Be,a=e.readState??It,s=e.writeState??Ld,i=e.remint??qt,c=e.heartbeat??IS,l=e.detectSeat??yn,d=e.rewriteTools??wH,u=e.rewriteHookLaneTools??kh,f=e.probeHookLane??Da,p=e.classifyBeacon??fc,m=e.force===!0,h=!1,g=!1,y=!1,w=!1;e.hookLaneRepair===!0&&(m=!0,w=!0);let b=async C=>{if(!w){C==="repaired"&&await TE("none",{now:t,readState:a,writeState:s});return}let S=C;if(C==="repaired"){let E=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));S=E.verdict==="live"?"repaired":E.verdict==="dark"?"repair_failed":"unverified"}await TE(S,{now:t,readState:a,writeState:s})},k=async()=>{if(!e.runAmbientSelfcheck||g||!h)return!1;g=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(E=>CH(E,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await dr().then(F=>F.some(Y=>!pr(Y.watcherPid))).catch(()=>!1),await kH({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??Ab)();let C=await n();if(h=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let S=C.gateway,E=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(E)||E<=t())return"cert-expired";let I=await o();if(!I)return"not-enrolled";let O=(e.resolveMachineUuid??Wt)()||void 0,T=await $h(C,I,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=T.profile;let U=T.outcome==="renewed",z=C.enrolledCert;if(!z)return"not-enrolled";let K=Date.parse(C.clientKeyExpiresAt??""),oe=Number.isFinite(K)?K-t():0,ae=await a(),Z=!C.clientKey||oe<=Nh(C);if(!m&&cE(vn(ae.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(m=!0,w=!0),C.clientKey&&(m||Z)){let F=await lt(Y=>{let te=t()-(Y.lastAttemptAt??0);return te<SE?{result:"throttled"}:Y.failureCount&&te<OE(Y.failureCount,Y.keyTtlMs)?{result:"backoff"}:{next:{...Y,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(F!=="ok")return F;try{let Y=await c(S,C.clientKey,z,I,{machineUuid:O}),te=await n().catch(()=>C);return te.clientKey!==C.clientKey||te.enrolledCert?.sig!==z.sig?"failed":(await r({...te,clientKeyExpiresAt:Y.expiresAt}),await Pd(({lastError:Ue,...ve})=>({...ve,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Dd(C)??ve.keyTtlMs}),{now:t,readState:a,writeState:s}),w?await b(await AH(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Y){let te=EE(Y);return await Pd(Ue=>({...Ue,lastAttemptAt:t(),failureCount:(Ue.failureCount??0)+1,lastError:{name:Y instanceof Error?Y.name:"Error",...te!==void 0?{code:te}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Y instanceof va&&Y.policyCode==="managed_device_required"&&console.error(Y.message),Y instanceof va?Y.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!m&&C.clientKey&&!Z){let F=await _E(C,e,n),Y=await k();return F||Y?"repaired":U?"cert-renewed":"not-due"}let ie=await lt(F=>{let Y=t()-(F.lastAttemptAt??0);if(m)return Y<oH(F.failureCount)?{result:"throttled"}:{next:{...F,lastAttemptAt:t()},result:"ok"};let te=F.lastError?.code!==void 0&&eH.has(F.lastError.code)?tH:SE;return Y<te?{result:"throttled"}:F.failureCount&&Y<OE(F.failureCount,F.keyTtlMs)?{result:"backoff"}:{next:{...F,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(ie!=="ok")return ie;try{let F=await i(S,z,I,{machineUuid:O}),Y=await l().catch(()=>{}),te=Oe({origin:S,clientKey:F.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Y,user:C.name,team:C.team});if(await d(te,te.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let ve=await n().catch(()=>C),ge=null;ve.enrolledCert&&await ME(ve,z.sig,I,o)&&(ge={...ve,clientKey:F.key,clientKeyExpiresAt:F.expiresAt??ve.clientKeyExpiresAt},await r(ge));let Ht=F.expiresAt?Date.parse(F.expiresAt):NaN,$=Dd(C)??(Number.isFinite(Ht)&&Ht-t()>0?Ht-t():void 0);return await Pd(({lastError:D,...X})=>({...X,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:$??X.keyTtlMs}),{now:t,readState:a,writeState:s}),ge&&await _E(ge,e,n),await b(ge?"repaired":"repair_failed"),await k(),"refreshed"}catch(F){let Y=EE(F);return await Pd(te=>({...te,lastAttemptAt:t(),failureCount:(te.failureCount??0)+1,lastError:{name:F instanceof Error?F.name:"Error",...Y!==void 0?{code:Y}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),F instanceof ct&&F.policyCode==="managed_device_required"&&console.error(F.message),F instanceof ct?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var SH=`anyray-connect print-key [--json | --passthrough-headers]
|
|
355
355
|
|
|
356
356
|
Print the current short-lived Anyray client key for a consuming app.
|
|
357
357
|
|
|
@@ -363,10 +363,10 @@ Options:
|
|
|
363
363
|
"x-anyray-provider":"anthropic","x-anyray-metadata":"..."}).
|
|
364
364
|
Carries the client key, never the seat OAuth token.
|
|
365
365
|
--help Show this help.
|
|
366
|
-
`,
|
|
367
|
-
`);let s=o.passthroughHeaders?
|
|
366
|
+
`,EH=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}},IH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Nh(e):!0},HE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},GE=(e,t)=>{if(!be(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},Mh=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,xH=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Mh(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 \`${Mh(t)}\`.`:"Your enrollment certificate is no longer valid. Reconnect with `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"gateway-incompatible":return"The gateway key-renewal route is unavailable (HTTP 404). Check the deployment version and routing; your enrollment certificate was not rejected.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${Mh(t)}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.";case"disabled":return"Automatic key refresh is disabled.";case"backoff":case"throttled":return"Key refresh is temporarily unavailable; retry shortly.";case"not-due":case"repaired":case"cert-renewed":case"heartbeat-refreshed":case"refreshed":return""}},Ci=async(e={})=>{let t=e.loadProfile??P,n=e.refreshIfDue??Qt,r=e.now??Date.now,o=await t();if(HE(o),!o.enrolledCert){if(!GE(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||IH(o,r)){let i=xH(await n(),o);if(i){if(!GE(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(HE(s),!be(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},VE=e=>fe({user:e.name,team:e.team}),$d=({profile:e,token:t})=>{let n={},r=VE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Bh=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=VE(e);return r&&(n["x-anyray-metadata"]=r),n},RH=e=>JSON.stringify(Bh(e)),KE=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=EH(e);if(o.help)return n.write(SH),0;let a=await Ci(t);a.warning&&r.write(`${a.warning}
|
|
367
|
+
`);let s=o.passthroughHeaders?RH(a):o.json?$d(a):a.token;return n.write(`${s}
|
|
368
368
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
369
|
-
`),1}};var
|
|
369
|
+
`),1}};var jE=`anyray-connect models [<model-id>] [--json]
|
|
370
370
|
|
|
371
371
|
List the Copilot models your seat can run on the Anyray lane, or switch the
|
|
372
372
|
Copilot CLI's startup model. The CLI's own /models cannot list models on a
|
|
@@ -378,8 +378,8 @@ Options:
|
|
|
378
378
|
--json Emit {"origin","current","models":[{"id","wire",...caps}]} instead
|
|
379
379
|
of the table (listing only).
|
|
380
380
|
--help Show this help.
|
|
381
|
-
`,
|
|
382
|
-
`),0;A(j(`Copilot models your seat serves (via ${o.origin})`));for(let m of l){let
|
|
381
|
+
`,OH=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},TH=e=>{let t=pe.find(n=>n.id===ro);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},_H=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(" / ")},PH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Us(t)}/${Dn(n)==="responses"?"responses":"chat/completions"}`,ZE=async(e=[],t={})=>{let n=OH(e);if(n.help)return process.stdout.write(jE),0;if(n.error)return R(n.error),process.stdout.write(jE),1;let r=await(t.loadTarget??We)();if(!r)return R("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??hl)({allowKeychainPrompt:!0});if(!a.token)return R("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??ea)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=Rf(c);if(l.length===0)return R("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(m=>({id:m.id,wire:Dn(m.id),...m.maxPromptTokens?{maxPromptTokens:m.maxPromptTokens}:{},...m.maxOutputTokens?{maxOutputTokens:m.maxOutputTokens}:{}}))})}
|
|
382
|
+
`),0;A(j(`Copilot models your seat serves (via ${o.origin})`));for(let m of l){let h=m.id===p?"*":" ",g=_H(m);A(` ${h} ${m.id.padEnd(24)}${g?v(g):""}`)}return N("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),N("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 R(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??ml)(PH(o,i,d.id),{...xf(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return R(`GitHub refuses chat as '${d.id}' for this sign-in (it is in the catalog, but chat entitlement is narrower). Pick another id from \`anyray-connect models\`.`),1;u==="unreachable"?_("Could not verify the model over the lane (offline?) \u2014 applying anyway."):B(`'${d.id}' answers on your lane.`);let f=process.env.ANYRAY_COPILOT_MODEL;process.env.ANYRAY_COPILOT_MODEL=d.id;try{let p=await(t.applyCopilotCli??TH)(o);if(p.status!=="configured"){for(let m of p.messages)A(m);return R("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 B(`Copilot CLI startup model \u2192 ${d.id}`),N("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var DH=`anyray-connect copilot-login
|
|
383
383
|
|
|
384
384
|
Sign Anyray in to GitHub Copilot (device flow) so the Copilot CLI seat lane
|
|
385
385
|
can run your plan's current models. Opens no browser for you: it prints a
|
|
@@ -387,23 +387,23 @@ code to type at github.com/login/device.
|
|
|
387
387
|
|
|
388
388
|
Options:
|
|
389
389
|
--help Show this help.
|
|
390
|
-
`,
|
|
391
|
-
`,{mode:384}),await
|
|
390
|
+
`,YE=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(DH),0;A(j("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??rC)();if(!n)return R("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;A(` 1. Open ${ze(n.verificationUri)}`),A(` 2. Enter the code: ${j(n.userCode)}`),N(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??oC)(n);if(r.status!=="ok")return R(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??aC)(r.token,o);B(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??Af)(r.token);if(s.verdict==="no-copilot")return R("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??We)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??ea)(r.token,{},s.capiSegment,c);return l.length===0?_("Signed in, but no model list came back \u2014 that is usually this machine or its network, not the sign-in. Continue with `anyray-connect --tools copilot-cli`; it verifies the model with a live check of its own."):B(`${l.length} models available (e.g. ${l[0].id}).`),N("Now run: anyray-connect --tools copilot-cli"),0};import{randomBytes as LH}from"node:crypto";import{chmod as NH,readFile as $H,rm as XE,writeFile as MH}from"node:fs/promises";import{join as BH}from"node:path";var FH=/^[A-Za-z0-9_-]{43}$/,JE=3900,WH=1e4,Fh=()=>BH(Q(),"device-token.json"),UH=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&FH.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},zE=async()=>{try{let e=JSON.parse(await $H(Fh(),"utf-8"));return UH(e)?e:null}catch{return null}},HH=0,GH=async e=>{await Qe();let t=Fh(),n=`${t}.${process.pid}.${HH++}.tmp`;try{await MH(n,`${JSON.stringify(e)}
|
|
391
|
+
`,{mode:384}),await NH(n,384),await he(n,t)}catch(r){throw await XE(n,{force:!0}).catch(()=>{}),r}},Md=async()=>{await XE(Fh(),{force:!0}).catch(()=>{})},VH=()=>LH(32).toString("base64url"),KH=e=>e instanceof Error?e.name:"UnknownError",qE=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=VH(),i=new AbortController,c=setTimeout(()=>i.abort(),WH),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:JE}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await GH({v:1,token:s,expiresAt:t()+JE*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${KH(r)}`),!1}};var QE=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??P)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=e.readState??zE,i=await s();return(!i||i.expiresAt<=r())&&(await(e.rotateToken??qE)(),i=await s()),!i||i.expiresAt<=r()?(n.write(`Could not register a device token \u2014 retry after checking gateway connectivity.
|
|
392
392
|
`),1):(t.write(`${a}/device?dt=${i.token}
|
|
393
|
-
`),0)};import{join as
|
|
393
|
+
`),0)};import{join as sI,dirname as nG}from"node:path";import{mkdir as rG,readFile as Zh,rm as iI,writeFile as cI}from"node:fs/promises";import{fstatSync as JH,openSync as XH,statSync as zH}from"node:fs";import{createInterface as qH}from"node:readline/promises";import{ReadStream as QH}from"node:tty";import{execFileSync as eI}from"node:child_process";import jH from"node:os";var Wh=e=>{try{return eI("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},ZH=e=>{try{return eI("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},YH=new Set(["root","unknown","user","admin","administrator","developer","dev","node","ubuntu","debian","ec2-user","vagrant","docker","container","vscode","codespace","devcontainer","runner","builder","jenkins","build","ci"]),Uh=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:YH.has(t):!0},Bd=()=>{try{return jH.userInfo().username||void 0}catch{return}},tI=()=>Wh("user.name")??Wh("user.email")??Bd()??"unknown",nI=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Wh),global:e.globalGitConfig??(t||ZH)}},So=e=>{try{return e()?.trim()||void 0}catch{return}},Hh=(e={})=>{let t=nI(e),n=So(e.osUsername??Bd),r=So(()=>t.global("user.email"))??So(()=>t.local("user.email"));return r||(So(()=>t.global("user.name"))??So(()=>t.local("user.name"))??n??"unknown")},rI=(e={})=>{let t=Hh(e);if(Uh(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=nI(e);return!!(So(()=>n.global("user.email"))??So(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var mt=()=>!!process.stdin.isTTY,eG=()=>{try{let e=JH(0);return e.isCharacterDevice()&&e.rdev===zH("/dev/tty").rdev}catch{return!1}},Gh=()=>{if(eG()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new QH(XH(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},ft=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},oI=async(e,t)=>{let n=t.input??Gh(),r=t.output??process.stdout,o=qH({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 ft))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new ft)))})}finally{o.close(),n.close()}},Eo=async(e,t={})=>{let n=(await oI(`${e} ${v("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Na=async(e,t,n={})=>{let r=t?` ${v(`[${t}]`)}`:"";return(await oI(`${e}${r}: `,n)).trim()||t},Vh=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return N(`Your name: ${t} ${v("(cached \u2014 pass --user to change)")}`),t;let r=tI();return n||!mt()?(N(`Your name: ${r} ${v("(auto-detected \u2014 pass --user to change)")}`),r):Na("? Your name",r)},Kh=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return N(`Team: ${t} ${v("(cached \u2014 pass --team to change)")}`),t;if(!(n||!mt()))return Na("? Team (optional)")},Tr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return Vt(e??n)},aI=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,$a="claude-desktop",Fd=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await Sr(e.runReg??Hn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Mt({home:e.home});return await x(s)?{authoritative:!0}:n("no-local-record")}if(t!=="darwin")return n("manual-platform");let r={home:e.home,managedPolicyPaths:e.managedPolicyPaths,readManagedPolicyKeys:e.readManagedPolicyKeys},o=Yt(r);return await co(o,r)?n("managed-policy"):(await ba({home:e.home,readClaudeAppVersion:e.readClaudeAppVersion,readClaudeAppBundle:e.readClaudeAppBundle})).supported?await x(o.journal)?{authoritative:!0}:n("no-local-record"):n("unverified-build")}catch{return n("no-local-record")}},Wd=e=>e.id!==$a||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",tG={"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"},Ud=(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=tG[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 jh=["claude-code","codex"],oG="anyray-connect print-key",Yh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),aG=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:ts,authMode:"placeholder",metadata:{}}),Jh=e=>sI(e,".claude","settings.json"),sG=async(e,t,n)=>{let r=Jh(e),o=await M(r),{env:a}=rn(t,{includeAuthToken:!1,includeClientKey:!1}),s=Yh(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=oG,n||await J(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]}},lI=async(e=process.cwd())=>{let t=[],n=Jh(e);try{if(await x(n)){let o=await M(n),a=Yh(o.env)?o.env:{};(Wr.some(s=>s in a)||Ur(o))&&t.push(n)}}catch{}let r=Xh(e);try{if(await x(r)){let o=await Zh(r,"utf-8");Ep(o)&&t.push(r)}}catch{}return t},iG=async(e,t)=>{let n=Jh(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await M(n),o=!1;if(Yh(r.env)){let s={...r.env};for(let i of Wr)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 iI(n,{force:!0}):await J(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},Xh=e=>sI(e,".codex","config.toml"),cG=async(e,t,n)=>{let r=Xh(e),o=await Zh(r,"utf-8").catch(()=>""),a=Tc(o,ws(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await rG(nG(r),{recursive:!0}),await cI(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]}},lG=async(e,t)=>{let n=Xh(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Zh(n,"utf-8"),o=_c(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await iI(n,{force:!0}):await cI(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},dI=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...jh],r=n.filter(s=>!jh.includes(s));if(r.length>0)return R(`--project supports ${jh.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 R("--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 R(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=aG(Gt(i))}if(A(j(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),H("Project"),A(` Directory: ${t}`),o&&A(` Gateway: ${o.origin}`),A(` Tools: ${n.join(", ")}`),e.revert||(_(`
|
|
394
394
|
A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),N(" 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(!mt())return R(`
|
|
395
395
|
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 Eo(`
|
|
396
396
|
${s} ${n.length} tool(s)?`))return N("Aborted. Nothing changed."),0}e.dryRun&&N(`
|
|
397
|
-
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){H(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await
|
|
398
|
-
`),1;let o;try{o=await Ci(t)}catch(i){let c=i instanceof Error&&i.message?i.message:
|
|
399
|
-
`),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=$d(o);else try{s=await
|
|
397
|
+
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){H(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await sG(t,o,e.dryRun):await cG(t,o,e.dryRun):s==="claude-code"?await iG(t,e.dryRun):await lG(t,e.dryRun);for(let c of i.messages)A(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(H("Next"),e.revert)B(" Project config removed. Commit the change to propagate it.");else{B(" Commit these files to route every checkout of this repo:");for(let s of a)A(` ${s}`);A(v(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as dG}from"node:child_process";var uG="/usr/bin/security",pG=["find-generic-password","-s","Claude Code-credentials","-w"],fG=1e4,mG=64*1024,hG=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,zh="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",yG=(e,t,n)=>new Promise((r,o)=>{dG(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),uI=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),gG=e=>{let t=JSON.parse(e);if(!uI(t)||!uI(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!hG.test(n))throw new Error("unexpected keychain access token");return n},wG=async(e,t)=>{let n=Bh(e),r=await(t.execSecurity??yG)(uG,[...pG],{encoding:"utf8",timeout:fG,maxBuffer:mG,shell:!1});return JSON.stringify({token:gG(r.stdout),headers:n})},pI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${zh}
|
|
398
|
+
`),1;let o;try{o=await Ci(t)}catch(i){let c=i instanceof Error&&i.message?i.message:zh;return r.write(`${c}
|
|
399
|
+
`),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=$d(o);else try{s=await wG(o,t)}catch{if(a==="subscription")return r.write(`${zh}
|
|
400
400
|
`),1;s=$d(o)}return o.warning&&r.write(`${o.warning}
|
|
401
401
|
`),n.write(`${s}
|
|
402
|
-
`),0};var
|
|
402
|
+
`),0};var fI="Anyray: could not resolve the Anyray client key for the Claude Desktop bootstrap fetch. Run `anyray-connect` and try again.",mI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${fI}
|
|
403
403
|
`),1;try{let o=await Ci(t);return o.warning&&r.write(`${o.warning}
|
|
404
404
|
`),n.write(`${JSON.stringify({Authorization:`Bearer ${o.token}`})}
|
|
405
|
-
`),0}catch{return r.write(`${
|
|
406
|
-
`),1}};import{mkdir as
|
|
405
|
+
`),0}catch{return r.write(`${fI}
|
|
406
|
+
`),1}};import{mkdir as GG,writeFile as VG}from"node:fs/promises";import{dirname as KG}from"node:path";import{Buffer as jG}from"node:buffer";import{constants as hI}from"node:fs";import{access as bG,chmod as AG,lstat as CG,mkdir as kG,open as vG,readFile as SG,realpath as EG,rm as IG,stat as gI,writeFile as xG}from"node:fs/promises";import{randomUUID as RG}from"node:crypto";import{platform as Qh}from"node:os";import{dirname as OG,join as TG,posix as _G,win32 as wI}from"node:path";var Si="/usr/local/bin/anyray-credential-helper",Ei="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Hd="/usr/local/bin/anyray-bootstrap-headers-helper",Gd="C:\\Program Files\\Anyray\\anyray-bootstrap-headers-helper.cmd",vi="Managed by anyray-connect desktop helper; do not edit.",PG=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
|
|
407
407
|
|
|
408
408
|
Create the helpers required by Claude Desktop and Codex fleet artifacts: the
|
|
409
409
|
credential helper (inferenceCredentialHelper, also used by Codex) and the
|
|
@@ -445,15 +445,15 @@ Examples:
|
|
|
445
445
|
anyray-connect desktop helper --print --wrapper bootstrap-headers \\
|
|
446
446
|
--platform posix --bin /usr/local/bin/anyray-connect \\
|
|
447
447
|
> anyray-bootstrap-headers-helper
|
|
448
|
-
`,
|
|
449
|
-
`);let r=
|
|
450
|
-
`)},
|
|
451
|
-
`):["#!/bin/sh",`# ${vi}`,'if [ "$#" -eq 0 ]; then',` exec ${
|
|
452
|
-
`)},Kd=(e,t)=>{if(!Ii(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=xi(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"]}},
|
|
453
|
-
`),0}if(s!==
|
|
448
|
+
`,qh=(e=Qh())=>e==="win32"?"windows":"posix",bI=e=>e==="windows"?Ei:Si,AI=e=>e==="windows"?Gd:Hd,yI=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},DG=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":yI(t,"write");break;case"--print":yI(t,"print");break;case"--bin":t.binaryPath=o();break;case"--path":t.helperPath=o();break;case"--bootstrap-headers-path":t.bootstrapHeadersHelperPath=o();break;case"--wrapper":{let a=o();if(a!=="credential"&&a!=="bootstrap-headers")throw new Error("--wrapper must be credential or bootstrap-headers");t.wrapper=a;break}case"--platform":{let a=o();if(a!=="posix"&&a!=="windows")throw new Error("--platform must be posix or windows");t.targetPlatform=a;break}case"--help":case"-h":t.help=!0;break;default:throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r}`)}}return t},LG=e=>/[\0\r\n]/.test(e),NG=e=>/^[A-Za-z]:[\\/]/.test(e)&&wI.isAbsolute(e),Ii=(e,t)=>!LG(e)&&(t==="windows"?NG(e):_G.isAbsolute(e)),ki=e=>e.replace(/\\/g,"/").toLowerCase(),Vd=(e,t)=>{if(!Ii(e,t))return!1;let n=ki(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)))},xi=(e,t)=>t==="windows"?wI.normalize(e):e,ey=e=>`'${e.replace(/'/g,`'"'"'`)}'`,CI=(e,t)=>{if(!Vd(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=xi(t,e);if(e==="windows")return["@echo off",`REM ${vi}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" ${kr}`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
449
|
+
`);let r=ey(n);return["#!/bin/sh",`# ${vi}`,'if [ "$#" -eq 0 ]; then',` exec ${r} ${kr}`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
|
|
450
|
+
`)},kI=(e,t)=>{if(!Vd(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=xi(t,e);return e==="windows"?["@echo off",`REM ${vi}`,'if not "%~1"=="" exit /b 64',`"${n}" ${Xs}`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
451
|
+
`):["#!/bin/sh",`# ${vi}`,'if [ "$#" -eq 0 ]; then',` exec ${ey(n)} ${Xs}`,"fi","exit 64",""].join(`
|
|
452
|
+
`)},Kd=(e,t)=>{if(!Ii(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=xi(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"]}},vI=async e=>{try{return await SG(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},$G=async(e,t)=>{try{let n=await EG(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!Vd(r,t))throw new Error;if(!(await gI(n)).isFile())throw new Error;await bG(n,t==="posix"?hI.X_OK:hI.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},SI=e=>e.slice(0,300).includes(vi),EI=async(e,t,n)=>{let r=await vI(e);if(r!==void 0&&r!==t&&!SI(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 gI(e)).mode&511)===493)return"unchanged"}catch{}}let o=OG(e);try{await kG(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=TG(o,`.anyray-helper.${process.pid}.${RG()}.tmp`),s=!1;try{await xG(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await AG(a,493);let i=await vG(a,"r");try{await Yn(i)}finally{await i.close()}await he(a,e),s=!0}catch{throw new Error(`could not install helper at ${e}`)}finally{s||await IG(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},MG=(e,t,n)=>{let r=n==="windows"?`"${xi(t,n)}" `:` exec ${ey(t)} `;return e.split(/\r?\n/).some(o=>o.startsWith(r)&&o.length>r.length)},jd=async(e,t={})=>{let n=qh((t.platform??Qh)());if(!Vd(e,n))return;let r=[{path:t.helperPath??bI(n),content:CI(n,e)},{path:t.bootstrapHeadersHelperPath??AI(n),content:kI(n,e)}];for(let o of r)try{if((await CG(o.path).catch(()=>{}))?.isSymbolicLink())continue;let a=await vI(o.path);if(a===void 0||a===o.content||!SI(a)||!MG(a,e,n))continue;await EI(o.path,o.content,n)}catch{}},II=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=DG(e);if(o.help)return n.write(PG),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");if(o.wrapper&&o.mode!=="print")throw new Error("--wrapper applies to --print only; --write installs both helpers");let a=(t.platform??Qh)(),s=o.targetPlatform??qh(a),i=o.binaryPath,c=(d,u,f)=>{let p=xi(u??f,s);if(!Ii(p,s))throw new Error(`${d} must be an absolute ${s} path`);if(s==="windows"&&Kd("windows",p),ki(p)===ki(i))throw new Error(`${d} must differ from --bin (the helper cannot invoke itself)`);return p},l=[{kind:"credential",label:"credential helper",path:c("--path",o.helperPath,bI(s)),content:CI(s,i)},{kind:"bootstrap-headers",label:"bootstrap-headers helper",path:c("--bootstrap-headers-path",o.bootstrapHeadersHelperPath,AI(s)),content:kI(s,i)}];if(ki(l[0].path)===ki(l[1].path))throw new Error("--path and --bootstrap-headers-path must differ");if(o.mode==="print"){let d=o.wrapper??"credential",u=l.find(f=>f.kind===d);return n.write(u.content),r.write(`Deploy this wrapper at ${u.path} after deploying the binary at ${i}.
|
|
453
|
+
`),0}if(s!==qh(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await $G(i,s);for(let d of l){let u=await EI(d.path,d.content,s),f=d.label[0].toUpperCase()+d.label.slice(1);r.write(u==="unchanged"?`${f} already current at ${d.path}.
|
|
454
454
|
`:`${u==="installed"?"Installed":"Updated"} ${d.label} at ${d.path}.
|
|
455
455
|
`)}return 0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
456
|
-
`),1}};var
|
|
456
|
+
`),1}};var BG=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),FG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,WG=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.")},UG=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Zd=(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!==""||WG(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ma=(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()}},xI=e=>{if(!UG(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!BG.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ma(e.clientId,"clientId",!0),r=Ma(e.scopes,"scopes",!0),o=Ma(e.issuer,"issuer",!1),a=Ma(e.authorizationUrl,"authorizationUrl",!1),s=Ma(e.tokenUrl,"tokenUrl",!1),i=Ma(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:Zd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Zd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Zd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},RI=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return xI(t)},ty=e=>e==="windows"?Gd:Hd,HG=(e,t)=>{let n=new URL(e);return n.searchParams.set("os",t),n.toString()},Yd=(e,t)=>{let n=HG(Zd(e.url,"--bootstrap-url"),t),r=e.oidc?xI(e.oidc):void 0,o;if(e.deploymentOrganizationUuid!==void 0&&(o=e.deploymentOrganizationUuid.trim(),!FG.test(o)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:n,bootstrapHeadersHelper:ty(t),...r?{bootstrapOidc:r}:{},...o?{deploymentOrganizationUuid:o}:{}}},OI=(e,t)=>vr(Yd(e,t));var ZG=`anyray-connect desktop [disconnect] [options]
|
|
457
457
|
|
|
458
458
|
The minimum Claude Desktop workflow:
|
|
459
459
|
anyray-connect desktop Connect this machine
|
|
@@ -498,8 +498,8 @@ Options:
|
|
|
498
498
|
|
|
499
499
|
Older flag-based Claude artifacts and Codex fleet output remain accepted for
|
|
500
500
|
compatibility, but are not part of the recommended Claude Desktop workflow.
|
|
501
|
-
`,
|
|
502
|
-
<string>${Zn(t)}</string>`,
|
|
501
|
+
`,YG=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",JG=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),XG=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[YG(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...JG(o)]},zG=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),ny=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>zG.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,"'"),TI=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),qG=(e,t)=>` <key>${Zn(e)}</key>
|
|
502
|
+
<string>${Zn(t)}</string>`,ry=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>qG(i,c)).join(`
|
|
503
503
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
504
504
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
505
505
|
<plist version="1.0">
|
|
@@ -532,21 +532,21 @@ ${s}
|
|
|
532
532
|
<string>${Zn(n)}</string>
|
|
533
533
|
</dict>
|
|
534
534
|
</plist>
|
|
535
|
-
`},Ri={disableDeploymentModeChooser:!0},
|
|
536
|
-
`,
|
|
537
|
-
`,
|
|
538
|
-
`),
|
|
535
|
+
`},Ri={disableDeploymentModeChooser:!0},PI=(e,t)=>ry("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",vr({...io(e,t),...Ri})),QG=(e,t)=>`${JSON.stringify({...io(e,t),...Ri},null,2)}
|
|
536
|
+
`,e1=e=>ry("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",vr({...Yd(e,"macos"),...Ri})),t1=e=>`${JSON.stringify({...Yd(e,"linux"),...Ri},null,2)}
|
|
537
|
+
`,DI=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries({...e,...vr(Ri)}).map(([n,r])=>`"${TI(n)}"="${TI(r)}"`),""].join(`
|
|
538
|
+
`),LI=(e,t)=>{let n=Vl(e,t);return DI(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},n1=e=>DI(OI(e,"windows")),NI=(e,t,n)=>{if(t==="darwin"){let r=Si;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:PI(e,r),helperPath:r}}if(t==="win32"){let r=Ei;return{path:`${n}\\claude-desktop-anyray.reg`,content:LI(e,r),helperPath:r}}},$I=(e,t)=>[`Generated the complete Claude Desktop profile your administrator can deploy: ${e.path}`,t==="darwin"?"Send it to IT to push through MDM (Jamf, Intune, Kandji). It carries the full Anyray connection \u2014 no hand-merging, and no Developer Mode on the target machines.":"Send it to IT to import into machine policy (HKLM\\SOFTWARE\\Policies\\Claude), or push it through your device-management system.",`It references the shared credential helper at ${e.helperPath}, which IT deploys once per machine with \`anyray-connect desktop helper --write\`. The profile contains no credential.`,"Nothing on this machine changed; the managed policy stays authoritative until IT deploys it."],r1=(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=Kd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${ws(e,o).join(`
|
|
539
539
|
`)}
|
|
540
|
-
`},
|
|
540
|
+
`},o1=e=>ry("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:jG.from(e,"utf-8").toString("base64")}),a1=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},s1=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=Vt(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:ts,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},_I=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??GG,o=n.writeFile??VG;await r(KG(t),{recursive:!0}),await o(t,e)},i1=(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:
|
|
541
541
|
`),o.write(r==="windows"?` anyray-connect desktop helper --write --platform windows --bin "C:\\Program Files\\Anyray\\anyray-connect.exe" --path "${n}"
|
|
542
542
|
`:` sudo anyray-connect desktop helper --write --platform posix --bin /usr/local/bin/anyray-connect --path '${n.replace(/'/g,`'"'"'`)}'
|
|
543
543
|
`),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.
|
|
544
544
|
`):t==="json"&&o.write(`Deploy this file to /etc/claude-desktop/managed-settings.json.
|
|
545
|
-
`)},
|
|
546
|
-
`),t.write(`The bootstrap fetch is authenticated by the bootstrap-headers helper at ${
|
|
545
|
+
`)},c1=(e,t)=>{t.write(`This artifact is a stable MDM trust anchor; it contains no inference credential. Claude Desktop authenticates the user and fetches the effective configuration from the bootstrap service at launch.
|
|
546
|
+
`),t.write(`The bootstrap fetch is authenticated by the bootstrap-headers helper at ${ty(e)}, and the response names the credential helper; install both on every managed machine first with \`anyray-connect desktop helper --write\` (deploy a stable anyray-connect binary through your software-distribution system before that).
|
|
547
547
|
`),t.write(`Update the bootstrap response instead of redeploying MDM. Claude polls every 30 minutes, then applies changed values on the next Claude Desktop launch; no managed action is required for each policy update.
|
|
548
548
|
`),t.write(`Each bootstrap response replaces the allowed managed configuration; omitted keys are unset.
|
|
549
|
-
`)},
|
|
549
|
+
`)},l1=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??po)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
|
|
550
550
|
${o.remedy}
|
|
551
551
|
`),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("; ")})`:"")+`
|
|
552
552
|
`)}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)`:"")+`
|
|
@@ -557,10 +557,10 @@ Reopen Claude Desktop \u2014 migrated ${c} available in the Anyray profile.
|
|
|
557
557
|
Your previous profile is untouched, so \`desktop disconnect\` still works.
|
|
558
558
|
`)}else n.write(`
|
|
559
559
|
Nothing new to migrate \u2014 no local sessions or portable local data needed copying.
|
|
560
|
-
`);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},
|
|
561
|
-
`),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 ${Si} on macOS/Linux or ${Ei} 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(!Ii(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"&&Kd("windows",i);let l=
|
|
560
|
+
`);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},MI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=XG(e);if(o[0]==="helper")return II(o.slice(1),t);let a=a1(o);if(a.help)return n.write(ZG),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 l1(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:RI(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?n1(u):a.artifact==="json"?t1(u):e1(u);return await _I(f,a.path,t),c1(a.artifact==="reg"?"windows":a.artifact==="json"?"linux":"macos",r),a.path&&n.write(`Wrote ${a.path}
|
|
561
|
+
`),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 ${Si} on macOS/Linux or ${Ei} 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(!Ii(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"&&Kd("windows",i);let l=s1(a),d;if(a.target==="claude")d=a.artifact==="reg"?LI(l,i):a.artifact==="json"?QG(l,i):PI(l,i);else{let u=r1(l,i);d=a.artifact==="mobileconfig"?o1(u):u}return await _I(d,a.path,t),i1(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
|
|
562
562
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
563
|
-
`),1}};var
|
|
563
|
+
`),1}};var d1=`anyray-connect retrieve <handle> [--source auto|claude|profile]
|
|
564
564
|
|
|
565
565
|
Print the original content Anyray externalized behind a "\xB7 retrieve ctx_\u2026"
|
|
566
566
|
marker. The content is written to stdout byte-for-byte (no trailing newline
|
|
@@ -570,7 +570,7 @@ Options:
|
|
|
570
570
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
571
571
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
572
572
|
--help Show this help.
|
|
573
|
-
`,
|
|
573
|
+
`,u1=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
|
|
574
574
|
|
|
575
575
|
Semantic search over your externalized tool outputs. Prints one match per line
|
|
576
576
|
to stdout as: handle<TAB>score<TAB>preview. Fetch a full original with
|
|
@@ -581,36 +581,36 @@ Options:
|
|
|
581
581
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
582
582
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
583
583
|
--help Show this help.
|
|
584
|
-
|
|
584
|
+
`,BI=(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},p1=e=>e.replace(/[\t\r\n]+/g," ").trim(),FI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=BI(e,!1);if(o.help)return n.write(d1),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
|
|
585
585
|
`),1;let s=await(t.readTarget??tt)(o.source),i=await(t.retrieve??Pa)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
|
|
586
586
|
`),1)}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
587
|
-
`),1}},
|
|
587
|
+
`),1}},WI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=BI(e,!0);if(o.help)return n.write(u1),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
|
|
588
588
|
`),1;let s=await(t.readTarget??tt)(o.source),i=await(t.recall??Rd)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
|
|
589
589
|
`),1;if(i.matches.length===0)return r.write(`No matching externalized outputs found.
|
|
590
|
-
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${
|
|
590
|
+
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${p1(c.preview)}
|
|
591
591
|
`)}return r.write(`Fetch a full original: anyray-connect retrieve <handle>
|
|
592
592
|
`),0}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
593
|
-
`),1}};import{promises as
|
|
593
|
+
`),1}};import{promises as B1}from"node:fs";var Sn=e=>typeof e=="string"?e:"",f1=e=>{let t=Sn(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=Sn(o.text).trim();a&&r.push(a)}return r.join(`
|
|
594
594
|
|
|
595
|
-
`).trim()},
|
|
595
|
+
`).trim()},m1=e=>{let t=Sn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},h1=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=f1(r);if(!o)continue;let a=Sn(r.created_at).trim();t.push({role:m1(r),text:o,...a?{createdAt:a}:{}})}return t},Jd=e=>{let t;try{t=JSON.parse(e)}catch{return{ok:!1,conversations:[],skipped:0,message:"the file is not valid JSON"}}let n=Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.conversations)?t.conversations:null;if(!n)return{ok:!1,conversations:[],skipped:0,message:"expected a list of conversations \u2014 is this the conversations.json from a Claude data export?"};let r=[],o=0;for(let a of n){if(!a||typeof a!="object"){o+=1;continue}let s=a,i=h1(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(Sn(s.uuid)||Sn(s.id)).trim(),l=(Sn(s.name)||Sn(s.title)).trim()||"Untitled conversation",d=Sn(s.created_at).trim(),u=Sn(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 P1}from"node:crypto";import{promises as _i}from"node:fs";import{homedir as ZI}from"node:os";import{join as zd}from"node:path";import{promises as UI}from"node:fs";import oy from"node:path";var y1=4e4,g1=16*1024*1024,Oi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Ti=async(e,t={})=>{let n=(e??"").trim();if(!n)return Oi("","path is required");let r=t.cwd??process.cwd(),o=oy.resolve(r,n),a=oy.relative(r,o);if(a.startsWith("..")||oy.isAbsolute(a))return Oi(n,"path is outside the workspace");let s=t.maxBytes??y1,i;try{let g=await UI.stat(o);if(!g.isFile())return Oi(n,"not a regular file");let y=t.maxFileBytes??g1;if(g.size>y)return Oi(n,`file too large to read (${g.size} bytes; limit ${y})`);i=await UI.readFile(o,"utf8")}catch(g){return Oi(n,g instanceof Error?g.message:"read failed")}let c=i.split(`
|
|
596
596
|
`),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(`
|
|
597
|
-
`),p=l<=d?d:l,m=!1,
|
|
598
|
-
`),p=l+
|
|
597
|
+
`),p=l<=d?d:l,m=!1,h=!1;if(Buffer.byteLength(f,"utf8")>s){let g=0,y=0;for(let w of u){let b=Buffer.byteLength(w,"utf8")+(y===0?0:1);if(g+b>s)break;g+=b,y+=1}y===0?(f=Buffer.from(u[0]??"","utf8").subarray(0,s).toString("utf8").replace(/\uFFFD$/,""),p=l,m=!0):(f=u.slice(0,y).join(`
|
|
598
|
+
`),p=l+y-1),h=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:h,span:{startLine:l,endLine:p,...m?{partialLine:!0}:{}}}},ay=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
|
|
599
599
|
${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}
|
|
600
|
-
${e.content}`};import{spawn as
|
|
601
|
-
`)){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:
|
|
602
|
-
`);for(let C=0;C<k.length;C+=1){let S=c(k[C]);if(l.some(E=>S.includes(E))&&(u.push({file:
|
|
600
|
+
${e.content}`};import{spawn as w1}from"node:child_process";import{promises as sy}from"node:fs";import iy from"node:path";var cy=400,b1=240,A1=4e3,C1=4e3,k1=512*1024,v1=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),GI=(e,t)=>e.length>t?e.slice(0,t):e,S1=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"]),E1=8,I1=2e3,x1=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],R1=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")},VI=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!S1.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=E1))break}return n},KI=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},O1=(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)},HI=(e,t,n)=>{let r=[];for(let o of e.split(`
|
|
601
|
+
`)){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:GI(l,t)})}return r},T1=(e,t,n,r,o,a,s)=>new Promise(i=>{let c=["--line-number","--no-heading","--color","never","--max-columns",String(o),"--max-columns-preview","--smart-case","--max-count","20","--fixed-strings"];for(let m of n)c.push("-g",m);for(let m of x1)c.push("-g",m);if(s?.length){for(let m of s)c.push("-e",m);c.push("--",".")}else c.push("--",e,".");let l;try{l=w1("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,f=m=>{u||(u=!0,clearTimeout(p),i(m))},p=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let m=HI(d,o,r);f({ok:!0,matches:m,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",m=>{if(d+=m,d.length>r*(o+64))try{l.kill("SIGKILL")}catch{}}),l.on("error",()=>{f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"})}),l.on("close",m=>{if(typeof m=="number"&&m>=2){f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let h=HI(d,o,r+1),g=h.length>r;f({ok:!0,matches:g?h.slice(0,r):h,truncated:g,engine:"ripgrep"})})}),_1=async(e,t,n,r,o,a,s)=>{let i=KI(s?.length?s:e),c=h=>i?h:h.toLowerCase(),l=(s?.length?s:[e]).map(c),d=n.map(h=>h.replace(/^\*+/,"")).filter(h=>h.startsWith(".")),u=[],f=0,p=!1,m=async h=>{if(u.length>=r||Date.now()>a){p=!0;return}let g;try{g=await sy.readdir(h,{withFileTypes:!0})}catch{return}for(let y of g){if(u.length>=r||Date.now()>a){p=!0;return}let w=iy.join(h,y.name);if(y.isDirectory()){if(v1.has(y.name))continue;await m(w)}else if(y.isFile()){if(f>=C1){p=!0;return}if(d.length&&!d.some(C=>y.name.endsWith(C))||R1(iy.relative(t,w)))continue;f+=1;let b;try{if((await sy.stat(w)).size>k1)continue;b=await sy.readFile(w,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let k=b.split(`
|
|
602
|
+
`);for(let C=0;C<k.length;C+=1){let S=c(k[C]);if(l.some(E=>S.includes(E))&&(u.push({file:iy.relative(t,w),line:C+1,text:GI(k[C],o)}),u.length>=r)){p=!0;return}}}}};return await m(t),{ok:!0,matches:u,truncated:p,engine:"walk"}},Xd=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??cy,s=t.maxColumns??b1,i=t.timeoutMs??A1,c=Date.now()+i,l=VI(n),d=l.length>1,u=Math.min(a*4,I1),f=(y,w)=>_1(n,r,o,y,s,c,w),p=async y=>{let w=await y(u,l);if(!w.ok)return w;let b=O1(w.matches,l,KI(l)),k=b.length>a;return{...w,matches:k?b.slice(0,a):b,truncated:w.truncated||k,matched:"tokens",tokens:l}};if(t.engine==="walk"){let y=await f(a);return y.matches.length>0||!d?y:p((w,b)=>f(w,b))}let m=(y,w)=>T1(n,r,o,y,s,Math.max(0,c-Date.now()),w),h=await m(a);if(h.ok){if(h.matches.length>0||!d)return h;let y=await p((w,b)=>m(w,b));return y.ok?y:p((w,b)=>f(w,b))}let g=await f(a);return g.matches.length>0||!d?g:p((y,w)=>f(y,w))},jI=(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=VI(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.
|
|
603
603
|
`:"";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(`
|
|
604
604
|
`)}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(`
|
|
605
605
|
`):[o,...a.slice(0,Math.max(1,l)),s(a.length-Math.max(1,l))].join(`
|
|
606
|
-
`)};var
|
|
606
|
+
`)};var YI=448,D1=384,L1=4e4,Pr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=zd(ZI(),".anyray");try{if((await _i.stat(t)).isDirectory())return zd(t,"history")}catch{}return zd(ZI(),".anyray-history")},N1=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:$1(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},$1=e=>{let t=P1("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)},M1=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}
|
|
607
607
|
|
|
608
608
|
${r.text}
|
|
609
609
|
`});return[...t,...n].join(`
|
|
610
610
|
`).replace(/\n{3,}/g,`
|
|
611
611
|
|
|
612
612
|
`)+`
|
|
613
|
-
`},qd=async e=>{let t=await Pr();await _i.mkdir(t,{recursive:!0,mode:
|
|
613
|
+
`},qd=async e=>{let t=await Pr();await _i.mkdir(t,{recursive:!0,mode:YI});try{await _i.chmod(t,YI)}catch{}let n=0,r=0;for(let o of e)try{await _i.writeFile(zd(t,N1(o)),M1(o),{mode:D1}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Ba=async()=>{try{let e=await Pr();return(await _i.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},JI=async e=>{let t=await Pr();return Xd(e,{cwd:t,globs:["*.md"]})},XI=async e=>{let t=await Pr();return Ti(e,{cwd:t,maxBytes:L1})};var zI=`anyray-connect history <command>
|
|
614
614
|
|
|
615
615
|
Make past Claude conversations searchable from any Anyray-connected client.
|
|
616
616
|
|
|
@@ -631,7 +631,7 @@ Which one you want:
|
|
|
631
631
|
conversation into the chat when you ask for it. Recall, not a list.
|
|
632
632
|
|
|
633
633
|
Running both is fine, and gets you both.
|
|
634
|
-
`,
|
|
634
|
+
`,F1=async e=>{try{return{raw:await B1.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"})`}}},W1=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return R("Usage: anyray-connect history import <conversations.json>"),A(v("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await F1(t);if("error"in n)return R(n.error),1;let r=Jd(n.raw);if(!r.ok)return R(`Could not read that export: ${r.message??"unrecognized format"}`),A(v("Expected the conversations.json from a Claude data export (claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data).")),1;if(r.conversations.length===0)return R("That export contains no conversations with readable messages."),1;let o;try{o=await qd(r.conversations)}catch(a){let s=a?.code;return R(`Could not create the history archive (${s??"write failed"}).`),A(v("Check that ~/.anyray is a writable directory, then try again.")),1}return B(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&A(v(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&_(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),A(""),A(j("Your history is now searchable from any Anyray-connected client.")),A(v(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),A(v(" and the assistant can search this archive and pull it up.")),A(v(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),A(v(" for them, they do not reappear as a clickable list in the app.")),0},U1=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return R("Usage: anyray-connect history restore <export.zip>"),A(v("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await jl(t);return n.ok?(B(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&A(v(` ${n.skipped} already present, left untouched.`)),n.failed>0&&_(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),A(""),A(j("Open Claude Desktop \u2014 they are in the sidebar again.")),A(v(" Anyray stays configured; this changed nothing about your routing.")),A(v(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),A(v(" undocumented. A future Desktop release could stop reading it \u2014 your export")),A(v(" file still works, and `history import` remains a second copy.")),0):(R(`Could not restore into Claude Desktop: ${n.reason}`),A(v(` ${n.remedy}`)),1)},H1=async()=>{let e=await Pr(),t=await Ba();return t===0?(A(`No conversations imported yet. Archive would live at ${e}`),A(v(" Import one with: anyray-connect history import <conversations.json>")),0):(B(`${t} conversation${t===1?"":"s"} in ${e}`),0)},qI=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(zI),0):t==="import"?W1(e.slice(1)):t==="restore"?U1(e.slice(1)):t==="status"?H1():(R(`Unknown history command: ${t}`),console.log(zI),1)};import{promises as G1}from"node:fs";var V1=`anyray-connect migrate [options]
|
|
635
635
|
|
|
636
636
|
Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
|
|
637
637
|
|
|
@@ -660,57 +660,57 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
|
|
|
660
660
|
Open claude.ai -> Settings -> Privacy -> Export data. Anthropic emails a link.
|
|
661
661
|
Pass the .zip to --export, and the conversations.json inside it to
|
|
662
662
|
--conversations. Both are safe to re-run; they skip what is already there.
|
|
663
|
-
`,
|
|
664
|
-
`).filter(Boolean))A(` ${s}`);return!1}for(let s of n.lanes)A(` ${
|
|
663
|
+
`,K1=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},QI={code:"Claude Code sessions",cowork:"Cowork tasks"},j1=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`${QI[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},Z1=async(e,t)=>{A(j("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??po)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){R(` ${n.reason}`);for(let s of n.remedy.split(`
|
|
664
|
+
`).filter(Boolean))A(` ${s}`);return!1}for(let s of n.lanes)A(` ${j1(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";A(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&_(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&_(` Claude Desktop has more than one target ${r.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run this again.`);let o=n.retryableAssets??[];o.length>0&&_(` ${o.length} portable configuration ${o.length===1?"type needs":"types need"} another local-copy attempt; no existing target entry was replaced.`);for(let s of n.blocked??[])_(` ${QI[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),A(` ${Bm(s.reason,s.lane,"anyray-connect migrate")}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&A(v(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},Y1=async(e,t)=>{if(A(""),A(j("2. Your claude.ai chats")),t){A(v(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){A(" These live on your Claude account, not this machine, so they need"),A(" an export. Anyray cannot fetch them: the only credential that could"),A(" is your claude.ai session, which Connect never holds."),A(v(" claude.ai -> Settings -> Privacy -> Export data, then:")),A(v(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await jl(e.exportZip);if(!n.ok){R(` ${n.reason}`),A(` ${n.remedy}`);return}B(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),A(v(" They are listed under Cowork \u2014 the Chat tab has no local store."));let r=n.projects;if(r.imported+r.alreadyPresent+r.skippedCollision+r.failed>0){let a=[r.alreadyPresent>0?`${r.alreadyPresent} already there`:"",r.skippedCollision>0?`${r.skippedCollision} skipped, a folder of that name already exists`:"",r.failed>0?`${r.failed} failed`:""].filter(Boolean);B(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&A(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},J1=async e=>{if(A(""),A(j("3. Searchable from every Anyray client")),!e.conversations){let o=await Ba();o>0?A(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(A(v(" Optional. Pass the conversations.json inside the export:")),A(v(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await G1.readFile(e.conversations,"utf8")}catch{R(` could not read ${e.conversations}`);return}let n=Jd(t);if(!n.ok){R(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await qd(n.conversations);B(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),A(v(` Ask any Anyray-connected client about a past chat. ${await Pr()}`))},X1=e=>{A(""),A(j("Next")),A(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||_(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),A(v(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},ex=async(e,t={})=>{let n;try{n=K1(e)}catch(o){return R(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(V1),0;A(j("Migrating Claude Desktop onto Anyray")),A(v("Claude Desktop must be fully quit.")),A("");let r=await Z1(n,t);return await Y1(n,!r),await J1(n),r?(X1(n),0):(A(""),_("Fix the item above and re-run to finish the migration."),1)};var z1=3e3,Qd=async(e,t={})=>{let n=t.timeoutMs??z1,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`:pt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};import{execFileSync as rx}from"node:child_process";import{lstatSync as q1,readFileSync as Q1}from"node:fs";import eV from"node:os";var ox="ai.anyray.connect",uy="EnrollmentEmail",py="EnrollmentUrl",tV="HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Anyray\\Connect",tx="/etc/anyray/anyray-enroll.json",nV=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,rV=254,oV=2048,aV=64*1024,sV=e=>e.isFile()&&e.uid===0&&(e.mode&63)===0&&e.size<=aV,iV=()=>`/Library/Managed Preferences/${ox}.plist`,cV=e=>`/Library/Managed Preferences/${e}/${ox}.plist`;var ly=e=>{try{let t=JSON.parse(e);return{...typeof t[uy]=="string"?{email:t[uy]}:{},...typeof t[py]=="string"?{enrollmentUrl:t[py]}:{}}}catch{return{}}},nx=(e,t)=>{for(let n of e.split(/\r?\n/u)){let r=/^\s*(\S+)\s+REG_SZ\s+([^\r\n]+)$/u.exec(n);if(r?.[1]===t)return r[2]?.trim()||void 0}},ax=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(!t||t.length>rV))return nV.test(t)?t:void 0},lV=e=>{if(!e)return;let t=e.trim();if(!(!t||t.length>oV))try{let n=new URL(t);return n.protocol==="https:"&&n.username===""&&n.password===""&&n.search===""&&n.hash===""&&/^\/enroll\/enp_[A-Za-z0-9_-]{43}$/.test(n.pathname)?n.toString():void 0}catch{return}},dV=e=>{try{return rx("plutil",["-convert","json","-o","-",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},uV=()=>{try{return eV.userInfo().username||void 0}catch{return}},pV=()=>{try{return rx("reg",["query",tV],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},fV=()=>{try{let e=q1(tx);return sV(e)?Q1(tx,"utf8"):void 0}catch{return}},sx={platform:process.platform,readMacPlistJson:dV,username:uV,readWindowsRegQuery:pV,readLinuxJson:fV},dy=(e,t)=>{let n=e.map(ax).find(o=>o!==void 0),r=lV(t);return{...n?{email:n}:{},...r?{enrollmentUrl:r}:{}}},fy=(e=sx)=>{try{if(e.platform==="darwin"){let t=e.username(),n=t?ly(e.readMacPlistJson(cV(t))??""):{},r=ly(e.readMacPlistJson(iV())??"");return dy([n.email,r.email],r.enrollmentUrl)}if(e.platform==="win32"){let t=e.readWindowsRegQuery();return t?dy([nx(t,uy)],nx(t,py)):{}}if(e.platform==="linux"){let t=ly(e.readLinuxJson?.()??"");return dy([t.email],t.enrollmentUrl)}return{}}catch{return{}}},ix=(e,t)=>{if(!e?.length)return;let n=t?.trim().split(/[\\/]/).at(-1)?.toLowerCase();if(n)return ax(`${n}@${e[0]}`)},cx=(e=sx)=>fy(e).email;import{spawn as mV}from"node:child_process";import{platform as hV}from"node:os";var Fa=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=hV(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=mV(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var lx=()=>Gh(),dx=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??lx)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},yV=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},ux=async(e,t={})=>{let n=(t.openInput??lx)(),r=n.stream,o=t.output??process.stderr;if(typeof r.setRawMode!="function")throw n.close(),new Error("raw terminal input is unavailable");let a=e.items.map(m=>m.selected===!0&&m.requiresExplicitChoice!==!0),s=0,i=0,c=Sa(o,t.env??process.env),l=(m,h)=>c?`\x1B[${m}m${h}\x1B[0m`:h,d=()=>{let m=[l("1",e.title)];for(let h=0;h<e.items.length;h++){let g=e.items[h],y=h===s?l("36","\u276F"):" ",w=e.single?a[h]?"(\u25CF)":"(\u25CB)":a[h]?"[x]":"[ ]",b=g.hint?` ${l("2",g.hint)}`:"";m.push(`${y} ${w} ${g.label}${b}`)}m.push(l("2",e.single?"\u2191/\u2193 move \xB7 space choose \xB7 enter accept \xB7 q cancel":"\u2191/\u2193 move \xB7 space toggle \xB7 a toggle all \xB7 enter accept \xB7 q cancel")),i>0&&o.write(`\x1B[${i}A`),o.write(m.map(h=>`\r\x1B[2K${h}`).join(`
|
|
665
665
|
`)),o.write(`
|
|
666
666
|
`),i=m.length},u=()=>{i!==0&&(o.write(`\x1B[${i}A`),o.write(Array.from({length:i},()=>`\r\x1B[2K
|
|
667
|
-
`).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((m,
|
|
668
|
-
`)&&
|
|
669
|
-
`){
|
|
670
|
-
`),t();let a=0,s=()=>{r.write(`\r${
|
|
671
|
-
`)){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()}},RV=e=>e.mode==="off"?{allow:!1,outcome:"fleet-off"}:e.mode==="directed"&&e.initiator==="tick"?{allow:!1,outcome:"fleet-directed"}:{allow:!0},OV=e=>e==="auto",mx=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&&Ua(e.current,e.minVersion)<0&&Ua(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},TV=e=>Ua(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}:{...mx(e),downgradeBlocked:!1},_V=(e=process.execPath)=>{let t=Yu(e);return t?en(t):en(en(e))},PV=async(e=dt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=cr(_V(e.execPath)).launcher;try{if(await ru(t)!==await ru(e.execPath))return}catch{return}return t},wy=async(e=dt(),t=Q())=>{let n=await PV(e);if(n)return{kind:"managed",root:en(en(n)),link:n,entryPath:Xn(e)};let r=Xn(e);return Xu(r,t)?{kind:"durable",root:t,entryPath:r}:ju(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},au=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)}},by=async(e=Ni)=>{let t=await au(`${ir}/latest`,e,{redirect:"manual"});return xV(t.headers.get("location"))},DV=async e=>{try{let t=await au(`${e}/connect-update.json`,Ni);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}},Li=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},Ay=async(e,t,n)=>{let r=await au(e,SV);if(!r.ok||!r.body)throw new Li(r.status);let o=bV("sha256"),a=0;if(await CV(AV.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>vV)throw new Error("asset exceeds size cap");o.update(c),yield c}},yV(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},LV=e=>tu(e)===Zr()?tu(en(e)):tu(e),NV=async e=>{let t=await ou(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await xt(Wa(e,n),{force:!0}).catch(()=>{})},hx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await xt(r,{force:!0}).catch(()=>{});let o=!1;try{await eu(e,r),o=!0}catch{}try{await my(t,e),await wV(is(e),LV(t))}catch(a){throw o&&await eu(r,e).catch(()=>{}),a}await xt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await xt(n,{force:!0}),await gV(t,n),await eu(n,e)},Cy=(e,t)=>e===t||tu(e)===wp?448:493,Di=async(e,t)=>{let n=(await fx(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await px(e,n&4095|t).catch(()=>{})},nu=async(e,t)=>{await yy(e,{recursive:!0,mode:t}),await Di(e,t)},$V=async(e,t,n)=>{let r=Cy(e,Q());if(r!==448){let o=cr(e),a=o.versionsDir;await Di(e,r),await Di(en(o.launcher),r),await Di(a,r);for(let s of await ou(a).catch(()=>[]))await Di(Wa(a,s),r)}await(n.refreshDesktopHelpers??jd)(t)},MV=async(e,t={})=>{let n=cr(e.root),r=en(n.launcher),{versionsDir:o,launcher:a}=n,s=Cy(e.root,(t.privateRoot??Q)());await nu(r,s),await nu(o,s);let i=Wa(o,e.version),l=(await hy(i).catch(()=>{}))?.isFile()?i:Wa(i,Zr());if(!(await hy(l).catch(()=>{}))?.isFile()){let u=await(t.fetchResponse??au)(`${e.tagUrl}/SHA256SUMS`,Ni),f=u.ok?gy(await u.text(),e.asset):void 0;if(!f)throw new Error("no published checksum");await nu(en(l),s),await NV(en(l));let p=`${l}.part-${process.pid}`;try{await(t.download??Ay)(`${e.tagUrl}/${e.asset}`,p,f),await px(p,493),await eu(p,l)}catch(m){throw await xt(p,{force:!0}).catch(()=>{}),m}}return await(t.activate??hx)(a,l),{link:a,target:l,versionsDir:o}},BV=async e=>{ux(e.target,[jr,e.link],{stdio:"ignore",timeout:Ni})},FV=async e=>{if(process.platform==="darwin"){let t=ux("/usr/bin/codesign",["--verify","--strict",e],{stdio:"ignore",timeout:Ni});return!t.error&&t.status===0}return!0},WV=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??Ao)(n);if(r.length>0){let o=await(t.resolveTarget??We)(async()=>e);if(!o||!(await(t.repair??Ft)(r,o.target)).every(bo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??ar)()).ok)},UV=async e=>{let t=await e.install();if(!await(e.smoke??FV)(t.target))throw await e.rollback?.(t),new Error("managed binary smoke test failed");if(!await e.repoint(t.link))throw new Error("persistent config repoint failed");return await e.prune(),t},HV=async(e,t)=>{let n=await ou(e).catch(()=>[]);for(let r of n)t.includes(r)||await xt(Wa(e,r),{force:!0,recursive:!0}).catch(()=>{})},GV=async e=>{let t=await ou(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await xt(Wa(e,n),{force:!0}).catch(()=>{})},VV=async(e,t)=>{let n=async()=>{await xt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await yy(e,{recursive:!1}),n}catch{}let r=await fx(e).catch(()=>{});if(!(!r||t-r.mtimeMs<IV)){await n();try{return await yy(e,{recursive:!1}),n}catch{return}}},fy=e=>cr(e).state,KV=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}},Ha=async(e={})=>{let t=e.now??Date.now,n=ke;if(Rn(on(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??dt(),o=e.root??Q(),a;try{let s=await wy(r,o);if(o=s.root,s.kind==="unmanaged")return{outcome:"unmanaged",current:n};if(s.kind==="npm"&&!e.allowNpmMigration)return{outcome:"unmanaged",current:n};let i=s.kind!=="managed",c=e.force===!0,l=await(e.load??P)().catch(()=>({})),d=l.autoUpdate!==!1,u=l.fleetUpdatePolicy?.mode??"auto",f=RV({mode:u,initiator:e.initiator??"tick"});if(!f.allow)return{outcome:f.outcome,current:n};!i&&s.link&&!e.checkOnly&&(d||c)&&await $V(o,s.link,e).catch(()=>{});let p=ys(e.platform??process.platform,e.arch??process.arch);if(!p)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??by)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let m=a;if(!i&&m===n)return{outcome:"current",current:n,latest:m};if(i&&Ua(m,n)<0)return{outcome:"migration-deferred",current:n,latest:m};let y=await KV(fy(o));if((e.respectFailureBackoff===!0||!c)&&y.failedVersion===m&&y.failedAt!==void 0&&t()-y.failedAt<EV)return{outcome:"failed",current:n,latest:m};let g=`${ir}/download/${Kr}${m}`,h=d||c||!OV(u)?void 0:await(e.minimumVersion??DV)(g),w={current:n,latest:m,autoUpdate:d,forced:c,minVersion:h},b=i?TV(w):{...mx(w),downgradeBlocked:!1};if(b.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:m};if(!b.apply)return{outcome:"disabled",current:n,latest:m};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:m,mandatory:b.mandatory};o===Q()?await Qe():await nu(o,Cy(o,Q()));let k=cr(o),C=await VV(k.lock,t());if(!C)return{outcome:i?"migration-available":"available",current:n,latest:m};let S,E;try{await GV(en(k.launcher));let I=await ru(k.versionsDir).catch(()=>{}),O=await ru(k.launcher).catch(()=>{}),T=O&&oc(O,I)?O:void 0,U=k.launcher;i&&process.platform==="win32"&&(await hy(U).catch(()=>{}))?.isFile()&&(E=`${U}.rollback-${process.pid}`,await my(U,E));let z=()=>(e.installBinary??MV)({root:o,version:m,asset:p,tagUrl:g});i?S=await UV({install:z,smoke:e.smoke,rollback:async({link:K,target:oe})=>{E?(await my(E,K),await xt(is(K),{force:!0}).catch(()=>{})):T&&T!==oe?await hx(K,T):(await xt(K,{force:!0}),await xt(is(K),{force:!0}).catch(()=>{}))},repoint:async K=>e.repoint?e.repoint(l,K):WV(l),prune:async()=>{await(e.pruneDurable??(K=>ac(K)))(r)}}):S=await z(),await HV(S.versionsDir,[m,n]),await(e.refreshHelpersFromInstalled??BV)(S).catch(()=>{}),await xt(fy(o),{force:!0}).catch(()=>{})}finally{E&&await xt(E,{force:!0}).catch(()=>{}),await C()}return{outcome:i?"migrated":"updated",current:n,latest:m,managedPath:S.link,mandatory:b.mandatory}}catch{return a&&await J(fy(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},yx=async(e={})=>{let t=e.context??dt(),n=await wy(t,e.root??Q()),r=$o(e.root??Q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:ke,managedPath:n.link??r}:Ha({initiator:"human",...e,context:t,allowNpmMigration:!0})},Io=async(e={})=>{let t=e.context??dt(),n=e.root??Q(),r=await wy(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&&!!ys(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=Rn(on(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:ke,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l,fleetMode:a.fleetUpdatePolicy?.mode??"auto"}};import{z as gx}from"zod";var jV=5e3,ZV=gx.object({lane:gx.enum(["subscription","org"]).optional().catch(void 0)}),wx=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??jV);try{let a=await(n.fetchResponse??fetch)(`${e.replace(/\/$/,"")}/connect/policy`,{headers:{"x-anyray-api-key":t.trim()},signal:r.signal});if(!a.ok)return;let s=ZV.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},bx=(e,t)=>{if(!e||t.byoUpstream)return{overrodeFlag:!1};let n=t.subscription?"subscription":t.org?"org":void 0;return{lane:e,overrodeFlag:n!=null&&n!==e}};var YV=12e3,JV="anyray-wiring-probe-not-a-real-token",XV={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},vy={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},xo=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},Cx=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},Sy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},Ax=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."],zV=e=>e.includes("no provider key configured for"),Ey=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},Iy=e=>({kind:"enrollment-required",detail:`gateway requires per-developer enrollment (HTTP ${e}).`,remedy:["This gateway only serves enrolled developers. Re-run with your enrollment","link from your admin so connect can mint your personal key automatically:"," anyray-connect --enroll <link>"]}),$i=e=>({kind:"key-rejected",detail:`gateway rejected the client key (HTTP ${e}).`,remedy:["The gateway did not receive a usable personal key (missing, unknown, expired,","or revoked). Re-run `anyray-connect` to refresh an existing enrollment, or","use `--enroll` / `--sso` to enroll first."]}),qV=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:zV(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${xo(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")?Ax([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:e===401||e===403?Ey(t)?Iy(e):Sy(t)?$i(e):Cx(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${xo(t)}`,remedy:["The org provider rejected the request \u2014 check the gateway\u2019s provider","key/config (e.g. the model is enabled for that account)."]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${xo(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).",...Ax([" \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}: ${xo(t)}`,remedy:[]},QV=(e,t)=>{if(Sy(t))return $i(e);if(Ey(t))return Iy(e);if(Cx(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}: ${xo(t)}`,remedy:[]}},eK=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),tK=(e,t)=>{if(Sy(t))return $i(e);if(Ey(t))return Iy(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")||eK(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}: ${xo(t)}`,remedy:[`The probe asks for a fixed model (${vy.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."]}},ky=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)}},nK=async(e,t)=>{if(!e.clientKey)return $i(401);let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`${e.origin}/connect/savings`,{method:"GET",headers:{"x-anyray-api-key":e.clientKey},signal:n.signal}),a=await o.text();return o.ok?{kind:"ok",detail:"gateway accepted your personal key \u2014 Cursor hooks/MCP can report and retrieve.",remedy:[]}:o.status===401||o.status===403?$i(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${xo(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},rK=(e,t)=>{let n=typeof t?.code=="string"?` ${t.code}`:"";return{kind:"unreachable",detail:`could not reach the gateway to verify (${t instanceof Error&&t.name==="AbortError"?`no response within ${e}ms`:t instanceof Error?`${t.name}${n}`:"unknown error"}).`,remedy:["Your config was still written \u2014 re-run the curl below once the gateway is reachable."]}},Mi=async(e,t={})=>{let n=t.timeoutMs??YV,r=fe(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await nK(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 ky(`${e.anthropicBaseUrl}/v1/messages`,l,vy,n);return tK(d,u)}if(ee(e,"anthropic")){let l={Authorization:`Bearer ${JV}`,"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 ky(`${e.anthropicBaseUrl}/v1/messages`,l,vy,n);return QV(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await ky(`${e.openaiBaseUrl}/chat/completions`,s,XV,n);return qV(i,c,t.tools??[])}catch(o){return rK(n,o)}};var kx=async e=>{let t=await P(),n;try{n=Tr(e.gateway,t)}catch(o){return A(j("Anyray connect \u2014 status")),N(`Gateway: ${o.message}`),0}A(j("Anyray connect \u2014 status")),H("Gateway"),A(` Origin: ${ze(n)}`),t.gateway?N(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?N(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||N(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),H("Identity"),A(` Name: ${t.name??v("(not set)")}`),A(` Team: ${t.team??v("(not set)")}`);let r=on();r&&(H("Environment"),A(` Remote dev context: ${Fo(r)}`),Rn(r)&&N(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),N(" VS Code tools configure the remote server variant backing this window.")),t.enrolledCert&&t.clientKey&&(H("Credential renewal"),B(" Direct gateway routing with a proof-backed key heartbeat."),N(" Renewal extends the same key; tool configuration is not rewritten.")),H("Tools");for(let o of pe){if(!(await o.detect()).installed){N(` ${o.title}: not installed`);continue}if(!o.pointsAt){N(` ${o.title}: installed ${v("(status not introspectable)")}`);continue}let s=await o.pointsAt(n);if(s){if(o.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){B(` ${o.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}B(` ${o.title}: pointed at Anyray`)}else{let i=null,c=null;if(o.id===$a&&o.mcpStatus)try{let l=(await o.mcpStatus()).registered,d=await Fd();i=Wd({id:o.id,installed:!0,pointedAt:s,mcpRegistered:l,introspectable:d.authoritative}),c={...d.authoritative?{}:{reason:d.reason},mcpRegistered:l}}catch{i=null,c=null}if((i==="not-routed"||i==="unverifiable")&&c){let l=Ud(i,c);_(` ${o.title}: ${l.headline}`);for(let d of l.detail)A(v(` ${d}`))}else N(` ${o.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as IK}from"node:fs";import{isAbsolute as xK}from"node:path";import{homedir as RK}from"node:os";import{readFile as oK,stat as aK}from"node:fs/promises";import{homedir as sK,platform as iK}from"node:os";var cK=e=>e.replace(/\\(\d{3})/g,(t,n)=>String.fromCharCode(parseInt(n,8))),lK=e=>e.split(`
|
|
672
|
-
`).map(t=>t.split(" ")[4]).filter(t=>!!t).map(
|
|
673
|
-
`)){let o=new RegExp(`${kK}=(\\w*)`).exec(r);if(!o)continue;let a=r.replace(/\bVSCODE_[A-Z0-9_]*=\S*/g,"");if(/Code Helper|MacOS\/Code|VSCodium|Visual Studio Code|agentHost/i.test(a)&&(n=!0,o[1]==="true"))return"on"}return n?"off":"unknown"},EK=e=>e.mode!=="copilot-seat"?"not-applicable":e.settings.readable?e.settings.supportsAnyray!==!0||e.settings.bridgeEnabled!==!0?"not-configured":e.bridge==="off"?"awaiting-relaunch":"ready":"unknown",iu=(e,t)=>{switch(e){case"ready":return t==="on"?"Agents window: Anyray models available (agent host is running with the model bridge on).":"Agents window: configured. No running agent host was found to confirm it, so it applies from the next VS Code start.";case"awaiting-relaunch":return"Agents window: configured, but the agent host running right now started before it. Quit and relaunch VS Code once; a window reload will not do it, because that process outlives every window.";case"not-configured":return`Agents window: not enabled. Re-run anyray-connect --tools copilot, then quit and relaunch VS Code (it sets ${fn} and ${mn}; if you switched either off yourself, that choice is left alone).`;case"unknown":return"Agents window: could not read VS Code settings.json, so its state is unknown. Nothing is reported as missing on that basis.";case"not-applicable":return"Agents window: not applicable on this machine."}},Sx=async(e={})=>{let{installedVariant:t=Xo,receiptMode:n=sl,awaitingReload:r=al,readSettings:o=vK,probeBridge:a=SK,home:s=wK()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:iu("not-applicable","unknown")};let c=await n(i,s);if(c!=="copilot-seat"){let f=c===void 0&&await r(i,s);return{state:f?"unknown":"not-applicable",bridge:"unknown",detail:f?"Agents window: VS Code has an Anyray configuration staged but not applied yet, so its state is unknown. Restart VS Code to finish.":iu("not-applicable","unknown")}}let l=await o(Ds(i)),d=await a(),u=EK({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:iu(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:iu("not-applicable","unknown")}}};var tn="connect",cu=e=>e.replace(/-/g,"_"),Ex=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:tn,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:tn,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:tn,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:tn,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.removed&&e.serviceRemoval.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:tn,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:tn,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=cu(e.retrieval.kind);t.push({tool:tn,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":cu(e.verify.kind);t.push({tool:tn,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:tn,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:cu(e.hookLane.reason)}:{}})}t.push({tool:tn,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)if(i.installed){if(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp){let c=!i.mcp.registered&&!i.routingHeld;t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing",...c&&i.mcp.reason?{errorClass:cu(i.mcp.reason)}:{}})}a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"})}return t.push({tool:tn,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};var OK=e=>{let t=RK();return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e};function TK(){return ke}var _K="ctx_doctor-probe-synthetic",PK=(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: ${Oy(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 DK(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function LK(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Oy(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 Ix=e=>Wd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),xy=e=>e.pointedAt===!1&&e.tombstoned!==!0&&Ix(e)!=="unverifiable",xx=e=>e.registered&&e.command&&xK(e.command)?IK(e.command):null,NK=e=>{switch(e.mcp?.reason){case"ephemeral-runtime":return"this Connect is running from a temporary npx/cache path, so a registration naming it would rot \u2014 install it durably (`curl -fsSL https://app.anyray.ai/connect.sh | sh`) and re-run.";case"no-config":return`${e.title} has not written its config yet \u2014 launch it once, then re-run \`anyray-connect\`.`;case"stale":return"the entry was written by an older Connect \u2014 re-run `anyray-connect` to refresh it.";case"foreign":return"an MCP server named `anyray` that Connect did not write is already there, and it was left untouched. Rename or remove it, then re-run `anyray-connect`.";case"unreadable":return`${e.title}'s config could not be read or parsed \u2014 repair it (or check its permissions), then re-run \`anyray-connect\`.`;case"absent":return"re-run `anyray-connect` to register it.";default:return"re-run `anyray-connect` to register it."}},Ry=e=>(xy(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),$K=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,MK=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},Rx=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},BK=(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(ko),s=[],i=n(e.selfcheck?.adapters)?e.selfcheck.adapters:{};for(let[c,l]of Object.entries(i)){if(!o.has(c)||!n(l))continue;let d=n(l.lastRepaired)?l.lastRepaired:{},u=Object.entries(d).filter(g=>a.has(g[0])&&r(g[1])).map(([g,h])=>({checkId:g,at:h})),f=n(l.flapping)?l.flapping:void 0,p=Array.isArray(f?.checks)?f.checks.filter(g=>typeof g=="string"&&a.has(g)):[],m=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,y=f&&r(f.since)&&m&&p.length>0?{since:f.since,reason:m,checks:p}:void 0;(u.length>0||y)&&s.push({tool:c,repaired:u,...y?{flapping:y}:{}})}return s},FK=async(e,t,n,r,o,a,s=n,i=Mi,c=!0,l=Uo,d=Io,u=It,f=Da)=>{let p=c?await Qd(e):null,m=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=G=>G&&Wh(G)?"machine_default":null,g=t.enrolledCert?.payload,h=g?.expiresAt??t.enrolledCertExpiry??null,b=(await a())?.sso??null,k=LK({ssoLink:b,enrolledViaToken:!!t.enrolledTokenHash}),C=wt(),S=await Qw(C),E=S?[]:Bc(Oe({origin:e})),I=[];for(let G of r){let xe=await G.detect(),ht=null;if(xe.installed&&G.mcpStatus)try{let es=await G.mcpStatus();ht={...es,commandOk:xx(es)}}catch{}let yt=xe.installed&&G.id===$a?await o():void 0,De=xe.installed&&G.pointsAt?await G.pointsAt(e):null,qe=await $K(De,G,t.managedTools??[]),gt=De===!1&&qe===null,Xa=qe===!1&&G.routingPendingReload?await G.routingPendingReload().catch(()=>!1):!1,Ji=xe.installed?G.runtimeDiagnostics?await G.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:G.routingOverrides?await G.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:To,claudeCodeHookPolicy:za}=Ji,qa=t.fleetToolPolicy,Qa=qa?.enabled.includes(G.id)?qa.tiers?.[G.id]??xa:void 0;I.push({id:G.id,title:G.title,installed:xe.installed,...xe.detail?{detail:xe.detail}:{},pointedAt:qe,...gt?{routingHeld:!0}:{},...Xa?{routingPendingReload:!0}:{},...To.length?{routingOverrides:To}:{},...za===void 0?{}:{claudeCodeHookPolicy:za},mcp:ht,...Qa?{policyTier:Qa}:{},...t.revertedTools?.includes(G.id)?{tombstoned:!0}:{},...G.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...yt===void 0?{}:{inferenceIntrospectable:yt.authoritative,...yt.authoritative?{}:{inferenceUnverifiableReason:yt.reason}}})}let O=s?await(async()=>{let{kind:G,detail:xe,remedy:ht}=await i(Oe({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:G,detail:xe,remedy:ht}})():null,T=O?.kind==="provider-rejected"&&await MK(t.managedTools??[],r),U=O?{...O,...T?{notApplicableSubscription:!0}:{}}:null,z=n?PK(await Pa({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:fe({user:t.name,team:t.team})},_K,{probe:!0}),{mode:k,ssoLink:b}):null,K=await u().catch(()=>({})),oe=vn(K.hookLane),ae=s?await Rx(r):!1,Z=ae?await(async()=>{let G=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...Rh(G,{hookRegistered:ae,neverInvoked:Ih(oe,Date.now())}),lastInvokedAt:Id(oe)}})():null,ie=(await dr()).map(G=>({adapter:G.adapter,op:G.op,requestedAt:G.requestedAt,watcherAlive:pr(G.watcherPid)})),F=ie.find(G=>G.adapter==="cursor"),Y=F?{op:F.op,requestedAt:F.requestedAt,watcherAlive:F.watcherAlive}:null,te=!!t.refreshSchedulerEnabled,Ue=await Wo(),ve=await d(),ge=t.persistenceOwner==="tray",Ht=ge?await l(t)==="healthy":null,$=await Ww({schedulerEnabled:te&&!ge,schedulerInstalled:Ue,binaryDurable:!et(Bo()),schedulerInstalledOnce:t.refreshSchedulerInstalledOnce===!0,trayManaged:ge}),D=0;p&&!p.reachable&&(D+=1),ge?te&&!Ht&&(D+=1):te&&!Ue&&(D+=1);for(let G of I)D+=Ry(G);U&&U.kind!=="ok"&&!U.notApplicableSubscription&&(D+=1),z&&z.kind!=="ok"&&(D+=1),Z?.verdict==="dark"&&(D+=1),E.length>0&&(D+=1),D+=ie.filter(G=>!G.watcherAlive).length;let X=await Sx();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:TK(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:on(),fileBindMounts:await su(),selfUpdate:{managed:ve.managed,available:ve.available,autoUpdate:ve.autoUpdate,state:ve.state,fleetMode:ve.fleetMode}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},refreshScheduler:{enabled:te,installed:Ue,owner:ge?"tray":"os",...ge?{trayHealthy:!!Ht}:{}},serviceRemoval:$,fleetdPresent:await Ro(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:m,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:y(t.name)},enrollment:{enrolled:!!g,deploymentId:g?.deploymentId??null,issuedAt:g?.issuedAt??null,expiresAt:h,expired:h?Date.parse(h)<Date.now():null,orgMode:k,ssoLink:b},shell:{profilePath:C,blockPresent:S,staleExports:E},tools:I,...t.fleetToolPolicy?{fleetPlan:Sd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Y,pendingOps:ie,ambientRepairs:BK(K,r),verify:U,retrieval:z,hookLane:Z,agentsWindow:X,problems:D}},WK=e=>{if(e.serviceRemoval.suspected){if(!e.serviceRemoval.removed){H("Automatic key refresh"),_(" This seat expects the key-refresh schedule, but no unit is installed and"),_(" Anyray has no record of ever installing one here. Re-run `anyray-connect`"),_(" to install it.");for(let t of e.serviceRemoval.missingPaths)A(v(` expected: ${t}`));return}H("Endpoint security"),_(" Anyray installed these background services, but their files are gone from disk \u2014"),_(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),_(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)A(v(` missing: ${t}`));A(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),A(v(" tools straight at the gateway (your key then needs a periodic re-run).")),A(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),A(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},UK=e=>{if(A(j("Anyray connect \u2014 doctor")),e.connect.remoteContext||e.connect.fileBindMounts.length>0){H("Environment"),e.connect.remoteContext&&(A(` Remote dev context: ${Fo(e.connect.remoteContext)}`),Rn(e.connect.remoteContext)&&A(v(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule.")));for(let c of e.connect.fileBindMounts)A(` Bind-mounted config file: ${OK(c)}`),A(v(" A file mounted into this container cannot be replaced atomically; connect writes it in place (verified). Mount the parent directory instead to restore atomic writes."))}switch(H("CLI updates"),e.connect.selfUpdate.state){case"managed":B(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.fleetMode==="off"?A(v(" Your organization manages Connect updates; this machine downloads nothing.")):e.connect.selfUpdate.fleetMode==="directed"?A(v(" Your organization applies Connect updates centrally; an administrator pushes new versions.")):e.connect.selfUpdate.autoUpdate||_(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":_(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),A(v(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":_(" Self-update is unavailable on this platform because no standalone binary is published."),A(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":A(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":A(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(H("Gateway"),e.gateway.reachable===null?A(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?B(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(R(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),A(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(H("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(R(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),A(v(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?B(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(R(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||A(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),WK(e),H("Personal key"),DK(e)){case"env":B(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":B(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":_(" Enrolled, but no personal key is cached locally right now."),A(v(" Fix: re-run `anyray-connect` to re-mint it from your enrollment \u2014 no need to re-enroll. Claude Code and Codex are still attributed to you by name."));break;default:_(" Enrollment required \u2014 no personal gateway key is available."),A(v(` Fix: ${Oy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?_(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):B(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(H("Shell"),R(" This terminal still exports Anyray, but the config is gone."),A(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),A(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),A(v(" Anything you start from this terminal keeps reaching the gateway with")),A(v(" no credential, and fails with 401.")),A(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),A(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),A(v(" reuses the environment it captured at launch, so a new terminal")),A(v(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};H("Claude Code hook policy"),R(` ${uc(c)}.`),A(v(` ${pc(c)}`))}H("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])R(` ${c.title}: ${l.problem}.`),A(v(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(R(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),A(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):B(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(_(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(` Fix: ${NK(c)}`))))};for(let c of e.tools){if(!c.installed){A(v(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){A(v(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){B(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}B(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===$a&&A(v(` ${XC}`)),c.id==="codex"&&A(v(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=Ix(c);if(l==="not-routed"||l==="unverifiable"){let d=Ud(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});_(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(_(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?_(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):A(v(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(R(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),A(v(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(R(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),A(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(_(" No tools are pointed at this gateway yet."),A(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){H("Queued operations");for(let c of e.pendingOps){let l=ut(c.adapter)?.title??c.adapter;c.watcherAlive?_(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(R(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),A(v(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){H("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=ut(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:p,at:m})=>`${c(p)} ${new Date(m).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?_(f):A(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){H("Fleet policy");let c=l=>l.map(d=>ut(d)?.title??d).join(", ");i.freshIds.length>0&&A(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&_(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(H("Auth probe"),e.verify.notApplicableSubscription)B(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")B(` ${e.verify.detail}`);else{R(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)A(v(` ${c}`))}if(e.retrieval)if(H("Retrieval loop"),e.retrieval.kind==="ok")B(` ${e.retrieval.detail}`);else{R(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)A(v(` ${c}`))}if(e.hookLane){if(H("Hook lane"),e.hookLane.verdict==="live")B(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){R(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}else{_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}e.hookLane.lastInvokedAt!==null&&A(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(H("VS Code Agents window"),_(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(H("VS Code Agents window"),B(` ${e.agentsWindow.detail}`)),H("Summary"),e.problems===0?(e.verify?B(" No problems found."):B(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):R(` ${e.problems} problem(s) found \u2014 see fixes above.`)},HK=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}),GK=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!vh(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??Da,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Qt)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=vn((await(t.readRefreshState??It)().catch(()=>({}))).hookLane),l=Rh(i,{hookRegistered:await Rx(t.adapters??pe).catch(()=>!1),neverInvoked:Ih(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:Id(c)},note:d}},VK=async(e,t,n={})=>{let r=n.adapters??pe,o=n.resolveTarget??We,a=n.applyTools??Ft,s=await GK(e,n).catch(()=>null),i=s&&e.hookLane?.verdict==="dark"&&s.hookLane?.verdict==="live"?1:0,c=s?{hookLane:s.hookLane,notes:[s.note]}:{notes:[]},l=e.tools.filter(w=>w.installed&&(xy(w)||w.mcp?.commandOk===!1||w.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t);if(!d)return{entries:l.map(w=>({id:w.id,title:w.title,status:"skipped-not-enrolled"})),remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,`Repair needs an enrolled personal key \u2014 ${Oy(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],p=[...c.notes],m=[];for(let w of l){let b=r.find(k=>k.id===w.id);if(!u.has(w.id)||!b){f.push({id:w.id,title:w.title,status:"skipped-unmanaged"});continue}m.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 y=await a(m,d.target),g=new Map,h=0;for(let w of y){if(f.push(w),!bo(w))continue;let b=e.tools.find(T=>T.id===w.id);if(!b)continue;let k=r.find(T=>T.id===w.id),C=b.mcp;if(k?.mcpStatus)try{let T=await k.mcpStatus();C={...T,commandOk:xx(T)}}catch{}let S=xy(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{S=await k.pointsAt(e.gateway.origin)}catch{}let E=b.routingOverrides,I=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let T=await k.runtimeDiagnostics();E=T.routingOverrides.length?T.routingOverrides:void 0,I=T.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let T=await k.routingOverrides();E=T.length?T:void 0}catch{}let O={...b,pointedAt:S,mcp:C,...E?{routingOverrides:E}:{},...I===void 0?{}:{claudeCodeHookPolicy:I}};E||delete O.routingOverrides,I===void 0&&delete O.claudeCodeHookPolicy,g.set(w.id,O),h+=Ry(b)-Ry(O)}return{entries:f,remainingProblems:Math.max(0,e.problems-h-i),refreshedTools:g,...s?{hookLane:s.hookLane}:{},notes:p}},KK=e=>{H("Repair"),e.entries.length===0&&B(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?B(` ${t.title}: re-applied`):t.status==="queued"?B(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):R(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},lu=async(e,t={})=>{let n=await P();if(e.securityReview){if(!e.silent){A(j("Anyray connect \u2014 security review"));for(let c of Uw())A(c?` ${c}`:"")}return 0}let r;try{r=Tr(e.gateway,n)}catch(c){return e.silent?1:e.json?(console.log(JSON.stringify({error:c.message})),1):(A(j("Anyray connect \u2014 doctor")),R(` Gateway URL: ${c.message}`),A(v(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.silent||(e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(A(j("Anyray connect \u2014 doctor")),R(" --quick skips the network probes; it cannot be combined with --verify."))),1;let o=!e.noVerify&&!e.quick,a=await FK(r,n,!!e.verify&&!e.quick,t.adapters??pe,t.inferenceIntrospection??Fd,t.fleetBootstrap??xr,o,t.verifyAuth??Mi,!e.quick,t.checkTray??Uo,t.updateStatus??Io,t.readRefreshState??It,t.probeHookLane??Da),s=e.repair?await VK(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;t.captureReport?.(i),e.silent||(e.json?console.log(JSON.stringify(HK(i),null,2)):(UK(i),s&&KK(s)));try{e.quick||await(t.reportHealth??uE)(Ex(i),i.connect.version)}catch{}return i.problems===0?0:1};var jK=()=>{let e=[];for(let t of pe){let n=t.skillsDir?.();n&&e.push(n)}return e},Ox=async e=>{let t=await P();A(j("Anyray connect \u2014 sync"));let n;try{n=Tr(e.gateway,t)}catch(s){return R(s.message),1}N(`Gateway: ${n}`);let r=rI(t.clientKey,"anyray-placeholder"),o;try{o=await Oa(n,r)}catch(s){return R(`Team policy sync failed: ${Ah(s)}`),1}let a=jK();if(a.length===0)ZK();else if(o.skills.length===0)N("No team skills published yet \u2014 nothing to sync.");else{let s=await zS(o,a,t.syncedSkills??{});H("Skills");for(let i of s.results)i.written?B(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):N(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await le({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){N(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}H("Summary"),A(` ${ze(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Ta(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(A(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&N(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){N(`Fleet policy reconcile skipped: ${Ah(s)}`)}return 0},ZK=()=>{N("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as z2}from"node:zlib";import{promisify as q2}from"node:util";var Dr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Ty=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),Tx=e=>`
|
|
667
|
+
`).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((m,h)=>{let g=()=>{r.off("data",C),r.off("end",b),r.off("close",b),r.off("error",k)},y=S=>{g(),m(S)},w=S=>{g(),h(S)},b=()=>y({kind:"cancelled"}),k=S=>w(S),C=S=>{try{for(let E of yV(S)){if(E===""||E==="\x1B"||E==="q"){y({kind:"cancelled"});return}if(e.items.length===0){(E==="\r"||E===`
|
|
668
|
+
`)&&y({kind:"ok",values:[]});continue}if(E==="\x1B[A"||E==="k")s=(s-1+e.items.length)%e.items.length,d();else if(E==="\x1B[B"||E==="j")s=(s+1)%e.items.length,d();else if(E===" "){if(e.single){let I=!a[s];a.fill(!1),a[s]=I}else a[s]=!a[s];d()}else if(E==="a"&&!e.single){let I=e.items.map((T,U)=>({item:T,index:U})).filter(({item:T})=>T.requiresExplicitChoice!==!0),O=!I.every(({index:T})=>a[T]);for(let{index:T}of I)a[T]=O;d()}else if(E==="\r"||E===`
|
|
669
|
+
`){y({kind:"ok",values:e.items.filter((I,O)=>a[O]).map(I=>I.value)});return}}}catch(E){w(E)}};r.on("data",C),r.on("end",b),r.on("close",b),r.on("error",k)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),p&&r.setRawMode(f)}catch{}n.close()}};var px=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],gV=80,Pi=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&Sa(r,n.env??process.env)))return r.write(`${e}
|
|
670
|
+
`),t();let a=0,s=()=>{r.write(`\r${px[a++%px.length]} ${e}`)};s();let i=setInterval(s,gV);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as wV}from"node:fs";import{spawnSync as fx}from"node:child_process";import{chmod as mx,copyFile as hy,lstat as yy,mkdir as gy,readdir as ou,realpath as ru,rename as eu,rm as xt,stat as hx,symlink as bV,writeFile as AV}from"node:fs/promises";import{createHash as CV}from"node:crypto";import{basename as tu,dirname as en,join as Wa}from"node:path";import{Readable as kV}from"node:stream";import{pipeline as vV}from"node:stream/promises";var SV=new RegExp(`/releases/tag/${Kr}([0-9][0-9A-Za-z.-]*)$`),EV=300*1024*1024,Ni=1e4,IV=5*6e4,xV=360*6e4,RV=30*6e4,Ua=(e,t)=>{let n=s=>s.split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),r=n(e),o=n(t);for(let s=0;s<Math.max(r.length,o.length);s++){let i=(r[s]??0)-(o[s]??0);if(i!==0)return i<0?-1:1}let a=s=>s.includes("-")?0:1;return a(e)-a(t)};var OV=e=>{if(e)return SV.exec(e.trim())?.[1]},wy=(e,t)=>{for(let n of e.split(`
|
|
671
|
+
`)){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()}},TV=e=>e.mode==="off"?{allow:!1,outcome:"fleet-off"}:e.mode==="directed"&&e.initiator==="tick"?{allow:!1,outcome:"fleet-directed"}:{allow:!0},_V=e=>e==="auto",yx=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&&Ua(e.current,e.minVersion)<0&&Ua(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},PV=e=>Ua(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}:{...yx(e),downgradeBlocked:!1},DV=(e=process.execPath)=>{let t=Ju(e);return t?en(t):en(en(e))},LV=async(e=dt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=cr(DV(e.execPath)).launcher;try{if(await ru(t)!==await ru(e.execPath))return}catch{return}return t},by=async(e=dt(),t=Q())=>{let n=await LV(e);if(n)return{kind:"managed",root:en(en(n)),link:n,entryPath:Xn(e)};let r=Xn(e);return zu(r,t)?{kind:"durable",root:t,entryPath:r}:Zu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},au=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)}},Ay=async(e=Ni)=>{let t=await au(`${ir}/latest`,e,{redirect:"manual"});return OV(t.headers.get("location"))},NV=async e=>{try{let t=await au(`${e}/connect-update.json`,Ni);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}},Li=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},Cy=async(e,t,n)=>{let r=await au(e,IV);if(!r.ok||!r.body)throw new Li(r.status);let o=CV("sha256"),a=0;if(await vV(kV.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>EV)throw new Error("asset exceeds size cap");o.update(c),yield c}},wV(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},$V=e=>tu(e)===Zr()?tu(en(e)):tu(e),MV=async e=>{let t=await ou(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await xt(Wa(e,n),{force:!0}).catch(()=>{})},gx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await xt(r,{force:!0}).catch(()=>{});let o=!1;try{await eu(e,r),o=!0}catch{}try{await hy(t,e),await AV(is(e),$V(t))}catch(a){throw o&&await eu(r,e).catch(()=>{}),a}await xt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await xt(n,{force:!0}),await bV(t,n),await eu(n,e)},ky=(e,t)=>e===t||tu(e)===bp?448:493,Di=async(e,t)=>{let n=(await hx(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await mx(e,n&4095|t).catch(()=>{})},nu=async(e,t)=>{await gy(e,{recursive:!0,mode:t}),await Di(e,t)},BV=async(e,t,n)=>{let r=ky(e,Q());if(r!==448){let o=cr(e),a=o.versionsDir;await Di(e,r),await Di(en(o.launcher),r),await Di(a,r);for(let s of await ou(a).catch(()=>[]))await Di(Wa(a,s),r)}await(n.refreshDesktopHelpers??jd)(t)},FV=async(e,t={})=>{let n=cr(e.root),r=en(n.launcher),{versionsDir:o,launcher:a}=n,s=ky(e.root,(t.privateRoot??Q)());await nu(r,s),await nu(o,s);let i=Wa(o,e.version),l=(await yy(i).catch(()=>{}))?.isFile()?i:Wa(i,Zr());if(!(await yy(l).catch(()=>{}))?.isFile()){let u=await(t.fetchResponse??au)(`${e.tagUrl}/SHA256SUMS`,Ni),f=u.ok?wy(await u.text(),e.asset):void 0;if(!f)throw new Error("no published checksum");await nu(en(l),s),await MV(en(l));let p=`${l}.part-${process.pid}`;try{await(t.download??Cy)(`${e.tagUrl}/${e.asset}`,p,f),await mx(p,493),await eu(p,l)}catch(m){throw await xt(p,{force:!0}).catch(()=>{}),m}}return await(t.activate??gx)(a,l),{link:a,target:l,versionsDir:o}},WV=async e=>{fx(e.target,[jr,e.link],{stdio:"ignore",timeout:Ni})},UV=async e=>{if(process.platform==="darwin"){let t=fx("/usr/bin/codesign",["--verify","--strict",e],{stdio:"ignore",timeout:Ni});return!t.error&&t.status===0}return!0},HV=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??Ao)(n);if(r.length>0){let o=await(t.resolveTarget??We)(async()=>e);if(!o||!(await(t.repair??Ft)(r,o.target)).every(bo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??ar)()).ok)},GV=async e=>{let t=await e.install();if(!await(e.smoke??UV)(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},VV=async(e,t)=>{let n=await ou(e).catch(()=>[]);for(let r of n)t.includes(r)||await xt(Wa(e,r),{force:!0,recursive:!0}).catch(()=>{})},KV=async e=>{let t=await ou(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await xt(Wa(e,n),{force:!0}).catch(()=>{})},jV=async(e,t)=>{let n=async()=>{await xt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await gy(e,{recursive:!1}),n}catch{}let r=await hx(e).catch(()=>{});if(!(!r||t-r.mtimeMs<RV)){await n();try{return await gy(e,{recursive:!1}),n}catch{return}}},my=e=>cr(e).state,ZV=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}},Ha=async(e={})=>{let t=e.now??Date.now,n=ke;if(Rn(on(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??dt(),o=e.root??Q(),a;try{let s=await by(r,o);if(o=s.root,s.kind==="unmanaged")return{outcome:"unmanaged",current:n};if(s.kind==="npm"&&!e.allowNpmMigration)return{outcome:"unmanaged",current:n};let i=s.kind!=="managed",c=e.force===!0,l=await(e.load??P)().catch(()=>({})),d=l.autoUpdate!==!1,u=l.fleetUpdatePolicy?.mode??"auto",f=TV({mode:u,initiator:e.initiator??"tick"});if(!f.allow)return{outcome:f.outcome,current:n};!i&&s.link&&!e.checkOnly&&(d||c)&&await BV(o,s.link,e).catch(()=>{});let p=ys(e.platform??process.platform,e.arch??process.arch);if(!p)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Ay)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let m=a;if(!i&&m===n)return{outcome:"current",current:n,latest:m};if(i&&Ua(m,n)<0)return{outcome:"migration-deferred",current:n,latest:m};let h=await ZV(my(o));if((e.respectFailureBackoff===!0||!c)&&h.failedVersion===m&&h.failedAt!==void 0&&t()-h.failedAt<xV)return{outcome:"failed",current:n,latest:m};let g=`${ir}/download/${Kr}${m}`,y=d||c||!_V(u)?void 0:await(e.minimumVersion??NV)(g),w={current:n,latest:m,autoUpdate:d,forced:c,minVersion:y},b=i?PV(w):{...yx(w),downgradeBlocked:!1};if(b.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:m};if(!b.apply)return{outcome:"disabled",current:n,latest:m};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:m,mandatory:b.mandatory};o===Q()?await Qe():await nu(o,ky(o,Q()));let k=cr(o),C=await jV(k.lock,t());if(!C)return{outcome:i?"migration-available":"available",current:n,latest:m};let S,E;try{await KV(en(k.launcher));let I=await ru(k.versionsDir).catch(()=>{}),O=await ru(k.launcher).catch(()=>{}),T=O&&oc(O,I)?O:void 0,U=k.launcher;i&&process.platform==="win32"&&(await yy(U).catch(()=>{}))?.isFile()&&(E=`${U}.rollback-${process.pid}`,await hy(U,E));let z=()=>(e.installBinary??FV)({root:o,version:m,asset:p,tagUrl:g});i?S=await GV({install:z,smoke:e.smoke,rollback:async({link:K,target:oe})=>{E?(await hy(E,K),await xt(is(K),{force:!0}).catch(()=>{})):T&&T!==oe?await gx(K,T):(await xt(K,{force:!0}),await xt(is(K),{force:!0}).catch(()=>{}))},repoint:async K=>e.repoint?e.repoint(l,K):HV(l),prune:async()=>{await(e.pruneDurable??(K=>ac(K)))(r)}}):S=await z(),await VV(S.versionsDir,[m,n]),await(e.refreshHelpersFromInstalled??WV)(S).catch(()=>{}),await xt(my(o),{force:!0}).catch(()=>{})}finally{E&&await xt(E,{force:!0}).catch(()=>{}),await C()}return{outcome:i?"migrated":"updated",current:n,latest:m,managedPath:S.link,mandatory:b.mandatory}}catch{return a&&await J(my(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},wx=async(e={})=>{let t=e.context??dt(),n=await by(t,e.root??Q()),r=$o(e.root??Q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:ke,managedPath:n.link??r}:Ha({initiator:"human",...e,context:t,allowNpmMigration:!0})},Io=async(e={})=>{let t=e.context??dt(),n=e.root??Q(),r=await by(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&&!!ys(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=Rn(on(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:ke,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l,fleetMode:a.fleetUpdatePolicy?.mode??"auto"}};import{z as bx}from"zod";var YV=5e3,JV=bx.object({lane:bx.enum(["subscription","org"]).optional().catch(void 0)}),Ax=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??YV);try{let a=await(n.fetchResponse??fetch)(`${e.replace(/\/$/,"")}/connect/policy`,{headers:{"x-anyray-api-key":t.trim()},signal:r.signal});if(!a.ok)return;let s=JV.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},Cx=(e,t)=>{if(!e||t.byoUpstream)return{overrodeFlag:!1};let n=t.subscription?"subscription":t.org?"org":void 0;return{lane:e,overrodeFlag:n!=null&&n!==e}};var XV=12e3,zV="anyray-wiring-probe-not-a-real-token",qV={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},Sy={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},xo=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},vx=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}"`))},kx=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."],QV=e=>e.includes("no provider key configured for"),Iy=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},xy=e=>({kind:"enrollment-required",detail:`gateway requires per-developer enrollment (HTTP ${e}).`,remedy:["This gateway only serves enrolled developers. Re-run with your enrollment","link from your admin so connect can mint your personal key automatically:"," anyray-connect --enroll <link>"]}),$i=e=>({kind:"key-rejected",detail:`gateway rejected the client key (HTTP ${e}).`,remedy:["The gateway did not receive a usable personal key (missing, unknown, expired,","or revoked). Re-run `anyray-connect` to refresh an existing enrollment, or","use `--enroll` / `--sso` to enroll first."]}),eK=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:QV(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${xo(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")?kx([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:e===401||e===403?Iy(t)?xy(e):Ey(t)?$i(e):vx(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${xo(t)}`,remedy:["The org provider rejected the request \u2014 check the gateway\u2019s provider","key/config (e.g. the model is enabled for that account)."]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${xo(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).",...kx([" \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}: ${xo(t)}`,remedy:[]},tK=(e,t)=>{if(Ey(t))return $i(e);if(Iy(t))return xy(e);if(vx(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}: ${xo(t)}`,remedy:[]}},nK=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),rK=(e,t)=>{if(Ey(t))return $i(e);if(Iy(t))return xy(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")||nK(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}: ${xo(t)}`,remedy:[`The probe asks for a fixed model (${Sy.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."]}},vy=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)}},oK=async(e,t)=>{if(!e.clientKey)return $i(401);let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`${e.origin}/connect/savings`,{method:"GET",headers:{"x-anyray-api-key":e.clientKey},signal:n.signal}),a=await o.text();return o.ok?{kind:"ok",detail:"gateway accepted your personal key \u2014 Cursor hooks/MCP can report and retrieve.",remedy:[]}:o.status===401||o.status===403?$i(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${xo(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},aK=(e,t)=>{let n=typeof t?.code=="string"?` ${t.code}`:"";return{kind:"unreachable",detail:`could not reach the gateway to verify (${t instanceof Error&&t.name==="AbortError"?`no response within ${e}ms`:t instanceof Error?`${t.name}${n}`:"unknown error"}).`,remedy:["Your config was still written \u2014 re-run the curl below once the gateway is reachable."]}},Mi=async(e,t={})=>{let n=t.timeoutMs??XV,r=fe(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await oK(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 vy(`${e.anthropicBaseUrl}/v1/messages`,l,Sy,n);return rK(d,u)}if(ee(e,"anthropic")){let l={Authorization:`Bearer ${zV}`,"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 vy(`${e.anthropicBaseUrl}/v1/messages`,l,Sy,n);return tK(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await vy(`${e.openaiBaseUrl}/chat/completions`,s,qV,n);return eK(i,c,t.tools??[])}catch(o){return aK(n,o)}};var Sx=async e=>{let t=await P(),n;try{n=Tr(e.gateway,t)}catch(o){return A(j("Anyray connect \u2014 status")),N(`Gateway: ${o.message}`),0}A(j("Anyray connect \u2014 status")),H("Gateway"),A(` Origin: ${ze(n)}`),t.gateway?N(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?N(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||N(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),H("Identity"),A(` Name: ${t.name??v("(not set)")}`),A(` Team: ${t.team??v("(not set)")}`);let r=on();r&&(H("Environment"),A(` Remote dev context: ${Fo(r)}`),Rn(r)&&N(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),N(" VS Code tools configure the remote server variant backing this window.")),t.enrolledCert&&t.clientKey&&(H("Credential renewal"),B(" Direct gateway routing with a proof-backed key heartbeat."),N(" Renewal extends the same key; tool configuration is not rewritten.")),H("Tools");for(let o of pe){if(!(await o.detect()).installed){N(` ${o.title}: not installed`);continue}if(!o.pointsAt){N(` ${o.title}: installed ${v("(status not introspectable)")}`);continue}let s=await o.pointsAt(n);if(s){if(o.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){B(` ${o.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}B(` ${o.title}: pointed at Anyray`)}else{let i=null,c=null;if(o.id===$a&&o.mcpStatus)try{let l=(await o.mcpStatus()).registered,d=await Fd();i=Wd({id:o.id,installed:!0,pointedAt:s,mcpRegistered:l,introspectable:d.authoritative}),c={...d.authoritative?{}:{reason:d.reason},mcpRegistered:l}}catch{i=null,c=null}if((i==="not-routed"||i==="unverifiable")&&c){let l=Ud(i,c);_(` ${o.title}: ${l.headline}`);for(let d of l.detail)A(v(` ${d}`))}else N(` ${o.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as RK}from"node:fs";import{isAbsolute as OK}from"node:path";import{homedir as TK}from"node:os";import{readFile as sK,stat as iK}from"node:fs/promises";import{homedir as cK,platform as lK}from"node:os";var dK=e=>e.replace(/\\(\d{3})/g,(t,n)=>String.fromCharCode(parseInt(n,8))),uK=e=>e.split(`
|
|
672
|
+
`).map(t=>t.split(" ")[4]).filter(t=>!!t).map(dK),pK=async(e,t,n=async r=>(await iK(r)).isFile())=>{let r=t.endsWith("/")?t:`${t}/`,o=[];for(let a of e)a.startsWith(r)&&await n(a).catch(()=>!1)&&o.push(a);return o},su=async()=>{if(lK()!=="linux")return[];try{let e=await sK("/proc/self/mountinfo","utf-8");return await pK(uK(e),cK())}catch{return[]}};import{access as fK}from"node:fs/promises";import{constants as mK}from"node:fs";import{platform as hK}from"node:os";var yK=async e=>{try{return await fK(e,mK.F_OK),!0}catch{return!1}},gK=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"]:[],Ro=async(e={})=>{let t=e.os??hK(),n=e.exists??yK;for(let r of gK(t))if(await n(r))return!0;return!1};import{execFile as wK}from"node:child_process";import{readFile as bK}from"node:fs/promises";import{homedir as AK,platform as CK}from"node:os";import{promisify as kK}from"node:util";var vK=kK(wK),SK="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",Ex=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),EK=async e=>{let t;try{t=await bK(e,"utf-8")}catch(n){return n?.code==="ENOENT"?{readable:!0}:{readable:!1}}try{if(t.trim()==="")return{readable:!0};let n=bt(t);if(!Ex(n))return{readable:!1};let r=n[fn],o=n[mn];return{readable:!0,supportsAnyray:Ex(r)?r[q]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},IK=async(e=async()=>(await vK("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(CK()==="win32")return"unknown";let t;try{t=await e()}catch{return"unknown"}let n=!1;for(let r of t.split(`
|
|
673
|
+
`)){let o=new RegExp(`${SK}=(\\w*)`).exec(r);if(!o)continue;let a=r.replace(/\bVSCODE_[A-Z0-9_]*=\S*/g,"");if(/Code Helper|MacOS\/Code|VSCodium|Visual Studio Code|agentHost/i.test(a)&&(n=!0,o[1]==="true"))return"on"}return n?"off":"unknown"},xK=e=>e.mode!=="copilot-seat"?"not-applicable":e.settings.readable?e.settings.supportsAnyray!==!0||e.settings.bridgeEnabled!==!0?"not-configured":e.bridge==="off"?"awaiting-relaunch":"ready":"unknown",iu=(e,t)=>{switch(e){case"ready":return t==="on"?"Agents window: Anyray models available (agent host is running with the model bridge on).":"Agents window: configured. No running agent host was found to confirm it, so it applies from the next VS Code start.";case"awaiting-relaunch":return"Agents window: configured, but the agent host running right now started before it. Quit and relaunch VS Code once; a window reload will not do it, because that process outlives every window.";case"not-configured":return`Agents window: not enabled. Re-run anyray-connect --tools copilot, then quit and relaunch VS Code (it sets ${fn} and ${mn}; if you switched either off yourself, that choice is left alone).`;case"unknown":return"Agents window: could not read VS Code settings.json, so its state is unknown. Nothing is reported as missing on that basis.";case"not-applicable":return"Agents window: not applicable on this machine."}},Ix=async(e={})=>{let{installedVariant:t=Xo,receiptMode:n=sl,awaitingReload:r=al,readSettings:o=EK,probeBridge:a=IK,home:s=AK()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:iu("not-applicable","unknown")};let c=await n(i,s);if(c!=="copilot-seat"){let f=c===void 0&&await r(i,s);return{state:f?"unknown":"not-applicable",bridge:"unknown",detail:f?"Agents window: VS Code has an Anyray configuration staged but not applied yet, so its state is unknown. Restart VS Code to finish.":iu("not-applicable","unknown")}}let l=await o(Ds(i)),d=await a(),u=xK({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:iu(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:iu("not-applicable","unknown")}}};var tn="connect",cu=e=>e.replace(/-/g,"_"),xx=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:tn,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:tn,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:tn,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:tn,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.removed&&e.serviceRemoval.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:tn,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:tn,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=cu(e.retrieval.kind);t.push({tool:tn,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":cu(e.verify.kind);t.push({tool:tn,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:tn,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:cu(e.hookLane.reason)}:{}})}t.push({tool:tn,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)if(i.installed){if(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp){let c=!i.mcp.registered&&!i.routingHeld;t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing",...c&&i.mcp.reason?{errorClass:cu(i.mcp.reason)}:{}})}a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"})}return t.push({tool:tn,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};var _K=e=>{let t=TK();return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e};function PK(){return ke}var DK="ctx_doctor-probe-synthetic",LK=(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: ${Ty(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 NK(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function $K(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Ty(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 Rx=e=>Wd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),Ry=e=>e.pointedAt===!1&&e.tombstoned!==!0&&Rx(e)!=="unverifiable",Ox=e=>e.registered&&e.command&&OK(e.command)?RK(e.command):null,MK=e=>{switch(e.mcp?.reason){case"ephemeral-runtime":return"this Connect is running from a temporary npx/cache path, so a registration naming it would rot \u2014 install it durably (`curl -fsSL https://app.anyray.ai/connect.sh | sh`) and re-run.";case"no-config":return`${e.title} has not written its config yet \u2014 launch it once, then re-run \`anyray-connect\`.`;case"stale":return"the entry was written by an older Connect \u2014 re-run `anyray-connect` to refresh it.";case"foreign":return"an MCP server named `anyray` that Connect did not write is already there, and it was left untouched. Rename or remove it, then re-run `anyray-connect`.";case"unreadable":return`${e.title}'s config could not be read or parsed \u2014 repair it (or check its permissions), then re-run \`anyray-connect\`.`;case"absent":return"re-run `anyray-connect` to register it.";default:return"re-run `anyray-connect` to register it."}},Oy=e=>(Ry(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),BK=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,FK=async(e,t)=>{if(e.length===0)return!1;for(let n of e){let r=t.find(a=>a.id===n);if(!r?.inferenceAuthLanes)return!1;let o=await r.inferenceAuthLanes().catch(()=>["unknown"]);if(o.length===0||o.some(a=>a!=="subscription"&&a!=="native"))return!1}return!0},Tx=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},WK=(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(ko),s=[],i=n(e.selfcheck?.adapters)?e.selfcheck.adapters:{};for(let[c,l]of Object.entries(i)){if(!o.has(c)||!n(l))continue;let d=n(l.lastRepaired)?l.lastRepaired:{},u=Object.entries(d).filter(g=>a.has(g[0])&&r(g[1])).map(([g,y])=>({checkId:g,at:y})),f=n(l.flapping)?l.flapping:void 0,p=Array.isArray(f?.checks)?f.checks.filter(g=>typeof g=="string"&&a.has(g)):[],m=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,h=f&&r(f.since)&&m&&p.length>0?{since:f.since,reason:m,checks:p}:void 0;(u.length>0||h)&&s.push({tool:c,repaired:u,...h?{flapping:h}:{}})}return s},UK=async(e,t,n,r,o,a,s=n,i=Mi,c=!0,l=Uo,d=Io,u=It,f=Da)=>{let p=c?await Qd(e):null,m=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,h=G=>G&&Uh(G)?"machine_default":null,g=t.enrolledCert?.payload,y=g?.expiresAt??t.enrolledCertExpiry??null,b=(await a())?.sso??null,k=$K({ssoLink:b,enrolledViaToken:!!t.enrolledTokenHash}),C=wt(),S=await tb(C),E=S?[]:Bc(Oe({origin:e})),I=[];for(let G of r){let xe=await G.detect(),ht=null;if(xe.installed&&G.mcpStatus)try{let es=await G.mcpStatus();ht={...es,commandOk:Ox(es)}}catch{}let yt=xe.installed&&G.id===$a?await o():void 0,De=xe.installed&&G.pointsAt?await G.pointsAt(e):null,qe=await BK(De,G,t.managedTools??[]),gt=De===!1&&qe===null,Xa=qe===!1&&G.routingPendingReload?await G.routingPendingReload().catch(()=>!1):!1,Ji=xe.installed?G.runtimeDiagnostics?await G.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:G.routingOverrides?await G.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:To,claudeCodeHookPolicy:za}=Ji,qa=t.fleetToolPolicy,Qa=qa?.enabled.includes(G.id)?qa.tiers?.[G.id]??xa:void 0;I.push({id:G.id,title:G.title,installed:xe.installed,...xe.detail?{detail:xe.detail}:{},pointedAt:qe,...gt?{routingHeld:!0}:{},...Xa?{routingPendingReload:!0}:{},...To.length?{routingOverrides:To}:{},...za===void 0?{}:{claudeCodeHookPolicy:za},mcp:ht,...Qa?{policyTier:Qa}:{},...t.revertedTools?.includes(G.id)?{tombstoned:!0}:{},...G.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...yt===void 0?{}:{inferenceIntrospectable:yt.authoritative,...yt.authoritative?{}:{inferenceUnverifiableReason:yt.reason}}})}let O=s?await(async()=>{let{kind:G,detail:xe,remedy:ht}=await i(Oe({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:G,detail:xe,remedy:ht}})():null,T=O?.kind==="provider-rejected"&&await FK(t.managedTools??[],r),U=O?{...O,...T?{notApplicableSubscription:!0}:{}}:null,z=n?LK(await Pa({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:fe({user:t.name,team:t.team})},DK,{probe:!0}),{mode:k,ssoLink:b}):null,K=await u().catch(()=>({})),oe=vn(K.hookLane),ae=s?await Tx(r):!1,Z=ae?await(async()=>{let G=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...Oh(G,{hookRegistered:ae,neverInvoked:xh(oe,Date.now())}),lastInvokedAt:Id(oe)}})():null,ie=(await dr()).map(G=>({adapter:G.adapter,op:G.op,requestedAt:G.requestedAt,watcherAlive:pr(G.watcherPid)})),F=ie.find(G=>G.adapter==="cursor"),Y=F?{op:F.op,requestedAt:F.requestedAt,watcherAlive:F.watcherAlive}:null,te=!!t.refreshSchedulerEnabled,Ue=await Wo(),ve=await d(),ge=t.persistenceOwner==="tray",Ht=ge?await l(t)==="healthy":null,$=await Hw({schedulerEnabled:te&&!ge,schedulerInstalled:Ue,binaryDurable:!et(Bo()),schedulerInstalledOnce:t.refreshSchedulerInstalledOnce===!0,trayManaged:ge}),D=0;p&&!p.reachable&&(D+=1),ge?te&&!Ht&&(D+=1):te&&!Ue&&(D+=1);for(let G of I)D+=Oy(G);U&&U.kind!=="ok"&&!U.notApplicableSubscription&&(D+=1),z&&z.kind!=="ok"&&(D+=1),Z?.verdict==="dark"&&(D+=1),E.length>0&&(D+=1),D+=ie.filter(G=>!G.watcherAlive).length;let X=await Ix();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:PK(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:on(),fileBindMounts:await su(),selfUpdate:{managed:ve.managed,available:ve.available,autoUpdate:ve.autoUpdate,state:ve.state,fleetMode:ve.fleetMode}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},refreshScheduler:{enabled:te,installed:Ue,owner:ge?"tray":"os",...ge?{trayHealthy:!!Ht}:{}},serviceRemoval:$,fleetdPresent:await Ro(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:m,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:h(t.name)},enrollment:{enrolled:!!g,deploymentId:g?.deploymentId??null,issuedAt:g?.issuedAt??null,expiresAt:y,expired:y?Date.parse(y)<Date.now():null,orgMode:k,ssoLink:b},shell:{profilePath:C,blockPresent:S,staleExports:E},tools:I,...t.fleetToolPolicy?{fleetPlan:Sd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Y,pendingOps:ie,ambientRepairs:WK(K,r),verify:U,retrieval:z,hookLane:Z,agentsWindow:X,problems:D}},HK=e=>{if(e.serviceRemoval.suspected){if(!e.serviceRemoval.removed){H("Automatic key refresh"),_(" This seat expects the key-refresh schedule, but no unit is installed and"),_(" Anyray has no record of ever installing one here. Re-run `anyray-connect`"),_(" to install it.");for(let t of e.serviceRemoval.missingPaths)A(v(` expected: ${t}`));return}H("Endpoint security"),_(" Anyray installed these background services, but their files are gone from disk \u2014"),_(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),_(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)A(v(` missing: ${t}`));A(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),A(v(" tools straight at the gateway (your key then needs a periodic re-run).")),A(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),A(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},GK=e=>{if(A(j("Anyray connect \u2014 doctor")),e.connect.remoteContext||e.connect.fileBindMounts.length>0){H("Environment"),e.connect.remoteContext&&(A(` Remote dev context: ${Fo(e.connect.remoteContext)}`),Rn(e.connect.remoteContext)&&A(v(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule.")));for(let c of e.connect.fileBindMounts)A(` Bind-mounted config file: ${_K(c)}`),A(v(" A file mounted into this container cannot be replaced atomically; connect writes it in place (verified). Mount the parent directory instead to restore atomic writes."))}switch(H("CLI updates"),e.connect.selfUpdate.state){case"managed":B(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.fleetMode==="off"?A(v(" Your organization manages Connect updates; this machine downloads nothing.")):e.connect.selfUpdate.fleetMode==="directed"?A(v(" Your organization applies Connect updates centrally; an administrator pushes new versions.")):e.connect.selfUpdate.autoUpdate||_(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":_(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),A(v(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":_(" Self-update is unavailable on this platform because no standalone binary is published."),A(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":A(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":A(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(H("Gateway"),e.gateway.reachable===null?A(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?B(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(R(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),A(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(H("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(R(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),A(v(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?B(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(R(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||A(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),HK(e),H("Personal key"),NK(e)){case"env":B(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":B(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":_(" Enrolled, but no personal key is cached locally right now."),A(v(" Fix: re-run `anyray-connect` to re-mint it from your enrollment \u2014 no need to re-enroll. Claude Code and Codex are still attributed to you by name."));break;default:_(" Enrollment required \u2014 no personal gateway key is available."),A(v(` Fix: ${Ty(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?_(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):B(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(H("Shell"),R(" This terminal still exports Anyray, but the config is gone."),A(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),A(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),A(v(" Anything you start from this terminal keeps reaching the gateway with")),A(v(" no credential, and fails with 401.")),A(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),A(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),A(v(" reuses the environment it captured at launch, so a new terminal")),A(v(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};H("Claude Code hook policy"),R(` ${uc(c)}.`),A(v(` ${pc(c)}`))}H("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])R(` ${c.title}: ${l.problem}.`),A(v(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(R(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),A(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):B(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(_(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(` Fix: ${MK(c)}`))))};for(let c of e.tools){if(!c.installed){A(v(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){A(v(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){B(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}B(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===$a&&A(v(` ${qC}`)),c.id==="codex"&&A(v(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=Rx(c);if(l==="not-routed"||l==="unverifiable"){let d=Ud(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});_(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(_(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?_(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):A(v(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(R(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),A(v(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(R(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),A(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(_(" No tools are pointed at this gateway yet."),A(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){H("Queued operations");for(let c of e.pendingOps){let l=ut(c.adapter)?.title??c.adapter;c.watcherAlive?_(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(R(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),A(v(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){H("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=ut(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:p,at:m})=>`${c(p)} ${new Date(m).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?_(f):A(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){H("Fleet policy");let c=l=>l.map(d=>ut(d)?.title??d).join(", ");i.freshIds.length>0&&A(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&_(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(H("Auth probe"),e.verify.notApplicableSubscription)B(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")B(` ${e.verify.detail}`);else{R(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)A(v(` ${c}`))}if(e.retrieval)if(H("Retrieval loop"),e.retrieval.kind==="ok")B(` ${e.retrieval.detail}`);else{R(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)A(v(` ${c}`))}if(e.hookLane){if(H("Hook lane"),e.hookLane.verdict==="live")B(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){R(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}else{_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}e.hookLane.lastInvokedAt!==null&&A(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(H("VS Code Agents window"),_(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(H("VS Code Agents window"),B(` ${e.agentsWindow.detail}`)),H("Summary"),e.problems===0?(e.verify?B(" No problems found."):B(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):R(` ${e.problems} problem(s) found \u2014 see fixes above.`)},VK=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}),KK=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Sh(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??Da,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Qt)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=vn((await(t.readRefreshState??It)().catch(()=>({}))).hookLane),l=Oh(i,{hookRegistered:await Tx(t.adapters??pe).catch(()=>!1),neverInvoked:xh(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:Id(c)},note:d}},jK=async(e,t,n={})=>{let r=n.adapters??pe,o=n.resolveTarget??We,a=n.applyTools??Ft,s=await KK(e,n).catch(()=>null),i=s&&e.hookLane?.verdict==="dark"&&s.hookLane?.verdict==="live"?1:0,c=s?{hookLane:s.hookLane,notes:[s.note]}:{notes:[]},l=e.tools.filter(w=>w.installed&&(Ry(w)||w.mcp?.commandOk===!1||w.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t);if(!d)return{entries:l.map(w=>({id:w.id,title:w.title,status:"skipped-not-enrolled"})),remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,`Repair needs an enrolled personal key \u2014 ${Ty(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],p=[...c.notes],m=[];for(let w of l){let b=r.find(k=>k.id===w.id);if(!u.has(w.id)||!b){f.push({id:w.id,title:w.title,status:"skipped-unmanaged"});continue}m.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 h=await a(m,d.target),g=new Map,y=0;for(let w of h){if(f.push(w),!bo(w))continue;let b=e.tools.find(T=>T.id===w.id);if(!b)continue;let k=r.find(T=>T.id===w.id),C=b.mcp;if(k?.mcpStatus)try{let T=await k.mcpStatus();C={...T,commandOk:Ox(T)}}catch{}let S=Ry(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{S=await k.pointsAt(e.gateway.origin)}catch{}let E=b.routingOverrides,I=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let T=await k.runtimeDiagnostics();E=T.routingOverrides.length?T.routingOverrides:void 0,I=T.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let T=await k.routingOverrides();E=T.length?T:void 0}catch{}let O={...b,pointedAt:S,mcp:C,...E?{routingOverrides:E}:{},...I===void 0?{}:{claudeCodeHookPolicy:I}};E||delete O.routingOverrides,I===void 0&&delete O.claudeCodeHookPolicy,g.set(w.id,O),y+=Oy(b)-Oy(O)}return{entries:f,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:g,...s?{hookLane:s.hookLane}:{},notes:p}},ZK=e=>{H("Repair"),e.entries.length===0&&B(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?B(` ${t.title}: re-applied`):t.status==="queued"?B(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):R(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},lu=async(e,t={})=>{let n=await P();if(e.securityReview){if(!e.silent){A(j("Anyray connect \u2014 security review"));for(let c of Gw())A(c?` ${c}`:"")}return 0}let r;try{r=Tr(e.gateway,n)}catch(c){return e.silent?1:e.json?(console.log(JSON.stringify({error:c.message})),1):(A(j("Anyray connect \u2014 doctor")),R(` Gateway URL: ${c.message}`),A(v(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.silent||(e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(A(j("Anyray connect \u2014 doctor")),R(" --quick skips the network probes; it cannot be combined with --verify."))),1;let o=!e.noVerify&&!e.quick,a=await UK(r,n,!!e.verify&&!e.quick,t.adapters??pe,t.inferenceIntrospection??Fd,t.fleetBootstrap??xr,o,t.verifyAuth??Mi,!e.quick,t.checkTray??Uo,t.updateStatus??Io,t.readRefreshState??It,t.probeHookLane??Da),s=e.repair?await jK(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;t.captureReport?.(i),e.silent||(e.json?console.log(JSON.stringify(VK(i),null,2)):(GK(i),s&&ZK(s)));try{e.quick||await(t.reportHealth??fE)(xx(i),i.connect.version)}catch{}return i.problems===0?0:1};var YK=()=>{let e=[];for(let t of pe){let n=t.skillsDir?.();n&&e.push(n)}return e},_x=async e=>{let t=await P();A(j("Anyray connect \u2014 sync"));let n;try{n=Tr(e.gateway,t)}catch(s){return R(s.message),1}N(`Gateway: ${n}`);let r=aI(t.clientKey,"anyray-placeholder"),o;try{o=await Oa(n,r)}catch(s){return R(`Team policy sync failed: ${Ch(s)}`),1}let a=YK();if(a.length===0)JK();else if(o.skills.length===0)N("No team skills published yet \u2014 nothing to sync.");else{let s=await QS(o,a,t.syncedSkills??{});H("Skills");for(let i of s.results)i.written?B(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):N(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await le({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){N(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}H("Summary"),A(` ${ze(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Ta(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(A(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&N(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){N(`Fleet policy reconcile skipped: ${Ch(s)}`)}return 0},JK=()=>{N("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as Q2}from"node:zlib";import{promisify as ej}from"node:util";var Dr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},_y=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),Px=e=>`
|
|
674
674
|
|
|
675
675
|
\u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
|
|
676
676
|
|
|
677
|
-
`,du=(e,t={})=>{if(typeof e!="string")return
|
|
677
|
+
`,du=(e,t={})=>{if(typeof e!="string")return _y(String(e??""));let n=Math.max(1,t.maxChars??Dr.maxChars);if(e.length<=n)return _y(e);let r=e.length,o=Math.max(0,t.headChars??Dr.headChars),a=Math.max(0,t.tailChars??Dr.tailChars),s=Math.max(0,t.middleWindows??Dr.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 y=d-l,w=Math.max(1,Math.floor(f/s));for(let b=0;b<s;b++){let k=l+Math.round((b+.5)/s*y),C=Math.min(d,Math.max(l,k)+Math.ceil(w/2)),S=Math.max(l,C-w),E=e.lastIndexOf(`
|
|
678
678
|
`,S);E>=l&&(S=E+1);let I=e.indexOf(`
|
|
679
|
-
`,C);I!==-1&&I<d&&(C=I),C>S&&u.push([S,C])}}a>0&&u.push([d,r]),u.sort((
|
|
679
|
+
`,C);I!==-1&&I<d&&(C=I),C>S&&u.push([S,C])}}a>0&&u.push([d,r]),u.sort((y,w)=>y[0]-w[0]);let p=[];for(let[y,w]of u){let b=p[p.length-1];b&&y<=b[1]?b[1]=Math.max(b[1],w):p.push([y,w])}let m="",h=0;for(let[y,w]of p)y>h&&(m+=Px(y-h)),m+=e.slice(y,w),h=w;if(r>h&&(m+=Px(r-h)),m.length>=r)return _y(e);let g=r-m.length;return{text:m,trimmed:!0,originalChars:r,trimmedChars:m.length,charsRemoved:g,estTokensSaved:Math.round(g/3.3)}},XK=["stdout","content","output","text","result"],Dx=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} ---
|
|
680
680
|
${d}`);s&&i.push(`--- MCP structuredContent ---
|
|
681
681
|
${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
|
|
682
682
|
|
|
683
|
-
`),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=
|
|
684
|
-
`),s=0,i=0;for(let c of a)c.trim()&&(s++,
|
|
685
|
-
${e.slice(-
|
|
686
|
-
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},
|
|
687
|
-
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},
|
|
688
|
-
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},
|
|
689
|
-
`).filter(s=>s.trim()!==""),r=
|
|
690
|
-
|
|
691
|
-
\u2026[anyray-hook digest \u2014 ${e}; ${
|
|
692
|
-
|
|
693
|
-
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,
|
|
694
|
-
|
|
695
|
-
\u2026[anyray-hook \u2014 ${
|
|
696
|
-
`):"",
|
|
697
|
-
`).slice(0,
|
|
698
|
-
`);i=l>=0?i.slice(l+1):""}let c=
|
|
699
|
-
`));return
|
|
700
|
-
`:"",
|
|
701
|
-
${
|
|
702
|
-
`,{mode:384}),await
|
|
683
|
+
`),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=XK.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 zK=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},Bi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},uu=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Bi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Bi.minDataLineRatio,o=t.minDataLines??Bi.minDataLines,a=e.split(`
|
|
684
|
+
`),s=0,i=0;for(let c of a)c.trim()&&(s++,zK(c)&&i++);return s===0||i<o?!1:i/s>=r};var Fi=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,pu={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"},$x=new Set(["npm","pnpm","yarn","bun"]),fu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},qK=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=fu(r[0]);if(o in pu)return pu[o];if((o==="npx"||o==="bunx")&&r[1]){let a=fu(r[1]);if(a in pu)return pu[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||$x.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=qK(t);if(n)return n}return null},QK={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},e2=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,t2=(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},Mx=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=fu(r[0]);if($x.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&e2.test(i)}let a=r[1]?fu(r[1]):void 0;if(t2(o,a,r))return!1;let s=QK[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},n2=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==="]"},r2=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},o2=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=r2(t);return r>0&&t[r+1]===":"},a2=80,s2=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/a2),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,o2(e[o])&&r++;return n>0&&r/n>.3},i2=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,c2=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();(i2.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},l2=[/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b.*\bin\s+[\d.]+\s*s/i,/^=+ FAILURES =+/m,/^=+ short test summary/im,/test session starts/i,/^Test Suites:\s+\d+/m,/^Tests:\s+\d+\s+(failed|passed|total)/m,/^test result:\s+(ok|FAILED)\b/m,/^running \d+ tests?$/m,/^--- (FAIL|PASS): /m,/^(ok|FAIL)\s+\S+\s+[\d.]+s/m],Py=8192,d2=e=>{let t=e.length>2*Py?`${e.slice(0,Py)}
|
|
685
|
+
${e.slice(-Py)}`:e;return l2.some(n=>n.test(t))},u2=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),p2=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),f2=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},m2=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),Lx=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(p2(i)){t.push(Fi(i));continue}let c=f2(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Fi(c)),o=12;continue}u2(i)||m2(i)||o>0&&(t.push(Fi(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
|
|
686
|
+
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},h2=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,Bx=e=>{let t=h2.exec(e);return t&&/[/.]/.test(t[1])?t:null},y2=/^([^\s:]+)-(\d+)-/,g2=e=>{if(e==="--")return!0;let t=y2.exec(e);return t!=null&&/[/.]/.test(t[1])},w2=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>Bx(r)!=null).length;return n>=3&&n/t.length>=.7},Nx=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=Bx(c);if(!l){if(g2(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(Fi(` ${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(`
|
|
687
|
+
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},b2=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(),A2=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=b2(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=Fi(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
|
|
688
|
+
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},Fx=(e,t)=>{if(typeof t!="string"||t.length===0||n2(t))return null;let n=t.split(`
|
|
689
|
+
`).filter(s=>s.trim()!==""),r=Dy(e),o=d2(t),a=null;return r==="test-run"&&o?a=Lx(n):r==="grep"&&(a=Nx(n,.5)),a||(o?a=Lx(n):w2(n)?a=Nx(n,.7):!c2(n)&&!s2(n)&&(a=A2(n))),!a||a.text.length>=t.length?null:a},Wx=e=>`full output: Read ${e}`,Ly=(e,t)=>t?`
|
|
690
|
+
|
|
691
|
+
\u2026[anyray-hook digest \u2014 ${e}; ${Wx(t)}]\u2026`:`
|
|
692
|
+
|
|
693
|
+
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,Ux=e=>`
|
|
694
|
+
|
|
695
|
+
\u2026[anyray-hook \u2014 ${Wx(e)}]\u2026`;import{createHash as C2}from"node:crypto";import{homedir as k2}from"node:os";import{join as Lr}from"node:path";import{chmod as v2,mkdir as S2,readdir as Kx,stat as Ui,unlink as Wi,utimes as E2,writeFile as $y}from"node:fs/promises";var mu={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},jx=".swept",I2=".sweeping",Hx=64,Gx=448,My=384,By=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",Zx=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,Fy=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=Q();try{if((await Ui(t)).isDirectory())return Lr(t,"hook-tee")}catch{}return Lr(k2(),".anyray-hook-tee")},x2=/^(?:ctx_)?([0-9a-f]{16})$/,Wy=e=>e.trim().match(x2)?.[1]??null,Uy=async e=>{let t=Wy(e);return t?Lr(await Fy(),`${t}.txt`):null},R2=async(e,t={})=>{let n=t.limits??mu;try{let r=Date.now(),o=(await Kx(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=Hx)await Promise.all(o.slice(c,c+Hx).map(async l=>{let d=Lr(e,l);try{let u=await Ui(d);if(!u.isFile())return;let f=r-u.mtimeMs>n.ttlMs||r-Zx(u)>n.maxAgeMs;if(d!==t.protect&&f){await Wi(d);return}a.push({path:d,mtimeMs:u.mtimeMs,size:u.size})}catch{}}));a.sort((c,l)=>l.mtimeMs-c.mtimeMs);let s=0,i=0;for(let c of a){let l=s<n.maxFiles&&i+c.size<=n.maxTotalBytes,d=r-c.mtimeMs<n.writeGraceMs;if(l||s===0||c.path===t.protect||d){s+=1,i+=c.size;continue}await Wi(c.path).catch(()=>{})}}catch{}},Yx=async e=>{try{return Date.now()-(await Ui(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},Vx=async e=>{try{return await $y(e,"",{mode:My,flag:"wx"}),!0}catch{return!1}},O2=async(e,t)=>{let n=mu,r=Lr(e,I2),o=Lr(e,jx);if(!await Vx(r)){let a=0;try{a=Date.now()-(await Ui(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await Wi(r).catch(()=>{}),!await Vx(r)))return!1}try{return await Yx(o)<n.sweepIntervalMs?!1:(await $y(o,"",{mode:My}).catch(()=>{}),await R2(e,{protect:t}),!0)}finally{await Wi(r).catch(()=>{})}},Ny=async(e,t)=>await Yx(Lr(e,jx))<mu.sweepIntervalMs?!1:O2(e,t),T2=async()=>{try{let e=await Fy();if(!(await Kx(e)).some(t=>t.endsWith(".txt")))return;await Ny(e)}catch{}},Jx=async e=>{if(By())return await T2(),null;try{let t=await Fy();await S2(t,{recursive:!0,mode:Gx}),await v2(t,Gx).catch(()=>{});let n=`${C2("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=Lr(t,n),o=Date.now();try{let a=await Ui(r);if(a.isFile()){if(o-Zx(a)<=mu.maxAgeMs){let s=new Date(o);return await E2(r,s,s).catch(()=>{}),await Ny(t,r),r}await Wi(r).catch(()=>{})}}catch{}return await $y(r,e,{mode:My}),await Ny(t,r),r}catch{return null}};import{createHash as _2}from"node:crypto";import{homedir as Xx}from"node:os";import{join as Hy}from"node:path";import{readFile as P2,writeFile as D2,chmod as L2,stat as N2,unlink as $2}from"node:fs/promises";var M2=200,B2=1440*60*1e3,F2=4e6,zx=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",qx=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},W2=()=>qx("ANYRAY_HOOK_CACHE_MAX_ENTRIES",M2),Qx=()=>qx("ANYRAY_HOOK_CACHE_TTL_MS",B2),e0=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Hy(Xx(),".anyray");try{if((await N2(t)).isDirectory())return Hy(t,"hook-cache.json")}catch{}return Hy(Xx(),".anyray-hook-cache.json")},t0=(e,t,n)=>_2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),n0=async e=>{try{let t=JSON.parse(await P2(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},r0=async e=>{if(zx())return null;try{let n=(await n0(await e0())).entries[e];return!n||Date.now()-n.at>Qx()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},U2=e=>{let t=Date.now(),n=Qx(),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=W2();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>F2&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},o0=async(e,t)=>{if(zx())return;let n;try{let r=await e0(),o=await n0(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=U2(o.entries),n=`${r}.${process.pid}.tmp`,await D2(n,JSON.stringify(o),{mode:384}),await L2(n,384),await he(n,r)}catch{if(n)try{await $2(n)}catch{}}};import{open as H2,stat as G2}from"node:fs/promises";var a0=600,V2=3,K2=256e3,j2=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(`
|
|
696
|
+
`):"",Z2=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),Y2=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},J2=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=j2(o.message?.content).trim();if(!(!a||Z2(a))&&(t.unshift(a),n+=a.length,t.length>=V2||n>=a0))break}return t.join(`
|
|
697
|
+
`).slice(0,a0)};var X2=e=>/(^|[\\/])subagents[\\/]/i.test(e),z2=e=>/\.jsonl$/i.test(e),q2=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),s0=async e=>{let t={intent:"",kind:"unknown"};if(!e||!z2(e))return t;let n;try{let{size:r}=await G2(e),o=Math.max(0,r-K2),a=r-o;if(a<=0)return t;n=await H2(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(`
|
|
698
|
+
`);i=l>=0?i.slice(l+1):""}let c=Y2(i.split(`
|
|
699
|
+
`));return q2(c)?{intent:J2(c),kind:X2(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var tj=3e3,nj=1500,rj=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:tj},oj={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},aj=new Set(["claude","opencode"]),sj=(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:oj[t]})},ij={cacheGet:async()=>null,cachePut:async()=>{}},cj=(e,t={cacheGet:r0,cachePut:o0,tee:Jx})=>e==="claude"?t:ij,lj=1e3,dj=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),hu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),uj=e=>{try{let t=JSON.parse(e);if(!hu(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 hu(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},pj=e=>{try{let t=JSON.parse(e);return hu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},fj=e=>hu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
700
|
+
`:"",Gy=e=>Math.round(Math.max(0,e)/4),i0=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",mj=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),hj=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),yj=["tool_output","tool_response","tool_result"],gj=e=>{for(let t of yj)if(t in e)return e[t]},wj=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},bj=120,Aj=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??lj))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=Ly(r.stat,null).length+bj;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=Ly(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}}},Cj=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let S=JSON.parse(e);if(!S||typeof S!="object")return n;r=S}catch{return n}let o=typeof r.tool_name=="string"?r.tool_name:"unknown";if(mj.has(o)||hj(o))return n;let a=Dx(gj(r));if(!a)return n;let s=async S=>{try{await t.beacon(o,S)}catch{}},i=a.body,c=typeof r.transcript_path=="string"?r.transcript_path:"",l={intent:"",retrievalContext:t.defaultRetrievalContext??"unknown"};if(t.readContext&&c)try{l=await t.readContext(c)}catch{l={intent:"",retrievalContext:"unknown"}}if(c0(o)&&l.retrievalContext!=="available")return n;let d=await Aj(t,wj(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!uu(i,{minChars:nj})))return n;let p=i.length-u.length-f.length,m=async(S,E,I=S.length+f.length)=>{let O=d?.teePath??null;if(!O&&t.tee)try{O=await t.tee(i)}catch{O=null}let T=O?S.replaceAll("; not retrievable in this context]","]"):S,U=O&&!f?Ux(O):"",z=T+f+U,K=U.length,oe=z;if(t.finalizeOutput)try{let F=t.finalizeOutput(z);F.length<=z.length&&(oe=F)}catch{oe=z}let ae=z.length-oe.length,Z=Gy(Math.max(0,p-K))+E+Gy(ae);Z>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,I+K-ae),estTokensSaved:Z,...d&&{digest:d.decision}});let ie=a.rebuild(oe);return{stdout:dj(ie),replacement:ie}},h=async()=>d?m(u,0):n;if(d&&u.length<=t.sizeGate)return m(u,0);let g=l.intent?`${l.intent}
|
|
701
|
+
${i0(r.tool_input)}`:i0(r.tool_input),y=t0(o,g,u),w=async S=>{try{await t.cachePut(y,S)}catch{}},b=null;try{b=await t.cacheGet(y)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?m(b.output,b.tokensSaved):h();let k=null;try{k=xj(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{k=null}if(k&&!k.handled&&(k=null),k)return k.optimized&&k.output.length<u.length?(await w({optimized:!0,output:k.output,tokensSaved:Gy(u.length-k.output.length)}),m(k.output,0,u.length+f.length)):(await w({optimized:!1}),h());let C;try{C=t.localTrim(u)}catch{return h()}return C.trimmed?m(C.text,C.estTokensSaved):h()},Hi=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},kj=()=>{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")}},vj=ej(Q2),Sj=async e=>{try{let t=await vj(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},c0=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),Ej=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},Ij=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),xj=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),Rj=2048,Oj=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,Rj),n=Ed(t);if(!n)return;await FE({at:Date.now(),status:e.status,code:n})}catch{}},Tj=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),rj());try{let c=await Sj(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...c0(t)||Ej(t)&&a==="available"?{reversible:!0}:{},...Ij(t)?{semanticRerank:!0}:{},output:r})),l=jt(e);c.encoding&&(l["content-encoding"]=c.encoding);let d=await fetch(`${e.origin}/connect/optimize-output`,{method:"POST",headers:l,body:c.body,signal:s.signal});if(!d.ok)return(d.status===401||d.status===403)&&await Oj(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)}},l0=async(e="claude")=>{let t=await Hi();if(e!=="cursor"&&pj(t))return 0;let n=e==="cursor"?uj(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Vy(n,e);if(e==="cursor"){let a=fj(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Vy=async(e,t="claude",n)=>{await Or(),await BE(t);let r=kj(),o=await tt(),a=o&&{...o,metadata:sj(o.metadata,t)},s=cj(t);return Cj(e,{optimize:(i,c,l,d,u)=>Tj(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await s0(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>du(i,r),beacon:(i,c)=>mc(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Dr.maxChars,digestCommand:Fx,tee:s.tee,mediumBand:aj.has(t),finalizeOutput:n})};var d0=async()=>0;import{spawn as Mj}from"node:child_process";import{homedir as Bj}from"node:os";import{join as Fj}from"node:path";import{chmod as _j,readFile as Pj,rm as u0,writeFile as Dj}from"node:fs/promises";import{join as Lj}from"node:path";var Ky=()=>Lj(Q(),"sso-gate.json"),Nj=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))},Ga=async()=>{try{let e=JSON.parse(await Pj(Ky(),"utf-8"));return Nj(e)?e:null}catch{return null}},$j=0,yu=async e=>{await Qe();let t=Ky(),n=`${t}.${process.pid}.${$j++}.tmp`;try{await Dj(n,`${JSON.stringify(e)}
|
|
702
|
+
`,{mode:384}),await _j(n,384),await he(n,t)}catch(r){throw await u0(n,{force:!0}).catch(()=>{}),r}},p0=async()=>{await u0(Ky(),{force:!0}).catch(()=>{})},f0=e=>{if(!e||!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}};var Wj=3e4,Uj=5*6e4,Hj=30*6e4,Gj=e=>{let t={};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--sso":t.sso=o();break;case"--gateway":t.gateway=o();break;case"--team":t.team=o();break;case"--session-start":t.sessionStart=!0;break;default:throw new Error("invalid SSO gate arguments")}}if(!t.sso)throw new Error("missing --sso");return t},Vj=()=>Fj(Bj(),".claude","settings.json"),Kj=async e=>{try{let n=(await M(Vj())).env;if(!n)return!1;let r=rn(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}},jj=async e=>{await rr.apply(e,{dryRun:!1})},Zj=()=>{let{command:e,args:t}=or("__anyray-sso-poll");return{exe:e,args:t}},Yj=()=>{let{exe:e,args:t}=Zj(),n=Mj(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))}}},Jj=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},m0=(e,t,n,r)=>Oe({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},h0=e=>`Anyray: one-time sign-in required to use AI tools on this device.
|
|
703
703
|
1. Open ${e.verificationUriComplete}
|
|
704
704
|
2. Confirm code ${e.userCode}
|
|
705
705
|
Your prompt was not sent \u2014 complete sign-in, then resubmit it.
|
|
706
|
-
`,
|
|
706
|
+
`,jy=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
|
|
707
707
|
`:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
|
|
708
708
|
`:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
|
|
709
|
-
`,
|
|
710
|
-
`))}let ae;await
|
|
711
|
-
`}catch{return}},
|
|
709
|
+
`,Xj=e=>Math.min(Uj,Wj*2**Math.max(0,e-1)),zj=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?Hj:Xj(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Oo=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??P,o=t.saveProfile??le,a=t.loadDevKey??Be,s=t.readGateState??Ga,i=t.writeGateState??yu,c=t.isProcessAlive??f0,l=t.startGrant??bd,d=t.verify??qt,u=t.routingIntact??Kj,f=t.applyClaudeCode??jj,p=t.maybeSpawnRefresh??Or,m=t.recordMint??La,h=t.reserveMint??vo,g=t.spawnPoller??Yj,y=t.openBrowser??Fa;try{let w=Et(e.sso);if(!w)return{exitCode:0};let b=await r(),k=await s(),C=b.enrolledCert?await a():void 0,S=Jj(b),E=!!(b.enrolledCert&&C)&&Number.isFinite(S)&&S>n(),I=e.gateway??b.gateway;if(E&&b.enrolledCert&&C&&I){let K=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(K)&&K>n()&&b.clientKey){let ie=m0(I,b,e.team,b.clientKey);return await u(ie)?(K-n()<=Lh()&&await p(),{exitCode:0}):(await f(ie),Va(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
|
|
710
|
+
`))}let ae;await h();let Z=(t.resolveMachineUuid??Wt)()||void 0;try{ae=await d(I,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:Z})}catch(ie){if(!(ie instanceof ct))return Va(e,jy("gateway-unreachable",w.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(ae){let ie={...b,gateway:I,name:ae.user,team:e.team??ae.team??b.team,clientKey:ae.key,clientKeyExpiresAt:ae.expiresAt,authMode:"subscription"};return await o(ie),await m({expiresAt:ae.expiresAt}),await f(m0(I,ie,e.team,ae.key)),{exitCode:0}}}if(k?.status==="pending"&&(k.userCode&&k.verificationUriComplete)&&(k.grantExpiresAt??0)>n()&&c(k.pollerPid)){if(e.sessionStart&&k.verificationUriComplete)try{y(k.verificationUriComplete)}catch{}return Va(e,h0(k))}if(k){let K=zj(k,n());if(K)return Va(e,jy(K,w.cpOrigin))}let O;try{O=await l({cpOrigin:w.cpOrigin,tenantId:w.tenantId,gatewayUrl:e.gateway,now:n})}catch(K){let oe=K instanceof wo?K.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:k?.lastFailure===oe?(k.failureCount??0)+1:1,lastFailure:oe}),Va(e,jy(oe,w.cpOrigin))}let T={v:1,status:"pending",userCode:O.userCode,verificationUriComplete:O.verificationUriComplete,grantExpiresAt:O.grantExpiresAt,startedAt:O.startedAt,lastAttemptAt:n(),failureCount:0};await i(T);let U=g(),z={...T,pollerPid:U.pid};if(await i(z),U.handoff({deviceCode:O.deviceCode,privateKeyPem:O.privateKeyPem,publicKeyPem:O.publicKeyPem,cpOrigin:O.cpOrigin,tenantId:O.tenantId,intervalMs:O.intervalMs,grantExpiresAt:O.grantExpiresAt,startedAt:O.startedAt,gatewayUrl:O.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{y(O.verificationUriComplete)}catch{}return Va(e,h0(z))}catch{return{exitCode:0}}},qj=async()=>{try{for await(let e of process.stdin);}catch{}},y0=async e=>{await qj();try{let t=await Oo(Gj(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var Qj=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},eZ=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??xr)();if(!r)return;let o=await(t.ssoGate??Oo)({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})}
|
|
711
|
+
`}catch{return}},tZ=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},nZ=()=>{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")}},rZ=(e,t)=>{let n=t.minChars??Bi.minChars,r={maxChars:Math.min(Dr.maxChars,n)},o=du(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},g0=async()=>{let e=await tZ(),t=await eZ(e);t&&process.stdout.write(t);let n=nZ(),r=await tt();return await Qj(e,{isPaste:o=>uu(o,n),measure:o=>rZ(o,n),beacon:o=>mc(r,"prompt",o)}),0};import{spawn as oZ}from"node:child_process";var w0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),aZ=/[|&;<>`$()\n]/,b0=e=>{if(aZ.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},sZ=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!w0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!w0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(ep)||!t.isRecognized(o)||b0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},iZ=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?b0(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
|
|
712
712
|
`),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
|
|
713
|
-
`),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},
|
|
713
|
+
`),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},cZ=16*1024*1024,lZ=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=oZ(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>cZ){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)}}),dZ=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Vy(n,"cursor");return typeof r=="string"?r:t},A0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return iZ(t,{exec:lZ,trim:dZ,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},C0=async()=>{let e=await Hi();if(process.platform==="win32")return 0;let t=sZ(e,{isRecognized:n=>Dy(n)!==null||Mx(n),wrap:n=>Ot(ep,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as uZ}from"node:crypto";import{homedir as k0}from"node:os";import{extname as pZ,isAbsolute as fZ,join as Zy,resolve as Gi,sep as v0}from"node:path";import{chmod as mZ,readFile as hZ,stat as R0,unlink as yZ,writeFile as gZ}from"node:fs/promises";var Jy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wZ=16*1024,S0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],bZ=["pattern","query","regex","search"],AZ=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".pdf",".zip",".gz",".tar",".tgz",".woff",".woff2",".ttf",".otf",".mp3",".mp4",".mov",".wasm",".so",".dylib",".dll",".exe",".bin",".parquet",".sqlite",".db"]),CZ=720*60*1e3,kZ=512,Yy=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},vZ=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],E0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(v0)?n:n+v0)),SZ=(e,t,n)=>fZ(e)?[Gi(e)]:[...new Set([Gi(t,e),...n.map(r=>Gi(r,e))])],I0=(e,t,n)=>uZ("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),x0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),EZ=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!Jy(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!Jy(o))return"";let a=vZ(n.workspace_roots).map(d=>Gi(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,bZ);if(!d)return"";let u=Yy(o,S0);return u&&!E0(Gi(s,u),a)||!await t.remember(I0(i,"Grep",d))?"":x0(`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,S0);if(!c||AZ.has(pZ(c).toLowerCase()))return"";let l=await t.resolveFile(SZ(c,s,a));return!l||l.bytes<wZ||!E0(l.path,a)||!await t.remember(I0(i,"Read",l.path))?"":x0(`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.`)},IZ=async e=>{for(let t of e)try{let n=await R0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},xZ=async()=>{let e=Zy(k0(),".anyray");try{if((await R0(e)).isDirectory())return Zy(e,"cursor-redirects.json")}catch{}return Zy(k0(),".anyray-cursor-redirects.json")},RZ=async e=>{let t;try{let n=await xZ(),r=Date.now(),o={};try{let s=JSON.parse(await hZ(n,"utf-8"));if(s?.v===1&&Jy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=CZ&&(o[i]=c)}catch{}if(o[e]!==void 0)return!1;o[e]=r;let a=Object.entries(o).sort((s,i)=>i[1]-s[1]).slice(0,kZ);return t=`${n}.${process.pid}.tmp`,await gZ(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await mZ(t,384),await he(t,n),!0}catch{if(t)try{await yZ(t)}catch{}return!1}},O0=async()=>{let e=await Hi(),t="";try{t=await EZ(e,{resolveFile:IZ,remember:RZ})}catch{t=""}return t&&process.stdout.write(t),0};import{execFileSync as $Y}from"node:child_process";import{createReadStream as OZ}from"node:fs";import{spawnSync as U0}from"node:child_process";import{createHash as TZ}from"node:crypto";import{access as H0,chmod as qy,copyFile as _Z,lstat as PZ,mkdir as DZ,mkdtemp as G0,readFile as Cu,rename as LZ,rm as Nr,stat as NZ,writeFile as $Z}from"node:fs/promises";import{constants as V0}from"node:fs";import{platform as Za,tmpdir as MZ}from"node:os";import{dirname as BZ,isAbsolute as FZ,join as wu}from"node:path";import{z as $e}from"zod";var WZ="fleetd-installer-v4.89.2",T0=`https://github.com/anyrayHQ/install/releases/download/${WZ}`,UZ=1e4,HZ=1e4,_0=31,GZ=1500,K0=20*1024,Xy=20,VZ="0.25",KZ="/var/tmp",ja="/Library/LaunchDaemons/com.fleetdm.orbit.plist",bu="/etc/default/orbit",Ki="/opt/orbit/anyray-enroll-secret.txt",j0="/opt/orbit/secret-orbit-node-key.txt",jZ="/opt/orbit/bin/orbit/orbit",ji="C:\\Program Files\\Orbit",ZZ=`${ji}\\bin\\orbit`,Z0=`${ji}\\secret-orbit-node-key.txt`,Vi=`${ji}\\secret.txt`,YZ=`${ji}\\fleet_url.txt`,Y0=`${ji}\\anyray-managed.txt`,Au="Fleet osquery",Qy="C:\\Windows\\System32\\sc.exe",rg="C:\\Windows\\System32\\whoami.exe",gu="C:\\Windows\\System32\\icacls.exe",JZ="C:\\Windows\\System32\\msiexec.exe",eg="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",P0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],XZ=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],zZ=`anyray-connect endpoint install
|
|
714
714
|
|
|
715
715
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
716
716
|
|
|
@@ -718,11 +718,11 @@ Supported on macOS, Linux and Windows.
|
|
|
718
718
|
|
|
719
719
|
The command uses the current seat's stored gateway key. Administrator access is
|
|
720
720
|
required: on macOS and Linux Connect asks through sudo once when /dev/tty is
|
|
721
|
-
available; on Windows, run it from a shell started as Administrator.`,
|
|
722
|
-
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Ki)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},
|
|
723
|
-
`&&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},
|
|
721
|
+
available; on Windows, run it from a shell started as Administrator.`,og=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),J0=(e,t=Za())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),X0=(e,t=Za(),n=!1)=>(og(e)||n)&&t!=="win32",de=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},qZ=$e.object({kind:$e.enum(["pkg","deb","rpm","msi"]),path:$e.string().min(1).refine(FZ),sha256:$e.string().regex(/^[0-9a-f]{64}$/)}).strict(),QZ=$e.object({action:$e.literal("restart"),os:$e.enum(["darwin","linux","win32"])}).strict(),eY=$e.object({action:$e.literal("configure"),os:$e.enum(["darwin","linux","win32"]),fleetUrl:$e.string().min(1).max(2048),enrollSecret:$e.string().min(1).max(4096),package:qZ.optional()}).strict(),tY=$e.discriminatedUnion("action",[QZ,eY]),Zi=(e,t)=>{let n=U0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},ag=async e=>{try{return await H0(e,V0.F_OK),!0}catch{return!1}},nY=async e=>{try{let t=await NZ(e);return t.isFile()&&t.size>0}catch{return!1}},sg=(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}},zy=(e,t)=>sg(e,t)!==null,D0=e=>e==="win32"?Vi:Ki,rY=e=>e==="win32"?Z0:j0,oY=e=>zy(e,"ORBIT_FLEET_URL")&&zy(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Ki}</string>`)&&!zy(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),aY=e=>{let t=(n,r)=>e.split(`
|
|
722
|
+
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Ki)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},tg=(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()},z0=e=>{let t=e(Qy,["qc",Au,"8192"]);return t.status===0?t.stdout:""},ng=e=>{let t=e(eg,XZ(Au)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},sY=async e=>{try{return e==="win32"?tg(e,z0(Zi)):tg(e,await Cu(e==="darwin"?ja:bu,"utf8"))}catch{return}},iY=async e=>{try{if(e==="win32")return await ag(Y0)&&tg(e,z0(Zi))!==void 0;let n=await Cu(e==="darwin"?ja:bu,"utf8");return e==="darwin"?oY(n):aY(n)}catch{return!1}},q0=async(e,t={})=>{let n=t.exists??ag,r=t.command??Zi,o,a="absent";if(e==="win32")a=ng(r),o=await n(ZZ)&&a!=="absent";else{let l=e==="darwin"?await n(ja):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(jZ)&&l}let s=await(t.configured??iY)(e),i=await(t.hasNodeKey??(()=>nY(rY(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}},cY=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Q0=(e,t)=>{let n=sg(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]===`
|
|
723
|
+
`&&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},lY=(e,t)=>{let n=Q0(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},L0=(e,t,n)=>{let r=`
|
|
724
724
|
<key>${t}</key>
|
|
725
|
-
<string>${
|
|
725
|
+
<string>${cY(n)}</string>`,o=Q0(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=sg(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new de("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)},dY=(e,t,n=Ki)=>{let r=lY(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=L0(r,"ORBIT_FLEET_URL",t),L0(r,"ORBIT_ENROLL_SECRET_PATH",n)},uY=(e,t,n=Ki)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
|
|
726
726
|
`).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(`
|
|
727
727
|
`).trimEnd()}
|
|
728
728
|
|
|
@@ -732,17 +732,17 @@ available; on Windows, run it from a shell started as Administrator.`,rg=e=>!!(e
|
|
|
732
732
|
# file, never in this world-readable one.
|
|
733
733
|
ORBIT_FLEET_URL=${t}
|
|
734
734
|
ORBIT_ENROLL_SECRET_PATH=${n}
|
|
735
|
-
`},
|
|
736
|
-
`,384);e.os!=="win32"&&await
|
|
737
|
-
`,384),e.os==="win32"&&
|
|
738
|
-
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??
|
|
739
|
-
sudo anyray-connect endpoint install`),"deferred"},
|
|
740
|
-
`;if(Buffer.byteLength(t)>
|
|
741
|
-
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Za()==="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}},eR=async(e={},t={})=>{let n=t.os??Za();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new de("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??X0)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??B0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??oY)(r);if(!l||!d||u===void 0)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};let f=await(t.fetchEnrollment??L0)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};N("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new de("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??B0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new de("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??L0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>fY(r)))();if(i=await(t.stagePackage??yY)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${sg(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??PY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},ig=e=>e instanceof de?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",tR=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return A(JZ),0;if(e.length!==1||e[0]!=="install")return R("Usage: anyray-connect endpoint install"),1;try{let t=await eR();return t.message&&(t.outcome==="installed"?B(t.message):N(t.message)),0}catch(t){return R(ig(t)),1}},DY=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>G0)throw new de("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new de("The privileged endpoint plan is malformed.")}let r=QZ.safeParse(n);if(!r.success||r.data.os!==Za()||r.data.action==="configure"&&!q0(r.data.fleetUrl))throw new de("The privileged endpoint plan is invalid.");return r.data},nR=async e=>{if((process.getuid?.()??-1)!==0)return R("The privileged endpoint step must run as root."),1;if(e.length!==0)return R("The privileged endpoint step does not accept arguments."),1;try{return await Q0(await DY()),0}catch(t){return R(ig(t)),1}},rR=async(e,t=eR)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?B(n.message):N(n.message)),n.outcome}catch(n){N(`Endpoint agent: ${ig(n)} Tool routing remains configured.`);return}};var NY=new Set(["darwin","win32","linux"]),$Y=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),MY=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!$Y.has(t)},oR=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},aR=async e=>{try{if(!NY.has(e.platform)||e.isUserSession?.()===!1)return 0;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return 0;let n=e.readManagedEnrollment().enrollmentUrl;return n?await e.runApply(["--enroll",n,"--yes"],t.revertedTools??[]):0}catch{return 1}},sR=e=>({platform:process.platform,readManagedEnrollment:py,loadProfile:P,isUserSession:()=>{try{if(process.platform==="win32"){let t=LY(ng,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return MY(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var Yi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},cg=e=>typeof e=="string"&&e.trim()?e.trim():void 0,BY=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Yi(n,"deviceCode"),o=Yi(n,"privateKeyPem"),a=Yi(n,"publicKeyPem"),s=Yi(n,"cpOrigin"),i=Yi(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=cg(n.gatewayUrl),f=cg(n.gatewayOverride),p=cg(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}},FY=e=>new Promise(t=>setTimeout(t,e)),WY=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})},UY=async(e,t={})=>{let n=t.poll??Ad,r=t.verify??qt,o=t.loadProfile??P,a=t.saveProfile??le,s=t.saveDevKey??ec,i=t.readGateState??Ga,c=t.writeGateState??yu,l=t.clearGateState??d0,d=t.sleep??FY,u=t.now??Date.now,f=t.recordMint??La,p=t.reserveMint??vo,m=t.applyClaudeCode??(async I=>{await rr.apply(I,{dryRun:!1})}),y=I=>WY(I,{readGateState:i,writeGateState:c,now:u}),g={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},h;try{h=await n(g,{gatewayUrl:e.gatewayOverride})}catch(I){let O=I instanceof Bt?I.kind:"cp-unreachable";return await y(O),O}let w=e.gatewayOverride??h.gatewayUrl,b=await o(),k={...b,gateway:w??b.gateway,name:h.cert.payload.user||b.name,team:e.team??h.cert.payload.team??b.team,enrolledCert:h.cert,enrolledCertExpiry:h.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(h.privateKeyPem),await a(k)}catch{return"failed"}if(!w)return await y("gateway-unreachable"),"gateway-unreachable";let C;await p();let S=(t.resolveMachineUuid??Wt)()||void 0;for(let I=0;I<3;I++)try{C=await r(w,h.cert,h.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(O){if(O instanceof ct||I===2)break;await d(1e3)}if(!C)return await y("gateway-unreachable"),"gateway-unreachable";let E={...k,gateway:w,name:C.user,team:e.team??C.team??k.team,clientKey:C.key,clientKeyExpiresAt:C.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:C.expiresAt});let I=Oe({origin:w,clientKey:C.key,subscription:!0,user:E.name,team:E.team});return await m(I),await l(),"enrolled"}catch{return await y("gateway-unreachable"),"failed"}},HY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},iR=async()=>{let e=BY(await HY());if(e)try{await UY(e)}catch{}return 0};var GY=1e4,lg=/^[\w.:-]{1,64}$/,Ut=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},dg=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,cR=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),GY);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new Ut("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},VY=e=>{let t=dg(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}},KY=e=>{let t=dg(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&lg.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&lg.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},jY=e=>{let t=dg(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!be(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!lg.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}}},ZY=e=>new Promise(t=>setTimeout(t,e)),YY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Ut("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}A("Available teams:"),e.forEach((i,c)=>A(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Na("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Ut("invalid-team","Choose one of the teams shown above.");return s},JY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??ZY,a=t.loadProfile??P,s=t.saveProfile??le,i=t.clearDevKey??os,c=t.chooseTeam??YY,l=t.apply??(async h=>{await rr.apply(h,{dryRun:!1})}),d=t.log??N,u=await a(),f=Tr(e.gateway,u),p=await cR(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),m=VY(p.body);if(p.status!==200||!m)throw new Ut("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${m.browser_url}`),d(`Enter this code in the browser: ${m.user_code}`),(t.openBrowser??Fa)(m.browser_url);let y=r()+m.expires_in*1e3,g=e.team?.trim()||void 0;for(;r()<y;){let h=await cR(`${f}/sso/cli/poll/${encodeURIComponent(m.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":m.poll_secret,...g?{"x-anyray-team":g}:{}}},n);if(h.status===202){await o(m.interval*1e3);continue}if(h.status===401)throw new Ut("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(h.status===410)throw new Ut("expired","SSO login expired before it completed. Run anyray-connect login again.");let w=KY(h.body);if(h.status===200&&w){if(g&&!w.teams.includes(g))throw new Ut("invalid-team",`Team ${g} is not available for this account.`);g=await c(w.teams,w.default_team,e.interactive??mt());continue}let b=jY(h.body);if(h.status!==200||!b)throw new Ut("login-failed","SSO login could not be completed.");let k={...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(k),await l(Oe({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Ut("expired","SSO login expired before it completed. Run anyray-connect login again.")},XY=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
735
|
+
`},eR=e=>{if(/[\u0000-\u0020\u007f]/.test(e)||/["'`\\^<>|{}]/.test(e))return!1;try{let t=new URL(e);return t.username||t.password?!1:t.protocol==="https:"?!0:t.protocol==="http:"&&(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1")}catch{return!1}},pY=$e.object({code:$e.string().min(1).optional(),message:$e.string().min(1).optional()}).passthrough(),N0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},fY=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=pY.safeParse(t);if(!r.success)return n;let o=N0(r.data.message??""),a=N0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},$0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??HZ),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":ke},body:"{}",signal:r.signal})}catch{throw new de("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new de("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new de(fY(a.status,c))}let s;try{s=await a.json()}catch{throw new de("The gateway returned malformed endpoint enrollment data.")}let i=$e.object({fleetUrl:$e.string().min(1).max(2048),enrollSecret:$e.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!eR(i.data.fleetUrl))throw new de("The gateway returned invalid endpoint enrollment data.");return i.data},mY=async(e={})=>{let t=e.exists??ag;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 de("Linux endpoint installation requires either dpkg or rpm.")},hY=async e=>e==="darwin"?"pkg":e==="win32"?"msi":mY(),ig=e=>`fleetd.${e}`,yY=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",gY=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),UZ);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},wY=async(e,t={})=>{let n=ig(e),r=t.fetchResponse??fetch,o;try{o=await gY(`${T0}/SHA256SUMS`,r)}catch{throw new de("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new de(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=wy(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await G0(wu(MZ(),"anyray-endpoint-")),i=wu(s,n);try{await qy(s,448),await(t.download??Cy)(`${T0}/${n}`,i,a)}catch(c){if(await Nr(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Li&&c.status===404)return;throw new de("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Nr(s,{recursive:!0,force:!0})}},bY=async(e,t,n)=>{await DZ(BZ(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Nr(r,{force:!0});try{await $Z(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await LZ(r,e)}catch(o){throw await Nr(r,{force:!0}).catch(()=>{}),o}},M0=async e=>{let t=TZ("sha256");for await(let n of OZ(e))t.update(n);return t.digest("hex")},AY=async(e,t={})=>{let n=await PZ(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new de("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await M0(e.path)!==e.sha256)throw new de("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await G0(wu(KZ,"anyray-endpoint-root-")),o=wu(r,ig(e.kind));try{if(await qy(r,448),await _Z(e.path,o),await qy(o,384),await M0(o)!==e.sha256)throw new de("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Nr(r,{recursive:!0,force:!0})}}catch(a){throw await Nr(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ka=(e,t)=>{if(e.status!==0)throw new de(t)},B0="com.fleetdm.fleetd.config",CY="com.fleetdm.fleetd.enroll.secret",kY=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",j0],vY=[YZ,Z0],SY=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(B0))throw new de(`This machine already receives its endpoint configuration from an MDM profile (${B0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},F0=async(e,t,n)=>{let r=n.removeFile??(o=>Nr(o,{force:!0}));for(let o of e==="win32"?vY:kY)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",CY,"/Library/Keychains/System.keychain"])},EY=e=>{e(gu,[Vi,"/inheritance:r"]),e(gu,[Vi,"/grant:r","*S-1-5-18:(F)"]),e(gu,[Vi,"/grant:r","*S-1-5-32-544:(F)"]),e(gu,[Vi,"/remove:g","*S-1-5-32-545"])},IY=(e,t,n)=>{if(e.kind==="pkg"){Ka(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ka(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ka(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ka(t(JZ,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},xY=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<Xy;r++){if(n=t("/bin/launchctl",["bootstrap","system",ja]),n.status===0)return;t("/bin/sleep",[VZ])}throw new de(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(Qy,["stop",Au]);for(let n=0;n<Xy;n++){let r=ng(t);if(r==="Stopped"||r==="absent")break;t(eg,P0)}for(let n=0;n<Xy;n++){if(t(Qy,["start",Au]).status===0||ng(t)==="Running")return;t(eg,P0)}throw new de("Orbit was configured, but the Windows service could not be started.")}Ka(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ka(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},RY=e=>new Promise(t=>setTimeout(t,e)),tR=async(e,t={})=>{let n=t.command??Zi,r=t.readText??(c=>Cu(c,"utf8")),o=t.writeText??bY,a=t.removeSecret??(()=>Nr(D0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&SY(n),e.package&&!yY(e.os,e.package.kind))throw new de("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new de("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await F0(e.os,n,t),e.package){let d=await(t.preparePackage??AY)(e.package);i=d.cleanup,IY(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(ja);await o(ja,dY(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(bu);await o(bu,uY(d,e.fleetUrl),420)}else await o(Y0,`anyray
|
|
736
|
+
`,384);e.os!=="win32"&&await F0(e.os,n,t),await o(D0(e.os),`${e.enrollSecret}
|
|
737
|
+
`,384),e.os==="win32"&&EY(n),s=e.os!=="win32"}xY(e.os,n);let c=t.checkIn??(async d=>{let u=await q0(d);return u.running&&u.checkedIn}),l=t.wait??RY;for(let d=0;d<(t.attempts??_0);d++){if(await c(e.os))return;d+1<(t.attempts??_0)&&await l(GZ)}throw new de("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(()=>{})}},OY=async()=>{try{return await H0("/dev/tty",V0.R_OK),!0}catch{return!1}},TY=12288,_Y=e=>{let t=e(rg,["/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>=TY},PY=async(e,t={})=>{if((t.os??Za())==="win32")return(t.elevated??(()=>_Y(t.command??Zi)))()?(await e(),"direct"):((t.print??A)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
738
|
+
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??OY)()){if(await(t.reexec??(async()=>1))()!==0)throw new de("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??A)(`Administrator access is required. Run:
|
|
739
|
+
sudo anyray-connect endpoint install`),"deferred"},DY=async e=>{let t=`${JSON.stringify(e)}
|
|
740
|
+
`;if(Buffer.byteLength(t)>K0)throw new de("The privileged endpoint plan is unexpectedly large.");let n=nn(["__anyray-endpoint-install"]);return U0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},LY=async(e,t={})=>(t.withRoot??PY)(()=>(t.apply??tR)(e),{...t.root,reexec:()=>(t.sudo??DY)(e)}),W0=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 Cu("/etc/passwd","utf8")).split(`
|
|
741
|
+
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Za()==="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}},nR=async(e={},t={})=>{let n=t.os??Za();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new de("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??q0)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??W0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??sY)(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??$0)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};N("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new de("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??W0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new de("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??$0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>hY(r)))();if(i=await(t.stagePackage??wY)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${ig(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??LY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},cg=e=>e instanceof de?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",rR=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return A(zZ),0;if(e.length!==1||e[0]!=="install")return R("Usage: anyray-connect endpoint install"),1;try{let t=await nR();return t.message&&(t.outcome==="installed"?B(t.message):N(t.message)),0}catch(t){return R(cg(t)),1}},NY=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>K0)throw new de("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new de("The privileged endpoint plan is malformed.")}let r=tY.safeParse(n);if(!r.success||r.data.os!==Za()||r.data.action==="configure"&&!eR(r.data.fleetUrl))throw new de("The privileged endpoint plan is invalid.");return r.data},oR=async e=>{if((process.getuid?.()??-1)!==0)return R("The privileged endpoint step must run as root."),1;if(e.length!==0)return R("The privileged endpoint step does not accept arguments."),1;try{return await tR(await NY()),0}catch(t){return R(cg(t)),1}},aR=async(e,t=nR)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?B(n.message):N(n.message)),n.outcome}catch(n){N(`Endpoint agent: ${cg(n)} Tool routing remains configured.`);return}};var MY=new Set(["darwin","win32","linux"]),BY=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),FY=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!BY.has(t)},sR=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},iR=async e=>{try{if(!MY.has(e.platform)||e.isUserSession?.()===!1)return 0;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return 0;let n=e.readManagedEnrollment().enrollmentUrl;return n?await e.runApply(["--enroll",n,"--yes"],t.revertedTools??[]):0}catch{return 1}},cR=e=>({platform:process.platform,readManagedEnrollment:fy,loadProfile:P,isUserSession:()=>{try{if(process.platform==="win32"){let t=$Y(rg,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return FY(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var Yi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},lg=e=>typeof e=="string"&&e.trim()?e.trim():void 0,WY=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Yi(n,"deviceCode"),o=Yi(n,"privateKeyPem"),a=Yi(n,"publicKeyPem"),s=Yi(n,"cpOrigin"),i=Yi(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=lg(n.gatewayUrl),f=lg(n.gatewayOverride),p=lg(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}},UY=e=>new Promise(t=>setTimeout(t,e)),HY=async(e,t)=>{let n=await t.readGateState()??{v:1};await t.writeGateState({v:1,lastAttemptAt:t.now(),failureCount:(n.failureCount??0)+1,lastFailure:e})},GY=async(e,t={})=>{let n=t.poll??Ad,r=t.verify??qt,o=t.loadProfile??P,a=t.saveProfile??le,s=t.saveDevKey??ec,i=t.readGateState??Ga,c=t.writeGateState??yu,l=t.clearGateState??p0,d=t.sleep??UY,u=t.now??Date.now,f=t.recordMint??La,p=t.reserveMint??vo,m=t.applyClaudeCode??(async I=>{await rr.apply(I,{dryRun:!1})}),h=I=>HY(I,{readGateState:i,writeGateState:c,now:u}),g={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},y;try{y=await n(g,{gatewayUrl:e.gatewayOverride})}catch(I){let O=I instanceof Bt?I.kind:"cp-unreachable";return await h(O),O}let w=e.gatewayOverride??y.gatewayUrl,b=await o(),k={...b,gateway:w??b.gateway,name:y.cert.payload.user||b.name,team:e.team??y.cert.payload.team??b.team,enrolledCert:y.cert,enrolledCertExpiry:y.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(y.privateKeyPem),await a(k)}catch{return"failed"}if(!w)return await h("gateway-unreachable"),"gateway-unreachable";let C;await p();let S=(t.resolveMachineUuid??Wt)()||void 0;for(let I=0;I<3;I++)try{C=await r(w,y.cert,y.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(O){if(O instanceof ct||I===2)break;await d(1e3)}if(!C)return await h("gateway-unreachable"),"gateway-unreachable";let E={...k,gateway:w,name:C.user,team:e.team??C.team??k.team,clientKey:C.key,clientKeyExpiresAt:C.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:C.expiresAt});let I=Oe({origin:w,clientKey:C.key,subscription:!0,user:E.name,team:E.team});return await m(I),await l(),"enrolled"}catch{return await h("gateway-unreachable"),"failed"}},VY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},lR=async()=>{let e=WY(await VY());if(e)try{await GY(e)}catch{}return 0};var KY=1e4,dg=/^[\w.:-]{1,64}$/,Ut=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},ug=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,dR=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),KY);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new Ut("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},jY=e=>{let t=ug(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}},ZY=e=>{let t=ug(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&dg.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&dg.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},YY=e=>{let t=ug(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!be(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!dg.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}}},JY=e=>new Promise(t=>setTimeout(t,e)),XY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Ut("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}A("Available teams:"),e.forEach((i,c)=>A(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Na("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Ut("invalid-team","Choose one of the teams shown above.");return s},zY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??JY,a=t.loadProfile??P,s=t.saveProfile??le,i=t.clearDevKey??os,c=t.chooseTeam??XY,l=t.apply??(async y=>{await rr.apply(y,{dryRun:!1})}),d=t.log??N,u=await a(),f=Tr(e.gateway,u),p=await dR(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),m=jY(p.body);if(p.status!==200||!m)throw new Ut("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${m.browser_url}`),d(`Enter this code in the browser: ${m.user_code}`),(t.openBrowser??Fa)(m.browser_url);let h=r()+m.expires_in*1e3,g=e.team?.trim()||void 0;for(;r()<h;){let y=await dR(`${f}/sso/cli/poll/${encodeURIComponent(m.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":m.poll_secret,...g?{"x-anyray-team":g}:{}}},n);if(y.status===202){await o(m.interval*1e3);continue}if(y.status===401)throw new Ut("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new Ut("expired","SSO login expired before it completed. Run anyray-connect login again.");let w=ZY(y.body);if(y.status===200&&w){if(g&&!w.teams.includes(g))throw new Ut("invalid-team",`Team ${g} is not available for this account.`);g=await c(w.teams,w.default_team,e.interactive??mt());continue}let b=YY(y.body);if(y.status!==200||!b)throw new Ut("login-failed","SSO login could not be completed.");let k={...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(k),await l(Oe({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Ut("expired","SSO login expired before it completed. Run anyray-connect login again.")},qY=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
742
742
|
|
|
743
743
|
Start browser SSO, choose a team, mint a personal gateway key, and configure
|
|
744
744
|
the subscription-backed Connect lane. In a non-interactive shell, --team may be
|
|
745
|
-
omitted only when the identity authority supplies a default or sole team.`,
|
|
745
|
+
omitted only when the identity authority supplies a default or sole team.`,uR=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return A(qY),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return R(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return R(`unknown login option: ${a}`),1}try{let o=await zY({gateway:n,team:r},t);return B(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof ft)throw o;return R(o instanceof Ut?o.message:"SSO login failed."),1}};var pR=`anyray-connect update [--check] [--auto on|off] [--json]
|
|
746
746
|
|
|
747
747
|
Keep this machine's anyray-connect binary on the published release. Runs
|
|
748
748
|
automatically about every 30 minutes; this command forces it now.
|
|
@@ -753,34 +753,34 @@ Options:
|
|
|
753
753
|
Off still accepts a release the Anyray team marks mandatory.
|
|
754
754
|
--json Emit the result as JSON.
|
|
755
755
|
--help Show this help.
|
|
756
|
-
`,
|
|
756
|
+
`,QY=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},eJ=e=>{switch(e.outcome){case"current":return`Already on the published version (${e.current}).`;case"available":return`Version ${e.latest} is published; this machine is on ${e.current}.`;case"updated":return`Updated ${e.current} \u2192 ${e.latest}. New commands run it immediately.`;case"migrated":return`Installed the managed ${e.latest} binary at ${e.managedPath}.`;case"migration-available":return`Version ${e.latest} will migrate this npm runtime to the managed standalone binary.`;case"migration-deferred":return`The published standalone binary (${e.latest}) is older than this npm runtime (${e.current}); migration was deferred.`;case"disabled":return`Automatic updates are off. Version ${e.latest} is published; this machine is on ${e.current}.`;case"fleet-directed":return"Your organization applies Connect updates centrally. This machine does not update on its own; an administrator pushes new versions.";case"fleet-off":return"Your organization manages Connect updates outside Anyray. This machine does not download binaries; new versions arrive through your own deployment tooling.";case"unmanaged":return"This copy is not an Anyray-managed or npm runtime, so it updates elsewhere.";case"container":return"Self-update is skipped inside a container \u2014 it updates by rebuild, not by download-and-swap.";case"platform-unsupported":return"Self-update is unavailable because this platform has no published standalone binary.";case"unavailable":return"Could not reach the release feed to check for a newer version.";case"failed":return`Could not install ${e.latest??"the published version"} \u2014 staying on ${e.current}.`}},fR=async e=>{let t;try{t=QY(e)}catch(o){return R(o.message),process.stderr.write(pR),1}if(t.help)return process.stdout.write(pR),0;if(t.auto!==void 0){let o=await P();if(o.autoUpdate!==!1!==t.auto&&await le({...o,autoUpdate:t.auto}),t.json||(B(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||A("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!t.auto)return t.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
|
|
757
757
|
`),0}let n=await Ha({checkOnly:t.check,force:!t.check,allowNpmMigration:!0,initiator:"human"});if(t.json){let o=await Io();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state,fleetUpdateMode:o.fleetMode},null,2)}
|
|
758
|
-
`),n.outcome==="failed"?1:0}let r=
|
|
758
|
+
`),n.outcome==="failed"?1:0}let r=eJ(n);switch(n.outcome){case"updated":case"migrated":B(r);break;case"current":B(r);break;case"available":case"migration-available":A(r),t.check&&A(`Run ${j("anyray-connect update")} to install it.`);break;case"migration-deferred":_(r),A(v("Use the newer npm runtime until that standalone release is published."));break;case"disabled":_(r),A(`Run ${j("anyray-connect update")} to install it now, or ${j("--auto on")} to resume.`);break;case"fleet-directed":case"fleet-off":A(r),A(v("Ask your Anyray administrator if you need a newer version."));break;case"unmanaged":A(r),A(v("A copy your IT team placed is theirs to roll."));break;case"container":A(r);break;case"platform-unsupported":_(r),A(v("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":_(r);break;case"failed":return R(r),1}return 0};var tJ=3e3,mR=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>Ay(tJ)),o=e.updateStatus??Io;t(`anyray-connect ${ke}
|
|
759
759
|
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&Ua(a,ke)>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: ${ke} \u2192 ${a}
|
|
760
760
|
${i}
|
|
761
|
-
`)}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
|
|
762
|
-
`),0};import
|
|
763
|
-
`)},
|
|
764
|
-
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,
|
|
761
|
+
`)}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 nJ=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},rJ=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),oJ=async(e={})=>{try{let t=await(e.readBootstrap??xr)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??Qt)().catch(()=>{});let n=await(e.loadProfile??P)();if(be(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Oo)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??P)(),be(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Ga)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!nJ(a)||!rJ(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"}}},hR=async(e={})=>{let t=await oJ(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
762
|
+
`),0};import aJ from"node:path";var sJ="2025-06-18",iJ={name:"anyray",version:"1"},yR={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}},cJ=20,gR={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}},kR=cy,lJ=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,kR)},dJ=e=>e==="paths"||e==="lines"||e==="full"?e:"full",wR={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-${kR}). 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}},bR={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}},uJ=8,pJ=3,AR={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}},fJ=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(`
|
|
763
|
+
`)},mJ=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
764
|
+
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,uJ).map(([a,s])=>{let i=s.slice(0,pJ).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
765
765
|
`)});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(`
|
|
766
|
-
`)},Ae=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),
|
|
766
|
+
`)},Ae=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),pg=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),CR=e=>e?.name??"error",ye=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
|
|
767
767
|
|
|
768
768
|
[anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
|
|
769
769
|
|
|
770
770
|
[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(`
|
|
771
|
-
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},
|
|
772
|
-
`+
|
|
773
|
-
${m.content}`))}return Ae(n??null,ye(m.content))}if(a.name===
|
|
774
|
-
`)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let m;try{m=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let
|
|
775
|
-
`))>=0;){let m=u.slice(0,p);u=u.slice(p+1),await l(m)}}u.trim()&&await l(u)}catch(f){console.error("anyray mcp: stdin error",
|
|
771
|
+
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},hJ=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 Ae(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:sJ,capabilities:{tools:{}},serverInfo:iJ});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Ae(n??null,{});case"tools/list":{let a=[yR,gR];t.advertiseContextTools!==!1&&a.push(wR,bR);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(AR),Ae(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===yR.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Ae(n??null,ye("handle is required",!0));let c=g=>{if(g!==void 0)return typeof g!="number"||!Number.isFinite(g)?null:Math.max(Math.round(g),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return Ae(n??null,ye("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return Ae(n??null,ye("grep must be non-empty",!0));if(s.grep.length>256)return Ae(n??null,ye("grep is limited to 256 characters",!0));u=s.grep}let f=l!==void 0||d!==void 0||u!==void 0,p=Wy(i);if(p){let g=await Uy(p);if(u!==void 0)return Ae(n??null,ye(`${i} is a local hook-tee file, not a stash handle, and grep is not supported on these \u2014 re-call with startLine/endLine, or Read ${g??"the path in the footer"} directly.`,!0));let y=t.readTee?await t.readTee(p,{startLine:l,endLine:d}).catch(b=>({ok:!1,content:"",path:g??p,lines:0,truncated:!1,message:b instanceof Error?b.message:"tee read failed"})):null;if(y?.ok){let b=y.span?`lines ${y.span.startLine}-${y.span.endLine} of ${y.lines}`:`${y.lines} line(s)`,k=y.truncated&&!y.span?.partialLine&&y.span?` Continue with anyray_retrieve(handle="${i}", startLine=${y.span.endLine+1}).`:"";return Ae(n??null,ye(`[anyray: ${i} is a local hook-tee file, not a stash handle \u2014 served ${b} from ${y.teePath??g}.${k} Read that path directly next time.]
|
|
772
|
+
`+y.content))}let w=y!==null;return Ae(n??null,ye(`${i} is a hook-tee file id, not a stash handle`+(w&&g?`, and ${g} is not readable`+(y?.message?` (${y.message})`:"")+". The hook writes these files when it trims a tool output; this one has been swept, or the tee is off. Re-run the command to regenerate its output.":`. Read ${g??"the path in its footer"} directly.`),!0))}let m;try{m=await t.retrieve(i,f?{startLine:l,endLine:d,grep:u}:void 0)}catch(g){m={ok:!1,message:g instanceof Error?g.message:"retrieve failed"}}let h="this gateway does not support partial retrieval yet \u2014 call again without startLine/endLine/grep for the full content";if(!m.ok)return Ae(n??null,ye(m.kind==="slice-unsupported"?h:m.message,!0));if(f&&(m.partial===void 0||typeof m.totalLines!="number"))return Ae(n??null,ye(h,!0));if(m.partial===!0&&typeof m.totalLines=="number"){let g=m.grepMatches!==void 0?`[anyray: partial \u2014 ${m.grepMatches} matching line(s) in lines ${m.startLine}-${m.endLine} of ${m.totalLines}`+(m.grepTruncated?`, windows around the first ${cJ} matches shown \u2014 narrow the range or grep`:"")+` \xB7 retrieve ${i} again with startLine/endLine, another grep, or no params for full]`:`[anyray: partial \u2014 lines ${m.startLine}-${m.endLine} of ${m.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return Ae(n??null,ye(`${g}
|
|
773
|
+
${m.content}`))}return Ae(n??null,ye(m.content))}if(a.name===gR.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Ae(n??null,ye("query is required",!0));let c=typeof s.k=="number"?s.k:void 0,l;try{l=await t.recall(i,c)}catch(d){l={ok:!1,message:d instanceof Error?d.message:"recall failed"}}return Ae(n??null,l.ok?ye(fJ(l.matches)):ye(l.message,!0))}if(a.name===wR.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Ae(n??null,ye("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=lJ(s.maxResults),d=dJ(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 Ae(n??null,u.ok?ye(jI(i,u,d)):ye(u.message??"search failed",!0))}if(a.name===AR.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 Ae(n??null,d.ok?ye(ay(d)):ye(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Ae(n??null,ye("query (or open) is required",!0));let l;try{l=await t.historySearch(c)}catch(d){l={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:d instanceof Error?d.message:"history search failed"}}return Ae(n??null,l.ok?ye(mJ(c,l)):ye(l.message??"history search failed",!0))}if(a.name===bR.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Ae(n??null,ye("path is required",!0));let c={startLine:typeof s.startLine=="number"?s.startLine:void 0,endLine:typeof s.endLine=="number"?s.endLine:void 0},l;try{l=await t.read(i,c)}catch(d){l={ok:!1,content:"",path:i,lines:0,truncated:!1,message:d instanceof Error?d.message:"read failed"}}return Ae(n??null,l.ok?ye(ay(l)):ye(l.message??"read failed",!0))}return pg(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:pg(n??null,-32601,`method not found: ${o}`)}},yJ=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),xd);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:jt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},gJ=(e,t=!0)=>({retrieve:async(n,r)=>Pa(await e(),n,r),recall:async(n,r)=>Rd(await e(),n,r),search:(n,r,o)=>Xd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Ti(n,r),readTee:async(n,r)=>{if(By())return{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"the hook tee is off (ANYRAY_HOOK_TEE=off)"};let o=await Uy(n);return o?{...await Ti(o,{cwd:aJ.dirname(o),...r}),teePath:o}:{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"not a tee id"}},historySearch:n=>JI(n),historyOpen:n=>XI(n),historyAvailable:async()=>await Ba()>0,advertiseContextTools:t,heartbeat:()=>{e().then(yJ).catch(()=>{})}}),vR=async(e="auto",t={})=>{let n=gJ(()=>tt(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,Or().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=f=>{try{o.write(JSON.stringify(f)+`
|
|
774
|
+
`)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let m;try{m=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let h;try{h=await hJ(m,n)}catch(g){console.error("anyray mcp: dispatch error",CR(g)),h=m?.id===void 0?null:pg(m.id,-32603,"internal error")}h&&c(h),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(`
|
|
775
|
+
`))>=0;){let m=u.slice(0,p);u=u.slice(p+1),await l(m)}}u.trim()&&await l(u)}catch(f){console.error("anyray mcp: stdin error",CR(f))}finally{clearInterval(d)}return 0};import{spawn as wJ}from"node:child_process";var bJ=e=>e==="jetbrains"||e==="windsurf"?e:void 0,AJ=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 m=s.indexOf(`
|
|
776
776
|
`);m!==-1?c(s.slice(0,m)):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}})}
|
|
777
|
-
`),!0)}catch{return!1}},
|
|
777
|
+
`),!0)}catch{return!1}},CJ={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},kJ=(e,t,n)=>{let r=new Set(CJ[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}},SR=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
778
778
|
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!id(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
779
|
-
`),1;await(n.refreshIfDue??Qt)().catch(()=>{});let s=await(n.loadProfile??P)(),i=await(n.readBootstrap??xr)().catch(()=>{});if(i){let w=await(n.ssoGate??Oo)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(w.exitCode===2&&w.stderr)return await
|
|
780
|
-
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??yn)():void 0,d=Oe({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=
|
|
781
|
-
`),1;g=n.comSpec??a.ComSpec??"cmd.exe",
|
|
782
|
-
`),w(1)}),k.once("exit",(C,S)=>{w(typeof C=="number"?C:S?1:0)})})};import{randomUUID as
|
|
783
|
-
`,"utf8"),await a.chmod(384),await Yn(a),await a.close(),a=void 0,await(t.publish??he)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await
|
|
779
|
+
`),1;await(n.refreshIfDue??Qt)().catch(()=>{});let s=await(n.loadProfile??P)(),i=await(n.readBootstrap??xr)().catch(()=>{});if(i){let w=await(n.ssoGate??Oo)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(w.exitCode===2&&w.stderr)return await AJ(w.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(w.stderr),1;s=await(n.loadProfile??P)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
|
|
780
|
+
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??yn)():void 0,d=Oe({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=bJ(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",p=(n.hookBinaryIsDurable??ne)(),m=Jv(d,t,{mcpServer:p?Ge("profile"):void 0})[f],h=n.spawn??wJ,g=m.command,y=m.args;if(o==="win32"){if(!m.args.every(w=>w==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(w)))return r.write(`Anyray ACP adapter arguments are invalid.
|
|
781
|
+
`),1;g=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${m.command}" ${m.args.join(" ")}`]}return await new Promise(w=>{let b=kJ(e,a,m.env),k=h(g,y,{env:b,stdio:"inherit",windowsHide:!0});k.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
|
|
782
|
+
`),w(1)}),k.once("exit",(C,S)=>{w(typeof C=="number"?C:S?1:0)})})};import{randomUUID as vJ}from"node:crypto";import{open as SJ,rm as EJ}from"node:fs/promises";import{join as IJ}from"node:path";import{z as Ie}from"zod";var ku=Ie.string().min(1).refine(e=>Number.isFinite(Date.parse(e)),"expected an ISO-8601 timestamp"),xJ=Ie.enum(["reconcile","refresh","repair","status","offboard"]),fg=Ie.union([Ie.literal(0),Ie.literal(1),Ie.literal(2),Ie.literal(3),Ie.literal(4)]),RJ=Ie.enum(["locked","required","recommended","optional"]),vu=Ie.object({schemaVersion:Ie.literal(1),generatedAt:ku,connectVersion:Ie.string().min(1),fleetManaged:Ie.boolean(),enrollment:Ie.object({state:Ie.enum(["enrolled","degraded","broken","none"]),lastRefreshAt:ku.optional(),lastRefreshOutcome:Ie.enum(["ok","failed"]).optional()}).strict(),keyExpiresAt:ku.optional(),tools:Ie.array(Ie.object({id:Ie.string().min(1),tier:RJ,routed:Ie.boolean()}).strict()),lastVerb:Ie.object({verb:xJ,exitCode:fg,at:ku}).strict()}).strict(),ER=(e,t)=>{if(!e)return!1;let n=Date.parse(e);return Number.isFinite(n)&&n>t},OJ=(e,t,n=Date.now())=>{if(!!!(e.clientKey||e.enrolledCert||t))return"none";let o=e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt;return!e.gateway||!e.enrolledCert||!t||!ER(o,n)?"broken":!e.clientKey||e.clientKeyExpiresAt&&!ER(e.clientKeyExpiresAt,n)?"degraded":"enrolled"},TJ=e=>{let t=e.lastSuccessAt,n=e.lastAttemptAt;if(t===void 0&&n===void 0)return{};let r=Math.max(t??0,n??0);return!Number.isFinite(r)||r<=0?{}:{lastRefreshAt:new Date(r).toISOString(),lastRefreshOutcome:t!==void 0&&t>=(n??0)?"ok":"failed"}},IR=(e,t)=>e.fleetToolPolicy?.tiers?.[t]??"required",_J=async(e,t)=>{let n=new Set(e.managedTools??[]),r=new Set(e.revertedTools??[]),o=(e.fleetToolPolicy?.enabled??[]).filter(c=>{let l=IR(e,c);return l==="locked"||l==="required"||l==="recommended"&&!r.has(c)}),a=[...new Set([...n,...o])].sort();if(a.length===0)return[];let s=e.gateway,i=[];for(let c of a){let l=t(c),d=!1;if(l&&s&&l.pointsAt)try{let u=await l.detect();if(!u.installed&&!n.has(c))continue;u.installed&&(d=await l.pointsAt(s))}catch{d=!1}i.push({id:c,tier:IR(e,c),routed:d})}return i},xR=async(e,t={})=>{let n=t.now??Date.now,r=await(t.loadProfile??P)(),o=await(t.loadDevKey??Be)().catch(()=>{}),a=await(t.readRefreshState??It)().catch(()=>({})),s={schemaVersion:1,generatedAt:new Date(n()).toISOString(),connectVersion:ke,fleetManaged:r.anyrayFleetManaged===!0,enrollment:{state:OJ(r,!!o,n()),...TJ(a)},...r.clientKeyExpiresAt&&Number.isFinite(Date.parse(r.clientKeyExpiresAt))?{keyExpiresAt:r.clientKeyExpiresAt}:{},tools:await _J(r,t.toolById??ut),lastVerb:e};return vu.parse(s)},PJ=()=>IJ(Q(),"status.json"),RR=async(e,t={})=>{let n=vu.parse(e);await(t.ensureStateDir??Qe)();let r=PJ(),o=`${r}.${process.pid}.${vJ()}.tmp`,a;try{a=await SJ(o,"wx",384),await a.writeFile(`${JSON.stringify(n,null,2)}
|
|
783
|
+
`,"utf8"),await a.chmod(384),await Yn(a),await a.close(),a=void 0,await(t.publish??he)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await EJ(o,{force:!0}).catch(()=>{}),s}},mg=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var DJ=1e4,Ya=e=>e?.name??"Error",hg=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(DJ)})}catch(o){console.error(`anyray seat offboard report: ${Ya(o)}`)}},LJ=e=>e==="reverted"||e==="queued",Su=async(e={})=>{let t=e.loadProfile??P,n=e.clearDeviceTokenState??Md,r=e.reportSeatOffboarded??hg,o=e.clearEnrollment??tc,a=e.recordManagedTools??Jn,s=e.markSeatOffboarded??nc,i=e.adapterById??ut,c=e.uninstallScheduler??sr,l=e.unitsPresent??Ec,d=e.saveProfile??le,u=await t(),f=u.managedTools??[];await r(u).catch(()=>{}),await n().catch(()=>{});let p=!1,m=!1;try{p=await o()}catch(C){m=!0,console.error(`anyray offboard: clearing enrollment: ${Ya(C)}`)}let h=[],g=[],y=[];for(let C of f){let S=i(C);if(!S){y.push(C);continue}try{let E=await S.revert({dryRun:!1,fullRevert:!0});h.push({id:C,status:E.status}),LJ(E.status)?g.push(C):y.push(C)}catch(E){console.error(`anyray offboard: reverting ${C}: ${Ya(E)}`),y.push(C)}}let w=!0;try{await a(h,!0,!0)}catch(C){w=!1,console.error(`anyray offboard: recording managed tools: ${Ya(C)}`)}let b=y.length===0&&w,k=!1;if(b)try{await s(),k=!0}catch(C){console.error(`anyray offboard: stamping offboard: ${Ya(C)}`)}try{((await t()).refreshSchedulerEnabled||await l())&&await c(),await d({...await t(),refreshSchedulerEnabled:!1})}catch(C){console.error(`anyray offboard: unit teardown: ${Ya(C)}`)}return{reverted:g,unresolved:y,enrollmentCleared:p,credentialHeld:m,recordPersisted:w,offboardMarked:k,ok:y.length===0&&!m&&w&&k}};var ue={success:0,unexpected:1,usage:2,authBroken:3,partial:4},NJ=`Stable non-interactive runtime commands:
|
|
784
784
|
anyray-connect reconcile
|
|
785
785
|
anyray-connect refresh
|
|
786
786
|
anyray-connect repair
|
|
@@ -796,11 +796,12 @@ Exit codes:
|
|
|
796
796
|
1 unexpected error
|
|
797
797
|
2 usage error (unknown flag or argument)
|
|
798
798
|
3 authentication broken; re-enrollment required
|
|
799
|
-
4 partial; the command ran but drift remains
|
|
800
|
-
`)
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
`).map(s=>s.trim()).
|
|
799
|
+
4 partial; the command ran but drift remains`,$J={reconcile:"reconcile",__anyray_reconcile:"reconcile",refresh:"refresh",__anyray_refresh:"refresh",repair:"repair",__anyray_repair:"repair",status:"status",__anyray_status:"status",offboard:"offboard",__anyray_offboard:"offboard"},MJ=e=>e.replaceAll("-","_"),_R=e=>{let t=e[0];if(!t)return;let n=$J[MJ(t)];if(!n)return;let r=e.slice(1);if(n==="status"&&t==="status"&&!r.includes("--json"))return;if(r.length===1&&(r[0]==="--help"||r[0]==="-h"))return{verb:n,help:!0,usageError:!1};let a=n==="status"?t==="status"?r.length===1&&r[0]==="--json":r.length===0||r.length===1&&r[0]==="--json":r.length===0;return{verb:n,help:!1,usageError:!a}},yg=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},BJ=async(e=P,t=Date.now())=>{let n=await e(),r=Date.parse(n.enrolledCertExpiry??n.enrolledCert?.payload.expiresAt??""),o=!!n.enrolledCert&&Number.isFinite(r)&&r>t,a=Date.parse(n.clientKeyExpiresAt??""),s=n.clientKeyExpiresAt!==void 0&&(!Number.isFinite(a)||a<=t);if(!n.gateway)return"auth-broken";if(!n.clientKey||s)return o?"credential-degraded":"auth-broken";try{let i=await Oa(n.gateway,n.clientKey);return await Ta(i)}catch(i){if(Ah(i))return o?"credential-degraded":"auth-broken";throw i}},FJ=e=>e==="auth-broken"?ue.authBroken:e==="credential-degraded"||e.toolsApplied<e.toolsRequested||e.toolsTombstoned.length>0?ue.partial:ue.success,WJ=e=>e.refresh==="not-enrolled"||e.refresh==="cert-expired"||e.refresh==="cert-rejected"?ue.authBroken:e.refresh==="failed"?ue.unexpected:e.partial||e.refresh==="disabled"||e.refresh==="backoff"||e.refresh==="throttled"||e.refresh==="gateway-incompatible"?ue.partial:ue.success,UJ=e=>!e.enrollment.enrolled||e.enrollment.expired===!0||e.verify?.kind==="enrollment-required",OR=async e=>{let t;return{code:await lu({repair:e,quick:!e,silent:!0},{captureReport:r=>t=r}),authBroken:t?UJ(t):!1}},TR=e=>typeof e!="number"&&e.authBroken?ue.authBroken:(typeof e=="number"?e:e.code)===0?ue.success:ue.partial,HJ=(e,t)=>{let n=mg(t);return n===ue.authBroken?n:e!==0||n===ue.partial?ue.partial:ue.success},GJ=async(e,t)=>{if(e==="reconcile")return FJ(await(t.reconcile??(()=>BJ(t.loadProfile)))());if(e==="refresh"){if(!t.refresh)throw new Error("refresh runtime is unavailable");return WJ(await t.refresh())}return e==="repair"?TR(await(t.repair??(()=>OR(!0)))()):e==="status"?TR(await(t.status??(()=>OR(!1)))()):(await(t.offboard??Su)()).ok?ue.success:ue.partial},gg=(e,t)=>vu.parse({...e,lastVerb:{...e.lastVerb,exitCode:t}}),PR=async(e,t={})=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.help)return n(NJ),ue.success;let o=t.now??Date.now,a=new Date(o()).toISOString(),s=t.withProfileLock??as,i=t.buildStatus??xR,c=t.writeStatus??RR,l,d=e.usageError?ue.usage:ue.unexpected;e.usageError&&r(`anyray-connect ${e.verb}: UsageError`);try{await s(async()=>{if(!e.usageError)try{d=fg.parse(await GJ(e.verb,t))}catch(u){d=Ah(u)?ue.authBroken:ue.unexpected,r(`anyray-connect ${e.verb}: ${yg(u)}`)}if(l=await i({verb:e.verb,exitCode:d,at:a},{now:o}),(e.verb==="repair"||e.verb==="status")&&d!==ue.unexpected&&d!==ue.usage&&d!==ue.authBroken)d=HJ(d===0?0:1,l);else if(e.verb!=="offboard"&&d!==ue.unexpected&&d!==ue.usage){let u=mg(l);(u===ue.authBroken||d===ue.success)&&(d=u)}l=gg(l,d);try{await c(l)}catch(u){d=ue.unexpected,l=gg(l,d),r(`anyray-connect ${e.verb}: ${yg(u)}`)}})}catch(u){d=ue.unexpected,r(`anyray-connect ${e.verb}: ${yg(u)}`);try{l=gg(await i({verb:e.verb,exitCode:d,at:a},{now:o}),d)}catch{l=void 0}}return n(JSON.stringify(l||{schemaVersion:1,generatedAt:a,connectVersion:"unknown",fleetManaged:!1,enrollment:{state:"broken"},tools:[],lastVerb:{verb:e.verb,exitCode:d,at:a}})),d};var VJ=new Set(["not-due","repaired","cert-renewed","heartbeat-refreshed","refreshed"]),DR=async(e,t={})=>await(t.fleetdPresent??Ro)()?VJ.has(e)?{retired:!0,messages:(await(t.uninstallScheduler??sr)()).messages}:{retired:!1,reason:"refresh-unhealthy",messages:[]}:{retired:!1,reason:"no-fleetd",messages:[]};var LR=["reapply_config","remint","revert","revert_tool","update"],KJ=/^[a-z0-9][a-z0-9-]{0,31}$/;var jJ=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"||!LR.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&KJ.test(t.tool):t.tool===void 0},wg=e=>e?.name??"error",NR=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":LR.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!jJ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",wg(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",wg(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:",wg(i))}return a.kind};var $R=e=>e?.name??"Error",MR=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??P,r=t.recordManagedTools??Jn,o=t.adapterById??ut,a=t.isLocked??yi,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}: ${$R(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${$R(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{basename as ZJ}from"node:path";import{join as BR}from"node:path";var YJ="history.recentlyOpenedPathsList",JJ={"ssh-remote":"ssh","dev-container":"devcontainer","attached-container":"attached-container",wsl:"wsl",codespaces:"codespace",tunnel:"tunnel"},XJ=e=>{try{let t=JSON.parse(Buffer.from(e,"hex").toString("utf-8"));if(typeof t.hostPath=="string"&&t.hostPath)return{name:ZJ(t.hostPath),hostPath:t.hostPath};if(typeof t.containerName=="string"&&t.containerName)return{name:t.containerName.replace(/^\//,"")}}catch{}return{name:"container"}},zJ=e=>{let t=/^vscode-remote:\/\/([^/]+)/.exec(e);if(!t)return;let n;try{n=decodeURIComponent(t[1])}catch{return}let r=n.indexOf("+");if(r<=0)return;let o=JJ[n.slice(0,r)];if(!o)return;let a=n.slice(r+1);if(a){if(o==="devcontainer"||o==="attached-container"){let s=XJ(a);return{kind:o,name:s.name,...o==="devcontainer"&&s.hostPath?{ref:s.hostPath}:{}}}return{kind:o,name:a}}},qJ=e=>{let t;try{t=JSON.parse(e).entries}catch{return[]}if(!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){if(typeof o!="object"||o===null)continue;let a=o,s=[a.folderUri,a.fileUri,a.workspace?.configPath].filter(i=>typeof i=="string");for(let i of s){let c=zJ(i);if(!c)continue;let l=`${c.kind}|${c.ref??c.name}`;r.has(l)||(r.add(l),n.push(c))}}return n},QJ=()=>[...Qr.map(e=>BR(rl(e),"User","globalStorage","state.vscdb")),BR(Le("Cursor"),"User","globalStorage","state.vscdb")],bg=async(e={})=>{let t=e.readItem??(()=>{let o=lr();return o?o.readItem.bind(o):void 0})();if(!t)return[];let n=[],r=new Set;for(let o of e.dbPaths??QJ()){let a;try{a=t(o,YJ)}catch{continue}if(a)for(let s of qJ(a)){let i=`${s.kind}|${s.ref??s.name}`;r.has(i)||(r.add(i),n.push(s))}}return n};import{execFile as e5,spawn as t5}from"node:child_process";import{promisify as n5}from"node:util";var r5="https://app.anyray.ai/connect.sh",o5=".anyray/bin/anyray-connect",Ja=e=>`'${e.replaceAll("'",`'"'"'`)}'`,a5=e=>{let n=`${["set -eu","if command -v anyray-connect >/dev/null 2>&1; then"," command -v anyray-connect"," exit 0","fi",`ANYRAY_CONNECT_TAG=${Ja(`connect-v${ke}`)} \\`,` sh -c ${Ja(`curl -fsSL ${r5} | sh`)} >&2 </dev/null`,`echo "$HOME/${o5}"`].join(`
|
|
800
|
+
`)}
|
|
801
|
+
`;switch(e.kind){case"ssh":return{command:"ssh",args:["-T","--",e.name,"sh","-s"],stdin:n};case"devcontainer":return{command:"docker",args:["exec","-i",e.name,"sh","-s"],stdin:n};case"wsl":return{command:"wsl.exe",args:["-d",e.name,"--","sh","-s"],stdin:n};case"codespace":return{command:"gh",args:["codespace","ssh","-c",e.name,"--","sh -s"],stdin:n}}},s5=(e,t,n)=>{let r=[n,"--yes","--key-stdin","--gateway",t.gateway,...t.user!==void 0?["--user",t.user]:[],...t.team!==void 0?["--team",t.team]:[]],o=[Ja(n),"--yes","--key-stdin","--gateway",Ja(t.gateway),...t.user!==void 0?["--user",Ja(t.user)]:[],...t.team!==void 0?["--team",Ja(t.team)]:[]].join(" "),a=`${t.clientKey}
|
|
802
|
+
`;switch(e.kind){case"ssh":return{command:"ssh",args:["-T","--",e.name,o],stdin:a};case"devcontainer":return{command:"docker",args:["exec","-i",e.name,...r],stdin:a};case"wsl":return{command:"wsl.exe",args:["-d",e.name,"--",...r],stdin:a};case"codespace":return{command:"gh",args:["codespace","ssh","-c",e.name,"--",o],stdin:a}}},i5=n5(e5),c5=async(e,t)=>(await i5(e,[...t],{encoding:"utf8"})).stdout.toString(),Ag=async(e,t={})=>{let n=typeof e=="string"?{name:e}:e,r=n.ref??(/[/\\]/.test(n.name)?n.name:void 0);if(!r)throw new Error("Cannot resolve a dev container by its bare name; use its full host path.");let a=(await(t.exec??c5)("docker",["ps","--filter",`label=devcontainer.local_folder=${r}`,"--format","{{.ID}}"])).split(`
|
|
803
|
+
`).map(s=>s.trim()).find(Boolean);if(!a)throw new Error("No running dev container matches the discovered workspace.");return a},FR=(e,t,n)=>new Promise(r=>{let o;try{o=t(e.command,e.args,{stdio:["pipe",n?"pipe":"inherit","inherit"]})}catch{r({code:1,stdout:""});return}let a="",s=!1,i=c=>{s||(s=!0,r({code:c,stdout:a}))};if(o.stdout?.on("data",c=>{a+=c.toString("utf-8")}),o.once("error",()=>i(1)),o.once("close",c=>i(c??1)),!o.stdin){i(1);return}o.stdin.end(e.stdin)}),Cg=async(e,t,n={})=>{let r=n.spawn??t5,o=e.kind==="devcontainer"&&e.ref?{...e,name:await Ag(e,n)}:e,a=await FR(a5(o),r,!0);if(a.code!==0)return a.code;let s=a.stdout.split(`
|
|
804
|
+
`).map(c=>c.trim()).filter(Boolean).at(-1);return s?(await FR(s5(o,t,s),r,!1)).code:1};import{spawnSync as l5}from"node:child_process";import{platform as xu}from"node:os";import{basename as d5}from"node:path";import{createInterface as u5}from"node:readline";var UR=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
804
805
|
|
|
805
806
|
${j("Usage")}
|
|
806
807
|
npx anyray-connect [options]
|
|
@@ -814,7 +815,7 @@ ${j("Subcommands")}
|
|
|
814
815
|
sync Pull the team's shared skills and instructions
|
|
815
816
|
update Update Connect or configure automatic updates
|
|
816
817
|
endpoint Install and enroll the Anyray endpoint agent
|
|
817
|
-
remote
|
|
818
|
+
remote Configure one remote environment from this machine
|
|
818
819
|
reconcile Pull fleet policy and repair routing drift (JSON)
|
|
819
820
|
refresh Renew credentials and re-assert configuration (JSON)
|
|
820
821
|
repair Run the full non-interactive repair pass (JSON)
|
|
@@ -909,8 +910,10 @@ ${j("Subcommands")}
|
|
|
909
910
|
runs automatically ~every 30 min). --check reports only;
|
|
910
911
|
--auto on|off turns automatic updates on or off.
|
|
911
912
|
endpoint install Install Fleet's signed endpoint agent and enroll this machine.
|
|
912
|
-
remote <ssh-host> Configure
|
|
913
|
-
|
|
913
|
+
remote <ssh-host> Configure an SSH environment from this machine. Use
|
|
914
|
+
--devcontainer <host-path>, --wsl <distro>, or --codespace
|
|
915
|
+
<name> for the other supported carriers. Requires a TTY
|
|
916
|
+
unless --yes is supplied; host-key verification remains
|
|
914
917
|
entirely under the user's SSH configuration.
|
|
915
918
|
reconcile Pull fleet policy and repair routing drift; JSON stdout.
|
|
916
919
|
refresh Run the unattended credential/config refresh; JSON stdout.
|
|
@@ -1053,22 +1056,22 @@ ${j("What it does")}
|
|
|
1053
1056
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1054
1057
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1055
1058
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1056
|
-
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
1057
|
-
${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?`}`,
|
|
1058
|
-
${o} ${n} tool target(s)?`;return await(r.confirm??Eo)(a)?"proceed":"declined"},O5=async(e=Ha)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0,initiator:"directive"});switch(t.outcome){case"current":case"updated":case"migrated":case"container":case"unmanaged":return"ok";case"available":case"migration-available":case"migration-deferred":case"disabled":case"platform-unsupported":case"unavailable":case"failed":return"failed";case"fleet-off":return"failed";case"fleet-directed":return"failed";default:return t.outcome}},T5=async()=>{let e=!1,t=await Qt({runAmbientSelfcheck:!0});await yp(),await BE(),await FE()==="retry"&&(e=!0);let n=await P().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await le(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Ro().catch(()=>!1);if(n&&(await _R(t,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Wt(),i=n.enrolledCert;if(s&&i){let l=await Be().catch(()=>{});l&&await ES(o,a,i,l,s).catch(()=>{})}await DR(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await Qt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await NR(d):l==="update"?u=await O5():u=(await Su()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await Ha(),{refresh:t,...e?{partial:!0}:{}}},_5=async e=>{if(e[0]==="__anyray-hook"){let r=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return i0(r)}if(e[0]==="__anyray-codex-hook")return c0();if(e[0]==="__anyray-prompt-hook")return h0();if(e[0]==="__anyray-shell-pretool")return b0();if(e[0]==="__anyray-shell-run")return w0(e.slice(1));if(e[0]==="__anyray-read-pretool")return x0();if(e[0]==="__anyray-sso-gate")return m0(e.slice(1));if(e[0]==="__anyray-sso-poll")return iR();if(e[0]==="__anyray-managed-enroll")try{return await as(()=>aR(sR((r,o)=>ZR(r,!1,{managedEnrollmentRevertedTools:o}))),{waitMs:KR})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return fR();if(e[0]==="__anyray-spawn-refresh")return await Or(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return CR(r)}if(e[0]==="__anyray-acp-agent")return kR(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return nR(e.slice(1));let t=OR(e);if(t)return TR(t,{refresh:T5});if(e[0]==="__anyray-persistence")return Lw(e.slice(1));if(e[0]==="__anyray-quit-watch")return sS(e.slice(1));if(e[0]===kr)return dI(e.slice(1));if(e[0]===Xs)return pI(e.slice(1));if(e[0]===jr){let r=e[1];return r&&await jd(r),0}if(e[0]==="--version"||e[0]==="-V")return pR();try{let r=await ew(e);if(r!==void 0)return r}catch(r){return R(`Could not persist anyray-connect for long-lived integrations: ${r instanceof Error?r.message:String(r)}`),1}if(I5(e)){let r=E5(await yx());r?.level==="warn"?_(r.message):r&&console.error(r.message)}if(e[0]==="managed")return KS(e.slice(1));if(e[0]==="endpoint")return tR(e.slice(1));if(e[0]==="print-key")return GE(e.slice(1));if(e[0]==="models")return KE(e.slice(1));if(e[0]==="copilot-login")return jE(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=ty(r);return o?Cg(o,!1):NI(r)}if(e[0]==="retrieve")return MI(e.slice(1));if(e[0]==="recall")return BI(e.slice(1));if(e[0]==="history")return XI(e.slice(1));if(e[0]==="migrate")return qI(e.slice(1));if(e[0]==="login")return lR(e.slice(1));if(e[0]==="update")return uR(e.slice(1));if(e[0]==="remote")return L5(e.slice(1));let n=e[0];if(n&&v5.has(n)){let r=e.slice(1),o;try{o=kg(r)}catch(a){return R(a.message),A("\nRun `npx anyray-connect --help` for usage."),1}return o.help?(A(o.helpAll?Iu:WR),0):n==="status"?kx({gateway:o.gateway}):n==="doctor"?lu({gateway:o.gateway,json:o.json,verify:o.verify,noVerify:o.noVerify,quick:o.quick,repair:o.repair,securityReview:o.securityReview}):n==="sync"?Ox({gateway:o.gateway}):n==="device-url"?zE():Cg(r,!0)}return Cg(e,!1)},jR=async e=>{try{return await _5(e)}catch(t){if(t instanceof ft)return console.error(v("Cancelled.")),130;throw t}},P5=e=>e.interactive&&!e.managed&&!e.yes&&!e.revert&&!e.dryRun,D5=async(e,t={})=>{if(!P5(e)||!be(e.clientKey))return;let n=t.discoverRemoteEnvironments??wg,r;try{r=await n()}catch{return}let o=t.confirm??Eo,a=t.runRemoteApply??bg;for(let s of r){if(s.kind!=="ssh"||!await o(`Configure \`${s.name}\` over SSH now?`))continue;let i=await a({host:s.name,gateway:e.gateway,user:e.user,team:e.team,clientKey:e.clientKey});if(i===0){N(`Remote \`${s.name}\` exited with code 0.`);continue}_(`Remote \`${s.name}\` exited with code ${i}.`),N("Fix: ssh in and run `anyray-connect doctor`.")}},L5=async(e,t={})=>{if(e[0]==="--help"||e[0]==="-h")return console.log(Iu),0;let n=e[0];if(!n||n.startsWith("-"))return R("usage: anyray-connect remote <ssh-host> [--yes] [--dry-run]"),1;let r;try{r=kg(e.slice(1))}catch(p){return R(p instanceof Error?p.message:String(p)),1}if(r.help)return console.log(Iu),0;let o=t.isInteractive??mt;if(!r.yes&&!o())return R("remote requires a TTY; pass --yes only when you explicitly intend to configure that SSH host."),1;if(r.revert||r.enroll||r.sso||r.claim||r.project||r.upstream||r.upstreamKey)return R("remote supports --gateway, --user, --team, --yes, --dry-run, and --key-stdin only."),1;if(r.dryRun)return N(`Dry run: would configure \`${n}\` over SSH.`),0;let a;if(r.keyStdin)try{a=await UR()}catch{return R("could not read the personal gateway key from stdin."),1}let s=await(t.loadProfile??P)(),i=!r.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0,c=Vt(r.gateway??i),l=a||process.env.ANYRAY_CLIENT_KEY?.trim()||HR(s);if(!be(l))return R("A personal gateway key is required. Enroll locally first or provide ANYRAY_CLIENT_KEY (or --key-stdin)."),1;let d=await Gh(r.user,s.name,r.yes),u=await Vh(r.team,s.team,r.yes),f=await(t.runRemoteApply??bg)({host:n,gateway:c,user:d,team:u,clientKey:l});return f===0?N(`Remote \`${n}\` exited with code 0.`):(_(`Remote \`${n}\` exited with code ${f}.`),N("Fix: ssh in and run `anyray-connect doctor`.")),f},ZR=async(e,t,n={})=>{let r=n.isInteractive??mt,o;try{o=kg(e)}catch($){return R($.message),A("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return A(o.helpAll?Iu:WR),0;if(o.revert&&(o.sso||o.enroll||o.claim))return R("--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?(R("--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):cI({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return R("--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 R("--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 R(`invalid --upstream URL: "${o.upstream}"`),1}if($.protocol!=="http:"&&$.protocol!=="https:")return R(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let D=o.upstreamKey.trim();if(!D)return R("--upstream-key must not be empty."),1;a={url:Gt(o.upstream),key:D}}let s=await P(),i;if(o.keyStdin)try{i=await UR()}catch{return R("could not read the personal gateway key from stdin."),1}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream);let c=!t&&mt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,l=!1;(t||c)&&r()&&(o=await(n.runWizard??A5)(o,s),l=!0);let d;try{if(d=a5(o.tools),n.managedEnrollmentRevertedTools){let $=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];d=oR(d,$)}}catch($){return R($.message),1}A(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&mi(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,A("That looks like an enrollment link \u2014 treating it as --enroll."));let u,f,p,m,y=!1;if(o.enroll){let $=gd(o.enroll);if($&&(!o.gateway||s.enrolledCert||rh($.token)))try{let D=await Pi("Resolving enrollment link\u2026",()=>wS($)),X=!o.gateway;X&&(o.gateway=D.gatewayUrl),u=D.deploymentId,f=D.email,p=D.provisioningKind,m=D.allowedDomains,y=!0,X&&N(`Enrollment link${D.org?` for ${D.org}`:""}: gateway ${D.gatewayUrl}`),D.seatMode&&!o.subscription&&(o.subscription=!0,N("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(D){if(rh($.token))return R(D instanceof Error?D.message:String(D)),1;let X=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(X)N(`Could not resolve the gateway from the enrollment link \u2014 using ${X}.`);else return R(D instanceof Error?D.message:String(D)),1}}let g,h;if(o.claim&&!o.revert)if(o.dryRun)N("dry run: not enrolled (skipped redeeming the enrollment link).");else{let $=TS(o.claim);if(!$)return R("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let D=await Pi("Connecting this machine\u2026",()=>_S({cpOrigin:$.cpOrigin,claim:$.claim,gatewayUrl:o.gateway}));g={cert:D.cert,privateKeyPem:D.privateKeyPem},D.deploymentId&&(u=D.deploymentId),!o.gateway&&D.gatewayUrl&&(o.gateway=D.gatewayUrl),h=D.ssoLink}catch(D){return R(D instanceof Error?D.message:String(D)),1}}if(o.sso&&!g&&!o.revert)if(o.dryRun)N("dry run: not enrolled via SSO (skipped minting a personal key).");else{let $=Et(o.sso);if(!$)return R(mi(o.sso)?"that is an enrollment link, not an SSO link \u2014 re-run with --enroll instead of --sso.":"invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let D=await bd({cpOrigin:$.cpOrigin,tenantId:$.tenantId,gatewayUrl:o.gateway,log:G=>N(G),open:r()?Fa:void 0}),X=await Pi("Waiting for SSO sign-in\u2026",()=>Ad(D,{gatewayUrl:o.gateway}));g={cert:X.cert,privateKeyPem:X.privateKeyPem},X.deploymentId&&(u=X.deploymentId),!o.gateway&&X.gatewayUrl&&(o.gateway=X.gatewayUrl)}catch(D){return R(D instanceof Error?D.message:String(D)),1}}let w=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;w&&(o.gateway=w);let b;try{b=Vt(o.gateway)}catch($){return R($.message),1}let k,C;w&&!o.revert&&N(`Gateway: ${b} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&Eg(b)&&_(`${b} 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 S=i??process.env.ANYRAY_CLIENT_KEY?.trim(),E=S||HR(s),I,O,T,U,z,K,oe=async $=>{await vo();let D=CS($.token),X=IS(s.enrolledCert,s.enrolledCertExpiry,$.deploymentId,Date.now(),D,s.enrolledTokenHash,$.expectedUser),G=X?await Be():void 0,xe=Wt()||void 0,ht=X&&G&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:G,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,yt=gt=>xS({cpOrigin:$.cpOrigin,token:$.token,gatewayOrigin:b,email:$.email,team:$.team,machineId:$.machineId,deploymentId:$.deploymentId,machineUuid:xe,reuse:gt?ht:void 0}),De=!!ht,qe=await(async()=>{try{return await yt(De)}catch(gt){if(ht&> instanceof ct&>.policyCode!=="managed_device_required")return N("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),De=!1,await yt(!1);throw gt}})();E=qe.clientKey,o.user=Eu(o.user,qe.user),o.team=Eu(o.team,qe.team),I=qe.cert,O=qe.cert.payload.expiresAt,K=qe.expiresAt,z=void 0,De||(T=qe.privateKeyPem),De||(U=D),B(`Enrolled${qe.user?` as ${qe.user}`:""}${De?" (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)N("dry run: not enrolled (skipped minting a personal key).");else{let $=gd(o.enroll);if(!$){let D=gS(o.enroll);return R(D?`that is ${D.what}, not an enrollment link \u2014 re-run with ${D.flag} instead of --enroll.`:Et(o.enroll)?"that is an SSO link, not an enrollment link \u2014 re-run with --sso instead of --enroll.":"invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1}try{let D=o.machine?Od():void 0,X=p==="mdm"&&!f?sx():void 0,G=p==="mdm"&&!f&&!X?ax(m,Bd()):void 0,xe=X??G;if(xe){let De=X?"the email your MDM assigned to this machine":`${xe} (this Mac's login name at the first allowed domain)`;A(o.user?.trim()&&o.user.trim()!==xe?`Ignoring --user: enrolling as ${De}.`:`Enrolling as ${De}.`)}let ht=f??xe??o5(o.user);if(!o.machine&&!o.user&&!f&&!xe){let De=tI();De.distinct||(_(` Enrolling as "${De.identity}" \u2014 this may not be unique to you.`),_(De.reason==="machine_default"?" That looks like a machine or container default, so every developer on":" No personal git email is set, so machines sharing this image can"),_(De.reason==="machine_default"?" this image would enroll as the same person and their spend would merge.":" enroll under the same name and their spend would merge."),_(" Re-run with `--user you@company.com` (or set `git config --global"),_(" user.email`) so your usage is attributed to you."))}let yt=o.machine?`machine:${D}`:y?ht:void 0;await oe({cpOrigin:$.cpOrigin,token:$.token,email:ht,team:o.team,machineId:D,deploymentId:u,expectedUser:yt})}catch(D){return R(D instanceof Error?D.message:String(D)),D instanceof ct&&D.policyCode!=="managed_device_required"&&N("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."),vS(D)?3:1}}if(g){await vo();try{let $=Wt()||void 0,D=await qt(b,g.cert,g.privateKeyPem,{machineUuid:$});E=D.key,o.user=Eu(o.user,D.user),o.team=Eu(o.team,D.team),I=g.cert,O=g.cert.payload.expiresAt,T=g.privateKeyPem,K=D.expiresAt;let X=o.sso?Et(o.sso):void 0;z=X?`${X.cpOrigin}/sso/${X.tenantId}`:h,B(`Enrolled${D.user?` as ${D.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch($){return R($ instanceof Error?$.message:String($)),$ instanceof ct&&$.policyCode!=="managed_device_required"&&N("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;k=await Gh(o.user,s.name,$),C=await Vh(o.team,s.team,$)}if(!o.revert&&!o.dryRun){let $=bx(await wx(b,E),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if($.lane){let D=$.lane==="subscription";o.subscription=D,o.placeholder=!D;let X=D?"your own subscription seat":"the organization's provider account";$.overrodeFlag?N(`Your administrator assigns this machine to ${X}, so that is what was applied (it overrides the lane flag you passed).`):N(`Billing lane set by your administrator: ${X}.`)}}let ae;!o.revert&&!o.subscription&&!o.placeholder&&(ae=await yn(),H("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?ze("BYO upstream key (passthrough)"):ae.anthropic?ze("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${ae.openai?ze("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),!ae.anthropic&&!ae.openai&&!ae.copilot&&Hr()&&(_(" No subscription sign-ins found on this host. Sign-ins do not cross the"),_(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),_(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),_(" and re-run, or everything below routes on the org key instead.")));let Z=Oe({origin:b,placeholderKey:o.key,clientKey:E,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:ae,user:k,team:C,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),ie=o.revert===!0&&(o.tools?.length??0)===0,F={dryRun:o.dryRun,fullRevert:ie};if(!o.revert&&Z.clientKey&&!be(Z.clientKey))return R("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&&!Z.clientKey){H("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(" Dry run only \u2014 no placeholder configuration will be written."),await BR(d,"after-enrollment"),N(`
|
|
1059
|
-
Dry run complete \u2014 no files were written.`),0):(R(` ${$}`),1)}o.revert||
|
|
1060
|
-
Dry run \u2014 no files will be written.`);let te=await
|
|
1059
|
+
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,p5=e=>{let t=e?.trim();return t||Hh()},HR=(e=process.stdin)=>new Promise((t,n)=>{let r=u5({input:e,crlfDelay:1/0}),o=!1,a=i=>{o||(o=!0,e.removeListener("error",s),r.close(),t(i))},s=i=>{o||(o=!0,r.close(),n(i))};r.once("line",i=>a(i.trim())),r.once("close",()=>a("")),e.once("error",s)}),Eu=(e,t)=>t||e,Sg=e=>{let t={subscription:!1,placeholder:!1,dryRun:!1,yes:!1,revert:!1,force:!1,skipVerify:!1,verbose:!1,help:!1,helpAll:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>e[++n];switch(r){case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":t.key=o();break;case"--key-stdin":t.keyStdin=!0;break;case"--devcontainer":t.devcontainer=o();break;case"--wsl":t.wsl=o();break;case"--codespace":t.codespace=o();break;case"--enroll":t.enroll=o();break;case"--sso":t.sso=o();break;case"--claim":t.claim=o();break;case"--machine":t.machine=!0;break;case"--subscription":t.subscription=!0;break;case"--placeholder":case"--org":t.placeholder=!0;break;case"--upstream":t.upstream=o();break;case"--upstream-key":t.upstreamKey=o();break;case"--tools":t.tools=(o()??"").split(",").map(a=>a.trim()).filter(Boolean);break;case"--project":t.project=!0;break;case"--dry-run":t.dryRun=!0;break;case"--yes":case"-y":t.yes=!0;break;case"--force":t.force=!0;break;case"--skip-verify":t.skipVerify=!0;break;case"--no-key-refresh":t.noKeyRefresh=!0;break;case"--quit-apps":t.quitApps=!0;break;case"--no-quit-apps":t.noQuitApps=!0;break;case"--endpoint":t.endpoint=!0;break;case"--no-endpoint":t.noEndpoint=!0;break;case"--revert":t.revert=!0;break;case"--json":t.json=!0;break;case"--verify":t.verify=!0;break;case"--no-verify":t.noVerify=!0;break;case"--quick":t.quick=!0;break;case"--repair":t.repair=!0;break;case"--security-review":t.securityReview=!0;break;case"--verbose":t.verbose=!0;break;case"--help":case"-h":t.help=!0;break;case"--help-all":t.help=!0,t.helpAll=!0;break;case"--all":if(!e.includes("--help")&&!e.includes("-h"))throw new Error(`unknown option: ${r}`);t.helpAll=!0;break;default:if(!r.startsWith("-")&&t.gateway===void 0)t.gateway=r;else throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r} (gateway already set to ${t.gateway})`)}}return t},f5=e=>!e||e.length===0?pe:e.map(t=>{let n=ut(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${pe.map(r=>r.id).join(", ")}`);return n}),m5=(e,t)=>{if(H("Gateway target"),A(` Origin: ${ze(e.origin)}`),e.byoUpstream)A(` Auth: BYO upstream key ${v(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&A(` Client key: personal gateway key (${Pt(e.clientKey)}) ${v("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=ee(e,"anthropic")?ze("your subscription"):"org key",r=ee(e,"openai")?ze("your subscription"):"org key";A(` Auth: auto ${v("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&A(` Client key: personal gateway key (${Pt(e.clientKey)})`)}else e.authMode==="subscription"?(A(` Auth: subscription pass-through ${v("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&A(` Client key: personal gateway key (${Pt(e.clientKey)}) ${v("rides x-anyray-api-key")}`)):e.clientKey?A(` Auth: personal gateway key (${Pt(e.clientKey)}) ${v("(replaces the placeholder)")}`):A(` Enrollment: ${v("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&A(` Cursor: ${ze("native Team subscription")} ${v("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(ee(e,"anthropic")?(A(` Claude Desktop: ${ze("subscription-backed Gateway lane")} ${v("(verified macOS builds; Windows fails closed)")}`),A(` ${v("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(A(` Claude Desktop: ${ze("third-party API lane")} ${v("(API-billed; switches the active local inference profile)")}`),A(` ${v("The first-party Claude subscription remains untouched.")}`))),A(` Attribution: ${fe(e.metadata)??v("(none \u2014 pass --user)")}`)},h5=e=>{switch(e.kind){case"ssh":return`SSH remote \`${e.name}\``;case"devcontainer":return`dev container \`${e.name}\``;case"attached-container":return`attached container \`${e.name}\``;case"wsl":return`WSL distro \`${e.name}\``;case"codespace":return`Codespace \`${e.name}\``;case"tunnel":return`remote tunnel \`${e.name}\``}},y5=async()=>{let[e,t]=await Promise.all([su().catch(()=>[]),bg().catch(()=>[])]);for(let n of e)A(` Bind-mounted config file: ${n} ${v("(cannot be replaced atomically; connect writes it in place, verified)")}`);if(t.length>0){H("Other environments you work in");for(let n of t)N(` ${h5(n)}`);A(v(" This run configures only this machine. Run `anyray-connect` inside each of these too \u2014 see docs.anyray.ai/get-started/remote-environments."))}},WR=async(e,t)=>{H("Selected tools");for(let n of e){let r=await n.detect();r.installed?A(` ${n.title} ${v(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):N(` ${n.title} ${v(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},GR=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!be(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},g5={loadDevKey:Be,saveDevKey:ec,clearDevKey:os,saveProfile:le},w5=async(e,t,n,r=g5,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}},b5=async(e,t,n,r,o)=>{let a=0,s=[],i=[],c=[],l=[],d=[];for(let u of e){if(!(await u.detect()).installed&&!r){d.push(u.title);continue}H(`${u.title} ${v(`(${u.id})`)}`);try{let p=r?await u.revert(n):await u.apply(t,{...n,explicit:o?.has(u.id)===!0,reportsToUser:!0});for(let m of p.messages)A(` ${m}`);a+=p.changedFiles?.length??0,l.push({id:u.id,status:p.status}),p.status==="configured"||p.status==="reverted"?B(` ${p.status}`):p.status==="manual"?(s.push(u.title),p.manualAudience==="admin"?(i.push(u.title),c.push(u.id),_(" blocked by machine policy \u2014 your IT team owns this one")):_(" manual step required (see above)")):p.status==="held"?N(" left on its own plan (no change)"):N(` ${p.status}`)}catch(p){l.push({id:u.id,status:"failed"}),R(` failed: ${p instanceof Error?p.message:String(p)}`)}}if(d.length>0&&N(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await ac().catch(()=>[]);u.length&&N(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},A5=(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},C5=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>VR(o)&&!r.has(o.id))},k5=async e=>{let t=NI(e,process.platform,Q());if(t){await we(t.path,t.content);for(let n of $I(t,process.platform))A(` ${n}`)}},v5=async(e,t,n=xu())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!Rb(i,n)||!xb(i,n))continue;let c=Eb(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:Ib(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},S5=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,E5=e=>`
|
|
1060
|
+
${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?`}`,I5=async(e,t={})=>{let n=t.requestQuit??(a=>Tb(a)),r=t.waitFor??(a=>_b(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),B(` Closed ${a.title}.`);continue}_(` ${a.title} is still open \u2014 leaving it alone.`),N(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},x5=(e,t={})=>{let n=t.relaunch??(o=>Pb(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),B(` Reopened ${o.title}.`)):_(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},VR=e=>e.changesBilling===!0||e.changesOrgManagement===!0,KR=e=>e.changesBilling===!0?"moves inference spend from your subscription to the org API bill":e.changesOrgManagement===!0?"switches the app to third-party mode; claude.ai Enterprise org settings stop applying":void 0,kg=e=>!VR(e),R5=async(e,t,n={})=>{let r=n.hasEnrollment??Gu,o=n.canMultiSelect??dx,a=n.multiSelect??ux,s=n.prompt??Na,i=n.registry??pe;if(A(j("Anyray connect \u2014 guided setup")),A(v("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())A("Stored enrollment will be reused. Run with --revert to clear it.");else if(!e.enroll&&!e.sso&&!e.gateway){H("How do you want to connect?");let c;for(let l=0;l<3&&!c;l++){if(o()){let d=await a({title:"Choose a connection method",single:!0,items:[{value:"enroll",label:"Paste an enrollment link",selected:!0},{value:"sso",label:"Sign in with SSO"},{value:"gateway",label:"I already have a gateway URL"}]});if(d.kind==="cancelled")throw new ft;c=d.values[0]}else{A(" 1. Paste an enrollment link"),A(" 2. Sign in with SSO"),A(" 3. I already have a gateway URL");let d=await s("? Connection method (1-3)","1");c=d==="1"?"enroll":d==="2"?"sso":d==="3"?"gateway":void 0}c||_("Choose one of the three connection methods.")}if(!c)throw new ft;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&mi(d)&&gd(d)){e.enroll=d;break}_("That is not a valid enrollment link or token. Try again.")}else if(c==="sso"){let d=await s("? SSO link or tenant id");if(d&&Et(d)){e.sso=d;break}_("That is not a valid SSO link or tenant id. Try again.")}else{let d=await s("? Gateway URL",t.gateway||process.env.ANYRAY_GATEWAY_URL);if(d&&mi(d)){e.enroll=d,A("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=Vt(d);break}catch{_("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new ft}if(!e.tools||e.tools.length===0){H("Tools detected");let c=[],l=[];for(let u of i){if(!(await u.detect()).installed){l.push(u);continue}c.push(u)}let d=c.filter(u=>kg(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(m=>({value:m.id,label:`${m.title} (${m.id})`,hint:KR(m),selected:kg(m),requiresExplicitChoice:!kg(m)}))});if(p.kind==="cancelled")throw new ft;f=p.values}else{f=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(g=>g.trim()).filter(Boolean);let m=new Set(c.map(g=>g.id)),h=f.filter(g=>!m.has(g));if(h.length>0){_(`Unknown or unavailable tool id${h.length===1?"":"s"}. Choose from: ${c.map(g=>g.id).join(", ")}.`);continue}}if(f.length===0){_("Choose at least one installed tool.");continue}e.tools=f}if(!e.tools)throw new ft}l.length>0&&N(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},O5=async(e,t)=>{H("Verifying the connection");let n=await Pi("Checking the gateway\u2026",()=>Mi(e,{tools:t}));n.kind==="ok"?B(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?_(` ${n.detail}`):R(` ${n.detail}`);for(let r of n.remedy)A(v(` ${r}`))},T5=async(e,t={})=>{if(e.dryRun)return;let n=t.install??ar,r=t.uninstall??sr;if(e.want&&e.trayManaged){H("Automatic key refresh"),B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh.");return}if(e.want){let o=await n();H("Automatic key refresh");for(let a of o.messages)A(` ${a}`);o.ok&&B(" Your gateway key now renews every ~30 min \u2014 no tool will 401 on a stale key mid-session."),o.ok?await le({...await P(),refreshSchedulerInstalledOnce:!0}):await le({...await P(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){H("Automatic key refresh");let o=await r();for(let a of o.messages)A(` ${a}`);await le({...await P(),refreshSchedulerEnabled:!1,refreshSchedulerInstalledOnce:!1}),B(" Removed the automatic key-refresh schedule.")}},_5=new Set(["login","wizard","status","doctor","sync","device-url"]),P5=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint","remote"]),D5=e=>{if(e.outcome==="migrated"&&e.managedPath)return{level:"info",message:`Installed managed anyray-connect at ${e.managedPath}.`};if(e.outcome==="platform-unsupported")return{level:"warn",message:"Self-update is unavailable on this platform; keeping the durable npm runtime for persistent integrations."};if(e.outcome==="migration-deferred")return{level:"warn",message:`Managed install deferred because the published binary (${e.latest}) is older than this npm runtime (${e.current}).`};if(e.outcome==="fleet-off"||e.outcome==="fleet-directed")return{level:"warn",message:"Your organization manages anyray-connect updates, so this run did not download a binary; continuing with the current runtime."};if(!(e.outcome==="current"||e.outcome==="unmanaged"||e.outcome==="updated"||e.outcome==="disabled"||e.outcome==="container"))return{level:"warn",message:"Could not install the managed anyray-connect binary; continuing with the current runtime \u2014 it migrates automatically on a later refresh."}},L5=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=ny(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]||!P5.has(e[0])},vg=async(e,t)=>{try{return await JR(e,t)}catch(n){if(n instanceof ft)return console.error(v("Cancelled \u2014 nothing was written.")),130;if(n instanceof Error&&n.message==="connect profile is busy; retry the command")return R("Another Connect update is in progress. Try again."),1;throw n}},jR=12e4,N5=async(e,t,n,r=as)=>e&&!t?r(n,{waitMs:jR}):n(),$5=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??mt)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
|
|
1061
|
+
${o} ${n} tool target(s)?`;return await(r.confirm??Eo)(a)?"proceed":"declined"},M5=async(e=Ha)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0,initiator:"directive"});switch(t.outcome){case"current":case"updated":case"migrated":case"container":case"unmanaged":return"ok";case"available":case"migration-available":case"migration-deferred":case"disabled":case"platform-unsupported":case"unavailable":case"failed":return"failed";case"fleet-off":return"failed";case"fleet-directed":return"failed";default:return t.outcome}},B5=async()=>{let e=!1,t=await Qt({runAmbientSelfcheck:!0});await gp(),await WE(),await UE()==="retry"&&(e=!0);let n=await P().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await le(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Ro().catch(()=>!1);if(n&&(await DR(t,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Wt(),i=n.enrolledCert;if(s&&i){let l=await Be().catch(()=>{});l&&await xS(o,a,i,l,s).catch(()=>{})}await NR(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await Qt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await MR(d):l==="update"?u=await M5():u=(await Su()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await Ha(),{refresh:t,...e?{partial:!0}:{}}},F5=async e=>{if(e[0]==="__anyray-hook"){let r=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return l0(r)}if(e[0]==="__anyray-codex-hook")return d0();if(e[0]==="__anyray-prompt-hook")return g0();if(e[0]==="__anyray-shell-pretool")return C0();if(e[0]==="__anyray-shell-run")return A0(e.slice(1));if(e[0]==="__anyray-read-pretool")return O0();if(e[0]==="__anyray-sso-gate")return y0(e.slice(1));if(e[0]==="__anyray-sso-poll")return lR();if(e[0]==="__anyray-managed-enroll")try{return await as(()=>iR(cR((r,o)=>JR(r,!1,{managedEnrollmentRevertedTools:o}))),{waitMs:jR})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return hR();if(e[0]==="__anyray-spawn-refresh")return await Or(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return vR(r)}if(e[0]==="__anyray-acp-agent")return SR(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return oR(e.slice(1));let t=_R(e);if(t)return PR(t,{refresh:B5});if(e[0]==="__anyray-persistence")return $w(e.slice(1));if(e[0]==="__anyray-quit-watch")return cS(e.slice(1));if(e[0]===kr)return pI(e.slice(1));if(e[0]===Xs)return mI(e.slice(1));if(e[0]===jr){let r=e[1];return r&&await jd(r),0}if(e[0]==="--version"||e[0]==="-V")return mR();try{let r=await nw(e);if(r!==void 0)return r}catch(r){return R(`Could not persist anyray-connect for long-lived integrations: ${r instanceof Error?r.message:String(r)}`),1}if(L5(e)){let r=D5(await wx());r?.level==="warn"?_(r.message):r&&console.error(r.message)}if(e[0]==="managed")return ZS(e.slice(1));if(e[0]==="endpoint")return rR(e.slice(1));if(e[0]==="print-key")return KE(e.slice(1));if(e[0]==="models")return ZE(e.slice(1));if(e[0]==="copilot-login")return YE(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=ny(r);return o?vg(o,!1):MI(r)}if(e[0]==="retrieve")return FI(e.slice(1));if(e[0]==="recall")return WI(e.slice(1));if(e[0]==="history")return qI(e.slice(1));if(e[0]==="migrate")return ex(e.slice(1));if(e[0]==="login")return uR(e.slice(1));if(e[0]==="update")return fR(e.slice(1));if(e[0]==="remote")return Y5(e.slice(1));let n=e[0];if(n&&_5.has(n)){let r=e.slice(1),o;try{o=Sg(r)}catch(a){return R(a.message),A("\nRun `npx anyray-connect --help` for usage."),1}return o.help?(A(o.helpAll?Iu:UR),0):n==="status"?Sx({gateway:o.gateway}):n==="doctor"?lu({gateway:o.gateway,json:o.json,verify:o.verify,noVerify:o.noVerify,quick:o.quick,repair:o.repair,securityReview:o.securityReview}):n==="sync"?_x({gateway:o.gateway}):n==="device-url"?QE():vg(r,!0)}return vg(e,!1)},ZR=async e=>{try{return await F5(e)}catch(t){if(t instanceof ft)return console.error(v("Cancelled.")),130;throw t}},W5=e=>{let t=process.platform==="win32"?"where":"which";try{return l5(t,[e],{stdio:"ignore"}).status===0}catch{return!1}},U5=(e,t={})=>{let n=t.which??W5,r=t.platform??xu;switch(e.kind){case"ssh":return!0;case"devcontainer":return n("docker");case"wsl":return r()==="win32"&&n("wsl.exe");case"codespace":return n("gh")}},H5=e=>{switch(e.kind){case"ssh":case"devcontainer":case"wsl":case"codespace":return{kind:e.kind,name:e.name,...e.kind==="devcontainer"&&e.ref?{ref:e.ref}:{}};case"attached-container":case"tunnel":return}},G5=(e,t)=>{switch(e.kind){case"ssh":return`Configure \`${t}\` over SSH now?`;case"devcontainer":return`Configure \`${t}\` in this dev container now?`;case"wsl":return`Configure \`${t}\` in WSL now?`;case"codespace":return`Configure Codespace \`${t}\` now?`}},V5=e=>e.interactive&&!e.managed&&!e.yes&&!e.revert&&!e.dryRun,K5=async(e,t={})=>{if(!V5(e)||!be(e.clientKey))return;let n=t.discoverRemoteEnvironments??bg,r;try{r=await n()}catch{return}let o=t.confirm??Eo,a=t.runRemoteApply??Cg,s=t.isCarrierAvailable??U5,i=t.resolveDevcontainer??Ag;for(let c of r){let l=H5(c);if(!l)continue;let d=l;try{if(!await s(d))continue;d.kind==="devcontainer"&&(d={kind:"devcontainer",name:await i(d)})}catch{continue}if(!await o(G5(d,c.name)))continue;let u=await a(d,{gateway:e.gateway,user:e.user,team:e.team,clientKey:e.clientKey});if(u===0){N(`Remote \`${c.name}\` exited with code 0.`);continue}_(`Remote \`${c.name}\` exited with code ${u}.`),N(YR(d.kind))}},YR=e=>{switch(e){case"ssh":return"Fix: ssh in and run `anyray-connect doctor`.";case"devcontainer":return"Fix: open a shell in the container and run `anyray-connect doctor`.";case"wsl":return"Fix: open the distro and run `anyray-connect doctor`.";case"codespace":return"Fix: `gh codespace ssh` in and run `anyray-connect doctor`."}},j5="usage: anyray-connect remote <ssh-host> [--yes] [--dry-run] | remote --devcontainer <host-path> | --wsl <distro> | --codespace <name> [--yes] [--dry-run]",Z5=e=>{let t=/[/\\]/.test(e);return{kind:"devcontainer",name:t?d5(e.replaceAll("\\","/")):e,...t?{ref:e}:{}}},Y5=async(e,t={})=>{if(e[0]==="--help"||e[0]==="-h")return console.log(Iu),0;let n=e[0]&&!e[0].startsWith("-")?e[0]:void 0,r;try{r=Sg(n?e.slice(1):e)}catch(h){return R(h instanceof Error?h.message:String(h)),1}if(r.help)return console.log(Iu),0;let o=[r.devcontainer,r.wsl,r.codespace].filter(h=>h!==void 0);if(n&&o.length>0||!n&&o.length!==1)return R(j5),1;let a=n?{kind:"ssh",name:n}:r.devcontainer!==void 0?Z5(r.devcontainer):r.wsl!==void 0?{kind:"wsl",name:r.wsl}:{kind:"codespace",name:r.codespace};if(a.kind==="devcontainer"&&!a.ref)return R("Cannot resolve a dev container by its bare name; use its full host path."),1;if(a.kind==="wsl"&&(t.platform??xu)()!=="win32")return R("--wsl is available only on Windows (win32)."),1;let s=t.isInteractive??mt;if(!r.yes&&!s())return R("remote requires a TTY; pass --yes only when you explicitly intend to configure that target."),1;if(r.revert||r.enroll||r.sso||r.claim||r.project||r.upstream||r.upstreamKey)return R("remote supports --gateway, --user, --team, --yes, --dry-run, and --key-stdin only."),1;if(r.dryRun)return N(`Dry run: would configure \`${a.name}\` remotely.`),0;let i;if(r.keyStdin)try{i=await HR()}catch{return R("could not read the personal gateway key from stdin."),1}let c=await(t.loadProfile??P)(),l=!r.gateway&&!process.env.ANYRAY_GATEWAY_URL?c.gateway:void 0,d=Vt(r.gateway??l),u=i||process.env.ANYRAY_CLIENT_KEY?.trim()||GR(c);if(!be(u))return R("A personal gateway key is required. Enroll locally first or provide ANYRAY_CLIENT_KEY (or --key-stdin)."),1;let f=await Vh(r.user,c.name,r.yes),p=await Kh(r.team,c.team,r.yes),m;try{m=await(t.runRemoteApply??Cg)(a,{gateway:d,user:f,team:p,clientKey:u})}catch(h){return R(h instanceof Error?h.message:String(h)),1}return m===0?N(`Remote \`${a.name}\` exited with code 0.`):(_(`Remote \`${a.name}\` exited with code ${m}.`),N(YR(a.kind))),m},JR=async(e,t,n={})=>{let r=n.isInteractive??mt,o;try{o=Sg(e)}catch($){return R($.message),A("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return A(o.helpAll?Iu:UR),0;if(o.revert&&(o.sso||o.enroll||o.claim))return R("--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?(R("--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):dI({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return R("--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 R("--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 R(`invalid --upstream URL: "${o.upstream}"`),1}if($.protocol!=="http:"&&$.protocol!=="https:")return R(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let D=o.upstreamKey.trim();if(!D)return R("--upstream-key must not be empty."),1;a={url:Gt(o.upstream),key:D}}let s=await P(),i;if(o.keyStdin)try{i=await HR()}catch{return R("could not read the personal gateway key from stdin."),1}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream);let c=!t&&mt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,l=!1;(t||c)&&r()&&(o=await(n.runWizard??R5)(o,s),l=!0);let d;try{if(d=f5(o.tools),n.managedEnrollmentRevertedTools){let $=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];d=sR(d,$)}}catch($){return R($.message),1}A(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&mi(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,A("That looks like an enrollment link \u2014 treating it as --enroll."));let u,f,p,m,h=!1;if(o.enroll){let $=gd(o.enroll);if($&&(!o.gateway||s.enrolledCert||oh($.token)))try{let D=await Pi("Resolving enrollment link\u2026",()=>AS($)),X=!o.gateway;X&&(o.gateway=D.gatewayUrl),u=D.deploymentId,f=D.email,p=D.provisioningKind,m=D.allowedDomains,h=!0,X&&N(`Enrollment link${D.org?` for ${D.org}`:""}: gateway ${D.gatewayUrl}`),D.seatMode&&!o.subscription&&(o.subscription=!0,N("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(D){if(oh($.token))return R(D instanceof Error?D.message:String(D)),1;let X=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(X)N(`Could not resolve the gateway from the enrollment link \u2014 using ${X}.`);else return R(D instanceof Error?D.message:String(D)),1}}let g,y;if(o.claim&&!o.revert)if(o.dryRun)N("dry run: not enrolled (skipped redeeming the enrollment link).");else{let $=PS(o.claim);if(!$)return R("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let D=await Pi("Connecting this machine\u2026",()=>DS({cpOrigin:$.cpOrigin,claim:$.claim,gatewayUrl:o.gateway}));g={cert:D.cert,privateKeyPem:D.privateKeyPem},D.deploymentId&&(u=D.deploymentId),!o.gateway&&D.gatewayUrl&&(o.gateway=D.gatewayUrl),y=D.ssoLink}catch(D){return R(D instanceof Error?D.message:String(D)),1}}if(o.sso&&!g&&!o.revert)if(o.dryRun)N("dry run: not enrolled via SSO (skipped minting a personal key).");else{let $=Et(o.sso);if(!$)return R(mi(o.sso)?"that is an enrollment link, not an SSO link \u2014 re-run with --enroll instead of --sso.":"invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let D=await bd({cpOrigin:$.cpOrigin,tenantId:$.tenantId,gatewayUrl:o.gateway,log:G=>N(G),open:r()?Fa:void 0}),X=await Pi("Waiting for SSO sign-in\u2026",()=>Ad(D,{gatewayUrl:o.gateway}));g={cert:X.cert,privateKeyPem:X.privateKeyPem},X.deploymentId&&(u=X.deploymentId),!o.gateway&&X.gatewayUrl&&(o.gateway=X.gatewayUrl)}catch(D){return R(D instanceof Error?D.message:String(D)),1}}let w=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;w&&(o.gateway=w);let b;try{b=Vt(o.gateway)}catch($){return R($.message),1}let k,C;w&&!o.revert&&N(`Gateway: ${b} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&xg(b)&&_(`${b} 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 S=i??process.env.ANYRAY_CLIENT_KEY?.trim(),E=S||GR(s),I,O,T,U,z,K,oe=async $=>{await vo();let D=vS($.token),X=RS(s.enrolledCert,s.enrolledCertExpiry,$.deploymentId,Date.now(),D,s.enrolledTokenHash,$.expectedUser),G=X?await Be():void 0,xe=Wt()||void 0,ht=X&&G&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:G,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,yt=gt=>OS({cpOrigin:$.cpOrigin,token:$.token,gatewayOrigin:b,email:$.email,team:$.team,machineId:$.machineId,deploymentId:$.deploymentId,machineUuid:xe,reuse:gt?ht:void 0}),De=!!ht,qe=await(async()=>{try{return await yt(De)}catch(gt){if(ht&> instanceof ct&>.policyCode!=="managed_device_required")return N("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),De=!1,await yt(!1);throw gt}})();E=qe.clientKey,o.user=Eu(o.user,qe.user),o.team=Eu(o.team,qe.team),I=qe.cert,O=qe.cert.payload.expiresAt,K=qe.expiresAt,z=void 0,De||(T=qe.privateKeyPem),De||(U=D),B(`Enrolled${qe.user?` as ${qe.user}`:""}${De?" (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)N("dry run: not enrolled (skipped minting a personal key).");else{let $=gd(o.enroll);if(!$){let D=bS(o.enroll);return R(D?`that is ${D.what}, not an enrollment link \u2014 re-run with ${D.flag} instead of --enroll.`:Et(o.enroll)?"that is an SSO link, not an enrollment link \u2014 re-run with --sso instead of --enroll.":"invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1}try{let D=o.machine?Od():void 0,X=p==="mdm"&&!f?cx():void 0,G=p==="mdm"&&!f&&!X?ix(m,Bd()):void 0,xe=X??G;if(xe){let De=X?"the email your MDM assigned to this machine":`${xe} (this Mac's login name at the first allowed domain)`;A(o.user?.trim()&&o.user.trim()!==xe?`Ignoring --user: enrolling as ${De}.`:`Enrolling as ${De}.`)}let ht=f??xe??p5(o.user);if(!o.machine&&!o.user&&!f&&!xe){let De=rI();De.distinct||(_(` Enrolling as "${De.identity}" \u2014 this may not be unique to you.`),_(De.reason==="machine_default"?" That looks like a machine or container default, so every developer on":" No personal git email is set, so machines sharing this image can"),_(De.reason==="machine_default"?" this image would enroll as the same person and their spend would merge.":" enroll under the same name and their spend would merge."),_(" Re-run with `--user you@company.com` (or set `git config --global"),_(" user.email`) so your usage is attributed to you."))}let yt=o.machine?`machine:${D}`:h?ht:void 0;await oe({cpOrigin:$.cpOrigin,token:$.token,email:ht,team:o.team,machineId:D,deploymentId:u,expectedUser:yt})}catch(D){return R(D instanceof Error?D.message:String(D)),D instanceof ct&&D.policyCode!=="managed_device_required"&&N("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."),ES(D)?3:1}}if(g){await vo();try{let $=Wt()||void 0,D=await qt(b,g.cert,g.privateKeyPem,{machineUuid:$});E=D.key,o.user=Eu(o.user,D.user),o.team=Eu(o.team,D.team),I=g.cert,O=g.cert.payload.expiresAt,T=g.privateKeyPem,K=D.expiresAt;let X=o.sso?Et(o.sso):void 0;z=X?`${X.cpOrigin}/sso/${X.tenantId}`:y,B(`Enrolled${D.user?` as ${D.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch($){return R($ instanceof Error?$.message:String($)),$ instanceof ct&&$.policyCode!=="managed_device_required"&&N("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;k=await Vh(o.user,s.name,$),C=await Kh(o.team,s.team,$)}if(!o.revert&&!o.dryRun){let $=Cx(await Ax(b,E),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if($.lane){let D=$.lane==="subscription";o.subscription=D,o.placeholder=!D;let X=D?"your own subscription seat":"the organization's provider account";$.overrodeFlag?N(`Your administrator assigns this machine to ${X}, so that is what was applied (it overrides the lane flag you passed).`):N(`Billing lane set by your administrator: ${X}.`)}}let ae;!o.revert&&!o.subscription&&!o.placeholder&&(ae=await yn(),H("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?ze("BYO upstream key (passthrough)"):ae.anthropic?ze("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${ae.openai?ze("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),!ae.anthropic&&!ae.openai&&!ae.copilot&&Hr()&&(_(" No subscription sign-ins found on this host. Sign-ins do not cross the"),_(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),_(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),_(" and re-run, or everything below routes on the org key instead.")));let Z=Oe({origin:b,placeholderKey:o.key,clientKey:E,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:ae,user:k,team:C,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),ie=o.revert===!0&&(o.tools?.length??0)===0,F={dryRun:o.dryRun,fullRevert:ie};if(!o.revert&&Z.clientKey&&!be(Z.clientKey))return R("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&&!Z.clientKey){H("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(" Dry run only \u2014 no placeholder configuration will be written."),await WR(d,"after-enrollment"),N(`
|
|
1062
|
+
Dry run complete \u2014 no files were written.`),0):(R(` ${$}`),1)}o.revert||m5(Z,d);let Y=!o.revert&&!o.yes&&r();(l||Y)&&!o.revert&&await WR(d,"plan"),Y&&await y5(),o.dryRun&&N(`
|
|
1063
|
+
Dry run \u2014 no files will be written.`);let te=await $5(o,l,d.length,{isInteractive:r,confirm:n.confirm});if(te==="non-interactive")return R(`
|
|
1061
1064
|
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(te==="declined")return N(l?"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 Qd(Z.origin);if(!$.reachable)return R(`
|
|
1062
1065
|
Gateway ${Z.origin} is not reachable (${$.detail}).`),A(v(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1063
1066
|
that would break them until you re-run with --revert.`)),A(`
|
|
1064
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1;B(`Gateway reachable (${$.detail}).`)}let Ue=o.revert?[]:await
|
|
1065
|
-
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),A("Run --revert with no --tools to remove it."));let gt=d,Xa=
|
|
1067
|
+
Start the gateway and try again, or pass --force to configure anyway.`),1;B(`Gateway reachable (${$.detail}).`)}let Ue=o.revert?[]:await v5(d,Z.origin),ve=[],ge=()=>{ve.length!==0&&(H("Reopening"),x5(ve),ve=[])};if(Ue.length>0){let $=Ue.map(X=>X.title),D=$.length===1?"it":"them";if(H("Open apps"),S5(o,mt()))o.quitApps===!0||await Eo(E5($))?ve=await I5(Ue):N(` Leaving ${D} open \u2014 restart when convenient.`);else{let X=o.noQuitApps===!0?"":" (or pass --quit-apps)";N(o.dryRun?` Would offer to quit ${$.join(", ")} \u2014 dry run, nothing was closed.`:` ${$.join(", ")} ${$.length===1?"is":"are"} open; restart ${D} to pick this up${X}.`)}}let Ht=async()=>{if(!o.dryRun)try{await Qe()}catch{return R("Could not prepare the owner-only Anyray state directory."),1}let $=$E(s,K),D=s.anyrayFleetManaged===!0&&await Ro().catch(()=>!1),X=X0(o,xu(),D),G=!!(S&&Z.clientKey===S&&!I),xe=!G&&!!(I??s.enrolledCert),ht=d.some(Me=>NE.has(Me.id)),yt=!o.revert&&o.noKeyRefresh!==!0&&xe&&($||!ht),De=o.dryRun?await Uo(s):await gp(),qe=De==="healthy";if(De==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath),!o.revert&&!o.dryRun){let Me={...s,managedEnrollmentDisabled:void 0,gateway:Z.origin,name:k,team:C,clientKey:Z.clientKey??s.clientKey,enrolledCert:G?void 0:I??s.enrolledCert,enrolledCertExpiry:G?void 0:O??s.enrolledCertExpiry,enrolledTokenHash:G?void 0:U??s.enrolledTokenHash,ssoLink:G?void 0:g?z:I?void 0:s.ssoLink,clientKeyExpiresAt:G?void 0:K??(Z.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:Z.authMode,byoUpstream:Z.byoUpstream,refreshSchedulerEnabled:yt};try{await w5(s,Me,T,void 0,G)}catch{return R("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}K&&!G&&await La({expiresAt:K})}if(ie)if(o.dryRun)await Gu()&&(H("Enrollment"),A(" would remove the stored gateway credential"));else{await hg(s),await Md().catch(()=>{});try{await tc()&&(H("Enrollment"),B(" Removed the stored gateway credential."),N(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(Me){H("Enrollment"),_(" Could not remove the stored gateway credential."),_(` Delete ${Q()} by hand, or a credential refresh may restore your tool config.`)}}else o.revert&&!o.dryRun&&(A(`
|
|
1068
|
+
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),A("Run --revert with no --tools to remove it."));let gt=d,Xa=C5(gt,o,s.managedTools);if(Xa.length>0){H("Not configured \u2014 needs your say-so");for(let Re of Xa)_(` ${Re.id}: ${KR(Re)??"changes where inference is billed"}.`),A(` Configure it deliberately with \`npx anyray-connect --tools ${Re.id}\`.`);let Me=new Set(Xa.map(Re=>Re.id));gt=gt.filter(Re=>!Me.has(Re.id))}if(o.revert&&!ie){let Me=d.filter(Re=>yi(s,Re.id));if(Me.length>0){H("Fleet policy");for(let Re of Me)_(` ${Re.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);gt=d.filter(Re=>!yi(s,Re.id))}}let{changes:Ji,manual:To,manualAdminOnly:za,manualAdminOnlyIds:qa,results:Qa}=await b5(gt,Z,F,o.revert,new Set(o.tools??[])),es;if(og(o)){H("Endpoint agent");try{es=await(n.installEndpointAfterEnrollment??aR)({gateway:b,clientKey:Z.clientKey})}catch{N("Endpoint agent setup did not complete. Tool routing remains configured.")}}let Ru=X&&J0(es),Eg=yt&&!Ru;if(X&&!Ru&&yt&&!o.dryRun&&N(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),Ru&&!o.dryRun&&await le({...await P(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await Jn(Qa,o.revert,ie).catch(()=>{}),ie&&await nc().catch(()=>{})),await T5({want:Eg,scopedRevert:!!o.revert&&!ie,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!Eg&&await Ec(),trayManaged:qe}),!o.revert&&!o.dryRun&&!G){let Me=T??await Be();Me&&await $h(await P(),Me).catch(()=>{})}if(ge(),H("Summary"),o.dryRun)N("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){B(`Reverted (${Ji} file(s) touched).`),N("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let Me=await lI();Me.length>0&&(H("This repo carries its own Anyray routing"),_(` Committed here: ${Me.join(", ")}`),_(" Those are tracked files, so they route every checkout of this"),_(" repo \u2014 this machine included, and your teammates' too. This"),_(" revert only removed THIS machine's own configuration."),A(`
|
|
1066
1069
|
Remove them from the repo (then commit):`),A(v(" anyray-connect --project --revert")));let Re=Bc(Z);Re.length>0&&(H("This terminal still points at the gateway"),_(` Still exported here: ${Re.join(", ")}`),_(" Removing the block from your shell profile cannot reach a shell"),_(" that already ran it. Until these are gone, your tools keep"),_(" reaching the gateway and now fail with 401."),A(`
|
|
1067
1070
|
Fix this terminal:`),A(v(` unset ${Re.join(" ")}`)),A(`
|
|
1068
|
-
Every other open terminal needs the same \u2014 or just open a new one.`),A(" VS Code injects a copy it captured when IT launched, so its"),A(" terminals stay stale even if you open a new one: quit the app"),A(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(B(`Done (${Ji} file(s) written).`),To.length>0){let Rt=za.length===To.length;H(Rt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let
|
|
1069
|
-
Skipped the connection smoke test (--skip-verify).`):await
|
|
1071
|
+
Every other open terminal needs the same \u2014 or just open a new one.`),A(" VS Code injects a copy it captured when IT launched, so its"),A(" terminals stay stale even if you open a new one: quit the app"),A(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(B(`Done (${Ji} file(s) written).`),To.length>0){let Rt=za.length===To.length;H(Rt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let Ig of A5(To,za,qa.includes("claude-desktop")?process.platform:void 0))_(Ig);if(qa.includes("claude-desktop")&&!o.dryRun)try{await k5(Z)}catch{_(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}mt()&&!o.yes&&!Rt&&(await Eo("Have you applied the manual settings shown above?")?B("Acknowledged."):_("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?N(`
|
|
1072
|
+
Skipped the connection smoke test (--skip-verify).`):await O5(Z,d.map(Rt=>Rt.id)),H("What's next");let Me=new Set(Qa.filter(Rt=>Rt.status==="configured").map(Rt=>Rt.id)),Re=d.filter(Rt=>Me.has(Rt.id)).map(Rt=>Rt.title);if(A(Re.length>0?` Connected: ${Re.join(", ")}`:" Connected: no tools completed automatic configuration."),A(" Restart any editor that was already running \u2014 it loaded our config at startup."),A(" If something looks wrong: npx anyray-connect doctor"),be(Z.clientKey)&&await K5({interactive:mt(),managed:n.managedEnrollmentRevertedTools!==void 0,yes:!!o.yes,revert:!!o.revert,dryRun:!!o.dryRun,gateway:Z.origin,user:Z.metadata.user,team:Z.metadata.team,clientKey:Z.clientKey}),!o.verbose)return 0;A(`
|
|
1070
1073
|
Re-test by hand any time:`),Z.authMode!=="placeholder"&&d.length===1&&d[0]?.id==="cursor"?(A(v(` curl -sS ${Z.origin}/connect/savings \\
|
|
1071
1074
|
-H "x-anyray-api-key: $(anyray-connect print-key)"`)),A(v(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):A(v(` curl -sS ${Z.openaiBaseUrl}/chat/completions \\
|
|
1072
1075
|
-H "Content-Type: application/json" \\
|
|
1073
1076
|
-H "Authorization: Bearer ${Z.clientKey?`<your personal key (${Pt(Z.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
|
|
1074
|
-
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),A(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await
|
|
1077
|
+
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),A(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await N5(o.revert,o.dryRun,Ht,n.withProfileLock)}catch($){if($ instanceof Error&&$.message==="connect profile is busy; retry the command")return R("Another Connect update is in progress. Try again."),1;throw $}finally{ge()}};ZR(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
|