anyray-connect 0.11.149 → 0.11.152
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 +168 -167
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var PR="http://localhost:8787",rs="anyray-placeholder",
|
|
3
|
-
`;if(a||n.tombstoneAbsent!==!1)try{await
|
|
4
|
-
`),await he(o,e),await UR(e,384),await HR(e)}finally{await qt(o,{force:!0}).catch(()=>{})}},
|
|
5
|
-
`,{mode:384})}catch(a){throw await Br(e,{recursive:!0,force:!0}).catch(()=>{}),a}return async()=>{try{JSON.parse(await ss(t,"utf-8")).nonce===r&&await Br(e,{recursive:!0,force:!0})}catch{}}}catch(a){if(a.code!=="EEXIST")throw a}if(!(await rO(e).catch(()=>!1)&&await Br(e,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=n)throw new Error("connect profile is busy; retry the command");await new Promise(a=>setTimeout(a,eO))}}},
|
|
6
|
-
`,{mode:384}),await
|
|
7
|
-
`)},fn=(e,t={})=>{let n=e.byoUpstream,r=!n&&X(e,"anthropic"),o=de({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1&&!((r||n)&&e.viaLocalProxy),s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=CO(o,r,a?e.clientKey:void 0,n?.url);return{env:{ANTHROPIC_BASE_URL:e.anthropicBaseUrl,...c?{ANTHROPIC_CUSTOM_HEADERS:c}:{},...n&&s?{ANTHROPIC_AUTH_TOKEN:n.key}:{},...r||n||!s?{}:{ANTHROPIC_AUTH_TOKEN:e.clientKey??e.placeholderKey},...n?{}:{ENABLE_TOOL_SEARCH:"true"},...n?{}:{_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL:"1"},...i!==void 0?{CLAUDE_CODE_MAX_CONTEXT_TOKENS:String(i)}:{}},subscription:r,byoUpstream:!!n,meta:o,headers:c}};import{z as
|
|
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}},dw=async()=>{try{let e=await L();return e.gateway?{origin:new URL(e.gateway).origin,metadata:de({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},at=async(e="auto")=>e==="profile"?dw():e==="claude"?lw():await lw()??await dw(),Oc=async(e={})=>{let t=e.readTarget??at,n=e.loadProfile??L,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return ot(r)&&r.fallbackPort&&a.add(`http://${mt}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},Qt=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},_c=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),FO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Qt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var Ln=()=>Tc(Pc(),".claude","settings.json"),hs=()=>Tc(Pc(),".claude.json"),BO=Ec,lr="anyray",WO=()=>({type:"stdio",...Ve("claude"),alwaysLoad:!0}),Gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),HO=e=>{if("mcpServers"in e&&!Gr(e.mcpServers))return"conflict";let t=Gr(e.mcpServers)?{...e.mcpServers}:{},n=t[lr];return n!==void 0&&!zt(n,"claude")?"conflict":(t[lr]=WO(),e.mcpServers=t,"installed")},uw=e=>{let t=e.mcpServers;return!t||!(lr in t)||!zt(t[lr],"claude")?!1:(delete t[lr],Object.keys(t).length===0&&delete e.mcpServers,!0)},KO=e=>{Ac(e,"PostToolUse",Xe,Tn(Dt(Xe),{matcher:"*"})),Ac(e,"UserPromptSubmit",sr,Tn(Dt(sr)))},GO=e=>{Ac(e,"SessionStart",ir,Tn(Dt(ir),{async:!0}))},hw=e=>Wo(e,"SessionStart",ir),pw=e=>{let t=Wo(e,"PostToolUse",Xe),n=Wo(e,"UserPromptSubmit",sr),r=hw(e);return t||n||r},jO="print-key",VO=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Re()),jr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===jO&&VO(t)},YO=async(e,t)=>{let n=(await Fr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of BO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},ZO=e=>typeof e.apiKeyHelper=="string"&&!jr(e),mw=async e=>{let t=await ep(),n=async()=>t,[r,o,a]=await Promise.all([ew({userSettings:e,readManaged:n}),sw({userSettings:e,readManaged:n}).catch(()=>[]),aw({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},fw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await mw(e),o=Qu(t),a=cw(n);return{routingOverrides:[...t.map(i=>({problem:zu(i),fix:i.repairable?"Fix: run `anyray-connect doctor --repair` (or re-run `anyray-connect`) \u2014 apply disables this switch by pinning it empty in settings.json.":o,repairable:i.repairable})),...n.map(i=>({problem:iw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},dr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=Tc(Pc(),".claude"),t=await R(e);return{installed:t,detail:t?Ln():"no ~/.claude directory"}},async apply(e,t){let n=Ln(),r=await F(n),o=Jg(r),a=await Xg(e.origin,e.clientKey,o),s=qg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=fn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await mw(r),h=f.filter(x=>!x.repairable),m=f.filter(x=>x.repairable),w=[...h.map(x=>`WARNING: ${zu(x)}.`),...h.length?[Qu(h)]:[],...p.state==="fine"?[]:[`WARNING: ${xc(p)}.`,Rc(p)],...m.map(x=>tw(x)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let g=r.env??{};r.env={...g,...i};let y=r.env;for(let{name:x}of Dn)m.some(P=>P.name===x)?y[x]="":y[x]===""&&(process.env[x]??"").trim()===""&&delete y[x];if(u||delete y.ANTHROPIC_CUSTOM_HEADERS,c&&(g.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete y.ANTHROPIC_AUTH_TOKEN),l)for(let x of Zg)delete y[x];let b=!!e.clientKey,A=le(),v=ZO(r);!c&&!l&&b&&A&&!v?(r.apiKeyHelper=Yg(),y.ANTHROPIC_AUTH_TOKEN="",w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):jr(r)&&delete r.apiKeyHelper,v&&!c&&!l&&b&&A&&w.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&A?(GO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):hw(r),le()?(KO(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(pw(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await J(n,r);let I=[n],C=hs();try{let x=await F(C),P=!1;le()?HO(x)==="conflict"?w.push(`MCP name conflict in ${C}: mcpServers.${lr} is not owned by Anyray Connect, so it was left untouched.`):(P=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):P=uw(x),P&&(await J(C,x),I.push(C))}catch(x){w.push(`Could not register the Anyray MCP server in ${C} (${x instanceof Error?x.message:String(x)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:I}},skillsDir(){return Tc(Pc(),".claude","skills")},async watchPaths(){return[Ln(),hs()]},async pointsAt(e){let t=Ln();if(!await R(t))return!1;try{let o=(await F(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await F(Ln()).catch(()=>({}));return fw(e)},async routingOverrides(){let e=await F(Ln()).catch(()=>({}));return(await fw(e)).routingOverrides},async mcpStatus(){let e=hs();if(!await R(e))return{registered:!1,command:null};try{let r=(await F(e)).mcpServers?.[lr];return!r||!zt(r,"claude")?{registered:!1,command:null}:{registered:!0,command:typeof r.command=="string"?r.command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=Ln();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!Gr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>ar(c,Xe))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>ar(c,Xe)&&Gr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Gr(l)&&vc(l.command,Xe))))}}catch{e="unreadable"}let r,o=!0,a=hs();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!Gr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[lr];r=i===void 0?"missing":zt(i,"claude")?"owned":"foreign",r==="owned"&&(o=Sc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Hr()?"owned":"missing",beacon_target:await Oc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await F(Ln()),t=Gr(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=Ln();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await F(t),r=n.env,o=pw(n),a=jr(n);a&&delete n.apiKeyHelper;let s=r?await YO(t,r):[],i=zg(typeof n.model=="string"?n.model:void 0,(await Fr(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=hs();try{let d=await F(l);uw(d)&&(await J(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await se(t),{status:"reverted",messages:c,changedFiles:[t]}}};var we="0.11.149";var hn=e=>{let{command:t,args:n}=pn([e]);return{command:t,args:n}},ur=()=>Wr();import{homedir as yw,userInfo as JO}from"node:os";var ms=()=>{try{return yw()!==JO().homedir}catch{return!1}},Ho=e=>[`Skipped ${e} \u2014 HOME (${yw()}) 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 gt=(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,Vr=(e=process.env)=>gt(e)!==null,At=e=>e==="codespaces"||e==="devcontainer",pr=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var op="__anyray-fallback-proxy",ws="ai.anyray.connect.fallback",fr="anyray-fallback",Cw=ws,ke=8785,bs=60,ap="x-anyray-local",sp=()=>hn(op),gw=ur,Lc=async(e=ke)=>{let t=n=>new Promise(r=>{let o=zO();o.once("error",()=>r(!1)),o.listen(n,"127.0.0.1",()=>o.close(()=>r(!0)))});for(let n=e;n<e+20;n++)if(await t(n))return n;return e},be=async(e,t=1500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}/__anyray/health`,{signal:n.signal});return o.ok?await o.json():null}catch{return null}finally{clearTimeout(r)}},Vo=()=>jo(gs(),"Library","LaunchAgents",`${Cw}.plist`),ks=()=>jo(gs(),".anyray","logs"),ys=()=>jo(ks(),"connect-daemon.log"),Aw=async(e,t=1048576)=>{await bw(e).then(r=>r.size,()=>0)>t&&await qO(e).catch(()=>{})},Yo=()=>jo(gs(),".config","systemd","user",`${fr}.service`),tp=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Cs=(e=sp())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${tp(o)}</string>`).join(`
|
|
2
|
+
var PR="http://localhost:8787",rs="anyray-placeholder",xe=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Je=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},Iu=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,TR=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),mg=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!TR.has(n)}catch{return!1}},un=e=>{let t=Je(e||process.env.ANYRAY_GATEWAY_URL||PR),n;try{n=new URL(t)}catch{throw new Error(`invalid gateway URL: "${t}" (expected e.g. http://localhost:8787)`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`invalid gateway URL: "${t}" \u2014 must start with http:// or https://`);return t},mt="127.0.0.1",_n=(e,t)=>{let n=`http://${mt}:${t}`;return{...e,anthropicBaseUrl:n,openaiBaseUrl:`${n}/v1`,viaLocalProxy:!0}},ge=(e={})=>{let t=un(e.origin),n=e.placeholderKey?.trim()||rs,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:Iu(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:Iu(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:Iu(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 gs,platform as Go}from"node:os";import{join as jo}from"node:path";import{mkdir as rp,readFile as bw,rename as XO,stat as kw,truncate as qO,writeFile as Cw,rm as Ko}from"node:fs/promises";import{spawnSync as mn}from"node:child_process";import{createServer as zO}from"node:net";import{homedir as Pc}from"node:os";import{join as Tc}from"node:path";import{access as MR,chmod as UR,mkdir as Ru,open as Du,readFile as Ag,rm as qt,stat as gg,utimes as FR}from"node:fs/promises";import{createHash as BR,randomUUID as vg}from"node:crypto";import{dirname as Lu,join as WR}from"node:path";import{isDeepStrictEqual as No}from"node:util";import{randomUUID as DR}from"node:crypto";import{lstat as LR,rename as uc,rm as NR}from"node:fs/promises";import{platform as yg}from"node:os";var $R=e=>e?.code==="ENOENT",os=async(e,t=yg())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},he=async(e,t,n=yg())=>{if(n!=="win32"){await uc(e,t);return}let r=`${t}.anyray-old-${process.pid}-${DR()}`,o=!1;try{let a=await LR(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await uc(t,r),o=!0}catch(a){if(!$R(a))throw a}try{await uc(e,t)}catch(a){if(o)try{await uc(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await NR(r,{force:!0})};var as=e=>`${e}.anyray-bak`,Sg=async e=>{let t;try{t=await Du(Lu(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},wg=async(e,t)=>{let n,r;try{n=await Du(e,"wx",384),await n.writeFile(t,"utf-8"),await os(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await qt(e,{force:!0}).catch(()=>{}),r;await Sg(e)},HR=async e=>{let t;try{t=await Du(e,"r"),await os(t)}finally{await t?.close().catch(()=>{})}await Sg(e)},R=async e=>{try{return await MR(e),!0}catch{return!1}},F=async e=>{if(!await R(e))return{};let t=await Ag(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 Ru(Lu(e),{recursive:!0,mode:448});let r=as(e);if(n.backup!==!1&&!await R(r)){let a=await R(e),s=a?await Ag(e,"utf-8"):`{}
|
|
3
|
+
`;if(a||n.tombstoneAbsent!==!1)try{await wg(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${vg()}`;try{await wg(o,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`),await he(o,e),await UR(e,384),await HR(e)}finally{await qt(o,{force:!0}).catch(()=>{})}},Eg=1,bg=3e4,KR=5e3,GR=/^[a-f0-9]{64}$/,xg=e=>`${e}.pending`,jR=e=>`${e}.lock`,Ou=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=>Ou(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Ou(t[n])}`).join(",")}}`},_u=(e,t)=>({exists:e,sha256:BR("sha256").update(Ou(t)).digest("hex")}),Pu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),kg=e=>Pu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&GR.test(e.sha256),VR=e=>Pu(e)&&e.transactionVersion===Eg&&kg(e.before)&&kg(e.after)&&Pu(e.journal),Tu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,$o=async(e,t)=>{try{return await F(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},YR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Ig=async e=>{let t=jR(e),n=WR(t,"owner.json");await Ru(Lu(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=vg();try{await Ru(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await $o(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 gg(n)).mtimeMs;i=!YR(c.pid)||l>bg}catch{try{i=Date.now()-(await gg(t)).mtimeMs>bg}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await qt(t,{recursive:!0,force:!0});continue}try{await J(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await qt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await $o(n,"ownership journal")).nonce!==o)return;let i=new Date;await FR(n,i,i)}catch{}})()},KR);return a.unref(),async()=>{clearInterval(a);try{(await $o(n,"ownership journal")).nonce===o&&await qt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},Rg=async e=>{let t=await R(e),n={};if(t)try{n=await F(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:_u(t,n)}},Og=async(e,t)=>{let n=xg(t);if(!await R(n))return;let r=await $o(n,"prepared ownership transaction");if(!VR(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await Rg(e),a=await R(t),s=await R(as(e)),i=Tu(o.fingerprint,r.before),c=Tu(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 qt(n,{force:!0});return}if(i){await qt(n,{force:!0}),a||await se(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},pc=async(e,t,n)=>{let r=await Ig(t);try{return await Og(e,t),await n()}finally{await r()}},Cg=async(e,t,n,r)=>{if(!await R(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await $o(e,"ownership journal");if(!(n&&No(a,t))){if(!No(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await J(e,t,{backup:!1}):await qt(e,{force:!0})}},fc=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await Ig(a);try{await Og(n,a);let l=await Rg(n),d=_u(i,r),u=await R(a),f=u?await $o(a,"ownership journal"):void 0,p=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!Tu(l.fingerprint,d)){if(No(l.value,o)&&f&&No(f,p))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&No(l.value,o)&&f&&No(f,p))return;let h=await R(as(n));if(f?.fileExisted===!0&&!h)throw new Error("ownership backup is missing; configuration was left unchanged");if(h&&!f)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let m=xg(a),w={transactionVersion:Eg,before:l.fingerprint,after:_u(!0,o),journal:p};await J(m,w,{backup:!1});try{await J(n,o,f?{backup:!1}:{tombstoneAbsent:!1}),await(t.writeJournal??J)(a,p,{backup:!1}),await qt(m,{force:!0})}catch(g){try{await Cg(n,l.value,l.exists,o)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed and config rollback was incomplete")}try{await Cg(a,f??{},u,p),await qt(m,{force:!0}),!h&&!f&&await se(n)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed after config rollback")}throw g}}finally{await c()}},Fr=async e=>{try{return await F(as(e))}catch{return{}}},se=async e=>{await qt(as(e),{force:!0}).catch(()=>{})};import{access as bO}from"node:fs/promises";import{spawnSync as oO}from"node:child_process";import{readFileSync as aO,realpathSync as cs,statSync as Fg}from"node:fs";import{access as sO,cp as Bg,mkdir as Mg,readdir as iO,readFile as Ku,realpath as cO,rename as lO,rm as Wu,writeFile as dO}from"node:fs/promises";import{tmpdir as uO}from"node:os";import{basename as Uo,dirname as Ge,join as Ie,resolve as pO}from"node:path";import{writeFile as hc,readFile as ss,chmod as $u,stat as Mu,mkdir as Pg,rm as Br,access as ZR}from"node:fs/promises";import{randomUUID as JR}from"node:crypto";import{homedir as Tg}from"node:os";import{join as Pn}from"node:path";var ee=()=>Pn(Tg(),".anyray"),Mo=async()=>{let e=ee();try{if((await Mu(e)).isDirectory())return Pn(e,"connect.json")}catch{}return e},Uu=()=>Pn(ee(),"dev-key.pem"),Ct=async()=>{let e=ee(),t;try{if(!(await Mu(e)).isDirectory())t=await ss(e,"utf-8").catch(()=>{}),await Br(e,{force:!0});else return}catch{}if(await Pg(e,{recursive:!0,mode:448}),t!==void 0){let n=Pn(e,"connect.json");await hc(n,t,{mode:384}),await $u(n,384)}},mc=async e=>{await Ct();let t=Uu();await hc(t,e,{mode:384}),await $u(t,384)},We=async()=>{try{let e=await ss(Uu(),"utf-8");return e.trim()?e:void 0}catch{return}},is=async()=>{await Br(Uu(),{force:!0}).catch(()=>{})},XR=e=>{let{fallbackEnabled:t,fallbackGatewayTimeoutMs:n,fallbackBreaker:r,...o}=e,a=o;return t===!0&&(a.keyRefreshEnabled=!0),a},L=async()=>{try{let e=await ss(await Mo(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:XR(t)}catch{return{}}},qR=0,zR=3e4,QR=5e3,eO=25,tO=()=>Pn(Tg(),".anyray-connect-profile.lock"),nO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},rO=async e=>{try{let t=JSON.parse(await ss(Pn(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!nO(t.pid)}catch{}return Date.now()-(await Mu(e)).mtimeMs>zR},Dg=async()=>{let e=tO(),t=Pn(e,"owner.json"),n=Date.now()+QR;for(;;){let r=JR();try{await Pg(e,{mode:448});try{await hc(t,`${JSON.stringify({pid:process.pid,nonce:r})}
|
|
5
|
+
`,{mode:384})}catch(a){throw await Br(e,{recursive:!0,force:!0}).catch(()=>{}),a}return async()=>{try{JSON.parse(await ss(t,"utf-8")).nonce===r&&await Br(e,{recursive:!0,force:!0})}catch{}}}catch(a){if(a.code!=="EEXIST")throw a}if(!(await rO(e).catch(()=>!1)&&await Br(e,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=n)throw new Error("connect profile is busy; retry the command");await new Promise(a=>setTimeout(a,eO))}}},Lg=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Mo(),r=`${n}.${process.pid}.${qR++}.tmp`;await hc(r,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,{mode:384}),await $u(r,384);try{await he(r,n)}catch(o){throw await Br(r,{force:!0}).catch(()=>{}),o}},oe=async e=>{let t=await Dg();try{await Lg(e)}finally{await t()}},Ng=async e=>{let t=await Dg();try{let n=await L(),{next:r,result:o}=e(n);return r&&await Lg(r),o}finally{await t()}},Nu=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],_g="ssoLink",Fu=async()=>{let e=await L();return Nu.some(t=>e[t]!==void 0)?!0:await We()!==void 0},yc=async()=>{let e=await L(),t=Nu.some(a=>e[a]!==void 0),n=e[_g]!==void 0,r=e.byoUpstream!==void 0,o=await We()!==void 0;if(!t&&!n&&!r&&!o)return!1;if(t||n||r){let a={...e};for(let s of Nu)delete a[s];delete a[_g],delete a.byoUpstream,delete a.anyrayFleetManaged,await oe(a)}if(await is(),await We())throw new Error(`could not remove the dev key from ${ee()}`);return!0},$g=["fallback-bundle.enc","fallback-key","fallback-usage-queue.jsonl"],gc=async()=>{let e=ee();for(let t of $g)await Br(Pn(e,t),{force:!0}).catch(()=>{})},Bu=async()=>{let e=ee(),t=[];for(let n of $g){let r=Pn(e,n);try{await ZR(r),t.push(r)}catch{}}return t},rr=async(e,t,n=!1)=>{let r=await L(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let h of e){let m=h.status==="configured"||h.status==="queued";!t&&m&&(o.add(h.id),a.delete(h.id),s=void 0),t&&(h.status==="reverted"||h.status==="queued")&&(o.delete(h.id),a.add(h.id))}n&&o.clear();let i=[...o].sort(),c=[...r.managedTools??[]].sort(),l=[...a].sort(),d=[...r.revertedTools??[]].sort();if(i.length===c.length&&i.every((h,m)=>h===c[m])&&r.revertedTools!=null&&l.length===d.length&&l.every((h,m)=>h===d[m])&&s===r.offboardedAt)return;let{offboardedAt:f,...p}=r;await oe({...p,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},wc=async(e=new Date().toISOString())=>{await oe({...await L(),offboardedAt:e})};var Fo=e=>pO(e).replace(/\\/g,"/").toLowerCase(),Hu=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",ls=e=>`${e}.source`,Wg=e=>/(^|\/)_npx(\/|$)/.test(Fo(e)),Gu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Fo(e)),ju=e=>{let t=Fo(e),n=[uO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Fo);return Wg(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},yt=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),ds=e=>/[\\/](node|node\.exe)$/i.test(e),or=(e=yt())=>ds(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,Ug=e=>{try{let t=Fg(e);return t.isFile()?t.size:void 0}catch{return}},Vu=e=>{let t=Ge(e);if(Uo(t)==="versions")return t;let n=Ge(t);return Uo(n)==="versions"?n:void 0},kc=(e,t)=>t!==void 0&&(Ge(e)===t||Ge(Ge(e))===t),fO=e=>{let t=Vu(e);if(!t)return;let n=Ie(Ge(t),"bin",Hu());try{let r=cs(n);return r===cs(e)||kc(r,cs(t))?n:void 0}catch{return}},Bo=(e=ee(),t=process.platform)=>{let n=Ie(e,"bin",Hu(t));try{let r=cs(n),o=cs(Ie(e,"versions"));if(kc(r,o))return n;if(t==="win32"){let a=aO(ls(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=Ug(Ie(o,a,Hu(t)))??Ug(Ie(o,a));if(s!==void 0&&s===Fg(n).size)return n}}catch{return}},Wr=(e=yt())=>{let t=or(e),n=Gu(t)||Zu(t)?Bo():void 0;return fO(e.execPath)??n??t},Hg=(e=yt())=>Wr(e)!==or(e),pn=(e,t=yt())=>{let n=Wr(t);return ds(t.execPath)&&t.scriptPath!==void 0&&n===or(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},Kg=(e=yt())=>{let t=Wr(e);return!ds(e.execPath)&&!ju(t)?Ge(t):Ie(ee(),"bin")},bc=async e=>{try{return await sO(e),!0}catch{return!1}},hO=async e=>{let t=await cO(e),n=Ge(t),r=Ge(n),o=Ie(r,"package.json"),a=await Ku(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 bc(Ie(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},mO=async(e,t)=>{let n=t;for(;;){let r=Ie(n,"node_modules",e);if(await bc(Ie(r,"package.json")))return r;let o=Ge(n);if(o===n)return;n=o}},yO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Ku(Ie(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await mO(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Bg(i,Ie(t,s),{recursive:!0}),r.push(i)}}},gO=async(e=yt())=>{let t=Bo();if(t)return{command:t,args:[],entryPath:t};if(!ds(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await hO(e.scriptPath);await Ct();let r=Ie(ee(),"bin",`connect-runtime-${n.version}`),o=Ie(r,"dist","index.js");if(!await bc(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Wu(a,{recursive:!0,force:!0}),await Mg(a,{recursive:!0,mode:448});try{await Bg(n.dist,Ie(a,"dist"),{recursive:!0}),await dO(Ie(a,"package.json"),await Ku(n.packageJson),{mode:384}),await yO(n.root,Ie(a,"node_modules")),await Mg(Ge(r),{recursive:!0,mode:448});try{await lO(a,r)}catch(s){if(!await bc(o))throw s}}finally{await Wu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Yu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,wO=e=>{let t=Uo(Ge(Ge(e)));return Yu.test(t)?t:void 0},Zu=(e,t=ee())=>{let n=Ge(Ge(e));return Fo(Ge(n))===Fo(Ie(t,"bin"))&&Yu.test(Uo(n))&&Uo(Ge(e))==="dist"&&Uo(e)==="index.js"},Cc=async(e=yt())=>{let t=Ie(ee(),"bin"),n=wO(or(e)),r=[];for(let o of await iO(t).catch(()=>[])){if(!Yu.test(o)||o===n)continue;let a=Ie(t,o);await Wu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},Gg=async(e,t=yt())=>{let n=or(t);if(!ds(t.execPath)||!Wg(n)||Bo())return;let r=await gO(t),o=oO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Ju=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,us=(e,t)=>[e,...t].map(Ju).join(" "),Tn=(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}:{}}]}),ar=(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))},Ac=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!ar(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},Wo=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!ar(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)},Xu=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=>!ar(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 Xe="__anyray-hook",jg="__anyray-codex-hook",sr="__anyray-prompt-hook",Vg="__anyray-shell-pretool",qu="__anyray-shell-run",Yg="__anyray-read-pretool",ir="__anyray-refresh",ps=(e,t=[])=>{let{command:n,args:r}=pn([e,...t]);return{command:n,args:r}},Dt=(e,t=[])=>{let n=ps(e,t);return[n.command,...n.args].map(Ju).join(" ")},vc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Dt(t,n),Zg=()=>Dt("print-key"),Re=()=>Wr(),je=ju,le=()=>!je(Re()),Hr=async()=>{if(!le())return!1;try{return await bO(Re()),!0}catch{return!1}},cr="__anyray-mcp-server",Ve=e=>ps(cr,[e]),kO=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),Sc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ve(t);return n.command===r.command&&kO(n.args,r.args)},zt=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(typeof n.command!="string"||!Array.isArray(n.args)||!n.args.every(o=>typeof o=="string"))return!1;let r=n.args;return(r.length===2||r.length===3)&&r.at(-2)===cr&&r.at(-1)===t};var X=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,de=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Kr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Jg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Ec=[...Kr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],CO=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
|
|
7
|
+
`)},fn=(e,t={})=>{let n=e.byoUpstream,r=!n&&X(e,"anthropic"),o=de({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1&&!((r||n)&&e.viaLocalProxy),s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=CO(o,r,a?e.clientKey:void 0,n?.url);return{env:{ANTHROPIC_BASE_URL:e.anthropicBaseUrl,...c?{ANTHROPIC_CUSTOM_HEADERS:c}:{},...n&&s?{ANTHROPIC_AUTH_TOKEN:n.key}:{},...r||n||!s?{}:{ANTHROPIC_AUTH_TOKEN:e.clientKey??e.placeholderKey},...n?{}:{ENABLE_TOOL_SEARCH:"true"},...n?{}:{_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL:"1"},...i!==void 0?{CLAUDE_CODE_MAX_CONTEXT_TOKENS:String(i)}:{}},subscription:r,byoUpstream:!!n,meta:o,headers:c}};import{z as zu}from"zod";var AO=5e3,vO=1e3,SO=1e8,EO=zu.object({modelContext:zu.object({contextTokens:zu.number().int().min(vO).max(SO)}).optional()}),Xg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},qg=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??AO,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=EO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var xO=1e6,fs="[1m]",IO=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},zg=(e,t)=>!e||t===void 0?{}:IO(e)?{envTokens:t}:t<xO?{}:e.toLowerCase().endsWith(fs)?{}:{model:`${e}${fs}`},Qg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(fs))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(fs))return e.slice(0,-fs.length)};import{platform as RO}from"node:os";var Lt=(e=RO())=>{switch(e){case"darwin":return"/Library/Application Support/ClaudeCode/managed-settings.json";case"win32":return"C:\\Program Files\\ClaudeCode\\managed-settings.json";default:return"/etc/claude-code/managed-settings.json"}};var Dn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],xc=e=>typeof e=="string"&&e.trim()!=="",OO=(e,t)=>typeof e[t]=="string"&&!xc(e[t]),ew=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},_O=()=>F(Lt()).catch(()=>({})),tw=async(e={})=>{let t=e.env??process.env,n=ew(e.userSettings??{}),r=ew(await(e.readManaged??_O)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of Dn)xc(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Lt()})`,repairable:!1}):xc(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!OO(n,a)&&xc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Qu=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`,ep=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.",nw=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 PO=Dn.map(e=>e.name),TO=Ec.filter(e=>!PO.includes(e)),rw=e=>typeof e=="string"&&e.trim()!=="",ow=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},DO=(e,t,n)=>{if(typeof e!="string"||typeof t!="string")return!1;let r=o=>n?o.trim().replace(/\/+$/,""):o.trim();return r(e)===r(t)},LO=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},tp=()=>F(Lt()).catch(()=>({})),aw=tp,NO=e=>{let t=e.hooks;if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t.PostToolUse;return Array.isArray(n)&&n.some(r=>ar(r,Xe))},sw=async(e={})=>{let t=await(e.readManaged??aw)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!NO(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},Ic=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Lt()}) \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 (${Lt()}), 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",Rc=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.",iw=async(e={})=>{let t=ow(e.userSettings??{}),n=ow(await(e.readManaged??aw)().catch(()=>({}))),r=[];for(let o of TO){if(!rw(n[o])||!rw(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(DO(n[o],t[o],a))continue;let s=a?LO(n[o]):void 0;r.push({name:o,source:`managed settings (${Lt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},cw=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`,lw=e=>"Fix: the managed settings file is IT-owned \u2014 ask your admin to "+(e.some(t=>t.routing)?"point it at the Anyray gateway (`anyray-connect managed --print` emits the block to deploy) or drop the key so per-user setup governs":"drop the key so per-user setup governs")+", then restart Claude Code.";import{homedir as $O}from"node:os";import{join as MO}from"node:path";import{readFile as UO}from"node:fs/promises";var ot=e=>!!e.keyRefreshEnabled;var FO=400,dw=async()=>{try{let e=MO($O(),".claude","settings.json"),n=JSON.parse(await UO(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}},uw=async()=>{try{let e=await L();return e.gateway?{origin:new URL(e.gateway).origin,metadata:de({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},at=async(e="auto")=>e==="profile"?uw():e==="claude"?dw():await dw()??await uw(),Oc=async(e={})=>{let t=e.readTarget??at,n=e.loadProfile??L,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return ot(r)&&r.fallbackPort&&a.add(`http://${mt}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},Qt=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},_c=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),FO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Qt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var Ln=()=>Tc(Pc(),".claude","settings.json"),hs=()=>Tc(Pc(),".claude.json"),BO=Ec,lr="anyray",WO=()=>({type:"stdio",...Ve("claude"),alwaysLoad:!0}),Gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),HO=e=>{if("mcpServers"in e&&!Gr(e.mcpServers))return"conflict";let t=Gr(e.mcpServers)?{...e.mcpServers}:{},n=t[lr];return n!==void 0&&!zt(n,"claude")?"conflict":(t[lr]=WO(),e.mcpServers=t,"installed")},pw=e=>{let t=e.mcpServers;return!t||!(lr in t)||!zt(t[lr],"claude")?!1:(delete t[lr],Object.keys(t).length===0&&delete e.mcpServers,!0)},KO=e=>{Ac(e,"PostToolUse",Xe,Tn(Dt(Xe),{matcher:"*"})),Ac(e,"UserPromptSubmit",sr,Tn(Dt(sr)))},GO=e=>{Ac(e,"SessionStart",ir,Tn(Dt(ir),{async:!0}))},mw=e=>Wo(e,"SessionStart",ir),fw=e=>{let t=Wo(e,"PostToolUse",Xe),n=Wo(e,"UserPromptSubmit",sr),r=mw(e);return t||n||r},jO="print-key",VO=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Re()),jr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===jO&&VO(t)},YO=async(e,t)=>{let n=(await Fr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of BO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},ZO=e=>typeof e.apiKeyHelper=="string"&&!jr(e),yw=async e=>{let t=await tp(),n=async()=>t,[r,o,a]=await Promise.all([tw({userSettings:e,readManaged:n}),iw({userSettings:e,readManaged:n}).catch(()=>[]),sw({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},hw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await yw(e),o=ep(t),a=lw(n);return{routingOverrides:[...t.map(i=>({problem:Qu(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:cw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},dr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=Tc(Pc(),".claude"),t=await R(e);return{installed:t,detail:t?Ln():"no ~/.claude directory"}},async apply(e,t){let n=Ln(),r=await F(n),o=Xg(r),a=await qg(e.origin,e.clientKey,o),s=zg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=fn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await yw(r),h=f.filter(I=>!I.repairable),m=f.filter(I=>I.repairable),w=[...h.map(I=>`WARNING: ${Qu(I)}.`),...h.length?[ep(h)]:[],...p.state==="fine"?[]:[`WARNING: ${Ic(p)}.`,Rc(p)],...m.map(I=>nw(I)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let g=r.env??{};r.env={...g,...i};let y=r.env;for(let{name:I}of Dn)m.some(P=>P.name===I)?y[I]="":y[I]===""&&(process.env[I]??"").trim()===""&&delete y[I];if(u||delete y.ANTHROPIC_CUSTOM_HEADERS,c&&(g.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete y.ANTHROPIC_AUTH_TOKEN),l)for(let I of Jg)delete y[I];let b=!!e.clientKey,A=le(),v=ZO(r);!c&&!l&&b&&A&&!v?(r.apiKeyHelper=Zg(),y.ANTHROPIC_AUTH_TOKEN="",w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):jr(r)&&delete r.apiKeyHelper,v&&!c&&!l&&b&&A&&w.push("Kept your existing apiKeyHelper; your gateway key stays in ANTHROPIC_AUTH_TOKEN (Anyray auto-refresh via the helper is off)."),(c||l)&&b&&A?(GO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):mw(r),le()?(KO(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(fw(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await J(n,r);let x=[n],C=hs();try{let I=await F(C),P=!1;le()?HO(I)==="conflict"?w.push(`MCP name conflict in ${C}: mcpServers.${lr} is not owned by Anyray Connect, so it was left untouched.`):(P=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):P=pw(I),P&&(await J(C,I),x.push(C))}catch(I){w.push(`Could not register the Anyray MCP server in ${C} (${I instanceof Error?I.message:String(I)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:x}},skillsDir(){return Tc(Pc(),".claude","skills")},async watchPaths(){return[Ln(),hs()]},async pointsAt(e){let t=Ln();if(!await R(t))return!1;try{let o=(await F(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await F(Ln()).catch(()=>({}));return hw(e)},async routingOverrides(){let e=await F(Ln()).catch(()=>({}));return(await hw(e)).routingOverrides},async mcpStatus(){let e=hs();if(!await R(e))return{registered:!1,command:null};try{let r=(await F(e)).mcpServers?.[lr];return!r||!zt(r,"claude")?{registered:!1,command:null}:{registered:!0,command:typeof r.command=="string"?r.command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=Ln();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!Gr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>ar(c,Xe))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>ar(c,Xe)&&Gr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Gr(l)&&vc(l.command,Xe))))}}catch{e="unreadable"}let r,o=!0,a=hs();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!Gr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[lr];r=i===void 0?"missing":zt(i,"claude")?"owned":"foreign",r==="owned"&&(o=Sc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Hr()?"owned":"missing",beacon_target:await Oc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await F(Ln()),t=Gr(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=Ln();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await F(t),r=n.env,o=fw(n),a=jr(n);a&&delete n.apiKeyHelper;let s=r?await YO(t,r):[],i=Qg(typeof n.model=="string"?n.model:void 0,(await Fr(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=hs();try{let d=await F(l);pw(d)&&(await J(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await se(t),{status:"reverted",messages:c,changedFiles:[t]}}};var we="0.11.152";var hn=e=>{let{command:t,args:n}=pn([e]);return{command:t,args:n}},ur=()=>Wr();import{homedir as gw,userInfo as JO}from"node:os";var ms=()=>{try{return gw()!==JO().homedir}catch{return!1}},Ho=e=>[`Skipped ${e} \u2014 HOME (${gw()}) 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 gt=(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,Vr=(e=process.env)=>gt(e)!==null,At=e=>e==="codespaces"||e==="devcontainer",pr=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var ap="__anyray-fallback-proxy",ws="ai.anyray.connect.fallback",fr="anyray-fallback",Aw=ws,ke=8785,bs=60,sp="x-anyray-local",ip=()=>hn(ap),ww=ur,Lc=async(e=ke)=>{let t=n=>new Promise(r=>{let o=zO();o.once("error",()=>r(!1)),o.listen(n,"127.0.0.1",()=>o.close(()=>r(!0)))});for(let n=e;n<e+20;n++)if(await t(n))return n;return e},be=async(e,t=1500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}/__anyray/health`,{signal:n.signal});return o.ok?await o.json():null}catch{return null}finally{clearTimeout(r)}},Vo=()=>jo(gs(),"Library","LaunchAgents",`${Aw}.plist`),ks=()=>jo(gs(),".anyray","logs"),ys=()=>jo(ks(),"connect-daemon.log"),vw=async(e,t=1048576)=>{await kw(e).then(r=>r.size,()=>0)>t&&await qO(e).catch(()=>{})},Yo=()=>jo(gs(),".config","systemd","user",`${fr}.service`),np=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Cs=(e=ip())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${np(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">
|
|
12
12
|
<dict>
|
|
13
|
-
<key>Label</key><string>${
|
|
13
|
+
<key>Label</key><string>${Aw}</string>
|
|
14
14
|
<key>ProgramArguments</key>
|
|
15
15
|
<array>
|
|
16
16
|
${r}
|
|
@@ -19,11 +19,11 @@ ${r}
|
|
|
19
19
|
<key>KeepAlive</key><true/>
|
|
20
20
|
<key>ProcessType</key><string>Background</string>
|
|
21
21
|
<key>ExitTimeOut</key><integer>${bs}</integer>
|
|
22
|
-
<key>StandardOutPath</key><string>${
|
|
23
|
-
<key>StandardErrorPath</key><string>${
|
|
22
|
+
<key>StandardOutPath</key><string>${np(ys())}</string>
|
|
23
|
+
<key>StandardErrorPath</key><string>${np(ys())}</string>
|
|
24
24
|
</dict>
|
|
25
25
|
</plist>
|
|
26
|
-
`},As=(e=
|
|
26
|
+
`},As=(e=ip())=>{let{command:t,args:n}=e;return`[Unit]
|
|
27
27
|
Description=Anyray connect local key-refresh proxy
|
|
28
28
|
After=network-online.target
|
|
29
29
|
|
|
@@ -35,8 +35,8 @@ TimeoutStopSec=${bs}
|
|
|
35
35
|
|
|
36
36
|
[Install]
|
|
37
37
|
WantedBy=default.target
|
|
38
|
-
`},Dc=()=>{let{command:e,args:t}=
|
|
39
|
-
`,"utf-8")}catch{}},
|
|
38
|
+
`},Dc=()=>{let{command:e,args:t}=ip();return["Auto-start is not wired for this OS. Run the key-refresh proxy yourself:",` ${[e,...t].map(r=>/\s/.test(r)?JSON.stringify(r):r).join(" ")}`,"(keep it running in the background \u2014 your tools route through it)."]},Sw=async()=>{let e=Go();if(e!=="darwin"&&e!=="linux")return!1;let t=e==="darwin"?Vo():Yo();try{return await kw(t),!0}catch{return!1}},Ew=async()=>{let e=Go();if(e!=="darwin"&&e!=="linux")return!0;let t=e==="darwin"?Vo():Yo(),n=e==="darwin"?Cs():As();return await bw(t,"utf-8").catch(()=>null)===n},op=async e=>{await rp(jo(gs(),"Library","LaunchAgents"),{recursive:!0}),await rp(ks(),{recursive:!0,mode:448}),await Cw(e,Cs())},xw=async()=>{let e=Go();return e==="darwin"?(await op(Vo()),!0):e==="linux"?(await rp(jo(gs(),".config","systemd","user"),{recursive:!0}),await Cw(Yo(),As()),!0):!1},Iw=async()=>xw().catch(()=>!1),QO=async(e,t)=>{let n=Go();if(n!=="darwin"&&n!=="linux")return!1;let r=n==="darwin"?Vo():Yo(),o=n==="darwin"?Cs():As();if(await bw(r,"utf-8").catch(()=>null)!==o)return!1;let s=await be(e);return s?.version!==we?!1:typeof s.remoteOrigin=="string"&&Je(s.remoteOrigin)===Je(t)},Nt=async e=>{if(je(ww()))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 anyray-connect is running from a temporary path (${ww()}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(ms())return{ok:!1,messages:Ho("key-refresh auto-start")};{let n=gt();if(At(n))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 ${pr(n)} has no per-user service manager to supervise the daemon.`]}}if(await QO(e.port,e.remoteOrigin))return{ok:!0,messages:["Key-refresh service already current \u2014 left running."]};let t=Go();try{if(t==="darwin"){let n=Vo(),r=String(process.getuid?.()??""),o=`${n}.new-${process.pid}`;await Ko(o,{force:!0}).catch(()=>{}),await op(o),mn("launchctl",["bootout",`gui/${r}`,n]),await Ko(n,{force:!0}).catch(()=>{});try{await XO(o,n)}catch{await op(n),await Ko(o,{force:!0}).catch(()=>{})}return mn("launchctl",["bootstrap",`gui/${r}`,n]).status===0||mn("launchctl",["load","-w",n]).status===0?{ok:!0,messages:[`Installed launchd agent ${n}.`]}:{ok:!1,messages:[`Wrote ${n} but launchd would not load the agent.`,...Dc()]}}if(t==="linux"){let n=Yo();return await xw(),mn("systemctl",["--user","daemon-reload"]),mn("systemctl",["--user","enable",`${fr}.service`]),mn("systemctl",["--user","restart",`${fr}.service`]).status!==0?{ok:!1,messages:[`Wrote ${n} but \`systemctl --user restart\` failed.`,...Dc()]}:{ok:!0,messages:[`Installed systemd user unit ${n}.`]}}return{ok:!1,messages:Dc()}}catch(n){return{ok:!1,messages:[`Could not install the key-refresh service: ${n instanceof Error?n.message:String(n)}`,...Dc()]}}},cp=async(e=ke,t={})=>{if(await be(e)===null)return!1;let n=t.drain==="idle"?"?drain=idle":"";try{let r=new AbortController,o=setTimeout(()=>r.abort(),1500);try{await fetch(`http://127.0.0.1:${e}/__anyray/shutdown${n}`,{method:"POST",headers:{[sp]:"1"},signal:r.signal})}finally{clearTimeout(o)}}catch{}for(let r=0;r<10&&await be(e,300)!==null;r++)await new Promise(o=>setTimeout(o,100));return!0},en=async(e=ke)=>{let t=Go();await Ko(ys(),{force:!0}).catch(()=>{});let n=[],r=ms();try{if(r)n.push(...Ho("key-refresh service teardown"));else if(t==="darwin"){let o=Vo(),a=String(process.getuid?.()??"");mn("launchctl",["bootout",`gui/${a}`,o]),mn("launchctl",["unload",o]),await Ko(o,{force:!0}),n.push("Removed the launchd key-refresh agent.")}else t==="linux"&&(mn("systemctl",["--user","disable","--now",`${fr}.service`]),await Ko(Yo(),{force:!0}),mn("systemctl",["--user","daemon-reload"]),n.push("Removed the systemd key-refresh unit."))}catch{}try{await cp(e)&&n.push("Stopped the running key-refresh proxy daemon.")}catch{}return{ok:!0,messages:n}};import{stat as UJ}from"node:fs/promises";import{readFileSync as e_,rmSync as t_,writeFileSync as n_,mkdirSync as r_}from"node:fs";import{join as o_}from"node:path";var lp=()=>o_(ee(),"draining"),Rw=e=>{try{r_(ee(),{recursive:!0}),n_(lp(),`${Math.floor(e)}
|
|
39
|
+
`,"utf-8")}catch{}},dp=()=>{try{t_(lp(),{force:!0})}catch{}},a_=16*6e4,up=(e=Date.now())=>{let t;try{t=e_(lp(),"utf-8")}catch{return!1}let n=t.trim();if(!/^\d+$/.test(n))return!1;let r=Number(n);return Number.isSafeInteger(r)&&r>e&&r<=e+a_};import{homedir as mp,platform as yp}from"node:os";import{join as Zo}from"node:path";import{mkdir as pp,readFile as s_,rename as i_,writeFile as Nc,rm as Yr}from"node:fs/promises";import{spawnSync as c_}from"node:child_process";var hp=()=>Zo(ks(),"connect-refresh.log"),Mc=1800,Es="ai.anyray.connect.refresh",Zr="anyray-refresh",Uc="\\AnyrayConnectKeyRefresh",Fc=Es,xs=Zr,Ss=Uc,l_=String(Mc/60),gp=(e,t)=>{let n=c_(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},wp=()=>Zo(mp(),"Library","LaunchAgents",`${Fc}.plist`),bp=()=>Zo(mp(),".config","systemd","user"),Ow=()=>Zo(bp(),`${xs}.service`),$c=()=>Zo(bp(),`${xs}.timer`),fp=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Bc=()=>hn(ir),d_=(e=Bc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${fp(o)}</string>`).join(`
|
|
40
40
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
41
41
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
42
42
|
<plist version="1.0">
|
|
@@ -50,8 +50,8 @@ ${r}
|
|
|
50
50
|
<key>RunAtLoad</key><true/>
|
|
51
51
|
<key>ProcessType</key><string>Background</string>
|
|
52
52
|
<key>LowPriorityIO</key><true/>
|
|
53
|
-
<key>StandardOutPath</key><string>${
|
|
54
|
-
<key>StandardErrorPath</key><string>${
|
|
53
|
+
<key>StandardOutPath</key><string>${fp(hp())}</string>
|
|
54
|
+
<key>StandardErrorPath</key><string>${fp(hp())}</string>
|
|
55
55
|
</dict>
|
|
56
56
|
</plist>
|
|
57
57
|
`},u_=(e=Bc())=>{let{command:t,args:n}=e;return`[Unit]
|
|
@@ -71,53 +71,53 @@ Persistent=true
|
|
|
71
71
|
|
|
72
72
|
[Install]
|
|
73
73
|
WantedBy=timers.target
|
|
74
|
-
`,f_=(e=Bc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),vs=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(" ")}`],Ow=e=>!e.run&&ms(),h_=async(e,t)=>await s_(gp(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Fc]).ok,hr=async(e={})=>{let t=e.os??mp(),n=e.invocation??Bc(),r=e.run??yp,o=e.binaryPath??ur();if(je(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(Ow(e))return{ok:!1,messages:Ho("auto-refresh scheduling")};let a=gt(e.env??(e.run?{}:process.env));if(At(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${pr(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=gp(),i=d_(n);if(await h_(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await up(ks(),{recursive:!0,mode:448}),await up(Zo(hp(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await Yr(l,{force:!0}).catch(()=>{}),await Nc(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await Yr(s,{force:!0}).catch(()=>{});try{await i_(l,s)}catch{await Nc(s,i),await Yr(l,{force:!0}).catch(()=>{})}return r("launchctl",["bootstrap",`gui/${c}`,s]).ok||r("launchctl",["load","-w",s]).ok?{ok:!0,messages:[`Scheduled auto-refresh via launchd (${s}).`]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...vs(n)]}}if(t==="linux")return await up(wp(),{recursive:!0}),await Nc(Rw(),u_(n)),await Nc($c(),p_()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${Is}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${$c()}).`]}:{ok:!1,messages:[`Wrote ${$c()} but \`systemctl --user enable --now\` failed.`,...vs(n)]};if(t==="win32"){let s=f_(n);return r("schtasks",["/Create","/TN",Ss,"/TR",s,"/SC","MINUTE","/MO",l_,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",Ss]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${Ss}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...vs(n)]}}return{ok:!1,messages:vs(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...vs(n)]}}},mr=async(e={})=>{await Yr(fp(),{force:!0}).catch(()=>{});let t=e.os??mp(),n=e.run??yp,r=[];if(Ow(e))return{ok:!0,messages:Ho("scheduler teardown")};try{if(t==="darwin"){let o=gp(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Yr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${Is}.timer`]),await Yr($c(),{force:!0}),await Yr(Rw(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",Ss,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Jo=async(e=mp(),t=yp)=>e==="win32"?t("schtasks",["/Query","/TN",Ss]).ok:e==="darwin"?t("launchctl",["list",Fc]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${Is}.timer`]).ok:!1;import AW from"node:http";import{spawn as TB}from"node:child_process";import{createHash as DB}from"node:crypto";import{homedir as LB}from"node:os";import{join as GS}from"node:path";import{readFile as NB,writeFile as jS,chmod as $B,stat as MB,unlink as LS}from"node:fs/promises";import{homedir as Kc,platform as Hw}from"node:os";import{join as st}from"node:path";import{execFile as v_}from"node:child_process";import{readFile as S_,readdir as E_}from"node:fs/promises";import{homedir as m_,platform as y_}from"node:os";import{join as Wc}from"node:path";var Ye=e=>{let t=m_();switch(y_()){case"darwin":return Wc(t,"Library","Application Support",e);case"win32":return Wc(process.env.APPDATA??Wc(t,"AppData","Roaming"),e);default:return Wc(t,".config",e)}};import{readFile as Tw}from"node:fs/promises";import{homedir as Jr,platform as Xo}from"node:os";import{join as Nn,posix as g_,win32 as w_}from"node:path";var xs=["Code","Code - Insiders","VSCodium"],bp="1.121.0",_w=1,b_=121,Dw="1.102.0",Pw=1,k_=102,C_={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Hc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},kp=e=>{let t=Hc(e);return t?t.major!==_w?t.major>_w:t.minor>=b_:!1},Lw=e=>{let t=Hc(e);return t?t.major!==Pw?t.major>Pw:t.minor>=k_:!1},A_=async e=>{if(Xo()!=="darwin")return;let t=Nn("/Applications",`${C_[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await Tw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Nw=(e,t=Xo(),n=Jr(),r=process.env)=>{switch(t){case"darwin":return Nn(n,"Library","Application Support",e);case"win32":return Nn(r.APPDATA??Nn(n,"AppData","Roaming"),e);default:return Nn(n,".config",e)}},Cp=(e,t)=>e?t==="win32"?w_.join:g_.join:Nn,qo=(e,t=!1,n=Xo(),r=Jr(),o=process.env)=>t?Cp(t,n)(r,Rs[e],"data","User"):Nn(Nw(e,n,r,o),"User"),$w=async(e,t=!1,n=Xo(),r=Jr(),o=process.env)=>{try{let a=Cp(t,n)(qo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Tw(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[]}},Mw=async(e,t=Xo(),n=Jr(),r=process.env)=>{let a=(await $w(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},Uw=async(e,t=!1,n=Xo(),r=Jr(),o=process.env)=>{let a=Cp(t,n),s=qo(e,t,n,r,o),i=await $w(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},zo=async()=>{for(let e of xs)if(await R(Nw(e)))return e},Rs={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Fw=(e,t=Jr())=>Nn(t,Rs[e],"extensions"),Ap=async(e=Jr())=>{for(let t of xs)if(await R(Nn(e,Rs[t])))return t},Bw=async e=>{let t=e??await zo();if(!t)return{status:"unknown"};let n=await A_(t);return n?{variant:t,version:n,status:kp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var I_=3e3,x_="Claude Code-credentials",R_=["copilot-cli","CopilotCLI"],Kw=e=>new Promise(t=>{try{v_("security",["find-generic-password","-s",e],{timeout:I_},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),O_=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=st(Kc(),".claude");return!!(await R(st(e,".oauth_token"))||await R(st(e,".credentials.json"))||Hw()==="darwin"&&await Kw(x_))},__=async()=>{let e=st(process.env.CODEX_HOME?.trim()||st(Kc(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await S_(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},Ww=async e=>{try{return(await E_(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},vp=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of xs){let n=st(Ye(t),"User","globalStorage");if(await R(st(n,"github.copilot-chat"))||await R(st(n,"github.copilot")))return!0}let e=st(Kc(),".config","github-copilot");if(await R(st(e,"apps.json"))||await R(st(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await Ww(st(Kc(),t,"extensions")))return!0;for(let t of xs){if(await Ww(Fw(t)))return!0;let n=st(qo(t,!0),"globalStorage");if(await R(st(n,"github.copilot-chat"))||await R(st(n,"github.copilot")))return!0}if(Hw()==="darwin"){for(let t of R_)if(await Kw(t))return!0}return!1},$t=async()=>{let[e,t,n]=await Promise.all([O_(),__(),vp()]);return{anthropic:e,openai:t,copilot:n}};var Oe=async(e=L,t=$t,n)=>{let r=await e();if(!r.gateway||!r.clientKey)return;let o=await t().catch(()=>{}),a=ge({origin:r.gateway,clientKey:r.clientKey,subscription:r.authMode==="subscription",placeholder:r.authMode==="placeholder",byoUpstream:r.byoUpstream,seat:o,user:r.name,team:r.team});if(!ot(r))return{target:a,toolOrigin:a.origin};if(!(!Number.isInteger(r.fallbackPort)||r.fallbackPort<1||r.fallbackPort>65535))return n&&await n(r.fallbackPort)===null?{target:a,toolOrigin:a.origin}:{target:_n(a,r.fallbackPort),toolOrigin:`http://${mt}:${r.fallbackPort}`}};import{homedir as U_}from"node:os";import{join as qc}from"node:path";import{chmod as F_,readFile as Os,rm as Jw,copyFile as B_}from"node:fs/promises";var Xr="# >>> anyray connect >>>",Vc="# <<< anyray connect <<<",Sp="# restore: ",Gw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Yc=e=>{let t=new RegExp(`\\n*${Gw(Xr)}[\\s\\S]*?${Gw(Vc)}\\n?`,"g");return e.replace(t,"")},Ep=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},Gc=(e,t)=>e.split(t).length-1,jw=e=>Gc(e,"[")-Gc(e,"]"),P_=e=>e.replace(/^['"]|['"]$/g,""),jc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Gc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+jw(Ep(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?P_(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=Ep(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Gc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+jw(l)))}return t},Ip=e=>e.findIndex(t=>t.kind==="table"),xp=e=>e.includes(Xr),Vw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
75
|
-
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},
|
|
76
|
-
`),o=jc(r),a=Ip(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=
|
|
74
|
+
`,f_=(e=Bc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),vs=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(" ")}`],_w=e=>!e.run&&ms(),h_=async(e,t)=>await s_(wp(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Fc]).ok,hr=async(e={})=>{let t=e.os??yp(),n=e.invocation??Bc(),r=e.run??gp,o=e.binaryPath??ur();if(je(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(_w(e))return{ok:!1,messages:Ho("auto-refresh scheduling")};let a=gt(e.env??(e.run?{}:process.env));if(At(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${pr(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=wp(),i=d_(n);if(await h_(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await pp(ks(),{recursive:!0,mode:448}),await pp(Zo(mp(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await Yr(l,{force:!0}).catch(()=>{}),await Nc(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await Yr(s,{force:!0}).catch(()=>{});try{await i_(l,s)}catch{await Nc(s,i),await Yr(l,{force:!0}).catch(()=>{})}return r("launchctl",["bootstrap",`gui/${c}`,s]).ok||r("launchctl",["load","-w",s]).ok?{ok:!0,messages:[`Scheduled auto-refresh via launchd (${s}).`]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...vs(n)]}}if(t==="linux")return await pp(bp(),{recursive:!0}),await Nc(Ow(),u_(n)),await Nc($c(),p_()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${xs}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${$c()}).`]}:{ok:!1,messages:[`Wrote ${$c()} but \`systemctl --user enable --now\` failed.`,...vs(n)]};if(t==="win32"){let s=f_(n);return r("schtasks",["/Create","/TN",Ss,"/TR",s,"/SC","MINUTE","/MO",l_,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",Ss]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${Ss}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...vs(n)]}}return{ok:!1,messages:vs(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...vs(n)]}}},mr=async(e={})=>{await Yr(hp(),{force:!0}).catch(()=>{});let t=e.os??yp(),n=e.run??gp,r=[];if(_w(e))return{ok:!0,messages:Ho("scheduler teardown")};try{if(t==="darwin"){let o=wp(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Yr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${xs}.timer`]),await Yr($c(),{force:!0}),await Yr(Ow(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",Ss,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Jo=async(e=yp(),t=gp)=>e==="win32"?t("schtasks",["/Query","/TN",Ss]).ok:e==="darwin"?t("launchctl",["list",Fc]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${xs}.timer`]).ok:!1;import AW from"node:http";import{spawn as TB}from"node:child_process";import{createHash as DB}from"node:crypto";import{homedir as LB}from"node:os";import{join as GS}from"node:path";import{readFile as NB,writeFile as jS,chmod as $B,stat as MB,unlink as LS}from"node:fs/promises";import{homedir as Kc,platform as Kw}from"node:os";import{join as st}from"node:path";import{execFile as v_}from"node:child_process";import{readFile as S_,readdir as E_}from"node:fs/promises";import{homedir as m_,platform as y_}from"node:os";import{join as Wc}from"node:path";var Ye=e=>{let t=m_();switch(y_()){case"darwin":return Wc(t,"Library","Application Support",e);case"win32":return Wc(process.env.APPDATA??Wc(t,"AppData","Roaming"),e);default:return Wc(t,".config",e)}};import{readFile as Dw}from"node:fs/promises";import{homedir as Jr,platform as Xo}from"node:os";import{join as Nn,posix as g_,win32 as w_}from"node:path";var Is=["Code","Code - Insiders","VSCodium"],kp="1.121.0",Pw=1,b_=121,Lw="1.102.0",Tw=1,k_=102,C_={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Hc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},Cp=e=>{let t=Hc(e);return t?t.major!==Pw?t.major>Pw:t.minor>=b_:!1},Nw=e=>{let t=Hc(e);return t?t.major!==Tw?t.major>Tw:t.minor>=k_:!1},A_=async e=>{if(Xo()!=="darwin")return;let t=Nn("/Applications",`${C_[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await Dw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},$w=(e,t=Xo(),n=Jr(),r=process.env)=>{switch(t){case"darwin":return Nn(n,"Library","Application Support",e);case"win32":return Nn(r.APPDATA??Nn(n,"AppData","Roaming"),e);default:return Nn(n,".config",e)}},Ap=(e,t)=>e?t==="win32"?w_.join:g_.join:Nn,qo=(e,t=!1,n=Xo(),r=Jr(),o=process.env)=>t?Ap(t,n)(r,Rs[e],"data","User"):Nn($w(e,n,r,o),"User"),Mw=async(e,t=!1,n=Xo(),r=Jr(),o=process.env)=>{try{let a=Ap(t,n)(qo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Dw(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[]}},Uw=async(e,t=Xo(),n=Jr(),r=process.env)=>{let a=(await Mw(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},Fw=async(e,t=!1,n=Xo(),r=Jr(),o=process.env)=>{let a=Ap(t,n),s=qo(e,t,n,r,o),i=await Mw(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},zo=async()=>{for(let e of Is)if(await R($w(e)))return e},Rs={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Bw=(e,t=Jr())=>Nn(t,Rs[e],"extensions"),vp=async(e=Jr())=>{for(let t of Is)if(await R(Nn(e,Rs[t])))return t},Ww=async e=>{let t=e??await zo();if(!t)return{status:"unknown"};let n=await A_(t);return n?{variant:t,version:n,status:Cp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var x_=3e3,I_="Claude Code-credentials",R_=["copilot-cli","CopilotCLI"],Gw=e=>new Promise(t=>{try{v_("security",["find-generic-password","-s",e],{timeout:x_},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),O_=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=st(Kc(),".claude");return!!(await R(st(e,".oauth_token"))||await R(st(e,".credentials.json"))||Kw()==="darwin"&&await Gw(I_))},__=async()=>{let e=st(process.env.CODEX_HOME?.trim()||st(Kc(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await S_(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},Hw=async e=>{try{return(await E_(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},Sp=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of Is){let n=st(Ye(t),"User","globalStorage");if(await R(st(n,"github.copilot-chat"))||await R(st(n,"github.copilot")))return!0}let e=st(Kc(),".config","github-copilot");if(await R(st(e,"apps.json"))||await R(st(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await Hw(st(Kc(),t,"extensions")))return!0;for(let t of Is){if(await Hw(Bw(t)))return!0;let n=st(qo(t,!0),"globalStorage");if(await R(st(n,"github.copilot-chat"))||await R(st(n,"github.copilot")))return!0}if(Kw()==="darwin"){for(let t of R_)if(await Gw(t))return!0}return!1},$t=async()=>{let[e,t,n]=await Promise.all([O_(),__(),Sp()]);return{anthropic:e,openai:t,copilot:n}};var Oe=async(e=L,t=$t,n)=>{let r=await e();if(!r.gateway||!r.clientKey)return;let o=await t().catch(()=>{}),a=ge({origin:r.gateway,clientKey:r.clientKey,subscription:r.authMode==="subscription",placeholder:r.authMode==="placeholder",byoUpstream:r.byoUpstream,seat:o,user:r.name,team:r.team});if(!ot(r))return{target:a,toolOrigin:a.origin};if(!(!Number.isInteger(r.fallbackPort)||r.fallbackPort<1||r.fallbackPort>65535))return n&&await n(r.fallbackPort)===null?{target:a,toolOrigin:a.origin}:{target:_n(a,r.fallbackPort),toolOrigin:`http://${mt}:${r.fallbackPort}`}};import{homedir as U_}from"node:os";import{join as qc}from"node:path";import{chmod as F_,readFile as Os,rm as Xw,copyFile as B_}from"node:fs/promises";var Xr="# >>> anyray connect >>>",Vc="# <<< anyray connect <<<",Ep="# restore: ",jw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Yc=e=>{let t=new RegExp(`\\n*${jw(Xr)}[\\s\\S]*?${jw(Vc)}\\n?`,"g");return e.replace(t,"")},xp=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},Gc=(e,t)=>e.split(t).length-1,Vw=e=>Gc(e,"[")-Gc(e,"]"),P_=e=>e.replace(/^['"]|['"]$/g,""),jc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Gc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+Vw(xp(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?P_(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=xp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Gc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+Vw(l)))}return t},Ip=e=>e.findIndex(t=>t.kind==="table"),Rp=e=>e.includes(Xr),Yw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
75
|
+
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},Op=(e,t)=>Yw(Yc(e),t),_p=e=>{let t=e.indexOf(Xr);if(t<0)return;let n=e.indexOf(Vc,t+Xr.length);if(!(n<0))return e.slice(t,n)},Zw=(e,t)=>{let n=e.indexOf(Xr);if(n<0)return!1;let r=e.indexOf(Vc,n+Xr.length);return r<0?!1:Yw(e.slice(n,r),t)},Pp=(e,t)=>{let r=Yc(e).split(`
|
|
76
|
+
`),o=jc(r),a=Ip(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=xp(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}},Zc=(e,t,n)=>{let r=Jw(e),a=Yc(e).split(`
|
|
77
77
|
`),s=jc(a),i=Ip(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 A=s[b];if(b<l&&A.kind==="key"&&c.has(A.key)){u.has(A.key)||u.set(A.key,a[b].trim());continue}d.push(a[b])}let f=jc(d),p=Ip(f),h=(p===-1?d:d.slice(0,p)).join(`
|
|
78
78
|
`),m=p===-1?"":d.slice(p).join(`
|
|
79
|
-
`),w=[...u.entries()].sort(([b],[A])=>b.localeCompare(A)).map(([,b])=>`${
|
|
79
|
+
`),w=[...u.entries()].sort(([b],[A])=>b.localeCompare(A)).map(([,b])=>`${Ep}${b}`),g=[Xr,...w,...t,Vc].join(`
|
|
80
80
|
`);return[h.replace(/\s*$/,""),g,m.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
|
|
81
81
|
|
|
82
82
|
`).replace(/\s*$/,"")+`
|
|
83
|
-
`},
|
|
84
|
-
`)){let o=r.trim();if(!o.startsWith(
|
|
83
|
+
`},Jw=e=>{let t=new Map,n=_p(e);if(n===void 0)return t;for(let r of n.split(`
|
|
84
|
+
`)){let o=r.trim();if(!o.startsWith(Ep))continue;let a=o.slice(Ep.length).trim(),[s]=jc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Jc=e=>{if(!Rp(e))return null;let t=[...Jw(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Yc(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
|
|
85
85
|
`),n].filter(a=>a.length>0).join(`
|
|
86
86
|
|
|
87
87
|
`);return o.length>0?o+`
|
|
88
|
-
`:""};import{randomUUID as T_}from"node:crypto";import{chmod as D_,mkdir as L_,rm as N_,writeFile as $_}from"node:fs/promises";import{dirname as M_}from"node:path";var pe=async(e,t)=>{await L_(M_(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${T_()}`;try{await $_(n,t,{flag:"wx",mode:384}),await he(n,e),await D_(e,384)}finally{await N_(n,{force:!0}).catch(()=>{})}};var W_="codex",H_="Codex app / CLI / IDE",K_="https://chatgpt.com/backend-api/codex",G_="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",j_="x-anyray-client-context-window",V_="x-anyray-client-auto-compact-limit",zc=()=>process.env.CODEX_HOME?.trim()||qc(U_(),".codex"),qr=()=>qc(zc(),"config.toml"),Xc=()=>`${qr()}.anyray-bak`,
|
|
88
|
+
`:""};import{randomUUID as T_}from"node:crypto";import{chmod as D_,mkdir as L_,rm as N_,writeFile as $_}from"node:fs/promises";import{dirname as M_}from"node:path";var pe=async(e,t)=>{await L_(M_(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${T_()}`;try{await $_(n,t,{flag:"wx",mode:384}),await he(n,e),await D_(e,384)}finally{await N_(n,{force:!0}).catch(()=>{})}};var W_="codex",H_="Codex app / CLI / IDE",K_="https://chatgpt.com/backend-api/codex",G_="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",j_="x-anyray-client-context-window",V_="x-anyray-client-auto-compact-limit",zc=()=>process.env.CODEX_HOME?.trim()||qc(U_(),".codex"),qr=()=>qc(zc(),"config.toml"),Xc=()=>`${qr()}.anyray-bak`,Tp=()=>qc(zc(),"hooks.json"),$n=()=>qc(zc(),"anyray.config.toml"),qw=e=>Wo(e,"PostToolUse",jg),zw=(e,t=!1)=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||W_,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||H_}),it=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Dp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,_s=(e,t={})=>{let n=zw(e,t.ignoreEnv),r=X(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:Dp(),i=e.clientKey&&!e.viaLocalProxy,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${it(K_)}`,`"x-anyray-forward-headers" = ${it(G_)}`,...i?[`"x-anyray-api-key" = ${it(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${it(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${it(n)}`),a&&c.push(`"x-anyray-provider" = ${it(a)}`),t.modelContextWindow&&c.push(`"${j_}" = ${it(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${V_}" = ${it(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 = ${it(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${it(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${it(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>it(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${it(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(it).join(", ")}]`]:[]]},Y_=()=>Dp()?["model_provider","model"]:["model_provider"],Qw={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=zc(),t=await R(e);return{installed:t,detail:t?qr():`no ${e} directory`}},async apply(e,t){let n=qr(),r=Tp(),o=zw(e),a=X(e,"openai"),s=Dp(),i=le(),c={},l=await R(r);try{l&&(c=await F(r))}catch(A){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${A instanceof Error?A.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=qw(c),u=await R(n),f=u?await Os(n,"utf-8"):"";if(Op(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=Op(f,"mcp_servers.anyray"),h=Pp(f,"model_context_window"),m=Pp(f,"model_auto_compact_token_limit"),w=[`${n} \u2190 always-on default route (model_provider = anyray)`,`Base URL: ${e.openaiBaseUrl}/responses (wire_api = responses)`,"Plain `codex` now routes through the gateway \u2014 no --profile needed.","Codex app, CLI, and IDE extension share this config.toml route.",a?"Subscription mode: Codex keeps your ChatGPT sign-in; its OAuth token passes through the gateway to the ChatGPT backend (never stored). Requires being signed in with ChatGPT, not an API key.":`Auth: ${e.clientKey?"personal gateway key (written to the config, not shown here)":"placeholder token (gateway swaps in the server-held key)"}`,s?`Model: ${s} (pinned via ANYRAY_CODEX_MODEL)`:"Model: inherits your existing default. If the desktop or IDE model picker ignores custom providers, re-run with ANYRAY_CODEX_MODEL pinned.",m?`Context budget: follows model_auto_compact_token_limit=${m}.`:h?`Context budget: follows model_context_window=${h}.`:"Context budget: follows the request model; unknown models use the safe fallback.",`Attribution: ${o??"(none \u2014 pass --user)"}`,"Codex cloud/web tasks run on OpenAI infrastructure and cannot route through a local gateway."];if(t.dryRun)return w.push(d?`Would remove the retired Anyray Codex PostToolUse hook from ${r}.`:"Codex source-side tool-output trimming remains unavailable: its only replacement signal rejects the already-completed tool promise and is unsafe for side-effecting tools."),{status:"configured",messages:w};let g=[];d?(await J(r,c,{backup:!1}),await se(r),g.push(r),w.push(`Removed the retired Anyray Codex PostToolUse hook from ${r}; Codex does not expose a safe pre-transcript replacement seam for side-effecting tools.`)):w.push("Codex source-side tool-output trimming is not installed because its blocking PostToolUse result can turn a completed side effect into an apparent failure."),u&&!await R(Xc())&&(await B_(n,Xc()),await F_(Xc(),384),w.push(`Backed up your original config to ${Xc()}.`));let y=i&&!p?Ve("profile"):void 0;w.push(p?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:y?"Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.":`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer or a global install to enable retrieval.`);let b=Zc(f,_s(e,{mcpServer:y,modelContextWindow:h,modelAutoCompactTokenLimit:m}),Y_());return await pe(n,b),g.push(n),await R($n())&&(await Xw($n(),{force:!0}),g.push($n()),w.push(`Removed the old opt-in profile ${$n()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:g}},async pointsAt(e){let t=qr();if(!await R(t))return!1;try{let n=await Os(t,"utf-8"),r=`base_url = ${it(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){let e=qr();if(!await R(e))return{registered:!1,command:null};try{let t=await Os(e,"utf-8");if(!Zw(t,"mcp_servers.anyray"))return{registered:!1,command:null};let n=t.match(/\[mcp_servers\.anyray\]\r?\ncommand = ("(?:[^"\\]|\\.)*")/),r=null;if(n)try{r=JSON.parse(n[1])}catch{r=null}return{registered:!0,command:r}}catch{return{registered:!1,command:null}}},async inferenceAuthLanes(){try{let e=await Os(qr(),"utf-8"),t=_p(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=qr(),n=await R(t),r=await R($n()),o=await R(Tp());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=Tp(),c;try{c=await F(i)}catch(l){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${i} (${l instanceof Error?l.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run --revert.`]}}qw(c)&&(e.dryRun||(await J(i,c,{backup:!1}),await se(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=Jc(await Os(t,"utf-8"));i!==null&&(e.dryRun||await pe(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 Xw($n(),{force:!0}),s.push($n()),a.push(e.dryRun?`would remove the old opt-in profile ${$n()}`:`removed the old opt-in profile ${$n()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await se(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as Q_}from"node:os";import{join as eP}from"node:path";import{readFile as rb,rm as Np}from"node:fs/promises";import{readFile as Z_,writeFile as eb,access as J_}from"node:fs/promises";import{homedir as X_}from"node:os";import{join as Lp}from"node:path";var q_="# >>> anyray connect >>>",z_="# <<< anyray connect <<<",Ps=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:q_,end:z_},vt=()=>{let e=X_(),t=process.env.SHELL||"";return t.includes("zsh")?Lp(e,".zshrc"):t.includes("bash")?Lp(e,".bashrc"):Lp(e,".profile")},Qc=async e=>{try{return await J_(e),await Z_(e,"utf-8")}catch{return""}},tb=(e,t)=>{let{begin:n,end:r}=Ps(t),o=e.indexOf(n);if(o===-1)return e;let a=e.indexOf(r,o+n.length);if(a===-1)return e;let s=o;for(;s>0&&e[s-1]===`
|
|
89
89
|
`;)s-=1;let i=a+r.length;return e[i]===`
|
|
90
|
-
`&&(i+=1),e.slice(0,s)+e.slice(i)},el=async(e,t,n)=>{let r=await Qc(e),{begin:o,end:a}=Ps(n),s=
|
|
90
|
+
`&&(i+=1),e.slice(0,s)+e.slice(i)},el=async(e,t,n)=>{let r=await Qc(e),{begin:o,end:a}=Ps(n),s=tb(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
|
|
91
91
|
`),c=s?`${s}
|
|
92
92
|
|
|
93
93
|
${i}
|
|
94
94
|
`:`${i}
|
|
95
|
-
`;return await
|
|
96
|
-
`).filter(c=>c.trim().length>0)},
|
|
97
|
-
`),!0):!1};var Mt=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var ve=e=>`'${e.replace(/'/g,"'\\''")}'`,tP=e=>{let t=ve(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},
|
|
98
|
-
`)):w&&y&&await
|
|
95
|
+
`;return await eb(e,c),e},tl=async(e,t)=>{let n=await Qc(e),{begin:r,end:o}=Ps(t),a=n.indexOf(r);if(a===-1)return;let s=a+r.length,i=n.indexOf(o,s);if(i!==-1)return n.slice(s,i).split(`
|
|
96
|
+
`).filter(c=>c.trim().length>0)},nb=async(e,t)=>(await Qc(e)).includes(Ps(t).begin),Ts=async(e,t)=>{let n=await Qc(e);return n.includes(Ps(t).begin)?(await eb(e,tb(n,t).replace(/\s*$/,"")+`
|
|
97
|
+
`),!0):!1};var Mt=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var ve=e=>`'${e.replace(/'/g,"'\\''")}'`,tP=e=>{let t=ve(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},ob=(e,t,n,r)=>{let a=e.viaLocalProxy===!0?e.placeholderKey:t;return[`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${ve(a)}`],`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${ve(a)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]]},nP=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],rP=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],$p=()=>eP(Q_(),".anyray","shell-env.sh"),sb="# Managed by anyray-connect. Do not source this file anywhere else.",ab=e=>e.split(/\r?\n/,1)[0]===sb,Mp=e=>rP.some(t=>e.startsWith(`export ${t}=`)),ib=(e,t=process.env)=>Up([e],t),Up=(e,t=process.env)=>e.some(r=>t.ANTHROPIC_BASE_URL===r.anthropicBaseUrl||t.OPENAI_BASE_URL===r.openaiBaseUrl)?nP.filter(r=>(t[r]??"")!==""):[],cb={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=vt();return{installed:!0,detail:await R(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await tl(vt());return e?e.some(n=>Mp(n)||n.includes($p()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=vt(),r=X(e,"openai"),o=X(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=ob(e,s,r,o),c=i.filter(Mp),l=i.filter(b=>!Mp(b)),d=$p(),u=Kg(),f=[tP(u),...l,...c.length>0?[`[ -r ${ve(d)} ] && . ${ve(d)}`]:[]],p=e.clientKey?ob(e,Mt(e.clientKey),r,o):i,h=r&&o?"either family":r?"OpenAI":"Anthropic",m=[`${n} \u2190 managed Anyray block`,` ${u} added to PATH (so \`anyray-connect\` runs from a new shell)`,...p.map(b=>` ${b}`),...c.length>0?[`${d} \u2190 owner-only credentials (mode 0600)`]:[],`Run \`source ${n}\` or open a new terminal to apply.`,...a?[`No auth token exported for ${h} \u2014 your seat-based tool keeps`,"its own sign-in (a placeholder here would override it). Raw SDK/script","calls on a seat need your own key."]:["Note: standard SDK env vars carry no per-user header, so attribution","for these falls back to the gateway default."]],w=await R(d),g=w?await rb(d,"utf8"):void 0,y=g===void 0||ab(g);if(c.length>0&&!y)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(y||m.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:m};try{c.length>0?await pe(d,[sb,...c,""].join(`
|
|
98
|
+
`)):w&&y&&await Np(d,{force:!0}),await el(n,f)}catch(b){try{g!==void 0&&y?await pe(d,g):y&&await Np(d,{force:!0})}catch{throw new Error("shell environment update failed and credential rollback could not be completed")}throw b}return{status:"configured",messages:m,changedFiles:[n,...c.length>0||w&&y?[d]:[]]}},async revert(e){let t=vt(),n=$p(),r=await R(n),o=r?ab(await rb(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 Ts(t);o&&await Np(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 UP}from"node:child_process";import{closeSync as FP,copyFileSync as BP,existsSync as Se,mkdirSync as WP,openSync as HP,readFileSync as Bb,readSync as KP,renameSync as GP,rmSync as yn,writeFileSync as Qp}from"node:fs";import{homedir as Wb,platform as jP}from"node:os";import{dirname as Hb,join as na,resolve as VP}from"node:path";import{isIP as Vp}from"node:net";import{execFileSync as ol}from"node:child_process";import{mkdtempSync as oP,rmSync as aP,writeFileSync as sP}from"node:fs";import{createRequire as iP}from"node:module";import{tmpdir as cP}from"node:os";import{join as lb}from"node:path";var Ds=class extends Error{},Ls=e=>e instanceof Ds?`: ${e.message}`:"",db=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new Ds("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new Ds(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},ub=()=>{try{return ol("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Bp=64*1024*1024,lP=Bp*2+64,rl=e=>`'${e.replace(/'/g,"''")}'`,dP=(e,t)=>ol("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:lP,stdio:["ignore","pipe","pipe"]}),uP=(e,t)=>ol("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Bp,stdio:["pipe","pipe","pipe"]}),pb=(e,t,n=dP)=>{let r=rl(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
|
|
99
99
|
`)?a.slice(0,-2):a.endsWith(`
|
|
100
|
-
`)?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")},
|
|
100
|
+
`)?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")},fb=(e,t=uP)=>{let r=t(e,`.bail on
|
|
101
101
|
.timeout 5000
|
|
102
102
|
PRAGMA wal_checkpoint(TRUNCATE);
|
|
103
|
-
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");
|
|
104
|
-
`);ol("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:
|
|
105
|
-
`,{mode:384}),await he(n,t)},RP=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,gr=async(e,t)=>await
|
|
106
|
-
`),XP=e=>{let t=VP(e);for(;;){if(Se(na(t,".git")))return t;let n=
|
|
107
|
-
`,{encoding:"utf-8",flag:"wx",mode:384})},
|
|
108
|
-
`,{encoding:"utf-8",flag:"wx",mode:384});try{GP(n,e)}catch(r){throw yn(n,{force:!0}),r}},lT=(e,t)=>{let n=Qo(e);jb(e,{...n,lastWritten:t})},ae=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Mb=e=>ae(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Qo=e=>{let t=Fb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(ae(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||ae(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(!ae(n)||n.version!==1||!ae(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[qe],o=n.rows[lt];if(!Mb(r)||!Mb(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}},Ub=e=>{let t=Buffer.alloc(16),n=HP(e,"r");try{return KP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{FP(n)}},dT=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return ae(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(".")&&jp(t)===0||t==="0.0.0.0")return!0;if(jp(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(jp(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},Zp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Vb(t.hostname)}catch{return!1}},uT=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},pT=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Je(e.origin)}/v1${Yp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Yp}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),ea=(e,t=!1)=>[...t?[`Cursor's server-side BYOK lane bypasses the local key-refresh proxy and points directly at ${e.openaiBaseUrl}.`]:[],"Route capability: only custom-model requests Cursor actually sends to its OpenAI BYOK endpoint. Cursor's Agent wire behavior varies by release; native Team models, Tab, indexing, and other first-party traffic stay on Cursor-hosted services.","Billing: this lane bills as an Anyray subscription seat \u2014 each distinct attributed developer with usage in a month is one seat. Attribution rides your per-user ark_ key (Cursor sends no metadata header), so enroll each developer with their own key."],Yb=()=>{let e=Qr();if(!Se(e))return"clear";let t=Ns();if(!t)return"unverifiable";let n;try{n=t.readItem(e,qe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ae(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},fT=(e,t)=>{if(!Zp(e))return{routed:!1,problem:"gateway-not-public-https"};let n=Qr();if(!Se(n))return{routed:!1,problem:"state-db-missing"};let r=Ns();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,qe),a=r.readItem(n,lt)}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(!ae(s))return{routed:!1,problem:"settings-malformed"};let i=`${Je(e)}/v1${Yp}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ie(a)||!Ie(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},hT=(e,t=[])=>({command:Dt(e,[...t,hl])}),ef=(e,t,n)=>{if(!ae(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Dt(t,[...n,hl])||r===Dt(t,n)||r.endsWith(` ${hl}`)&&r.includes(` ${t} `)},mT=(e,t)=>ae(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Zb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(ef(a,t,n)){r=!0;continue}if(!ae(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!mT(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}},tf=(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)=>ae(e.hooks)&&tf(e.hooks,t).some(a=>ae(a)&&a.matcher===o&&ef(a,n,r)),yT=(e,t,n,r,o)=>ae(e.hooks)&&tf(e.hooks,t).some(a=>ae(a)&&a.matcher===o&&ef(a,n,r)&&vc(a.command,n,[...r,hl])),Xb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!ae(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=ae(e.hooks)?{...e.hooks}:{},{entries:s}=Zb(tf(a,t),n,r);return s.push({...hT(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},gT=(e,t,n,r=[])=>{if(!ae(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Zb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},wT=async()=>{let e=tn();if(!le()){let t=await zb();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await F(e);for(let n of eo)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}}},fl=()=>{let e=Ve("profile");return{command:e.command,args:[...e.args,Gb]}},Jp=e=>ae(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===fl().command&&e.args.length===fl().args.length&&e.args.every((t,n)=>t===fl().args[n]),bT=e=>{if(!ae(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")||je(e.command))return!1;let t=e.args;if(t.at(-2)!==cr||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!je(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},ml=e=>ae(e)&&Array.isArray(e.args)&&e.args.at(-1)===Gb||bT(e),kT=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,CT=async()=>{if(!le())return qb();let e=nn();try{let t=await F(e);if(t.mcpServers!==void 0&&!ae(t.mcpServers))throw new Error("mcpServers is not an object");let n=ae(t.mcpServers)?{...t.mcpServers}:{},r=n[Ut];return r!==void 0&&!ml(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Ut} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Ut]=fl(),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}}},qb=async()=>{let e=nn();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e);if(!ae(t.mcpServers)||!(Ut in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!ml(t.mcpServers[Ut]))return{changedFiles:[],messages:[`Preserved the foreign ${Ut} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Ut];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}}},zb=async()=>{let e=tn();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e),n=t;for(let r of eo)n=gT(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}}},AT=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=XP(e);if(!n)return t;let r=na(n,Fs),o=JP();try{if(Se(r)){let a=Fb(r,"utf8");if(a===o)return t;if(!a.includes(Kb))return{...t,messages:[`Left ${Fs} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Qp}"`]}}return WP(Wb(r),{recursive:!0}),zp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Fs} 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 ${Fs} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Qb=async()=>{let e=await wT(),t=await CT(),n=await AT();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Xp=async()=>{let e=await zb(),t=await qb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},ek=async()=>{if(!le()){let e=await Xp();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${Re()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await F(tn());for(let r of eo)e=Xb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await F(nn());if(t.mcpServers!==void 0&&!ae(t.mcpServers))throw new Error("mcpServers is not an object");let n=ae(t.mcpServers)?t.mcpServers[Ut]:void 0;return n!==void 0&&!ml(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${nn()} already contains a foreign ${Ut} 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 ${tn()} and ${nn()}, then re-run Connect.`],complete:!1}}},vT=async()=>{if(!le())return!1;try{let e=await F(tn());if(!ae(e.hooks)||!eo.every(r=>Jb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await F(nn()),n=ae(t.mcpServers)?t.mcpServers[Ut]:void 0;return Jp(n)}catch{return!1}},tk=["openAIBaseUrl","useOpenAIKey"],Ws=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!ae(t))throw new Error("Cursor application-user settings are not an object");return t},ST=(e,t,n)=>{let r=Ws(e),o=Ws(t??void 0),a=n===void 0?void 0:Ws(n),s={...r},i=[];for(let c of tk){let l=Object.prototype.hasOwnProperty.call(r,c),d=a!==void 0&&Object.prototype.hasOwnProperty.call(a,c);if(a===void 0||l!==d||l&&!Object.is(r[c],a[c])){i.push(c);continue}Object.prototype.hasOwnProperty.call(o,c)?s[c]=o[c]:delete s[c]}return{mutation:Object.keys(s).length===0?{key:qe}:{key:qe,value:JSON.stringify(s)},conflicts:i}},Vp=(e,t)=>{let n=Ws(e),r=Ws(t??void 0),o={...n};for(let a of tk)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:qe}:{key:qe,value:JSON.stringify(o)}},dl=e=>typeof e=="string"&&e.startsWith("ark_"),ul=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ae(o)&&(n=o)}catch{}let r=dl(t)||n!==null&&(dl(n.useOpenAIKey)||dl(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,dl(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}},ct=(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.",...ea(e)];let n=de(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.",...ea(e)]},qp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!le())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 Ms("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]}},ET=async(e,t)=>{if(!Ie(e.clientKey))return{status:"manual",messages:["Cursor native subscription mode was not changed: a valid personal ark_ gateway key is required for Anyray hooks and MCP retrieval."]};if(!t.dryRun&&!t.preservePendingOp)try{await gr("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 ek();if(!n.complete)return{status:"manual",messages:n.messages};let r=Se(Bs())||Se(ta());if(r&&pl())return qp("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=Yb();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 ${Se(ta())?ta():Bs()}, 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 ${tn()}, and register the Anyray retrieval MCP server in ${nn()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Hs.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 gr("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 -- "${Qp}" (connect already writes ${Fs} 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."]}},Hs={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>pl(),quitTarget:YP,needsTarget:e=>e!=="revert",async complete(e,t,n){return ZP(e)?e!=="revert"&&t?Hs.apply(t,n):Hs.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=Hb(),t=Se(e);return{installed:t,detail:t?Qr():"Cursor user dir not found"}},async watchPaths(){return[tn(),nn()]},async mcpStatus(){let e=nn();if(!await R(e))return{registered:!1,command:null};try{let t=await F(e),n=ae(t.mcpServers)?t.mcpServers[Ut]:void 0;return Jp(n)?{registered:!0,command:kT(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=tn();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!ae(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(eo.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=eo.every(c=>Jb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=eo.every(c=>yT(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=nn();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!ae(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Ut];r=i===void 0?"missing":ml(i)?"owned":"foreign",r==="owned"&&(o=Jp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Hr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await L();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(qP(e))return ET(e,t);let n=pT(e),r=uT(e.openaiBaseUrl),o=Qr(),a=Bs(),s=ta();if(!Ie(e.clientKey))return{status:"manual",messages:ct(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let i={changedFiles:[],messages:[],complete:!0},c=y=>{let b=y.status==="configured"&&!i.complete;return{...y,status:b?"manual":y.status,changedFiles:[...y.changedFiles??[],...i.changedFiles],messages:[...y.messages,...i.messages,...b?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Zp(n.openaiBaseUrl))return c({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach loopback/LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect. No proxy, DNS, certificate, or interception workaround is installed.",...ea(n)]});let l=await ek();if(!l.complete)return{status:"manual",messages:l.messages};let d=Ns();if(!d)return c({status:"manual",messages:ct(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Se(o))return c({status:"manual",messages:ct(n,`No Cursor state DB at ${o} (open Cursor once first).`)});let u=null,f;if(Se(s)){if(Se(a))return c({status:"manual",messages:ct(n,`Both a legacy Cursor Anyray backup (${s}) and a current value backup (${a}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{Ub(s)?u="sqlite":(Qo(s),u="value")}catch{u=null}if(!u)return c({status:"manual",messages:ct(n,`Legacy Cursor Anyray backup at ${s} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(Se(a))try{p=Qo(a)}catch{return c({status:"manual",messages:ct(n,`Existing Cursor backup at ${a} is invalid \u2014 refusing to write or replace recovery data.`)})}if(pl())return c(await qp("apply",t,{status:"manual",messages:ct(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...ea(n,r),...u?[`The legacy Anyray backup at ${s} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...u?[`Would migrate the legacy Anyray backup at ${s}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${o}, ${Se(a)?`retain the original value backup at ${a}`:`create a mode-0600 value backup at ${a}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${tn()}, and register the Anyray retrieval MCP server in ${nn()}.`,...ea(n,r)]};if(u){try{d.checkpointWal(o)}catch(b){return c({status:"manual",messages:ct(n,`Couldn't checkpoint Cursor's state DB at ${o} while migrating the legacy Anyray backup at ${s}${Ls(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=ul(d.readItem(s,qe)??null,d.readItem(s,lt)??null);else{let b=Qo(s);y=ul(b.applicationUser,b.openAIKey)}}catch{return c({status:"manual",messages:ct(n,`Couldn't read the legacy Anyray backup at ${s} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{d.mutateRows(o,[Vp(d.readItem(o,qe),y.applicationUser),y.openAIKey===null?{key:lt}:{key:lt,value:y.openAIKey}])}catch{return c({status:"manual",messages:ct(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${s} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{yn(s,{force:!0}),yn(`${s}-wal`,{force:!0}),yn(`${s}-shm`,{force:!0}),f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held and removed it.`}catch{f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{d.checkpointWal(o)}catch(y){return c({status:"manual",messages:ct(n,`Couldn't checkpoint Cursor's state DB at ${o}${Ls(y)} \u2014 refusing to write; set it by hand:`)})}let h;try{h=d.readItem(o,qe)}catch{return c({status:"manual",messages:ct(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=dT(h,n);if(!m)return c({status:"manual",messages:ct(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let w={applicationUser:m.value,openAIKey:e.clientKey};if(Se(a))try{lT(a,w)}catch{return c({status:"manual",messages:ct(n,`Couldn't update three-way ownership in the protected Cursor backup at ${a} \u2014 refusing to write; set it by hand:`)})}else try{cT(d,a,o,w)}catch{return c({status:"manual",messages:ct(n,`Couldn't create the protected Cursor value backup at ${a} \u2014 refusing to write; set it by hand:`)})}try{d.mutateRows(o,[{key:qe,value:m.value},{key:lt,value:e.clientKey}])}catch{let y=!0;if(p)try{jb(a,p)}catch{y=!1}return c({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${a}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${a} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}i=await Qb();let g=[];if(!t.preservePendingOp)try{await gr("cursor")}catch{g.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return c({status:"configured",changedFiles:[o],messages:[...f?[f]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${a}).`,"Stored the API key in Cursor's credential row (not shown here).",...g,...ea(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await L().catch(()=>{}),n=e;if(!Zp(n)){let o=t&&ot(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&Je(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Se(Bs())||Se(ta())||Yb()!=="clear"?!1:vT():fT(n,r).routed},async revert(e){let t=Qr(),n=Bs(),r=ta(),o=Se(n),a=Se(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 ${tn()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${tn()} and unregister its owned retrieval MCP server.`]};if((o||a)&&pl()){if(e.fullRevert){let h=await Xp(),m=!0;try{await gr("cursor")}catch{m=!1}return{status:"manual",changedFiles:h.changedFiles,messages:[...h.messages,...m?[]:["Could not clear Cursor's stale queue marker."],`Cursor is running, so its saved settings in ${a?r:n} were left in place and nothing was queued. Quit Cursor and re-run --revert to restore them.`]}}return qp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Ns(),i=!1,c=!1,l,d=[];if(a)try{if(Ub(r))if(Se(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let h=ul(s.readItem(r,qe)??null,s.readItem(r,lt)??null);s.mutateRows(t,[Vp(s.readItem(t,qe),h.applicationUser),h.openAIKey===null?{key:lt}:{key:lt,value:h.openAIKey}]),c=!0}else i=!0,BP(r,t),yn(`${t}-wal`,{force:!0}),yn(`${t}-shm`,{force:!0});else{let h=Qo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let m=ul(h.applicationUser,h.openAIKey);s.mutateRows(t,[Vp(s.readItem(t,qe),m.applicationUser),m.openAIKey===null?{key:lt}:{key:lt,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${Ls(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Qo(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(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let h=ST(s.readItem(t,qe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,lt);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:lt}:{key:lt,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${Ls(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{yn(r,{force:!0}),yn(`${r}-wal`,{force:!0}),yn(`${r}-shm`,{force:!0}),yn(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 gr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await Xp();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 gD,mkdir as wD,readFile as Rk,rm as bD,writeFile as kD}from"node:fs/promises";import{randomUUID as CD}from"node:crypto";import{dirname as AD,join as Ok}from"node:path";var IT=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]!==`
|
|
109
|
-
`;)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},
|
|
110
|
-
`;)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},OT=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},_T=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},
|
|
103
|
+
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");db(o?.slice(1).map(Number))},pP=(e,t)=>{let n=oP(lb(cP(),"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=${rl(a.key)};`;let i=lb(n,`value-${s}`);return sP(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${rl(a.key)}, CAST(readfile(${rl(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
|
|
104
|
+
`);ol("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Bp,stdio:["pipe","ignore","pipe"]})}finally{try{aP(n,{recursive:!0,force:!0})}catch{}}},fP={kind:"sqlite3-cli",readItem:(e,t)=>pb(e,t),checkpointWal:e=>fb(e),mutateRows:pP},hP=()=>{try{let t=iP(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Fp=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},mP=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),yP=e=>({kind:"node-sqlite",readItem:(t,n)=>Fp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:mP(o.value)}),checkpointWal:t=>Fp(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);db(o)}),mutateRows:(t,n)=>Fp(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}})}),nl,Ns=()=>{if(nl!==void 0)return nl;let e=hP();return nl=e?yP(e):ub()?fP:null,nl};import{spawn as gP}from"node:child_process";import{randomUUID as hb}from"node:crypto";import{constants as mb}from"node:fs";import{chmod as wP,copyFile as yb,mkdir as bP,readdir as kP,readFile as CP,rename as AP,rm as $s,writeFile as vP}from"node:fs/promises";import{join as Wp}from"node:path";var Hp=/^[a-z0-9][a-z0-9-]{0,31}$/,SP=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,gb=/^[a-z0-9][a-z0-9-]{0,31}$/,EP=/^[0-9TZ:.+-]{1,40}$/,Kp=()=>Wp(ee(),"pending"),sl=e=>{if(!Hp.test(e)||SP.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Wp(Kp(),`${e}.json`)},wb=()=>Wp(ee(),"cursor-pending.json"),xP=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),IP=(e,t)=>{if(!xP(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Hp.test(n)||typeof e.op!="string"||!gb.test(e.op)||typeof e.requestedAt!="string"||!EP.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}:{}}},Gp=async(e,t)=>{try{return IP(JSON.parse(await CP(e,"utf-8")),t)}catch{return}},bb=async()=>{let e=wb(),t=await Gp(e,"cursor");if(!t)return;let n=!1;try{await kb(),await yb(e,sl("cursor"),mb.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await $s(e,{force:!0})}catch{}return t},il=async e=>{let t=await Gp(sl(e),e);return t||(e==="cursor"?bb():void 0)},yr=async()=>{let e;try{e=await kP(Kp())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Hp.test(r))continue;let o=await il(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await bb();n&&t.push(n)}return t},kb=async()=>{await Ct();let e=Kp();await bP(e,{recursive:!0,mode:448});try{await wP(e,448)}catch{}},al=async e=>{await kb();let t=sl(e.adapter),n=`${t}.${process.pid}.tmp`;await vP(n,`${JSON.stringify(e)}
|
|
105
|
+
`,{mode:384}),await he(n,t)},RP=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,gr=async(e,t)=>await jp(e,t)==="claimed",jp=async(e,t)=>{let n=sl(e);if(t){let o=`${n}.${process.pid}.${hb()}.claimed`;try{await AP(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Gp(o,e);if(a&&RP(a,t))return await $s(o,{force:!0}),"claimed";let s=!1;try{await yb(o,n,mb.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await $s(o,{force:!0})}return"superseded"}let r=!1;try{await $s(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await $s(wb(),{force:!0})}catch{}return r?"claimed":"absent"},wr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},OP=e=>{let{command:t,args:n}=hn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},_P=e=>{let{exe:t,args:n}=OP(e),r=gP(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},Cb=_P;var Ab=async()=>{let e=[],t;try{t=await yr()}catch{return e}for(let n of t)if(!wr(n.watcherPid))try{let r=Cb(n.adapter);if(!r)continue;await al({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},Ms=async(e,t)=>{if(!gb.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await il(e),r=new Date().toISOString(),o=hb();if(n&&wr(n.watcherPid))return await al({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await al({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=Cb(e)}catch{a=void 0}return a&&await al({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as PP,spawnSync as Sb}from"node:child_process";import{existsSync as cl}from"node:fs";import{homedir as TP,platform as br}from"node:os";import{join as Eb,win32 as vb}from"node:path";var xb=(e,t={})=>{let n=t.env??process.env,r=t.exists??cl,o=(t.home??TP)(),a={localAppData:n.LOCALAPPDATA??vb.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=vb.join(i,s.path);if(r(c))return c}},zr=/^[A-Za-z0-9 ._-]{1,64}$/,DP=/^[A-Za-z0-9.-]{1,128}$/,ll=e=>e.darwinBundleId&&DP.test(e.darwinBundleId)?e.darwinBundleId:void 0,Ib=(e,t=br())=>t==="darwin"?ll(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",Rb=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",Ob=(e,t=br(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return xb(e,r)!==void 0;let o=e.linuxProcess;return!o||!zr.test(o)?!1:n.split(":").filter(Boolean).some(a=>cl(Eb(a,o)))},_b=(e,t=br())=>{if(t==="darwin"&&ll(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&zr.test(n))},Pb=1e4,Us=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=Eb(t,"System32",e);return cl(n)?n:e},LP=e=>{let t=`/usr/bin/${e}`;return cl(t)?t:e},NP=(e,t)=>{try{let n=Sb(e,t,{encoding:"utf-8",timeout:Pb,windowsHide:!0,...br()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:br()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},$P=e=>new Promise(t=>setTimeout(t,e)),Tb=(e,t={})=>{let n=t.runtimePlatform??br(),r=t.run??NP;if(n==="darwin"){let a=ll(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||!zr.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||!zr.test(a)?!1:r(Us("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!zr.test(o)?!1:r(LP("pkill"),["-TERM","-o","-x",o])},Db=async(e,t=2e4,n={})=>{let r=n.sleep??$P,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},MP=(e,t,n={})=>{let r=br();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=Sb(e,t,{stdio:"ignore",timeout:Pb,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=PP(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},Lb=(e,t={})=>{let n=t.runtimePlatform??br(),r=t.launch??MP;if(n==="darwin"){let a=ll(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!zr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=xb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!zr.test(o)?!1:r(o,[])};var YP={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"}]},ZP=e=>e==="apply"||e==="native"||e==="revert",Kb=()=>Ye("Cursor"),Qr=()=>na(Kb(),"User","globalStorage","state.vscdb"),Bs=()=>`${Qr()}.anyray-bak.json`,ta=()=>`${Qr()}.anyray-bak`,qe="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",lt="cursorAuth/openAIKey";var Zp="/seat/cursor",ef="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.",Fs=na(".cursor","rules","anyray.mdc"),Gb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",JP=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",Gb,"",ef,""].join(`
|
|
106
|
+
`),XP=e=>{let t=VP(e);for(;;){if(Se(na(t,".git")))return t;let n=Hb(t);if(n===t)return null;t=n}},qP=e=>e.authMode!=="placeholder",tn=()=>na(Wb(),".cursor","hooks.json"),nn=()=>na(Wb(),".cursor","mcp.json"),Ut="anyray",jb="--anyray-owner=cursor-v1",zP="postToolUse",QP="beforeSubmitPrompt",Nb="preToolUse",eT="^MCP:",tT="UserPromptSubmit",nT="Shell",rT="^(Read|Grep)$",hl="--anyray-owner=cursor-hook-v1",eo=[{event:zP,flag:Xe,trailingArgs:["cursor"],matcher:eT},{event:QP,flag:sr,trailingArgs:[],matcher:tT},{event:Nb,flag:Vg,trailingArgs:[],matcher:nT},{event:Nb,flag:Yg,trailingArgs:[],matcher:rT}];var $b={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},oT=(e,t,n)=>UP(e,t,n),Mb=oT,aT,sT=()=>{let e=aT??jP();if(e==="win32"){let t=Mb(Us("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],$b);return t.error||t.signal||t.status!==0?!0:/(?:^|\r?\n)"Cursor\.exe",/iu.test(t.stdout??"")}for(let t of e==="linux"?["cursor","Cursor"]:["Cursor"]){let n=Mb("pgrep",["-x",t],$b);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},iT=sT,pl=()=>iT();var cT=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,qe)??null,openAIKey:e.readItem(n,lt)??null,lastWritten:r};Qp(t,`${JSON.stringify(o,null,2)}
|
|
107
|
+
`,{encoding:"utf-8",flag:"wx",mode:384})},Vb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Qp(n,`${JSON.stringify(t,null,2)}
|
|
108
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{GP(n,e)}catch(r){throw yn(n,{force:!0}),r}},lT=(e,t)=>{let n=Qo(e);Vb(e,{...n,lastWritten:t})},ae=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ub=e=>ae(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Qo=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(ae(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||ae(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(!ae(n)||n.version!==1||!ae(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[qe],o=n.rows[lt];if(!Ub(r)||!Ub(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}},Fb=e=>{let t=Buffer.alloc(16),n=HP(e,"r");try{return KP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{FP(n)}},dT=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return ae(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Yb=e=>{let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".lan")||t.endsWith(".internal")||t.endsWith(".home")||!t.includes(".")&&Vp(t)===0||t==="0.0.0.0")return!0;if(Vp(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(Vp(t)===6){let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return Yb(`${r>>>8}.${r&255}.${o>>>8}.${o&255}`)}return t==="::"||t==="::1"||t.startsWith("fc")||t.startsWith("fd")?!0:/^fe[89a-f]/.test(t)}return!1},Jp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Yb(t.hostname)}catch{return!1}},uT=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},pT=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Je(e.origin)}/v1${Zp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Zp}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),ea=(e,t=!1)=>[...t?[`Cursor's server-side BYOK lane bypasses the local key-refresh proxy and points directly at ${e.openaiBaseUrl}.`]:[],"Route capability: only custom-model requests Cursor actually sends to its OpenAI BYOK endpoint. Cursor's Agent wire behavior varies by release; native Team models, Tab, indexing, and other first-party traffic stay on Cursor-hosted services.","Billing: this lane bills as an Anyray subscription seat \u2014 each distinct attributed developer with usage in a month is one seat. Attribution rides your per-user ark_ key (Cursor sends no metadata header), so enroll each developer with their own key."],Zb=()=>{let e=Qr();if(!Se(e))return"clear";let t=Ns();if(!t)return"unverifiable";let n;try{n=t.readItem(e,qe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ae(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},fT=(e,t)=>{if(!Jp(e))return{routed:!1,problem:"gateway-not-public-https"};let n=Qr();if(!Se(n))return{routed:!1,problem:"state-db-missing"};let r=Ns();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,qe),a=r.readItem(n,lt)}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(!ae(s))return{routed:!1,problem:"settings-malformed"};let i=`${Je(e)}/v1${Zp}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!xe(a)||!xe(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},hT=(e,t=[])=>({command:Dt(e,[...t,hl])}),tf=(e,t,n)=>{if(!ae(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Dt(t,[...n,hl])||r===Dt(t,n)||r.endsWith(` ${hl}`)&&r.includes(` ${t} `)},mT=(e,t)=>ae(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(tf(a,t,n)){r=!0;continue}if(!ae(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!mT(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}},nf=(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},Xb=(e,t,n,r,o)=>ae(e.hooks)&&nf(e.hooks,t).some(a=>ae(a)&&a.matcher===o&&tf(a,n,r)),yT=(e,t,n,r,o)=>ae(e.hooks)&&nf(e.hooks,t).some(a=>ae(a)&&a.matcher===o&&tf(a,n,r)&&vc(a.command,n,[...r,hl])),qb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!ae(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=ae(e.hooks)?{...e.hooks}:{},{entries:s}=Jb(nf(a,t),n,r);return s.push({...hT(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},gT=(e,t,n,r=[])=>{if(!ae(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},wT=async()=>{let e=tn();if(!le()){let t=await Qb();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await F(e);for(let n of eo)t=qb(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}}},fl=()=>{let e=Ve("profile");return{command:e.command,args:[...e.args,jb]}},Xp=e=>ae(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===fl().command&&e.args.length===fl().args.length&&e.args.every((t,n)=>t===fl().args[n]),bT=e=>{if(!ae(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")||je(e.command))return!1;let t=e.args;if(t.at(-2)!==cr||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!je(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},ml=e=>ae(e)&&Array.isArray(e.args)&&e.args.at(-1)===jb||bT(e),kT=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,CT=async()=>{if(!le())return zb();let e=nn();try{let t=await F(e);if(t.mcpServers!==void 0&&!ae(t.mcpServers))throw new Error("mcpServers is not an object");let n=ae(t.mcpServers)?{...t.mcpServers}:{},r=n[Ut];return r!==void 0&&!ml(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Ut} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Ut]=fl(),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=nn();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e);if(!ae(t.mcpServers)||!(Ut in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!ml(t.mcpServers[Ut]))return{changedFiles:[],messages:[`Preserved the foreign ${Ut} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Ut];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=tn();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await F(e),n=t;for(let r of eo)n=gT(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}}},AT=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=XP(e);if(!n)return t;let r=na(n,Fs),o=JP();try{if(Se(r)){let a=Bb(r,"utf8");if(a===o)return t;if(!a.includes(Gb))return{...t,messages:[`Left ${Fs} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${ef}"`]}}return WP(Hb(r),{recursive:!0}),Qp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Fs} 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 ${Fs} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},ek=async()=>{let e=await wT(),t=await CT(),n=await AT();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},qp=async()=>{let e=await Qb(),t=await zb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},tk=async()=>{if(!le()){let e=await qp();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${Re()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await F(tn());for(let r of eo)e=qb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await F(nn());if(t.mcpServers!==void 0&&!ae(t.mcpServers))throw new Error("mcpServers is not an object");let n=ae(t.mcpServers)?t.mcpServers[Ut]:void 0;return n!==void 0&&!ml(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${nn()} already contains a foreign ${Ut} 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 ${tn()} and ${nn()}, then re-run Connect.`],complete:!1}}},vT=async()=>{if(!le())return!1;try{let e=await F(tn());if(!ae(e.hooks)||!eo.every(r=>Xb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await F(nn()),n=ae(t.mcpServers)?t.mcpServers[Ut]:void 0;return Xp(n)}catch{return!1}},nk=["openAIBaseUrl","useOpenAIKey"],Ws=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!ae(t))throw new Error("Cursor application-user settings are not an object");return t},ST=(e,t,n)=>{let r=Ws(e),o=Ws(t??void 0),a=n===void 0?void 0:Ws(n),s={...r},i=[];for(let c of nk){let l=Object.prototype.hasOwnProperty.call(r,c),d=a!==void 0&&Object.prototype.hasOwnProperty.call(a,c);if(a===void 0||l!==d||l&&!Object.is(r[c],a[c])){i.push(c);continue}Object.prototype.hasOwnProperty.call(o,c)?s[c]=o[c]:delete s[c]}return{mutation:Object.keys(s).length===0?{key:qe}:{key:qe,value:JSON.stringify(s)},conflicts:i}},Yp=(e,t)=>{let n=Ws(e),r=Ws(t??void 0),o={...n};for(let a of nk)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:qe}:{key:qe,value:JSON.stringify(o)}},dl=e=>typeof e=="string"&&e.startsWith("ark_"),ul=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ae(o)&&(n=o)}catch{}let r=dl(t)||n!==null&&(dl(n.useOpenAIKey)||dl(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,dl(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}},ct=(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.",...ea(e)];let n=de(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.",...ea(e)]},zp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!le())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 Ms("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]}},ET=async(e,t)=>{if(!xe(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 gr("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 tk();if(!n.complete)return{status:"manual",messages:n.messages};let r=Se(Bs())||Se(ta());if(r&&pl())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=Zb();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 ${Se(ta())?ta():Bs()}, 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 ${tn()}, and register the Anyray retrieval MCP server in ${nn()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Hs.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 ek(),s=[];if(!t.preservePendingOp)try{await gr("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 -- "${ef}" (connect already writes ${Fs} 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."]}},Hs={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>pl(),quitTarget:YP,needsTarget:e=>e!=="revert",async complete(e,t,n){return ZP(e)?e!=="revert"&&t?Hs.apply(t,n):Hs.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=Kb(),t=Se(e);return{installed:t,detail:t?Qr():"Cursor user dir not found"}},async watchPaths(){return[tn(),nn()]},async mcpStatus(){let e=nn();if(!await R(e))return{registered:!1,command:null};try{let t=await F(e),n=ae(t.mcpServers)?t.mcpServers[Ut]:void 0;return Xp(n)?{registered:!0,command:kT(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=tn();if(!await R(n))e="missing";else try{let s=await F(n);if(s.hooks===void 0)e="missing";else if(!ae(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(eo.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=eo.every(c=>Xb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=eo.every(c=>yT(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=nn();if(!await R(a))r="missing";else try{let s=await F(a);if(s.mcpServers===void 0)r="missing";else if(!ae(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Ut];r=i===void 0?"missing":ml(i)?"owned":"foreign",r==="owned"&&(o=Xp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Hr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await L();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(qP(e))return ET(e,t);let n=pT(e),r=uT(e.openaiBaseUrl),o=Qr(),a=Bs(),s=ta();if(!xe(e.clientKey))return{status:"manual",messages:ct(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let i={changedFiles:[],messages:[],complete:!0},c=y=>{let b=y.status==="configured"&&!i.complete;return{...y,status:b?"manual":y.status,changedFiles:[...y.changedFiles??[],...i.changedFiles],messages:[...y.messages,...i.messages,...b?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Jp(n.openaiBaseUrl))return c({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach loopback/LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect. No proxy, DNS, certificate, or interception workaround is installed.",...ea(n)]});let l=await tk();if(!l.complete)return{status:"manual",messages:l.messages};let d=Ns();if(!d)return c({status:"manual",messages:ct(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!Se(o))return c({status:"manual",messages:ct(n,`No Cursor state DB at ${o} (open Cursor once first).`)});let u=null,f;if(Se(s)){if(Se(a))return c({status:"manual",messages:ct(n,`Both a legacy Cursor Anyray backup (${s}) and a current value backup (${a}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{Fb(s)?u="sqlite":(Qo(s),u="value")}catch{u=null}if(!u)return c({status:"manual",messages:ct(n,`Legacy Cursor Anyray backup at ${s} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(Se(a))try{p=Qo(a)}catch{return c({status:"manual",messages:ct(n,`Existing Cursor backup at ${a} is invalid \u2014 refusing to write or replace recovery data.`)})}if(pl())return c(await zp("apply",t,{status:"manual",messages:ct(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...ea(n,r),...u?[`The legacy Anyray backup at ${s} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...u?[`Would migrate the legacy Anyray backup at ${s}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${o}, ${Se(a)?`retain the original value backup at ${a}`:`create a mode-0600 value backup at ${a}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${tn()}, and register the Anyray retrieval MCP server in ${nn()}.`,...ea(n,r)]};if(u){try{d.checkpointWal(o)}catch(b){return c({status:"manual",messages:ct(n,`Couldn't checkpoint Cursor's state DB at ${o} while migrating the legacy Anyray backup at ${s}${Ls(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=ul(d.readItem(s,qe)??null,d.readItem(s,lt)??null);else{let b=Qo(s);y=ul(b.applicationUser,b.openAIKey)}}catch{return c({status:"manual",messages:ct(n,`Couldn't read the legacy Anyray backup at ${s} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{d.mutateRows(o,[Yp(d.readItem(o,qe),y.applicationUser),y.openAIKey===null?{key:lt}:{key:lt,value:y.openAIKey}])}catch{return c({status:"manual",messages:ct(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${s} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{yn(s,{force:!0}),yn(`${s}-wal`,{force:!0}),yn(`${s}-shm`,{force:!0}),f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held and removed it.`}catch{f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{d.checkpointWal(o)}catch(y){return c({status:"manual",messages:ct(n,`Couldn't checkpoint Cursor's state DB at ${o}${Ls(y)} \u2014 refusing to write; set it by hand:`)})}let h;try{h=d.readItem(o,qe)}catch{return c({status:"manual",messages:ct(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=dT(h,n);if(!m)return c({status:"manual",messages:ct(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let w={applicationUser:m.value,openAIKey:e.clientKey};if(Se(a))try{lT(a,w)}catch{return c({status:"manual",messages:ct(n,`Couldn't update three-way ownership in the protected Cursor backup at ${a} \u2014 refusing to write; set it by hand:`)})}else try{cT(d,a,o,w)}catch{return c({status:"manual",messages:ct(n,`Couldn't create the protected Cursor value backup at ${a} \u2014 refusing to write; set it by hand:`)})}try{d.mutateRows(o,[{key:qe,value:m.value},{key:lt,value:e.clientKey}])}catch{let y=!0;if(p)try{Vb(a,p)}catch{y=!1}return c({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${a}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${a} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}i=await ek();let g=[];if(!t.preservePendingOp)try{await gr("cursor")}catch{g.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return c({status:"configured",changedFiles:[o],messages:[...f?[f]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${a}).`,"Stored the API key in Cursor's credential row (not shown here).",...g,...ea(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await L().catch(()=>{}),n=e;if(!Jp(n)){let o=t&&ot(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&Je(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Se(Bs())||Se(ta())||Zb()!=="clear"?!1:vT():fT(n,r).routed},async revert(e){let t=Qr(),n=Bs(),r=ta(),o=Se(n),a=Se(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 ${tn()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${tn()} and unregister its owned retrieval MCP server.`]};if((o||a)&&pl()){if(e.fullRevert){let h=await qp(),m=!0;try{await gr("cursor")}catch{m=!1}return{status:"manual",changedFiles:h.changedFiles,messages:[...h.messages,...m?[]:["Could not clear Cursor's stale queue marker."],`Cursor is running, so its saved settings in ${a?r:n} were left in place and nothing was queued. Quit Cursor and re-run --revert to restore them.`]}}return zp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Ns(),i=!1,c=!1,l,d=[];if(a)try{if(Fb(r))if(Se(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let h=ul(s.readItem(r,qe)??null,s.readItem(r,lt)??null);s.mutateRows(t,[Yp(s.readItem(t,qe),h.applicationUser),h.openAIKey===null?{key:lt}:{key:lt,value:h.openAIKey}]),c=!0}else i=!0,BP(r,t),yn(`${t}-wal`,{force:!0}),yn(`${t}-shm`,{force:!0});else{let h=Qo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let m=ul(h.applicationUser,h.openAIKey);s.mutateRows(t,[Yp(s.readItem(t,qe),m.applicationUser),m.openAIKey===null?{key:lt}:{key:lt,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${Ls(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Qo(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(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let h=ST(s.readItem(t,qe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,lt);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:lt}:{key:lt,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${Ls(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{yn(r,{force:!0}),yn(`${r}-wal`,{force:!0}),yn(`${r}-shm`,{force:!0}),yn(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 gr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await qp();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 gD,mkdir as wD,readFile as Rk,rm as bD,writeFile as kD}from"node:fs/promises";import{randomUUID as CD}from"node:crypto";import{dirname as AD,join as Ok}from"node:path";var xT=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]!==`
|
|
109
|
+
`;)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},IT=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},ze=e=>JSON.parse(IT(xT(e)));import{readFile as aD,writeFile as sD}from"node:fs/promises";import{dirname as iD,join as cD}from"node:path";import{mkdir as lD}from"node:fs/promises";var rk=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),RT=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]!==`
|
|
110
|
+
`;)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},OT=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},_T=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},rf=(e,t,n)=>{let r;try{r=ze(e)}catch{return{ok:!1,reason:"unsupported"}}if(!rk(r))return{ok:!1,reason:"unsupported"};if(t in r)return{ok:!1,reason:"key-present"};let o=RT(e);if(o===-1)return{ok:!1,reason:"unsupported"};let a=OT(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=_T(e,o)?`
|
|
111
111
|
${a}${s}
|
|
112
112
|
`:`
|
|
113
|
-
${a}${s},`,d=`${i}${l}${c}`;try{let u=ze(d);if(!nk(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 PT}from"node:child_process";import{readdirSync as TT,statSync as DT}from"node:fs";import{createHash as ik,randomBytes as LT,randomUUID as ck}from"node:crypto";import{chmod as NT,lstat as sf,mkdir as cf,readdir as lk,readFile as wn,rm as dk,unlink as gl,writeFile as lf}from"node:fs/promises";import{homedir as ra,platform as df}from"node:os";import{dirname as rf,join as St,posix as ok,win32 as $T}from"node:path";import{promisify as MT}from"node:util";var gn="0.1.27";var kr="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",yl="b464c3084ddac2d001fca4c71eb8384d55651e77f83928d8aa380548ca735fc5",rk="UEsDBBQAAAgIAAaSDV2VWjUKCAMAALQJAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeoqXlSwt3tYGg2IlQKVAg18cCI3K0mpoiCQ5XlvLrg93Vl5W0jewgt13OzHucDz4yf7teWrHCyORdT3azKynQaW/IlT1ZpXnnd/m2uLzIJ6AfocQxOJojJ/GwC7nOruqg9dI67slFSuFGKdYLXAJnS9LRs5+nTPulMrhC6wNGteJ1p/VR11fd7jb8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8DFAAICAgABZINXRMcpkKbAgAApAUAABYAAAAAAAAAAAAAAKSBKQQAAGV4dGVuc2lvbi9wYWNrYWdlLmpzb25QSwECPwMUAAgICACTjQ1dsoZ6jXkCAAAnBAAAFQAAAAAAAAAAAAAApIEIBwAAZXh0ZW5zaW9uL0xJQ0VOU0UudHh0UEsBAj8DFAAICAgABpINXacyHPQDOQAAI6kAABsAAAAAAAAAAAAAAKSBxAkAAGV4dGVuc2lvbi9kaXN0L2V4dGVuc2lvbi5qc1BLBQYAAAAABQAFAFUBAAAQQwAAAAA=";var q="anyray.anyray-vscode",uf="vscode-handoffs",uk="vscode-receipts",Ks=2,UT=MT(PT),Mn={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"]}},FT={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"}},BT=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),pk=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&BT(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Gs=e=>{if(pk(e))try{return new URL(e.trim()).origin}catch{return}},WT=(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)},HT=e=>{try{return TT(e)}catch{return[]}},KT=e=>{try{return DT(e).mtimeMs}catch{return}},GT=(e,t,n,r,o)=>{if(!Vr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=Mn[e].commands[0],s=St(t,Rs[e]),i=[];for(let{directory:c,suffix:l}of[{directory:St(s,"bin"),suffix:["bin","remote-cli"]},{directory:St(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=St(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)},jT=(e,t,n)=>{let{macAppName:r,commands:o}=Mn[e],a=o[0],s=[];for(let i of["/Applications",ok.join(t,"Applications")])for(let c of n(i))WT(c,r)&&s.push(ok.join(i,c,"Contents/Resources/app/bin",a));return s},VT=(e,t=df(),n=ra(),r=process.env,o=HT,a=KT)=>{let s=GT(e,n,r,o,a);if(t==="darwin")return[...new Set([...Mn[e].commands,...jT(e,n,o),...s])];if(t!=="win32"){let u=Mn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=FT[e],c=$T.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)),Mn[e].commands[0],...s])]},fk={run:async(e,t)=>({stdout:(await UT(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>LT(24).toString("base64url"),home:"",commandCandidates:e=>VT(e)},to=(e,t)=>St(e,".anyray",uk,`${t}.json`),pf=(e,t)=>St(e,".anyray",uk,`${t}.applied.json`),hk=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Hc(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]===gn}catch{return}},mk=async(e,t)=>{let n=await hk(e,t);if(n)return of(n.command,t)},YT=async(e,t,n)=>{let r=St(e,".anyray",uf);for(let o of n){if(!o.endsWith(".json"))continue;let a=St(r,o);try{if(!(await sf(a)).isFile()||JSON.parse(await wn(a,"utf8")).variant!==t)continue;await gl(a)}catch{}}},ZT=async(e,t)=>{let n=St(e,".anyray",uf),r;try{r=await lk(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=St(n,o);try{if(!(await sf(a)).isFile()||JSON.parse(await wn(a,"utf8")).variant!==t)continue;await gl(a)}catch{}}},JT=async(e,t)=>{try{let n=JSON.parse(await wn(to(e,t),"utf8"));return n.extensionVersion===gn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==kr}catch{return!1}},yk=250,XT=9e4,qT=XT/yk,zT=async(e,t,n,r)=>{for(let o=0;o<qT;o++){try{let a=JSON.parse(await wn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Ks&&a.action===n?"confirmed":a.extensionVersion!==gn||a.extensionDistSha256!==kr?"reload-required":a.version===Ks&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(yk)}return"timeout"},QT=200,ak=(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,QT))}return r.join(": ")},eD=async e=>{try{let t=await sf(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},sk=e=>ik("sha256").update(e).digest("hex"),tD=async(e=ra())=>{let t=Buffer.from(rk,"base64");if(t.length<4||t[0]!==80||t[1]!==75||sk(t)!==yl)throw new Error("bundled VS Code extension failed integrity validation");let n=St(e,".anyray","vscode-extension"),r=St(n,`anyray-vscode-${gn}-${yl.slice(0,12)}.vsix`);try{if(sk(await wn(r))===yl)return r}catch{}await cf(n,{recursive:!0,mode:448});let o=`${r}.${ck()}.tmp`;try{await lf(o,t,{mode:384}),await he(o,r),df()!=="win32"&&await NT(r,384)}finally{await dk(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(",")}}`},gk=(e,t,n)=>ik("sha256").update(af({gatewayUrl:Gs(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:gn,extensionDistSha256:kr,profiles:[...n].sort()})).digest("hex"),nD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await wn(pf(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==gk(t,n,r))return!1;let i=JSON.parse(await wn(to(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===gn&&i.extensionDistSha256===kr&&i.gatewayUrl===Gs(t.origin)?await mk(e,a)===!0:!1},rD=async(e,t,n,r)=>{let o=pf(e,t),a=`${o}.${ck()}.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()})}
|
|
114
|
-
`,{mode:384}),await he(a,o)}catch{}finally{await
|
|
115
|
-
`,{mode:384}),await YT(a.home,s.slug,w).catch(()=>{});let g={installed:[],failed:[]},y=!1;try{if(n==="configure"){let A=await JT(a.home,s.slug);if(A||await
|
|
116
|
-
`,{flag:"wx",mode:384}),await he(n,e),await gD(e,384)}finally{await bD(n,{force:!0}).catch(()=>{})}},hf=e=>{if(!Et(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!==Cr||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(!Et(o))return!1;let a=["id","maxInputTokens","maxOutputTokens","name",...o.requestHeaders===void 0?[]:["requestHeaders"],"toolCalling","url","vision"].sort(),s=Object.keys(o).sort();if(s.length!==a.length||!s.every((i,c)=>i===a[c])||typeof o.id!="string"||o.id.length===0||o.id.length>200||o.name!==Tk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!Et(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=>!hf(n));return{next:t,removed:t.length!==e.length}},ED=async(e,t)=>{let n=Ys(e),r=await kl(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 "${Cr}" 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 "${Cr}" Custom Endpoint from ${n}.`]};try{return await Dk(n,o),await se(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${Cr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${Cr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},ID=async e=>{try{let t=ze(await Rk(e,"utf-8"));if(Et(t))return Pk(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Zs}.${Cl} 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 ${Zs}.${Cl} value manually if present.`]}},Lk=async(e,t)=>{let n=vD(e),r;try{r=await F(n)}catch{return ID(n)}let{next:o,removed:a}=Pk(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 se(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.`]}}},xD=async(e,t)=>{let n=await ED(e,t),r=await Lk(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},Nk=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,_k]}},$k=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},Mk=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),RD=e=>Array.isArray(e.args)&&e.args.at(-1)===_k,Uk=(e,t)=>{if(!t.hookBinaryIsDurable()||!Et(e)||!$k(e,["type","command","args"]))return!1;let n=Nk(t);return e.type==="stdio"&&e.command===n.command&&Mk(e.args,n.args)},OD=(e,t)=>{if(!Et(e)||!$k(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&&Mk(e.args,n.args))return!0;if(je(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===cr&&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!je(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},yf=(e,t)=>Uk(e,t)?"exact":Et(e)&&RD(e)||OD(e,t)?"stale-owned":"foreign",Ek=e=>`MCP name conflict in ${e}: servers.${Cn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,_D=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let p of a)try{let h=await F(p);if(i){if("servers"in h&&!Et(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${p} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let y=Et(h.servers)?{...h.servers}:{},b=Nk(o),A=y[Cn],v=A===void 0?void 0:yf(A,o);if(v==="exact"){d+=1;continue}if(v==="foreign"){u=!0,l.push(Ek(p));continue}if(t){d+=1;continue}y[Cn]=b,f.push({path:p,next:{...h,servers:y},backup:v!=="stale-owned",clearBackupAfter:!1});continue}if(!Et(h.servers)||!(Cn in h.servers))continue;if(yf(h.servers[Cn],o)==="foreign"){u=!0,l.push(Ek(p));continue}if(t)continue;let w={...h.servers};delete w[Cn];let g={...h};Object.keys(w).length===0?delete g.servers:g.servers=w,f.push({path:p,next:g,backup:!1,clearBackupAfter:!0})}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let p of f)try{await J(p.path,p.next,p.backup?{}:{backup:!1}),p.clearBackupAfter&&await se(p.path),c.push(p.path),i&&(d+=1)}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p.path} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`);break}return i?l.unshift(t?d===a.length?`Would register the Anyray retrieval MCP server in ${a.length} VS Code user profile config(s).`:`Would register the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); resolve the conflicts below first.`:d===a.length?`Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) in ${a.length} VS Code user profile config(s).`:`Registered the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); see the profile-specific errors below.`):n?l.unshift(t?`Would skip the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary.`:`Skipped the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary; removed any stale owned registration. Re-run via the installer or a global install to enable retrieval.`):l.unshift(`${t?"Would skip":"Skipped"} the Anyray retrieval MCP server because this VS Code build predates profile-scoped mcp.json support (${Dw}+).`),{changedFiles:c,messages:l,manual:u}},PD=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await R(c))try{let l=await F(c);if(!Et(l.servers)||!(Cn in l.servers)||yf(l.servers[Cn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[Cn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await J(c,u,{backup:!1}),await se(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}},Fk=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.`]:[]],Bk=()=>`${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.)`,Ik=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."],Wk=(e,t,n,r)=>({runMcp:o=>_D(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):xD(e,o)}),Hk=(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 ${bp} 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.`}},TD=(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.`}},DD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Wk(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 h=await c(!0),m=await i(!0);return{status:h.manual||m.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...Ik(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).`,...m.messages,...h.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:[Hk(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),f=await i(!1),p=a?void 0:await Ak(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?[js(e)]:[]],messages:[...d.alreadyCurrent?[Bk()]:[],...Ik(t),ff(p??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:Fk(d.profiles),...f.messages,...u.messages]}},xk=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: ${Xs().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."],LD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Wk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...xk(t),...h.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:Xs().map(p=>({id:p,name:Tk(p)}))});if(!d.ok)return{status:"manual",messages:[Hk(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?[Bk()]:[],...xk(t),...d.alreadyCurrent?[]:Fk(d.profiles),...f.messages,...u.messages]}},ND=async(e,t,n)=>{let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null};let o=[];for(let s of r){if(!await R(s))return{registered:!1,command:null};try{let i=await F(s),c=Et(i.servers)?i.servers[Cn]:void 0;if(!Uk(c,n))return{registered:!1,command:null};o.push(c.command)}catch{return{registered:!1,command:null}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var $D=async(e={installedVariant:zo,remoteServerVariant:Ap,isRemoteDevContext:Vr})=>{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}},MD={installedVariant:zo,remoteServerVariant:Ap,detectVscodeLmProviderEligibility:Bw,configureVscodeExtension:wk,vscodeExtensionPointsAt:kk,vscodeExtensionAwaitingReload:bk,vscodeExtensionReceiptMode:wl,hookBinaryIsDurable:le,hookBinaryPath:Re,mcpServerCommand:Ve,vscodeUserMcpConfigPaths:Uw,isRemoteDevContext:Vr},UD=(e={})=>{let t={...MD,...e},n=()=>$D(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Vs,quitTarget:bl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${qo(r,!0)}`:Ys(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ie(r.clientKey))return{status:"manual",messages:["Enrollment required: Copilot setup needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; no VS Code configuration was written."]};let{variant:a,remote:s}=await n();if(!a)return{status:"manual",messages:[t.isRemoteDevContext()?"No VS Code server found here yet \u2014 this looks like a dev container, Codespace, or SSH remote. `--tools copilot` now configures the Anyray provider directly in a remote VS Code window, but only after VS Code has attached to this machine and installed its server. Open this machine with the VS Code Remote-SSH (or Dev Containers) extension, then re-run anyray-connect --tools copilot in that window\u2019s integrated terminal. To route this shell through Anyray without the Copilot UI, use an in-container tool instead: anyray-connect --tools opencode --sso <link> --subscription.":"No VS Code install found. Install VS Code, then re-run anyray-connect; the personal key will be transferred directly into SecretStorage."]};let i=await t.detectVscodeLmProviderEligibility(a);if(i.status==="needs-update")return{status:"manual",messages:[`${a} ${i.version??""} cannot expose public third-party models in Chat's picker. Upgrade to VS Code ${bp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||Lw(i.version);return X(r,"copilot")?DD(a,r,o,t.configureVscodeExtension,c,s,t):LD(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?ND(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Gs(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await kl(Ys(o));if(s.kind==="array"){let c=s.entries.find(hf)?.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 kl(Ys(r));if(o.kind==="array"&&o.entries.some(hf))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 PD(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await Lk(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 y=await t.configureVscodeExtension(o,void 0,"reset");y.ok?(c=!0,d=y.receipt,u.push(`Cleared ${q} gateway configuration and secret.`)):(l=!0,u.push(TD(y.reason,o,a,y.detail)))}let f=Ys(o),p=await kl(f),h=p.kind==="missing"||p.kind==="array"&&!mf(p.entries).removed,m=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),h)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:m.length?m:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:m.length?m:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:m,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(p.kind==="unrecognized")return{status:"manual",changedFiles:m.length?m:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${Cr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=mf(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${Cr} Custom Endpoint from ${f}`]};await Dk(f,w);let g=[...u,`Removed the ${Cr} Custom Endpoint from ${f}.`];return await se(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},Kk=UD();import{accessSync as sL,constants as eC,statSync as iL}from"node:fs";import{readFile as tC,rm as zs}from"node:fs/promises";import{homedir as If,platform as cC}from"node:os";import{delimiter as cL,join as xf,resolve as lL}from"node:path";import{execFile as KD}from"node:child_process";import{readFile as GD}from"node:fs/promises";import{homedir as bf,platform as jD}from"node:os";import{join as qs}from"node:path";import{join as FD}from"node:path";var gf="Iv1.b507a08c87ecfe98",BD="https://github.com/login/device/code",WD="https://github.com/login/oauth/access_token",HD="read:user",Gk=1e4,oa=()=>FD(ee(),"copilot-seat-login.json"),jk={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},wf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vk=async(e={})=>{let t={...jk,...e};try{let n=await t.fetch(BD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:gf,scope:HD}),signal:AbortSignal.timeout(Gk)});if(!n.ok)return;let r=await n.json();if(!wf(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}},Yk=async(e,t={})=>{let n={...jk,...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(WD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:gf,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(Gk)})).json();if(!wf(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"}},Zk=async(e,t)=>{let n=oa();return await pe(n,`${JSON.stringify({token:e,clientId:gf,mintedAtIso:t},null,2)}
|
|
117
|
-
`),n},
|
|
118
|
-
`))}`]:[],`export ${Il}=${ve(n)}`]},
|
|
119
|
-
`).map(SL).join(" + [Environment]::NewLine + "),
|
|
120
|
-
`)):Z&&z&&await zs($,{force:!0}),await el(c,Y,An)}catch(De){try{W!==void 0&&z?await pe($,W):z&&await zs($,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw De}return{status:"configured",messages:re,changedFiles:[c,...
|
|
113
|
+
${a}${s},`,d=`${i}${l}${c}`;try{let u=ze(d);if(!rk(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 PT}from"node:child_process";import{readdirSync as TT,statSync as DT}from"node:fs";import{createHash as ck,randomBytes as LT,randomUUID as lk}from"node:crypto";import{chmod as NT,lstat as cf,mkdir as lf,readdir as dk,readFile as wn,rm as uk,unlink as gl,writeFile as df}from"node:fs/promises";import{homedir as ra,platform as uf}from"node:os";import{dirname as of,join as St,posix as ak,win32 as $T}from"node:path";import{promisify as MT}from"node:util";var gn="0.1.27";var kr="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",yl="b464c3084ddac2d001fca4c71eb8384d55651e77f83928d8aa380548ca735fc5",ok="UEsDBBQAAAgIAAaSDV2VWjUKCAMAALQJAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeoqXlSwt3tYGg2IlQKVAg18cCI3K0mpoiCQ5XlvLrg93Vl5W0jewgt13OzHucDz4yf7teWrHCyORdT3azKynQaW/IlT1ZpXnnd/m2uLzIJ6AfocQxOJojJ/GwC7nOruqg9dI67slFSuFGKdYLXAJnS9LRs5+nTPulMrhC6wNGteJ1p/VR11fd7jb8xrwAoGOQqXQtTnF5cZGPMYGBBPXPRT406BKljRiBKysosSfRdf6aSjE0PQluE2HTWbH2BuUhq6usm13/JsWkmlniBcad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ECPwMUAAgICACTjQ1dsoZ6jXkCAAAnBAAAFQAAAAAAAAAAAAAApIEIBwAAZXh0ZW5zaW9uL0xJQ0VOU0UudHh0UEsBAj8DFAAICAgABpINXacyHPQDOQAAI6kAABsAAAAAAAAAAAAAAKSBxAkAAGV4dGVuc2lvbi9kaXN0L2V4dGVuc2lvbi5qc1BLBQYAAAAABQAFAFUBAAAQQwAAAAA=";var q="anyray.anyray-vscode",pf="vscode-handoffs",pk="vscode-receipts",Ks=2,UT=MT(PT),Mn={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"]}},FT={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"}},BT=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),fk=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&BT(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Gs=e=>{if(fk(e))try{return new URL(e.trim()).origin}catch{return}},WT=(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)},HT=e=>{try{return TT(e)}catch{return[]}},KT=e=>{try{return DT(e).mtimeMs}catch{return}},GT=(e,t,n,r,o)=>{if(!Vr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=Mn[e].commands[0],s=St(t,Rs[e]),i=[];for(let{directory:c,suffix:l}of[{directory:St(s,"bin"),suffix:["bin","remote-cli"]},{directory:St(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=St(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)},jT=(e,t,n)=>{let{macAppName:r,commands:o}=Mn[e],a=o[0],s=[];for(let i of["/Applications",ak.join(t,"Applications")])for(let c of n(i))WT(c,r)&&s.push(ak.join(i,c,"Contents/Resources/app/bin",a));return s},VT=(e,t=uf(),n=ra(),r=process.env,o=HT,a=KT)=>{let s=GT(e,n,r,o,a);if(t==="darwin")return[...new Set([...Mn[e].commands,...jT(e,n,o),...s])];if(t!=="win32"){let u=Mn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=FT[e],c=$T.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)),Mn[e].commands[0],...s])]},hk={run:async(e,t)=>({stdout:(await UT(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>LT(24).toString("base64url"),home:"",commandCandidates:e=>VT(e)},to=(e,t)=>St(e,".anyray",pk,`${t}.json`),ff=(e,t)=>St(e,".anyray",pk,`${t}.applied.json`),mk=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Hc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},af=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]===gn}catch{return}},yk=async(e,t)=>{let n=await mk(e,t);if(n)return af(n.command,t)},YT=async(e,t,n)=>{let r=St(e,".anyray",pf);for(let o of n){if(!o.endsWith(".json"))continue;let a=St(r,o);try{if(!(await cf(a)).isFile()||JSON.parse(await wn(a,"utf8")).variant!==t)continue;await gl(a)}catch{}}},ZT=async(e,t)=>{let n=St(e,".anyray",pf),r;try{r=await dk(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=St(n,o);try{if(!(await cf(a)).isFile()||JSON.parse(await wn(a,"utf8")).variant!==t)continue;await gl(a)}catch{}}},JT=async(e,t)=>{try{let n=JSON.parse(await wn(to(e,t),"utf8"));return n.extensionVersion===gn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==kr}catch{return!1}},gk=250,XT=9e4,qT=XT/gk,zT=async(e,t,n,r)=>{for(let o=0;o<qT;o++){try{let a=JSON.parse(await wn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Ks&&a.action===n?"confirmed":a.extensionVersion!==gn||a.extensionDistSha256!==kr?"reload-required":a.version===Ks&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(gk)}return"timeout"},QT=200,sk=(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,QT))}return r.join(": ")},eD=async e=>{try{let t=await cf(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},ik=e=>ck("sha256").update(e).digest("hex"),tD=async(e=ra())=>{let t=Buffer.from(ok,"base64");if(t.length<4||t[0]!==80||t[1]!==75||ik(t)!==yl)throw new Error("bundled VS Code extension failed integrity validation");let n=St(e,".anyray","vscode-extension"),r=St(n,`anyray-vscode-${gn}-${yl.slice(0,12)}.vsix`);try{if(ik(await wn(r))===yl)return r}catch{}await lf(n,{recursive:!0,mode:448});let o=`${r}.${lk()}.tmp`;try{await df(o,t,{mode:384}),await he(o,r),uf()!=="win32"&&await NT(r,384)}finally{await uk(o,{force:!0})}return r},sf=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=>sf(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${sf(t[n])}`).join(",")}}`},wk=(e,t,n)=>ck("sha256").update(sf({gatewayUrl:Gs(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:gn,extensionDistSha256:kr,profiles:[...n].sort()})).digest("hex"),nD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await wn(ff(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==wk(t,n,r))return!1;let i=JSON.parse(await wn(to(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===gn&&i.extensionDistSha256===kr&&i.gatewayUrl===Gs(t.origin)?await yk(e,a)===!0:!1},rD=async(e,t,n,r)=>{let o=ff(e,t),a=`${o}.${lk()}.tmp`;try{await lf(of(o),{recursive:!0,mode:448}),await df(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
114
|
+
`,{mode:384}),await he(a,o)}catch{}finally{await uk(a,{force:!0})}},oD=async(e,t)=>{await gl(ff(e,t)).catch(()=>{})},bk=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...hk,...r,home:r.home??ra()},s=Mn[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!fk(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,A,v)=>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)&&v.findIndex(E=>E.id===b.id)===A);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await mk(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!Cp(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>Uw(b,uf(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await nD(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:to(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let f=a.extensionPath;if(n==="configure"){try{f??=await tD(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await eD(f))return{ok:!1,reason:"extension-missing"}}let p=a.nonce(),h=St(a.home,".anyray",pf,`${p}.json`),m=to(a.home,s.slug);await lf(of(h),{recursive:!0,mode:448});let w=await dk(of(h)).catch(()=>[]);await df(h,`${JSON.stringify({version:Ks,action:n,nonce:p,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:gn,expectedExtensionDistSha256:kr})}
|
|
115
|
+
`,{mode:384}),await YT(a.home,s.slug,w).catch(()=>{});let g={installed:[],failed:[]},y=!1;try{if(n==="configure"){let A=await JT(a.home,s.slug);if(A||await af(l,a)!==!0)try{await a.run(l,["--install-extension",f,"--force"])}catch(v){return y=!0,{ok:!1,reason:"install-failed",detail:sk(v,p)}}for(let v of u)try{(A||await af(l,a,v)!==!0)&&await a.run(l,["--profile",v,"--install-extension",f,"--force"]),g.installed.push(v)}catch{g.failed.push(v)}}try{await a.run(l,["--open-url",`${s.scheme}://${q}/configure?nonce=${encodeURIComponent(p)}`])}catch(A){return{ok:!1,reason:"handoff-undeliverable",detail:sk(A,p)}}let b=await zT(m,p,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(y=!0,n==="configure")g.failed.length===0&&await rD(a.home,s.slug,wk(t,o,u),p);else{await oD(a.home,s.slug),await ZT(a.home,s.slug).catch(()=>{});for(let A of[void 0,...u])try{await a.run(l,[...A?["--profile",A]:[],"--uninstall-extension",q])}catch{}}return{ok:!0,receipt:m,profiles:g}}catch{return{ok:!1,reason:"failed"}}finally{y&&await gl(h).catch(()=>{})}},wl=async(e,t=ra())=>{try{let n=JSON.parse(await wn(to(t,Mn[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==gn||n.extensionDistSha256!==kr)}catch{return!1}},bl=async(e,t=ra())=>{try{let n=JSON.parse(await wn(to(t,Mn[e].slug),"utf8"));return n.version!==Ks||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},kk=async(e,t,n=ra(),r={})=>{try{let o=Gs(t);if(!o)return!1;let a=JSON.parse(await wn(to(n,Mn[e].slug),"utf8"));if(!(a.version===Ks&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===gn&&a.extensionDistSha256===kr))return!1;let i={...hk,...r,home:n};return await yk(e,i)===!0}catch{return!1}};var bn="extensions.supportAgentsWindow",kn="chat.agentHost.byokModels.enabled",js=e=>cD(Ye(e),"User","settings.json"),Ck=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dD=e=>Ck(e)&&e[q]===!0,Ak=async(e,t={})=>{let n=js(e),r=t.read??(p=>aD(p,"utf-8")),o=t.exists??R,a=t.write??(async(p,h)=>{await lD(iD(p),{recursive:!0}),await sD(p,h,"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=ze(s)}catch{return{status:"manual",reason:`${n} is not valid JSON/JSONC, so it was left untouched`}}if(!Ck(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(bn in i)){let p=rf(c,bn,{[q]:!0});if(!p.ok)return{status:"manual",reason:`could not add ${bn} to ${n} without rewriting it`};c=p.text,l=!0}if(!(kn in i)){let p=rf(c,kn,!0);if(!p.ok)return{status:"manual",reason:`could not add ${kn} to ${n} without rewriting it`};c=p.text,l=!0}l&&await a(n,c);let d=l?ze(c):i,u=dD(d[bn]),f=d[kn]===!0;return!u||!f?{status:"manual",reason:`${n} already sets ${u?kn:bn} to something else; left as it is`}:{status:"enabled",changed:l}},hf=(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 "${bn}": {"${q}": true} and "${kn}": 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 uD}from"node:child_process";import{platform as pD}from"node:os";var vk={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},fD=(e,t,n)=>uD(e,t,n),Sk=fD,hD,mD=()=>{let e=hD??pD();if(e==="win32"){let n=Sk(Us("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],vk);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=Sk("pgrep",[n,r],vk);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},yD=mD,Vs=()=>yD();var kl={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 Cr="Anyray",Cn="anyray",_k="--anyray-owner=vscode-profile-v1",Ys=e=>Ok(Ye(e),"User","chatLanguageModels.json"),vD=e=>Ok(Ye(e),"User","settings.json"),Zs="github.copilot.advanced",Al="debug.overrideCapiUrl",Et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),SD=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}},Pk=e=>{let t=e[Zs];if(!Et(t)||!SD(t[Al]))return{next:e,removed:!1};let n={...t};delete n[Al];let r={...e};return Object.keys(n).length>0?r[Zs]=n:delete r[Zs],{next:r,removed:!0}},Js="anyray-default",Xs=()=>{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:[Js]},Tk=e=>e===Js?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),Cl=async e=>{if(!await R(e))return{kind:"missing"};try{let t=await Rk(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"}}},Dk=async(e,t)=>{await wD(AD(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${CD()}`;try{await kD(n,`${JSON.stringify(t,null,2)}
|
|
116
|
+
`,{flag:"wx",mode:384}),await he(n,e),await gD(e,384)}finally{await bD(n,{force:!0}).catch(()=>{})}},mf=e=>{if(!Et(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!==Cr||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(!Et(o))return!1;let a=["id","maxInputTokens","maxOutputTokens","name",...o.requestHeaders===void 0?[]:["requestHeaders"],"toolCalling","url","vision"].sort(),s=Object.keys(o).sort();if(s.length!==a.length||!s.every((i,c)=>i===a[c])||typeof o.id!="string"||o.id.length===0||o.id.length>200||o.name!==Tk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!Et(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}})},yf=e=>{let t=e.filter(n=>!mf(n));return{next:t,removed:t.length!==e.length}},ED=async(e,t)=>{let n=Ys(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 "${Cr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=yf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${Cr}" Custom Endpoint from ${n}.`]};try{return await Dk(n,o),await se(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${Cr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${Cr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},xD=async e=>{try{let t=ze(await Rk(e,"utf-8"));if(Et(t))return Pk(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Zs}.${Al} in ${e}, which uses JSONC that Connect will not rewrite; remove it manually.`]}:{changedFiles:[],messages:[],manual:!1}}catch{}return{changedFiles:[],manual:!0,messages:[`Could not parse ${e}; remove an old Anyray ${Zs}.${Al} value manually if present.`]}},Lk=async(e,t)=>{let n=vD(e),r;try{r=await F(n)}catch{return xD(n)}let{next:o,removed:a}=Pk(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 se(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.`]}}},ID=async(e,t)=>{let n=await ED(e,t),r=await Lk(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},Nk=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,_k]}},$k=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},Mk=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),RD=e=>Array.isArray(e.args)&&e.args.at(-1)===_k,Uk=(e,t)=>{if(!t.hookBinaryIsDurable()||!Et(e)||!$k(e,["type","command","args"]))return!1;let n=Nk(t);return e.type==="stdio"&&e.command===n.command&&Mk(e.args,n.args)},OD=(e,t)=>{if(!Et(e)||!$k(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&&Mk(e.args,n.args))return!0;if(je(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===cr&&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!je(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},gf=(e,t)=>Uk(e,t)?"exact":Et(e)&&RD(e)||OD(e,t)?"stale-owned":"foreign",Ek=e=>`MCP name conflict in ${e}: servers.${Cn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,_D=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let p of a)try{let h=await F(p);if(i){if("servers"in h&&!Et(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${p} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let y=Et(h.servers)?{...h.servers}:{},b=Nk(o),A=y[Cn],v=A===void 0?void 0:gf(A,o);if(v==="exact"){d+=1;continue}if(v==="foreign"){u=!0,l.push(Ek(p));continue}if(t){d+=1;continue}y[Cn]=b,f.push({path:p,next:{...h,servers:y},backup:v!=="stale-owned",clearBackupAfter:!1});continue}if(!Et(h.servers)||!(Cn in h.servers))continue;if(gf(h.servers[Cn],o)==="foreign"){u=!0,l.push(Ek(p));continue}if(t)continue;let w={...h.servers};delete w[Cn];let g={...h};Object.keys(w).length===0?delete g.servers:g.servers=w,f.push({path:p,next:g,backup:!1,clearBackupAfter:!0})}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let p of f)try{await J(p.path,p.next,p.backup?{}:{backup:!1}),p.clearBackupAfter&&await se(p.path),c.push(p.path),i&&(d+=1)}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p.path} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`);break}return i?l.unshift(t?d===a.length?`Would register the Anyray retrieval MCP server in ${a.length} VS Code user profile config(s).`:`Would register the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); resolve the conflicts below first.`:d===a.length?`Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) in ${a.length} VS Code user profile config(s).`:`Registered the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); see the profile-specific errors below.`):n?l.unshift(t?`Would skip the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary.`:`Skipped the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary; removed any stale owned registration. Re-run via the installer or a global install to enable retrieval.`):l.unshift(`${t?"Would skip":"Skipped"} the Anyray retrieval MCP server because this VS Code build predates profile-scoped mcp.json support (${Lw}+).`),{changedFiles:c,messages:l,manual:u}},PD=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await R(c))try{let l=await F(c);if(!Et(l.servers)||!(Cn in l.servers)||gf(l.servers[Cn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[Cn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await J(c,u,{backup:!1}),await se(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}},Fk=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.`]:[]],Bk=()=>`${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.)`,xk=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."],Wk=(e,t,n,r)=>({runMcp:o=>_D(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):ID(e,o)}),Hk=(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 ${kp} 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.`}},TD=(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.`}},DD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Wk(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 h=await c(!0),m=await i(!0);return{status:h.manual||m.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...xk(t),a?hf({status:"enabled",changed:!0},!0):`Would enable the VS Code Agents window in ${e}'s settings.json (two keys, each added only if absent).`,...m.messages,...h.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:[Hk(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),f=await i(!1),p=a?void 0:await Ak(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?[js(e)]:[]],messages:[...d.alreadyCurrent?[Bk()]:[],...xk(t),hf(p??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:Fk(d.profiles),...f.messages,...u.messages]}},Ik=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: ${Xs().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."],LD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Wk(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...Ik(t),...h.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:Xs().map(p=>({id:p,name:Tk(p)}))});if(!d.ok)return{status:"manual",messages:[Hk(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?[Bk()]:[],...Ik(t),...d.alreadyCurrent?[]:Fk(d.profiles),...f.messages,...u.messages]}},ND=async(e,t,n)=>{let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null};let o=[];for(let s of r){if(!await R(s))return{registered:!1,command:null};try{let i=await F(s),c=Et(i.servers)?i.servers[Cn]:void 0;if(!Uk(c,n))return{registered:!1,command:null};o.push(c.command)}catch{return{registered:!1,command:null}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var $D=async(e={installedVariant:zo,remoteServerVariant:vp,isRemoteDevContext:Vr})=>{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}},MD={installedVariant:zo,remoteServerVariant:vp,detectVscodeLmProviderEligibility:Ww,configureVscodeExtension:bk,vscodeExtensionPointsAt:kk,vscodeExtensionAwaitingReload:wl,vscodeExtensionReceiptMode:bl,hookBinaryIsDurable:le,hookBinaryPath:Re,mcpServerCommand:Ve,vscodeUserMcpConfigPaths:Fw,isRemoteDevContext:Vr},UD=(e={})=>{let t={...MD,...e},n=()=>$D(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Vs,quitTarget:kl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${qo(r,!0)}`:Ys(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!xe(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 ${kp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||Nw(i.version);return X(r,"copilot")?DD(a,r,o,t.configureVscodeExtension,c,s,t):LD(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?ND(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Gs(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await Cl(Ys(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(Ys(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 PD(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await Lk(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 y=await t.configureVscodeExtension(o,void 0,"reset");y.ok?(c=!0,d=y.receipt,u.push(`Cleared ${q} gateway configuration and secret.`)):(l=!0,u.push(TD(y.reason,o,a,y.detail)))}let f=Ys(o),p=await Cl(f),h=p.kind==="missing"||p.kind==="array"&&!yf(p.entries).removed,m=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),h)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:m.length?m:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:m.length?m:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:m,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(p.kind==="unrecognized")return{status:"manual",changedFiles:m.length?m:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${Cr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=yf(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${Cr} Custom Endpoint from ${f}`]};await Dk(f,w);let g=[...u,`Removed the ${Cr} Custom Endpoint from ${f}.`];return await se(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},Kk=UD();import{accessSync as sL,constants as eC,statSync as iL}from"node:fs";import{readFile as tC,rm as zs}from"node:fs/promises";import{homedir as If,platform as cC}from"node:os";import{delimiter as cL,join as Rf,resolve as lL}from"node:path";import{execFile as KD}from"node:child_process";import{readFile as GD}from"node:fs/promises";import{homedir as kf,platform as jD}from"node:os";import{join as qs}from"node:path";import{join as FD}from"node:path";var wf="Iv1.b507a08c87ecfe98",BD="https://github.com/login/device/code",WD="https://github.com/login/oauth/access_token",HD="read:user",Gk=1e4,oa=()=>FD(ee(),"copilot-seat-login.json"),jk={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},bf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vk=async(e={})=>{let t={...jk,...e};try{let n=await t.fetch(BD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:wf,scope:HD}),signal:AbortSignal.timeout(Gk)});if(!n.ok)return;let r=await n.json();if(!bf(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}},Yk=async(e,t={})=>{let n={...jk,...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(WD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:wf,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(Gk)})).json();if(!bf(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"}},Zk=async(e,t)=>{let n=oa();return await pe(n,`${JSON.stringify({token:e,clientId:wf,mintedAtIso:t},null,2)}
|
|
117
|
+
`),n},vl=async()=>{try{let e=await F(oa());if(!bf(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var VD=5e3,Cf=5e3,YD=["copilot-cli","CopilotCLI"],ZD="https://api.github.com/copilot_internal/user",Xk="~/.copilot/config.json",qk="macOS Keychain (Copilot CLI)",zk=e=>e===Xk||e===qk,aa=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),rn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),JD=()=>process.env.XDG_CONFIG_HOME?.trim()||qs(kf(),".config"),XD=()=>process.env.XDG_DATA_HOME?.trim()||qs(kf(),".local","share"),qD=async()=>{try{let e=await GD(qs(kf(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return aa(t)?t:void 0}catch{}},zD=async e=>{try{let t=await F(qs(JD(),"github-copilot",e));if(!rn(t))return;for(let n of Object.values(t))if(rn(n)&&aa(n.oauth_token))return n.oauth_token}catch{}},QD=async()=>{try{let e=await F(qs(XD(),"opencode","auth.json")),t=rn(e)?e["github-copilot"]:void 0;if(!rn(t)||t.type!=="oauth")return;if(aa(t.access))return t.access;if(aa(t.refresh))return t.refresh}catch{}},eL=(e,t)=>new Promise((n,r)=>{try{KD(e,[...t],{timeout:VD},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),tL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return aa(r)?r:void 0}catch{return}},nL=async(e=eL)=>{for(let t of YD){let n=await tL(t,e);if(n)return n}};var Sl={env:process.env,platform:jD,tokenFromDeviceLogin:vl,tokenFromCopilotCliConfig:qD,tokenFromSharedConfig:zD,tokenFromOpenCode:QD,tokenFromKeychain:nL,fetch:(...e)=>fetch(...e)},rL=new Set([401,403,404]),Qk=/^[a-z][a-z0-9-]{0,30}$/,oL=e=>e!=="default"&&Qk.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",aL=e=>typeof e!="string"?"default":/^https:\/\/api\.([a-z][a-z0-9-]{0,30})\.githubcopilot\.com\/?$/.exec(e.trim())?.[1]??"default",Af=async(e,t={})=>{let n={...Sl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),Cf);try{let a=await n.fetch(ZD,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=rn(i)&&rn(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:aL(s)}}return{verdict:rL.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var sa=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${Qk.test(n)?n:"default"}/header/models`,a=await Jk(o,e,r.clientKey,t);if(a.length>0)return a}return Jk(`${oL(n)}/models`,e,void 0,t)},Jk=async(e,t,n,r={})=>{let o={...Sl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),Cf);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=rn(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!rn(u))continue;let f=u.id;if(typeof f!="string"||f.length===0||u.model_picker_enabled!==!0)continue;let p=u.policy;if(rn(p)&&p.state!=="enabled")continue;let h=u.supported_endpoints,m=Array.isArray(h)?h.filter(E=>typeof E=="string"):[],w=u.capabilities,g=rn(w)?w.limits:void 0,y=E=>{let x=rn(g)?g[E]:void 0;return typeof x=="number"&&Number.isFinite(x)&&x>0?Math.floor(x):void 0},b={id:f,endpoints:m},A=y("max_prompt_tokens"),v=y("max_output_tokens");A!==void 0&&(b.maxPromptTokens=A),v!==void 0&&(b.maxOutputTokens=v),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},El=async(e,t,n,r={})=>{let o={...Sl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),Cf);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)}},xl=async(e={},t={})=>{let n={...Sl,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return aa(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:qk,read:()=>n.tokenFromKeychain()}]:[],{source:Xk,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}};var oo="copilot-cli",An="copilot-cli",dL=Vs,uL=()=>dL()?["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."]:[],lC=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],Of=()=>Object.fromEntries(lC.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),vf=()=>Rf(If(),".anyray","copilot-cli.sh"),dC="# Managed by anyray-connect. Do not source this file anywhere else.",nC=e=>e.split(/\r?\n/,1)[0]===dC,pL=["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"],Il="COPILOT_PROVIDER_API_KEY",rC=e=>e.startsWith(`export ${Il}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Fn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",fL=()=>Xs()[0],Qs=(e="default")=>`/copilot/${e}/header`,c6=Qs(),no=e=>e.replace(/\/+$/,""),hL=(e,t="default")=>`${no(e.openaiBaseUrl)}${Qs(t)}`,Sf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),xf="claude-sonnet-5",mL=()=>{let e=Xs()[0];return e===Js?xf:e},uC=e=>e.endpoints.includes(Fn(e.id)==="responses"?"/responses":"/chat/completions"),_f=e=>{let t=e.filter(uC),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)=>oC(a.version,s.version)?-1:oC(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var oC=(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=de({...e.metadata,tool:oo}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...lC];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(hL(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Fn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...o?.maxPromptTokens?[`export COPILOT_PROVIDER_MAX_PROMPT_TOKENS='${o.maxPromptTokens}'`]:[],...o?.maxOutputTokens?[`export COPILOT_PROVIDER_MAX_OUTPUT_TOKENS='${o.maxOutputTokens}'`]:[],...i.length>0?[`export COPILOT_PROVIDER_HEADERS=${ve(i.join(`
|
|
118
|
+
`))}`]:[],`export ${Il}=${ve(n)}`]},Ef=(e,t,n)=>{let r=de({...e.metadata,tool:oo});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Fn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${ve(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${Il}=${ve(n)}`]:[]]},yL=(e,t)=>t||!X(e,"copilot"),sC=()=>{let e=pL.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).`]},iC=(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 ${oo}\`), 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`."],gL=(e=process.env.PATH,t=cC())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(cL)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=lL(o,n);try{if(!iL(a).isFile())continue;return sL(a,t==="win32"?eC.F_OK:eC.X_OK),a}catch{}}},wL=()=>Rf(If(),".copilot","config.json"),Un=()=>Rf(If(),".copilot","mcp-config.json"),ro="anyray",bL=()=>({type:"local",...Ve("profile"),tools:["*"]}),Ar=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kL=async()=>{let e=Un(),t;try{t=await F(e)}catch{return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because ${e} could not be parsed; it was left unchanged.`}}if("mcpServers"in t&&!Ar(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=(Ar(t.mcpServers)?t.mcpServers:{})[ro];return r!==void 0&&!zt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${ro} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},CL=async e=>{let t=Un(),n=e.json,r=Ar(n.mcpServers)?n.mcpServers:{};r[ro]=bL(),n.mcpServers=r,await J(t,n)},AL=async()=>{let e=Un(),t;try{let r=await F(e);if(!Ar(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!Ar(n)||!(ro in n)||!zt(n[ro],"profile")?!1:(delete n[ro],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await zs(e,{force:!0}):await J(e,t,{backup:!1}),await se(e),!0)},vL={resolveCopilotCommand:gL,platform:cC,detectCopilotSeat:Sp,discoverSeatToken:xl,readDeviceLoginToken:vl,fetchSeatModelCatalog:sa,probeSeatChatModel:El},SL=e=>`'${e.replace(/'/g,"''")}'`,EL=e=>e.split(`
|
|
119
|
+
`).map(SL).join(" + [Environment]::NewLine + "),xL=(e={})=>{let t={...vL,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await tl(vt(),An))?.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&&no(s)===`${no(i)}/v1`,a=(s,i)=>s!==void 0&&Sf(s)&&no(s).startsWith(`${no(i)}/v1/copilot/`);return{id:oo,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Vs,quitTarget:kl},async usesDynamicCredential(s){let i=await r();return a(i,s)||!o(i,s)?!1:!await R(vf())},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=wL();return await R(i)?{installed:!0,detail:i}:{installed:!1,detail:"no `copilot` on PATH and no ~/.copilot state"}},async apply(s,i){let c=vt(),l=async(E,x,C)=>{let I=E.filter(rC),P=E.filter(De=>!rC(De)),$=vf(),Y=[...P,...I.length>0?[`[ -r ${ve($)} ] && . ${ve($)}`]:[]],Z=await R($),W=Z?await tC($,"utf8"):void 0,z=W===void 0||nC(W);if(I.length>0&&!z)return{status:"manual",messages:[`Refused to overwrite user-managed ${$}; move or rename that file, then run Connect again.`]};let me=le(),Te=me?await kL():void 0,re=[`${c} \u2190 managed Anyray block (${An})`,...x.map(De=>` ${De}`),...I.length>0?[`${$} \u2190 owner-only credential (mode 0600)`]:["No key exported \u2014 the local refresh daemon injects a freshly minted","key per request, so a running CLI session never carries a stale one."],...C,Te?.status==="skipped"?Te.message:me?`${Un()} \u2190 Anyray retrieval MCP server (anyray_retrieve / anyray_recall)`:`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Re()}). 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.`,...uL()];if(i.dryRun)return{status:"configured",messages:re};let Ke=!1;Te?.status==="installable"&&(await CL(Te),Ke=!0);try{I.length>0?await pe($,[dC,...I,""].join(`
|
|
120
|
+
`)):Z&&z&&await zs($,{force:!0}),await el(c,Y,An)}catch(De){try{W!==void 0&&z?await pe($,W):z&&await zs($,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw De}return{status:"configured",messages:re,changedFiles:[c,...I.length>0||Z&&z?[$]:[],...Ke?[Un()]:[]]}},d=await r(),u=d!==void 0&&!Sf(d),f=s.authMode==="placeholder",p=u&&!s.viaLocalProxy,h=u&&(!p||!X(s,"copilot")),m=f?void 0:await t.readDeviceLoginToken().catch(()=>{}),w=f||h&&!m?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),g=w.token,y=w.rejected;if(g){let E=w.capiSegment??"default",x=mL(),C=x!==xf||!!process.env.ANYRAY_COPILOT_MODEL,I=await t.fetchSeatModelCatalog(g.token,{},E,{laneOrigin:no(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),P=I.find(re=>re.id===x);if(!C){let re=_f(I);if(P=re[0],!i.dryRun&&re.length>0){let Ke=H=>`${no(s.origin)}/v1${Qs(E)}/${Fn(H)==="responses"?"responses":"chat/completions"}`,De={...Of(),authorization:`Bearer ${g.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},O=new Set,T;for(let H of re.slice(0,4)){let fe=await t.probeSeatChatModel(Ke(H.id),De,H.id);if(fe==="ok"){T=H;break}if(fe==="unreachable")break;O.add(H.id)}P=T??re.find(H=>!O.has(H.id))??re[0]}x=P?.id??xf}let $=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,Y=$&&s.clientKey?Mt($):$,Z=aC(s,x,g.token,$,P,E),W=aC(s,x,Mt(g.token),Y,P,E),z=Fn(x),me=I.filter(re=>uC(re)&&Fn(re.id)===z).map(re=>re.id).filter(re=>re!==x),Te=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${g.source}).`,`Model: ${x}${C?" (pinned via ANYRAY_COPILOT_MODEL)":I.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...I.length===0&&zk(g.source)?["GitHub served no current models for this sign-in \u2014 the Copilot CLI's own login is","entitled to legacy models only. Fix it with: `anyray-connect copilot-login`","(one browser step), then re-run this command."]:[],...me.length>0?[`Your plan also serves: ${me.slice(0,8).join(", ")}${me.length>8?", \u2026":""} \u2014 switch anytime with \`copilot --model <id>\`.`]:[]];return n()?{status:"manual",messages:["Windows: run these in PowerShell (persists user env), then restart your terminal \u2014",...W.map(re=>{let Ke=re.indexOf("="),De=re.slice(7,Ke),O=re.slice(Ke+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${De}', ${EL(O)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${g.source}, and the gateway key from \`anyray-connect print-key\`.)`,...Te]}:l(Z,W,Te)}if(!yL(s,h)){if(p&&!i.dryRun){let E=vt();if(await Ts(E,An))return{status:"reverted",changedFiles:[E],messages:[`removed a stale Anyray ${An} block from ${E}`,"It routed the CLI on ORG API billing, which predates the Copilot","seat lane and is not a lane you chose. Nothing replaces it yet:",...iC(t.platform(),y),...sC()]}}return{status:"held",messages:[...p&&i.dryRun?[`would remove a stale Anyray ${An} block from ${vt()} (org lane, not chosen)`]:[],...iC(t.platform(),y)]}}let b=fL(),A=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,v=A&&s.clientKey?Mt(A):A;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...Ef(s,b,v).map(E=>{let[x,...C]=E.replace(/^export /,"").split("=");return` setx ${x} "${C.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${Il} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(Ef(s,b,A),Ef(s,b,v),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===Js?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=vt(),c=vf(),l=await R(c),d=l?nC(await tC(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${An} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Un()} if registered`,...await R(oa())?[`would remove the Copilot sign-in Connect minted (${oa()})`]:[]]};let u=await Ts(i,An);d&&await zs(c,{force:!0});let f=await AL(),p=oa(),h=await R(p);h&&await zs(p,{force:!0});let m=[...u?[i]:[],...d?[c]:[],...f?[Un()]:[],...h?[p]:[]];return{status:m.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${An} block from ${i}`:`no Anyray ${An} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...h?[`removed the Copilot sign-in Connect minted (${p})`]:[],...f?[`removed the Anyray MCP server from ${Un()}`]:[],...sC()],changedFiles:m.length>0?m:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){try{let s=await F(Un()),i=Ar(s)?s.mcpServers:void 0,c=Ar(i)?i[ro]:void 0;return!Ar(c)||!zt(c,"profile")?{registered:!1,command:null}:{registered:!0,command:typeof c.command=="string"?c.command:null}}catch{return{registered:!1,command:null}}},async inferenceAuthLanes(){try{let s=await r();return s===void 0?["native"]:Sf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(oo)?!0:!await t.detectCopilotSeat()}}},pC=xL();import{homedir as kC}from"node:os";import{join as Sr}from"node:path";import{constants as OL,chmod as _L,copyFile as PL,readFile as _l}from"node:fs/promises";import{applyEdits as TL,modify as DL}from"jsonc-parser";import{readFile as fC,rm as IL}from"node:fs/promises";var hC="// Managed by anyray-connect: OpenCode trim carrier v1",RL=5e3,Pf=e=>`${hC}
|
|
121
121
|
import { spawn } from "node:child_process"
|
|
122
122
|
|
|
123
123
|
const hookCommand = ${JSON.stringify([e.command,...e.args])}
|
|
@@ -189,37 +189,37 @@ export const AnyrayTrimPlugin = async () => ({
|
|
|
189
189
|
},
|
|
190
190
|
})
|
|
191
191
|
`,ei=async e=>await R(e)?(await fC(e,"utf-8")).startsWith(`${hC}
|
|
192
|
-
`)?"owned":"foreign":"absent",mC=async(e,t)=>{let n=
|
|
192
|
+
`)?"owned":"foreign":"absent",mC=async(e,t)=>{let n=Pf(t),r=await ei(e);return r==="foreign"?"foreign":r==="owned"&&await fC(e,"utf-8")===n?"unchanged":(await pe(e,n),"installed")},Tf=async e=>{let t=await ei(e);return t!=="owned"?t:(await IL(e,{force:!0}),"removed")};var Df="https://opencode.ai/config.json",Hn="x-anyray-metadata",Ft="x-anyray-api-key",Lf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Bn="Authorization",vr=["anthropic","openai"],Kn="github-copilot",LL="header",Wn="anyray",NL=()=>process.env.XDG_CONFIG_HOME?.trim()||Sr(kC(),".config"),$L=()=>process.env.XDG_DATA_HOME?.trim()||Sr(kC(),".local","share"),Pl=()=>Sr(NL(),"opencode"),Rl=()=>Sr(Pl(),"plugins","anyrayTrim.js"),CC=()=>Sr($L(),"opencode"),AC=async()=>{try{let e=await _l(Sr(CC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return B(t)?{chatGptOAuth:B(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}}},yC=async()=>(await AC()).chatGptOAuth,ML=["opencode.jsonc","opencode.json","config.json"],ca=async()=>{let e=Pl(),t=[];for(let n of ML){let r=Sr(e,n);await R(r)&&t.push(r)}return t},gC=async()=>(await ca())[0]??Sr(Pl(),"opencode.json"),ia=async e=>{let t=await R(e),n=t?await _l(e,"utf8"):`{}
|
|
193
193
|
`,r=n.trim()?ze(n):{};if(!B(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},vC=(e,t,n=[])=>{if(B(e)&&B(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...vC(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}]},wC=async(e,t,n,r)=>{let o=vC(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await PL(e,`${e}.anyray-bak`,OL.COPYFILE_EXCL),await _L(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await pe(`${e}.anyray-bak`,`{}
|
|
194
194
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
195
195
|
`)?`\r
|
|
196
196
|
`:`
|
|
197
197
|
`},s=t.raw;for(let i of o)s=TL(s,DL(s,i.path,i.value,{formattingOptions:a}));return await pe(e,s.endsWith(`
|
|
198
198
|
`)?s:`${s}
|
|
199
|
-
`),!0},UL=async e=>{try{let t=ze(await Ol(`${e}.anyray-bak`,"utf8"));return B(t)?t:void 0}catch{return}},Lf=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",Nf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Lf()}/${LL}`,B=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}/`)},FL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===vr[0]||n===vr[1]||n===Kn?[]:B(r)&&B(r.options)&&Bf(r.options.baseURL,t)?[n]:[]),$f=/claude/i,Wf=["model","small_model"],SC=(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)||!$f.test(o)))return`${vr[0]}/${o}`},Mf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Mf(n,t);return t}if(!B(e))return t;for(let[n,r]of Object.entries(e))Wf.includes(n)&&typeof r=="string"?t.push(r):Mf(r,t);return t},BL=(e,t,n)=>{if(!B(e)||!B(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>$f.test(a)))return!1;let o=`${n}/`;return Mf(t).filter(a=>a.startsWith(o)).every(a=>$f.test(a.slice(o.length)))},Uf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Uf(o,t,n));if(!B(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Wf.includes(o)?SC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Uf(a,t,n)}return r},Ff=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Ff(o,t[a],n));if(!B(e)||!B(t))return e;let r={};for(let[o,a]of Object.entries(e))Wf.includes(o)&&typeof a=="string"&&SC(t[o],n)===a?r[o]=t[o]:r[o]=Ff(a,t[o],n);return r},WL=e=>{if(B(e))for(let t of vr){let n=e[t];if(B(n)&&B(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},ti=e=>{if(!B(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&zt({command:t,args:n},"profile")},Rl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),HL=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return B(t)&&t.tool==="opencode"}catch{return!1}},Hf=e=>X(e,"copilot")&&!!e.clientKey,KL=e=>e.byoUpstream?[]:X(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],GL=(e,t)=>X(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.`]:[],jL=e=>Hf(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."]:[],VL=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Tf);let o=!1;if(n)if("mcp"in r&&!B(r.mcp))o=!0;else{let y=B(r.mcp)?{...r.mcp}:{},b=y[Wn];b!==void 0&&!ti(b)?o=!0:(y[Wn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(B(r.mcp)&&ti(r.mcp[Wn])){let y={...r.mcp};delete y[Wn],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=B(r.provider)?{...r.provider}:{},s=FL(a,t.origin),i=s.every(y=>BL(a[y],e,y))?s:[],c=s.filter(y=>!i.includes(y)),l=[];if(i.length>0){for(let y of i)delete a[y];r=Uf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,h=de({...t.metadata,tool:"opencode"});for(let y of c){let b={...a[y]},A={...b.options};if("headers"in A&&!B(A.headers)){u.push(y);continue}let v=B(A.headers)?{...A.headers}:{},E=!1;for(let[I,C]of[[Ft,p],...h?[[Hn,h]]:[]])I in v?(typeof v[I]!="string"||v[I].trim()==="")&&u.push(`${y}.${I}`):(v[I]=C,d.push(`${y}.${I}`),E=!0);E&&(A.headers=v,b.options=A,a[y]=b)}let m=c.length>0?[]:vr.filter(y=>y!=="openai"||!X(t,"openai")),w=t.byoUpstream;for(let y of m){let b=B(a[y])?{...a[y]}:{},A=B(b.options)?{...b.options}:{};A.baseURL=f;let v=B(A.headers)?{...A.headers}:{};if(y==="anthropic"&&w)A.apiKey=w.key,v[Bn]=`Bearer ${w.key}`,v["x-anyray-provider"]="anthropic",v["x-anyray-auth-mode"]="passthrough",v["x-anyray-custom-host"]=w.url;else{A.apiKey=p,"x-anyray-custom-host"in v&&delete v[Bn];for(let E of Df)delete v[E]}v[Ft]=p,h&&(v[Hn]=h),A.headers=v,b.options=A,a[y]=b}let g=c.length===0&&Hf(t);if(g){let y=B(a[Kn])?{...a[Kn]}:{},b=B(y.options)?{...y.options}:{};b.baseURL=Nf(t);let A=B(b.headers)?{...b.headers}:{};A[Ft]=t.clientKey,h&&(A[Hn]=h),b.headers=A,y.options=b,a[Kn]=y}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:g,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},YL=["baseURL","apiKey"],bC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!B(s)||!B(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=B(c.headers)?{...c.headers}:void 0,f=u?.[Ft],p=Rl(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let h=u,m=B(r)?r.options:void 0,w=B(m)&&B(m.headers)?m.headers:void 0;for(let g of[Ft,Hn])w&&g in w?h[g]!==w[g]&&(h[g]=w[g],l=!0):g in h&&(delete h[g],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}else{let d=B(r)?r.options:void 0,u=B(d)?d:{},f=B(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Ft]=="string"||typeof f[Hn]=="string"||Df.some(h=>h in f);if(!o&&!p)return!1;for(let h of YL)h in u?c[h]!==u[h]&&(c[h]=u[h],l=!0):h in c&&(delete c[h],l=!0);if(B(c.headers)){let h={...c.headers},m=B(u.headers)?u.headers:{};"x-anyray-custom-host"in h&&Bn in h&&(Bn in m?h[Bn]!==m[Bn]&&(h[Bn]=m[Bn],l=!0):(delete h[Bn],l=!0));for(let w of[Ft,Hn,...Df])w in m?h[w]!==m[w]&&(h[w]=m[w],l=!0):w in h&&(delete h[w],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}return l?(Object.keys(c).length===0?delete i.options:i.options=c,Object.keys(i).length===0?delete e[t]:e[t]=i,!0):!1},ZL=(e,t,n)=>{let r=e[t];if(!B(r)||!B(r.options)||!B(n)||!B(n.options))return!1;let o={...r.options};if(!B(o.headers)||"headers"in n.options&&!B(n.options.headers))return!1;let a={...o.headers},s=B(n.options.headers)?n.options.headers:{},i=!1;return!(Ft in s)&&Rl(a[Ft])&&(delete a[Ft],i=!0),!(Hn in s)&&HL(a[Hn])&&(delete a[Hn],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},JL=(e,t)=>{let n={...e},r=!1,o=WL(e.provider);if(B(n.mcp)&&ti(n.mcp[Wn])){let c={...n.mcp};delete c[Wn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!B(n.provider))return{next:n,removed:r};let a={...n.provider},s=B(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Tf&&vr.every(c=>{let l=a[c];return B(l)&&B(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of vr)bC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...vr,Kn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;ZL(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&B(u)&&B(u.options)&&Bf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Ff(n,t,l))}return bC(a,Kn,!0,s[Kn])&&(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}},EC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=_l(),t=CC(),n=await R(e)||await R(t),r=n&&await yC();return{installed:n,detail:n?`${await gC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await gC(),r=e.openaiBaseUrl,o=de({...e.metadata,tool:"opencode"}),a=Hf(e),s=X(e,"openai"),i=await yC(),c;try{c=await ia(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(Nf(e))}, "headers": { "${Ft}": "<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 Hr()?Ve("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=VL(c.data,e,l),g=u.length>0,y=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(C=>`provider.${C}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...p.length>0?[`Updated model references: ${p.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=g?[`${n} already routes through ${e.origin} via ${u.map(C=>`provider.${C}`).join(", ")}; existing provider values were preserved.`,h.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${h.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...m.length>0?[`Could not safely add required headers at ${m.join(", ")} because the existing values have incompatible shapes. Fix those values manually; no existing value was replaced.`]:[],"Canonical anthropic, openai, and github-copilot provider blocks were left untouched.","Restart OpenCode (or start a new session) to pick up the change."]:[...y,s?`${n} \u2192 provider.anthropic options.baseURL = ${r}; provider.openai left untouched because OpenCode's ChatGPT OAuth loader has no configurable endpoint.`:`${n} \u2192 provider.anthropic + provider.openai options.baseURL = ${r}`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${o??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...KL(e),...GL(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Nf(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. ${Lf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Lf()} 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).",...jL(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Wn} 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 A=m.length>0?"manual":"configured";if(t.dryRun)return{status:A,messages:b};let E=await wC(n,c,d,!0)?[n]:[],I=xl();if(le())try{let C=await mC(I,ps(Xe,["opencode"]));C==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${I} already exists and is not owned by Anyray.`):(C==="installed"&&E.push(I),b.push(`The OpenCode tool.execute.after carrier is active in ${I}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${I}. Gateway-side optimization remains active.`)}else{try{await Pf(I)==="removed"&&E.push(I)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:A,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await ca())try{let{data:n}=await ia(t);if(!B(n.provider))continue;for(let r of Object.values(n.provider))if(!(!B(r)||!B(r.options))&&Bf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await ca())try{let{data:t}=await ia(e);if(!B(t.mcp))continue;let n=t.mcp[Wn];if(!ti(n)||!B(n))continue;return{registered:!0,command:Array.isArray(n.command)&&typeof n.command[0]=="string"?n.command[0]:null}}catch{}return{registered:!1,command:null}},async integrationStatus(){let e,t=!0;try{let i=await ei(xl());e=i==="absent"?"missing":i,e==="owned"&&(t=await Ol(xl(),"utf-8")===_f(ps(Xe,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await ca()){let c;try{c=await ia(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!B(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Wn];if(l!==void 0)if(ti(l))if(n=!0,!B(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;Sc({command:d,args:u},"profile")||(a=!1)}else r=!0}return{hook_registration:e,mcp_registration:o?"unreadable":r?"foreign":n?"owned":"missing",hook_binary:t&&a&&await Hr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await AC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await ca()){let{data:o}=await ia(r);if(B(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!B(s)||!B(s.options)){e.add("unknown");continue}let i=s.options,c=B(i.headers)?i.headers:{};if(a===Kn&&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===Kn&&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(Rl(c[Ft])||Rl(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 ca(),n=xl(),r="absent";try{r=await ei(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 ia(i)}catch{s.push(i);continue}let{next:l,removed:d}=JL(c.data,await UL(i));d&&(await wC(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await se(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 Pf(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 _C}from"node:os";import{join as Tl}from"node:path";import{constants as eN,chmod as tN,copyFile as nN,readFile as PC}from"node:fs/promises";import{applyEdits as rN,modify as oN}from"jsonc-parser";import{homedir as XL}from"node:os";import{dirname as qL,join as ni}from"node:path";import{mkdir as zL,readFile as xC,rm as QL}from"node:fs/promises";var Kf="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",IC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfQogICAgfQogIH0sCiAgImNvbmZpZ1NjaGVtYSI6IHsKICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAiYWRkaXRpb25hbFByb3BlcnRpZXMiOiBmYWxzZSwKICAgICJyZXF1aXJlZCI6IFsiZ2F0ZXdheVVybCJdLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkFueXJheSBnYXRld2F5IG9yaWdpbiwgZS5nLiBodHRwczovL2dhdGV3YXkuZXhhbXBsZS5hbnlyYXkuYWkgKG5vIC92MSBzdWZmaXgpLiIKICAgICAgfSwKICAgICAgImFwaUtleSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJQZXJzb25hbCBBbnlyYXkgY2xpZW50IGtleSAoYXJrX+KApikuIFN1cHBvcnRzICR7RU5WX1ZBUn0gc3Vic3RpdHV0aW9uOyBkZWZhdWx0cyB0byAke0FOWVJBWV9DTElFTlRfS0VZfS4iCiAgICAgIH0sCiAgICAgICJ1c2VyIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkF0dHJpYnV0aW9uIHVzZXIgKGNvbnRlbnQtZnJlZTsgdXN1YWxseSBhbiBlbWFpbCkuIE9wdGlvbmFsIOKAlCB0aGUgY2xpZW50IGtleSBhbHJlYWR5IGF0dHJpYnV0ZXMgdGhlIGVucm9sbGVkIHVzZXIuIgogICAgICB9LAogICAgICAidGVhbSI6IHsKICAgICAgICAidHl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g=="}];var Gf=".anyray-source-sha",on=()=>ni(XL(),".anyray","openclaw-plugin"),RC=async(e=on())=>{try{if((await xC(ni(e,Gf),"utf8")).trim()===Kf)return"current"}catch{}for(let t of IC){let n=ni(e,t.path);await zL(qL(n),{recursive:!0,mode:448}),await pe(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await pe(ni(e,Gf),`${Kf}
|
|
200
|
-
`),"installed"},
|
|
201
|
-
`,r=n.trim()?ze(n):{};if(!N(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},LC=(e,t,n=[])=>{if(N(e)&&N(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...LC(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}]},
|
|
199
|
+
`),!0},UL=async e=>{try{let t=ze(await _l(`${e}.anyray-bak`,"utf8"));return B(t)?t:void 0}catch{return}},Nf=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",$f=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Nf()}/${LL}`,B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},FL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===vr[0]||n===vr[1]||n===Kn?[]:B(r)&&B(r.options)&&Wf(r.options.baseURL,t)?[n]:[]),Mf=/claude/i,Hf=["model","small_model"],SC=(e,t)=>{if(typeof e!="string")return;let n=e.indexOf("/");if(n<=0)return;let r=e.slice(0,n),o=e.slice(n+1);if(!(!t.includes(r)||!Mf.test(o)))return`${vr[0]}/${o}`},Uf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Uf(n,t);return t}if(!B(e))return t;for(let[n,r]of Object.entries(e))Hf.includes(n)&&typeof r=="string"?t.push(r):Uf(r,t);return t},BL=(e,t,n)=>{if(!B(e)||!B(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Mf.test(a)))return!1;let o=`${n}/`;return Uf(t).filter(a=>a.startsWith(o)).every(a=>Mf.test(a.slice(o.length)))},Ff=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Ff(o,t,n));if(!B(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Hf.includes(o)?SC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Ff(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(!B(e)||!B(t))return e;let r={};for(let[o,a]of Object.entries(e))Hf.includes(o)&&typeof a=="string"&&SC(t[o],n)===a?r[o]=t[o]:r[o]=Bf(a,t[o],n);return r},WL=e=>{if(B(e))for(let t of vr){let n=e[t];if(B(n)&&B(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},ti=e=>{if(!B(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&zt({command:t,args:n},"profile")},Ol=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),HL=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return B(t)&&t.tool==="opencode"}catch{return!1}},Kf=e=>X(e,"copilot")&&!!e.clientKey,KL=e=>e.byoUpstream?[]:X(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],GL=(e,t)=>X(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.`]:[],jL=e=>Kf(e)?["Tip: to spend your Copilot subscription (incl. Claude & GPT), pick the github-copilot/* models in OpenCode \u2014 e.g. github-copilot/claude-sonnet-4.5. The anthropic/* and openai/* entries are the direct providers (api-key mode, separate billing) \u2014 not your Copilot plan."]:[],VL=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Df);let o=!1;if(n)if("mcp"in r&&!B(r.mcp))o=!0;else{let y=B(r.mcp)?{...r.mcp}:{},b=y[Wn];b!==void 0&&!ti(b)?o=!0:(y[Wn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(B(r.mcp)&&ti(r.mcp[Wn])){let y={...r.mcp};delete y[Wn],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=B(r.provider)?{...r.provider}:{},s=FL(a,t.origin),i=s.every(y=>BL(a[y],e,y))?s:[],c=s.filter(y=>!i.includes(y)),l=[];if(i.length>0){for(let y of i)delete a[y];r=Ff(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,h=de({...t.metadata,tool:"opencode"});for(let y of c){let b={...a[y]},A={...b.options};if("headers"in A&&!B(A.headers)){u.push(y);continue}let v=B(A.headers)?{...A.headers}:{},E=!1;for(let[x,C]of[[Ft,p],...h?[[Hn,h]]:[]])x in v?(typeof v[x]!="string"||v[x].trim()==="")&&u.push(`${y}.${x}`):(v[x]=C,d.push(`${y}.${x}`),E=!0);E&&(A.headers=v,b.options=A,a[y]=b)}let m=c.length>0?[]:vr.filter(y=>y!=="openai"||!X(t,"openai")),w=t.byoUpstream;for(let y of m){let b=B(a[y])?{...a[y]}:{},A=B(b.options)?{...b.options}:{};A.baseURL=f;let v=B(A.headers)?{...A.headers}:{};if(y==="anthropic"&&w)A.apiKey=w.key,v[Bn]=`Bearer ${w.key}`,v["x-anyray-provider"]="anthropic",v["x-anyray-auth-mode"]="passthrough",v["x-anyray-custom-host"]=w.url;else{A.apiKey=p,"x-anyray-custom-host"in v&&delete v[Bn];for(let E of Lf)delete v[E]}v[Ft]=p,h&&(v[Hn]=h),A.headers=v,b.options=A,a[y]=b}let g=c.length===0&&Kf(t);if(g){let y=B(a[Kn])?{...a[Kn]}:{},b=B(y.options)?{...y.options}:{};b.baseURL=$f(t);let A=B(b.headers)?{...b.headers}:{};A[Ft]=t.clientKey,h&&(A[Hn]=h),b.headers=A,y.options=b,a[Kn]=y}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:g,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},YL=["baseURL","apiKey"],bC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!B(s)||!B(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=B(c.headers)?{...c.headers}:void 0,f=u?.[Ft],p=Ol(f);if(d&&(delete c.baseURL,l=!0),u&&(d||p)){let h=u,m=B(r)?r.options:void 0,w=B(m)&&B(m.headers)?m.headers:void 0;for(let g of[Ft,Hn])w&&g in w?h[g]!==w[g]&&(h[g]=w[g],l=!0):g in h&&(delete h[g],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}else{let d=B(r)?r.options:void 0,u=B(d)?d:{},f=B(c.headers)?c.headers:{},p=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Ft]=="string"||typeof f[Hn]=="string"||Lf.some(h=>h in f);if(!o&&!p)return!1;for(let h of YL)h in u?c[h]!==u[h]&&(c[h]=u[h],l=!0):h in c&&(delete c[h],l=!0);if(B(c.headers)){let h={...c.headers},m=B(u.headers)?u.headers:{};"x-anyray-custom-host"in h&&Bn in h&&(Bn in m?h[Bn]!==m[Bn]&&(h[Bn]=m[Bn],l=!0):(delete h[Bn],l=!0));for(let w of[Ft,Hn,...Lf])w in m?h[w]!==m[w]&&(h[w]=m[w],l=!0):w in h&&(delete h[w],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}return l?(Object.keys(c).length===0?delete i.options:i.options=c,Object.keys(i).length===0?delete e[t]:e[t]=i,!0):!1},ZL=(e,t,n)=>{let r=e[t];if(!B(r)||!B(r.options)||!B(n)||!B(n.options))return!1;let o={...r.options};if(!B(o.headers)||"headers"in n.options&&!B(n.options.headers))return!1;let a={...o.headers},s=B(n.options.headers)?n.options.headers:{},i=!1;return!(Ft in s)&&Ol(a[Ft])&&(delete a[Ft],i=!0),!(Hn in s)&&HL(a[Hn])&&(delete a[Hn],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},JL=(e,t)=>{let n={...e},r=!1,o=WL(e.provider);if(B(n.mcp)&&ti(n.mcp[Wn])){let c={...n.mcp};delete c[Wn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!B(n.provider))return{next:n,removed:r};let a={...n.provider},s=B(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Df&&vr.every(c=>{let l=a[c];return B(l)&&B(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of vr)bC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...vr,Kn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;ZL(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&B(u)&&B(u.options)&&Wf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Bf(n,t,l))}return bC(a,Kn,!0,s[Kn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Df&&(delete n.$schema,r=!0),{next:n,removed:r}},EC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=Pl(),t=CC(),n=await R(e)||await R(t),r=n&&await yC();return{installed:n,detail:n?`${await gC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await gC(),r=e.openaiBaseUrl,o=de({...e.metadata,tool:"opencode"}),a=Kf(e),s=X(e,"openai"),i=await yC(),c;try{c=await ia(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($f(e))}, "headers": { "${Ft}": "<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 Hr()?Ve("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=VL(c.data,e,l),g=u.length>0,y=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(C=>`provider.${C}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...p.length>0?[`Updated model references: ${p.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=g?[`${n} already routes through ${e.origin} via ${u.map(C=>`provider.${C}`).join(", ")}; existing provider values were preserved.`,h.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${h.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...m.length>0?[`Could not safely add required headers at ${m.join(", ")} because the existing values have incompatible shapes. Fix those values manually; no existing value was replaced.`]:[],"Canonical anthropic, openai, and github-copilot provider blocks were left untouched.","Restart OpenCode (or start a new session) to pick up the change."]:[...y,s?`${n} \u2192 provider.anthropic options.baseURL = ${r}; provider.openai left untouched because OpenCode's ChatGPT OAuth loader has no configurable endpoint.`:`${n} \u2192 provider.anthropic + provider.openai options.baseURL = ${r}`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${o??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...KL(e),...GL(e,i),a?`provider.github-copilot options.baseURL \u2192 ${$f(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. ${Nf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Nf()} 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).",...jL(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Wn} 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 A=m.length>0?"manual":"configured";if(t.dryRun)return{status:A,messages:b};let E=await wC(n,c,d,!0)?[n]:[],x=Rl();if(le())try{let C=await mC(x,ps(Xe,["opencode"]));C==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${x} already exists and is not owned by Anyray.`):(C==="installed"&&E.push(x),b.push(`The OpenCode tool.execute.after carrier is active in ${x}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${x}. Gateway-side optimization remains active.`)}else{try{await Tf(x)==="removed"&&E.push(x)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:A,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await ca())try{let{data:n}=await ia(t);if(!B(n.provider))continue;for(let r of Object.values(n.provider))if(!(!B(r)||!B(r.options))&&Wf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await ca())try{let{data:t}=await ia(e);if(!B(t.mcp))continue;let n=t.mcp[Wn];if(!ti(n)||!B(n))continue;return{registered:!0,command:Array.isArray(n.command)&&typeof n.command[0]=="string"?n.command[0]:null}}catch{}return{registered:!1,command:null}},async integrationStatus(){let e,t=!0;try{let i=await ei(Rl());e=i==="absent"?"missing":i,e==="owned"&&(t=await _l(Rl(),"utf-8")===Pf(ps(Xe,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await ca()){let c;try{c=await ia(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!B(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Wn];if(l!==void 0)if(ti(l))if(n=!0,!B(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;Sc({command:d,args:u},"profile")||(a=!1)}else r=!0}return{hook_registration:e,mcp_registration:o?"unreadable":r?"foreign":n?"owned":"missing",hook_binary:t&&a&&await Hr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await AC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await ca()){let{data:o}=await ia(r);if(B(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!B(s)||!B(s.options)){e.add("unknown");continue}let i=s.options,c=B(i.headers)?i.headers:{};if(a===Kn&&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===Kn&&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(Ol(c[Ft])||Ol(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 ca(),n=Rl(),r="absent";try{r=await ei(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 ia(i)}catch{s.push(i);continue}let{next:l,removed:d}=JL(c.data,await UL(i));d&&(await wC(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await se(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 _C}from"node:os";import{join as Dl}from"node:path";import{constants as eN,chmod as tN,copyFile as nN,readFile as PC}from"node:fs/promises";import{applyEdits as rN,modify as oN}from"jsonc-parser";import{homedir as XL}from"node:os";import{dirname as qL,join as ni}from"node:path";import{mkdir as zL,readFile as IC,rm as QL}from"node:fs/promises";var Gf="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",xC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfQogICAgfQogIH0sCiAgImNvbmZpZ1NjaGVtYSI6IHsKICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAiYWRkaXRpb25hbFByb3BlcnRpZXMiOiBmYWxzZSwKICAgICJyZXF1aXJlZCI6IFsiZ2F0ZXdheVVybCJdLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkFueXJheSBnYXRld2F5IG9yaWdpbiwgZS5nLiBodHRwczovL2dhdGV3YXkuZXhhbXBsZS5hbnlyYXkuYWkgKG5vIC92MSBzdWZmaXgpLiIKICAgICAgfSwKICAgICAgImFwaUtleSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJQZXJzb25hbCBBbnlyYXkgY2xpZW50IGtleSAoYXJrX+KApikuIFN1cHBvcnRzICR7RU5WX1ZBUn0gc3Vic3RpdHV0aW9uOyBkZWZhdWx0cyB0byAke0FOWVJBWV9DTElFTlRfS0VZfS4iCiAgICAgIH0sCiAgICAgICJ1c2VyIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkF0dHJpYnV0aW9uIHVzZXIgKGNvbnRlbnQtZnJlZTsgdXN1YWxseSBhbiBlbWFpbCkuIE9wdGlvbmFsIOKAlCB0aGUgY2xpZW50IGtleSBhbHJlYWR5IGF0dHJpYnV0ZXMgdGhlIGVucm9sbGVkIHVzZXIuIgogICAgICB9LAogICAgICAidGVhbSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB0ZWFtIChjb250ZW50LWZyZWUpLiBPcHRpb25hbC4iCiAgICAgIH0KICAgIH0sCiAgICAidWlIaW50cyI6IHsKICAgICAgImdhdGV3YXlVcmwiOiB7CiAgICAgICAgImxhYmVsIjogIkdhdGV3YXkgVVJMIiwKICAgICAgICAiaGVscCI6ICJZb3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IG9yaWdpbi4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgImxhYmVsIjogIkNsaWVudCBrZXkiLAogICAgICAgICJoZWxwIjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudC4gTGVhdmUgdW5zZXQgdG8gcmVhZCAkQU5ZUkFZX0NMSUVOVF9LRVkuIgogICAgICB9CiAgICB9CiAgfQp9Cg=="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjEuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIs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uUGF5bG9hZChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpIDogcGF5bG9hZDsKICAgIH07CiAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdHMpOwogIH07CiAgcmV0dXJuIHdyYXBwZWQ7Cn07Cg=="}];var jf=".anyray-source-sha",on=()=>ni(XL(),".anyray","openclaw-plugin"),RC=async(e=on())=>{try{if((await IC(ni(e,jf),"utf8")).trim()===Gf)return"current"}catch{}for(let t of xC){let n=ni(e,t.path);await zL(qL(n),{recursive:!0,mode:448}),await pe(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await pe(ni(e,jf),`${Gf}
|
|
200
|
+
`),"installed"},Tl=async(e=on())=>{try{await IC(ni(e,jf),"utf8")}catch{return!1}return await QL(e,{recursive:!0,force:!0}),!0};var Jf="x-anyray-metadata",la="x-anyray-api-key",Xf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],so="Authorization",io="anthropic-beta",Ll="interleaved-thinking-2025-05-14",Nl=["anthropic","openai"],TC="short",zf="anthropic-messages",Qf=32e3,$l="anthropic/claude-sonnet-4-5",eh=["anthropic/claude-haiku-4-5"],th="anyray/claude-sonnet-4-5",nh=["anyray/claude-haiku-4-5"],aN=[$l,th],sN=[eh,nh],Qe="anyray",Er="ANYRAY_API_KEY",oi="openclaw",DC=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Dl(_C(),".openclaw"),ao=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Dl(DC(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),OC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},ri=async e=>{let t=await R(e),n=t?await PC(e,"utf8"):`{}
|
|
201
|
+
`,r=n.trim()?ze(n):{};if(!N(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},LC=(e,t,n=[])=>{if(N(e)&&N(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...LC(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}]},Vf=async(e,t,n,r)=>{let o=LC(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await nN(e,`${e}.anyray-bak`,eN.COPYFILE_EXCL),await tN(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await pe(`${e}.anyray-bak`,`{}
|
|
202
202
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
203
203
|
`)?`\r
|
|
204
204
|
`:`
|
|
205
205
|
`},s=t.raw;for(let i of o)s=rN(s,oN(s,i.path,i.value,{formattingOptions:a}));return await pe(e,s.endsWith(`
|
|
206
206
|
`)?s:`${s}
|
|
207
|
-
`),!0},Vf=async e=>{try{let t=ze(await PC(`${e}.anyray-bak`,"utf8"));return N(t)?t:void 0}catch{return}},Xf=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},iN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=de({...t.metadata,tool:oi}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!N(l.models)&&d.push("models");let u=N(l.models)?{...l.models}:{};if("providers"in u&&!N(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=N(u.providers)?{...u.providers}:{},p=!1;if(n){let v=N(l.plugins)?{...l.plugins}:{},E=N(v.load)?{...v.load}:{},I=N(v.entries)?{...v.entries}:{},C=N(I[Qe])?{...I[Qe]}:{},x=N(C.config)?{...C.config}:{};if("plugins"in l&&!N(l.plugins)||"load"in v&&!N(v.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in v&&!N(v.entries)||Qe in I&&!N(I[Qe])||"config"in C&&!N(C.config)||"env"in l&&!N(l.env))d.push("plugins");else{let P=Array.isArray(E.paths)?[...E.paths]:[];P.includes(n)||P.push(n),E.paths=P,v.load=E,C.enabled=!0,x.gatewayUrl=t.anthropicBaseUrl,x.apiKey=r;let $=t.metadata.user,Y=t.metadata.team;$&&(x.user=$),Y&&(x.team=Y),C.config=x,I[Qe]=C,v.entries=I,l.plugins=v;let Z=N(l.env)?{...l.env}:{};Z[Er]=r,l.env=Z,p=!0}}let h=Ll.filter(v=>v!=="openai"||!X(t,"openai"));for(let v of h){if(v in f&&!N(f[v])){d.push(`models.providers.${v}`);continue}let E=N(f[v])?{...f[v]}:{};if("headers"in E&&!N(E.headers)){i.push(v);continue}let I=N(E.headers)?{...E.headers}:{};if(E.baseUrl=v==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,v==="anthropic"&&(E.api=qf,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=zf)),v==="anthropic"&&a)E.apiKey=a.key,I[so]=`Bearer ${a.key}`,I["x-anyray-provider"]="anthropic",I["x-anyray-auth-mode"]="passthrough",I["x-anyray-custom-host"]=a.url;else{E.apiKey=r,"x-anyray-custom-host"in I&&delete I[so];for(let C of Jf)delete I[C]}I[la]=r,o&&(I[Zf]=o),v==="anthropic"&&(io in I?c=I[io]!==Dl:I[io]=Dl),E.headers=I,f[v]=E,s.push(v)}u.providers=f,l.models=u;let m=!1,w=!1,g=!1,y,b=[],A="agents"in l&&!N(l.agents)||N(l.agents)&&"defaults"in l.agents&&!N(l.agents.defaults)||N(l.agents)&&N(l.agents.defaults)&&("params"in l.agents.defaults&&!N(l.agents.defaults.params)||"model"in l.agents.defaults&&!N(l.agents.defaults.model));if(A&&d.push("agents.defaults"),s.includes("anthropic")&&!A){let v=N(l.agents)?{...l.agents}:{},E=N(v.defaults)?{...v.defaults}:{},I=N(E.params)?{...E.params}:{};"cacheRetention"in I||(I.cacheRetention=TC,m=!0,E.params=I);let C=N(E.model)?{...E.model}:{},x=p?[...s,Qe]:s,P=$=>typeof $=="string"&&x.some(Y=>$.startsWith(`${Y}/`));typeof C.primary!="string"||C.primary.trim()===""?(C.primary=p?eh:Nl,w=!0,E.model=C,"fallbacks"in C||(C.fallbacks=p?[...th]:[...Qf],g=!0)):P(C.primary)||(y=C.primary),b=(Array.isArray(C.fallbacks)?C.fallbacks:[]).filter($=>typeof $=="string"&&!P($)),(m||w)&&(v.defaults=E,l.agents=v)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:g,unroutedPrimary:y,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},cN=["baseUrl","apiKey","api","maxTokens"],Yf=(e,t,n=Ll,r)=>{let o={...e},a=!("models"in o)||N(o.models)&&(!("providers"in o.models)||N(o.models.providers)),s=N(o.models)?{...o.models}:{},i=N(s.providers)?{...s.providers}:{},c=Xf(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!N(f))continue;let p={...f},h=N(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof h[la]=="string"||typeof h[Zf]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Jf.some(v=>v in h)))continue;let w=N(c[u])?c[u]:{},g=N(w.headers)?w.headers:{},y="x-anyray-custom-host"in h,b=v=>v==="api"?p.api===qf:v==="maxTokens"?p.maxTokens===zf:v==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let v of cN)b(v)&&(v in w?p[v]!==w[v]&&(p[v]=w[v],l=!0):v in p&&(delete p[v],l=!0));let A=[la,Zf,...Jf,..."x-anyray-custom-host"in h?[so]:[]];h[io]===Dl&&A.push(io);for(let v of A)v in g?h[v]!==g[v]&&(h[v]=g[v],l=!0):v in h&&(delete h[v],l=!0);so in g&&!(so in h)&&(h[so]=g[so],l=!0),Object.keys(h).length===0?delete p.headers:p.headers=h,Object.keys(p).length===0?delete i[u]:i[u]=p}if(a&&(Object.keys(i).length===0?delete s.providers:s.providers=i,Object.keys(s).length===0?delete o.models:o.models=s),r&&n.includes("anthropic")){let u=N(o.plugins)?{...o.plugins}:{},f=N(u.load)?{...u.load}:{},p=N(u.entries)?{...u.entries}:{};if((!("plugins"in o)||N(o.plugins))&&(!("load"in u)||N(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||N(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let w=f.paths.filter(g=>g!==r);w.length===0?delete f.paths:f.paths=w,l=!0}let m=p[Qe];if(N(m)){let w=N(m.config)?m.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let y=N(t?.plugins)?t.plugins:{},b=N(y.entries)?y.entries:{};Qe in b?JSON.stringify(p[Qe])!==JSON.stringify(b[Qe])&&(p[Qe]=b[Qe],l=!0):(delete p[Qe],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,N(o.env)){let w={...o.env},g=w[Er];if(typeof g=="string"&&g.startsWith("ark_")){let y=N(t?.env)?t.env:{};Er in y?w[Er]!==y[Er]&&(w[Er]=y[Er],l=!0):(delete w[Er],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||N(o.agents)&&(!("defaults"in o.agents)||N(o.agents.defaults)&&(!("params"in o.agents.defaults)||N(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||N(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=N(o.agents)?{...o.agents}:{},f=N(u.defaults)?{...u.defaults}:{},p=N(f.params)?{...f.params}:{},h=N(t.agents)?t.agents:{},m=N(h.defaults)?h.defaults:{},w=N(m.params)?m.params:{};p.cacheRetention===TC&&("cacheRetention"in w?p.cacheRetention!==w.cacheRetention&&(p.cacheRetention=w.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let g=N(f.model)?{...f.model}:{},y=N(m.model)?m.model:{};aN.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),sN.some(b=>JSON.stringify(g.fallbacks)===JSON.stringify(b))&&("fallbacks"in y?JSON.stringify(g.fallbacks)!==JSON.stringify(y.fallbacks)&&(g.fallbacks=y.fallbacks,l=!0):(delete g.fallbacks,l=!0)),Object.keys(g).length===0?delete f.model:f.model=g,Object.keys(p).length===0?delete f.params:f.params=p,Object.keys(f).length===0?delete u.defaults:u.defaults=f,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},NC={id:oi,title:"OpenClaw",automatic:!0,async detect(){let e=await R(ao())||await R(DC());return{installed:e,detail:e?ao():`no ${Tl(_C(),".openclaw")} state dir`}},async apply(e,t){let n=ao();if(!e.byoUpstream&&X(e,"anthropic")){let E=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${oi}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],I;try{I=await ri(n)}catch{return{status:"held",messages:E}}let{next:C,removed:x}=Yf(I.data,await Vf(n),Ll,on());return x?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...E]}:(await jf(n,I,C,!1),await se(n),await Pl(),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...E]}):(t.dryRun||await Pl(),{status:"held",messages:E})}let r=on(),o=!1;if(!t.dryRun)try{await RC(r)}catch{r=void 0,o=!0}let a;try{a=await ri(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${qf}", "maxTokens": ${zf}, "apiKey": "<your personal ark_ key>", "headers": { "${la}": "<your personal ark_ key>", "${io}": "${Dl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${la}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Nl}") if none is set,`,'and under "agents.defaults.params" set "cacheRetention": "short" \u2014',"custom Anthropic-compatible hosts get no prompt-cache auto-seed, and","an unset value would leave the provider cache permanently cold.","Then run `openclaw config validate`."]}}let{next:s,routed:i,cacheRetentionSeeded:c,betaPreserved:l,headerConflicts:d,primarySeeded:u,fallbacksSeeded:f,unroutedPrimary:p,unroutedFallbacks:h,structureConflicts:m,pluginConfigured:w}=iN(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=Yf(g,await Vf(n),["openai"]);E.removed&&(g=E.next,y=!0)}let b=[i.includes("openai")?`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; models.providers.openai baseUrl = ${e.openaiBaseUrl}`:`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; openai left on its native ChatGPT sign-in`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${de({...e.metadata,tool:oi})??"(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 ${io} header value (OpenClaw suppresses its implicit beta headers off-host; yours replaces our default restore).`]:[],...d.length>0?[`Could not add headers on models.providers.${d.join(", ")}: the existing "headers" value is not an object. Fix it manually; nothing there was replaced.`]:[],...u?[`Seeded agents.defaults.model.primary = ${w?eh:Nl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?th:Qf).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...p!==void 0?[`Your primary model (${p}) resolves to a provider Connect does not route, so those requests bypass the gateway. Pick an anthropic/* or openai/* model to route them; your setting was kept.`]:[],...h.length>0?[`Fallback model(s) ${h.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...y?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...w?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${on()}) and registered it under plugins.entries.${Qe}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${on()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...m.length>0?[`Left ${m.join(", ")} untouched: the existing value has the wrong shape (array or null where an object belongs), and OpenClaw's strict schema will refuse it as-is. Fix the shape and re-run.`]:[],"OpenClaw hot-reloads model config; run `openclaw config validate` to confirm the merged config passes its strict schema."],A=d.length>0||m.length>0?"manual":"configured";if(t.dryRun)return{status:A,messages:b};let v=await jf(n,a,g,!0);return{status:A,messages:b,changedFiles:v?[n]:[]}},async pointsAt(e){try{let{data:t}=await ri(ao());for(let a of Object.values(Xf(t)))if(N(a)&&OC(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[Qe];if(N(o)&&N(o.config)&&OC(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[ao(),Tl(on(),".anyray-source-sha")]},async routingExpected(e){return e.includes(oi)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await ri(ao());for(let a of Object.values(Xf(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[la]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[Qe];if(N(o)&&N(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=ao();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await ri(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}=Yf(n.data,await Vf(t),Ll,on()),a=await Pl();return o?(await jf(t,n,r,!1),await se(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${on()}`]:[]],changedFiles:[t]}):(await se(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${on()}`]:[]]})}};import{execFile as zM}from"node:child_process";import{readFile as QM}from"node:fs/promises";import{homedir as vi,platform as xr}from"node:os";import{join as In}from"node:path";import{isDeepStrictEqual as Wh,promisify as eU}from"node:util";var ai=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},$l=(e,t)=>{let n=ai(e),r=ai(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 mM}from"node:crypto";import{promises as YA}from"node:fs";import{platform as yM,tmpdir as gM}from"node:os";import{join as ed}from"node:path";import{execFile as lN}from"node:child_process";import{promises as si}from"node:fs";import{homedir as dN,platform as uN}from"node:os";import{delimiter as pN,join as Ml}from"node:path";import{promisify as fN}from"node:util";var hN=fN(lN),mN=15*6e4,yN=64*1024*1024,gN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],$C=async(e={})=>{let t=(e.home??dN)(),n=e.env??process.env,r=gN(e.runtimePlatform??uN()),o=[Ml(t,".local","bin"),Ml(t,".claude","local"),...(n.PATH??"").split(pN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Ml(a,`claude${s}`);try{return await si.access(i),i}catch{}}return null},wN=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},bN=async e=>{let t=Ml(e,"projects"),n;try{n=(await si.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(!AN.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},kN=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:wN(n.projectList)}},CN=async e=>{let t,n;try{let r=await si.readFile(e,"utf8");for(let o of r.split(`
|
|
207
|
+
`),!0},Yf=async e=>{try{let t=ze(await PC(`${e}.anyray-bak`,"utf8"));return N(t)?t:void 0}catch{return}},qf=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},iN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=de({...t.metadata,tool:oi}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!N(l.models)&&d.push("models");let u=N(l.models)?{...l.models}:{};if("providers"in u&&!N(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=N(u.providers)?{...u.providers}:{},p=!1;if(n){let v=N(l.plugins)?{...l.plugins}:{},E=N(v.load)?{...v.load}:{},x=N(v.entries)?{...v.entries}:{},C=N(x[Qe])?{...x[Qe]}:{},I=N(C.config)?{...C.config}:{};if("plugins"in l&&!N(l.plugins)||"load"in v&&!N(v.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in v&&!N(v.entries)||Qe in x&&!N(x[Qe])||"config"in C&&!N(C.config)||"env"in l&&!N(l.env))d.push("plugins");else{let P=Array.isArray(E.paths)?[...E.paths]:[];P.includes(n)||P.push(n),E.paths=P,v.load=E,C.enabled=!0,I.gatewayUrl=t.anthropicBaseUrl,I.apiKey=r;let $=t.metadata.user,Y=t.metadata.team;$&&(I.user=$),Y&&(I.team=Y),C.config=I,x[Qe]=C,v.entries=x,l.plugins=v;let Z=N(l.env)?{...l.env}:{};Z[Er]=r,l.env=Z,p=!0}}let h=Nl.filter(v=>v!=="openai"||!X(t,"openai"));for(let v of h){if(v in f&&!N(f[v])){d.push(`models.providers.${v}`);continue}let E=N(f[v])?{...f[v]}:{};if("headers"in E&&!N(E.headers)){i.push(v);continue}let x=N(E.headers)?{...E.headers}:{};if(E.baseUrl=v==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,v==="anthropic"&&(E.api=zf,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=Qf)),v==="anthropic"&&a)E.apiKey=a.key,x[so]=`Bearer ${a.key}`,x["x-anyray-provider"]="anthropic",x["x-anyray-auth-mode"]="passthrough",x["x-anyray-custom-host"]=a.url;else{E.apiKey=r,"x-anyray-custom-host"in x&&delete x[so];for(let C of Xf)delete x[C]}x[la]=r,o&&(x[Jf]=o),v==="anthropic"&&(io in x?c=x[io]!==Ll:x[io]=Ll),E.headers=x,f[v]=E,s.push(v)}u.providers=f,l.models=u;let m=!1,w=!1,g=!1,y,b=[],A="agents"in l&&!N(l.agents)||N(l.agents)&&"defaults"in l.agents&&!N(l.agents.defaults)||N(l.agents)&&N(l.agents.defaults)&&("params"in l.agents.defaults&&!N(l.agents.defaults.params)||"model"in l.agents.defaults&&!N(l.agents.defaults.model));if(A&&d.push("agents.defaults"),s.includes("anthropic")&&!A){let v=N(l.agents)?{...l.agents}:{},E=N(v.defaults)?{...v.defaults}:{},x=N(E.params)?{...E.params}:{};"cacheRetention"in x||(x.cacheRetention=TC,m=!0,E.params=x);let C=N(E.model)?{...E.model}:{},I=p?[...s,Qe]:s,P=$=>typeof $=="string"&&I.some(Y=>$.startsWith(`${Y}/`));typeof C.primary!="string"||C.primary.trim()===""?(C.primary=p?th:$l,w=!0,E.model=C,"fallbacks"in C||(C.fallbacks=p?[...nh]:[...eh],g=!0)):P(C.primary)||(y=C.primary),b=(Array.isArray(C.fallbacks)?C.fallbacks:[]).filter($=>typeof $=="string"&&!P($)),(m||w)&&(v.defaults=E,l.agents=v)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:g,unroutedPrimary:y,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},cN=["baseUrl","apiKey","api","maxTokens"],Zf=(e,t,n=Nl,r)=>{let o={...e},a=!("models"in o)||N(o.models)&&(!("providers"in o.models)||N(o.models.providers)),s=N(o.models)?{...o.models}:{},i=N(s.providers)?{...s.providers}:{},c=qf(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!N(f))continue;let p={...f},h=N(p.headers)?{...p.headers}:{};if(!(t!==void 0||typeof h[la]=="string"||typeof h[Jf]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Xf.some(v=>v in h)))continue;let w=N(c[u])?c[u]:{},g=N(w.headers)?w.headers:{},y="x-anyray-custom-host"in h,b=v=>v==="api"?p.api===zf:v==="maxTokens"?p.maxTokens===Qf:v==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let v of cN)b(v)&&(v in w?p[v]!==w[v]&&(p[v]=w[v],l=!0):v in p&&(delete p[v],l=!0));let A=[la,Jf,...Xf,..."x-anyray-custom-host"in h?[so]:[]];h[io]===Ll&&A.push(io);for(let v of A)v in g?h[v]!==g[v]&&(h[v]=g[v],l=!0):v in h&&(delete h[v],l=!0);so in g&&!(so in h)&&(h[so]=g[so],l=!0),Object.keys(h).length===0?delete p.headers:p.headers=h,Object.keys(p).length===0?delete i[u]:i[u]=p}if(a&&(Object.keys(i).length===0?delete s.providers:s.providers=i,Object.keys(s).length===0?delete o.models:o.models=s),r&&n.includes("anthropic")){let u=N(o.plugins)?{...o.plugins}:{},f=N(u.load)?{...u.load}:{},p=N(u.entries)?{...u.entries}:{};if((!("plugins"in o)||N(o.plugins))&&(!("load"in u)||N(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||N(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let w=f.paths.filter(g=>g!==r);w.length===0?delete f.paths:f.paths=w,l=!0}let m=p[Qe];if(N(m)){let w=N(m.config)?m.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let y=N(t?.plugins)?t.plugins:{},b=N(y.entries)?y.entries:{};Qe in b?JSON.stringify(p[Qe])!==JSON.stringify(b[Qe])&&(p[Qe]=b[Qe],l=!0):(delete p[Qe],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,N(o.env)){let w={...o.env},g=w[Er];if(typeof g=="string"&&g.startsWith("ark_")){let y=N(t?.env)?t.env:{};Er in y?w[Er]!==y[Er]&&(w[Er]=y[Er],l=!0):(delete w[Er],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||N(o.agents)&&(!("defaults"in o.agents)||N(o.agents.defaults)&&(!("params"in o.agents.defaults)||N(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||N(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=N(o.agents)?{...o.agents}:{},f=N(u.defaults)?{...u.defaults}:{},p=N(f.params)?{...f.params}:{},h=N(t.agents)?t.agents:{},m=N(h.defaults)?h.defaults:{},w=N(m.params)?m.params:{};p.cacheRetention===TC&&("cacheRetention"in w?p.cacheRetention!==w.cacheRetention&&(p.cacheRetention=w.cacheRetention,l=!0):(delete p.cacheRetention,l=!0));let g=N(f.model)?{...f.model}:{},y=N(m.model)?m.model:{};aN.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),sN.some(b=>JSON.stringify(g.fallbacks)===JSON.stringify(b))&&("fallbacks"in y?JSON.stringify(g.fallbacks)!==JSON.stringify(y.fallbacks)&&(g.fallbacks=y.fallbacks,l=!0):(delete g.fallbacks,l=!0)),Object.keys(g).length===0?delete f.model:f.model=g,Object.keys(p).length===0?delete f.params:f.params=p,Object.keys(f).length===0?delete u.defaults:u.defaults=f,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},NC={id:oi,title:"OpenClaw",automatic:!0,async detect(){let e=await R(ao())||await R(DC());return{installed:e,detail:e?ao():`no ${Dl(_C(),".openclaw")} state dir`}},async apply(e,t){let n=ao();if(!e.byoUpstream&&X(e,"anthropic")){let E=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${oi}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],x;try{x=await ri(n)}catch{return{status:"held",messages:E}}let{next:C,removed:I}=Zf(x.data,await Yf(n),Nl,on());return I?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...E]}:(await Vf(n,x,C,!1),await se(n),await Tl(),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...E]}):(t.dryRun||await Tl(),{status:"held",messages:E})}let r=on(),o=!1;if(!t.dryRun)try{await RC(r)}catch{r=void 0,o=!0}let a;try{a=await ri(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${zf}", "maxTokens": ${Qf}, "apiKey": "<your personal ark_ key>", "headers": { "${la}": "<your personal ark_ key>", "${io}": "${Ll}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${la}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${$l}") if none is set,`,'and under "agents.defaults.params" set "cacheRetention": "short" \u2014',"custom Anthropic-compatible hosts get no prompt-cache auto-seed, and","an unset value would leave the provider cache permanently cold.","Then run `openclaw config validate`."]}}let{next:s,routed:i,cacheRetentionSeeded:c,betaPreserved:l,headerConflicts:d,primarySeeded:u,fallbacksSeeded:f,unroutedPrimary:p,unroutedFallbacks:h,structureConflicts:m,pluginConfigured:w}=iN(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=Zf(g,await Yf(n),["openai"]);E.removed&&(g=E.next,y=!0)}let b=[i.includes("openai")?`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; models.providers.openai baseUrl = ${e.openaiBaseUrl}`:`${n} \u2192 models.providers.anthropic baseUrl = ${e.anthropicBaseUrl}; openai left on its native ChatGPT sign-in`,e.byoUpstream?`Auth (anthropic): your personal upstream key (written to the config, not shown here) \u2014 the gateway forwards it verbatim to ${e.byoUpstream.url} (must be in the gateway's custom-host allowlist).`:e.clientKey?"Auth: your personal gateway key (written to the config, not shown here) \u2014 the gateway swaps in the server-held provider key.":"Enrollment required before a real apply; the gateway does not accept a shared placeholder.",`Attribution: ${de({...e.metadata,tool:oi})??"(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 ${io} header value (OpenClaw suppresses its implicit beta headers off-host; yours replaces our default restore).`]:[],...d.length>0?[`Could not add headers on models.providers.${d.join(", ")}: the existing "headers" value is not an object. Fix it manually; nothing there was replaced.`]:[],...u?[`Seeded agents.defaults.model.primary = ${w?th:$l} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?nh:eh).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...p!==void 0?[`Your primary model (${p}) resolves to a provider Connect does not route, so those requests bypass the gateway. Pick an anthropic/* or openai/* model to route them; your setting was kept.`]:[],...h.length>0?[`Fallback model(s) ${h.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...y?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...w?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${on()}) and registered it under plugins.entries.${Qe}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${on()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...m.length>0?[`Left ${m.join(", ")} untouched: the existing value has the wrong shape (array or null where an object belongs), and OpenClaw's strict schema will refuse it as-is. Fix the shape and re-run.`]:[],"OpenClaw hot-reloads model config; run `openclaw config validate` to confirm the merged config passes its strict schema."],A=d.length>0||m.length>0?"manual":"configured";if(t.dryRun)return{status:A,messages:b};let v=await Vf(n,a,g,!0);return{status:A,messages:b,changedFiles:v?[n]:[]}},async pointsAt(e){try{let{data:t}=await ri(ao());for(let a of Object.values(qf(t)))if(N(a)&&OC(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[Qe];if(N(o)&&N(o.config)&&OC(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[ao(),Dl(on(),".anyray-source-sha")]},async routingExpected(e){return e.includes(oi)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await ri(ao());for(let a of Object.values(qf(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[la]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[Qe];if(N(o)&&N(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=ao();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await ri(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}=Zf(n.data,await Yf(t),Nl,on()),a=await Tl();return o?(await Vf(t,n,r,!1),await se(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${on()}`]:[]],changedFiles:[t]}):(await se(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${on()}`]:[]]})}};import{execFile as zM}from"node:child_process";import{readFile as QM}from"node:fs/promises";import{homedir as vi,platform as Ir}from"node:os";import{join as xn}from"node:path";import{isDeepStrictEqual as Hh,promisify as eU}from"node:util";var ai=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},Ml=(e,t)=>{let n=ai(e),r=ai(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 mM}from"node:crypto";import{promises as YA}from"node:fs";import{platform as yM,tmpdir as gM}from"node:os";import{join as td}from"node:path";import{execFile as lN}from"node:child_process";import{promises as si}from"node:fs";import{homedir as dN,platform as uN}from"node:os";import{delimiter as pN,join as Ul}from"node:path";import{promisify as fN}from"node:util";var hN=fN(lN),mN=15*6e4,yN=64*1024*1024,gN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],$C=async(e={})=>{let t=(e.home??dN)(),n=e.env??process.env,r=gN(e.runtimePlatform??uN()),o=[Ul(t,".local","bin"),Ul(t,".claude","local"),...(n.PATH??"").split(pN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Ul(a,`claude${s}`);try{return await si.access(i),i}catch{}}return null},wN=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},bN=async e=>{let t=Ul(e,"projects"),n;try{n=(await si.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(!AN.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},kN=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:wN(n.projectList)}},CN=async e=>{let t,n;try{let r=await si.readFile(e,"utf8");for(let o of r.split(`
|
|
208
208
|
`)){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}},AN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vN=/\.(?:cmd|bat)$/i,SN=(e,t)=>vN.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},MC=async(e,t={})=>{let n=t.exec??hN,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 si.mkdir(e.configDir,{recursive:!0,mode:448}),await si.mkdir(e.workDir,{recursive:!0,mode:448});let o=SN(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:mN,maxBuffer:yN,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(`
|
|
209
|
-
`).filter(d=>d.trim().length>0),i=kN(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 CN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await bN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as EN}from"node:crypto";import{promises as Gn}from"node:fs";import{homedir as IN,platform as xN}from"node:os";import{join as It}from"node:path";var UC=448,jn="local_",RN="local-agent-mode-sessions",nh="-3p",ON="cowork_account_settings.json",co=(e={})=>{let t=(e.home??IN)(),n=e.runtimePlatform??xN(),r=e.env??process.env;if(n==="darwin")return It(t,"Library","Application Support",`Claude${nh}`);if(n==="win32"){let o=r.LOCALAPPDATA??It(t,"AppData","Local");return It(o,`Claude${nh}`)}return null},ii=(e={})=>{let t=co(e);return t?t.slice(0,-nh.length):null},rh=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)}`},Ul=async e=>{let t=It(e,RN),n;try{n=(await Gn.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 Gn.readdir(It(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=It(t,o,s);try{await Gn.access(It(i,ON)),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]}},oh=async e=>{try{let t=await Gn.readdir(e);return new Set(t.filter(n=>n.startsWith(jn)&&n.endsWith(".json")).map(n=>n.slice(jn.length,-5)))}catch{return new Set}},da=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),_N=async(e,t)=>{let n=`${jn}${t.sessionId}`,r=It(e,n),o=It(r,"outputs"),a=It(r,".claude"),s=It(a,"projects",rh(o));await Gn.mkdir(o,{recursive:!0,mode:UC}),await Gn.mkdir(s,{recursive:!0,mode:UC});let i=It(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${EN()}`;await Gn.copyFile(t.transcriptPath,c),await Gn.chmod(c,384),await Gn.rename(c,i);let l=t.createdAt??Date.now();await J(It(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})},FC=async(e,t)=>{let n=await oh(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!da(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await _N(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as ua}from"node:fs";import{homedir as PN}from"node:os";import{dirname as TN,join as ci}from"node:path";var DN=448,LN=["Documents","Claude","Projects"],NN="spaces.json",$N=(e={})=>ci((e.home??PN)(),...LN),MN=async e=>{try{let t=JSON.parse(await ua.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}}},UN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},ah=async e=>{try{return await ua.access(e),!0}catch{return!1}},FN=async(e,t,n)=>{let r=ci(t,UN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await ah(r)?o:r;return a===o&&await ah(o)?null:(await ua.mkdir(TN(a),{recursive:!0}),await ua.cp(e,a,{recursive:!0}),a)},BN=async e=>{try{let t=(await ua.readFile(ci(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},BC=async e=>{let t=$N({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=ci(e.storageDir,NN),{spaces:a,readable:s}=await MN(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=ci(e.stagedProjectsDir,l.dirName);try{if(!await ah(d)){n.failed+=1;continue}let u=await FN(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await BN(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 ua.mkdir(e.storageDir,{recursive:!0,mode:DN}),await J(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as GN}from"node:crypto";import{execFile as jN,spawnSync as qC}from"node:child_process";import{constants as zC}from"node:fs";import{access as Gl,chmod as VN,mkdir as YN,readdir as ZN,readFile as ih,rename as JN,rm as fa,stat as QC,writeFile as XN}from"node:fs/promises";import{homedir as qN,platform as zN,userInfo as QN}from"node:os";import{basename as e$,dirname as eA,isAbsolute as ha,join as Bt,resolve as jC}from"node:path";import{isDeepStrictEqual as di,promisify as t$}from"node:util";var li="__anyray-claude-desktop-credential";var Fl=["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>`."],Bl=["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."],WC="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 Wl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],HC=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],WN=new Set(HC),HN=new Set(HC.map(e=>e.toLowerCase())),KN=new Set(Wl.map(e=>e.toLowerCase())),Hl=(e,t=!1)=>(t?HN:WN).has(t?e.toLowerCase():e),KC=(e,t=!1)=>t?KN.has(e.toLowerCase()):Wl.some(n=>n===e),GC=["*"],lo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...GC]}),pa=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var ui=/^[a-f0-9-]{36}$/,tA="Anyray",ch=4,hi=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],mi=["deploymentMode","awaitingSignIn"],nA=[...hi,...mi,"configLibrary","_meta.json"],vn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),dt=e=>structuredClone(e),pi=async e=>{try{return await Gl(e),!0}catch{return!1}},n$=async e=>{try{let t=await ZN(eA(e)),n=e$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},r$=async e=>{try{return await Gl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":n$(e)}},an=(e={})=>{let t=(e.home??qN)(),n=(e.username??(()=>QN().username))(),r=Bt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Bt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Bt(r,"configLibrary"),meta:Bt(r,"configLibrary","_meta.json"),appConfig:Bt(r,"claude_desktop_config.json"),helper:Bt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Bt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},jl=()=>{let e=qC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},rA=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],o$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...rA(t)]}},lh=(e="json")=>{let t=pn(rA(e)),n=jC(t.command),r=jC(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:le()&&(!o||r!==n)}},a$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,dh=e=>[e.command,...e.args].map(a$).join(" "),s$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ha(e.command))throw new Error("the credential helper executable is not absolute")},oA=(e,t)=>{s$(e);let n=Vl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!ha(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},aA=e=>(oA(e,"--json"),`#!/bin/sh
|
|
210
|
-
exec ${
|
|
209
|
+
`).filter(d=>d.trim().length>0),i=kN(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 CN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await bN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as EN}from"node:crypto";import{promises as Gn}from"node:fs";import{homedir as xN,platform as IN}from"node:os";import{join as xt}from"node:path";var UC=448,jn="local_",RN="local-agent-mode-sessions",rh="-3p",ON="cowork_account_settings.json",co=(e={})=>{let t=(e.home??xN)(),n=e.runtimePlatform??IN(),r=e.env??process.env;if(n==="darwin")return xt(t,"Library","Application Support",`Claude${rh}`);if(n==="win32"){let o=r.LOCALAPPDATA??xt(t,"AppData","Local");return xt(o,`Claude${rh}`)}return null},ii=(e={})=>{let t=co(e);return t?t.slice(0,-rh.length):null},oh=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)}`},Fl=async e=>{let t=xt(e,RN),n;try{n=(await Gn.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 Gn.readdir(xt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=xt(t,o,s);try{await Gn.access(xt(i,ON)),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]}},ah=async e=>{try{let t=await Gn.readdir(e);return new Set(t.filter(n=>n.startsWith(jn)&&n.endsWith(".json")).map(n=>n.slice(jn.length,-5)))}catch{return new Set}},da=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),_N=async(e,t)=>{let n=`${jn}${t.sessionId}`,r=xt(e,n),o=xt(r,"outputs"),a=xt(r,".claude"),s=xt(a,"projects",oh(o));await Gn.mkdir(o,{recursive:!0,mode:UC}),await Gn.mkdir(s,{recursive:!0,mode:UC});let i=xt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${EN()}`;await Gn.copyFile(t.transcriptPath,c),await Gn.chmod(c,384),await Gn.rename(c,i);let l=t.createdAt??Date.now();await J(xt(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})},FC=async(e,t)=>{let n=await ah(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!da(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await _N(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as ua}from"node:fs";import{homedir as PN}from"node:os";import{dirname as TN,join as ci}from"node:path";var DN=448,LN=["Documents","Claude","Projects"],NN="spaces.json",$N=(e={})=>ci((e.home??PN)(),...LN),MN=async e=>{try{let t=JSON.parse(await ua.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}}},UN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},sh=async e=>{try{return await ua.access(e),!0}catch{return!1}},FN=async(e,t,n)=>{let r=ci(t,UN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await sh(r)?o:r;return a===o&&await sh(o)?null:(await ua.mkdir(TN(a),{recursive:!0}),await ua.cp(e,a,{recursive:!0}),a)},BN=async e=>{try{let t=(await ua.readFile(ci(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},BC=async e=>{let t=$N({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=ci(e.storageDir,NN),{spaces:a,readable:s}=await MN(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=ci(e.stagedProjectsDir,l.dirName);try{if(!await sh(d)){n.failed+=1;continue}let u=await FN(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await BN(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 ua.mkdir(e.storageDir,{recursive:!0,mode:DN}),await J(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as GN}from"node:crypto";import{execFile as jN,spawnSync as qC}from"node:child_process";import{constants as zC}from"node:fs";import{access as jl,chmod as VN,mkdir as YN,readdir as ZN,readFile as ch,rename as JN,rm as fa,stat as QC,writeFile as XN}from"node:fs/promises";import{homedir as qN,platform as zN,userInfo as QN}from"node:os";import{basename as e$,dirname as eA,isAbsolute as ha,join as Bt,resolve as jC}from"node:path";import{isDeepStrictEqual as di,promisify as t$}from"node:util";var li="__anyray-claude-desktop-credential";var Bl=["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>`."],Wl=["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."],WC="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 Hl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],HC=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],WN=new Set(HC),HN=new Set(HC.map(e=>e.toLowerCase())),KN=new Set(Hl.map(e=>e.toLowerCase())),Kl=(e,t=!1)=>(t?HN:WN).has(t?e.toLowerCase():e),KC=(e,t=!1)=>t?KN.has(e.toLowerCase()):Hl.some(n=>n===e),GC=["*"],lo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...GC]}),pa=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var ui=/^[a-f0-9-]{36}$/,tA="Anyray",lh=4,hi=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],mi=["deploymentMode","awaitingSignIn"],nA=[...hi,...mi,"configLibrary","_meta.json"],vn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),dt=e=>structuredClone(e),pi=async e=>{try{return await jl(e),!0}catch{return!1}},n$=async e=>{try{let t=await ZN(eA(e)),n=e$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},r$=async e=>{try{return await jl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":n$(e)}},an=(e={})=>{let t=(e.home??qN)(),n=(e.username??(()=>QN().username))(),r=Bt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Bt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Bt(r,"configLibrary"),meta:Bt(r,"configLibrary","_meta.json"),appConfig:Bt(r,"claude_desktop_config.json"),helper:Bt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Bt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Vl=()=>{let e=qC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},rA=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],o$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...rA(t)]}},dh=(e="json")=>{let t=pn(rA(e)),n=jC(t.command),r=jC(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:le()&&(!o||r!==n)}},a$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,uh=e=>[e.command,...e.args].map(a$).join(" "),s$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ha(e.command))throw new Error("the credential helper executable is not absolute")},oA=(e,t)=>{s$(e);let n=Yl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!ha(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},aA=e=>(oA(e,"--json"),`#!/bin/sh
|
|
210
|
+
exec ${uh(e)}
|
|
211
211
|
`),i$=`#!/bin/sh
|
|
212
|
-
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,sA=e=>{oA(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),li]};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 ${
|
|
213
|
-
`)},c$=e=>e.args.at(-1)==="--passthrough-headers"?sA(e):aA(e),
|
|
212
|
+
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,sA=e=>{oA(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),li]};return["#!/bin/sh","# Anyray subscription pass-through credential helper v2 for Claude Desktop.","# The durable credential runtime reads and validates the Keychain JSON,","# combines it with Anyray headers, and writes one credential response.",`exec ${uh(t)}`,""].join(`
|
|
213
|
+
`)},c$=e=>e.args.at(-1)==="--passthrough-headers"?sA(e):aA(e),Yl=e=>/[\\/](node|node\.exe)$/i.test(e),ph=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++}},l$=e=>{let t=`#!/bin/sh
|
|
214
214
|
exec `;if(!e.startsWith(t)||!e.endsWith(`
|
|
215
215
|
`))return;let n=e.slice(t.length,-1);if(n.includes(`
|
|
216
|
-
`)||n.includes("\r"))return;let r=
|
|
217
|
-
# Anyray subscription pass-through credential helper`,p$=e=>{let t=
|
|
218
|
-
`)},f$=e=>{if(!e.startsWith(u$))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=
|
|
219
|
-
`,384)},Sn=async e=>{if(!await pi(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await
|
|
220
|
-
`,384)},fi=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!ui.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(!vn(o)||typeof o.id!="string"||!ui.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},E$=async(e,t,n)=>{let r=await Sn(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:dt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[dt(t.metaEntry)]}}}let c=fi(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!di(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:dt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...dt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=fi(r.value);let c=Bt(e.library,`${o}.json`);if(!await pi(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=dt(r.value.entries)}let s=n();if(!ui.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await pi(Bt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:tA};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?dt(r.value):{},appliedId:s,entries:[...a,i]}}},I$=(e,t)=>{let n=lo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},lA=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),x$=async(e,t,n,r,o,a,s)=>{let i=lA(),c=Object.fromEntries(hi.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(mi.map(d=>[d,{original:s?.deployment[d].original??cA(r.value,d),lastWritten:i[d]}]));return{version:ch,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??dt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await yi(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Kl=e=>({status:"manual",messages:[e]}),R$=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}`)]}},O$=t$(jN),_$=new Set(Wl),P$=async e=>{try{let{stdout:t}=await O$("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return vn(n)?Object.keys(n):void 0}catch{return}},uo=async(e,t={})=>{let n=t.readManagedPolicyKeys??P$;for(let r of e.managedPolicies){let o=await r$(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=>Hl(i)&&!_$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},hh=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.`},mh=e=>(e.platform??zN)()==="darwin",dA=async(e,t,n={})=>{if(!mh(n))return Kl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??jl)()&&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=an(n),a=await uo(o,n);if(a&&r.push({audience:"admin",message:hh(a)}),r.length>0)return R$(r);let s=!1,i=!1,c=[o.journal];try{let l=X(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=o$((n.credentialCommand??(()=>lh(d)))(),d),f=c$(u),p=await fh(o),h=await yi(o.helper);if(p&&h.present&&h.content!==p.helper.lastWritten&&h.content!==p.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!p&&h.present&&h.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let m=await E$(o,p,n.randomUUID??GN),w=Bt(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await Sn(w),y=await Sn(o.appConfig),b=I$(e,o.helper),A=await x$(o,m,g,y,f,b,p);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${m.configId} for ${e.anthropicBaseUrl}, activate it in third-party mode, and install a ${l?"subscription pass-through":"dynamic API-billed"} credential helper at ${o.helper}.`]};s=!0,await JC(o.journal,A),i=!0,await Yl(o.helper,f,448),A.helper.previousWritten!==void 0&&(delete A.helper.previousWritten,await JC(o.journal,A));let v=dt(g.value);for(let C of hi)sh(v,C,b[C]);await Vn(w,v),m.metaToWrite&&await Vn(o.meta,m.metaToWrite);let E=dt(y.value),I=lA();for(let C of mi)sh(E,C,I[C]);return await Vn(o.appConfig,E),{status:"configured",changedFiles:[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig],messages:[`Configured Claude Desktop's native local gateway profile \u2192 ${e.anthropicBaseUrl}.`,l?`Installed a subscription pass-through credential helper at ${o.helper}; the helper reads your Claude Code subscription token on demand and no credential is stored in Claude's config.`:`Installed a dynamic credential helper at ${o.helper}; no gateway key is stored in Claude's config.`,l?"Claude Desktop Gateway requests now ride your Claude subscription through Anyray for content-free metering and optimization. Stay signed in to Claude Code so the token remains available.":"Claude Desktop uses its API-billed third-party inference lane; its first-party subscription remains separate.","Fully quit and reopen Claude Desktop to load the change.",...Fl]}}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.`]}:Kl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},XC=(e,t,n,r)=>{let o=dt(e);for(let a of n){let s=t[a];di(cA(e,a),s.lastWritten)?sh(o,a,s.original):r.push(a)}return o},uA=async(e,t={})=>{if(!mh(t))return{status:"not-found",messages:[]};if((t.appRunning??jl)())return Kl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=an(t);try{let r=await fh(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Bt(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 Sn(o),i=s.value;s.present&&(i=XC(s.value,r.config,hi,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await Sn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=fi(l.value),m=dt(l.value.entries),w=m.findIndex(b=>b.id===r.configId),g=w>=0?m[w]:void 0,y=g!==void 0&&di(g,r.metaEntry);if(g!==void 0&&!y&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=dt(l.value),h===r.configId){let b=r.originalAppliedId;b&&m.some(A=>A.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&y?(m.splice(w,1),d.entries=m):c&&g===void 0&&(d.entries=m)}else{let b=di(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(y&&m.splice(w,1),d={...dt(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await fa(o,{force:!0}):await Vn(o,i)),l.present&&(u?await fa(n.meta,{force:!0}):di(l.value,d)||await Vn(n.meta,d));let f=await Sn(n.appConfig);if(f.present){let h=XC(f.value,r.deployment,mi,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await fa(n.appConfig,{force:!0}):await Vn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await yi(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Yl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await fa(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await fa(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?[]:Bl]}}catch(r){return Kl(`Could not safely revert Claude Desktop (${r instanceof Error?r.message:String(r)}). Existing config was left in place where ownership could not be proven.`)}},yh=async(e,t={})=>{if(!mh(t))return!1;let n=an(t);if(await uo(n,t))return!1;try{let r=await Sn(n.meta);if(!r.present)return!1;let o=fi(r.value),a=await Sn(Bt(n.library,`${o}.json`)),s=await Sn(n.appConfig);if(!a.present||!s.present)return!1;await Gl(n.helper,zC.X_OK);let i=Je(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}},pA=async(e={})=>{try{let t=an(e),n=await yi(t.helper);if(!n.present||typeof n.content!="string")return;let r=iA(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},fA=async(e,t={})=>{if(!await yh(e,t))return!1;let n=an(t);try{let r=await fh(n);if(!r)return!1;let o=await Sn(n.meta);if(!o.present||fi(o.value)!==r.configId)return!1;let a=await yi(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=iA(a.content??"");return s?await(t.helperLauncherAvailable??m$)(s):!1}catch{return!1}};import{createHash as OA,randomUUID as _A}from"node:crypto";import{spawn as T$,spawnSync as D$}from"node:child_process";import{link as vh,mkdir as gh,open as PA,readFile as wh,readdir as TA,rename as DA,rm as sn,stat as LA}from"node:fs/promises";import{homedir as Sh}from"node:os";import{basename as NA,dirname as wi,join as Ca,win32 as L$}from"node:path";import{isDeepStrictEqual as ma}from"node:util";var _e="HKCU\\SOFTWARE\\Policies\\Claude",gi="HKLM\\SOFTWARE\\Policies\\Claude",ql=5,Aa="inferenceGatewayApiKey",$e=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",Aa],hA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",Aa],mA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",Aa],yA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",Aa],$A="Managed by anyray-connect; dynamic credential only.",N$=e=>/^[A-Za-z]:[\\/]/.test(e)&&L$.isAbsolute(e),gA=e=>{if(!N$(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)},MA=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!gA(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&&!gA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},Eh=(e={})=>Ca((e.home??Sh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),$$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},M$=e=>(MA(e),["@echo off",`REM ${$A}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map($$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
216
|
+
`)||n.includes("\r"))return;let r=ph(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Yl(o);if(!ha(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!ha(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return aA(i)===e?i:void 0}catch{return}},d$=e=>{if(!e.startsWith(i$))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=ph(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==li)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return sA(a)===e?a:void 0}catch{return}},u$=`#!/bin/sh
|
|
217
|
+
# Anyray subscription pass-through credential helper`,p$=e=>{let t=Yl(e.command);if(!(!ha(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!ha(e.args[0]):e.args.length!==2)))return["#!/bin/sh","# Anyray subscription pass-through credential helper for Claude Desktop.","# Reads the Claude subscription token from the login keychain at request","# time and wraps it with Anyray pass-through headers. connect never stores","# the token; only this on-machine helper reads it.","set -eu",`headers=$(${uh(e)})`,'if [ -z "${headers}" ]; then'," echo 'Anyray: could not resolve gateway headers; is this machine enrolled? Run: anyray-connect' >&2"," exit 1","fi","token=$(security find-generic-password -s 'Claude Code-credentials' -w 2>/dev/null | grep -oE 'sk-ant-oat[0-9A-Za-z._-]+' | head -n1)",'if [ -z "${token}" ]; then'," echo 'Anyray: no Claude subscription sign-in found; run: claude' >&2"," exit 1","fi",'printf \'{"token":"%s","headers":%s}\\n\' "${token}" "${headers}"',""].join(`
|
|
218
|
+
`)},f$=e=>{if(!e.startsWith(u$))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=ph(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return p$(a)===e?a:void 0},iA=e=>l$(e)??d$(e)??f$(e),h$=async()=>{let e=qC("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},m$=async e=>{let t=[e.command,...Yl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>QC(r)))).every(r=>r.isFile())?(await jl(e.command,zC.X_OK),!0):!1}catch{return!1}},y$=0,Zl=async(e,t,n)=>{await YN(eA(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${y$++}.tmp`;try{await XN(r,t,{mode:n}),await VN(r,n),await JN(r,e)}catch(o){throw await fa(r,{force:!0}).catch(()=>{}),o}},Vn=async(e,t)=>{await Zl(e,`${JSON.stringify(t,null,2)}
|
|
219
|
+
`,384)},Sn=async e=>{if(!await pi(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await ch(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!vn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},yi=async e=>{if(!await pi(e))return{present:!1};let t=await QC(e);return{present:!0,content:await ch(e,"utf-8"),mode:t.mode&511}},cA=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:dt(e[t])}:{present:!1},ih=(e,t,n)=>{n.present?e[t]=dt(n.value):delete e[t]},VC=e=>vn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),g$=e=>vn(e)&&VC(e.original)&&VC(e.lastWritten),w$=e=>vn(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),YC=(e,t)=>vn(e)&&t.every(n=>g$(e[n])),b$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],k$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],fh=(e,t,n,r)=>!(!vn(e)||e.version!==n||typeof e.configId!="string"||!ui.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!ui.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!vn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==tA||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!YC(e.config,r)||r.some(o=>e.config[o].original.present)||!YC(e.deployment,mi)||!vn(e.helper)||e.helper.path!==t.helper||!w$(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),C$=(e,t)=>fh(e,t,lh,hi),A$=(e,t)=>fh(e,t,2,b$),v$=(e,t)=>fh(e,t,3,k$),S$=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),ZC=e=>({...e,version:lh,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),hh=async e=>{if(!await pi(e.journal))return;let t;try{t=JSON.parse(await ch(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(C$(t,e))return t;if(v$(t,e))return ZC(t);if(A$(t,e))return ZC(S$(t));throw new Error(`${e.journal} is not a valid ownership journal`)},JC=async(e,t)=>{await Zl(e,`${JSON.stringify(t,null,2)}
|
|
220
|
+
`,384)},fi=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!ui.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(!vn(o)||typeof o.id!="string"||!ui.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},E$=async(e,t,n)=>{let r=await Sn(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:dt(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[dt(t.metaEntry)]}}}let c=fi(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!di(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:dt(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...dt(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=fi(r.value);let c=Bt(e.library,`${o}.json`);if(!await pi(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=dt(r.value.entries)}let s=n();if(!ui.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await pi(Bt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:tA};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?dt(r.value):{},appliedId:s,entries:[...a,i]}}},x$=(e,t)=>{let n=lo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},lA=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),I$=async(e,t,n,r,o,a,s)=>{let i=lA(),c=Object.fromEntries(hi.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(mi.map(d=>[d,{original:s?.deployment[d].original??cA(r.value,d),lastWritten:i[d]}]));return{version:lh,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??dt(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await yi(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Gl=e=>({status:"manual",messages:[e]}),R$=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}`)]}},O$=t$(jN),_$=new Set(Hl),P$=async e=>{try{let{stdout:t}=await O$("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return vn(n)?Object.keys(n):void 0}catch{return}},uo=async(e,t={})=>{let n=t.readManagedPolicyKeys??P$;for(let r of e.managedPolicies){let o=await r$(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=>Kl(i)&&!_$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},mh=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.`},yh=e=>(e.platform??zN)()==="darwin",dA=async(e,t,n={})=>{if(!yh(n))return Gl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Vl)()&&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=an(n),a=await uo(o,n);if(a&&r.push({audience:"admin",message:mh(a)}),r.length>0)return R$(r);let s=!1,i=!1,c=[o.journal];try{let l=X(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=o$((n.credentialCommand??(()=>dh(d)))(),d),f=c$(u),p=await hh(o),h=await yi(o.helper);if(p&&h.present&&h.content!==p.helper.lastWritten&&h.content!==p.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!p&&h.present&&h.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let m=await E$(o,p,n.randomUUID??GN),w=Bt(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await Sn(w),y=await Sn(o.appConfig),b=x$(e,o.helper),A=await I$(o,m,g,y,f,b,p);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${m.configId} for ${e.anthropicBaseUrl}, activate it in third-party mode, and install a ${l?"subscription pass-through":"dynamic API-billed"} credential helper at ${o.helper}.`]};s=!0,await JC(o.journal,A),i=!0,await Zl(o.helper,f,448),A.helper.previousWritten!==void 0&&(delete A.helper.previousWritten,await JC(o.journal,A));let v=dt(g.value);for(let C of hi)ih(v,C,b[C]);await Vn(w,v),m.metaToWrite&&await Vn(o.meta,m.metaToWrite);let E=dt(y.value),x=lA();for(let C of mi)ih(E,C,x[C]);return await Vn(o.appConfig,E),{status:"configured",changedFiles:[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig],messages:[`Configured Claude Desktop's native local gateway profile \u2192 ${e.anthropicBaseUrl}.`,l?`Installed a subscription pass-through credential helper at ${o.helper}; the helper reads your Claude Code subscription token on demand and no credential is stored in Claude's config.`:`Installed a dynamic credential helper at ${o.helper}; no gateway key is stored in Claude's config.`,l?"Claude Desktop Gateway requests now ride your Claude subscription through Anyray for content-free metering and optimization. Stay signed in to Claude Code so the token remains available.":"Claude Desktop uses its API-billed third-party inference lane; its first-party subscription remains separate.","Fully quit and reopen Claude Desktop to load the change.",...Bl]}}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.`]}:Gl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},XC=(e,t,n,r)=>{let o=dt(e);for(let a of n){let s=t[a];di(cA(e,a),s.lastWritten)?ih(o,a,s.original):r.push(a)}return o},uA=async(e,t={})=>{if(!yh(t))return{status:"not-found",messages:[]};if((t.appRunning??Vl)())return Gl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=an(t);try{let r=await hh(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Bt(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 Sn(o),i=s.value;s.present&&(i=XC(s.value,r.config,hi,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await Sn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=fi(l.value),m=dt(l.value.entries),w=m.findIndex(b=>b.id===r.configId),g=w>=0?m[w]:void 0,y=g!==void 0&&di(g,r.metaEntry);if(g!==void 0&&!y&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=dt(l.value),h===r.configId){let b=r.originalAppliedId;b&&m.some(A=>A.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&y?(m.splice(w,1),d.entries=m):c&&g===void 0&&(d.entries=m)}else{let b=di(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(y&&m.splice(w,1),d={...dt(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await fa(o,{force:!0}):await Vn(o,i)),l.present&&(u?await fa(n.meta,{force:!0}):di(l.value,d)||await Vn(n.meta,d));let f=await Sn(n.appConfig);if(f.present){let h=XC(f.value,r.deployment,mi,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await fa(n.appConfig,{force:!0}):await Vn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await yi(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Zl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await fa(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await fa(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?[]:Wl]}}catch(r){return Gl(`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.`)}},gh=async(e,t={})=>{if(!yh(t))return!1;let n=an(t);if(await uo(n,t))return!1;try{let r=await Sn(n.meta);if(!r.present)return!1;let o=fi(r.value),a=await Sn(Bt(n.library,`${o}.json`)),s=await Sn(n.appConfig);if(!a.present||!s.present)return!1;await jl(n.helper,zC.X_OK);let i=Je(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}},pA=async(e={})=>{try{let t=an(e),n=await yi(t.helper);if(!n.present||typeof n.content!="string")return;let r=iA(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},fA=async(e,t={})=>{if(!await gh(e,t))return!1;let n=an(t);try{let r=await hh(n);if(!r)return!1;let o=await Sn(n.meta);if(!o.present||fi(o.value)!==r.configId)return!1;let a=await yi(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=iA(a.content??"");return s?await(t.helperLauncherAvailable??m$)(s):!1}catch{return!1}};import{createHash as OA,randomUUID as _A}from"node:crypto";import{spawn as T$,spawnSync as D$}from"node:child_process";import{link as Sh,mkdir as wh,open as PA,readFile as bh,readdir as TA,rename as DA,rm as sn,stat as LA}from"node:fs/promises";import{homedir as Eh}from"node:os";import{basename as NA,dirname as wi,join as Ca,win32 as L$}from"node:path";import{isDeepStrictEqual as ma}from"node:util";var _e="HKCU\\SOFTWARE\\Policies\\Claude",gi="HKLM\\SOFTWARE\\Policies\\Claude",zl=5,Aa="inferenceGatewayApiKey",$e=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",Aa],hA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",Aa],mA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",Aa],yA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",Aa],$A="Managed by anyray-connect; dynamic credential only.",N$=e=>/^[A-Za-z]:[\\/]/.test(e)&&L$.isAbsolute(e),gA=e=>{if(!N$(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)},MA=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!gA(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&&!gA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},xh=(e={})=>Ca((e.home??Eh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),$$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},M$=e=>(MA(e),["@echo off",`REM ${$A}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map($$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
221
221
|
`)),U$=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},UA=e=>{let t=e.split(`\r
|
|
222
|
-
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${$A}`||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(U$);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return MA(s),s}catch{return}},F$=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>LA(r)))).every(r=>r.isFile())}catch{return!1}},B$=async(e,t)=>{let n=UA(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??F$)(n)}catch{return!1}},
|
|
222
|
+
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${$A}`||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(U$);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return MA(s),s}catch{return}},F$=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>LA(r)))).every(r=>r.isFile())}catch{return!1}},B$=async(e,t)=>{let n=UA(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??F$)(n)}catch{return!1}},kh=e=>({sha256:po(e),content:e}),wA=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Wt(t,["sha256","content"])&&Z$(t.sha256)&&typeof t.content=="string"&&po(t.content)===t.sha256&&UA(t.content)!==void 0},Ih=()=>{let e=D$("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??"")},W$=async(e,t)=>{await wh(wi(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await PA(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await Sh(n,e)}finally{await sn(n,{force:!0}).catch(()=>{})}},H$=e=>`${NA(e)}.anyray-old-`,K$=e=>`${e}.anyray-old-${process.pid}-${_A()}`,FA=async(e,t)=>{try{await Sh(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await sn(t,{force:!0}),!0},Xl=async(e,t,n,r,o)=>{let a=K$(e),s=n===void 0?void 0:po(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${_A()}`,c=!1;try{if(i&&n!==void 0){let d=await PA(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 DA(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ba(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await Sh(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await ka(e)!==s))throw new Error("credential helper publication verification failed");await sn(a,{force:!0}),c=!1}catch(l){throw c&&await FA(e,a).catch(()=>!1),l}finally{i&&await sn(i,{force:!0}).catch(()=>{})}},Ch=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,G$=String.raw`
|
|
223
223
|
$ErrorActionPreference = 'Stop'
|
|
224
224
|
try {
|
|
225
225
|
$request = ConvertFrom-Json ([Console]::In.ReadToEnd())
|
|
@@ -288,29 +288,29 @@ try {
|
|
|
288
288
|
exit 5
|
|
289
289
|
} catch {
|
|
290
290
|
exit 6
|
|
291
|
-
}`,Zn=async e=>new Promise((t,n)=>{let r=T$("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",G$],{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(
|
|
292
|
-
`)}catch(a){if(a.code!=="EEXIST")throw await sn(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await
|
|
293
|
-
`;t.writeJournalFile?await t.writeJournalFile(n,r):await pe(n,r)},nM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,rM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),oM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),aM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),sM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===aM(t).toUpperCase(),xA=(e,t,n,r,o)=>{let a=$e.find(i=>i.toLowerCase()===t.toLowerCase());if(!a)return!1;let s=n==="String"?"REG_SZ":n==="ExpandString"?"REG_EXPAND_SZ":n;if(s!=="REG_SZ"&&s!=="REG_EXPAND_SZ"){if(o)throw new Error("an owned Claude policy value has an unsupported type");return!1}if(e[a].present)throw new Error("a Claude policy value was returned more than once");return e[a]={present:!0,type:s,value:r},!0},iM=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,cM=(e,t)=>{if(!Hl(e,!0))return!1;let n=iM(t);if(oM.has(n))return!1;if(rM.has(n))return n==="REG_EXPAND_SZ"?!0:!KC(e,!0)},lM=(e,t)=>{let n=BA(),r=!1,o=!1,a=!1,s=t.toUpperCase()===gi.toUpperCase(),i=(l,d)=>{if(!s)return;let u=cM(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),xA(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||sM(d,t))continue;let u=nM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),xA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Yn=async(e,t=_e)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:BA(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return lM(n.stdout,t)},Ir=async e=>{let t=await Yn(e,gi);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...$e.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},Ph=e=>e.unparsed?`This machine may have a Claude policy under ${gi} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${gi} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${gi} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Ql=(e,t)=>pa(lo(e,t)),WA=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],dM=(e,t)=>{let n=Ql(e,t);return Object.fromEntries($e.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},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}}),pM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,Ch=e=>Object.fromEntries($e.map(t=>[t,Y$(t,e[t])])),RA=(e,t,n,r)=>({version:ql,registryKey:_e,keyExisted:e,lastWritten:Ch(t),helper:{path:n,lastWritten:bh(r)}}),fM=(e,t,n,r,o,a)=>({version:ql,registryKey:_e,keyExisted:e,lastWritten:Ch(t),pending:Ch(n),helper:{path:r,...o?{lastWritten:bh(o)}:{},pending:bh(a)}}),Ah=(e,t,n)=>ya(n,e.lastWritten[t])||e.pending!==void 0&&ya(n,e.pending[t]),ba=async e=>{try{let t=await wh(e,"utf8");return{content:t,sha256:po(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ka=async e=>(await ba(e))?.sha256,ga=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Xl=async(e,t)=>{let n=H$(e),r;try{r=await TA(wi(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>Ca(wi(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([ba(e),ba(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ga(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await FA(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ga(t,s.sha256)&&ga(t,i.sha256)){await sn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Th=async(e,t,n)=>(n.present?await e(WA(_e,t,n.value??"",n.type??"REG_SZ")):await e(["delete",_e,"/v",t,"/f"])).code===0,hM=async(e,t,n)=>{let r=!0,o=await Yn(e);for(let a of $e)if(!ma(o.values[a],t[a])){if(!ma(o.values[a],n[a])){r=!1;continue}await Th(e,a,t[a])||(r=!1),o=await Yn(e)}return r&&$e.every(a=>ma(o.values[a],t[a]))},et=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Ht(n)]}}),HA=async(e,t,n,r={})=>{if(!Ie(t))return et("A valid personal ark_ gateway key is required.",!1,r);let o=Eh(r),a;try{a=M$((r.credentialCommand??lh)())}catch{return et("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=po(a),i=r.runReg??Zn,c=Ht(r),l;if(!n.dryRun)try{l=await xh(r)}catch(m){return et(m instanceof wa?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; the registry was left unchanged.",!1,r)}let d,u,f,p,h=!1;try{let m=await Ir(i);if(m)return et(Ph(m),!1,r);let w=await _h(r,!n.dryRun);n.dryRun||await Xl(o,w);let g=await Yn(i),y=dM(e,o),b=await ba(o),A=b?.sha256,v=!1;if(d=w,u=g,f=y,w){let C=$e.find(x=>!Ah(w,x,g.values[x]));if(C)return et(`Claude's ${C} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(A!==void 0&&!ga(w,A))return et(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);v=pM(w)}else{if(A!==void 0&&A!==s)return et(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let C=g.foreignState||$e.some($=>g.values[$].present),x=$e.every($=>ma(g.values[$],y[$])),P=$e.every($=>ma(g.values[$],uM(e,t.trim())[$]));if(C&&!x&&!P)return et(`Existing Claude third-party-inference policy values under ${_e} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(v=P,x&&A===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${_e} into an owner-only journal without rewriting them.`]}:(await Zl(RA(g.keyPresent,y,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${_e} into the ownership journal.`]})}if(v){let C=!0;try{C=(r.appRunning??Ih)()}catch{}if(C)return et("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=fM(w?.keyExisted??g.keyPresent,g.values,y,o,b?.content,a);if(p=E,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${_e}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Zl(E,r),h=!0;for(let C of $e){let x=await Yn(i);if(!ya(x.values[C],E.lastWritten[C])&&!ya(x.values[C],E.pending[C]))throw new Error("registry value changed during apply");if(!ma(x.values[C],y[C])&&!await Th(i,C,y[C]))throw new Error("registry write failed")}let I=await Yn(i);if(!$e.every(C=>ya(I.values[C],E.pending[C])))throw new Error("registry verification failed");if(A!==s&&(A===void 0?await W$(o,a):await Jl(o,A,a,"apply",r)),await ka(o)!==s)throw new Error("credential helper verification failed");return await Zl(RA(E.keyExisted,y,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${_e}.`,`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.",...Fl]}}catch{if(!h||!u||!f||!p)return et("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Xl(o,p);let m=!0,w=await ba(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await Jl(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await ka(o)===p.helper.lastWritten.sha256):await Jl(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await hM(i,u.values,f))return d?await Zl(d,r):await sn(c,{force:!0}),et("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return et("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?.()}},KA=async(e,t={})=>{let n=t.runReg??Zn,r=Ht(t),o;if(!e.dryRun)try{o=await xh(t)}catch(a){return et(a instanceof wa?"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 _h(t,!e.dryRun);a&&!e.dryRun&&await Xl(a.helper.path,a);let s=await Yn(n);if(!a)return $e.filter(h=>s.values[h].present).length>0?et(`Claude policy values exist under ${_e}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=$e.filter(p=>s.values[p].present&&!Ah(a,p,s.values[p])),c=await ka(a.helper.path),l=c!==void 0&&!ga(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${_e}.`,`Would remove the Anyray-owned credential helper at ${a.helper.path}.`,...i.length||l?[`Would preserve changed values: ${[...i,...l?["credential helper"]:[]].join(", ")}.`]:[]]};let d=!1,u=new Set(i);for(let p of $e){let m=(await Yn(n)).values[p];if(m.present){if(!Ah(a,p,m)){u.add(p);continue}await Th(n,p,{present:!1})||(d=!0)}}let f=await ka(a.helper.path);if(f!==void 0)if(ga(a,f))try{await Jl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?et(`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 sn(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${_e}.`,"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?[]:Bl]})}catch{return et(`Could not safely inspect or revert ${_e}; no unproven value was removed.`,!1,t)}finally{await o?.()}},GA=async(e,t={})=>{let n=t.runReg??Zn;if(!await R(Ht(t)))return;let r;try{r=await xh(t);let o=await _h(t);if(o&&await Xl(o.helper.path,o),!o||o.pending||await Ir(n)!==void 0)return;let a=await Yn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Je(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&$e.every(l=>ya(a.values[l],o.lastWritten[l]))))return;let i=await ka(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 B$(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?.()}},jA=async(e,t={})=>await GA(e,t)!==void 0,VA=async(e,t={})=>await GA(e,t)==="dynamic";var va=(e=yM())=>e==="win32"?Ih:jl,Dh="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",td=async(e,t={})=>{let n=(t.profileRoot??co)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Dh};if((t.appRunning??va(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await YA.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 Ul(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 "+Dh}:{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??$C)();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=ed(t.stagingRoot??gM(),`anyray-history-${process.pid}-${mM()}`);try{let s=await(t.runImporter??MC)({binary:o,exportPath:e,configDir:ed(a,"config"),workDir:ed(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. "+Dh};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 FC(r.dir,s.conversations),c=await BC({stagedProjectsDir:ed(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 YA.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Rt}from"node:fs";import{homedir as FM}from"node:os";import{join as ln,sep as BM}from"node:path";import{isDeepStrictEqual as ad}from"node:util";import{constants as wM}from"node:fs";import{promises as G}from"node:fs";import{dirname as Sa,isAbsolute as Nh,join as ne,relative as nd,resolve as cn,sep as bi}from"node:path";import{randomUUID as sd}from"node:crypto";var En=448,ki=384,qA=448,bM=4,$h=3e4,zA=5e3,kM=10*6e4,Lh=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),ut=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"),QA=(e,t)=>{let n=nd(cn(e),cn(t));return n===""||!n.startsWith(`..${bi}`)&&n!==".."&&!Nh(n)},fo=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return ut(n)?{raw:t,value:n}:void 0}catch(t){return xt(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},xt=e=>e instanceof Error&&"code"in e,CM=e=>{try{return process.kill(e,0),!0}catch(t){return xt(t)&&t.code==="EPERM"}},ev=e=>e===0?"owner.json":`owner.${e}.json`,rd=async e=>{let t;try{t=await G.readdir(e)}catch{return}let r=t.map(d=>{if(d==="owner.json")return{name:d,generation:0};let u=/^owner\.(\d+)\.json$/.exec(d);if(!u)return;let f=Number(u[1]);return Number.isSafeInteger(f)&&f>0?{name:d,generation:f}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=ne(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));ut(d)&&typeof d.pid=="number"&&Number.isSafeInteger(d.pid)&&d.pid>0&&typeof d.nonce=="string"&&d.nonce.length>0&&(a=d.pid,s=d.nonce,typeof d.createdAt=="number"&&Number.isFinite(d.createdAt)&&d.createdAt>=0&&(i=d.createdAt))}catch{}let c=await G.stat(o).then(d=>d.mtimeMs),l=i!==void 0&&i<=Date.now()+6e4?i:c;return{generation:r.generation,pid:a,nonce:s,createdAtMs:l,mtimeMs:c}},tv=e=>{if(e.pid===void 0||!CM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>$h&&t-e.createdAtMs>kM},AM=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(Sa(t),{recursive:!0,mode:En});let n=sd(),r,o=!1;try{await G.mkdir(t,{mode:En}),o=!0}catch(i){if(!xt(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await rd(t);if(d){if(!tv(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=$h)return}let l=ne(t,ev(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
294
|
-
`,{flag:"wx",mode:ki}),r=l}catch(d){if(
|
|
295
|
-
`,{mode:ki,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},
|
|
296
|
-
`,{flag:"wx",mode:ki}),o=u}catch(f){if(
|
|
297
|
-
`)}},Fh=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),hv=async e=>{let t=[];for(let n of KM)t.push({lane:n,sources:await jM(e,n)});return t},mv=async(e={})=>{let t=(e.firstPartyRoot??(()=>ii()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([hv(t),Mh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Fh(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}},ho=async(e={})=>{let t=(e.home??FM)(),n=(e.firstPartyRoot??(()=>ii()))(),r=(e.thirdPartyRoot??(()=>co()))();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??va())())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([hv(n),Mh(n)]),s;if(e.account){let p=e.account;for(let w of o)w.sources=w.sources.filter(g=>g.account.startsWith(p));let h=a.accounts.filter(w=>w.startsWith(p));if(o.every(w=>w.sources.length===0)&&h.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${p}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let m=Fh(o);for(let w of h)m.add(w);if(m.size>1)return uv(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=Fh(o);for(let h of a.accounts)p.add(h);if(p.size>1)return uv(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 WM(r),l=await lv(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:s});if(l.sourceChanged)return{ok:!1,kind:"account-ambiguous",reason:"the previous Claude Desktop profile changed during migration and now holds local data for another account",remedy:`Re-run \`${i}\` so the account choice is made from a fresh snapshot.`};let d=[],u=[];for(let{lane:p,sources:h}of o){if(h.length===0){d.push(Uh(p));continue}let m=await VM(r,p);if("missing"in m){u.push({lane:p,reason:m.missing,waiting:h.reduce((w,g)=>w+g.ids.length,0)}),d.push(Uh(p));continue}d.push(await JM(p,h,m.dir,t))}if(!(d.some(p=>p.migrated>0||p.alreadyPresent>0)||l.outcomes.some(p=>p.migrated>0||p.alreadyPresent>0||p.conflicts>0))&&(u.length>0||l.blocked.length>0)){let p=u[0];return p?{ok:!1,kind:p.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:p.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${p.lane} store`:`Claude Desktop has no ${p.lane} store in its third-party profile yet`,remedy:Bh(p.reason,p.lane,i,c)}:{ok:!1,kind:"store-missing",reason:"Claude Desktop's third-party profile has no extension store yet",remedy:"Open Claude Desktop once after connecting it to Anyray, then fully quit it so the portable extensions can be copied safely."}}return{ok:!0,lanes:d,portableAssets:l.outcomes,...u.length>0?{blocked:u}:{},...l.blocked.length>0?{blockedAssets:l.blocked}:{},...l.ambiguous.length>0?{ambiguousAssets:l.ambiguous}:{},...l.retryable.length>0?{retryableAssets:l.retryable}:{}}};var qM=e=>[Ye(e)],yv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...qM(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await R(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var gv="1.21459.0",tU=eU(zM),nU=async e=>{try{let{stdout:t}=await tU("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},rU=async e=>{try{return await QM(e)}catch{return}},wv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",oU=["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."],Ea=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(bv??=kv({}),bv):kv(e),bv,kv=async e=>{let t=(e.home??vi)(),n=["/Applications/Claude.app",In(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??nU,o=e.readClaudeAppBundle??rU;for(let a of n){let s=await r(In(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${wv}`}),c=$l(s,gv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${gv} or newer.`);let l=await o(In(a,"Contents","Resources","app.asar"));return l?nA.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. ${wv}`}},ld="anyray",vv="--anyray-owner=claude-desktop-v1",dd=(e={})=>{let t=(e.platform??xr)(),n=(e.home??vi)();return t==="darwin"?an(e).appConfig:t==="win32"?In(process.env.APPDATA??In(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):In(n,".config","Claude","claude_desktop_config.json")},jh=(e={})=>In((e.home??vi)(),"Library","Application Support","Claude","claude_desktop_config.json"),Sv=()=>{let e=Ve("profile");return{command:e.command,args:[...e.args,vv]}},mo=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ev=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},aU=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),sU=e=>{if(!mo(e)||!Ev(e,["command","args"]))return!1;let t=Sv();return e.command===t.command&&aU(e.args,t.args)},iU=e=>mo(e)&&Array.isArray(e.args)&&e.args.at(-1)===vv,cU=e=>{if(!mo(e)||!Ev(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||je(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===cr&&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!je(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},lU=e=>e===void 0?"absent":sU(e)?"exact":iU(e)||cU(e)?"stale-owned":"foreign",He=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},yo=async e=>{let t=await R(e),n;try{n=await F(e)}catch{throw new He(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!mo(n.mcpServers))throw new He(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(mo(n.mcpServers)?n.mcpServers:void 0)?.[ld];return{path:e,fileExisted:t,json:n,entry:o,ownership:lU(o)}},ud=e=>{if(e.ownership==="foreign")throw new He(`MCP name conflict in ${e.path}: mcpServers.${ld} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},Iv=(e,t)=>{let n={...e},r=mo(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[ld]:r[ld]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Hh=async(e,t)=>{if(Wh(e.entry,t))return;let n=await yo(e.path);if(!Wh(n.entry,e.entry))throw new He(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Vn(e.path,Iv(n.json,t)),{reading:e,afterEntry:t}},Kh=async e=>{let t=await yo(e.reading.path);if(!Wh(t.entry,e.afterEntry))throw new He(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=Iv(t.json,e.reading.entry);await Vn(e.reading.path,n)},dU=async e=>{if(!le())throw new He(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Re()} is temporary); no inference setting was changed.`);let t=await yo(dd(e));ud(t);let n=jh(e),r=(e.platform??xr)()==="darwin"&&n!==t.path?await yo(n):void 0;return r&&ud(r),{active:t,...r?{legacy:r}:{}}},Cv=async e=>{let t=await yo(dd(e));ud(t);let n=jh(e),r=(e.platform??xr)()==="darwin"&&n!==t.path?await yo(n):void 0;return r&&ud(r),{active:t,...r?{legacy:r}:{}}},uU=async e=>{let t=[];try{let n=await Hh(e.active,Sv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Hh(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Kh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new He(`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 Kh(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new He(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},pU=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Hh(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Kh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new He(`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)},Av=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)."]},fU={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},pd="claude-desktop",Gh="migrate",xv=new Set(["app-running","store-missing"]),hU={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},mU={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"}},yU="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",Rv=e=>{let t=(e.platform??xr)(),n=e.home??vi;return{home:n,appRunning:e.appRunning??va(t),firstPartyRoot:()=>ii({home:n,runtimePlatform:t}),thirdPartyRoot:()=>co({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Ov=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=hU[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.`:"")},_v=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=mU[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.`:"")},Ai=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=Rv(e),r=await(e.pendingDesktopMigrationCount??mv)(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??ho)(n);if(a.ok){let c=Ov(a.lanes),l=_v(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(a.blocked??[]).filter(y=>y.reason!=="ambiguous"),p=a.blockedAssets??[],h=a.retryableAssets??[];if(f.length===0&&p.length===0&&h.length===0)return[c,l,u].filter(y=>!!y);if(t.preservePendingOp)return[c,l,u].filter(y=>!!y);await Ms(pd,Gh);let m=f.reduce((y,b)=>y+b.waiting,0),w=[m>0?`${m} more session${m===1?"":"s"}`:"",p.length>0?`${p.length} extension ${p.length===1?"store":"stores"}`:""].filter(Boolean),g=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...h.length>0?[`Queued: ${h.length} portable configuration ${h.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...g]}if(!xv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
298
|
-
${a.remedy}`];if(t.preservePendingOp)return[];await Ms(pd,Gh);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."]}},gU=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await gr(pd),[]}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."]}},wU=e=>yv({id:pd,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??xr)(),n=(e.home??vi)();return t==="darwin"?["/Applications/Claude.app",In(n,"Applications","Claude.app")]:t==="win32"?[In(process.env.LOCALAPPDATA??In(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>X(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:",...Av(t)]:["Claude desktop org/API lane:",...Av(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`."]}),bU=(e={})=>{let t=wU(e),n=()=>(e.platform??xr)()==="darwin",r=()=>(e.platform??xr)()==="win32",o=(s,i)=>n()?dA(s,i,e):HA(s,s.clientKey??"",i,e),a=s=>n()?uA(s,e):KA(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??va((e.platform??xr)()))(),quitTarget:fU,needsTarget:()=>!1,async complete(s){if(s!==Gh)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??ho)(Rv(e));if(i.ok){let c=Ov(i.lanes),l=_v(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let f=(i.blocked??[]).filter(m=>m.reason!=="ambiguous"),p=i.blockedAssets??[],h=i.retryableAssets??[];return f.length>0||p.length>0||h.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...f.length>0||p.length>0?["Still waiting on Claude Desktop to create the remaining third-party stores, which appear the first time those parts of the app are opened."]:[],...h.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(m=>!!m):["No portable Claude Desktop data was left to bring across."]}}return xv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?fA(s,e):r()?VA(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=an(e),p=await uo(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[hh(p),...await Ai(e,i)]}}if(r()){let f;try{f=await Ir(e.runReg??Zn)}catch{return{status:"manual",manualAudience:"admin",messages:[yU,...await Ai(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[Ph(f),...await Ai(e,i)]}}if(r()&&X(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 Ea(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await dU(e)}catch(f){let p=f instanceof He?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof He?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 Ai(e,i)]}}let d;try{d=await uU(c)}catch(f){let p=f instanceof He?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof He?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 Ai(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?oU:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=dd(e),c=await gU(s),l=m=>c.length===0?m:{...m,messages:[...m.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await Cv(e)}catch(m){return l({status:"manual",messages:[m instanceof He?m.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let m=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...m&&m.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${m.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let m=r()?Ht(e):void 0;if(!(m!==void 0&&f.changedFiles?.includes(m)===!0&&!await R(m)))return l(f)}let p;try{p=await pU(await Cv(e))}catch(m){let w=m instanceof He?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof He?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await se(i);let h=jh(e);return n()&&h!==i&&await se(h),l({...f,messages:[...f.messages,...p.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...p])]})},async mcpStatus(){if(!le())return{registered:!1,command:null};try{let s=await yo(dd(e));return s.ownership!=="exact"||!mo(s.entry)?{registered:!1,command:null}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null}}},async pointsAt(s){return n()?(await Ea(e)).supported?yh(s,e):!1:r()?jA(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await Ea(e)).supported)return["unknown"];let s=await pA(e);return s?[s]:["unknown"]}if(r())return await R(Ht(e))?await Ir(e.runReg??Zn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=an(e);return!await R(s.journal)||await uo(s,e)?!1:(await Ea(e)).supported}return r()&&await R(Ht(e))?!await Ir(e.runReg??Zn):!1}catch{return!1}}}},Pv=bU();import{homedir as YU}from"node:os";import{join as ZU}from"node:path";import{rm as Cd}from"node:fs/promises";import{constants as Tv,accessSync as kU,statSync as CU}from"node:fs";import{platform as Vh}from"node:os";import{delimiter as AU,posix as vU,resolve as SU,win32 as EU}from"node:path";var IU="0.59.0",xU="1.1.4",Jn="Anyray \xB7 Claude",Xn="Anyray \xB7 Codex",fd="__anyray-acp-agent",Dv=(e,t,n)=>{let{command:r,args:o}=pn([fd,e,t,n]);return{command:r,args:o,env:{}}},hd=(e=Vh())=>e==="win32"?"npx.cmd":"npx",md=(e=process.env.PATH,t=Vh())=>{if(!e)return;let n=hd(t);for(let r of e.split(AU)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=SU(o,n);try{if(!CU(a).isFile())continue;return kU(a,t==="win32"?Tv.F_OK:Tv.X_OK),a}catch{}}},yd=(e,t=Vh())=>{let n=t==="win32"?EU:vU;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==hd(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},RU="https://chatgpt.com/backend-api/codex",OU="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Lv="ANYRAY_ACP_CODEX_AUTHORIZATION",Nv="ANYRAY_ACP_CODEX_CLIENT_KEY",$v="ANYRAY_ACP_CODEX_METADATA",Mv=e=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),_U=(e,t={})=>{let n=X(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":RU,"x-anyray-forward-headers":OU}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Nv}:{}}:{Authorization:Lv};return Mv(e)&&(o["x-anyray-metadata"]=$v),{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}}}:{}}},PU=e=>{let t=X(e,"openai"),n=Mv(e);return{...t?e.clientKey?{[Nv]:e.clientKey}:{}:{[Lv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[$v]:n}:{}}},Uv=(e,t=hd(),n={})=>({[Jn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${IU}`],env:fn(e).env},[Xn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${xU}`],env:{CODEX_CONFIG:JSON.stringify(_U(e,n)),...PU(e)}}}),Si=(e=hd(),t="jetbrains")=>({[Jn]:Dv("claude",e,t),[Xn]:Dv("codex",e,t)}),go=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as TU}from"node:zlib";import{open as DU,readFile as qh,readdir as kd}from"node:fs/promises";import{dirname as Fv,join as ue}from"node:path";import{homedir as Kv,platform as zh}from"node:os";var wd="2025.3.2",Ia="253.30387.147",Ei="com.intellij.ml.llm",Yh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),LU=1e4,NU=256*1024*1024,$U=16*1024*1024,Zh=1024*1024,Jh=22,MU=Jh+65535,Xh=$l,UU=()=>{let e=Kv(),t=ue(e,".cache","JetBrains","RemoteDev");switch(zh()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:ue(e,"Applications"),layout:"app-bundles"},{path:ue(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:ue(process.env.LOCALAPPDATA??ue(e,"AppData","Local"),"Programs"),layout:"children"},{path:ue(process.env.LOCALAPPDATA??ue(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:ue(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:ue(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},FU=()=>zh()==="linux"?ue(Kv(),".local","share","JetBrains"):Ye("JetBrains"),BU=()=>zh()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),WU=async(e,t=LU)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await kd(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=ue(r.path,i.name),l=r.layout==="app-bundles"?ue(c,"Contents","Resources","product-info.json"):ue(c,"product-info.json");await R(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=ue(s,"product-info.json"),l=ue(s,"Contents","Resources","product-info.json");if(await R(c)){n.push(c);return}if(await R(l)){n.push(l);return}let d;try{d=await kd(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=ue(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)]},HU=e=>{let t=Fv(e);return t.endsWith(`${ue("Contents","Resources")}`)?Fv(t):t},KU=async e=>{try{let t=JSON.parse(await qh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!ai(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:HU(e)}}catch{return}},bd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},GU=async(e,t)=>{let n;try{n=await DU(e,"r");let{size:r}=await n.stat();if(r<Jh||r>NU)return;let o=Math.min(r,MU),a=await bd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Jh;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>$U||c+i>r)return;let l=await bd(n,i,c);if(!l)return;let d=0;for(;d+46<=l.length;){if(l.readUInt32LE(d)!==33639248)return;let u=l.readUInt16LE(d+10),f=l.readUInt32LE(d+20),p=l.readUInt32LE(d+24),h=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),g=l.readUInt32LE(d+42),y=d+46+h+m+w;if(y>l.length)return;let b=l.subarray(d+46,d+46+h).toString("utf8");if(d=y,b!==t)continue;if(f===4294967295||p===4294967295||f>Zh||p>Zh)return;let A=await bd(n,30,g);if(!A||A.readUInt32LE(0)!==67324752)return;let v=A.readUInt16LE(26),E=A.readUInt16LE(28),I=await bd(n,f,g+30+v+E);return I?u===0?I.toString("utf8"):u===8?TU(I,{maxOutputLength:Zh}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},Bv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!ai(n)))return{id:t,version:n}},jU=async(e,t)=>{let n=ue(e,"META-INF","plugin.xml");if(await R(n))try{let o=Bv(await qh(n,"utf8"));return{present:o?.id===Ei||t,descriptor:o?.id===Ei?o:void 0}}catch{return{present:t}}let r=[];try{r=(await kd(ue(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=>ue(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await GU(o,"META-INF/plugin.xml"),s=a?Bv(a):void 0;if(s?.id===Ei)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Wv=async e=>{let t;try{t=await kd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Yh.has(o.name.toLowerCase()),i=Yh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Yh.has(o.name.toLowerCase());if(!a){let i=ue(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await jU(ue(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},VU=async e=>{try{return(await qh(ue(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(Ei)}catch{return!1}},Hv=e=>e.reduce((t,n)=>t?(Xh(n,t)??-1)>0?n:t:n,void 0),Gv=async(e={})=>{let t=e.configRoot??Ye("JetBrains"),n=e.userPluginsRoot??FU(),r=await WU(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):UU(),e.scanBudget),o=(await Promise.all(r.map(h=>KU(h)))).filter(h=>h!==void 0),a=o.length>0||await R(t);if(e.wsl??BU())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(h=>(Xh(h.version,wd)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let h of s){let m=ue(t,h.dataDirectoryName);if(!await R(m)){d=!0;continue}let w=[ue(m,"plugins"),ue(n,h.dataDirectoryName),ue(n,h.dataDirectoryName,"plugins")],g;for(let y of[...new Set(w)]){let b=await Wv(y);if(b.present){g=b;break}}if(g??=await Wv(ue(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==Ei)){if(i.push(g.descriptor.version),await VU(m)){c=!0;continue}if(!((Xh(g.descriptor.version,Ia)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${h.version}; AI Assistant ${g.descriptor.version}; ACP supported`,ideVersion:h.version,pluginVersion:g.descriptor.version}}}let u=Hv(o.map(h=>h.version)),f=Hv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${wd}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${wd}+ once, enable AI Assistant ${Ia}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${Ia}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${Ia}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${Ia}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${Ia}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${wd}+ 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 JU=[Jn,Xn],Qh=()=>ZU(YU(),".jetbrains","acp.json"),wo=()=>`${Qh()}.anyray-state`,XU=(e,t,n="npx")=>{let r=go(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,Si(n,"jetbrains")),{...e,agent_servers:r}},qU=(e,t,n)=>{if(!go(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=go(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of JU)if(c in r){if(!gd(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}},zU=(e=Gv)=>({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=Qh(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=md();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await R(r),c;try{c=await F(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=Si(a,"jetbrains");return await fc({configPath:r,current:c,next:XU(c,t,a),journalPath:wo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,wo()]}},async revert(t){let n=Qh(),r=async()=>{if(!await R(n))return t.dryRun||(await se(n),await Cd(wo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await F(n)}catch{return t.dryRun||(await se(n),await Cd(wo(),{force:!0}).catch(()=>{})),{status:"manual",messages:[`Could not parse ${n}; remove the two \u201CAnyray \xB7 \u2026\u201D agent entries manually.`]}}let a={},s=!1,i=!1;try{let u=await F(wo());(u.version===1||u.version===2)&&go(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await R(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await F(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Fr(n);let l=qU(o,c,a),d=[];return l.removed.length&&d.push(`Removed ${l.removed.join(", ")} from ${n}.`),l.conflicts.length&&d.push(`Preserved user-modified ACP entries: ${l.conflicts.join(", ")}.`),!t.dryRun&&l.removed.length&&(s&&Object.keys(l.next).length===0?await Cd(n,{force:!0}):await J(n,l.next,{backup:!1})),t.dryRun||(await se(n),await Cd(wo(),{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():pc(n,wo(),r)}}),jv=zU();import{homedir as vd}from"node:os";import{join as Sd}from"node:path";import{rm as em}from"node:fs/promises";var tm="1.0.0",Ed=["anyray-claude-acp","anyray-codex-acp"],QU=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],nm=()=>Sd(vd(),".windsurf","acp","registry.json"),rm=()=>Sd(vd(),".windsurf-next","acp","registry.json"),xa=e=>`${e}.anyray-state`,Vv=e=>({binary:Object.fromEntries(QU.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Zv=(e="npx")=>{let t=Si(e,"windsurf");return[{id:Ed[0],name:Jn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Vv(t[Jn])},{id:Ed[1],name:Xn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Vv(t[Xn])}]},Ad=e=>!Array.isArray(e)||e.some(t=>!go(t)||typeof t.id!="string")?null:e,eF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==tm||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:Ad(e.agents);if(!n)return null;let r=new Set(Ed);return{...e,version:typeof e.version=="string"?e.version:tm,agents:[...n.filter(o=>!r.has(o.id)),...Zv(t)],extensions:e.extensions??[]}},tF=(e,t,n)=>{let r=Ad(e.agents);if(!r)return null;let o=Ad(t.agents)??[],a=new Map((Ad(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!Ed.includes(u.id)){l.push(u);continue}if(!gd(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===tm&&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}},Yv=async()=>{let e=[];return(await R(rm())||await R(Sd(vd(),".windsurf-next")))&&e.push(rm()),(await R(nm())||await R(Sd(vd(),".windsurf"))||await R(Ye("Devin"))||await R(Ye("Windsurf")))&&e.push(nm()),e},Jv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Yv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Yv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=md();if(!r)return{status:"manual",messages:["Devin ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP registry was written."]};let o=[],a=[];for(let s of n){let i;try{i=await F(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=eF(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await R(s),d=Zv(r);await fc({configPath:s,current:i,next:c,journalPath:xa(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,xa(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=[nm(),rm()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await se(a),await em(xa(a),{force:!0}).catch(()=>{}));return}let i;try{i=await F(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let p=await F(xa(a));(p.version===1||p.version===2)&&Array.isArray(p.agents)&&(c=p.agents,l=p.version===2&&p.fileExisted===!1,d=p.version===2&&p.fileExisted===!0)}catch{}let u;if(d){let p=`${a}.anyray-bak`;if(!await R(p)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await F(p)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await Fr(a);let f=tF(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 em(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 se(a),await em(xa(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await pc(a,xa(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var ie=[dr,zw,Hs,Kk,pC,EC,NC,jv,Pv,Jv,ib],Kt=e=>ie.find(t=>t.id===e);var nF=["hook_registration","mcp_registration","hook_binary","beacon_target"],bo=e=>e.status==="configured"||e.status==="queued",ko=async(e,t=ie)=>{let n=new Set(e),r=[];for(let o of t)if(n.has(o.id))try{(await o.detect()).installed&&r.push(o)}catch{}return r},Rr=async(e,t,n=ie)=>{let r=[];for(let o of await ko(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},om=async(e,t=ie)=>{let n=[];for(let r of await ko(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(nF.map(o=>[o,"unreadable"]))})}return n},Xv=e=>e.filter(t=>!t.integrationStatus),rF=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},wt=async(e,t)=>{let n=[];for(let r of e)try{let o=await r.apply(t,{dryRun:!1});n.push({id:r.id,title:r.title,status:o.status})}catch(o){let a=rF(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 pF,writeFile as fF}from"node:fs/promises";import{join as rS}from"node:path";import{z as Me}from"zod";var oF=["HTTPS_PROXY","https_proxy"],qv=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_UNTRUSTED"]),zv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Qv=new Set(["ENOTFOUND","EAI_AGAIN"]),eS=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),tS=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),aF=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 sF(e)},sF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...qv,...zv,...Qv,...eS,...tS])if(t.includes(n))return n}},iF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",cF=e=>oF.filter(t=>(e[t]??"").trim()!==""),lF=(e,t=process.env)=>{let n=aF(e),r=cF(t);return{kind:n&&qv.has(n)?"tls-unknown-issuer":n&&zv.has(n)?"tls-invalid-cert":n&&Qv.has(n)?"dns":iF(e)||n&&tS.has(n)?"timeout":n&&eS.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},dF=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}},bt=(e,t=process.env)=>dF(lF(e,t));var Ra="required",uF=e=>e==="subscription"?"subscription":"placeholder",nS=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?uF(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}:{}}},Id=(e,t,n)=>{let r=new Set(t.enabled??[]),o=e.managedTools??[],a=o.filter(u=>r.has(u)||n),s=new Set(e.revertedTools??[]),i=e.revertedTools!=null,c=u=>t.tiers?.[u]??Ra,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 hF=1e4,mF=1,yF=Me.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),gF=Me.object({id:yF,name:Me.string().min(1),version:Me.string().min(1),body:Me.string()}),wF=Me.object({version:Me.literal(mF).optional(),skills:Me.array(gF),updatedAt:Me.string().min(1).optional(),routing:Me.object({origin:Me.string().min(1)}).optional(),team:Me.string().min(1).optional(),lane:Me.enum(["subscription","org"]).optional().catch(void 0),tools:Me.object({enabled:Me.array(Me.string().min(1)),tiers:Me.record(Me.string().min(1),Me.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),bF=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",xd=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",Rd=async(e,t,n={})=>{let r=n.timeoutMs??hF,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.`:bt(l);throw new Error(`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Error(`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch(l){let d=new Error("team policy fetch failed: the gateway returned a malformed response");throw d.name=xd(l),d}return wF.parse(c)},oS=/^[a-z0-9][a-z0-9-]{0,31}$/,aS=64,kF=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>oS.test(o)).slice(0,aS).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>oS.test(o)).slice(0,aS).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},Ii=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??Ra)==="locked":!1},Od=async(e,t={})=>{let n=t.loadProfile??L,r=t.saveProfile??oe,o=t.targetFromProfile??Oe,a=t.adapters??ie,s=t.repairTools??wt,i=t.recordManaged??rr,c=await n(),l={...c},d=nS(c,{routingOrigin:e.routing?.origin?un(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 h=Id(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f||p),{candidateIds:m,freshIds:w}=h,g=0,y=0,b=0;if(m.length>0||w.length>0){let E=await o(async()=>l);if(E){let I;if(u||f||p){let P=new Set(m);I=[];for(let $ of a)if(P.has($.id))try{(await $.detect()).installed&&I.push($)}catch{}}else I=await Rr(m,E.toolOrigin,a);let C=new Set(w),x=[];for(let P of a)if(C.has(P.id))try{(await P.detect()).installed&&x.push(P)}catch{}if(g=I.length+x.length,g>0){let P=await s([...I,...x],E.target);y=P.filter(bo).length;let $=P.filter(Y=>C.has(Y.id));if(b=$.filter(bo).length,$.length>0)try{await i($,!1)}catch{}}}}let A=kF(e),v=await n();if(JSON.stringify(A??null)!==JSON.stringify(v.fleetToolPolicy??null)){let{fleetToolPolicy:E,...I}=v;await r({...I,...A?{fleetToolPolicy:A}:{}})}return{routingUpdated:u,teamUpdated:f,laneUpdated:p,toolsRequested:g,toolsApplied:y,toolsEnrolled:b,toolsTombstoned:h.tombstonedIds,profileUpdated:u||f||p}},sS=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!bF(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=rS(d,i.id),f=rS(u,"SKILL.md");await pF(u,{recursive:!0}),await fF(f,CF(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}},CF=e=>e.endsWith(`
|
|
291
|
+
}`,Zn=async e=>new Promise((t,n)=>{let r=T$("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",G$],{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(Ch(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(Ch({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Ht=(e={})=>Ca((e.home??Eh)(),".anyray","claude-desktop-windows.json"),j$=e=>Ca((e.home??Eh)(),".anyray","claude-desktop-windows.lock"),wa=class extends Error{},V$=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Rh=async e=>{let t=j$(e);await wh(wi(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=OA("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=Ca(t,"owner.json");try{await wh(t,{mode:448}),await pe(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
292
|
+
`)}catch(a){if(a.code!=="EEXIST")throw await sn(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await bh(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!V$(i.pid)}catch{try{s=Date.now()-(await LA(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new wa;await sn(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await bh(o,"utf8")).nonce===r&&await sn(t,{recursive:!0,force:!0})}catch{}}}throw new wa},BA=()=>Object.fromEntries($e.map(e=>[e,{present:!1}])),po=e=>OA("sha256").update(e).digest("hex"),Y$=(e,t)=>t.present?e===Aa?{present:!0,type:t.type,sha256:po(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},ya=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?po(e.value??"")===t.sha256:e.value===t.value:!0,Wt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Ql=(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===Aa?Wt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Wt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},bA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,$e)&&$e.every(t=>Ql(e[t],t)),kA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,hA)&&hA.every(t=>Ql(e[t],t)),Z$=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),Oh=(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 Wt(n,r)&&n.path===xh(t)&&(n.lastWritten===void 0||wA(n.lastWritten))&&(n.pending===void 0||wA(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},J$=(e,t)=>Wt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===zl&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&bA(e.lastWritten)&&(e.pending===void 0||bA(e.pending))&&Oh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),X$=e=>Wt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&kA(e.lastWritten)&&(e.pending===void 0||kA(e.pending)),CA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,mA)&&mA.every(t=>Ql(e[t],t)),q$=(e,t)=>Wt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&CA(e.lastWritten)&&(e.pending===void 0||CA(e.pending))&&Oh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),AA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,yA)&&yA.every(t=>Ql(e[t],t)),z$=(e,t)=>Wt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&AA(e.lastWritten)&&(e.pending===void 0||AA(e.pending))&&Oh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),vA=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),_h=e=>{let{pending:t,...n}=e;return{...n,version:zl,lastWritten:vA(e.lastWritten),...t?{pending:vA(t)}:{}}},SA=e=>({...e,chatTabEnabled:{present:!1}}),Q$=e=>{let{pending:t,...n}=e;return _h({...n,version:4,lastWritten:SA(e.lastWritten),...t?{pending:SA(t)}:{}})},EA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),eM=(e,t)=>_h({version:4,registryKey:_e,keyExisted:e.keyExisted,lastWritten:EA(e.lastWritten),...e.pending?{pending:EA(e.pending)}:{},helper:{path:xh(t)}}),Ph=async(e,t=!0)=>{let n=Ht(e),r=wi(n),o=`${NA(n)}.anyray-old-`,a=(await TA(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>Ca(r,l)),s=n;if(!await R(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await DA(a[0],n):s=a[0]}let i=await F(s),c=X$(i)?eM(i,e):q$(i,e)?Q$(i):z$(i,e)?_h(i):J$(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>sn(l,{force:!0}))),c},xA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),tM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:_e,keyExisted:e.keyExisted,lastWritten:xA(e.lastWritten),...e.pending?{pending:xA(e.pending)}:{}}:e,Jl=async(e,t)=>{let n=Ht(t),r=`${JSON.stringify(tM(e),null,2)}
|
|
293
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await pe(n,r)},nM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,rM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),oM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),aM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),sM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===aM(t).toUpperCase(),IA=(e,t,n,r,o)=>{let a=$e.find(i=>i.toLowerCase()===t.toLowerCase());if(!a)return!1;let s=n==="String"?"REG_SZ":n==="ExpandString"?"REG_EXPAND_SZ":n;if(s!=="REG_SZ"&&s!=="REG_EXPAND_SZ"){if(o)throw new Error("an owned Claude policy value has an unsupported type");return!1}if(e[a].present)throw new Error("a Claude policy value was returned more than once");return e[a]={present:!0,type:s,value:r},!0},iM=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,cM=(e,t)=>{if(!Kl(e,!0))return!1;let n=iM(t);if(oM.has(n))return!1;if(rM.has(n))return n==="REG_EXPAND_SZ"?!0:!KC(e,!0)},lM=(e,t)=>{let n=BA(),r=!1,o=!1,a=!1,s=t.toUpperCase()===gi.toUpperCase(),i=(l,d)=>{if(!s)return;let u=cM(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),IA(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||sM(d,t))continue;let u=nM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),IA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Yn=async(e,t=_e)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:BA(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return lM(n.stdout,t)},xr=async e=>{let t=await Yn(e,gi);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...$e.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},Th=e=>e.unparsed?`This machine may have a Claude policy under ${gi} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${gi} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${gi} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var ed=(e,t)=>pa(lo(e,t)),WA=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],dM=(e,t)=>{let n=ed(e,t);return Object.fromEntries($e.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},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}}),pM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,Ah=e=>Object.fromEntries($e.map(t=>[t,Y$(t,e[t])])),RA=(e,t,n,r)=>({version:zl,registryKey:_e,keyExisted:e,lastWritten:Ah(t),helper:{path:n,lastWritten:kh(r)}}),fM=(e,t,n,r,o,a)=>({version:zl,registryKey:_e,keyExisted:e,lastWritten:Ah(t),pending:Ah(n),helper:{path:r,...o?{lastWritten:kh(o)}:{},pending:kh(a)}}),vh=(e,t,n)=>ya(n,e.lastWritten[t])||e.pending!==void 0&&ya(n,e.pending[t]),ba=async e=>{try{let t=await bh(e,"utf8");return{content:t,sha256:po(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ka=async e=>(await ba(e))?.sha256,ga=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,ql=async(e,t)=>{let n=H$(e),r;try{r=await TA(wi(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>Ca(wi(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([ba(e),ba(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ga(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await FA(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ga(t,s.sha256)&&ga(t,i.sha256)){await sn(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Dh=async(e,t,n)=>(n.present?await e(WA(_e,t,n.value??"",n.type??"REG_SZ")):await e(["delete",_e,"/v",t,"/f"])).code===0,hM=async(e,t,n)=>{let r=!0,o=await Yn(e);for(let a of $e)if(!ma(o.values[a],t[a])){if(!ma(o.values[a],n[a])){r=!1;continue}await Dh(e,a,t[a])||(r=!1),o=await Yn(e)}return r&&$e.every(a=>ma(o.values[a],t[a]))},et=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Ht(n)]}}),HA=async(e,t,n,r={})=>{if(!xe(t))return et("A valid personal ark_ gateway key is required.",!1,r);let o=xh(r),a;try{a=M$((r.credentialCommand??dh)())}catch{return et("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=po(a),i=r.runReg??Zn,c=Ht(r),l;if(!n.dryRun)try{l=await Rh(r)}catch(m){return et(m instanceof wa?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; the registry was left unchanged.",!1,r)}let d,u,f,p,h=!1;try{let m=await xr(i);if(m)return et(Th(m),!1,r);let w=await Ph(r,!n.dryRun);n.dryRun||await ql(o,w);let g=await Yn(i),y=dM(e,o),b=await ba(o),A=b?.sha256,v=!1;if(d=w,u=g,f=y,w){let C=$e.find(I=>!vh(w,I,g.values[I]));if(C)return et(`Claude's ${C} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(A!==void 0&&!ga(w,A))return et(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);v=pM(w)}else{if(A!==void 0&&A!==s)return et(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let C=g.foreignState||$e.some($=>g.values[$].present),I=$e.every($=>ma(g.values[$],y[$])),P=$e.every($=>ma(g.values[$],uM(e,t.trim())[$]));if(C&&!I&&!P)return et(`Existing Claude third-party-inference policy values under ${_e} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(v=P,I&&A===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${_e} into an owner-only journal without rewriting them.`]}:(await Jl(RA(g.keyPresent,y,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${_e} into the ownership journal.`]})}if(v){let C=!0;try{C=(r.appRunning??Ih)()}catch{}if(C)return et("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=fM(w?.keyExisted??g.keyPresent,g.values,y,o,b?.content,a);if(p=E,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${_e}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Jl(E,r),h=!0;for(let C of $e){let I=await Yn(i);if(!ya(I.values[C],E.lastWritten[C])&&!ya(I.values[C],E.pending[C]))throw new Error("registry value changed during apply");if(!ma(I.values[C],y[C])&&!await Dh(i,C,y[C]))throw new Error("registry write failed")}let x=await Yn(i);if(!$e.every(C=>ya(x.values[C],E.pending[C])))throw new Error("registry verification failed");if(A!==s&&(A===void 0?await W$(o,a):await Xl(o,A,a,"apply",r)),await ka(o)!==s)throw new Error("credential helper verification failed");return await Jl(RA(E.keyExisted,y,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${_e}.`,`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.",...Bl]}}catch{if(!h||!u||!f||!p)return et("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await ql(o,p);let m=!0,w=await ba(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await Xl(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await ka(o)===p.helper.lastWritten.sha256):await Xl(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await hM(i,u.values,f))return d?await Jl(d,r):await sn(c,{force:!0}),et("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return et("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?.()}},KA=async(e,t={})=>{let n=t.runReg??Zn,r=Ht(t),o;if(!e.dryRun)try{o=await Rh(t)}catch(a){return et(a instanceof wa?"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 Ph(t,!e.dryRun);a&&!e.dryRun&&await ql(a.helper.path,a);let s=await Yn(n);if(!a)return $e.filter(h=>s.values[h].present).length>0?et(`Claude policy values exist under ${_e}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=$e.filter(p=>s.values[p].present&&!vh(a,p,s.values[p])),c=await ka(a.helper.path),l=c!==void 0&&!ga(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${_e}.`,`Would remove the Anyray-owned credential helper at ${a.helper.path}.`,...i.length||l?[`Would preserve changed values: ${[...i,...l?["credential helper"]:[]].join(", ")}.`]:[]]};let d=!1,u=new Set(i);for(let p of $e){let m=(await Yn(n)).values[p];if(m.present){if(!vh(a,p,m)){u.add(p);continue}await Dh(n,p,{present:!1})||(d=!0)}}let f=await ka(a.helper.path);if(f!==void 0)if(ga(a,f))try{await Xl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?et(`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 sn(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${_e}.`,"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?[]:Wl]})}catch{return et(`Could not safely inspect or revert ${_e}; no unproven value was removed.`,!1,t)}finally{await o?.()}},GA=async(e,t={})=>{let n=t.runReg??Zn;if(!await R(Ht(t)))return;let r;try{r=await Rh(t);let o=await Ph(t);if(o&&await ql(o.helper.path,o),!o||o.pending||await xr(n)!==void 0)return;let a=await Yn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Je(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&$e.every(l=>ya(a.values[l],o.lastWritten[l]))))return;let i=await ka(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 B$(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?.()}},jA=async(e,t={})=>await GA(e,t)!==void 0,VA=async(e,t={})=>await GA(e,t)==="dynamic";var va=(e=yM())=>e==="win32"?Ih:Vl,Lh="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",nd=async(e,t={})=>{let n=(t.profileRoot??co)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Lh};if((t.appRunning??va(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await YA.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 Fl(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 "+Lh}:{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??$C)();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=td(t.stagingRoot??gM(),`anyray-history-${process.pid}-${mM()}`);try{let s=await(t.runImporter??MC)({binary:o,exportPath:e,configDir:td(a,"config"),workDir:td(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. "+Lh};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 FC(r.dir,s.conversations),c=await BC({stagedProjectsDir:td(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 YA.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Rt}from"node:fs";import{homedir as FM}from"node:os";import{join as ln,sep as BM}from"node:path";import{isDeepStrictEqual as sd}from"node:util";import{constants as wM}from"node:fs";import{promises as G}from"node:fs";import{dirname as Sa,isAbsolute as $h,join as ne,relative as rd,resolve as cn,sep as bi}from"node:path";import{randomUUID as id}from"node:crypto";var En=448,ki=384,qA=448,bM=4,Mh=3e4,zA=5e3,kM=10*6e4,Nh=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),ut=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"),QA=(e,t)=>{let n=rd(cn(e),cn(t));return n===""||!n.startsWith(`..${bi}`)&&n!==".."&&!$h(n)},fo=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return ut(n)?{raw:t,value:n}:void 0}catch(t){return It(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},It=e=>e instanceof Error&&"code"in e,CM=e=>{try{return process.kill(e,0),!0}catch(t){return It(t)&&t.code==="EPERM"}},ev=e=>e===0?"owner.json":`owner.${e}.json`,od=async e=>{let t;try{t=await G.readdir(e)}catch{return}let r=t.map(d=>{if(d==="owner.json")return{name:d,generation:0};let u=/^owner\.(\d+)\.json$/.exec(d);if(!u)return;let f=Number(u[1]);return Number.isSafeInteger(f)&&f>0?{name:d,generation:f}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=ne(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));ut(d)&&typeof d.pid=="number"&&Number.isSafeInteger(d.pid)&&d.pid>0&&typeof d.nonce=="string"&&d.nonce.length>0&&(a=d.pid,s=d.nonce,typeof d.createdAt=="number"&&Number.isFinite(d.createdAt)&&d.createdAt>=0&&(i=d.createdAt))}catch{}let c=await G.stat(o).then(d=>d.mtimeMs),l=i!==void 0&&i<=Date.now()+6e4?i:c;return{generation:r.generation,pid:a,nonce:s,createdAtMs:l,mtimeMs:c}},tv=e=>{if(e.pid===void 0||!CM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Mh&&t-e.createdAtMs>kM},AM=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(Sa(t),{recursive:!0,mode:En});let n=id(),r,o=!1;try{await G.mkdir(t,{mode:En}),o=!0}catch(i){if(!It(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await od(t);if(d){if(!tv(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=Mh)return}let l=ne(t,ev(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
294
|
+
`,{flag:"wx",mode:ki}),r=l}catch(d){if(It(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await G.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await G.readFile(a,"utf8"));if(!ut(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},zA);return s.unref(),async()=>{clearInterval(s);try{(await od(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},vM=async(e,t,n)=>{await G.mkdir(Sa(e),{recursive:!0,mode:En});let r=await AM(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!It(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${id()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
|
|
295
|
+
`,{mode:ki,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},cd=async(e,t)=>{for(let n=0;n<bM;n+=1){let r=await fo(e);if(!r)return"failed";let o=t(r.value);if(!o||sd(o,r.value))return"unchanged";try{if(await vM(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},ZA=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},ld=async e=>{let t=[];for(let n of await ZA(e))for(let r of await ZA(ne(e,n)))t.push(ne(e,n,r));return t},SM=e=>Array.isArray(e.skills)?e.skills.filter(t=>ut(t)&&Ci(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],EM=async e=>{let t=ne(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await ld(t)){let o=await fo(ne(r,"manifest.json"));if(!o)continue;let a=r.split(bi).at(-1)??"";for(let s of SM(o.value))n.push({account:a,packageDir:r,entry:s})}return n},xM=async e=>{let t=await fo(ne(e,".claude-plugin","plugin.json"));return!!t&&Ci(t.value.name)},IM=(e,t)=>{let n=$h(t)?cn(t):cn(e,t);if(!QA(e,n)||n===cn(e))return;let r=rd(cn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},RM=async e=>{let t=await ld(ne(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(bi).includes("skills-plugin"))continue;let o=ne(r,"cowork_plugins"),a=await fo(ne(o,"installed_plugins.json"));if(!a||!ut(a.value.plugins))continue;let s=r.split(bi).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!Ci(i)||!Array.isArray(c)))for(let l of c){if(!ut(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=IM(o,l.installPath);!d||!await xM(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:ne(r,"cowork_account_settings.json")})}}return n},OM=async e=>{let t=await fo(ne(e,"claude_desktop_config.json"));return!t||!ut(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>Ci(n)&&n.toLowerCase()!=="anyray"&&ut(r)))},nv=async e=>{let[t,n,r]=await Promise.all([EM(e),RM(e),OM(e)]);return{skills:t,plugins:n,localMcpServers:r}},Uh=async e=>{let t=await nv(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)}},JA=async e=>{try{let n=await G.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())return!1}catch{return!1}let t=async n=>{let r;try{r=await G.readdir(n,{withFileTypes:!0})}catch{return!1}for(let o of r){if(!Ci(o.name))return!1;let a=ne(n,o.name);if(o.isSymbolicLink())return!1;if(o.isDirectory()){if(!await t(a))return!1}else if(!o.isFile())return!1}return!0};return t(e)},_M=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=ne(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,En);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?qA:ki)}}};await t(e),await G.chmod(e,En)},rv=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},ad=async(e,t)=>{try{let[n,r]=await Promise.all([G.readdir(e,{withFileTypes:!0}),G.readdir(t,{withFileTypes:!0})]),o=n.map(s=>s.name).sort(),a=r.map(s=>s.name).sort();if(!sd(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 ad(ne(e,s),ne(t,s)))return!1}else if(!i.isFile()||!await rv(ne(e,s),ne(t,s)))return!1}return!0}catch{return!1}},ov=e=>`${e}.anyray-incomplete`,av=async(e,t)=>{let n=!1;if(t){await G.mkdir(Sa(e),{recursive:!0,mode:En});try{await G.mkdir(e,{mode:En}),n=!0}catch(l){if(!It(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=id(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await od(e)}catch{return}if(f){if(!tv(f)||!Number.isSafeInteger(f.generation+1))return;d=f.generation+1}else if(await G.stat(e).then(h=>Date.now()-h.mtimeMs).catch(()=>0)<=Mh)return}let u=ne(e,ev(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
296
|
+
`,{flag:"wx",mode:ki}),o=u}catch(f){if(It(f)&&f.code==="EEXIST"){n=!1;continue}n&&await G.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await G.readFile(a,"utf8"));if(!ut(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},zA);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await od(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},sv=async e=>{let t=await av(e,!1);t&&await t.complete()},PM=async(e,t,n)=>{let r=ov(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await ad(e,t))return await sv(r),"present"}catch(c){if(!It(c)||c.code!=="ENOENT")return"failed"}if(o)try{let c=await G.lstat(r);if(!c.isDirectory()||c.isSymbolicLink())return"conflict"}catch{return"conflict"}let a=await av(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:En})}catch(c){if(!It(c)||c.code!=="EEXIST")return a.abandon(),"failed";try{let l=await G.lstat(t);if(!l.isDirectory()||l.isSymbolicLink())return await a.complete(),"conflict"}catch{return a.abandon(),"failed"}}let s=async(c,l)=>{let d;try{d=await G.readdir(c,{withFileTypes:!0})}catch{return"failed"}for(let u of d){let f=ne(c,u.name),p=ne(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(p,{mode:En})}catch(m){if(!It(m)||m.code!=="EEXIST")throw m;let w=await G.lstat(p);if(!w.isDirectory()||w.isSymbolicLink())return"conflict"}let h=await s(f,p);if(h!=="copied")return h}else if(u.isFile())try{await G.copyFile(f,p,wM.COPYFILE_EXCL);let h=await G.stat(f);await G.chmod(p,(h.mode&73)!==0?qA:ki)}catch(h){if(!It(h)||h.code!=="EEXIST")throw h;if(!await rv(f,p))return"conflict"}else return"failed"}catch(h){return It(h)&&h.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await ad(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},iv=async(e,t,n,r)=>{if(!await JA(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await ad(e,t))return await sv(ov(t)),"present"}catch(a){if(!It(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(Sa(t),{recursive:!0,mode:En});let o=ne(Sa(t),`.anyray-stage-${id()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await JA(o)?(await _M(o),await n?.(t),await PM(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},XA=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),TM=async e=>{let t=await ld(ne(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await fo(ne(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},DM=async e=>{let t=await ld(ne(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(bi).includes("skills-plugin"))try{await G.access(ne(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},LM=async(e,t,n,r,o)=>{let a=ne(t,"manifest.json");for(let s of e){let i=ne(s.packageDir,"skills",s.entry.name);try{await G.access(ne(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=ne(t,"skills",s.entry.name),l=await iv(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 cd(a,f=>{let p=Array.isArray(f.skills)?f.skills:[];if(p.find(m=>ut(m)&&typeof m.name=="string"&&m.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...f,skills:[...p,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},cv=(e,t)=>({...e,installPath:t}),NM=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=$h(r.installPath)?cn(r.installPath):cn(o,r.installPath),s=cv(e,rd(cn(t),cn(n))),i={...r,installPath:rd(cn(o),a)};return sd(s,i)},$M=async(e,t,n)=>{let r=await fo(e);if(!r||!ut(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":cd(t,a=>{let s=ut(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},MM=async(e,t,n,r,o)=>{let a=ne(t,"cowork_plugins"),s=ne(a,"installed_plugins.json"),i=ne(t,"cowork_account_settings.json");for(let c of e){let l=ne(a,c.relativeInstallPath);if(!QA(a,l)){n.invalid+=1;continue}let d=await iv(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 cd(s,h=>{let m=ut(h.plugins)?h.plugins:{},w=m[c.id],g=Array.isArray(w)?w:[],y=g.find(A=>ut(A)&&A.scope==="user");if(y){u=NM(c.entry,Sa(c.settingsFile),c.packageDir,y,t),f=!u;return}let b=cv(c.entry,l);return{...h,version:typeof h.version=="number"?h.version:2,plugins:{...m,[c.id]:[...g,b]}}})==="failed"?n.failed+=1:f?n.conflicts+=1:await $M(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},UM=async(e,t,n)=>{let r=ne(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await cd(r,c=>{let l=ut(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=sd(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}},lv=async(e,t,n={})=>{let r=await nv(e),o=Nh("skill"),a=Nh("plugin"),s=Nh("local-mcp"),i=[],c=[],l=XA(r.skills,n.account,n.allAccounts),d=XA(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let f=new Set(n.allowedAccounts);if([...new Set([...l.map(h=>h.account),...d.map(h=>h.account)])].some(h=>!f.has(h)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,sourceChanged:!0,retryable:[]}}if(l.length>0){let f=await TM(t);f.state==="found"?await LM(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 DM(t);f.state==="found"?await MM(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await UM(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 WM=async e=>{try{return await Rt.access(e),!0}catch{return!1}},dv=448,HM=384,pv={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},KM=["code","cowork"],Wh=(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.",Fh=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),fv=async e=>{let t;try{t=(await Rt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&da(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await Rt.readdir(ln(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&da(a.name)).map(a=>a.name);for(let a of o)n.push(ln(e,r,a))}catch{}return n},GM=async e=>{try{return(await Rt.readdir(e)).filter(t=>t.startsWith(jn)&&t.endsWith(".json")).map(t=>t.slice(jn.length,-5)).filter(da)}catch{return[]}},jM=async(e,t)=>{let n=await fv(ln(e,pv[t])),r=[];for(let o of n){let a=await GM(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(BM).slice(-2)[0]})}return r},VM=async(e,t)=>{if(t==="cowork"){let r=await Fl(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await fv(ln(e,pv.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},YM=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await Rt.copyFile(e,n),await Rt.chmod(n,HM),await Rt.rename(n,t)},ZM=async(e,t)=>{try{let n=JSON.parse(await Rt.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||!da(o)?!1:(await Rt.access(ln(t,".claude","projects",oh(r),`${o}.jsonl`)),!0)}catch{return!1}},JM=async(e,t,n,r)=>{let o=Fh(e),a=await ah(n);for(let s of t)await XM(e,s,n,r,a,o);return o},XM=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${jn}${s}.json`,c=ln(t.dir,i);try{if(e==="code"){if(!await ZM(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=ln(t.dir,`${jn}${s}`),d=ln(n,`${jn}${s}`),u=await Rt.readdir(l);await Rt.mkdir(d,{mode:dv});for(let f of u)await Rt.cp(ln(l,f),ln(d,f),{recursive:!0,force:!1,errorOnExist:!0});await Rt.chmod(d,dv)}await YM(c,ln(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},uv=(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(`
|
|
297
|
+
`)}},Bh=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),hv=async e=>{let t=[];for(let n of KM)t.push({lane:n,sources:await jM(e,n)});return t},mv=async(e={})=>{let t=(e.firstPartyRoot??(()=>ii()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([hv(t),Uh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Bh(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}},ho=async(e={})=>{let t=(e.home??FM)(),n=(e.firstPartyRoot??(()=>ii()))(),r=(e.thirdPartyRoot??(()=>co()))();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??va())())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([hv(n),Uh(n)]),s;if(e.account){let p=e.account;for(let w of o)w.sources=w.sources.filter(g=>g.account.startsWith(p));let h=a.accounts.filter(w=>w.startsWith(p));if(o.every(w=>w.sources.length===0)&&h.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${p}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let m=Bh(o);for(let w of h)m.add(w);if(m.size>1)return uv(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=Bh(o);for(let h of a.accounts)p.add(h);if(p.size>1)return uv(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 WM(r),l=await lv(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:s});if(l.sourceChanged)return{ok:!1,kind:"account-ambiguous",reason:"the previous Claude Desktop profile changed during migration and now holds local data for another account",remedy:`Re-run \`${i}\` so the account choice is made from a fresh snapshot.`};let d=[],u=[];for(let{lane:p,sources:h}of o){if(h.length===0){d.push(Fh(p));continue}let m=await VM(r,p);if("missing"in m){u.push({lane:p,reason:m.missing,waiting:h.reduce((w,g)=>w+g.ids.length,0)}),d.push(Fh(p));continue}d.push(await JM(p,h,m.dir,t))}if(!(d.some(p=>p.migrated>0||p.alreadyPresent>0)||l.outcomes.some(p=>p.migrated>0||p.alreadyPresent>0||p.conflicts>0))&&(u.length>0||l.blocked.length>0)){let p=u[0];return p?{ok:!1,kind:p.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:p.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${p.lane} store`:`Claude Desktop has no ${p.lane} store in its third-party profile yet`,remedy:Wh(p.reason,p.lane,i,c)}:{ok:!1,kind:"store-missing",reason:"Claude Desktop's third-party profile has no extension store yet",remedy:"Open Claude Desktop once after connecting it to Anyray, then fully quit it so the portable extensions can be copied safely."}}return{ok:!0,lanes:d,portableAssets:l.outcomes,...u.length>0?{blocked:u}:{},...l.blocked.length>0?{blockedAssets:l.blocked}:{},...l.ambiguous.length>0?{ambiguousAssets:l.ambiguous}:{},...l.retryable.length>0?{retryableAssets:l.retryable}:{}}};var qM=e=>[Ye(e)],yv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...qM(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await R(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var gv="1.21459.0",tU=eU(zM),nU=async e=>{try{let{stdout:t}=await tU("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},rU=async e=>{try{return await QM(e)}catch{return}},wv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",oU=["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."],Ea=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(bv??=kv({}),bv):kv(e),bv,kv=async e=>{let t=(e.home??vi)(),n=["/Applications/Claude.app",xn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??nU,o=e.readClaudeAppBundle??rU;for(let a of n){let s=await r(xn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${wv}`}),c=Ml(s,gv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${gv} or newer.`);let l=await o(xn(a,"Contents","Resources","app.asar"));return l?nA.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. ${wv}`}},dd="anyray",vv="--anyray-owner=claude-desktop-v1",ud=(e={})=>{let t=(e.platform??Ir)(),n=(e.home??vi)();return t==="darwin"?an(e).appConfig:t==="win32"?xn(process.env.APPDATA??xn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):xn(n,".config","Claude","claude_desktop_config.json")},Vh=(e={})=>xn((e.home??vi)(),"Library","Application Support","Claude","claude_desktop_config.json"),Sv=()=>{let e=Ve("profile");return{command:e.command,args:[...e.args,vv]}},mo=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ev=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},aU=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),sU=e=>{if(!mo(e)||!Ev(e,["command","args"]))return!1;let t=Sv();return e.command===t.command&&aU(e.args,t.args)},iU=e=>mo(e)&&Array.isArray(e.args)&&e.args.at(-1)===vv,cU=e=>{if(!mo(e)||!Ev(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||je(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===cr&&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!je(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},lU=e=>e===void 0?"absent":sU(e)?"exact":iU(e)||cU(e)?"stale-owned":"foreign",He=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},yo=async e=>{let t=await R(e),n;try{n=await F(e)}catch{throw new He(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!mo(n.mcpServers))throw new He(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(mo(n.mcpServers)?n.mcpServers:void 0)?.[dd];return{path:e,fileExisted:t,json:n,entry:o,ownership:lU(o)}},pd=e=>{if(e.ownership==="foreign")throw new He(`MCP name conflict in ${e.path}: mcpServers.${dd} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},xv=(e,t)=>{let n={...e},r=mo(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[dd]:r[dd]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Kh=async(e,t)=>{if(Hh(e.entry,t))return;let n=await yo(e.path);if(!Hh(n.entry,e.entry))throw new He(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Vn(e.path,xv(n.json,t)),{reading:e,afterEntry:t}},Gh=async e=>{let t=await yo(e.reading.path);if(!Hh(t.entry,e.afterEntry))throw new He(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=xv(t.json,e.reading.entry);await Vn(e.reading.path,n)},dU=async e=>{if(!le())throw new He(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Re()} is temporary); no inference setting was changed.`);let t=await yo(ud(e));pd(t);let n=Vh(e),r=(e.platform??Ir)()==="darwin"&&n!==t.path?await yo(n):void 0;return r&&pd(r),{active:t,...r?{legacy:r}:{}}},Cv=async e=>{let t=await yo(ud(e));pd(t);let n=Vh(e),r=(e.platform??Ir)()==="darwin"&&n!==t.path?await yo(n):void 0;return r&&pd(r),{active:t,...r?{legacy:r}:{}}},uU=async e=>{let t=[];try{let n=await Kh(e.active,Sv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Kh(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Gh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new He(`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 Gh(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new He(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},pU=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Kh(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Gh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new He(`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)},Av=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)."]},fU={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},fd="claude-desktop",jh="migrate",Iv=new Set(["app-running","store-missing"]),hU={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},mU={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"}},yU="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",Rv=e=>{let t=(e.platform??Ir)(),n=e.home??vi;return{home:n,appRunning:e.appRunning??va(t),firstPartyRoot:()=>ii({home:n,runtimePlatform:t}),thirdPartyRoot:()=>co({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Ov=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=hU[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.`:"")},_v=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=mU[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.`:"")},Ai=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=Rv(e),r=await(e.pendingDesktopMigrationCount??mv)(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??ho)(n);if(a.ok){let c=Ov(a.lanes),l=_v(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(a.blocked??[]).filter(y=>y.reason!=="ambiguous"),p=a.blockedAssets??[],h=a.retryableAssets??[];if(f.length===0&&p.length===0&&h.length===0)return[c,l,u].filter(y=>!!y);if(t.preservePendingOp)return[c,l,u].filter(y=>!!y);await Ms(fd,jh);let m=f.reduce((y,b)=>y+b.waiting,0),w=[m>0?`${m} more session${m===1?"":"s"}`:"",p.length>0?`${p.length} extension ${p.length===1?"store":"stores"}`:""].filter(Boolean),g=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...h.length>0?[`Queued: ${h.length} portable configuration ${h.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...g]}if(!Iv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
298
|
+
${a.remedy}`];if(t.preservePendingOp)return[];await Ms(fd,jh);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."]}},gU=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await gr(fd),[]}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."]}},wU=e=>yv({id:fd,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Ir)(),n=(e.home??vi)();return t==="darwin"?["/Applications/Claude.app",xn(n,"Applications","Claude.app")]:t==="win32"?[xn(process.env.LOCALAPPDATA??xn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>X(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:",...Av(t)]:["Claude desktop org/API lane:",...Av(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`."]}),bU=(e={})=>{let t=wU(e),n=()=>(e.platform??Ir)()==="darwin",r=()=>(e.platform??Ir)()==="win32",o=(s,i)=>n()?dA(s,i,e):HA(s,s.clientKey??"",i,e),a=s=>n()?uA(s,e):KA(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??va((e.platform??Ir)()))(),quitTarget:fU,needsTarget:()=>!1,async complete(s){if(s!==jh)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??ho)(Rv(e));if(i.ok){let c=Ov(i.lanes),l=_v(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let f=(i.blocked??[]).filter(m=>m.reason!=="ambiguous"),p=i.blockedAssets??[],h=i.retryableAssets??[];return f.length>0||p.length>0||h.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...f.length>0||p.length>0?["Still waiting on Claude Desktop to create the remaining third-party stores, which appear the first time those parts of the app are opened."]:[],...h.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(m=>!!m):["No portable Claude Desktop data was left to bring across."]}}return Iv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?fA(s,e):r()?VA(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=an(e),p=await uo(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[mh(p),...await Ai(e,i)]}}if(r()){let f;try{f=await xr(e.runReg??Zn)}catch{return{status:"manual",manualAudience:"admin",messages:[yU,...await Ai(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[Th(f),...await Ai(e,i)]}}if(r()&&X(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 Ea(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await dU(e)}catch(f){let p=f instanceof He?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof He?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 Ai(e,i)]}}let d;try{d=await uU(c)}catch(f){let p=f instanceof He?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof He?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 Ai(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?oU:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=ud(e),c=await gU(s),l=m=>c.length===0?m:{...m,messages:[...m.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await Cv(e)}catch(m){return l({status:"manual",messages:[m instanceof He?m.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let m=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...m&&m.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${m.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let m=r()?Ht(e):void 0;if(!(m!==void 0&&f.changedFiles?.includes(m)===!0&&!await R(m)))return l(f)}let p;try{p=await pU(await Cv(e))}catch(m){let w=m instanceof He?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof He?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await se(i);let h=Vh(e);return n()&&h!==i&&await se(h),l({...f,messages:[...f.messages,...p.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...p])]})},async mcpStatus(){if(!le())return{registered:!1,command:null};try{let s=await yo(ud(e));return s.ownership!=="exact"||!mo(s.entry)?{registered:!1,command:null}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null}}},async pointsAt(s){return n()?(await Ea(e)).supported?gh(s,e):!1:r()?jA(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await Ea(e)).supported)return["unknown"];let s=await pA(e);return s?[s]:["unknown"]}if(r())return await R(Ht(e))?await xr(e.runReg??Zn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=an(e);return!await R(s.journal)||await uo(s,e)?!1:(await Ea(e)).supported}return r()&&await R(Ht(e))?!await xr(e.runReg??Zn):!1}catch{return!1}}}},Pv=bU();import{homedir as YU}from"node:os";import{join as ZU}from"node:path";import{rm as Ad}from"node:fs/promises";import{constants as Tv,accessSync as kU,statSync as CU}from"node:fs";import{platform as Yh}from"node:os";import{delimiter as AU,posix as vU,resolve as SU,win32 as EU}from"node:path";var xU="0.59.0",IU="1.1.4",Jn="Anyray \xB7 Claude",Xn="Anyray \xB7 Codex",hd="__anyray-acp-agent",Dv=(e,t,n)=>{let{command:r,args:o}=pn([hd,e,t,n]);return{command:r,args:o,env:{}}},md=(e=Yh())=>e==="win32"?"npx.cmd":"npx",yd=(e=process.env.PATH,t=Yh())=>{if(!e)return;let n=md(t);for(let r of e.split(AU)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=SU(o,n);try{if(!CU(a).isFile())continue;return kU(a,t==="win32"?Tv.F_OK:Tv.X_OK),a}catch{}}},gd=(e,t=Yh())=>{let n=t==="win32"?EU:vU;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==md(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},RU="https://chatgpt.com/backend-api/codex",OU="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Lv="ANYRAY_ACP_CODEX_AUTHORIZATION",Nv="ANYRAY_ACP_CODEX_CLIENT_KEY",$v="ANYRAY_ACP_CODEX_METADATA",Mv=e=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),_U=(e,t={})=>{let n=X(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":RU,"x-anyray-forward-headers":OU}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Nv}:{}}:{Authorization:Lv};return Mv(e)&&(o["x-anyray-metadata"]=$v),{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}}}:{}}},PU=e=>{let t=X(e,"openai"),n=Mv(e);return{...t?e.clientKey?{[Nv]:e.clientKey}:{}:{[Lv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[$v]:n}:{}}},Uv=(e,t=md(),n={})=>({[Jn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${xU}`],env:fn(e).env},[Xn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${IU}`],env:{CODEX_CONFIG:JSON.stringify(_U(e,n)),...PU(e)}}}),Si=(e=md(),t="jetbrains")=>({[Jn]:Dv("claude",e,t),[Xn]:Dv("codex",e,t)}),go=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as TU}from"node:zlib";import{open as DU,readFile as zh,readdir as Cd}from"node:fs/promises";import{dirname as Fv,join as ue}from"node:path";import{homedir as Kv,platform as Qh}from"node:os";var bd="2025.3.2",xa="253.30387.147",Ei="com.intellij.ml.llm",Zh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),LU=1e4,NU=256*1024*1024,$U=16*1024*1024,Jh=1024*1024,Xh=22,MU=Xh+65535,qh=Ml,UU=()=>{let e=Kv(),t=ue(e,".cache","JetBrains","RemoteDev");switch(Qh()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:ue(e,"Applications"),layout:"app-bundles"},{path:ue(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:ue(process.env.LOCALAPPDATA??ue(e,"AppData","Local"),"Programs"),layout:"children"},{path:ue(process.env.LOCALAPPDATA??ue(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:ue(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:ue(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},FU=()=>Qh()==="linux"?ue(Kv(),".local","share","JetBrains"):Ye("JetBrains"),BU=()=>Qh()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),WU=async(e,t=LU)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await Cd(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=ue(r.path,i.name),l=r.layout==="app-bundles"?ue(c,"Contents","Resources","product-info.json"):ue(c,"product-info.json");await R(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=ue(s,"product-info.json"),l=ue(s,"Contents","Resources","product-info.json");if(await R(c)){n.push(c);return}if(await R(l)){n.push(l);return}let d;try{d=await Cd(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=ue(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)]},HU=e=>{let t=Fv(e);return t.endsWith(`${ue("Contents","Resources")}`)?Fv(t):t},KU=async e=>{try{let t=JSON.parse(await zh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!ai(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:HU(e)}}catch{return}},kd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},GU=async(e,t)=>{let n;try{n=await DU(e,"r");let{size:r}=await n.stat();if(r<Xh||r>NU)return;let o=Math.min(r,MU),a=await kd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Xh;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>$U||c+i>r)return;let l=await kd(n,i,c);if(!l)return;let d=0;for(;d+46<=l.length;){if(l.readUInt32LE(d)!==33639248)return;let u=l.readUInt16LE(d+10),f=l.readUInt32LE(d+20),p=l.readUInt32LE(d+24),h=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),g=l.readUInt32LE(d+42),y=d+46+h+m+w;if(y>l.length)return;let b=l.subarray(d+46,d+46+h).toString("utf8");if(d=y,b!==t)continue;if(f===4294967295||p===4294967295||f>Jh||p>Jh)return;let A=await kd(n,30,g);if(!A||A.readUInt32LE(0)!==67324752)return;let v=A.readUInt16LE(26),E=A.readUInt16LE(28),x=await kd(n,f,g+30+v+E);return x?u===0?x.toString("utf8"):u===8?TU(x,{maxOutputLength:Jh}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},Bv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!ai(n)))return{id:t,version:n}},jU=async(e,t)=>{let n=ue(e,"META-INF","plugin.xml");if(await R(n))try{let o=Bv(await zh(n,"utf8"));return{present:o?.id===Ei||t,descriptor:o?.id===Ei?o:void 0}}catch{return{present:t}}let r=[];try{r=(await Cd(ue(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=>ue(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await GU(o,"META-INF/plugin.xml"),s=a?Bv(a):void 0;if(s?.id===Ei)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Wv=async e=>{let t;try{t=await Cd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Zh.has(o.name.toLowerCase()),i=Zh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Zh.has(o.name.toLowerCase());if(!a){let i=ue(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await jU(ue(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},VU=async e=>{try{return(await zh(ue(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(Ei)}catch{return!1}},Hv=e=>e.reduce((t,n)=>t?(qh(n,t)??-1)>0?n:t:n,void 0),Gv=async(e={})=>{let t=e.configRoot??Ye("JetBrains"),n=e.userPluginsRoot??FU(),r=await WU(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):UU(),e.scanBudget),o=(await Promise.all(r.map(h=>KU(h)))).filter(h=>h!==void 0),a=o.length>0||await R(t);if(e.wsl??BU())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(h=>(qh(h.version,bd)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let h of s){let m=ue(t,h.dataDirectoryName);if(!await R(m)){d=!0;continue}let w=[ue(m,"plugins"),ue(n,h.dataDirectoryName),ue(n,h.dataDirectoryName,"plugins")],g;for(let y of[...new Set(w)]){let b=await Wv(y);if(b.present){g=b;break}}if(g??=await Wv(ue(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==Ei)){if(i.push(g.descriptor.version),await VU(m)){c=!0;continue}if(!((qh(g.descriptor.version,xa)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${h.version}; AI Assistant ${g.descriptor.version}; ACP supported`,ideVersion:h.version,pluginVersion:g.descriptor.version}}}let u=Hv(o.map(h=>h.version)),f=Hv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${bd}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${bd}+ once, enable AI Assistant ${xa}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${xa}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${xa}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${xa}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${xa}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${bd}+ 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 JU=[Jn,Xn],em=()=>ZU(YU(),".jetbrains","acp.json"),wo=()=>`${em()}.anyray-state`,XU=(e,t,n="npx")=>{let r=go(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,Si(n,"jetbrains")),{...e,agent_servers:r}},qU=(e,t,n)=>{if(!go(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=go(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of JU)if(c in r){if(!wd(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}},zU=(e=Gv)=>({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=em(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=yd();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await R(r),c;try{c=await F(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=Si(a,"jetbrains");return await fc({configPath:r,current:c,next:XU(c,t,a),journalPath:wo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,wo()]}},async revert(t){let n=em(),r=async()=>{if(!await R(n))return t.dryRun||(await se(n),await Ad(wo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await F(n)}catch{return t.dryRun||(await se(n),await Ad(wo(),{force:!0}).catch(()=>{})),{status:"manual",messages:[`Could not parse ${n}; remove the two \u201CAnyray \xB7 \u2026\u201D agent entries manually.`]}}let a={},s=!1,i=!1;try{let u=await F(wo());(u.version===1||u.version===2)&&go(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await R(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await F(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Fr(n);let l=qU(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 Ad(n,{force:!0}):await J(n,l.next,{backup:!1})),t.dryRun||(await se(n),await Ad(wo(),{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():pc(n,wo(),r)}}),jv=zU();import{homedir as Sd}from"node:os";import{join as Ed}from"node:path";import{rm as tm}from"node:fs/promises";var nm="1.0.0",xd=["anyray-claude-acp","anyray-codex-acp"],QU=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],rm=()=>Ed(Sd(),".windsurf","acp","registry.json"),om=()=>Ed(Sd(),".windsurf-next","acp","registry.json"),Ia=e=>`${e}.anyray-state`,Vv=e=>({binary:Object.fromEntries(QU.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Zv=(e="npx")=>{let t=Si(e,"windsurf");return[{id:xd[0],name:Jn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Vv(t[Jn])},{id:xd[1],name:Xn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Vv(t[Xn])}]},vd=e=>!Array.isArray(e)||e.some(t=>!go(t)||typeof t.id!="string")?null:e,eF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==nm||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:vd(e.agents);if(!n)return null;let r=new Set(xd);return{...e,version:typeof e.version=="string"?e.version:nm,agents:[...n.filter(o=>!r.has(o.id)),...Zv(t)],extensions:e.extensions??[]}},tF=(e,t,n)=>{let r=vd(e.agents);if(!r)return null;let o=vd(t.agents)??[],a=new Map((vd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!xd.includes(u.id)){l.push(u);continue}if(!wd(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===nm&&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}},Yv=async()=>{let e=[];return(await R(om())||await R(Ed(Sd(),".windsurf-next")))&&e.push(om()),(await R(rm())||await R(Ed(Sd(),".windsurf"))||await R(Ye("Devin"))||await R(Ye("Windsurf")))&&e.push(rm()),e},Jv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Yv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Yv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=yd();if(!r)return{status:"manual",messages:["Devin ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP registry was written."]};let o=[],a=[];for(let s of n){let i;try{i=await F(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=eF(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await R(s),d=Zv(r);await fc({configPath:s,current:i,next:c,journalPath:Ia(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Ia(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=[rm(),om()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await se(a),await tm(Ia(a),{force:!0}).catch(()=>{}));return}let i;try{i=await F(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let p=await F(Ia(a));(p.version===1||p.version===2)&&Array.isArray(p.agents)&&(c=p.agents,l=p.version===2&&p.fileExisted===!1,d=p.version===2&&p.fileExisted===!0)}catch{}let u;if(d){let p=`${a}.anyray-bak`;if(!await R(p)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await F(p)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await Fr(a);let f=tF(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 tm(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 se(a),await tm(Ia(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await pc(a,Ia(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var ie=[dr,Qw,Hs,Kk,pC,EC,NC,jv,Pv,Jv,cb],Kt=e=>ie.find(t=>t.id===e);var nF=["hook_registration","mcp_registration","hook_binary","beacon_target"],bo=e=>e.status==="configured"||e.status==="queued",ko=async(e,t=ie)=>{let n=new Set(e),r=[];for(let o of t)if(n.has(o.id))try{(await o.detect()).installed&&r.push(o)}catch{}return r},Rr=async(e,t,n=ie)=>{let r=[];for(let o of await ko(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},am=async(e,t=ie)=>{let n=[];for(let r of await ko(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(nF.map(o=>[o,"unreadable"]))})}return n},Xv=e=>e.filter(t=>!t.integrationStatus),rF=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},wt=async(e,t)=>{let n=[];for(let r of e)try{let o=await r.apply(t,{dryRun:!1});n.push({id:r.id,title:r.title,status:o.status})}catch(o){let a=rF(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 pF,writeFile as fF}from"node:fs/promises";import{join as rS}from"node:path";import{z as Me}from"zod";var oF=["HTTPS_PROXY","https_proxy"],qv=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_UNTRUSTED"]),zv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Qv=new Set(["ENOTFOUND","EAI_AGAIN"]),eS=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),tS=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),aF=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 sF(e)},sF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...qv,...zv,...Qv,...eS,...tS])if(t.includes(n))return n}},iF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",cF=e=>oF.filter(t=>(e[t]??"").trim()!==""),lF=(e,t=process.env)=>{let n=aF(e),r=cF(t);return{kind:n&&qv.has(n)?"tls-unknown-issuer":n&&zv.has(n)?"tls-invalid-cert":n&&Qv.has(n)?"dns":iF(e)||n&&tS.has(n)?"timeout":n&&eS.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},dF=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}},bt=(e,t=process.env)=>dF(lF(e,t));var Ra="required",uF=e=>e==="subscription"?"subscription":"placeholder",nS=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?uF(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}:{}}},Id=(e,t,n)=>{let r=new Set(t.enabled??[]),o=e.managedTools??[],a=o.filter(u=>r.has(u)||n),s=new Set(e.revertedTools??[]),i=e.revertedTools!=null,c=u=>t.tiers?.[u]??Ra,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 hF=1e4,mF=1,yF=Me.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),gF=Me.object({id:yF,name:Me.string().min(1),version:Me.string().min(1),body:Me.string()}),wF=Me.object({version:Me.literal(mF).optional(),skills:Me.array(gF),updatedAt:Me.string().min(1).optional(),routing:Me.object({origin:Me.string().min(1)}).optional(),team:Me.string().min(1).optional(),lane:Me.enum(["subscription","org"]).optional().catch(void 0),tools:Me.object({enabled:Me.array(Me.string().min(1)),tiers:Me.record(Me.string().min(1),Me.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),bF=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",Rd=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",Od=async(e,t,n={})=>{let r=n.timeoutMs??hF,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.`:bt(l);throw new Error(`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Error(`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch(l){let d=new Error("team policy fetch failed: the gateway returned a malformed response");throw d.name=Rd(l),d}return wF.parse(c)},oS=/^[a-z0-9][a-z0-9-]{0,31}$/,aS=64,kF=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>oS.test(o)).slice(0,aS).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>oS.test(o)).slice(0,aS).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},xi=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??Ra)==="locked":!1},_d=async(e,t={})=>{let n=t.loadProfile??L,r=t.saveProfile??oe,o=t.targetFromProfile??Oe,a=t.adapters??ie,s=t.repairTools??wt,i=t.recordManaged??rr,c=await n(),l={...c},d=nS(c,{routingOrigin:e.routing?.origin?un(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 h=Id(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f||p),{candidateIds:m,freshIds:w}=h,g=0,y=0,b=0;if(m.length>0||w.length>0){let E=await o(async()=>l);if(E){let x;if(u||f||p){let P=new Set(m);x=[];for(let $ of a)if(P.has($.id))try{(await $.detect()).installed&&x.push($)}catch{}}else x=await Rr(m,E.toolOrigin,a);let C=new Set(w),I=[];for(let P of a)if(C.has(P.id))try{(await P.detect()).installed&&I.push(P)}catch{}if(g=x.length+I.length,g>0){let P=await s([...x,...I],E.target);y=P.filter(bo).length;let $=P.filter(Y=>C.has(Y.id));if(b=$.filter(bo).length,$.length>0)try{await i($,!1)}catch{}}}}let A=kF(e),v=await n();if(JSON.stringify(A??null)!==JSON.stringify(v.fleetToolPolicy??null)){let{fleetToolPolicy:E,...x}=v;await r({...x,...A?{fleetToolPolicy:A}:{}})}return{routingUpdated:u,teamUpdated:f,laneUpdated:p,toolsRequested:g,toolsApplied:y,toolsEnrolled:b,toolsTombstoned:h.tombstonedIds,profileUpdated:u||f||p}},sS=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!bF(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=rS(d,i.id),f=rS(u,"SKILL.md");await pF(u,{recursive:!0}),await fF(f,CF(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}},CF=e=>e.endsWith(`
|
|
299
299
|
`)?e:`${e}
|
|
300
|
-
`;import{createHash as AF,createPrivateKey as vF,generateKeyPairSync as SF,randomBytes as am,sign as EF}from"node:crypto";var sm=1e4,Co=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Co).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Co(e[n])}`).join(",")}}`,xi="stable-key-heartbeat-v1",iS="key-heartbeat",IF=["reapply_config","remint","revert"];var cS=e=>AF("sha256").update(e).digest("hex"),tt=e=>typeof e=="string"&&e.trim()?e.trim():void 0,xF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],im=async e=>{try{let t=await e.json(),n=tt(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},Ot=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Or=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},cm=(e,t,n)=>{try{let r=vF(t),o=new TextEncoder().encode(Co(e));return EF(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},_d=()=>{let{publicKey:e,privateKey:t}=SF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},dn=async(e,t,n,r={})=>{let o=r.timeoutMs??sm,a=`${e}/connect/verify`,s=tt(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:am(16).toString("hex")},c=cm(i,n,"verification"),l=new AbortController,d=setTimeout(()=>l.abort(),o),u;try{u=await fetch(a,{method:"POST",headers:{"content-type":"application/json","x-anyray-connect-version":we},body:JSON.stringify({cert:t,challenge:i,sig:c,...r.health?{health:r.health}:{},...r.ack?{ack:r.ack}:{},...r.telemetryOnly?{telemetryOnly:!0}:{}}),signal:l.signal})}catch(y){let b=y instanceof Error&&y.name==="AbortError"?` no response within ${o}ms.`:bt(y);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:y})}finally{clearTimeout(d)}if(!u.ok)throw new Ot(u.status,await im(u));let f;try{f=await u.text()}catch{f=""}let p;try{p=JSON.parse(f)}catch{let y=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(y)||/^\s*<(?:!doctype|html)/i.test(f);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let h=tt(p?.key);if(!h)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(h))throw new Error("developer verification failed: the gateway returned a malformed key");let m=tt(p.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=RF(p.directive),g=xF(p.capabilities);return{key:h,user:m,team:tt(p.team),expiresAt:tt(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},Pd=async(e,t,n,r,o={})=>{let a=o.timeoutMs??sm,s=`${e}/connect/key/heartbeat`,i=tt(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:am(16).toString("hex"),purpose:iS},l=cm(c,r,"heartbeat"),d=new AbortController,u=setTimeout(()=>d.abort(),a),f;try{f=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(m){let w=m instanceof Error&&m.name==="AbortError"?` no response within ${a}ms.`:bt(m);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:m})}finally{clearTimeout(u)}if(!f.ok)throw new Or(f.status,await im(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=tt(p.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||p.credentialMode!==xi||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:xi}},lS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??sm,i=`${e.replace(/\/$/,"")}/connect/machine`,c=tt(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:am(16).toString("hex"),purpose:iS},d=cm(l,r,"heartbeat"),u=new AbortController,f=setTimeout(()=>u.abort(),s);try{return(await fetch(i,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(p){return console.error("connect machine report skipped:",p instanceof Error?p.name:"error"),!1}finally{clearTimeout(f)}},RF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=tt(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!IF.includes(r)?null:{id:n,kind:r}},OF=1e4,_F=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!tt(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!tt(r.deploymentId)&&!!tt(r.user)&&!!tt(r.devPublicKey)&&!!tt(r.issuedAt)&&!!tt(r.expiresAt)},PF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??OF,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.`:bt(u);throw new Error(`could not reach the control plane at ${s}.${f}`)}finally{clearTimeout(c)}if(!l.ok)throw new Error(`enrollment failed: ${await im(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!_F(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},dS=(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())},uS=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=_d();return{cert:await PF(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),privateKeyPem:s.privateKeyPem,publicKeyPem:s.publicKeyPem}})(),a=await dn(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};import{createPrivateKey as MF,randomBytes as UF,sign as FF}from"node:crypto";var TF="https://app.anyray.ai",DF=new Set(["localhost","::1","[::1]"]),LF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,NF=e=>DF.has(e)||LF.test(e),lm=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&NF(t.hostname)},$F=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},qn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!lm(e)?TF:$F(e)};var BF=1e4,WF="machine:",pS=e=>e.startsWith(WF),HF="cert-renew",KF=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)},fS=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??qn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:UF(16).toString("hex"),purpose:HF},c;try{let h=MF(t),m=new TextEncoder().encode(Co(i));c=FF(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),BF),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 KF(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var dm=async(e,t=e.origin,n=ie)=>{let r=0,o=0,a=!0;for(let s of n)try{if(!s.pointsAt||!await s.pointsAt(t)||await s.usesDynamicCredential?.(t))continue;r+=1,(await s.apply(e,{dryRun:!1})).status==="configured"?o+=1:a=!1}catch{a=!1}return{matched:r,rewritten:o,complete:a}},Ri=async(e,t=e.origin,n=ie)=>(await dm(e,t,n)).complete;var GF=["claude","codex","cursor","opencode"],jF=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],VF=new Set(["missing_key","key_expired"]);var YF=600*1e3,ZF=600*1e3,hS=1440*60*1e3,JF=1440*60*1e3,XF=10080*60*1e3,qF=3600*1e3,zF=720*60*1e3,QF=e=>Math.min(zF,qF*2**Math.max(0,e-1)),Oi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Oa=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,mS=e=>typeof e=="string"&&jF.includes(e),xn=e=>{if(!Oi(e))return{};let t={};if(Oa(e.watchSince)&&(t.watchSince=e.watchSince),Oi(e.invoked)){let n={};for(let r of GF){let o=e.invoked[r];Oa(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return Oi(e.authFailure)&&Oa(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...mS(e.authFailure.code)?{code:e.authFailure.code}:{}}),Oi(e.repair)&&Oa(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,...Oa(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Td=e=>{try{let n=JSON.parse(e);if(Oi(n)&&mS(n.code)&&n.code!=="key_invalid")return n.code}catch{}let t=e.toLowerCase();if(t.includes("valid client key required"))return"key_invalid";if(t.includes("client key required"))return"missing_key"},um=e=>e!==void 0&&VF.has(e),pm=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=YF},yS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),fm=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=ZF},gS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),wS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,bS=(e,t,n)=>{if(n==="repair_failed"||n==="unverified")return{...e,repair:{at:t,outcome:n,failures:(e.repair?.failures??0)+1}};let{authFailure:r,...o}=e;return n==="repaired"?{...o,repair:{at:t,outcome:n}}:o},kS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>hS||!um(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<QF(r.failures??1))},Dd=e=>{let t=Object.values(e?.invoked??{}).filter(Oa);return t.length>0?Math.max(...t):null},hm=(e,t)=>{if(Dd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=XF},CS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=JF)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=hS)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var mm="x-anyray-retrieve-probe",Ld=8e3,eB=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",AS=(e,t)=>{let n=Qt(e);return t?.probe&&(n[mm]="1"),n},_a=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(),Ld);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:AS(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=eB(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)}},Nd=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(),Ld);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:AS(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 tB=5e3,nB=2048,rB=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}"`))},Pa=async(e={})=>{let t=e.readTarget??at,n=e.fetch??fetch,r=e.timeoutMs??tB,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=Qt(o);i["content-type"]="application/json",i[mm]="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,nB);if(!rB(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Td(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)}},ym=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{createPrivateKey as oB,randomBytes as aB,sign as sB}from"node:crypto";var iB=500,vS=2e3,cB=2e3,lB=250,SS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),iB);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)}},dB=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},uB=e=>new Promise(t=>setTimeout(t,e)),pB=async(e,t,n=uB)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),vS),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=dB(i)??lB,s>cB))return!1}finally{clearTimeout(a)}await n(s)}},fB=async e=>{try{let n=(await L()).enrolledCert,r=await We(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:aB(16).toString("hex"),events:e},s;try{let i=oB(r),c=new TextEncoder().encode(Co(a));s=sB(null,c,i).toString("base64url")}catch{return!1}return await pB(`${qn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},hB=async(e,t)=>{try{let r=(await L()).enrolledCert,o=await We();if(!r||!o)return;await dn(e,r,o,{timeoutMs:vS,health:{events:t},telemetryOnly:!0})}catch{}},ES=async(e,t)=>{if(e.length!==0)try{let n=await at(),r=n&&await SS(n.origin,Qt(n),e,t);if(n&&await hB(n.origin,e),r)return;await fB(e)}catch{}},gm=async(e,t,n={readTarget:()=>at("profile"),post:SS})=>{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 vo=["hook_registration","mcp_registration","hook_binary","beacon_target"];var xS=128,RS=300*1e3,mB=["repaired","repair_failed","flapping","pending"],yB=["settings_not_writable","apply_unconfirmed","apply_threw"],OS=["rebroke_same_day","repeat_days"],_S=new Set(ie.map(e=>e.id)),Ao=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),PS=e=>Pi(e,vo),$d=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},_r=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,_i=e=>{if(!(!Array.isArray(e)||!e.every(PS)))return zn(e)},gB=e=>{if(!Ao(e))return;let t=_i(e.checks);if(!(!_r(e.since)||!Pi(e.reason,OS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},wB=e=>{if(!Ao(e))return;let t={};$d(e.day)&&(t.day=e.day),_r(e.attempts)&&(t.attempts=e.attempts);let n=_i(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=_i(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=_i(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=_i(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),$d(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),_r(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),Ao(e.lastRepaired)){let i={};for(let c of vo){let l=e.lastRepaired[c];_r(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=gB(e.flapping);return s&&(t.flapping=s),t},bB=e=>{if(!Ao(e)||!$d(e.day)||!_r(e.sequence)||e.sequence===0||typeof e.tool!="string"||!_S.has(e.tool)||!PS(e.checkId)||!Pi(e.status,mB)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!Pi(e.errorClass,yB))return;t=e.errorClass}else if(e.status==="flapping"){if(!Pi(e.errorClass,OS))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,..._r(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},IS=e=>{if(!Ao(e))return{};let t={};if(Ao(e.adapters)){let n={};for(let r of _S){let o=wB(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(bB).filter(n=>n!==void 0).slice(-xS)),_r(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Ao(e.report)&&$d(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,..._r(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},kB=e=>new Date(e).toISOString().slice(0,10),CB=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,zn=e=>[...new Set(e)],Md=(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}:{}}},Ti=(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(-xS),nextSequence:r}},AB=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),vB=async e=>await Oe(async()=>e,void 0,be)??null,SB=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=Md(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)},TS=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:CB(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:zn([...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:zn([...i?.checks??[],...t])}}:{}},slowFlap:a}},EB=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=Md(d,n),f=u.awaiting??[],p=a.get(l);if(f.length===0||t.has(l)||!p){c[l]=u;continue}let h=f.filter(y=>p.checks[y]==="owned"),m=f.filter(y=>{let b=p.checks[y];return b==="missing"||b==="foreign"}),w=f.filter(y=>{let b=p.checks[y];return b===void 0||b==="unreadable"}),g=TS(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=Ti(i,n,[...h.map(y=>({tool:l,checkId:y,status:"repaired"})),...m.map(y=>({tool:l,checkId:y,status:"repair_failed",errorClass:"apply_unconfirmed"})),...g.slowFlap?h.map(y=>({tool:l,checkId:y,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},IB=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Md(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(g=>!d.includes(g)||u.includes(g)),p=f.filter(g=>u.includes(g)),h=l.attempts??0;if(h>=2||f.length===0&&!n){let g=p.filter(A=>!(l.brokenReportedChecks??[]).includes(A));if(g.length===0)return{result:void 0};let y=l.flapping;return c[e]={...l,brokenReportedChecks:zn([...l.brokenReportedChecks??[],...g]),flapping:{since:y?.since??a,reason:"rebroke_same_day",checks:zn([...y?.checks??[],...g])}},{next:Ti({...i,adapters:c},o,g.map(A=>({tool:e,checkId:A,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let m=l.flapping;return c[e]={...l,attempts:h+1,attemptedChecks:zn([...d,...f]),confirmedChecks:u.filter(g=>!f.includes(g)),brokenReportedChecks:zn([...l.brokenReportedChecks??[],...p]),...p.length>0?{flapping:{since:m?.since??a,reason:"rebroke_same_day",checks:zn([...m?.checks??[],...p])}}:{}},{next:Ti({...i,adapters:c},o,p.map(g=>({tool:e,checkId:g,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),xB=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Md(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:zn([...l.awaiting??[],...t])},{next:Ti({...i,adapters:c},o,t.map(h=>({tool:e,checkId:h,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(h=>r[h]==="owned"):[],u=n.status==="configured"&&r?t.filter(h=>{let m=r[h];return m==="missing"||m==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=TS(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:Ti({...i,adapters:c},o,[...d.map(h=>({tool:e,checkId:h,status:"repaired"})),...u.map(h=>({tool:e,checkId:h,status:"repair_failed",errorClass:p})),...f.slowFlap?d.map(h=>({tool:e,checkId:h,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},RB=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>=RS));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??gm)(o.map(AB),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)},OB=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:f}of t){let p=r.adapters?.[u.id];for(let h of vo){let m=f[h];if(!m||m==="unreadable")continue;let w,g;p?.awaiting?.includes(h)&&c.has(u.id)?w="pending":m==="missing"&&p?.flapping?.checks.includes(h)?(w="flapping",g=p.flapping.reason):w=m==="owned"?"ok":m,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:h,status:w,...g?{errorClass:g}:{}})}}let l=Date.parse(e.enrolledCert?.payload.expiresAt??e.enrolledCertExpiry??"");e.enrolledCert&&Number.isFinite(l)&&(l<=o?(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"expired"})):l-o<=336*60*60*1e3&&(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"problems",errorClass:"cert_expiring"}))),e.refreshSchedulerEnabled&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Jo)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??wr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=CS(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},_B=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<RS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await OB(e,t,n,c,o,s);await(s.report??gm)(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)},DS=async(e,t,n)=>{let r=n.now??Date.now,o=kB(r()),a=e.managedTools??[],s={...n,readState:async()=>IS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(IS(l)),c)};try{let i=await(s.findIntegrations??om)(a);await SB(i,o,s);let c=await(s.listPending??yr)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await EB(i,l,o,r(),s);let d=await(s.resolveTarget??vB)(e),u=d?await(s.findDrifted??Rr)(a,d.toolOrigin):[],f=new Set(u.map(g=>g.id)),p=new Map(i.map(g=>[g.adapter.id,g]));for(let g of u)p.has(g.id)||p.set(g.id,{adapter:g,checks:{}});let h=!1,m=(s.runtimeDurable??le)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?vo.filter(P=>y[P]==="missing"):[];if(b.length===0&&!f.has(g.id))continue;let A=y;if(g.integrationStatus)try{A=await g.integrationStatus()}catch{A=Object.fromEntries(vo.map(P=>[P,"unreadable"]))}let v=b.filter(P=>A[P]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),v.length===0&&!E)continue;let I=await IB(g.id,v,E,l.has(g.id),o,r(),s);if(!I)continue;let[C]=await(s.repair??wt)([g],d.target);if(!C)continue;h=!0;let x;C.status==="configured"&&g.integrationStatus&&(x=await g.integrationStatus().catch(()=>{})),await xB(g.id,I.checks,C,x,o,r(),s)}await RB(o,r(),t,s),i=await(s.findIntegrations??om)(a);let w=await(s.listPending??yr)().catch(()=>[]);return await _B(e,i,w,o,r(),t,s),h}catch{return!1}};var UB=14,FB=.35,BB=900*1e3,NS=360*60*1e3,WB=.2,HB=1800*1e3,$S=3600*1e3,KB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),GB=300*1e3,jB=30*1e3,VB=900*1e3,YB=(e=0)=>Math.min(VB,jB*2**Math.max(0,e)),MS=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}},ZB=720*60*1e3,US=1440*60*1e3,JB=300*1e3,XB=.25,qB=.5,FS=3600*1e3,zB=720*60*60*1e3,QB=360*60*1e3,e1=1440*60*1e3,t1=4,Ud=e=>DB("sha256").update(e).digest("hex").slice(0,32),VS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Gt)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??L)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(Ud(e))},wm=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,t1)}),n1=()=>GS(LB(),".anyray"),km=()=>GS(n1(),"refresh-state.json"),Cm=e=>process.env?.[e],YS=()=>Cm("ANYRAY_REFRESH_DISABLE")==="true",Am=()=>{let e=Cm("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:UB)*e1},Li=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},ZS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),r1=10080*60*1e3,Fd=(e,t,n=Date.now())=>{let r=[],o=Li(e);o!==void 0&&r.push(o);let a=Date.parse(t??e.clientKeyExpiresAt??"");Number.isFinite(a)&&r.push(a-n);let s=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??"");return Number.isFinite(s)&&r.push(s-n),r.length===0?!1:Math.min(...r)<=r1},Ni=e=>{let t=Am(),n=e?Li(e):void 0;if(!n)return t;let r=Math.max(BB,Math.round(n*FB));return Math.min(t,r)},o1=e=>{let t=Cm("ANYRAY_REFRESH_THROTTLE_MS"),n=t?Number.parseInt(t,10):NaN;return Number.isFinite(n)&&n>0?n:typeof e=="number"&&Number.isFinite(e)&&e>0?Math.min(NS,Math.max(HB,Math.round(e*WB))):NS},Gt=async()=>{try{let e=await NB(km(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Bd=async e=>{try{let t=km(),n=`${t}.${process.pid}.tmp`;await jS(n,JSON.stringify(e),{mode:384}),await he(n,t),await $B(t,384).catch(()=>{})}catch{}},a1=3e4,s1=()=>`${km()}.lock`,BS=async e=>{try{return await jS(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},pt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Gt,a=n.writeState??Bd,s=s1(),i=!1;try{if(i=await BS(s),!i){if(await MB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<a1)return t;await LS(s).catch(()=>{}),i=await BS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await LS(s).catch(()=>{})}},Di=async(e,t={})=>{await pt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Ta=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0),a=await(t.loadProfile??L)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?Ud(a.clientKey):void 0;await pt(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:wm(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},So=async(e={})=>{let t=e.now??Date.now;await pt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},i1=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(zB,Math.max(FS,Math.round(o*qB))):FS},bm=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,vm=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??oe,a=n.loadProfile??L,s=n.loadDevKey??We,i=n.renew??fS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(pS(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()>i1(e))return{outcome:"not-due",profile:e};if(!await pt(w=>r()-(w.lastCertRenewAt??0)<QB?{result:!1}:{next:{...w,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await bm(f,c.sig,t,s))return{outcome:"superseded",profile:f};let p=u.cert.payload.expiresAt,h=Date.parse(p)-r(),m={...f,enrolledCert:u.cert,enrolledCertExpiry:p,...Number.isFinite(h)&&h>0?{enrolledCertLifetimeMs:h}:{}};return await o(m),{outcome:"renewed",profile:m}},WS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*XB):US,r=Math.min(US,n);return Math.min(r,JB*2**Math.max(0,e-1))},c1=()=>{let{command:e,args:t}=hn(ir);return{exe:e,args:t}},Pr=async(e={})=>{if(YS())return;let t=e.now??Date.now,n=e.readState??Gt,r=e.writeState??Bd,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=c1();TB(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await pt(s=>t()-(s.lastSpawnAt??0)<o1(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},l1=Ri,d1=async(e,t=be,n=!1)=>{try{let r=e.managedTools??[];if(r.length===0)return!1;let o=await Oe(async()=>e,void 0,t);if(!o)return!1;let a=await Rr(r,o.toolOrigin),s=n?Xv(a):a;return s.length===0?!1:(await wt(s,o.target),!0)}catch{return!1}},u1=async(e,t,n,r,o,a)=>{try{let s=new Set(e.managedTools??[]),i=ie.filter(p=>s.has(p.id));if(i.length===0)return!1;let c=await r().catch(()=>{}),l=ge({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:c,user:e.name,team:e.team}),d=e.fallbackPort,u=ot(e)&&Number.isInteger(d)&&d>0&&d<=65535&&await o(d)!==null,f=await a(u?_n(l,d):l,u?`http://${mt}:${d}`:l.origin,i);return f.matched>0&&f.complete}catch{return!1}},p1=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Gt,a=t.writeState??Bd;return DS(e,we,{now:r,deadWatcherObserved:n,readHookLane:()=>Wd({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>pt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Wd=async(e={})=>{let n=await(e.readState??Gt)().catch(()=>({}));return xn(n.hookLane)},JS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Wd(t);if(!pm(r,e,n()))return;await pt(o=>{let a=xn(o.hookLane);return pm(a,e,n())?{next:{...o,hookLane:yS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},XS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Wd(t);if(!fm(r,n()))return;await pt(o=>{let a=xn(o.hookLane);return fm(a,n())?{next:{...o,hookLane:gS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},f1=async(e={})=>{try{let t=e.now??Date.now;if((await Wd(e)).watchSince!==void 0)return;await pt(n=>{let r=xn(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:wS(r,t())},result:void 0}},void 0,e)}catch{}},HS=async(e,t={})=>{try{let n=t.now??Date.now;await pt(r=>{let o=xn(r.hookLane),a=bS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},qS=async(e={})=>{try{if((await(e.readState??Gt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>pt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??Wg)())return await r()?"stamped":"skipped";let o=await(e.load??L)(),s=await(e.findTools??ko)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Oe(async()=>o,void 0,e.probe??be);return!i||!await r()?"skipped":(await(e.repair??wt)(s,i.target),"repathed")}catch{return"skipped"}},zS=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Gt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>pt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??L)(),i=await(e.findTools??ko)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Oe(async()=>a,void 0,e.probe??be);return!c||!await o()?"skipped":(await(e.repair??wt)(i,c.target)).some(d=>d.status==="failed")?(await pt(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"}},h1=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await Rd(e.gateway,e.clientKey),n=await Od(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},KS=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??h1)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>d1(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},nt=async(e={})=>{if(YS())return"disabled";let t=e.now??Date.now,n=e.loadProfile??L,r=e.saveProfile??oe,o=e.loadDevKey??We,a=e.readState??Gt,s=e.writeState??Bd,i=e.remint??dn,c=e.heartbeat??Pd,l=e.detectSeat??$t,d=e.rewriteTools??l1,u=e.rewriteHookLaneTools??dm,f=e.probeHookLane??Pa,p=e.classifyBeacon??Oc,h=e.probe??be,m=e.installProxy??Nt,w=e.pickProxyPort??Lc,g=e.force===!0,y=!1,b=!1,A=!1,v=!1;e.hookLaneRepair===!0&&(g=!0,v=!0);let E=async C=>{if(!v){C==="repaired"&&await HS("none",{now:t,readState:a,writeState:s});return}let x=C;if(C==="repaired"){let P=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));x=P.verdict==="live"?"repaired":P.verdict==="dark"?"repair_failed":"unverified"}await HS(x,{now:t,readState:a,writeState:s})},I=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(P=>p1(P,{now:t,readState:a,writeState:s},A)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(A=await yr().then(O=>O.some(T=>!wr(T.watcherPid))).catch(()=>!1),await f1({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??Cb)();let C=await n();if(y=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let x=C.gateway,P=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(P)||P<=t())return"cert-expired";let $=await o();if(!$)return"not-enrolled";let Y=await vm(C,$,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=Y.profile;let Z=Y.outcome==="renewed",W=C.enrolledCert;if(!W)return"not-enrolled";let z=Date.parse(C.clientKeyExpiresAt??""),me=Number.isFinite(z)?z-t():0,Te=await a(),re=!C.clientKey||me<=Ni(C),Ke=C.credentialProtocol!=="stable-heartbeat-v1"&&t()-(Te.lastSuccessAt??0)>=ZB;if(!g&&kS(xn(Te.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,v=!0),C.credentialProtocol==="stable-heartbeat-v1"&&C.clientKey&&(g||re)){let O=await pt(T=>{let H=t()-(T.lastAttemptAt??0);return H<$S?{result:"throttled"}:T.failureCount&&H<WS(T.failureCount,T.keyTtlMs)?{result:"backoff"}:{next:{...T,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(O!=="ok")return O;try{let T=await c(x,C.clientKey,W,$),H=await n().catch(()=>C);return H.clientKey!==C.clientKey||H.enrolledCert?.sig!==W.sig?"failed":(await r({...H,clientKeyExpiresAt:T.expiresAt}),await Di(({lastError:fe,...Q})=>({...Q,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Li(C)??Q.keyTtlMs}),{now:t,readState:a,writeState:s}),v&&await E(await u1(C,x,C.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(T){let H=T;if(T instanceof Or&&T.status===404)try{let Q=await i(x,W,$),Ze=await l().catch(()=>{}),Fe=ge({origin:x,clientKey:Q.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Ze,user:C.name,team:C.team}),te=C.fallbackPort,Be=Number.isInteger(te)&&te>0&&te<=65535?te:await w();if(!(await m({port:Be,remoteOrigin:x})).ok||await h(Be)===null)throw new Error("key-refresh proxy recovery failed");let Xt=await n().catch(()=>C);if(!await bm(Xt,W.sig,$,o))throw new Error("enrollment changed during proxy recovery");if(await r({...Xt,clientKey:Q.key,clientKeyExpiresAt:Q.expiresAt??Xt.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:Be}),await d(_n(Fe,Be),Fe.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let V=Q.expiresAt?Date.parse(Q.expiresAt):NaN,Ne=Li(C)??(Number.isFinite(V)&&V-t()>0?V-t():void 0);return await Di(({lastError:nr,...ht})=>({...ht,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ne??ht.keyTtlMs,ownKeys:wm(ht.ownKeys,W.sig,Ud(Q.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(Q){H=Q}let fe=MS(H);return await Di(Q=>({...Q,lastAttemptAt:t(),failureCount:(Q.failureCount??0)+1,lastError:{name:H instanceof Error?H.name:"Error",...fe!==void 0?{code:fe}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),H instanceof Or?"cert-rejected":"failed"}}if(!g&&C.clientKey&&!re&&!Ke){let O=await KS(C,e,n,h),T=await I();return O||T?"repaired":Z?"cert-renewed":"not-due"}let De=await pt(O=>{let T=t()-(O.lastAttemptAt??0);if(g)return T<YB(O.failureCount)?{result:"throttled"}:{next:{...O,lastAttemptAt:t()},result:"ok"};let H=O.lastError?.code!==void 0&&KB.has(O.lastError.code)?GB:$S;return T<H?{result:"throttled"}:O.failureCount&&T<WS(O.failureCount,O.keyTtlMs)?{result:"backoff"}:{next:{...O,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(De!=="ok")return De;try{let O=await i(x,W,$),T=await l().catch(()=>{}),H=ge({origin:x,clientKey:O.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:T,user:C.name,team:C.team}),fe=H,Q=H.origin;if(ot(C)){if(!Number.isInteger(C.fallbackPort)||C.fallbackPort<1||C.fallbackPort>65535)throw new Error("key-refresh proxy profile has no valid port");await h(C.fallbackPort)!==null&&(fe=_n(H,C.fallbackPort),Q=`http://${mt}:${C.fallbackPort}`)}let Ze=await d(fe,Q);if(C.directMigration==="pending"&&fe.viaLocalProxy===!0){let V=await d(fe,H.origin);Ze=Ze!==!1&&V!==!1}if(Ze===!1)throw new Error("one or more configured tools rejected the refreshed key");let Fe=await n().catch(()=>C),te=null,Be;Fe.enrolledCert&&await bm(Fe,W.sig,$,o)&&(Be=Ud(O.key),te={...Fe,clientKey:O.key,clientKeyExpiresAt:O.expiresAt??Fe.clientKeyExpiresAt},await r(te));let Le=O.expiresAt?Date.parse(O.expiresAt):NaN,Xt=Li(C)??(Number.isFinite(Le)&&Le-t()>0?Le-t():void 0);return await Di(({lastError:V,...Ne})=>({...Ne,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Xt??Ne.keyTtlMs,...Be?{ownKeys:wm(Ne.ownKeys,W.sig,Be)}:{}}),{now:t,readState:a,writeState:s}),te&&await KS(te,e,n,h),await E(te?"repaired":"repair_failed"),await I(),"refreshed"}catch(O){let T=MS(O);return await Di(H=>({...H,lastAttemptAt:t(),failureCount:(H.failureCount??0)+1,lastError:{name:O instanceof Error?O.name:"Error",...T!==void 0?{code:T}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),O instanceof Ot?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await I()}catch{}}};import{readFile as C1}from"node:fs/promises";import{isAbsolute as A1,posix as rE,win32 as Im}from"node:path";var Sm=1e4,m1=900*1e3,eE="tnt_",y1=/^\/sso\/([^/]+)\/?$/,g1=/^\/i\/([^/]+)\/?$/,w1=e=>{let t=e.match(y1);if(t)return t[1];let n=e.match(g1);return n?.[1].startsWith(eE)?n[1]:void 0},_t=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=w1(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(eE))return{cpOrigin:qn(),tenantId:t}},Eo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},jt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},Em=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)}},b1=e=>new Promise(t=>setTimeout(t,e)),Hd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??_d)(),a;try{a=await Em(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},Sm,n)}catch(h){throw new Eo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${bt(h)}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new Eo(h?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${m}). Ask your admin to confirm SSO is configured.`,a.status)}let s=a.json;if(!s.device_code||!s.user_code||!s.verification_uri_complete)throw new Eo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??m1,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}`),k1(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},k1=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Kd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??b1,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 Em(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},Sm,o)}catch(c){throw new jt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${bt(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 jt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new jt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new jt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var QS="sdc_",tE=e=>{let t=e.trim();if(!t)return;if(t.startsWith(QS))return{cpOrigin:qn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!lm(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(QS)))return{cpOrigin:n.origin,claim:r}},nE=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??_d)(),o;try{o=await Em(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},Sm,t)}catch(s){throw new jt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${bt(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 jt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new jt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new jt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};var $i=(e=process.platform,t=process.env)=>e==="darwin"?rE.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?Im.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):rE.join("/etc","anyray","bootstrap.json"),v1=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),oE=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(A1(e)||Im.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),S1=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}},Vt=async(e=$i())=>{try{let t=await C1(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!v1(n)||n.v!==1||typeof n.sso!="string")return;let r=_t(n.sso);if(!r)return;let o=S1(n.gateway)?n.gateway:void 0,a=oE(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},aE=(e,t,n)=>{let r=_t(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!oE(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&Im.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)}
|
|
301
|
-
`};import{execFile as J1}from"node:child_process";import{chmod as E1,readFile as
|
|
302
|
-
`,{mode:384}),await E1(n,384),await he(n,t)}catch(r){throw await sE(n,{force:!0}).catch(()=>{}),r}},iE=async()=>{await sE(
|
|
300
|
+
`;import{createHash as AF,createPrivateKey as vF,generateKeyPairSync as SF,randomBytes as sm,sign as EF}from"node:crypto";var im=1e4,Co=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Co).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Co(e[n])}`).join(",")}}`,Ii="stable-key-heartbeat-v1",iS="key-heartbeat",xF=["reapply_config","remint","revert"];var cS=e=>AF("sha256").update(e).digest("hex"),tt=e=>typeof e=="string"&&e.trim()?e.trim():void 0,IF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],cm=async e=>{try{let t=await e.json(),n=tt(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},Ot=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Or=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},lm=(e,t,n)=>{try{let r=vF(t),o=new TextEncoder().encode(Co(e));return EF(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Pd=()=>{let{publicKey:e,privateKey:t}=SF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},dn=async(e,t,n,r={})=>{let o=r.timeoutMs??im,a=`${e}/connect/verify`,s=tt(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:sm(16).toString("hex")},c=lm(i,n,"verification"),l=new AbortController,d=setTimeout(()=>l.abort(),o),u;try{u=await fetch(a,{method:"POST",headers:{"content-type":"application/json","x-anyray-connect-version":we},body:JSON.stringify({cert:t,challenge:i,sig:c,...r.health?{health:r.health}:{},...r.ack?{ack:r.ack}:{},...r.telemetryOnly?{telemetryOnly:!0}:{}}),signal:l.signal})}catch(y){let b=y instanceof Error&&y.name==="AbortError"?` no response within ${o}ms.`:bt(y);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:y})}finally{clearTimeout(d)}if(!u.ok)throw new Ot(u.status,await cm(u));let f;try{f=await u.text()}catch{f=""}let p;try{p=JSON.parse(f)}catch{let y=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(y)||/^\s*<(?:!doctype|html)/i.test(f);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let h=tt(p?.key);if(!h)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(h))throw new Error("developer verification failed: the gateway returned a malformed key");let m=tt(p.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=RF(p.directive),g=IF(p.capabilities);return{key:h,user:m,team:tt(p.team),expiresAt:tt(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},Td=async(e,t,n,r,o={})=>{let a=o.timeoutMs??im,s=`${e}/connect/key/heartbeat`,i=tt(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:sm(16).toString("hex"),purpose:iS},l=lm(c,r,"heartbeat"),d=new AbortController,u=setTimeout(()=>d.abort(),a),f;try{f=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(m){let w=m instanceof Error&&m.name==="AbortError"?` no response within ${a}ms.`:bt(m);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:m})}finally{clearTimeout(u)}if(!f.ok)throw new Or(f.status,await cm(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=tt(p.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||p.credentialMode!==Ii||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:Ii}},lS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??im,i=`${e.replace(/\/$/,"")}/connect/machine`,c=tt(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:sm(16).toString("hex"),purpose:iS},d=lm(l,r,"heartbeat"),u=new AbortController,f=setTimeout(()=>u.abort(),s);try{return(await fetch(i,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":we},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(p){return console.error("connect machine report skipped:",p instanceof Error?p.name:"error"),!1}finally{clearTimeout(f)}},RF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=tt(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!xF.includes(r)?null:{id:n,kind:r}},OF=1e4,_F=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!tt(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!tt(r.deploymentId)&&!!tt(r.user)&&!!tt(r.devPublicKey)&&!!tt(r.issuedAt)&&!!tt(r.expiresAt)},PF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??OF,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.`:bt(u);throw new Error(`could not reach the control plane at ${s}.${f}`)}finally{clearTimeout(c)}if(!l.ok)throw new Error(`enrollment failed: ${await cm(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!_F(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},dS=(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())},uS=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=Pd();return{cert:await PF(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),privateKeyPem:s.privateKeyPem,publicKeyPem:s.publicKeyPem}})(),a=await dn(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};import{createPrivateKey as MF,randomBytes as UF,sign as FF}from"node:crypto";var TF="https://app.anyray.ai",DF=new Set(["localhost","::1","[::1]"]),LF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,NF=e=>DF.has(e)||LF.test(e),dm=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&NF(t.hostname)},$F=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},qn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!dm(e)?TF:$F(e)};var BF=1e4,WF="machine:",pS=e=>e.startsWith(WF),HF="cert-renew",KF=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)},fS=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??qn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:UF(16).toString("hex"),purpose:HF},c;try{let h=MF(t),m=new TextEncoder().encode(Co(i));c=FF(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),BF),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 KF(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var um=async(e,t=e.origin,n=ie)=>{let r=0,o=0,a=!0;for(let s of n)try{if(!s.pointsAt||!await s.pointsAt(t)||await s.usesDynamicCredential?.(t))continue;r+=1,(await s.apply(e,{dryRun:!1})).status==="configured"?o+=1:a=!1}catch{a=!1}return{matched:r,rewritten:o,complete:a}},Ri=async(e,t=e.origin,n=ie)=>(await um(e,t,n)).complete;var GF=["claude","codex","cursor","opencode"],jF=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],VF=new Set(["missing_key","key_expired"]);var YF=600*1e3,ZF=600*1e3,hS=1440*60*1e3,JF=1440*60*1e3,XF=10080*60*1e3,qF=3600*1e3,zF=720*60*1e3,QF=e=>Math.min(zF,qF*2**Math.max(0,e-1)),Oi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Oa=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,mS=e=>typeof e=="string"&&jF.includes(e),In=e=>{if(!Oi(e))return{};let t={};if(Oa(e.watchSince)&&(t.watchSince=e.watchSince),Oi(e.invoked)){let n={};for(let r of GF){let o=e.invoked[r];Oa(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return Oi(e.authFailure)&&Oa(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...mS(e.authFailure.code)?{code:e.authFailure.code}:{}}),Oi(e.repair)&&Oa(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,...Oa(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Dd=e=>{try{let n=JSON.parse(e);if(Oi(n)&&mS(n.code)&&n.code!=="key_invalid")return n.code}catch{}let t=e.toLowerCase();if(t.includes("valid client key required"))return"key_invalid";if(t.includes("client key required"))return"missing_key"},pm=e=>e!==void 0&&VF.has(e),fm=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=YF},yS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),hm=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=ZF},gS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),wS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,bS=(e,t,n)=>{if(n==="repair_failed"||n==="unverified")return{...e,repair:{at:t,outcome:n,failures:(e.repair?.failures??0)+1}};let{authFailure:r,...o}=e;return n==="repaired"?{...o,repair:{at:t,outcome:n}}:o},kS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>hS||!pm(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<QF(r.failures??1))},Ld=e=>{let t=Object.values(e?.invoked??{}).filter(Oa);return t.length>0?Math.max(...t):null},mm=(e,t)=>{if(Ld(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=XF},CS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=JF)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=hS)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var ym="x-anyray-retrieve-probe",Nd=8e3,eB=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",AS=(e,t)=>{let n=Qt(e);return t?.probe&&(n[ym]="1"),n},_a=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(),Nd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:AS(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=eB(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)}},$d=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(),Nd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:AS(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 tB=5e3,nB=2048,rB=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}"`))},Pa=async(e={})=>{let t=e.readTarget??at,n=e.fetch??fetch,r=e.timeoutMs??tB,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=Qt(o);i["content-type"]="application/json",i[ym]="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,nB);if(!rB(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Dd(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)}},gm=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{createPrivateKey as oB,randomBytes as aB,sign as sB}from"node:crypto";var iB=500,vS=2e3,cB=2e3,lB=250,SS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),iB);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)}},dB=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},uB=e=>new Promise(t=>setTimeout(t,e)),pB=async(e,t,n=uB)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),vS),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=dB(i)??lB,s>cB))return!1}finally{clearTimeout(a)}await n(s)}},fB=async e=>{try{let n=(await L()).enrolledCert,r=await We(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:aB(16).toString("hex"),events:e},s;try{let i=oB(r),c=new TextEncoder().encode(Co(a));s=sB(null,c,i).toString("base64url")}catch{return!1}return await pB(`${qn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},hB=async(e,t)=>{try{let r=(await L()).enrolledCert,o=await We();if(!r||!o)return;await dn(e,r,o,{timeoutMs:vS,health:{events:t},telemetryOnly:!0})}catch{}},ES=async(e,t)=>{if(e.length!==0)try{let n=await at(),r=n&&await SS(n.origin,Qt(n),e,t);if(n&&await hB(n.origin,e),r)return;await fB(e)}catch{}},wm=async(e,t,n={readTarget:()=>at("profile"),post:SS})=>{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 vo=["hook_registration","mcp_registration","hook_binary","beacon_target"];var IS=128,RS=300*1e3,mB=["repaired","repair_failed","flapping","pending"],yB=["settings_not_writable","apply_unconfirmed","apply_threw"],OS=["rebroke_same_day","repeat_days"],_S=new Set(ie.map(e=>e.id)),Ao=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),PS=e=>Pi(e,vo),Md=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},_r=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,_i=e=>{if(!(!Array.isArray(e)||!e.every(PS)))return zn(e)},gB=e=>{if(!Ao(e))return;let t=_i(e.checks);if(!(!_r(e.since)||!Pi(e.reason,OS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},wB=e=>{if(!Ao(e))return;let t={};Md(e.day)&&(t.day=e.day),_r(e.attempts)&&(t.attempts=e.attempts);let n=_i(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=_i(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=_i(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=_i(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Md(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),_r(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),Ao(e.lastRepaired)){let i={};for(let c of vo){let l=e.lastRepaired[c];_r(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=gB(e.flapping);return s&&(t.flapping=s),t},bB=e=>{if(!Ao(e)||!Md(e.day)||!_r(e.sequence)||e.sequence===0||typeof e.tool!="string"||!_S.has(e.tool)||!PS(e.checkId)||!Pi(e.status,mB)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!Pi(e.errorClass,yB))return;t=e.errorClass}else if(e.status==="flapping"){if(!Pi(e.errorClass,OS))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,..._r(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},xS=e=>{if(!Ao(e))return{};let t={};if(Ao(e.adapters)){let n={};for(let r of _S){let o=wB(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(bB).filter(n=>n!==void 0).slice(-IS)),_r(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Ao(e.report)&&Md(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,..._r(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},kB=e=>new Date(e).toISOString().slice(0,10),CB=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,zn=e=>[...new Set(e)],Ud=(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}:{}}},Ti=(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(-IS),nextSequence:r}},AB=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),vB=async e=>await Oe(async()=>e,void 0,be)??null,SB=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=Ud(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)},TS=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:CB(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:zn([...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:zn([...i?.checks??[],...t])}}:{}},slowFlap:a}},EB=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=Ud(d,n),f=u.awaiting??[],p=a.get(l);if(f.length===0||t.has(l)||!p){c[l]=u;continue}let h=f.filter(y=>p.checks[y]==="owned"),m=f.filter(y=>{let b=p.checks[y];return b==="missing"||b==="foreign"}),w=f.filter(y=>{let b=p.checks[y];return b===void 0||b==="unreadable"}),g=TS(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=Ti(i,n,[...h.map(y=>({tool:l,checkId:y,status:"repaired"})),...m.map(y=>({tool:l,checkId:y,status:"repair_failed",errorClass:"apply_unconfirmed"})),...g.slowFlap?h.map(y=>({tool:l,checkId:y,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},xB=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Ud(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(g=>!d.includes(g)||u.includes(g)),p=f.filter(g=>u.includes(g)),h=l.attempts??0;if(h>=2||f.length===0&&!n){let g=p.filter(A=>!(l.brokenReportedChecks??[]).includes(A));if(g.length===0)return{result:void 0};let y=l.flapping;return c[e]={...l,brokenReportedChecks:zn([...l.brokenReportedChecks??[],...g]),flapping:{since:y?.since??a,reason:"rebroke_same_day",checks:zn([...y?.checks??[],...g])}},{next:Ti({...i,adapters:c},o,g.map(A=>({tool:e,checkId:A,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let m=l.flapping;return c[e]={...l,attempts:h+1,attemptedChecks:zn([...d,...f]),confirmedChecks:u.filter(g=>!f.includes(g)),brokenReportedChecks:zn([...l.brokenReportedChecks??[],...p]),...p.length>0?{flapping:{since:m?.since??a,reason:"rebroke_same_day",checks:zn([...m?.checks??[],...p])}}:{}},{next:Ti({...i,adapters:c},o,p.map(g=>({tool:e,checkId:g,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),IB=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Ud(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:zn([...l.awaiting??[],...t])},{next:Ti({...i,adapters:c},o,t.map(h=>({tool:e,checkId:h,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(h=>r[h]==="owned"):[],u=n.status==="configured"&&r?t.filter(h=>{let m=r[h];return m==="missing"||m==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=TS(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:Ti({...i,adapters:c},o,[...d.map(h=>({tool:e,checkId:h,status:"repaired"})),...u.map(h=>({tool:e,checkId:h,status:"repair_failed",errorClass:p})),...f.slowFlap?d.map(h=>({tool:e,checkId:h,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},RB=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>=RS));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??wm)(o.map(AB),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)},OB=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:f}of t){let p=r.adapters?.[u.id];for(let h of vo){let m=f[h];if(!m||m==="unreadable")continue;let w,g;p?.awaiting?.includes(h)&&c.has(u.id)?w="pending":m==="missing"&&p?.flapping?.checks.includes(h)?(w="flapping",g=p.flapping.reason):w=m==="owned"?"ok":m,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:h,status:w,...g?{errorClass:g}:{}})}}let l=Date.parse(e.enrolledCert?.payload.expiresAt??e.enrolledCertExpiry??"");e.enrolledCert&&Number.isFinite(l)&&(l<=o?(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"expired"})):l-o<=336*60*60*1e3&&(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"problems",errorClass:"cert_expiring"}))),e.refreshSchedulerEnabled&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Jo)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??wr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=CS(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},_B=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<RS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await OB(e,t,n,c,o,s);await(s.report??wm)(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)},DS=async(e,t,n)=>{let r=n.now??Date.now,o=kB(r()),a=e.managedTools??[],s={...n,readState:async()=>xS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(xS(l)),c)};try{let i=await(s.findIntegrations??am)(a);await SB(i,o,s);let c=await(s.listPending??yr)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await EB(i,l,o,r(),s);let d=await(s.resolveTarget??vB)(e),u=d?await(s.findDrifted??Rr)(a,d.toolOrigin):[],f=new Set(u.map(g=>g.id)),p=new Map(i.map(g=>[g.adapter.id,g]));for(let g of u)p.has(g.id)||p.set(g.id,{adapter:g,checks:{}});let h=!1,m=(s.runtimeDurable??le)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?vo.filter(P=>y[P]==="missing"):[];if(b.length===0&&!f.has(g.id))continue;let A=y;if(g.integrationStatus)try{A=await g.integrationStatus()}catch{A=Object.fromEntries(vo.map(P=>[P,"unreadable"]))}let v=b.filter(P=>A[P]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),v.length===0&&!E)continue;let x=await xB(g.id,v,E,l.has(g.id),o,r(),s);if(!x)continue;let[C]=await(s.repair??wt)([g],d.target);if(!C)continue;h=!0;let I;C.status==="configured"&&g.integrationStatus&&(I=await g.integrationStatus().catch(()=>{})),await IB(g.id,x.checks,C,I,o,r(),s)}await RB(o,r(),t,s),i=await(s.findIntegrations??am)(a);let w=await(s.listPending??yr)().catch(()=>[]);return await _B(e,i,w,o,r(),t,s),h}catch{return!1}};var UB=14,FB=.35,BB=900*1e3,NS=360*60*1e3,WB=.2,HB=1800*1e3,$S=3600*1e3,KB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),GB=300*1e3,jB=30*1e3,VB=900*1e3,YB=(e=0)=>Math.min(VB,jB*2**Math.max(0,e)),MS=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}},ZB=720*60*1e3,US=1440*60*1e3,JB=300*1e3,XB=.25,qB=.5,FS=3600*1e3,zB=720*60*60*1e3,QB=360*60*1e3,e1=1440*60*1e3,t1=4,Fd=e=>DB("sha256").update(e).digest("hex").slice(0,32),VS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Gt)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??L)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(Fd(e))},bm=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,t1)}),n1=()=>GS(LB(),".anyray"),Cm=()=>GS(n1(),"refresh-state.json"),Am=e=>process.env?.[e],YS=()=>Am("ANYRAY_REFRESH_DISABLE")==="true",vm=()=>{let e=Am("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:UB)*e1},Li=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},ZS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),r1=10080*60*1e3,Bd=(e,t,n=Date.now())=>{let r=[],o=Li(e);o!==void 0&&r.push(o);let a=Date.parse(t??e.clientKeyExpiresAt??"");Number.isFinite(a)&&r.push(a-n);let s=Date.parse(e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt??"");return Number.isFinite(s)&&r.push(s-n),r.length===0?!1:Math.min(...r)<=r1},Ni=e=>{let t=vm(),n=e?Li(e):void 0;if(!n)return t;let r=Math.max(BB,Math.round(n*FB));return Math.min(t,r)},o1=e=>{let t=Am("ANYRAY_REFRESH_THROTTLE_MS"),n=t?Number.parseInt(t,10):NaN;return Number.isFinite(n)&&n>0?n:typeof e=="number"&&Number.isFinite(e)&&e>0?Math.min(NS,Math.max(HB,Math.round(e*WB))):NS},Gt=async()=>{try{let e=await NB(Cm(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Wd=async e=>{try{let t=Cm(),n=`${t}.${process.pid}.tmp`;await jS(n,JSON.stringify(e),{mode:384}),await he(n,t),await $B(t,384).catch(()=>{})}catch{}},a1=3e4,s1=()=>`${Cm()}.lock`,BS=async e=>{try{return await jS(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},pt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Gt,a=n.writeState??Wd,s=s1(),i=!1;try{if(i=await BS(s),!i){if(await MB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<a1)return t;await LS(s).catch(()=>{}),i=await BS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await LS(s).catch(()=>{})}},Di=async(e,t={})=>{await pt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Ta=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0),a=await(t.loadProfile??L)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?Fd(a.clientKey):void 0;await pt(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:bm(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},So=async(e={})=>{let t=e.now??Date.now;await pt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},i1=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(zB,Math.max(FS,Math.round(o*qB))):FS},km=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Sm=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??oe,a=n.loadProfile??L,s=n.loadDevKey??We,i=n.renew??fS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(pS(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()>i1(e))return{outcome:"not-due",profile:e};if(!await pt(w=>r()-(w.lastCertRenewAt??0)<QB?{result:!1}:{next:{...w,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await km(f,c.sig,t,s))return{outcome:"superseded",profile:f};let p=u.cert.payload.expiresAt,h=Date.parse(p)-r(),m={...f,enrolledCert:u.cert,enrolledCertExpiry:p,...Number.isFinite(h)&&h>0?{enrolledCertLifetimeMs:h}:{}};return await o(m),{outcome:"renewed",profile:m}},WS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*XB):US,r=Math.min(US,n);return Math.min(r,JB*2**Math.max(0,e-1))},c1=()=>{let{command:e,args:t}=hn(ir);return{exe:e,args:t}},Pr=async(e={})=>{if(YS())return;let t=e.now??Date.now,n=e.readState??Gt,r=e.writeState??Wd,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=c1();TB(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await pt(s=>t()-(s.lastSpawnAt??0)<o1(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},l1=Ri,d1=async(e,t=be,n=!1)=>{try{let r=e.managedTools??[];if(r.length===0)return!1;let o=await Oe(async()=>e,void 0,t);if(!o)return!1;let a=await Rr(r,o.toolOrigin),s=n?Xv(a):a;return s.length===0?!1:(await wt(s,o.target),!0)}catch{return!1}},u1=async(e,t,n,r,o,a)=>{try{let s=new Set(e.managedTools??[]),i=ie.filter(p=>s.has(p.id));if(i.length===0)return!1;let c=await r().catch(()=>{}),l=ge({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:c,user:e.name,team:e.team}),d=e.fallbackPort,u=ot(e)&&Number.isInteger(d)&&d>0&&d<=65535&&await o(d)!==null,f=await a(u?_n(l,d):l,u?`http://${mt}:${d}`:l.origin,i);return f.matched>0&&f.complete}catch{return!1}},p1=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Gt,a=t.writeState??Wd;return DS(e,we,{now:r,deadWatcherObserved:n,readHookLane:()=>Hd({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>pt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Hd=async(e={})=>{let n=await(e.readState??Gt)().catch(()=>({}));return In(n.hookLane)},JS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hd(t);if(!fm(r,e,n()))return;await pt(o=>{let a=In(o.hookLane);return fm(a,e,n())?{next:{...o,hookLane:yS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},XS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hd(t);if(!hm(r,n()))return;await pt(o=>{let a=In(o.hookLane);return hm(a,n())?{next:{...o,hookLane:gS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},f1=async(e={})=>{try{let t=e.now??Date.now;if((await Hd(e)).watchSince!==void 0)return;await pt(n=>{let r=In(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:wS(r,t())},result:void 0}},void 0,e)}catch{}},HS=async(e,t={})=>{try{let n=t.now??Date.now;await pt(r=>{let o=In(r.hookLane),a=bS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},qS=async(e={})=>{try{if((await(e.readState??Gt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>pt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??Hg)())return await r()?"stamped":"skipped";let o=await(e.load??L)(),s=await(e.findTools??ko)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Oe(async()=>o,void 0,e.probe??be);return!i||!await r()?"skipped":(await(e.repair??wt)(s,i.target),"repathed")}catch{return"skipped"}},zS=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Gt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>pt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??L)(),i=await(e.findTools??ko)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Oe(async()=>a,void 0,e.probe??be);return!c||!await o()?"skipped":(await(e.repair??wt)(i,c.target)).some(d=>d.status==="failed")?(await pt(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"}},h1=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await Od(e.gateway,e.clientKey),n=await _d(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},KS=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??h1)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>d1(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},nt=async(e={})=>{if(YS())return"disabled";let t=e.now??Date.now,n=e.loadProfile??L,r=e.saveProfile??oe,o=e.loadDevKey??We,a=e.readState??Gt,s=e.writeState??Wd,i=e.remint??dn,c=e.heartbeat??Td,l=e.detectSeat??$t,d=e.rewriteTools??l1,u=e.rewriteHookLaneTools??um,f=e.probeHookLane??Pa,p=e.classifyBeacon??Oc,h=e.probe??be,m=e.installProxy??Nt,w=e.pickProxyPort??Lc,g=e.force===!0,y=!1,b=!1,A=!1,v=!1;e.hookLaneRepair===!0&&(g=!0,v=!0);let E=async C=>{if(!v){C==="repaired"&&await HS("none",{now:t,readState:a,writeState:s});return}let I=C;if(C==="repaired"){let P=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));I=P.verdict==="live"?"repaired":P.verdict==="dark"?"repair_failed":"unverified"}await HS(I,{now:t,readState:a,writeState:s})},x=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(P=>p1(P,{now:t,readState:a,writeState:s},A)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(A=await yr().then(O=>O.some(T=>!wr(T.watcherPid))).catch(()=>!1),await f1({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??Ab)();let C=await n();if(y=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let I=C.gateway,P=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(P)||P<=t())return"cert-expired";let $=await o();if(!$)return"not-enrolled";let Y=await Sm(C,$,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=Y.profile;let Z=Y.outcome==="renewed",W=C.enrolledCert;if(!W)return"not-enrolled";let z=Date.parse(C.clientKeyExpiresAt??""),me=Number.isFinite(z)?z-t():0,Te=await a(),re=!C.clientKey||me<=Ni(C),Ke=C.credentialProtocol!=="stable-heartbeat-v1"&&t()-(Te.lastSuccessAt??0)>=ZB;if(!g&&kS(In(Te.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,v=!0),C.credentialProtocol==="stable-heartbeat-v1"&&C.clientKey&&(g||re)){let O=await pt(T=>{let H=t()-(T.lastAttemptAt??0);return H<$S?{result:"throttled"}:T.failureCount&&H<WS(T.failureCount,T.keyTtlMs)?{result:"backoff"}:{next:{...T,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(O!=="ok")return O;try{let T=await c(I,C.clientKey,W,$),H=await n().catch(()=>C);return H.clientKey!==C.clientKey||H.enrolledCert?.sig!==W.sig?"failed":(await r({...H,clientKeyExpiresAt:T.expiresAt}),await Di(({lastError:fe,...Q})=>({...Q,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Li(C)??Q.keyTtlMs}),{now:t,readState:a,writeState:s}),v&&await E(await u1(C,I,C.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(T){let H=T;if(T instanceof Or&&T.status===404)try{let Q=await i(I,W,$),Ze=await l().catch(()=>{}),Fe=ge({origin:I,clientKey:Q.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Ze,user:C.name,team:C.team}),te=C.fallbackPort,Be=Number.isInteger(te)&&te>0&&te<=65535?te:await w();if(!(await m({port:Be,remoteOrigin:I})).ok||await h(Be)===null)throw new Error("key-refresh proxy recovery failed");let Xt=await n().catch(()=>C);if(!await km(Xt,W.sig,$,o))throw new Error("enrollment changed during proxy recovery");if(await r({...Xt,clientKey:Q.key,clientKeyExpiresAt:Q.expiresAt??Xt.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:Be}),await d(_n(Fe,Be),Fe.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let V=Q.expiresAt?Date.parse(Q.expiresAt):NaN,Ne=Li(C)??(Number.isFinite(V)&&V-t()>0?V-t():void 0);return await Di(({lastError:nr,...ht})=>({...ht,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ne??ht.keyTtlMs,ownKeys:bm(ht.ownKeys,W.sig,Fd(Q.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(Q){H=Q}let fe=MS(H);return await Di(Q=>({...Q,lastAttemptAt:t(),failureCount:(Q.failureCount??0)+1,lastError:{name:H instanceof Error?H.name:"Error",...fe!==void 0?{code:fe}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),H instanceof Or?"cert-rejected":"failed"}}if(!g&&C.clientKey&&!re&&!Ke){let O=await KS(C,e,n,h),T=await x();return O||T?"repaired":Z?"cert-renewed":"not-due"}let De=await pt(O=>{let T=t()-(O.lastAttemptAt??0);if(g)return T<YB(O.failureCount)?{result:"throttled"}:{next:{...O,lastAttemptAt:t()},result:"ok"};let H=O.lastError?.code!==void 0&&KB.has(O.lastError.code)?GB:$S;return T<H?{result:"throttled"}:O.failureCount&&T<WS(O.failureCount,O.keyTtlMs)?{result:"backoff"}:{next:{...O,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(De!=="ok")return De;try{let O=await i(I,W,$),T=await l().catch(()=>{}),H=ge({origin:I,clientKey:O.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:T,user:C.name,team:C.team}),fe=H,Q=H.origin;if(ot(C)){if(!Number.isInteger(C.fallbackPort)||C.fallbackPort<1||C.fallbackPort>65535)throw new Error("key-refresh proxy profile has no valid port");await h(C.fallbackPort)!==null&&(fe=_n(H,C.fallbackPort),Q=`http://${mt}:${C.fallbackPort}`)}let Ze=await d(fe,Q);if(C.directMigration==="pending"&&fe.viaLocalProxy===!0){let V=await d(fe,H.origin);Ze=Ze!==!1&&V!==!1}if(Ze===!1)throw new Error("one or more configured tools rejected the refreshed key");let Fe=await n().catch(()=>C),te=null,Be;Fe.enrolledCert&&await km(Fe,W.sig,$,o)&&(Be=Fd(O.key),te={...Fe,clientKey:O.key,clientKeyExpiresAt:O.expiresAt??Fe.clientKeyExpiresAt},await r(te));let Le=O.expiresAt?Date.parse(O.expiresAt):NaN,Xt=Li(C)??(Number.isFinite(Le)&&Le-t()>0?Le-t():void 0);return await Di(({lastError:V,...Ne})=>({...Ne,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Xt??Ne.keyTtlMs,...Be?{ownKeys:bm(Ne.ownKeys,W.sig,Be)}:{}}),{now:t,readState:a,writeState:s}),te&&await KS(te,e,n,h),await E(te?"repaired":"repair_failed"),await x(),"refreshed"}catch(O){let T=MS(O);return await Di(H=>({...H,lastAttemptAt:t(),failureCount:(H.failureCount??0)+1,lastError:{name:O instanceof Error?O.name:"Error",...T!==void 0?{code:T}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),O instanceof Ot?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await x()}catch{}}};import{readFile as C1}from"node:fs/promises";import{isAbsolute as A1,posix as rE,win32 as Im}from"node:path";var Em=1e4,m1=900*1e3,eE="tnt_",y1=/^\/sso\/([^/]+)\/?$/,g1=/^\/i\/([^/]+)\/?$/,w1=e=>{let t=e.match(y1);if(t)return t[1];let n=e.match(g1);return n?.[1].startsWith(eE)?n[1]:void 0},_t=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=w1(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(eE))return{cpOrigin:qn(),tenantId:t}},Eo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},jt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},xm=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)}},b1=e=>new Promise(t=>setTimeout(t,e)),Kd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Pd)(),a;try{a=await xm(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},Em,n)}catch(h){throw new Eo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${bt(h)}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new Eo(h?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${m}). Ask your admin to confirm SSO is configured.`,a.status)}let s=a.json;if(!s.device_code||!s.user_code||!s.verification_uri_complete)throw new Eo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??m1,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}`),k1(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},k1=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Gd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??b1,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 xm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},Em,o)}catch(c){throw new jt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${bt(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 jt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new jt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new jt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var QS="sdc_",tE=e=>{let t=e.trim();if(!t)return;if(t.startsWith(QS))return{cpOrigin:qn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!dm(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(QS)))return{cpOrigin:n.origin,claim:r}},nE=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Pd)(),o;try{o=await xm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},Em,t)}catch(s){throw new jt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${bt(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 jt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new jt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new jt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};var $i=(e=process.platform,t=process.env)=>e==="darwin"?rE.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?Im.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):rE.join("/etc","anyray","bootstrap.json"),v1=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),oE=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(A1(e)||Im.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),S1=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}},Vt=async(e=$i())=>{try{let t=await C1(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!v1(n)||n.v!==1||typeof n.sso!="string")return;let r=_t(n.sso);if(!r)return;let o=S1(n.gateway)?n.gateway:void 0,a=oE(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},aE=(e,t,n)=>{let r=_t(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!oE(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&Im.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)}
|
|
301
|
+
`};import{execFile as J1}from"node:child_process";import{chmod as E1,readFile as x1,rm as sE,writeFile as I1}from"node:fs/promises";import{join as R1}from"node:path";var Rm=()=>R1(ee(),"sso-gate.json"),O1=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))},Tr=async()=>{try{let e=JSON.parse(await x1(Rm(),"utf-8"));return O1(e)?e:null}catch{return null}},_1=0,jd=async e=>{await Ct();let t=Rm(),n=`${t}.${process.pid}.${_1++}.tmp`;try{await I1(n,`${JSON.stringify(e)}
|
|
302
|
+
`,{mode:384}),await E1(n,384),await he(n,t)}catch(r){throw await sE(n,{force:!0}).catch(()=>{}),r}},iE=async()=>{await sE(Rm(),{force:!0}).catch(()=>{})},cE=e=>{if(!e||!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}};import{spawn as D1}from"node:child_process";import{homedir as L1}from"node:os";import{join as N1}from"node:path";import{spawn as P1}from"node:child_process";import{platform as T1}from"node:os";var Da=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=T1(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=P1(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var $1=3e4,M1=5*6e4,U1=30*6e4,F1=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},B1=()=>N1(L1(),".claude","settings.json"),W1=async e=>{try{let n=(await F(B1())).env;if(!n)return!1;let r=fn(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}},H1=async e=>{await dr.apply(e,{dryRun:!1})},K1=()=>{let{command:e,args:t}=hn("__anyray-sso-poll");return{exe:e,args:t}},G1=()=>{let{exe:e,args:t}=K1(),n=D1(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))}}},j1=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},lE=(e,t,n,r)=>ge({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),La=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},dE=e=>`Anyray: one-time sign-in required to use AI tools on this device.
|
|
303
303
|
1. Open ${e.verificationUriComplete}
|
|
304
304
|
2. Confirm code ${e.userCode}
|
|
305
305
|
Your prompt was not sent \u2014 complete sign-in, then resubmit it.
|
|
306
|
-
`,
|
|
306
|
+
`,Om=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
|
|
307
307
|
`:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
|
|
308
308
|
`:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
|
|
309
|
-
`,V1=e=>Math.min(M1,$1*2**Math.max(0,e-1)),Y1=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?U1:V1(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Qn=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??L,o=t.saveProfile??oe,a=t.loadDevKey??We,s=t.readGateState??Tr,i=t.writeGateState??
|
|
310
|
-
`))}let z;await m();try{z=await d(C,b.enrolledCert,v,{timeoutMs:1e4})}catch(me){if(!(me instanceof Ot))return La(e,
|
|
311
|
-
`,{mode:384}),await lW(n,384),await he(n,t)}catch(r){throw await bE(n,{force:!0}).catch(()=>{}),r}},
|
|
312
|
-
${t.stderr??""}`}},tH=async e=>{try{return(await JW(e)).isDirectory()}catch{return!1}},nH=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},
|
|
313
|
-
${j(e)}`),M=e=>console.log(S(e)),U=e=>console.log(`${hH("\u2713")} ${e}`),D=e=>console.error(`${mH("!")} ${e}`),_=e=>console.error(`${yH("\u2717")} ${e}`);var
|
|
309
|
+
`,V1=e=>Math.min(M1,$1*2**Math.max(0,e-1)),Y1=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?U1:V1(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Qn=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??L,o=t.saveProfile??oe,a=t.loadDevKey??We,s=t.readGateState??Tr,i=t.writeGateState??jd,c=t.isProcessAlive??cE,l=t.startGrant??Kd,d=t.verify??dn,u=t.routingIntact??W1,f=t.applyClaudeCode??H1,p=t.maybeSpawnRefresh??Pr,h=t.recordMint??Ta,m=t.reserveMint??So,w=t.spawnPoller??G1,g=t.openBrowser??Da;try{let y=_t(e.sso);if(!y)return{exitCode:0};let b=await r(),A=await s(),v=b.enrolledCert?await a():void 0,E=j1(b),x=!!(b.enrolledCert&&v)&&Number.isFinite(E)&&E>n(),C=e.gateway??b.gateway;if(x&&b.enrolledCert&&v&&C){let Z=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(Z)&&Z>n()&&b.clientKey){let me=lE(C,b,e.team,b.clientKey);return await u(me)?(Z-n()<=vm()&&await p(),{exitCode:0}):(await f(me),La(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
|
|
310
|
+
`))}let z;await m();try{z=await d(C,b.enrolledCert,v,{timeoutMs:1e4})}catch(me){if(!(me instanceof Ot))return La(e,Om("gateway-unreachable",y.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(z){let me={...b,gateway:C,name:z.user,team:e.team??z.team??b.team,clientKey:z.key,clientKeyExpiresAt:z.expiresAt,authMode:"subscription"};return await o(me),await h({expiresAt:z.expiresAt}),await f(lE(C,me,e.team,z.key)),{exitCode:0}}}if(A?.status==="pending"&&(A.userCode&&A.verificationUriComplete)&&(A.grantExpiresAt??0)>n()&&c(A.pollerPid)){if(e.sessionStart&&A.verificationUriComplete)try{g(A.verificationUriComplete)}catch{}return La(e,dE(A))}if(A){let Z=Y1(A,n());if(Z)return La(e,Om(Z,y.cpOrigin))}let I;try{I=await l({cpOrigin:y.cpOrigin,tenantId:y.tenantId,gatewayUrl:e.gateway,now:n})}catch(Z){let W=Z instanceof Eo?Z.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:A?.lastFailure===W?(A.failureCount??0)+1:1,lastFailure:W}),La(e,Om(W,y.cpOrigin))}let P={v:1,status:"pending",userCode:I.userCode,verificationUriComplete:I.verificationUriComplete,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,lastAttemptAt:n(),failureCount:0};await i(P);let $=w(),Y={...P,pollerPid:$.pid};if(await i(Y),$.handoff({deviceCode:I.deviceCode,privateKeyPem:I.privateKeyPem,publicKeyPem:I.publicKeyPem,cpOrigin:I.cpOrigin,tenantId:I.tenantId,intervalMs:I.intervalMs,grantExpiresAt:I.grantExpiresAt,startedAt:I.startedAt,gatewayUrl:I.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{g(I.verificationUriComplete)}catch{}return La(e,dE(Y))}catch{return{exitCode:0}}},Z1=async()=>{try{for await(let e of process.stdin);}catch{}},uE=async e=>{await Z1();try{let t=await Qn(F1(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var X1=6e4,q1=10*6e4,er=(e,t)=>{let n=e[t];return typeof n=="string"?n:Array.isArray(n)?n[0]:void 0},z1=e=>{if(er(e,"x-anyray-api-key")?.trim())return!0;let t=er(e,"authorization")?.trim()??"";return/^bearer\s+\S+/i.test(t)?!0:(er(e,"x-api-key")?.trim()??"").startsWith("ark_")},fE=e=>{if(er(e,"x-anyray-api-key")?.trim())return!0;let t=er(e,"authorization")?.trim()??"";return/^bearer\s+ark_\S+/i.test(t)?!0:(er(e,"x-api-key")?.trim()??"").startsWith("ark_")},hE=e=>{let t=er(e,"x-anyray-api-key")?.trim();if(t?.startsWith("ark_"))return{key:t,slot:"x-anyray-api-key"};let r=(er(e,"authorization")?.trim()??"").match(/^bearer\s+(ark_\S+)/i);if(r)return{key:r[1],slot:"authorization"};let o=er(e,"x-api-key")?.trim()??"";return o.startsWith("ark_")?{key:o,slot:"x-api-key"}:void 0},Q1=e=>e.split("?")[0].includes("/v1/"),pE=e=>e.replace(/[^\x20-\x7e]/g,"").replace(/["'`\\$]/g,"").slice(0,300),eW=(e,t,n=process.platform,r=J1)=>{let o=pE(e),a=pE(t);try{n==="darwin"?r("/usr/bin/osascript",["-e",`display notification "${a}" with title "${o}"`],{timeout:5e3},()=>{}):n==="linux"&&r("notify-send",["--app-name=Anyray",o,a],{timeout:5e3},()=>{})}catch{}},mE=(e={})=>{let t=e.readBootstrap??Vt,n=e.ssoGate??Qn,r=e.readState??Tr,o=e.notify??eW,a=e.now??Date.now,s=0,i,c=0,l=!1,d=async()=>{let u=await t();if(!u||(await n({sso:u.sso,gateway:u.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}})).exitCode!==2)return;let p=await r();p?.status!=="pending"||!p.userCode||!p.verificationUriComplete||!(p.userCode!==i)&&a()-c<q1||(i=p.userCode,c=a(),o("Anyray \u2014 sign in to use AI tools",`Open ${p.verificationUriComplete} and enter code ${p.userCode}. Requests keep failing until sign-in completes.`))};return{onGatewayUnauthorized(u,f){try{if(!Q1(u)||z1(f)||l||a()-s<X1)return;s=a(),l=!0,d().catch(()=>{}).finally(()=>{l=!1})}catch{}}}};import{watch as tW}from"node:fs";import{basename as nW,dirname as rW}from"node:path";var oW=2e3,aW=6e4,Na=e=>e instanceof Error?e.name:"UnknownError",sW=(e,t,n)=>{let r=tW(e,{persistent:!1},(o,a)=>{t(a==null?null:a.toString())});return r.on("error",n),r},iW=async(e,t)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Oe(async()=>e,void 0,t);if(!r)return!1;let o=await Rr(n,r.toolOrigin);return o.length===0?!1:(await wt(o,r.target),!0)}catch{return!1}},yE=(e={})=>{let t=e.loadProfile??L,n=e.adapters??ie,r=e.probe??be,o=e.repairDrift??(C=>iW(C,r)),a=e.resolveProfileFile??Mo,s=e.watchDir??sW,i=e.debounceMs??oW,c=e.repairFloorMs??aW,l=e.now??Date.now,d=e.logError??(C=>console.error(`anyray refresh proxy: drift watcher ${C}`)),u=!1,f=0,p,h=Promise.resolve(),m=new Map,w=C=>{let I=m.get(C);if(I){m.delete(C);try{I.handle.close()}catch{}}},g=()=>{if(u)return;p!==void 0&&clearTimeout(p);let C=setTimeout(()=>{p=void 0,h=h.then(E).catch(()=>{})},i);C.unref?.(),p=C},y=C=>I=>{if(!u)try{let P=m.get(C);if(!P||I!==null&&!P.files.has(I))return;g()}catch(P){d(Na(P))}},b=C=>I=>{d(Na(I)),w(C),g()},A=async C=>{let I=[],P=new Set(C.managedTools??[]);for(let Z of n)if(!(!P.has(Z.id)||!Z.watchPaths))try{I.push(...await Z.watchPaths())}catch(W){d(Na(W))}let $=await a().catch(()=>{});$&&I.push($);let Y=new Map;for(let Z of I){let W=rW(Z),z=Y.get(W)??new Set;z.add(nW(Z)),Y.set(W,z)}return Y},v=async C=>{let I=await A(C);if(!u){for(let P of[...m.keys()])I.has(P)||w(P);for(let[P,$]of I){let Y=m.get(P);if(Y){Y.files=$;continue}try{m.set(P,{handle:s(P,y(P),b(P)),files:$})}catch(Z){d(Na(Z))}}}},E=async()=>{if(!u)try{let C=await t().catch(()=>({}));if(await v(C),u||l()-f<c)return;f=l(),await o(C).catch(()=>!1)}catch(C){d(Na(C))}};return{ready:t().then(C=>v(C)).catch(C=>d(Na(C))),stop:()=>{u=!0,p!==void 0&&(clearTimeout(p),p=void 0);for(let C of[...m.keys()])w(C)}}};import{randomBytes as cW}from"node:crypto";import{chmod as lW,readFile as dW,rm as bE,writeFile as uW}from"node:fs/promises";import{join as pW}from"node:path";var fW=/^[A-Za-z0-9_-]{43}$/,hW=3600*1e3,gE=3900,mW=1e4,_m=()=>pW(ee(),"device-token.json"),yW=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&fW.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},kE=async()=>{try{let e=JSON.parse(await dW(_m(),"utf-8"));return yW(e)?e:null}catch{return null}},gW=0,wW=async e=>{await Ct();let t=_m(),n=`${t}.${process.pid}.${gW++}.tmp`;try{await uW(n,`${JSON.stringify(e)}
|
|
311
|
+
`,{mode:384}),await lW(n,384),await he(n,t)}catch(r){throw await bE(n,{force:!0}).catch(()=>{}),r}},Vd=async()=>{await bE(_m(),{force:!0}).catch(()=>{})},bW=()=>cW(32).toString("base64url"),kW=e=>e instanceof Error?e.name:"UnknownError",CW=(e,t)=>{let n=setInterval(e,t);return n.unref(),{stop:()=>clearInterval(n)}},wE=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??L)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=bW(),i=new AbortController,c=setTimeout(()=>i.abort(),mW),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:gE}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await wW({v:1,token:s,expiresAt:t()+gE*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${kW(r)}`),!1}},CE=(e={})=>{wE(e);let n=(e.scheduleRotation??CW)(()=>{wE(e)},hW);return{stop:()=>n.stop()}};var vW=1800*1e3,AE=50,SW=15e3,EW=1e3,xE=bs*1e3-1e4,vE=15*6e4,xW=75e3,IW=8e4,RW=async(e,t,n={})=>{let r=n.budgetMs??bs*1e3,o=n.delayMs??250,a=Date.now()+r;for(;;)try{await new Promise((s,i)=>{let c=l=>i(l);e.once("error",c),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",c),s()})});return}catch(s){if(s.code!=="EADDRINUSE"||Date.now()+o>a)throw s;await Tm(o)}},Yd=e=>{let t=e instanceof Error?e.name:"unknown",n=e?.code;return typeof n=="string"?`${t} ${n}`:t},OW=(e,t={})=>{let n=t.exit??(f=>process.exit(f)),r=t.exitCode??0,o=t.hardCapMs??xE,a=t.inFlight,s=Date.now()+(t.ceilingMs??o),i=setInterval(()=>e.closeIdleConnections(),500);i.unref();let c,l=!1,d=()=>{l||(l=!0,clearInterval(i),clearTimeout(c),n(r))},u=f=>{c=setTimeout(()=>{let p=s-Date.now();if(a&&a()>0&&p>0){u(Math.min(o,p));return}d()},f),c.unref()};u(o),e.close(d),e.closeIdleConnections()},IE=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),_W=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]),PW=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),TW=45*1e3,DW=600*1e3,LW=new Set(["host","connection","keep-alive","proxy-connection","content-length","transfer-encoding","upgrade"]),NW=new Set(["content-encoding","content-length","transfer-encoding","connection","keep-alive"]),$W=new Set(["missing_key","key_expired"]),MW=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object")return!1;let{status:n,code:r}=t;return n==="failure"&&typeof r=="string"&&$W.has(r)}catch{return!1}},UW=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(LW.has(n.toLowerCase())||(t[n.toLowerCase()]=Array.isArray(r)?r.join(", "):r));return t},FW=e=>new Promise((t,n)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>t(Buffer.concat(r))),e.on("error",o=>n(o))}),BW=(e,t)=>e?IE.has(e)?!0:_W.has(e)&&PW.has(t.toUpperCase()):!1,WW=new Set(["127.0.0.1","localhost","[::1]","::1"]),HW=e=>{if(e[sp]===void 0||e.origin!==void 0)return!1;let t=(e.host??"").replace(/:\d+$/,"");return WW.has(t)},KW=(e,t)=>{let n=(t??"").split("?")[0];return e==="GET"&&n==="/__anyray/health"||e==="POST"&&n==="/__anyray/shutdown"},GW=async(e,t,n,r)=>{try{return{res:await fetch(e,{method:t,headers:n,body:r.length?r:void 0,duplex:"half"})}}catch(o){return{failure:{kind:"transport-error",code:o?.cause?.code}}}},Tm=e=>new Promise(t=>setTimeout(t,e)),SE=async(e,t,n,r,o,a=SW)=>{let s=Date.now()+a,i=AE,c=!1;for(;;){let l=await GW(e,t,n,r);if("res"in l||!o())return l;let d=l.failure.code;if(d!==void 0&&IE.has(d)){if(Date.now()+i>s)return l;await Tm(i),i=Math.min(i*2,EW)}else if(!c&&BW(d,t))c=!0,await Tm(AE);else return l;if(!o())return l}},Pm=async(e,t)=>{let n={};if(t.headers.forEach((s,i)=>{NW.has(i.toLowerCase())||(n[i]=s)}),e.writeHead(t.status,n),!t.body){e.end();return}let r=t.body.getReader(),o=()=>{r.cancel().catch(()=>{})};e.once("close",o);let a=!1;try{for(;;){let{done:s,value:i}=await r.read();if(s)break;if(i){if(e.destroyed){r.cancel().catch(()=>{});continue}e.write(i)||await new Promise(c=>{if(e.destroyed||e.writableEnded){c();return}let l=()=>{e.off("close",d),c()},d=()=>{e.off("drain",l),c()};e.once("drain",l),e.once("close",d)})}}}catch{a=!0}finally{e.off("close",o)}a&&!e.writableEnded?e.destroy():e.end()},EE=(e,t,n)=>{e.headersSent||e.destroyed||(e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify({error:{type:"anyray_proxy",message:n}})))},jW=e=>{let t=e.remoteOrigin.replace(/\/+$/,""),n=0,r=async(a,s)=>{let i=a.url??"/",c=a.method??"GET";if(c==="GET"&&i==="/__anyray/health"){s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({status:"ok",mode:"refresh-only",port:e.port,remoteOrigin:t,version:we,inFlight:n}));return}if(c==="POST"&&(i==="/__anyray/shutdown"||i.startsWith("/__anyray/shutdown?"))){if(!HW(a.headers)){s.writeHead(403,{"content-type":"application/json"}),s.end(JSON.stringify({error:"forbidden"}));return}let b=i.includes("?")?i.slice(i.indexOf("?")+1):"",A=new URLSearchParams(b).get("drain")==="idle"?"idle":void 0;s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({status:"stopping"})),e.onShutdown?.({drain:A});return}let l=await FW(a),d=UW(a.headers),u=hE(a.headers),f=b=>{if(!u){d["x-anyray-api-key"]=b;return}d[u.slot]=u.slot==="authorization"?`Bearer ${b}`:b},p,h=!1;if(e.resolveClientKey&&!fE(a.headers)){h=!0;try{p=await e.resolveClientKey(),p&&f(p)}catch{}}let m=await SE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("failure"in m){EE(s,502,`gateway unreachable (${m.failure.code??"transport-error"})`);return}let w=()=>{if(!(m.res.status!==401||!e.onGatewayUnauthorized))try{e.onGatewayUnauthorized(i,a.headers)}catch{}},g=h;!g&&m.res.status===401&&u&&e.isOwnClientKey&&(g=await e.isOwnClientKey(u.key).catch(()=>!1));let y=g&&(h?!!e.recoverInjectedKey:!!e.resolveClientKey);if(m.res.status===401&&y){let b=await m.res.text().catch(()=>"");if(MW(b)){let A=h?await e.recoverInjectedKey().catch(()=>{}):await e.resolveClientKey().catch(()=>{}),v=p??u?.key;if(A!==void 0&&A!==v){f(A);let E=await SE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("res"in E){E.res.status===401&&w(),await Pm(s,E.res);return}}}w(),await Pm(s,new Response(b,{status:m.res.status,headers:m.res.headers}));return}w(),await Pm(s,m.res)},o=AW.createServer((a,s)=>{s.on("error",()=>{}),KW(a.method,a.url)||(n++,s.once("close",()=>{n--})),r(a,s).catch(i=>{console.error(`anyray refresh proxy: request error ${Yd(i)}`),s.headersSent?s.end():EE(s,502,"anyray proxy internal error")})});return o.keepAliveTimeout=xW,o.headersTimeout=IW,o.on("error",a=>{a.code!=="EADDRINUSE"&&console.error(`anyray refresh proxy: server error ${Yd(a)}`)}),{server:o,inFlight:()=>n}},RE=5e3,VW=2e3,YW=(e={})=>{let t=e.now??Date.now,n=e.loadProfile??L,r=e.refresh??(()=>nt()),o=e.remintBudgetMs??RE,a,s=-1/0,i=3e4;return Object.assign(async()=>{let l=a===void 0?VW:i;if(t()-s<l)return a;let d=await n().catch(()=>({})),u=Date.parse(d.clientKeyExpiresAt??"");if(Number.isFinite(u)){let f=u-t();if(f<=0){await Promise.race([Promise.resolve().then(r).catch(()=>{}),new Promise(h=>setTimeout(h,o).unref?.())]),d=await n().catch(()=>d);let p=Date.parse(d.clientKeyExpiresAt??"");if(Number.isFinite(p)&&p-t()<=0)return a=void 0,s=t(),a}else f<=Ni(d)&&Promise.resolve().then(r).catch(()=>{})}return a=d.clientKey,s=t(),a},{invalidate:()=>{a=void 0,s=-1/0}})},OE=async()=>{let e=await L(),t=e.fallbackPort,n=e.gateway?.replace(/\/+$/,"");if(!t||!n){let p=await Vt().catch(()=>{});p?.gateway&&(n??=p.gateway.replace(/\/+$/,""),t??=ke)}if(!t||!n)return console.error("anyray refresh proxy: not configured (missing loopbackPort/gateway in ~/.anyray, and no fleet bootstrap with a gateway). Run `anyray-connect` first."),1;let r=mE(),o=YW(),a=jW({port:t,remoteOrigin:n,onGatewayUnauthorized:(p,h)=>r.onGatewayUnauthorized(p,h),resolveClientKey:o,recoverInjectedKey:async()=>(o.invalidate(),await Promise.race([nt({force:!0}).catch(()=>{}),new Promise(p=>setTimeout(p,RE).unref?.())]),o()),isOwnClientKey:p=>VS(p),onShutdown:p=>f(0,{drain:p.drain})});nt().catch(()=>{});let s=setInterval(()=>{nt().catch(()=>{})},vW);s.unref();let i=yE(),c=CE(),l=Date.now();a.server.on("request",()=>{l=Date.now()});let d=setInterval(()=>{Date.now()-l>DW||fetch(`${n}/`,{method:"HEAD"}).catch(()=>{})},TW);d.unref();let u=!1,f=(p=0,h={})=>{if(u)return;u=!0,clearInterval(s),clearInterval(d),i.stop(),c.stop();let m=h.drain==="idle"?vE:xE;Rw(Date.now()+m),OW(a.server,{exitCode:p,inFlight:a.inFlight,ceilingMs:h.drain==="idle"?vE:void 0,exit:w=>{dp(),process.exit(w)}})};return process.once("SIGTERM",()=>f()),process.once("SIGINT",()=>f()),process.on("uncaughtException",p=>{console.error(`anyray refresh proxy: uncaught exception ${Yd(p)}`),f(1)}),process.on("unhandledRejection",p=>{console.error(`anyray refresh proxy: unhandled rejection ${p instanceof Error?Yd(p):typeof p}`),f(1)}),dp(),await vw(ys()).catch(()=>{}),await RW(a.server,t),console.error(`anyray refresh proxy listening on 127.0.0.1:${t} \u2192 ${n}`),await new Promise(()=>{}),0};import{platform as ZW}from"node:os";import{stat as JW}from"node:fs/promises";import{spawnSync as XW}from"node:child_process";var _E="/Applications/Anyray Connect Tray.app",qW=new Set(["V53XMA78UF"]),zW="ai.anyray.connect-tray",QW=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,eH=e=>{let t=XW("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
312
|
+
${t.stderr??""}`}},tH=async e=>{try{return(await JW(e)).isDirectory()}catch{return!1}},nH=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},Dm=async(e,t={})=>{if((t.os??ZW())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??tH)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??eH;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?nH(a.output):void 0;return s?qW.has(s)?QW(a.output)!==zW?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},xo=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await Dm(n,t)).ok?"healthy":"gone"},Lm=async(e={})=>{try{let t=e.load??L,n=await t(),r=await xo(n,e);if(r!=="gone")return r;let o=e.installScheduler??hr,a=e.installDaemon??Nt;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await a({port:n.fallbackPort??ke,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??oe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var rH={"not-macos":"persistence swap: macOS only \u2014 the LaunchAgents stay in place on this OS.","bad-path":"persistence swap: --app-path must point at a .app bundle.",missing:"persistence swap: tray app bundle not found \u2014 nothing changed.",unsigned:"persistence swap: tray app failed codesign verification \u2014 refusing to adopt (RFC 0010 invariant 5).","no-team-identifier":"persistence swap: tray app has no Developer ID TeamIdentifier (adhoc or unsigned) \u2014 refusing to adopt (RFC 0010 invariant 5).","untrusted-team":"persistence swap: tray app is signed by a Developer ID that is not Anyray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgents stay in place.","untrusted-bundle-id":"persistence swap: that bundle is not the Anyray Connect Tray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgents stay in place."},oH=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},aH=async(e,t)=>{let n=t.stderr??console.error,r=oH(e,"--app-path")??_E,o=await Dm(r,t);if(!o.ok)return n(rH[o.reason]),1;let s=await(t.load??L)();await(t.save??oe)({...s,persistenceOwner:"tray",trayAppPath:r});let c=t.uninstallScheduler??mr,l=t.uninstallDaemon??en;return await c().catch(()=>{}),await l(s.fallbackPort).catch(()=>{}),0},sH=async e=>{let t=e.load??L,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??hr,o=e.installDaemon??Nt;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),n.keyRefreshEnabled&&n.gateway&&await o({port:n.fallbackPort??ke,remoteOrigin:new URL(n.gateway).origin}).catch(()=>{}),await(e.save??oe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},PE=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await aH(e,t):e.includes("--release-tray")?await sH(t):(n("persistence swap: expected --adopt-tray or --release-tray."),1)}catch(r){return n(`persistence swap: failed (${r instanceof Error?r.name:"Error"}).`),1}};import{homedir as TE,platform as Nm}from"node:os";import{join as $a}from"node:path";import{access as iH}from"node:fs/promises";var $m=(e=Nm(),t=TE())=>{let n=a=>[$a(t,"Library","LaunchAgents",`${a}.plist`)],r=$a(t,".config","systemd","user"),o=a=>[$a(t,".anyray","logs",a)];return e==="darwin"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:ws,paths:n(ws),dataPaths:o("connect-daemon.log")},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:Es,paths:n(Es),dataPaths:o("connect-refresh.log")}]:e==="linux"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:`${fr}.service`,paths:[$a(r,`${fr}.service`)]},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:`${Zr}.timer`,paths:[$a(r,`${Zr}.timer`),$a(r,`${Zr}.service`)]}]:e==="win32"?[{kind:"scheduler",title:"key-refresh scheduler",supervisorName:Uc,paths:[]}]:[]},DE=async e=>{try{return await iH(e),!0}catch{return!1}},Mi=async(e,t={})=>{let n=t.exists??DE,r=t.os??Nm();for(let o of $m(r,t.home))if(o.kind===e){if(o.paths.length===0){if(await(t.supervisorHolds??cH)(e,r))return!0;continue}for(let a of o.paths)if(await n(a))return!0}return!1},cH=async(e,t)=>{if(e!=="scheduler")return!1;try{return await Jo(t)}catch{return!1}},LE=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable)return t;let n=e.exists??DE,r=$m(e.os,e.home);for(let o of r)if(o.kind==="daemon"?e.daemonEnabled&&e.daemonHealthy===!1:e.schedulerEnabled&&!e.schedulerInstalled)for(let s of o.paths)await n(s)||(t.missingPaths.push(s),t.kinds.includes(o.kind)||t.kinds.push(o.kind));return t.suspected=t.missingPaths.length>0,t},lH=[ws,`${fr}.service`,Es,`${Zr}.timer`,`${Zr}.service`,Uc],NE=(e,t=Nm(),n=TE(),r=ur())=>{let o=["Anyray connect installs two per-user background services. Both are","unprivileged, run as the logged-in user, and exist only to re-mint the","seat's short-lived gateway key so a long AI-coding session doesn't 401.","","Executable (both services):",` ${r}`,""];for(let a of $m(t,n)){o.push(`${a.title} \u2014 supervisor name: ${a.supervisorName}`);for(let s of a.paths)o.push(` ${s}`);a.paths.length===0&&o.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let s of a.dataPaths??[])o.push(` ${s} (captured stdout/stderr \u2014 error names only)`);o.push("")}return o.push("Also spawns, detached and short-lived (same executable, hidden","subcommands \u2014 not a separate install):"," - Coding-tool MCP clients (Copilot Chat, Copilot CLI, OpenCode, etc.) run"," `anyray-connect __anyray-mcp-server` as a stdio server, which spawns a"," detached `anyray-connect __anyray-refresh`."," - The Anyray VS Code extension, on activation (including a remote/"," Codespace/dev-container extension host), spawns"," `anyray-connect __anyray-spawn-refresh` \u2014 a cheap gate that may itself"," spawn the same detached `anyray-connect __anyray-refresh`."," Both are throttled independently of the scheduler (up to ~6h between"," spawns) and serialized through the same refresh-state claim, so they can"," never double-mint against it. Neither listens itself; the tick can"," (re)install the loopback daemon disclosed above, whose port is covered"," under Network behavior.","","Network behavior:",` - The daemon listens on 127.0.0.1:${e} ONLY (loopback; it never binds a`," routable interface and accepts no remote connections)."," - Outbound: your org's Anyray gateway over HTTPS, nothing else."," - It relays your AI tools\u2019 requests byte-for-byte; its single mutation is"," filling in a freshly minted gateway key header.","","Why it looks like persistence to a heuristic scanner: the launchd agent is a","KeepAlive login item, which is the same shape a persistence implant uses. It","is a real login item, by design \u2014 that is what keeps keys fresh across","reboots. Allow-list the paths above, or run `anyray-connect --no-key-refresh`","to install no background service at all (tools then point straight at the","gateway, at the cost of a periodic re-run when the key lapses).","","Retired supervisor labels (endpoint v2): on a machine running Fleet\u2019s signed","fleetd, connect retires the services above \u2014 fleetd drives key refresh","instead. If you find any of these labels/units on a fleetd host, they are","orphans safe to remove; connect no longer installs or supervises them:",...lH.map(a=>` - ${a}`)),o};var Mm=5e3,$E=3e4,dH=1440*60*1e3,uH=e=>new Promise(t=>setTimeout(t,e)),pH=async(e=L,t=$t)=>(await Oe(e,t))?.target,fH=e=>Kt(e)?.quitGated,ME=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??fH,o=t.readPending??il,a=t.clearPending??jp,s=t.targetFromProfile??pH,i=t.sleep??uH,c=t.now??Date.now,l=t.maxWaitMs??dH;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=Mm;for(;;){let h=await o(n);if(!h||c()-f>l)return 0;if(d.isRunning()){await i(p),p=Math.min($E,p*2);continue}let m;if(d.needsTarget?.(h.op)&&(m=await s(),!m)){if(await a(n,h)!=="superseded")return 0;await i(p),p=Mm;continue}if((await u(h.op,m,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(p),p=Math.min($E,p*2);continue}if(await a(n,h)!=="superseded")return 0;await i(p),p=Mm}}catch{return 0}};import{writeFileSync as gH}from"node:fs";import{chmod as Um,stat as wH}from"node:fs/promises";import{platform as Bm}from"node:os";import{dirname as WE,isAbsolute as bH}from"node:path";var Ma=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Zd=Ma(process.stdout,process.env),UE=Ma(process.stderr,process.env),Ua=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,j=e=>Ua("1",e,Zd),S=e=>Ua("2",e,Zd),hH=e=>Ua("32",e,Zd),mH=e=>Ua("33",e,UE),yH=e=>Ua("31",e,UE),rt=e=>Ua("36",e,Zd),k=e=>console.log(e),K=e=>console.log(`
|
|
313
|
+
${j(e)}`),M=e=>console.log(S(e)),U=e=>console.log(`${hH("\u2713")} ${e}`),D=e=>console.error(`${mH("!")} ${e}`),_=e=>console.error(`${yH("\u2717")} ${e}`);var Fm=`${j("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
|
|
314
314
|
|
|
315
315
|
Emit or install the OS \`managed-settings.json\` that points a managed fleet's
|
|
316
316
|
Claude Code at the Anyray gateway. It reads at a HIGHER precedence than a user's
|
|
@@ -398,13 +398,13 @@ ${j("Examples")}
|
|
|
398
398
|
anyray-connect managed --print --tool jetbrains --bin /usr/local/bin/anyray-connect --npx /usr/local/bin/npx > acp.json
|
|
399
399
|
|
|
400
400
|
# Shell/SDK fleet snippet (base URLs only; keys stay per-user):
|
|
401
|
-
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,FE=["claude-code","jetbrains","shell","bootstrap","proxy"],kH=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--print":t.mode="print";break;case"--write":t.mode="write";break;case"--revert":t.mode="revert";break;case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":throw new Error("--key is not valid for managed settings: fleet files never embed credentials; enroll each user instead");case"--scrub-direct-mode":t.scrubDirectMode=!0;break;case"--sso":t.sso=o();break;case"--bin":t.bin=o();break;case"--npx":t.npx=o();break;case"--loopback":t.loopback=!0;break;case"--out":t.out=o();break;case"--platform":{let a=o();if(a!=="launchd"&&a!=="systemd")throw new Error(`unknown --platform ${a} (expected launchd | systemd)`);t.servicePlatform=a;break}case"--tool":{let a=o();if(!FE.includes(a))throw new Error(`unknown --tool ${a} (expected ${FE.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&&!_t(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function
|
|
402
|
-
`)},
|
|
403
|
-
`),SH=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(!
|
|
404
|
-
`),Ce(S("# acp.json for ~/.jetbrains/acp.json (per user).")),Ce(S(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ce(S("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ce(S("# 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},EH=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&&!
|
|
405
|
-
`),Ce(S(`# managed-settings.json for ${Lt()}`)),n)Ce(S("# Deferred SSO: hooks only; no credential or managed env block.")),Ce(S(`# Push the binary to ${n.binaryPath} before this file.`)),Ce(S("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of YE(t))Ce(S(`# ${o}`));
|
|
406
|
-
`+
|
|
407
|
-
`+
|
|
401
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,FE=["claude-code","jetbrains","shell","bootstrap","proxy"],kH=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--print":t.mode="print";break;case"--write":t.mode="write";break;case"--revert":t.mode="revert";break;case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":throw new Error("--key is not valid for managed settings: fleet files never embed credentials; enroll each user instead");case"--scrub-direct-mode":t.scrubDirectMode=!0;break;case"--sso":t.sso=o();break;case"--bin":t.bin=o();break;case"--npx":t.npx=o();break;case"--loopback":t.loopback=!0;break;case"--out":t.out=o();break;case"--platform":{let a=o();if(a!=="launchd"&&a!=="systemd")throw new Error(`unknown --platform ${a} (expected launchd | systemd)`);t.servicePlatform=a;break}case"--tool":{let a=o();if(!FE.includes(a))throw new Error(`unknown --tool ${a} (expected ${FE.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&&!_t(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function Jd(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:[Tn(us(t.binaryPath,[Xe]),{matcher:"*"})],UserPromptSubmit:[Tn(us(t.binaryPath,o),{timeout:30}),Tn(us(t.binaryPath,[sr]))],SessionStart:[Tn(us(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=fn(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(Dn.map(o=>[o.name,""])),...r}}:{env:r}}var CH=(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 Kr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,Xu(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},AH=e=>{let t=e.env,n=Xu(e);if(t){for(let r of Kr)r in t&&(delete t[r],n=!0);for(let{name:r}of Dn)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},HE=async e=>{let t=async n=>{try{return(await wH(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(WE(e))!==void 0}},KE=async(e,t)=>(t.dirExisted||await Um(WE(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await Um(e,420),{mode:420,keptRestricted:!1}):(await Um(e,t.mode),{mode:t.mode,keptRestricted:!0})),GE=(e,t)=>{t.keptRestricted&&(D(`${e} was already restricted to mode ${t.mode.toString(8).padStart(3,"0")} and keeps it \u2014 widening it would expose whatever else that file holds to every local account.`),k(S(" 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.")))},jE=()=>process.getuid?.()===0,Ce=e=>{process.stderr.write(`${e}
|
|
402
|
+
`)},Io=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}gH(e.out,t,"utf8"),Ce(S(`# Wrote ${e.out}`))},Wm=e=>ge({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),Xd=e=>bH(e)||/^[A-Za-z]:[\\/]/.test(e),VE=e=>{if(!e.sso)return;let t=_t(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??Re();if(!e.bin&&!le())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(!Xd(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}},YE=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${de(e.metadata)??"(none \u2014 pass --team)"}`],Hm=(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{}},vH=(e,t)=>({agent_servers:{[Jn]:{command:e,args:[hd,"claude",t,"jetbrains"],env:{}},[Xn]:{command:e,args:[hd,"codex",t,"jetbrains"],env:{}}}}),BE=e=>["# Managed by anyray-connect (fleet). Routes shell/SDK traffic through the Anyray gateway.","# Per-user keys come from enrollment (`anyray-connect --enroll/--sso`); never add a key here.",`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,""].join(`
|
|
403
|
+
`),SH=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(!Xd(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(!gd(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return Io(e,`${JSON.stringify(vH(e.bin,e.npx),null,2)}
|
|
404
|
+
`),Ce(S("# acp.json for ~/.jetbrains/acp.json (per user).")),Ce(S(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ce(S("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ce(S("# 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},EH=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&&!Xd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return Io(e,aE(e.sso,e.gateway,e.bin)),Ce(S(`# Fleet bootstrap for ${$i("linux")}`)),Ce(S(`# macOS: ${$i("darwin")}`)),Ce(S(`# Windows: ${$i("win32",{ProgramData:"C:\\ProgramData"})}`)),Ce(S("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},xH=e=>{if(e.sso||e.bin||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool shell takes only --gateway (or --loopback): the snippet carries base URLs only (keys and attribution ride each user\u2019s enrollment)");if(e.loopback){if(e.gateway)throw new Error("--loopback and --gateway are mutually exclusive: the daemon resolves the real gateway from the fleet bootstrap file");let n=ge({origin:`http://127.0.0.1:${ke}`});return Io(e,BE(n)),Ce(S(`# Loopback shell snippet \u2014 pair with \`managed --tool proxy\` (daemon on :${ke}) and \`--tool bootstrap\`.`)),0}let t=Wm(e);return Io(e,BE(t)),Ce(S("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),Hm(t,Ce),0},IH=e=>{if(e.sso||e.gateway||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session||e.loopback)throw new Error("--tool proxy takes only --bin and --platform: the daemon resolves the gateway and per-user auth at runtime (bootstrap file + profile)");if(!e.bin)throw new Error("--bin <absolute path> is required (fleet-stable anyray-connect binary, e.g. /usr/local/bin/anyray-connect)");if(!Xd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");let t=e.servicePlatform??(Bm()==="darwin"?"launchd":"systemd"),n={command:e.bin,args:[ap]};return t==="launchd"?(Io(e,Cs(n)),Ce(S("# launchd agent \u2014 deploy to /Library/LaunchAgents/ai.anyray.connect.fallback.plist (loads for every user at login)."))):(Io(e,As(n)),Ce(S("# systemd user unit \u2014 deploy to /etc/systemd/user/anyray-fallback.service, then `systemctl --global enable anyray-fallback.service`."))),Ce(S(`# Pair with \`--tool bootstrap\` (the daemon's fleet boot needs it) and the \`--tool shell --loopback\` snippet (port ${ke}).`)),Ce(S(`# Push the binary to ${e.bin} before this unit.`)),0},RH=e=>{let t=Wm(e),n=VE(e),r=n?Jd(t,n):Jd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(Io(e,`${JSON.stringify(r,null,2)}
|
|
405
|
+
`),Ce(S(`# managed-settings.json for ${Lt()}`)),n)Ce(S("# Deferred SSO: hooks only; no credential or managed env block.")),Ce(S(`# Push the binary to ${n.binaryPath} before this file.`)),Ce(S("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of YE(t))Ce(S(`# ${o}`));Hm(t,Ce)}return 0},OH=async e=>{let t=Bm();if(t!=="darwin"&&t!=="linux")return _("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!jE())return _("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),k(S(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=Wm(e),r=VE(e);r||Hm(n,u=>D(u.replace(/^!\s*/,"")));let o=Lt(t),a=await F(o),s=r?Jd(n,r):Jd(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?Dn.filter(({name:u})=>{let f=a.env?.[u];return typeof f=="string"&&f.trim()!==""}):[],c=CH(a,s),l=await HE(o);await J(o,c);let d=await KE(o,l);U(`Wrote ${o}`),GE(o,d);for(let{name:u,cloud:f}of i)D(`${u} was set in this file and is now pinned empty \u2014 Claude Code no longer talks to ${f} directly. The gateway serves it instead; re-add the key here to undo.`);if(r)k(S(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),k(S(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of YE(n))k(` ${S(u)}`);return k(S(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},_H=async()=>{let e=Bm();if(e!=="darwin"&&e!=="linux")return _("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!jE())return _("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Lt(e);if(!await R(t))return k(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await F(t);if(!AH(n))return k(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await HE(t);await J(t,n);let o=await KE(t,r);return U(`Removed Anyray-owned keys from ${t} (other keys left intact).`),GE(t,o),0},ZE=async e=>{let t;try{t=kH(e)}catch(n){return _(n instanceof Error?n.message:"invalid managed arguments"),k(`
|
|
406
|
+
`+Fm),1}if(t.help||e.length===0&&!t.mode)return k(Fm),0;if(!t.mode)return _("Specify a mode: --print, --write, or --revert."),k(`
|
|
407
|
+
`+Fm),1;if(t.out!==void 0&&t.mode!=="print")return _(`--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 _(`--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"?(_(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?SH(t):n==="bootstrap"?EH(t):n==="proxy"?IH(t):xH(t):t.mode==="print"?RH(t):t.mode==="write"?await OH(t):await _H()}catch(n){return _(n instanceof Error?n.message:"managed settings failed"),1}};var PH=`anyray-connect print-key [--json | --passthrough-headers]
|
|
408
408
|
|
|
409
409
|
Print the current short-lived Anyray client key for a consuming app.
|
|
410
410
|
|
|
@@ -416,7 +416,7 @@ Options:
|
|
|
416
416
|
"x-anyray-provider":"anthropic","x-anyray-metadata":"..."}).
|
|
417
417
|
Carries the client key, never the seat OAuth token.
|
|
418
418
|
--help Show this help.
|
|
419
|
-
`,TH=e=>{let t=!1,n=!1,r=!1;for(let o of e)if(o==="--json")t=!0;else if(o==="--passthrough-headers")n=!0;else if(o==="--help"||o==="-h")r=!0;else throw new Error(`Unknown option: ${o}`);if(t&&n)throw new Error("Use only one of --json or --passthrough-headers.");return{json:t,passthroughHeaders:n,help:r}},DH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Ni(e):!0},JE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},XE=(e,t)=>{if(!
|
|
419
|
+
`,TH=e=>{let t=!1,n=!1,r=!1;for(let o of e)if(o==="--json")t=!0;else if(o==="--passthrough-headers")n=!0;else if(o==="--help"||o==="-h")r=!0;else throw new Error(`Unknown option: ${o}`);if(t&&n)throw new Error("Use only one of --json or --passthrough-headers.");return{json:t,passthroughHeaders:n,help:r}},DH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Ni(e):!0},JE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},XE=(e,t)=>{if(!xe(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},Km=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,LH=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Km(t)}\`.`:"Enrollment certificate expired. Re-run `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"cert-rejected":return t.ssoLink?`Your SSO reconnect credential is no longer valid. Reconnect with \`${Km(t)}\`.`:"Your enrollment certificate is no longer valid. Reconnect with `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${Km(t)}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.";case"disabled":return"Automatic key refresh is disabled.";case"backoff":case"throttled":return"Key refresh is temporarily unavailable; retry shortly.";case"not-due":case"repaired":case"cert-renewed":case"heartbeat-refreshed":case"proxy-restored":case"refreshed":return""}},Gm=async(e={})=>{let t=e.loadProfile??L,n=e.refreshIfDue??nt,r=e.now??Date.now,o=await t();if(JE(o),!o.enrolledCert){if(!XE(o,r))throw new Error("No valid Anyray client key is stored. Set ANYRAY_CLIENT_KEY to a minted ark_ key or enroll this machine.");return{profile:o,token:o.clientKey}}let a;if(!o.clientKey||DH(o,r)){let i=LH(await n(),o);if(i){if(!XE(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(JE(s),!xe(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},qE=e=>de({user:e.name,team:e.team}),NH=({profile:e,token:t})=>{let n={},r=qE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},jm=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=qE(e);return r&&(n["x-anyray-metadata"]=r),n},$H=e=>JSON.stringify(jm(e)),zE=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=TH(e);if(o.help)return n.write(PH),0;let a=await Gm(t);a.warning&&r.write(`${a.warning}
|
|
420
420
|
`);let s=o.passthroughHeaders?$H(a):o.json?NH(a):a.token;return n.write(`${s}
|
|
421
421
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
422
422
|
`),1}};var QE=`anyray-connect models [<model-id>] [--json]
|
|
@@ -431,8 +431,8 @@ Options:
|
|
|
431
431
|
--json Emit {"origin","current","models":[{"id","wire",...caps}]} instead
|
|
432
432
|
of the table (listing only).
|
|
433
433
|
--help Show this help.
|
|
434
|
-
`,MH=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},UH=e=>{let t=ie.find(n=>n.id===oo);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},FH=e=>{let t=r=>r>=1e3?`${Math.round(r/1e3)}k`:String(r);return[...e.maxPromptTokens?[`${t(e.maxPromptTokens)} in`]:[],...e.maxOutputTokens?[`${t(e.maxOutputTokens)} out`]:[]].join(" / ")},BH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Qs(t)}/${Fn(n)==="responses"?"responses":"chat/completions"}`,
|
|
435
|
-
`),0;k(j(`Copilot models your seat serves (via ${o.origin})`));for(let h of l){let m=h.id===p?"*":" ",w=FH(h);k(` ${m} ${h.id.padEnd(24)}${w?S(w):""}`)}return M("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),M("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(p=>p.id===n.modelId);if(!d)return _(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??
|
|
434
|
+
`,MH=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},UH=e=>{let t=ie.find(n=>n.id===oo);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},FH=e=>{let t=r=>r>=1e3?`${Math.round(r/1e3)}k`:String(r);return[...e.maxPromptTokens?[`${t(e.maxPromptTokens)} in`]:[],...e.maxOutputTokens?[`${t(e.maxOutputTokens)} out`]:[]].join(" / ")},BH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Qs(t)}/${Fn(n)==="responses"?"responses":"chat/completions"}`,ex=async(e=[],t={})=>{let n=MH(e);if(n.help)return process.stdout.write(QE),0;if(n.error)return _(n.error),process.stdout.write(QE),1;let r=await(t.loadTarget??Oe)();if(!r)return _("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??xl)({allowKeychainPrompt:!0});if(!a.token)return _("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??sa)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=_f(c);if(l.length===0)return _("Could not fetch your seat's model catalog from GitHub (offline, or the sign-in lost its Copilot seat)."),1;if(!n.modelId){let p=process.env.COPILOT_MODEL?.trim();if(n.json)return process.stdout.write(`${JSON.stringify({origin:o.origin,current:p??null,models:l.map(h=>({id:h.id,wire:Fn(h.id),...h.maxPromptTokens?{maxPromptTokens:h.maxPromptTokens}:{},...h.maxOutputTokens?{maxOutputTokens:h.maxOutputTokens}:{}}))})}
|
|
435
|
+
`),0;k(j(`Copilot models your seat serves (via ${o.origin})`));for(let h of l){let m=h.id===p?"*":" ",w=FH(h);k(` ${m} ${h.id.padEnd(24)}${w?S(w):""}`)}return M("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),M("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(p=>p.id===n.modelId);if(!d)return _(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??El)(BH(o,i,d.id),{...Of(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return _(`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"?D("Could not verify the model over the lane (offline?) \u2014 applying anyway."):U(`'${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??UH)(o);if(p.status!=="configured"){for(let h of p.messages)k(h);return _("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 U(`Copilot CLI startup model \u2192 ${d.id}`),M("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var WH=`anyray-connect copilot-login
|
|
436
436
|
|
|
437
437
|
Sign Anyray in to GitHub Copilot (device flow) so the Copilot CLI seat lane
|
|
438
438
|
can run your plan's current models. Opens no browser for you: it prints a
|
|
@@ -440,16 +440,16 @@ code to type at github.com/login/device.
|
|
|
440
440
|
|
|
441
441
|
Options:
|
|
442
442
|
--help Show this help.
|
|
443
|
-
`,
|
|
444
|
-
`),0)};import{join as
|
|
443
|
+
`,tx=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(WH),0;k(j("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??Vk)();if(!n)return _("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;k(` 1. Open ${rt(n.verificationUri)}`),k(` 2. Enter the code: ${j(n.userCode)}`),M(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??Yk)(n);if(r.status!=="ok")return _(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??Zk)(r.token,o);U(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??Af)(r.token);if(s.verdict==="no-copilot")return _("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??Oe)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??sa)(r.token,{},s.capiSegment,c);return l.length===0?D("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."):U(`${l.length} models available (e.g. ${l[0].id}).`),M("Now run: anyray-connect --tools copilot-cli"),0};var nx=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??L)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=await(e.readState??kE)();return!s||s.expiresAt<=r()?(n.write("No live device token yet \u2014 start the daemon: run `anyray-connect`.\n"),1):(t.write(`${a}/device?dt=${s.token}
|
|
444
|
+
`),0)};import{join as px,dirname as zH}from"node:path";import{mkdir as QH,readFile as qm,rm as fx,writeFile as hx}from"node:fs/promises";import{fstatSync as jH,openSync as VH,statSync as YH}from"node:fs";import{createInterface as ZH}from"node:readline/promises";import{ReadStream as JH}from"node:tty";import{execFileSync as rx}from"node:child_process";import HH from"node:os";var Vm=e=>{try{return rx("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},KH=e=>{try{return rx("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},GH=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"]),Ym=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:GH.has(t):!0},ox=()=>{try{return HH.userInfo().username||void 0}catch{return}},ax=()=>Vm("user.name")??Vm("user.email")??ox()??"unknown",sx=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Vm),global:e.globalGitConfig??(t||KH)}},Ro=e=>{try{return e()?.trim()||void 0}catch{return}},Zm=(e={})=>{let t=sx(e),n=Ro(e.osUsername??ox),r=Ro(()=>t.global("user.email"))??Ro(()=>t.local("user.email"));return r||(Ro(()=>t.global("user.name"))??Ro(()=>t.local("user.name"))??n??"unknown")},ix=(e={})=>{let t=Zm(e);if(Ym(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=sx(e);return!!(Ro(()=>n.global("user.email"))??Ro(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var Yt=()=>!!process.stdin.isTTY,XH=()=>{try{let e=jH(0);return e.isCharacterDevice()&&e.rdev===YH("/dev/tty").rdev}catch{return!1}},Jm=()=>{if(XH()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new JH(VH(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},kt=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},cx=async(e,t)=>{let n=t.input??Jm(),r=t.output??process.stdout,o=ZH({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 kt))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new kt)))})}finally{o.close(),n.close()}},Fa=async(e,t={})=>{let n=(await cx(`${e} ${S("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Ba=async(e,t,n={})=>{let r=t?` ${S(`[${t}]`)}`:"";return(await cx(`${e}${r}: `,n)).trim()||t},lx=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return M(`Your name: ${t} ${S("(cached \u2014 pass --user to change)")}`),t;let r=ax();return n||!Yt()?(M(`Your name: ${r} ${S("(auto-detected \u2014 pass --user to change)")}`),r):Ba("? Your name",r)},dx=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return M(`Team: ${t} ${S("(cached \u2014 pass --team to change)")}`),t;if(!(n||!Yt()))return Ba("? Team (optional)")},Dr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return un(e??n)},ux=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,Wa="claude-desktop",Ui=e=>e!=="cursor",Fi=(e,t,n)=>Ui(e)?n:t,qd=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await xr(e.runReg??Zn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Ht({home:e.home});return await R(s)?{authoritative:!0}:n("no-local-record")}if(t!=="darwin")return n("manual-platform");let r={home:e.home,managedPolicyPaths:e.managedPolicyPaths,readManagedPolicyKeys:e.readManagedPolicyKeys},o=an(r);return await uo(o,r)?n("managed-policy"):(await Ea({home:e.home,readClaudeAppVersion:e.readClaudeAppVersion,readClaudeAppBundle:e.readClaudeAppBundle})).supported?await R(o.journal)?{authoritative:!0}:n("no-local-record"):n("unverified-build")}catch{return n("no-local-record")}},zd=e=>e.id!==Wa||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",qH={"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"},Qd=(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=qH[t.reason??"no-local-record"],r=t.mcpRegistered?`retrieval MCP server registered, but inference routing can't be verified (${n}).`:`inference routing can't be verified (${n}), and the retrieval MCP server is not registered.`;return t.reason==="managed-policy"?{headline:r,detail:["Managed policy is authoritative; Connect will not overwrite or auto-repair it. Update the organization MDM profile or bootstrap service.","Bootstrap changes need no MDM redeployment; Claude applies the refreshed configuration on the next app launch."]}:t.reason==="policy-unreadable"?{headline:r,detail:["Connect could not prove whether HKLM policy is authoritative, so it will not overwrite or auto-repair the per-user route.","Check the organization policy and registry-read permissions, then run `anyray-connect doctor` again."]}:{headline:r,detail:["If Claude Desktop's third-party inference setup was never completed, its traffic bypasses the gateway and is NOT optimized.","Check: Claude Desktop \u2192 Developer \u2192 Configure Third-Party Inference; re-run `anyray-connect desktop` to reprint the steps.",...t.mcpRegistered?[]:["Re-running from a durable install also registers the retrieval MCP server."]]}};var Xm=["claude-code","codex"],eK="anyray-connect print-key",zm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tK=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:rs,authMode:"placeholder",metadata:{}}),Qm=e=>px(e,".claude","settings.json"),nK=async(e,t,n)=>{let r=Qm(e),o=await F(r),{env:a}=fn(t,{includeAuthToken:!1,includeClientKey:!1}),s=zm(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!jr(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=eK,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]}},mx=async(e=process.cwd())=>{let t=[],n=Qm(e);try{if(await R(n)){let o=await F(n),a=zm(o.env)?o.env:{};(Kr.some(s=>s in a)||jr(o))&&t.push(n)}}catch{}let r=ey(e);try{if(await R(r)){let o=await qm(r,"utf-8");Rp(o)&&t.push(r)}}catch{}return t},rK=async(e,t)=>{let n=Qm(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await F(n),o=!1;if(zm(r.env)){let s={...r.env};for(let i of Kr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(jr(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 fx(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]}},ey=e=>px(e,".codex","config.toml"),oK=async(e,t,n)=>{let r=ey(e),o=await qm(r,"utf-8").catch(()=>""),a=Zc(o,_s(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await QH(zH(r),{recursive:!0}),await hx(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]}},aK=async(e,t)=>{let n=ey(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await qm(n,"utf-8"),o=Jc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await fx(n,{force:!0}):await hx(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},yx=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Xm],r=n.filter(s=>!Xm.includes(s));if(r.length>0)return _(`--project supports ${Xm.join(", ")} \u2014 not: ${r.join(", ")}. Other tools keep per-machine state (run anyray-connect without --project there).`),1;let o;if(!e.revert){let s=await L(),i=e.gateway??s.gateway;if(!i)return _("--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 _(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=tK(Je(i))}if(k(j(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),K("Project"),k(` Directory: ${t}`),o&&k(` Gateway: ${o.origin}`),k(` Tools: ${n.join(", ")}`),e.revert||(D(`
|
|
445
445
|
A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),M(" Each machine still needs `anyray-connect` on PATH and a one-time enrollment (--sso/--enroll); the files carry no credential and no identity.")),!e.yes&&!e.dryRun){if(!Yt())return _(`
|
|
446
446
|
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 Fa(`
|
|
447
447
|
${s} ${n.length} tool(s)?`))return M("Aborted. Nothing changed."),0}e.dryRun&&M(`
|
|
448
|
-
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){K(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await nK(t,o,e.dryRun):await oK(t,o,e.dryRun):s==="claude-code"?await rK(t,e.dryRun):await aK(t,e.dryRun);for(let c of i.messages)k(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(K("Next"),e.revert)U(" Project config removed. Commit the change to propagate it.");else{U(" Commit these files to route every checkout of this repo:");for(let s of a)k(` ${s}`);k(S(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as sK}from"node:child_process";var iK="/usr/bin/security",cK=["find-generic-password","-s","Claude Code-credentials","-w"],lK=1e4,dK=64*1024,uK=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,
|
|
449
|
-
`),1;try{let o=await
|
|
448
|
+
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){K(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await nK(t,o,e.dryRun):await oK(t,o,e.dryRun):s==="claude-code"?await rK(t,e.dryRun):await aK(t,e.dryRun);for(let c of i.messages)k(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(K("Next"),e.revert)U(" Project config removed. Commit the change to propagate it.");else{U(" Commit these files to route every checkout of this repo:");for(let s of a)k(` ${s}`);k(S(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as sK}from"node:child_process";var iK="/usr/bin/security",cK=["find-generic-password","-s","Claude Code-credentials","-w"],lK=1e4,dK=64*1024,uK=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,gx="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",pK=(e,t,n)=>new Promise((r,o)=>{sK(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),wx=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),fK=e=>{let t=JSON.parse(e);if(!wx(t)||!wx(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!uK.test(n))throw new Error("unexpected keychain access token");return n},bx=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${gx}
|
|
449
|
+
`),1;try{let o=await Gm(t),a=jm(o),s=await(t.execSecurity??pK)(iK,[...cK],{encoding:"utf8",timeout:lK,maxBuffer:dK,shell:!1}),i=fK(s.stdout);return o.warning&&r.write(`${o.warning}
|
|
450
450
|
`),n.write(`${JSON.stringify({token:i,headers:a})}
|
|
451
|
-
`),0}catch{return r.write(`${
|
|
452
|
-
`),1}};import{mkdir as WK,writeFile as HK}from"node:fs/promises";import{dirname as KK}from"node:path";import{Buffer as GK}from"node:buffer";import{constants as
|
|
451
|
+
`),0}catch{return r.write(`${gx}
|
|
452
|
+
`),1}};import{mkdir as WK,writeFile as HK}from"node:fs/promises";import{dirname as KK}from"node:path";import{Buffer as GK}from"node:buffer";import{constants as kx}from"node:fs";import{access as hK,chmod as mK,mkdir as yK,open as gK,readFile as wK,realpath as bK,rm as kK,stat as vx,writeFile as CK}from"node:fs/promises";import{randomUUID as AK}from"node:crypto";import{platform as Sx}from"node:os";import{dirname as vK,join as SK,posix as EK,win32 as Ex}from"node:path";var Bi="/usr/local/bin/anyray-credential-helper",Wi="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",ty="Managed by anyray-connect desktop helper; do not edit.",xK=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
|
|
453
453
|
|
|
454
454
|
Create the credential helper required by Claude Desktop and Codex fleet
|
|
455
455
|
artifacts. The helper stores no key. It invokes a durable anyray-connect binary
|
|
@@ -479,13 +479,13 @@ Examples:
|
|
|
479
479
|
|
|
480
480
|
anyray-connect desktop helper --print --platform posix \\
|
|
481
481
|
--bin /usr/local/bin/anyray-connect > anyray-credential-helper
|
|
482
|
-
`,
|
|
483
|
-
`);let r=PK(n);return["#!/bin/sh",`# ${
|
|
484
|
-
`)},
|
|
485
|
-
`),0;if(s!==
|
|
482
|
+
`,Cx=(e=Sx())=>e==="win32"?"windows":"posix",IK=e=>e==="windows"?Wi:Bi,Ax=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},RK=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":Ax(t,"write");break;case"--print":Ax(t,"print");break;case"--bin":t.binaryPath=o();break;case"--path":t.helperPath=o();break;case"--platform":{let a=o();if(a!=="posix"&&a!=="windows")throw new Error("--platform must be posix or windows");t.targetPlatform=a;break}case"--help":case"-h":t.help=!0;break;default:throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r}`)}}return t},OK=e=>/[\0\r\n]/.test(e),_K=e=>/^[A-Za-z]:[\\/]/.test(e)&&Ex.isAbsolute(e),Hi=(e,t)=>!OK(e)&&(t==="windows"?_K(e):EK.isAbsolute(e)),ny=e=>e.replace(/\\/g,"/").toLowerCase(),xx=(e,t)=>{if(!Hi(e,t))return!1;let n=ny(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)))},ry=(e,t)=>t==="windows"?Ex.normalize(e):e,PK=e=>`'${e.replace(/'/g,`'"'"'`)}'`,TK=(e,t)=>{if(!xx(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=ry(t,e);if(e==="windows")return["@echo off",`REM ${ty}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" print-key --json`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
483
|
+
`);let r=PK(n);return["#!/bin/sh",`# ${ty}`,'if [ "$#" -eq 0 ]; then',` exec ${r} print-key --json`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
|
|
484
|
+
`)},eu=(e,t)=>{if(!Hi(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=ry(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"]}},DK=async e=>{try{return await wK(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},LK=async(e,t)=>{try{let n=await bK(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!xx(r,t))throw new Error;if(!(await vx(n)).isFile())throw new Error;await hK(n,t==="posix"?kx.X_OK:kx.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},NK=e=>e.slice(0,300).includes(ty),$K=async(e,t,n)=>{let r=await DK(e);if(r!==void 0&&r!==t&&!NK(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 vx(e)).mode&511)===493)return"unchanged"}catch{}}let o=vK(e);try{await yK(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=SK(o,`.anyray-credential-helper.${process.pid}.${AK()}.tmp`),s=!1;try{await CK(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await mK(a,493);let i=await gK(a,"r");try{await os(i)}finally{await i.close()}await he(a,e),s=!0}catch{throw new Error(`could not install credential helper at ${e}`)}finally{s||await kK(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},Ix=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=RK(e);if(o.help)return n.write(xK),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");let a=(t.platform??Sx)(),s=o.targetPlatform??Cx(a),i=ry(o.helperPath??IK(s),s);if(!Hi(i,s))throw new Error(`--path must be an absolute ${s} path`);if(s==="windows"&&eu("windows",i),ny(i)===ny(o.binaryPath))throw new Error("--path must differ from --bin (the helper cannot invoke itself)");let c=TK(s,o.binaryPath);if(o.mode==="print")return n.write(c),r.write(`Deploy this wrapper at ${i} after deploying the binary at ${o.binaryPath}.
|
|
485
|
+
`),0;if(s!==Cx(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await LK(o.binaryPath,s);let l=await $K(i,c,s);return r.write(l==="unchanged"?`Credential helper already current at ${i}.
|
|
486
486
|
`:`${l==="installed"?"Installed":"Updated"} credential helper at ${i}.
|
|
487
487
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
488
|
-
`),1}};var MK=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),UK=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,FK=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.")},BK=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),
|
|
488
|
+
`),1}};var MK=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),UK=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,FK=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.")},BK=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),tu=(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!==""||FK(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ha=(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()}},Rx=e=>{if(!BK(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!MK.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ha(e.clientId,"clientId",!0),r=Ha(e.scopes,"scopes",!0),o=Ha(e.issuer,"issuer",!1),a=Ha(e.authorizationUrl,"authorizationUrl",!1),s=Ha(e.tokenUrl,"tokenUrl",!1),i=Ha(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:tu(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:tu(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:tu(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},Ox=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return Rx(t)},oy=e=>{let t=tu(e.url,"--bootstrap-url"),n=e.oidc?Rx(e.oidc):void 0,r;if(e.deploymentOrganizationUuid!==void 0&&(r=e.deploymentOrganizationUuid.trim(),!UK.test(r)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:t,...n?{bootstrapOidc:n}:{},...r?{deploymentOrganizationUuid:r}:{}}},ay=e=>pa(oy(e));var jK=`anyray-connect desktop [disconnect] [options]
|
|
489
489
|
|
|
490
490
|
The minimum Claude Desktop workflow:
|
|
491
491
|
anyray-connect desktop Connect this machine
|
|
@@ -527,8 +527,8 @@ Options:
|
|
|
527
527
|
|
|
528
528
|
Older flag-based Claude artifacts and Codex fleet output remain accepted for
|
|
529
529
|
compatibility, but are not part of the recommended Claude Desktop workflow.
|
|
530
|
-
`,VK=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",YK=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),ZK=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[VK(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...YK(o)]},JK=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),
|
|
531
|
-
<string>${tr(t)}</string>`,
|
|
530
|
+
`,VK=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",YK=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),ZK=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[VK(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...YK(o)]},JK=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),sy=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>JK.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"]},tr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),_x=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),XK=(e,t)=>` <key>${tr(e)}</key>
|
|
531
|
+
<string>${tr(t)}</string>`,iy=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>XK(i,c)).join(`
|
|
532
532
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
533
533
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
534
534
|
<plist version="1.0">
|
|
@@ -561,12 +561,12 @@ ${s}
|
|
|
561
561
|
<string>${tr(n)}</string>
|
|
562
562
|
</dict>
|
|
563
563
|
</plist>
|
|
564
|
-
`},
|
|
565
|
-
`,zK=e=>
|
|
566
|
-
`,
|
|
567
|
-
`),
|
|
564
|
+
`},Tx=(e,t)=>iy("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",pa(lo(e,t))),qK=(e,t)=>`${JSON.stringify(lo(e,t),null,2)}
|
|
565
|
+
`,zK=e=>iy("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",ay(e)),QK=e=>`${JSON.stringify(oy(e),null,2)}
|
|
566
|
+
`,Dx=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries(e).map(([n,r])=>`"${_x(n)}"="${_x(r)}"`),""].join(`
|
|
567
|
+
`),Lx=(e,t)=>{let n=ed(e,t);return Dx(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},eG=e=>Dx(ay(e)),Nx=(e,t,n)=>{if(t==="darwin"){let r=Bi;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:Tx(e,r),helperPath:r}}if(t==="win32"){let r=Wi;return{path:`${n}\\claude-desktop-anyray.reg`,content:Lx(e,r),helperPath:r}}},$x=(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."],tG=(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=eu(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${_s(e,o).join(`
|
|
568
568
|
`)}
|
|
569
|
-
`},nG=e=>
|
|
569
|
+
`},nG=e=>iy("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:GK.from(e,"utf-8").toString("base64")}),rG=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},oG=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=un(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:rs,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},Px=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??WK,o=n.writeFile??HK;await r(KK(t),{recursive:!0}),await o(t,e)},aG=(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:
|
|
570
570
|
`),o.write(r==="windows"?` anyray-connect desktop helper --write --platform windows --bin "C:\\Program Files\\Anyray\\anyray-connect.exe" --path "${n}"
|
|
571
571
|
`:` sudo anyray-connect desktop helper --write --platform posix --bin /usr/local/bin/anyray-connect --path '${n.replace(/'/g,`'"'"'`)}'
|
|
572
572
|
`),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.
|
|
@@ -585,8 +585,8 @@ Reopen Claude Desktop \u2014 migrated ${c} available in the Anyray profile.
|
|
|
585
585
|
Your previous profile is untouched, so \`desktop disconnect\` still works.
|
|
586
586
|
`)}else n.write(`
|
|
587
587
|
Nothing new to migrate \u2014 no local sessions or portable local data needed copying.
|
|
588
|
-
`);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},
|
|
589
|
-
`),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 ${Bi} on macOS/Linux or ${Wi} 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(!Hi(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"&&
|
|
588
|
+
`);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},Mx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=ZK(e);if(o[0]==="helper")return Ix(o.slice(1),t);let a=rG(o);if(a.help)return n.write(jK),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 iG(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:Ox(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?eG(u):a.artifact==="json"?QK(u):zK(u);return await Px(f,a.path,t),sG(r),a.path&&n.write(`Wrote ${a.path}
|
|
589
|
+
`),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 ${Bi} on macOS/Linux or ${Wi} 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(!Hi(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"&&eu("windows",i);let l=oG(a),d;if(a.target==="claude")d=a.artifact==="reg"?Lx(l,i):a.artifact==="json"?qK(l,i):Tx(l,i);else{let u=tG(l,i);d=a.artifact==="mobileconfig"?nG(u):u}return await Px(d,a.path,t),aG(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
|
|
590
590
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
591
591
|
`),1}};var cG=`anyray-connect retrieve <handle> [--source auto|claude|profile]
|
|
592
592
|
|
|
@@ -609,36 +609,36 @@ Options:
|
|
|
609
609
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
610
610
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
611
611
|
--help Show this help.
|
|
612
|
-
`,
|
|
612
|
+
`,Ux=(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},dG=e=>e.replace(/[\t\r\n]+/g," ").trim(),Fx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=Ux(e,!1);if(o.help)return n.write(cG),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
|
|
613
613
|
`),1;let s=await(t.readTarget??at)(o.source),i=await(t.retrieve??_a)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
|
|
614
614
|
`),1)}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
615
|
-
`),1}},
|
|
616
|
-
`),1;let s=await(t.readTarget??at)(o.source),i=await(t.recall
|
|
615
|
+
`),1}},Bx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=Ux(e,!0);if(o.help)return n.write(lG),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
|
|
616
|
+
`),1;let s=await(t.readTarget??at)(o.source),i=await(t.recall??$d)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
|
|
617
617
|
`),1;if(i.matches.length===0)return r.write(`No matching externalized outputs found.
|
|
618
618
|
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${dG(c.preview)}
|
|
619
619
|
`)}return r.write(`Fetch a full original: anyray-connect retrieve <handle>
|
|
620
620
|
`),0}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
621
621
|
`),1}};import{promises as $G}from"node:fs";var Rn=e=>typeof e=="string"?e:"",uG=e=>{let t=Rn(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=Rn(o.text).trim();a&&r.push(a)}return r.join(`
|
|
622
622
|
|
|
623
|
-
`).trim()},pG=e=>{let t=Rn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},fG=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=uG(r);if(!o)continue;let a=Rn(r.created_at).trim();t.push({role:pG(r),text:o,...a?{createdAt:a}:{}})}return t},
|
|
623
|
+
`).trim()},pG=e=>{let t=Rn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},fG=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=uG(r);if(!o)continue;let a=Rn(r.created_at).trim();t.push({role:pG(r),text:o,...a?{createdAt:a}:{}})}return t},nu=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=fG(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(Rn(s.uuid)||Rn(s.id)).trim(),l=(Rn(s.name)||Rn(s.title)).trim()||"Untitled conversation",d=Rn(s.created_at).trim(),u=Rn(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 _G}from"node:crypto";import{promises as Gi}from"node:fs";import{homedir as Yx}from"node:os";import{join as au}from"node:path";import{promises as Wx}from"node:fs";import cy from"node:path";var hG=4e4,mG=16*1024*1024,Ki=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),ru=async(e,t={})=>{let n=(e??"").trim();if(!n)return Ki("","path is required");let r=t.cwd??process.cwd(),o=cy.resolve(r,n),a=cy.relative(r,o);if(a.startsWith("..")||cy.isAbsolute(a))return Ki(n,"path is outside the workspace");let s=t.maxBytes??hG,i;try{let w=await Wx.stat(o);if(!w.isFile())return Ki(n,"not a regular file");let g=t.maxFileBytes??mG;if(w.size>g)return Ki(n,`file too large to read (${w.size} bytes; limit ${g})`);i=await Wx.readFile(o,"utf8")}catch(w){return Ki(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
|
|
624
624
|
`),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(`
|
|
625
625
|
`),p=l<=d?d:l,h=!1,m=!1;if(Buffer.byteLength(f,"utf8")>s){let w=0,g=0;for(let y of u){let b=Buffer.byteLength(y,"utf8")+(g===0?0:1);if(w+b>s)break;w+=b,g+=1}g===0?(f=Buffer.from(u[0]??"","utf8").subarray(0,s).toString("utf8").replace(/\uFFFD$/,""),p=l,h=!0):(f=u.slice(0,g).join(`
|
|
626
|
-
`),p=l+g-1),m=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:m,span:{startLine:l,endLine:p,...h?{partialLine:!0}:{}}}},
|
|
626
|
+
`),p=l+g-1),m=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:m,span:{startLine:l,endLine:p,...h?{partialLine:!0}:{}}}},ly=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
|
|
627
627
|
${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}
|
|
628
|
-
${e.content}`};import{spawn as yG}from"node:child_process";import{promises as
|
|
629
|
-
`)){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:
|
|
630
|
-
`);for(let v=0;v<A.length;v+=1){let E=c(A[v]);if(l.some(
|
|
628
|
+
${e.content}`};import{spawn as yG}from"node:child_process";import{promises as dy}from"node:fs";import uy from"node:path";var py=400,gG=240,wG=4e3,bG=4e3,kG=512*1024,CG=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),Kx=(e,t)=>e.length>t?e.slice(0,t):e,AG=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"]),vG=8,SG=2e3,EG=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],xG=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")},Gx=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!AG.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=vG))break}return n},jx=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},IG=(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)},Hx=(e,t,n)=>{let r=[];for(let o of e.split(`
|
|
629
|
+
`)){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:Kx(l,t)})}return r},RG=(e,t,n,r,o,a,s)=>new Promise(i=>{let c=["--line-number","--no-heading","--color","never","--max-columns",String(o),"--max-columns-preview","--smart-case","--max-count","20","--fixed-strings"];for(let h of n)c.push("-g",h);for(let h of EG)c.push("-g",h);if(s?.length){for(let h of s)c.push("-e",h);c.push("--",".")}else c.push("--",e,".");let l;try{l=yG("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,f=h=>{u||(u=!0,clearTimeout(p),i(h))},p=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let h=Hx(d,o,r);f({ok:!0,matches:h,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",h=>{if(d+=h,d.length>r*(o+64))try{l.kill("SIGKILL")}catch{}}),l.on("error",()=>{f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"})}),l.on("close",h=>{if(typeof h=="number"&&h>=2){f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let m=Hx(d,o,r+1),w=m.length>r;f({ok:!0,matches:w?m.slice(0,r):m,truncated:w,engine:"ripgrep"})})}),OG=async(e,t,n,r,o,a,s)=>{let i=jx(s?.length?s:e),c=m=>i?m:m.toLowerCase(),l=(s?.length?s:[e]).map(c),d=n.map(m=>m.replace(/^\*+/,"")).filter(m=>m.startsWith(".")),u=[],f=0,p=!1,h=async m=>{if(u.length>=r||Date.now()>a){p=!0;return}let w;try{w=await dy.readdir(m,{withFileTypes:!0})}catch{return}for(let g of w){if(u.length>=r||Date.now()>a){p=!0;return}let y=uy.join(m,g.name);if(g.isDirectory()){if(CG.has(g.name))continue;await h(y)}else if(g.isFile()){if(f>=bG){p=!0;return}if(d.length&&!d.some(v=>g.name.endsWith(v))||xG(uy.relative(t,y)))continue;f+=1;let b;try{if((await dy.stat(y)).size>kG)continue;b=await dy.readFile(y,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let A=b.split(`
|
|
630
|
+
`);for(let v=0;v<A.length;v+=1){let E=c(A[v]);if(l.some(x=>E.includes(x))&&(u.push({file:uy.relative(t,y),line:v+1,text:Kx(A[v],o)}),u.length>=r)){p=!0;return}}}}};return await h(t),{ok:!0,matches:u,truncated:p,engine:"walk"}},ou=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??py,s=t.maxColumns??gG,i=t.timeoutMs??wG,c=Date.now()+i,l=Gx(n),d=l.length>1,u=Math.min(a*4,SG),f=(g,y)=>OG(n,r,o,g,s,c,y),p=async g=>{let y=await g(u,l);if(!y.ok)return y;let b=IG(y.matches,l,jx(l)),A=b.length>a;return{...y,matches:A?b.slice(0,a):b,truncated:y.truncated||A,matched:"tokens",tokens:l}};if(t.engine==="walk"){let g=await f(a);return g.matches.length>0||!d?g:p((y,b)=>f(y,b))}let h=(g,y)=>RG(n,r,o,g,s,Math.max(0,c-Date.now()),y),m=await h(a);if(m.ok){if(m.matches.length>0||!d)return m;let g=await p((y,b)=>h(y,b));return g.ok?g:p((y,b)=>f(y,b))}let w=await f(a);return w.matches.length>0||!d?w:p((g,y)=>f(g,y))},Vx=(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=Gx(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.
|
|
631
631
|
`:"";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(`
|
|
632
632
|
`)}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(`
|
|
633
633
|
`):[o,...a.slice(0,Math.max(1,l)),s(a.length-Math.max(1,l))].join(`
|
|
634
|
-
`)};var
|
|
634
|
+
`)};var Zx=448,PG=384,TG=4e4,Nr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=au(Yx(),".anyray");try{if((await Gi.stat(t)).isDirectory())return au(t,"history")}catch{}return au(Yx(),".anyray-history")},DG=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:LG(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},LG=e=>{let t=_G("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)},NG=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}
|
|
635
635
|
|
|
636
636
|
${r.text}
|
|
637
637
|
`});return[...t,...n].join(`
|
|
638
638
|
`).replace(/\n{3,}/g,`
|
|
639
639
|
|
|
640
640
|
`)+`
|
|
641
|
-
`},
|
|
641
|
+
`},su=async e=>{let t=await Nr();await Gi.mkdir(t,{recursive:!0,mode:Zx});try{await Gi.chmod(t,Zx)}catch{}let n=0,r=0;for(let o of e)try{await Gi.writeFile(au(t,DG(o)),NG(o),{mode:PG}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Ka=async()=>{try{let e=await Nr();return(await Gi.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},Jx=async e=>{let t=await Nr();return ou(e,{cwd:t,globs:["*.md"]})},Xx=async e=>{let t=await Nr();return ru(e,{cwd:t,maxBytes:TG})};var qx=`anyray-connect history <command>
|
|
642
642
|
|
|
643
643
|
Make past Claude conversations searchable from any Anyray-connected client.
|
|
644
644
|
|
|
@@ -659,7 +659,7 @@ Which one you want:
|
|
|
659
659
|
conversation into the chat when you ask for it. Recall, not a list.
|
|
660
660
|
|
|
661
661
|
Running both is fine, and gets you both.
|
|
662
|
-
`,MG=async e=>{try{return{raw:await $G.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"})`}}},UG=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return _("Usage: anyray-connect history import <conversations.json>"),k(S("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await MG(t);if("error"in n)return _(n.error),1;let r=
|
|
662
|
+
`,MG=async e=>{try{return{raw:await $G.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"})`}}},UG=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return _("Usage: anyray-connect history import <conversations.json>"),k(S("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await MG(t);if("error"in n)return _(n.error),1;let r=nu(n.raw);if(!r.ok)return _(`Could not read that export: ${r.message??"unrecognized format"}`),k(S("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 _("That export contains no conversations with readable messages."),1;let o;try{o=await su(r.conversations)}catch(a){let s=a?.code;return _(`Could not create the history archive (${s??"write failed"}).`),k(S("Check that ~/.anyray is a writable directory, then try again.")),1}return U(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&k(S(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&D(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),k(""),k(j("Your history is now searchable from any Anyray-connected client.")),k(S(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),k(S(" and the assistant can search this archive and pull it up.")),k(S(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),k(S(" for them, they do not reappear as a clickable list in the app.")),0},FG=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return _("Usage: anyray-connect history restore <export.zip>"),k(S("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await nd(t);return n.ok?(U(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&k(S(` ${n.skipped} already present, left untouched.`)),n.failed>0&&D(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),k(""),k(j("Open Claude Desktop \u2014 they are in the sidebar again.")),k(S(" Anyray stays configured; this changed nothing about your routing.")),k(S(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),k(S(" undocumented. A future Desktop release could stop reading it \u2014 your export")),k(S(" file still works, and `history import` remains a second copy.")),0):(_(`Could not restore into Claude Desktop: ${n.reason}`),k(S(` ${n.remedy}`)),1)},BG=async()=>{let e=await Nr(),t=await Ka();return t===0?(k(`No conversations imported yet. Archive would live at ${e}`),k(S(" Import one with: anyray-connect history import <conversations.json>")),0):(U(`${t} conversation${t===1?"":"s"} in ${e}`),0)},zx=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(qx),0):t==="import"?UG(e.slice(1)):t==="restore"?FG(e.slice(1)):t==="status"?BG():(_(`Unknown history command: ${t}`),console.log(qx),1)};import{promises as WG}from"node:fs";var HG=`anyray-connect migrate [options]
|
|
663
663
|
|
|
664
664
|
Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
|
|
665
665
|
|
|
@@ -688,50 +688,51 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
|
|
|
688
688
|
Open claude.ai -> Settings -> Privacy -> Export data. Anthropic emails a link.
|
|
689
689
|
Pass the .zip to --export, and the conversations.json inside it to
|
|
690
690
|
--conversations. Both are safe to re-run; they skip what is already there.
|
|
691
|
-
`,KG=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},
|
|
692
|
-
`).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${GG(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";k(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&D(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&D(` 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&&D(` ${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??[])D(` ${
|
|
691
|
+
`,KG=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},Qx={code:"Claude Code sessions",cowork:"Cowork tasks"},GG=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`${Qx[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},jG=async(e,t)=>{k(j("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??ho)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){_(` ${n.reason}`);for(let s of n.remedy.split(`
|
|
692
|
+
`).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${GG(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";k(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&D(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&D(` 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&&D(` ${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??[])D(` ${Qx[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${Wh(s.reason,s.lane,"anyray-connect migrate")}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&k(S(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},VG=async(e,t)=>{if(k(""),k(j("2. Your claude.ai chats")),t){k(S(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){k(" These live on your Claude account, not this machine, so they need"),k(" an export. Anyray cannot fetch them: the only credential that could"),k(" is your claude.ai session, which Connect never holds."),k(S(" claude.ai -> Settings -> Privacy -> Export data, then:")),k(S(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await nd(e.exportZip);if(!n.ok){_(` ${n.reason}`),k(` ${n.remedy}`);return}U(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),k(S(" 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);U(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&k(S(` Instructions and docs are in ${r.root}, listed under Projects.`))}},YG=async e=>{if(k(""),k(j("3. Searchable from every Anyray client")),!e.conversations){let o=await Ka();o>0?k(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(k(S(" Optional. Pass the conversations.json inside the export:")),k(S(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await WG.readFile(e.conversations,"utf8")}catch{_(` could not read ${e.conversations}`);return}let n=nu(t);if(!n.ok){_(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await su(n.conversations);U(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),k(S(` Ask any Anyray-connected client about a past chat. ${await Nr()}`))},ZG=e=>{k(""),k(j("Next")),k(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||D(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),k(S(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},eI=async(e,t={})=>{let n;try{n=KG(e)}catch(o){return _(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(HG),0;k(j("Migrating Claude Desktop onto Anyray")),k(S("Claude Desktop must be fully quit.")),k("");let r=await jG(n,t);return await VG(n,!r),await YG(n),r?(ZG(n),0):(k(""),D("Fix the item above and re-run to finish the migration."),1)};var JG=3e3,iu=async(e,t={})=>{let n=t.timeoutMs??JG,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`:bt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};var XG="enl_",qG="enp_",tI=e=>e.startsWith(XG)||e.startsWith(qG),zG=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],fy=e=>zG.find(t=>e.startsWith(t.prefix)),nI=/^\/enroll\/([^/]+)\/?$/,rI=/^\/i\/([^/]+)\/?$/,oI=e=>{let t=e.match(nI);if(t)return fy(t[1])?void 0:t[1];let n=e.match(rI);return n&&tI(n[1])?n[1]:void 0},QG=1e4,cu=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=oI(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!fy(t))return{cpOrigin:qn(),token:t}},aI=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(nI)??o.pathname.match(rI);if(!a)return;n=a[1]}catch{}let r=fy(n);return r?{flag:r.flag,what:r.what}:void 0},Vi=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:oI(n.pathname)!==void 0}catch{return tI(t)}},ji=e=>typeof e=="string"&&e.trim()?e.trim():void 0,sI=async(e,t={})=>{let n=t.timeoutMs??QG,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.`:bt(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${f}`)}finally{clearTimeout(a)}if(!s.ok)throw new Error(`enrollment link lookup failed: ${e.cpOrigin} responded ${s.status} \u2014 the link may be expired or revoked; ask your admin for a fresh one.`);let i;try{i=await s.json()}catch{throw new Error(`enrollment link lookup failed: ${e.cpOrigin} returned a malformed response`)}let l=(Array.isArray(i?.gateways)?i.gateways:[]).find(u=>u!==null&&typeof u=="object"&&ji(u.url)!==void 0),d=ji(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:ji(l?.deploymentId),org:ji(i.org),email:ji(i.email),seatMode:i.seatMode===!0}};var iI=()=>Jm(),cI=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??iI)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},ej=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},lI=async(e,t={})=>{let n=(t.openInput??iI)(),r=n.stream,o=t.output??process.stderr;if(typeof r.setRawMode!="function")throw n.close(),new Error("raw terminal input is unavailable");let a=e.items.map(h=>h.selected===!0&&h.requiresExplicitChoice!==!0),s=0,i=0,c=Ma(o,t.env??process.env),l=(h,m)=>c?`\x1B[${h}m${m}\x1B[0m`:m,d=()=>{let h=[l("1",e.title)];for(let m=0;m<e.items.length;m++){let w=e.items[m],g=m===s?l("36","\u276F"):" ",y=e.single?a[m]?"(\u25CF)":"(\u25CB)":a[m]?"[x]":"[ ]",b=w.hint?` ${l("2",w.hint)}`:"";h.push(`${g} ${y} ${w.label}${b}`)}h.push(l("2",e.single?"\u2191/\u2193 move \xB7 space choose \xB7 enter accept \xB7 q cancel":"\u2191/\u2193 move \xB7 space toggle \xB7 a toggle all \xB7 enter accept \xB7 q cancel")),i>0&&o.write(`\x1B[${i}A`),o.write(h.map(m=>`\r\x1B[2K${m}`).join(`
|
|
693
693
|
`)),o.write(`
|
|
694
694
|
`),i=h.length},u=()=>{i!==0&&(o.write(`\x1B[${i}A`),o.write(Array.from({length:i},()=>`\r\x1B[2K
|
|
695
|
-
`).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,p=!1;try{return p=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((h,m)=>{let w=()=>{r.off("data",v),r.off("end",b),r.off("close",b),r.off("error",A)},g=E=>{w(),h(E)},y=E=>{w(),m(E)},b=()=>g({kind:"cancelled"}),A=E=>y(E),v=E=>{try{for(let
|
|
696
|
-
`)&&g({kind:"ok",values:[]});continue}if(
|
|
697
|
-
`){g({kind:"ok",values:e.items.filter((C,
|
|
698
|
-
`),t();let a=0,s=()=>{r.write(`\r${
|
|
699
|
-
`)){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()}},hx=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&&ja(e.current,e.minVersion)<0&&ja(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},gj=e=>ja(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}:{...hx(e),downgradeBlocked:!1},Va=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",wj=(e=process.execPath)=>{let t=ju(e);return t?$r(t):$r($r(e))},bj=async(e=yt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=ft(wj(e.execPath),"bin",Va());try{if(await lu(t)!==await lu(e.execPath))return}catch{return}return t},by=async(e=yt(),t=ee())=>{let n=await bj(e);if(n)return{kind:"managed",root:$r($r(n)),link:n,entryPath:or(e)};let r=or(e);return Yu(r,t)?{kind:"durable",root:t,entryPath:r}:Ku(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},uu=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)}},ky=async(e=du)=>{let t=await uu(`${ux}/latest`,e,{redirect:"manual"});return yj(t.headers.get("location"))},kj=async e=>{try{let t=await uu(`${e}/connect-update.json`,du);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}},Zi=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},Cy=async(e,t,n)=>{let r=await uu(e,fj);if(!r.ok||!r.body)throw new Zi(r.status);let o=cj("sha256"),a=0;if(await dj(lj.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>pj)throw new Error("asset exceeds size cap");o.update(c),yield c}},nj(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},Cj=e=>fy(e)===Va()?fy($r(e)):fy(e),Aj=async e=>{let t=await gy(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Pt(ft(e,n),{force:!0}).catch(()=>{})},mx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Pt(r,{force:!0}).catch(()=>{});let o=!1;try{await cu(e,r),o=!0}catch{}try{await my(t,e),await ij(ls(e),Cj(t))}catch(a){throw o&&await cu(r,e).catch(()=>{}),a}await Pt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Pt(n,{force:!0}),await sj(t,n),await cu(n,e)},vj=async(e,t={})=>{let n=ft(e.root,"bin"),r=ft(e.root,"versions"),o=ft(n,Va());await Ga(n,{recursive:!0,mode:448}),await Ga(r,{recursive:!0,mode:448});let a=ft(r,e.version),i=(await yy(a).catch(()=>{}))?.isFile()?a:ft(a,Va());if(!(await yy(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??uu)(`${e.tagUrl}/SHA256SUMS`,du),d=l.ok?wy(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await Ga($r(i),{recursive:!0,mode:448}),await Aj($r(i));let u=`${i}.part-${process.pid}`;try{await(t.download??Cy)(`${e.tagUrl}/${e.asset}`,u,d),await oj(u,493),await cu(u,i)}catch(f){throw await Pt(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??mx)(o,i),{link:o,target:i,versionsDir:r}},Sj=async e=>{let t=rj(e,["--version"],{stdio:"ignore",timeout:du});return!t.error&&t.status===0},Ej=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??ko)(n);if(r.length>0){let o=await(t.resolveTarget??Oe)(async()=>e);if(!o||!(await(t.repair??wt)(r,o.target)).every(bo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??hr)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Nt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},Ij=async e=>{let t=await e.install();if(!await(e.smoke??Sj)(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},xj=async(e,t)=>{let n=await gy(e).catch(()=>[]);for(let r of n)t.includes(r)||await Pt(ft(e,r),{force:!0,recursive:!0}).catch(()=>{})},Rj=async e=>{let t=await gy(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Pt(ft(e,n),{force:!0}).catch(()=>{})},Oj=async(e,t)=>{let n=async()=>{await Pt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Ga(e,{recursive:!1}),n}catch{}let r=await aj(e).catch(()=>{});if(!(!r||t-r.mtimeMs<mj)){await n();try{return await Ga(e,{recursive:!1}),n}catch{return}}},hy=e=>ft(e,"update-state.json"),_j=async e=>{let t=await F(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},Pj=1e3,Tj=16*6e4,Dj=e=>e.inFlight===0,Lj=async(e,t,n={})=>{let r=n.probe??be,o=n.sleep??(i=>new Promise(c=>setTimeout(c,i))),a=n.now??Date.now,s=a()+(n.timeoutMs??Tj);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&Dj(i))return!0;if(a()>=s)return!1;await o(Pj)}},Ji=async(e={})=>{let t=e.now??Date.now,n=we;if(At(gt(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??yt(),o=e.root??ee(),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=fx(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??ky)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&ja(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await _j(hy(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<hj)return{outcome:"failed",current:n,latest:l};let f=`${ux}/download/${px}${l}`,p=await(e.load??L)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??kj)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?gj(w):{...hx(w),downgradeBlocked:!1};if(g.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:l};if(!g.apply)return{outcome:"disabled",current:n,latest:l};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:l,mandatory:g.mandatory};o===ee()?await Ct():await Ga(o,{recursive:!0,mode:448});let y=await Oj(ft(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,A;try{await Rj(ft(o,"bin"));let I=await lu(ft(o,"versions")).catch(()=>{}),C=await lu(ft(o,"bin",Va())).catch(()=>{}),x=C&&kc(C,I)?C:void 0,P=ft(o,"bin",Va());i&&process.platform==="win32"&&(await yy(P).catch(()=>{}))?.isFile()&&(A=`${P}.rollback-${process.pid}`,await my(P,A));let $=()=>(e.installBinary??vj)({root:o,version:l,asset:c,tagUrl:f});i?b=await Ij({install:$,smoke:e.smoke,rollback:async({link:Y,target:Z})=>{A?(await my(A,Y),await Pt(ls(Y),{force:!0}).catch(()=>{})):x&&x!==Z?await mx(Y,x):(await Pt(Y,{force:!0}),await Pt(ls(Y),{force:!0}).catch(()=>{}))},repoint:async Y=>e.repoint?e.repoint(p,Y):Ej(p),prune:async()=>{await(e.pruneDurable??(Y=>Cc(Y)))(r)}}):b=await $(),await xj(b.versionsDir,[l,n]),await Pt(hy(o),{force:!0}).catch(()=>{})}finally{A&&await Pt(A,{force:!0}).catch(()=>{}),await y()}let v=e.bounceDaemon??ip,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let I=p.fallbackPort??ke,C=E?!0:await Sw().catch(()=>!0),x=await v(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!C&&p.gateway&&((x?await(e.waitForDaemon??Lj)(I,l):!0)?await Nt({port:I,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??Iw)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await J(hy(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},yx=async(e={})=>{let t=e.context??yt(),n=await by(t,e.root??ee()),r=Bo(e.root??ee());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:we,managedPath:n.link??r}:Ji({...e,context:t,allowNpmMigration:!0})},Oo=async(e={})=>{let t=e.context??yt(),n=e.root??ee(),r=await by(t,n),o=r.kind==="npm"||r.kind==="durable"?Bo(n):void 0,a=await(e.load??L)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!fx(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=At(gt(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:we,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};var Nj=async(e,t)=>{if(!e.gateway||!e.clientKey)return;let n=await t().catch(()=>{});return ge({origin:e.gateway,clientKey:e.clientKey,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:n,user:e.name,team:e.team})},gx=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,$j=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},Ay=async(e={})=>{let t=e.load??L,n=e.save??oe,r=e.mutate??(e.load||e.save?$j(t,n):Lg),o=e.loadDevKey??We,a=e.heartbeat??Pd,s=e.detectSeat??$t,i=e.rewriteTools??Ri,c=e.uninstallProxy??en;try{let l=await t();if(l.credentialProtocol==="stable-heartbeat-v1"&&l.directMigration==="complete")return"already-direct";if(!l.keyRefreshEnabled&&!l.refreshSchedulerEnabled||!l.gateway||!l.clientKey||!l.enrolledCert)return"not-eligible";let d=l.enrolledCert.sig,u=await o();if(!u)return"not-eligible";let f;try{f=await a(l.gateway,l.clientKey,l.enrolledCert,u)}catch(y){return y instanceof Or&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!gx(y,l))return{result:void 0};let b={...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"pending"};return{next:b,result:b}});if(!p)return"pending";let h=await Nj(p,s);if(!h)return"pending";let m=l.keyRefreshEnabled===!0,w=Number.isInteger(l.fallbackPort)&&l.fallbackPort>0&&l.fallbackPort<=65535?l.fallbackPort:ke;if(m){let y=`http://${mt}:${w}`;if(await i(h,y)===!1)return"pending"}return await r(y=>y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||y.credentialProtocol!=="stable-heartbeat-v1"||y.directMigration!=="pending"||!gx(y,p)?{result:!1}:{next:{...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"complete",keyRefreshEnabled:!1,fallbackPort:void 0},result:!0})?((m||l.fallbackPort!==void 0)&&await c(w).catch(()=>{}),"migrated"):"pending"}catch{return"pending"}};import{z as wx}from"zod";var Mj=5e3,Uj=wx.object({lane:wx.enum(["subscription","org"]).optional().catch(void 0)}),bx=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??Mj);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=Uj.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},kx=(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 Fj=12e3,Bj="anyray-wiring-probe-not-a-real-token",Wj={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"}]},_o=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},Ax=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}"`))},Cx=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."],Hj=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>"]}),Xi=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."]}),Kj=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:e===401||e===403?Iy(t)?xy(e):Ey(t)?Xi(e):Ax(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${_o(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)."]}:Hj(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${_o(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")?Cx([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${_o(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).",...Cx([" \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}: ${_o(t)}`,remedy:[]},Gj=(e,t)=>{if(Ey(t))return Xi(e);if(Iy(t))return xy(e);if(Ax(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}: ${_o(t)}`,remedy:[]}},jj=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),Vj=(e,t)=>{if(Ey(t))return Xi(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")||jj(n));return e>=200&&e<300||r?{kind:"ok",detail:e>=200&&e<300?"gateway served a completion through the configured BYO upstream.":`gateway authenticated and reached the configured BYO upstream, which rejected this probe's fixed model (HTTP ${e}).`,remedy:[]}:{kind:"unknown",detail:`BYO-upstream probe got HTTP ${e}: ${_o(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)}},Yj=async(e,t)=>{if(!e.clientKey)return Xi(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?Xi(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${_o(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},Zj=(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."]}},qi=async(e,t={})=>{let n=t.timeoutMs??Fj,r=de(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await Yj(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 Vj(d,u)}if(X(e,"anthropic")){let l={Authorization:`Bearer ${Bj}`,"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 Gj(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,Wj,n);return Kj(i,c,t.tools??[])}catch(o){return Zj(n,o)}};var vx=async e=>{let t=await L(),n;try{n=Dr(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),M(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${rt(n)}`),t.gateway?M(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?M(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||M(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??S("(not set)")}`),k(` Team: ${t.team??S("(not set)")}`);let r=gt();r&&(K("Environment"),k(` Remote dev context: ${pr(r)}`),At(r)&&M(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),M(" VS Code tools configure the remote server variant backing this window.")),t.credentialProtocol==="stable-heartbeat-v1"&&(K("Credential renewal"),t.directMigration==="pending"?(k(" Stable-key heartbeat active; direct-routing migration is still completing."),M(" The local proxy remains available until every managed tool moves.")):(U(" Direct gateway routing with a proof-backed stable-key heartbeat."),M(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(ot(t)&&t.fallbackPort),a=o?`http://${mt}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await be(t.fallbackPort)?U(` Running on 127.0.0.1:${t.fallbackPort} \u2192 ${n} `+S("(auto-refreshes your key so long sessions never 401)")):(D(` Enabled on 127.0.0.1:${t.fallbackPort} but NOT responding \u2014 your tools cannot reach any gateway until it's back.`),k(S(" Re-run `anyray-connect`, or check the service logs.")))),K("Tools");for(let s of ie){if(!(await s.detect()).installed){M(` ${s.title}: not installed`);continue}if(!s.pointsAt){M(` ${s.title}: installed ${S("(status not introspectable)")}`);continue}let c=await s.pointsAt(Fi(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){U(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(S(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}U(` ${s.title}: pointed at Anyray${o&&Ui(s.id)?S(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===Wa&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await Xd();l=qd({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:f.authoritative}),d={...f.authoritative?{}:{reason:f.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=zd(l,d);D(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(S(` ${f}`))}else M(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as dV}from"node:fs";import{isAbsolute as uV}from"node:path";import{access as Jj}from"node:fs/promises";import{constants as Xj}from"node:fs";import{platform as qj}from"node:os";var zj=async e=>{try{return await Jj(e,Xj.F_OK),!0}catch{return!1}},Qj=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"]:[],Po=async(e={})=>{let t=e.os??qj(),n=e.exists??zj;for(let r of Qj(t))if(await n(r))return!0;return!1};import{execFile as eV}from"node:child_process";import{readFile as tV}from"node:fs/promises";import{homedir as nV,platform as rV}from"node:os";import{promisify as oV}from"node:util";var aV=oV(eV),sV="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",Sx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iV=async e=>{try{let t=ze(await tV(e,"utf-8"));if(!Sx(t))return{};let n=t[bn],r=t[kn];return{supportsAnyray:Sx(n)?n[q]===!0:void 0,bridgeEnabled:typeof r=="boolean"?r:void 0}}catch{return{}}},cV=async(e=async()=>(await aV("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(rV()==="win32")return"unknown";try{let t=(await e()).match(new RegExp(`${sV}=(\\w*)`,"g"))??[];return t.length===0?"unknown":t.some(n=>n.endsWith("=true"))?"on":"off"}catch{return"unknown"}},lV=e=>e.mode!=="copilot-seat"?"not-applicable":e.settings.supportsAnyray!==!0||e.settings.bridgeEnabled!==!0?"not-configured":e.bridge==="off"?"awaiting-relaunch":"ready",pu=(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. VS Code is not running one yet, so the next launch picks it up.";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 ${bn} and ${kn}; if you switched either off yourself, that choice is left alone).`;case"not-applicable":return"Agents window: not applicable on this machine."}},Ex=async(e={})=>{let{installedVariant:t=zo,receiptMode:n=wl,readSettings:r=iV,probeBridge:o=cV,home:a=nV()}=e;try{let s=await t();if(!s)return{state:"not-applicable",bridge:"unknown",detail:pu("not-applicable","unknown")};let i=await n(s,a);if(i!=="copilot-seat")return{state:"not-applicable",bridge:"unknown",detail:pu("not-applicable","unknown")};let c=await r(js(s)),l=await o(),d=lV({mode:i,settings:c,bridge:l});return{state:d,bridge:l,detail:pu(d,l)}}catch{return{state:"not-applicable",bridge:"unknown",detail:pu("not-applicable","unknown")}}};var Zt="connect",Ry=e=>e.replace(/-/g,"_"),Ix=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Zt,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:Zt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Zt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:Zt,checkId:"fallback_proxy",status:e.fallbackProxy.healthy===!1?"fail":e.fallbackProxy.healthy===!0?"ok":"unknown"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:Zt,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:Zt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Zt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=Ry(e.retrieval.kind);t.push({tool:Zt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":Ry(e.verify.kind);t.push({tool:Zt,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:Zt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:Ry(e.hookLane.reason)}:{}})}t.push({tool:Zt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:Zt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function pV(){return we}var fV="ctx_doctor-probe-synthetic",hV=(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: ${Py(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 mV(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function yV(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Py(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 xx=e=>qd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),Oy=e=>e.pointedAt===!1&&e.tombstoned!==!0&&xx(e)!=="unverifiable",Rx=e=>e.registered&&e.command&&uV(e.command)?dV(e.command):null,_y=e=>(Oy(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),gV=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,wV=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},Ox=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},bV=(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(vo),s=[],i=n(e.selfcheck?.adapters)?e.selfcheck.adapters:{};for(let[c,l]of Object.entries(i)){if(!o.has(c)||!n(l))continue;let d=n(l.lastRepaired)?l.lastRepaired:{},u=Object.entries(d).filter(w=>a.has(w[0])&&r(w[1])).map(([w,g])=>({checkId:w,at:g})),f=n(l.flapping)?l.flapping:void 0,p=Array.isArray(f?.checks)?f.checks.filter(w=>typeof w=="string"&&a.has(w)):[],h=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,m=f&&r(f.since)&&h&&p.length>0?{since:f.since,reason:h,checks:p}:void 0;(u.length>0||m)&&s.push({tool:c,repaired:u,...m?{flapping:m}:{}})}return s},kV=async(e,t,n,r,o,a,s=n,i=qi,c=!0,l=Io,d=Oo,u=Gt,f=Pa)=>{let p=c?await su(e):null,h=!!(ot(t)&&t.fallbackPort),m=h?await be(t.fallbackPort):null,w=h?`http://${mt}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=V=>V&&Vm(V)?"machine_default":null,b=t.enrolledCert?.payload,A=b?.expiresAt??t.enrolledCertExpiry??null,E=(await a())?.sso??null,I=yV({ssoLink:E,enrolledViaToken:!!t.enrolledTokenHash}),C=vt(),x=await tb(C),P=x?[]:sb(ge({origin:w})),$=[];for(let V of r){let Ne=await V.detect(),nr=null;if(Ne.installed&&V.mcpStatus)try{let Lo=await V.mcpStatus();nr={...Lo,commandOk:Rx(Lo)}}catch{}let ht=Ne.installed&&V.id===Wa?await o():void 0,Do=Ne.installed&&V.pointsAt?await V.pointsAt(Fi(V.id,e,w)):null,On=await gV(Do,V,t.managedTools??[]),qa=Do===!1&&On===null,lc=On===!1&&V.routingPendingReload?await V.routingPendingReload().catch(()=>!1):!1,za=Ne.installed?V.runtimeDiagnostics?await V.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:V.routingOverrides?await V.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Qa,claudeCodeHookPolicy:es}=za,ts=t.fleetToolPolicy,ns=ts?.enabled.includes(V.id)?ts.tiers?.[V.id]??Ra:void 0;$.push({id:V.id,title:V.title,installed:Ne.installed,...Ne.detail?{detail:Ne.detail}:{},pointedAt:On,...qa?{routingHeld:!0}:{},...lc?{routingPendingReload:!0}:{},...Qa.length?{routingOverrides:Qa}:{},...es===void 0?{}:{claudeCodeHookPolicy:es},mcp:nr,...ns?{policyTier:ns}:{},...t.revertedTools?.includes(V.id)?{tombstoned:!0}:{},...V.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...ht===void 0?{}:{inferenceIntrospectable:ht.authoritative,...ht.authoritative?{}:{inferenceUnverifiableReason:ht.reason}}})}let Y=s?await(async()=>{let{kind:V,detail:Ne,remedy:nr}=await i(ge({origin:e,clientKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey,subscription:t.authMode==="subscription",placeholder:t.authMode==="placeholder",byoUpstream:t.byoUpstream,...t.authMode==="auto"?{seat:{anthropic:!1,openai:!1,copilot:!1}}:{},user:t.name,team:t.team}),{tools:t.managedTools??[]});return{kind:V,detail:Ne,remedy:nr}})():null,Z=Y?.kind==="provider-rejected"&&await wV(t.managedTools??[],r),W=Y?{...Y,...Z?{notApplicableSubscription:!0}:{}}:null,z=n?hV(await _a({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:de({user:t.name,team:t.team})},fV,{probe:!0}),{mode:I,ssoLink:E}):null,me=await u().catch(()=>({})),Te=xn(me.hookLane),re=s?await Ox(r):!1,Ke=re?await(async()=>{let V=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...ym(V,{hookRegistered:re,neverInvoked:hm(Te,Date.now())}),lastInvokedAt:Dd(Te)}})():null,De=(await yr()).map(V=>({adapter:V.adapter,op:V.op,requestedAt:V.requestedAt,watcherAlive:wr(V.watcherPid)})),O=De.find(V=>V.adapter==="cursor"),T=O?{op:O.op,requestedAt:O.requestedAt,watcherAlive:O.watcherAlive}:null,H=!!t.refreshSchedulerEnabled,fe=await Jo(),Q=await d(),Ze=t.persistenceOwner==="tray",Fe=Ze?await l(t)==="healthy":null,te=await LE({daemonEnabled:h&&!Ze,daemonHealthy:h?!!m:null,schedulerEnabled:H&&!Ze,schedulerInstalled:fe,binaryDurable:!je(ur())}),Be=await Fu(),Le=0;p&&!p.reachable&&(Le+=1),h&&!m&&(Le+=1),Ze?H&&!Fe&&(Le+=1):H&&!fe&&(Le+=1);for(let V of $)Le+=_y(V);W&&W.kind!=="ok"&&!W.notApplicableSubscription&&(Le+=1),z&&z.kind!=="ok"&&(Le+=1),Ke?.verdict==="dark"&&(Le+=1),P.length>0&&(Le+=1),Le+=De.filter(V=>!V.watcherAlive).length,Be.length>0&&(Le+=1);let Xt=await Ex();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:pV(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:gt(),selfUpdate:{managed:Q.managed,available:Q.available,autoUpdate:Q.autoUpdate,state:Q.state}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},toolOrigin:w,fallbackProxy:{enabled:h,port:h?t.fallbackPort:null,healthy:h?!!m:null},refreshScheduler:{enabled:H,installed:fe,owner:Ze?"tray":"os",...Ze?{trayHealthy:!!Fe}:{}},serviceRemoval:te,retiredFallbackState:Be,fleetdPresent:await Po(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:y(t.name)},enrollment:{enrolled:!!b,deploymentId:b?.deploymentId??null,issuedAt:b?.issuedAt??null,expiresAt:A,expired:A?Date.parse(A)<Date.now():null,orgMode:I,ssoLink:E},shell:{profilePath:C,blockPresent:x,staleExports:P},tools:$,...t.fleetToolPolicy?{fleetPlan:Id(t,t.fleetToolPolicy,!1)}:{},cursorQueue:T,pendingOps:De,ambientRepairs:bV(me,r),verify:W,retrieval:z,hookLane:Ke,agentsWindow:Xt,problems:Le}},CV=e=>{if(e.serviceRemoval.suspected){K("Endpoint security"),D(" Anyray installed these background services, but their files are gone from disk \u2014"),D(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),D(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)k(S(` missing: ${t}`));k(S(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(S(" tools straight at the gateway (your key then needs a periodic re-run).")),k(S(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(S(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},AV=e=>{if(e.retiredFallbackState.length!==0){K("Retired fallback lane"),_(" A cached organization provider key from the removed --fallback lane is still on this machine.");for(let t of e.retiredFallbackState)k(S(` ${t}`));k(S(" Fix: `anyray-connect doctor --repair` deletes it (a normal `anyray-connect` run does too)."))}},vV=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${pr(e.connect.remoteContext)}`),At(e.connect.remoteContext)&&k(S(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),K("CLI updates"),e.connect.selfUpdate.state){case"managed":U(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||D(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":D(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),k(S(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":D(" Self-update is unavailable on this platform because no standalone binary is published."),k(S(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(S(" This copy is externally managed; update it with the method that installed it."));break;case"container":k(S(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(K("Gateway"),e.gateway.reachable===null?k(S(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?U(` Reachable: ${e.gateway.origin} ${S(`(${e.gateway.detail})`)}`):(_(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),k(S(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.fallbackProxy.enabled&&(K("Local key-refresh proxy"),e.fallbackProxy.healthy?U(` Running on 127.0.0.1:${e.fallbackProxy.port} \u2192 ${e.gateway.origin} `+S("(auto-refreshes your key so long sessions never 401)")):(_(` Enabled on 127.0.0.1:${e.fallbackProxy.port} but NOT responding \u2014 your tools point at it and cannot reach any gateway until it's back.`),e.serviceRemoval.kinds.includes("daemon")||k(S(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to point tools straight at the gateway.")))),e.refreshScheduler.enabled&&(K("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?U(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh and supervises the daemon."):(_(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),k(S(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?U(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(_(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||k(S(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),CV(e),AV(e),K("Personal key"),mV(e)){case"env":U(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":U(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":D(" Enrolled, but no personal key is cached locally right now."),k(S(" 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:D(" Enrollment required \u2014 no personal gateway key is available."),k(S(` Fix: ${Py(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?D(` Enrollment cert expired ${S(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):U(` Enrollment cert valid until ${e.enrollment.expiresAt} ${S(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(K("Shell"),_(" This terminal still exports Anyray, but the config is gone."),k(S(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(S(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(S(" Anything you start from this terminal keeps reaching the gateway with")),k(S(" no credential, and fails with 401.")),k(S(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(S(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(S(" reuses the environment it captured at launch, so a new terminal")),k(S(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};K("Claude Code hook policy"),_(` ${xc(c)}.`),k(S(` ${Rc(c)}`))}K("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])_(` ${c.title}: ${l.problem}.`),k(S(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(_(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),k(S(" Fix: re-run `anyray-connect` to re-register the current binary."))):U(` ${c.title}: retrieval MCP server registered ${S("(anyray_retrieve / anyray_recall)")}`):(D(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),k(S(" Fix: re-run `anyray-connect` from a durable install (registration is skipped for one-off npx runs)."))))};for(let c of e.tools){if(!c.installed){k(S(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){k(S(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){U(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),k(S(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}U(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&Ui(c.id)?S(" (via key-refresh proxy)"):""}`),o(c),c.id==="claude-code"&&k(S(" 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===Wa&&k(S(` ${WC}`)),c.id==="codex"&&k(S(" 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=xx(c);if(l==="not-routed"||l==="unverifiable"){let d=zd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});D(` ${c.title}: ${d.headline}`);for(let u of d.detail)k(S(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(D(` ${c.title}: reverted locally against admin policy (out of compliance)`),k(S(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?D(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):k(S(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(_(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),k(S(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(_(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),k(S(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(D(" No tools are pointed at this gateway yet."),k(S(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){K("Queued operations");for(let c of e.pendingOps){let l=Kt(c.adapter)?.title??c.adapter;c.watcherAlive?D(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(_(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),k(S(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){K("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=Kt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:p,at:h})=>`${c(p)} ${new Date(h).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?D(f):k(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){K("Fleet policy");let c=l=>l.map(d=>Kt(d)?.title??d).join(", ");i.freshIds.length>0&&k(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&D(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(K("Auth probe"),e.verify.notApplicableSubscription)U(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")U(` ${e.verify.detail}`);else{_(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(S(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")U(` ${e.retrieval.detail}`);else{_(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(S(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")U(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(S(` ${c}`))}else{D(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(S(` ${c}`))}e.hookLane.lastInvokedAt!==null&&k(S(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(K("VS Code Agents window"),D(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(K("VS Code Agents window"),U(` ${e.agentsWindow.detail}`)),K("Summary"),e.problems===0?(e.verify?U(" No problems found."):U(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(S(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):_(` ${e.problems} problem(s) found \u2014 see fixes above.`)},SV=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}),EV=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!um(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??Pa,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??nt)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=xn((await(t.readRefreshState??Gt)().catch(()=>({}))).hookLane),l=ym(i,{hookRegistered:await Ox(t.adapters??ie).catch(()=>!1),neverInvoked:hm(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:Dd(c)},note:d}},IV=async(e,t,n={})=>{let r=n.adapters??ie,o=n.resolveTarget??Oe,a=n.applyTools??wt,s=await EV(e,n).catch(()=>null),i=s&&e.hookLane?.verdict==="dark"&&s.hookLane?.verdict==="live"?1:0,c=s?{hookLane:s.hookLane,notes:[s.note]}:{notes:[]},l=e.tools.filter(y=>y.installed&&(Oy(y)||y.mcp?.commandOk===!1||y.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t,void 0,be);if(!d)return{entries:l.map(y=>({id:y.id,title:y.title,status:"skipped-not-enrolled"})),remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,`Repair needs an enrolled personal key \u2014 ${Py(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],p=[...c.notes],h=[];for(let y of l){let b=r.find(A=>A.id===y.id);if(!u.has(y.id)||!b){f.push({id:y.id,title:y.title,status:"skipped-unmanaged"});continue}h.push(b)}f.length>0&&p.push("Drifted tools outside the managed record are never auto-repaired \u2014 run `anyray-connect` once to (re)configure and record them.");let m=await a(h,d.target),w=new Map,g=0;for(let y of m){if(f.push(y),!bo(y))continue;let b=e.tools.find(P=>P.id===y.id);if(!b)continue;let A=r.find(P=>P.id===y.id),v=b.mcp;if(A?.mcpStatus)try{let P=await A.mcpStatus();v={...P,commandOk:Rx(P)}}catch{}let E=Oy(b)?!0:b.pointedAt;if(A?.pointsAt&&b.pointedAt!==null)try{E=await A.pointsAt(Fi(A.id,e.gateway.origin,e.toolOrigin))}catch{}let I=b.routingOverrides,C=b.claudeCodeHookPolicy;if(A?.runtimeDiagnostics)try{let P=await A.runtimeDiagnostics();I=P.routingOverrides.length?P.routingOverrides:void 0,C=P.claudeCodeHookPolicy}catch{}else if(A?.routingOverrides)try{let P=await A.routingOverrides();I=P.length?P:void 0}catch{}let x={...b,pointedAt:E,mcp:v,...I?{routingOverrides:I}:{},...C===void 0?{}:{claudeCodeHookPolicy:C}};I||delete x.routingOverrides,C===void 0&&delete x.claudeCodeHookPolicy,w.set(y.id,x),g+=_y(b)-_y(x)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},xV=e=>{K("Repair"),e.entries.length===0&&U(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?U(` ${t.title}: re-applied`):t.status==="queued"?U(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(S(` ${t.title}: ${t.status}`)):_(` ${t.title}: ${t.status}`);for(let t of e.notes)k(S(` ${t}`))},_x=async(e,t={})=>{let n=await L();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of NE(n.fallbackPort??ke))k(c?` ${c}`:"");return 0}let r;try{r=Dr(e.gateway,n)}catch(c){return e.json?(console.log(JSON.stringify({error:c.message})),1):(k(j("Anyray connect \u2014 doctor")),_(` Gateway URL: ${c.message}`),k(S(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(k(j("Anyray connect \u2014 doctor")),_(" --quick skips the network probes; it cannot be combined with --verify.")),1;let o=!e.noVerify&&!e.quick,a=await kV(r,n,!!e.verify&&!e.quick,t.adapters??ie,t.inferenceIntrospection??Xd,t.fleetBootstrap??Vt,o,t.verifyAuth??qi,!e.quick,t.checkTray??Io,t.updateStatus??Oo,t.readRefreshState??Gt,t.probeHookLane??Pa);e.repair&&a.retiredFallbackState.length>0&&(await gc(),a.retiredFallbackState=await Fu(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await IV(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;e.json?console.log(JSON.stringify(SV(i),null,2)):(vV(i),s&&xV(s));try{e.quick||await(t.reportHealth??ES)(Ix(i),i.connect.version)}catch{}return i.problems===0?0:1};var RV=()=>{let e=[];for(let t of ie){let n=t.skillsDir?.();n&&e.push(n)}return e},Px=async e=>{let t=await L();k(j("Anyray connect \u2014 sync"));let n;try{n=Dr(e.gateway,t)}catch(s){return _(s.message),1}M(`Gateway: ${n}`);let r=uI(t.clientKey,"anyray-placeholder"),o;try{o=await Rd(n,r)}catch(s){return _(`Team policy sync failed: ${xd(s)}`),1}let a=RV();if(a.length===0)OV();else if(o.skills.length===0)M("No team skills published yet \u2014 nothing to sync.");else{let s=await sS(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?U(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):M(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await oe({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){M(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${rt(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Od(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(k(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&M(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){M(`Fleet policy reconcile skipped: ${xd(s)}`)}return 0},OV=()=>{M("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as D2}from"node:zlib";import{promisify as L2}from"node:util";var Mr={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=>`
|
|
695
|
+
`).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,p=!1;try{return p=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((h,m)=>{let w=()=>{r.off("data",v),r.off("end",b),r.off("close",b),r.off("error",A)},g=E=>{w(),h(E)},y=E=>{w(),m(E)},b=()=>g({kind:"cancelled"}),A=E=>y(E),v=E=>{try{for(let x of ej(E)){if(x===""||x==="\x1B"||x==="q"){g({kind:"cancelled"});return}if(e.items.length===0){(x==="\r"||x===`
|
|
696
|
+
`)&&g({kind:"ok",values:[]});continue}if(x==="\x1B[A"||x==="k")s=(s-1+e.items.length)%e.items.length,d();else if(x==="\x1B[B"||x==="j")s=(s+1)%e.items.length,d();else if(x===" "){if(e.single){let C=!a[s];a.fill(!1),a[s]=C}else a[s]=!a[s];d()}else if(x==="a"&&!e.single){let C=e.items.map((P,$)=>({item:P,index:$})).filter(({item:P})=>P.requiresExplicitChoice!==!0),I=!C.every(({index:P})=>a[P]);for(let{index:P}of C)a[P]=I;d()}else if(x==="\r"||x===`
|
|
697
|
+
`){g({kind:"ok",values:e.items.filter((C,I)=>a[I]).map(C=>C.value)});return}}}catch(x){y(x)}};r.on("data",v),r.on("end",b),r.on("close",b),r.on("error",A)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),p&&r.setRawMode(f)}catch{}n.close()}};var dI=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],tj=80,Yi=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&Ma(r,n.env??process.env)))return r.write(`${e}
|
|
698
|
+
`),t();let a=0,s=()=>{r.write(`\r${dI[a++%dI.length]} ${e}`)};s();let i=setInterval(s,tj);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as nj}from"node:fs";import{spawnSync as rj}from"node:child_process";import{chmod as oj,copyFile as yy,lstat as gy,mkdir as Ga,readdir as wy,realpath as du,rename as lu,rm as Pt,stat as aj,symlink as sj,writeFile as ij}from"node:fs/promises";import{createHash as cj}from"node:crypto";import{basename as hy,dirname as $r,join as ft}from"node:path";import{Readable as lj}from"node:stream";import{pipeline as dj}from"node:stream/promises";var uI="https://github.com/anyrayHQ/install/releases",pI="connect-v",uj=new RegExp(`/releases/tag/${pI}([0-9][0-9A-Za-z.-]*)$`),pj=300*1024*1024,uu=1e4,fj=5*6e4,hj=360*6e4,mj=30*6e4,ja=(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)},fI=(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"}},yj=e=>{if(e)return uj.exec(e.trim())?.[1]},by=(e,t)=>{for(let n of e.split(`
|
|
699
|
+
`)){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()}},hI=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&&ja(e.current,e.minVersion)<0&&ja(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},gj=e=>ja(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}:{...hI(e),downgradeBlocked:!1},Va=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",wj=(e=process.execPath)=>{let t=Vu(e);return t?$r(t):$r($r(e))},bj=async(e=yt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=ft(wj(e.execPath),"bin",Va());try{if(await du(t)!==await du(e.execPath))return}catch{return}return t},ky=async(e=yt(),t=ee())=>{let n=await bj(e);if(n)return{kind:"managed",root:$r($r(n)),link:n,entryPath:or(e)};let r=or(e);return Zu(r,t)?{kind:"durable",root:t,entryPath:r}:Gu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},pu=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)}},Cy=async(e=uu)=>{let t=await pu(`${uI}/latest`,e,{redirect:"manual"});return yj(t.headers.get("location"))},kj=async e=>{try{let t=await pu(`${e}/connect-update.json`,uu);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}},Zi=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},Ay=async(e,t,n)=>{let r=await pu(e,fj);if(!r.ok||!r.body)throw new Zi(r.status);let o=cj("sha256"),a=0;if(await dj(lj.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>pj)throw new Error("asset exceeds size cap");o.update(c),yield c}},nj(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},Cj=e=>hy(e)===Va()?hy($r(e)):hy(e),Aj=async e=>{let t=await wy(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Pt(ft(e,n),{force:!0}).catch(()=>{})},mI=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Pt(r,{force:!0}).catch(()=>{});let o=!1;try{await lu(e,r),o=!0}catch{}try{await yy(t,e),await ij(ls(e),Cj(t))}catch(a){throw o&&await lu(r,e).catch(()=>{}),a}await Pt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Pt(n,{force:!0}),await sj(t,n),await lu(n,e)},vj=async(e,t={})=>{let n=ft(e.root,"bin"),r=ft(e.root,"versions"),o=ft(n,Va());await Ga(n,{recursive:!0,mode:448}),await Ga(r,{recursive:!0,mode:448});let a=ft(r,e.version),i=(await gy(a).catch(()=>{}))?.isFile()?a:ft(a,Va());if(!(await gy(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??pu)(`${e.tagUrl}/SHA256SUMS`,uu),d=l.ok?by(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await Ga($r(i),{recursive:!0,mode:448}),await Aj($r(i));let u=`${i}.part-${process.pid}`;try{await(t.download??Ay)(`${e.tagUrl}/${e.asset}`,u,d),await oj(u,493),await lu(u,i)}catch(f){throw await Pt(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??mI)(o,i),{link:o,target:i,versionsDir:r}},Sj=async e=>{let t=rj(e,["--version"],{stdio:"ignore",timeout:uu});return!t.error&&t.status===0},Ej=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??ko)(n);if(r.length>0){let o=await(t.resolveTarget??Oe)(async()=>e);if(!o||!(await(t.repair??wt)(r,o.target)).every(bo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??hr)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Nt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},xj=async e=>{let t=await e.install();if(!await(e.smoke??Sj)(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},Ij=async(e,t)=>{let n=await wy(e).catch(()=>[]);for(let r of n)t.includes(r)||await Pt(ft(e,r),{force:!0,recursive:!0}).catch(()=>{})},Rj=async e=>{let t=await wy(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Pt(ft(e,n),{force:!0}).catch(()=>{})},Oj=async(e,t)=>{let n=async()=>{await Pt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Ga(e,{recursive:!1}),n}catch{}let r=await aj(e).catch(()=>{});if(!(!r||t-r.mtimeMs<mj)){await n();try{return await Ga(e,{recursive:!1}),n}catch{return}}},my=e=>ft(e,"update-state.json"),_j=async e=>{let t=await F(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},Pj=1e3,Tj=16*6e4,Dj=e=>e.inFlight===0,Lj=async(e,t,n={})=>{let r=n.probe??be,o=n.sleep??(i=>new Promise(c=>setTimeout(c,i))),a=n.now??Date.now,s=a()+(n.timeoutMs??Tj);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&Dj(i))return!0;if(a()>=s)return!1;await o(Pj)}},Ji=async(e={})=>{let t=e.now??Date.now,n=we;if(At(gt(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??yt(),o=e.root??ee(),a;try{let s=await ky(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=fI(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Cy)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&ja(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await _j(my(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<hj)return{outcome:"failed",current:n,latest:l};let f=`${uI}/download/${pI}${l}`,p=await(e.load??L)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??kj)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?gj(w):{...hI(w),downgradeBlocked:!1};if(g.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:l};if(!g.apply)return{outcome:"disabled",current:n,latest:l};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:l,mandatory:g.mandatory};o===ee()?await Ct():await Ga(o,{recursive:!0,mode:448});let y=await Oj(ft(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,A;try{await Rj(ft(o,"bin"));let x=await du(ft(o,"versions")).catch(()=>{}),C=await du(ft(o,"bin",Va())).catch(()=>{}),I=C&&kc(C,x)?C:void 0,P=ft(o,"bin",Va());i&&process.platform==="win32"&&(await gy(P).catch(()=>{}))?.isFile()&&(A=`${P}.rollback-${process.pid}`,await yy(P,A));let $=()=>(e.installBinary??vj)({root:o,version:l,asset:c,tagUrl:f});i?b=await xj({install:$,smoke:e.smoke,rollback:async({link:Y,target:Z})=>{A?(await yy(A,Y),await Pt(ls(Y),{force:!0}).catch(()=>{})):I&&I!==Z?await mI(Y,I):(await Pt(Y,{force:!0}),await Pt(ls(Y),{force:!0}).catch(()=>{}))},repoint:async Y=>e.repoint?e.repoint(p,Y):Ej(p),prune:async()=>{await(e.pruneDurable??(Y=>Cc(Y)))(r)}}):b=await $(),await Ij(b.versionsDir,[l,n]),await Pt(my(o),{force:!0}).catch(()=>{})}finally{A&&await Pt(A,{force:!0}).catch(()=>{}),await y()}let v=e.bounceDaemon??cp,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let x=p.fallbackPort??ke,C=E?!0:await Ew().catch(()=>!0),I=await v(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!C&&p.gateway&&((I?await(e.waitForDaemon??Lj)(x,l):!0)?await Nt({port:x,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??Iw)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await J(my(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},yI=async(e={})=>{let t=e.context??yt(),n=await ky(t,e.root??ee()),r=Bo(e.root??ee());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:we,managedPath:n.link??r}:Ji({...e,context:t,allowNpmMigration:!0})},Oo=async(e={})=>{let t=e.context??yt(),n=e.root??ee(),r=await ky(t,n),o=r.kind==="npm"||r.kind==="durable"?Bo(n):void 0,a=await(e.load??L)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!fI(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=At(gt(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:we,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};var Nj=async(e,t)=>{if(!e.gateway||!e.clientKey)return;let n=await t().catch(()=>{});return ge({origin:e.gateway,clientKey:e.clientKey,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:n,user:e.name,team:e.team})},gI=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,$j=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},vy=async(e={})=>{let t=e.load??L,n=e.save??oe,r=e.mutate??(e.load||e.save?$j(t,n):Ng),o=e.loadDevKey??We,a=e.heartbeat??Td,s=e.detectSeat??$t,i=e.rewriteTools??Ri,c=e.uninstallProxy??en;try{let l=await t();if(l.credentialProtocol==="stable-heartbeat-v1"&&l.directMigration==="complete")return"already-direct";if(!l.keyRefreshEnabled&&!l.refreshSchedulerEnabled||!l.gateway||!l.clientKey||!l.enrolledCert)return"not-eligible";let d=l.enrolledCert.sig,u=await o();if(!u)return"not-eligible";let f;try{f=await a(l.gateway,l.clientKey,l.enrolledCert,u)}catch(y){return y instanceof Or&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!gI(y,l))return{result:void 0};let b={...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"pending"};return{next:b,result:b}});if(!p)return"pending";let h=await Nj(p,s);if(!h)return"pending";let m=l.keyRefreshEnabled===!0,w=Number.isInteger(l.fallbackPort)&&l.fallbackPort>0&&l.fallbackPort<=65535?l.fallbackPort:ke;if(m){let y=`http://${mt}:${w}`;if(await i(h,y)===!1)return"pending"}return await r(y=>y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||y.credentialProtocol!=="stable-heartbeat-v1"||y.directMigration!=="pending"||!gI(y,p)?{result:!1}:{next:{...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"complete",keyRefreshEnabled:!1,fallbackPort:void 0},result:!0})?((m||l.fallbackPort!==void 0)&&await c(w).catch(()=>{}),"migrated"):"pending"}catch{return"pending"}};import{z as wI}from"zod";var Mj=5e3,Uj=wI.object({lane:wI.enum(["subscription","org"]).optional().catch(void 0)}),bI=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??Mj);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=Uj.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},kI=(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 Fj=12e3,Bj="anyray-wiring-probe-not-a-real-token",Wj={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},Ey={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},_o=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},AI=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},xy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},CI=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."],Hj=e=>e.includes("no provider key configured for"),Iy=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},Ry=e=>({kind:"enrollment-required",detail:`gateway requires per-developer enrollment (HTTP ${e}).`,remedy:["This gateway only serves enrolled developers. Re-run with your enrollment","link from your admin so connect can mint your personal key automatically:"," anyray-connect --enroll <link>"]}),Xi=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."]}),Kj=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:e===401||e===403?Iy(t)?Ry(e):xy(t)?Xi(e):AI(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${_o(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)."]}:Hj(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${_o(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")?CI([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${_o(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).",...CI([" \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}: ${_o(t)}`,remedy:[]},Gj=(e,t)=>{if(xy(t))return Xi(e);if(Iy(t))return Ry(e);if(AI(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}: ${_o(t)}`,remedy:[]}},jj=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),Vj=(e,t)=>{if(xy(t))return Xi(e);if(Iy(t))return Ry(e);let n=t.toLowerCase();if(n.includes("bedrock"))return{kind:"routed-elsewhere",detail:"gateway routed to the org provider instead of the configured BYO upstream.",remedy:["Re-run anyray-connect with your --upstream URL and --upstream-key so","the custom-host pass-through pins are restored."]};if(n.includes("invalid custom host")||n.includes("custom_host_blocked")||n.includes("hostname is not authorized"))return{kind:"routed-elsewhere",detail:"gateway rejected the configured BYO upstream before routing to it.",remedy:["Ask the gateway admin to authorize this LiteLLM/upstream hostname in","ANYRAY_CUSTOM_HOST_ALLOWLIST (or TRUSTED_CUSTOM_HOSTS for an internal host)."]};if(e===401||e===403)return{kind:"provider-rejected",detail:`gateway accepted your personal key but the BYO upstream rejected its credential (HTTP ${e}).`,remedy:["Your Anyray enrollment key is fine. The configured personal upstream key","was rejected by the BYO upstream (for example, LiteLLM). Re-run","anyray-connect with a current --upstream-key."]};let r=e>=400&&e<500&&(n.includes("litellm")||jj(n));return e>=200&&e<300||r?{kind:"ok",detail:e>=200&&e<300?"gateway served a completion through the configured BYO upstream.":`gateway authenticated and reached the configured BYO upstream, which rejected this probe's fixed model (HTTP ${e}).`,remedy:[]}:{kind:"unknown",detail:`BYO-upstream probe got HTTP ${e}: ${_o(t)}`,remedy:[`The probe asks for a fixed model (${Ey.model}) your upstream`,"is not required to serve, so a model rejection here does not mean your","tools are broken. Check that the upstream serves it before chasing this."]}},Sy=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)}},Yj=async(e,t)=>{if(!e.clientKey)return Xi(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?Xi(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${_o(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},Zj=(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."]}},qi=async(e,t={})=>{let n=t.timeoutMs??Fj,r=de(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await Yj(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 Sy(`${e.anthropicBaseUrl}/v1/messages`,l,Ey,n);return Vj(d,u)}if(X(e,"anthropic")){let l={Authorization:`Bearer ${Bj}`,"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 Sy(`${e.anthropicBaseUrl}/v1/messages`,l,Ey,n);return Gj(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await Sy(`${e.openaiBaseUrl}/chat/completions`,s,Wj,n);return Kj(i,c,t.tools??[])}catch(o){return Zj(n,o)}};var vI=async e=>{let t=await L(),n;try{n=Dr(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),M(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${rt(n)}`),t.gateway?M(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?M(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||M(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??S("(not set)")}`),k(` Team: ${t.team??S("(not set)")}`);let r=gt();r&&(K("Environment"),k(` Remote dev context: ${pr(r)}`),At(r)&&M(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),M(" VS Code tools configure the remote server variant backing this window.")),t.credentialProtocol==="stable-heartbeat-v1"&&(K("Credential renewal"),t.directMigration==="pending"?(k(" Stable-key heartbeat active; direct-routing migration is still completing."),M(" The local proxy remains available until every managed tool moves.")):(U(" Direct gateway routing with a proof-backed stable-key heartbeat."),M(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(ot(t)&&t.fallbackPort),a=o?`http://${mt}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await be(t.fallbackPort)?U(` Running on 127.0.0.1:${t.fallbackPort} \u2192 ${n} `+S("(auto-refreshes your key so long sessions never 401)")):(D(` Enabled on 127.0.0.1:${t.fallbackPort} but NOT responding \u2014 your tools cannot reach any gateway until it's back.`),k(S(" Re-run `anyray-connect`, or check the service logs.")))),K("Tools");for(let s of ie){if(!(await s.detect()).installed){M(` ${s.title}: not installed`);continue}if(!s.pointsAt){M(` ${s.title}: installed ${S("(status not introspectable)")}`);continue}let c=await s.pointsAt(Fi(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){U(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(S(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}U(` ${s.title}: pointed at Anyray${o&&Ui(s.id)?S(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===Wa&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await qd();l=zd({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:f.authoritative}),d={...f.authoritative?{}:{reason:f.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=Qd(l,d);D(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(S(` ${f}`))}else M(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as dV}from"node:fs";import{isAbsolute as uV}from"node:path";import{access as Jj}from"node:fs/promises";import{constants as Xj}from"node:fs";import{platform as qj}from"node:os";var zj=async e=>{try{return await Jj(e,Xj.F_OK),!0}catch{return!1}},Qj=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"]:[],Po=async(e={})=>{let t=e.os??qj(),n=e.exists??zj;for(let r of Qj(t))if(await n(r))return!0;return!1};import{execFile as eV}from"node:child_process";import{readFile as tV}from"node:fs/promises";import{homedir as nV,platform as rV}from"node:os";import{promisify as oV}from"node:util";var aV=oV(eV),sV="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",SI=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iV=async e=>{let t;try{t=await tV(e,"utf-8")}catch(n){return n?.code==="ENOENT"?{readable:!0}:{readable:!1}}try{if(t.trim()==="")return{readable:!0};let n=ze(t);if(!SI(n))return{readable:!1};let r=n[bn],o=n[kn];return{readable:!0,supportsAnyray:SI(r)?r[q]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},cV=async(e=async()=>(await aV("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(rV()==="win32")return"unknown";let t;try{t=await e()}catch{return"unknown"}let n=!1;for(let r of t.split(`
|
|
700
|
+
`)){let o=new RegExp(`${sV}=(\\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"},lV=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",fu=(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 ${bn} and ${kn}; 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."}},EI=async(e={})=>{let{installedVariant:t=zo,receiptMode:n=bl,awaitingReload:r=wl,readSettings:o=iV,probeBridge:a=cV,home:s=nV()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:fu("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.":fu("not-applicable","unknown")}}let l=await o(js(i)),d=await a(),u=lV({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:fu(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:fu("not-applicable","unknown")}}};var Zt="connect",Oy=e=>e.replace(/-/g,"_"),xI=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Zt,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:Zt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Zt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:Zt,checkId:"fallback_proxy",status:e.fallbackProxy.healthy===!1?"fail":e.fallbackProxy.healthy===!0?"ok":"unknown"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:Zt,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:Zt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Zt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=Oy(e.retrieval.kind);t.push({tool:Zt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":Oy(e.verify.kind);t.push({tool:Zt,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:Zt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:Oy(e.hookLane.reason)}:{}})}t.push({tool:Zt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:Zt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function pV(){return we}var fV="ctx_doctor-probe-synthetic",hV=(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 mV(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function yV(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 II=e=>zd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),_y=e=>e.pointedAt===!1&&e.tombstoned!==!0&&II(e)!=="unverifiable",RI=e=>e.registered&&e.command&&uV(e.command)?dV(e.command):null,Py=e=>(_y(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),gV=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,wV=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},OI=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},bV=(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(vo),s=[],i=n(e.selfcheck?.adapters)?e.selfcheck.adapters:{};for(let[c,l]of Object.entries(i)){if(!o.has(c)||!n(l))continue;let d=n(l.lastRepaired)?l.lastRepaired:{},u=Object.entries(d).filter(w=>a.has(w[0])&&r(w[1])).map(([w,g])=>({checkId:w,at:g})),f=n(l.flapping)?l.flapping:void 0,p=Array.isArray(f?.checks)?f.checks.filter(w=>typeof w=="string"&&a.has(w)):[],h=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,m=f&&r(f.since)&&h&&p.length>0?{since:f.since,reason:h,checks:p}:void 0;(u.length>0||m)&&s.push({tool:c,repaired:u,...m?{flapping:m}:{}})}return s},kV=async(e,t,n,r,o,a,s=n,i=qi,c=!0,l=xo,d=Oo,u=Gt,f=Pa)=>{let p=c?await iu(e):null,h=!!(ot(t)&&t.fallbackPort),m=h?await be(t.fallbackPort):null,w=h?`http://${mt}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=V=>V&&Ym(V)?"machine_default":null,b=t.enrolledCert?.payload,A=b?.expiresAt??t.enrolledCertExpiry??null,E=(await a())?.sso??null,x=yV({ssoLink:E,enrolledViaToken:!!t.enrolledTokenHash}),C=vt(),I=await nb(C),P=I?[]:ib(ge({origin:w})),$=[];for(let V of r){let Ne=await V.detect(),nr=null;if(Ne.installed&&V.mcpStatus)try{let Lo=await V.mcpStatus();nr={...Lo,commandOk:RI(Lo)}}catch{}let ht=Ne.installed&&V.id===Wa?await o():void 0,Do=Ne.installed&&V.pointsAt?await V.pointsAt(Fi(V.id,e,w)):null,On=await gV(Do,V,t.managedTools??[]),qa=Do===!1&&On===null,lc=On===!1&&V.routingPendingReload?await V.routingPendingReload().catch(()=>!1):!1,za=Ne.installed?V.runtimeDiagnostics?await V.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:V.routingOverrides?await V.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Qa,claudeCodeHookPolicy:es}=za,ts=t.fleetToolPolicy,ns=ts?.enabled.includes(V.id)?ts.tiers?.[V.id]??Ra:void 0;$.push({id:V.id,title:V.title,installed:Ne.installed,...Ne.detail?{detail:Ne.detail}:{},pointedAt:On,...qa?{routingHeld:!0}:{},...lc?{routingPendingReload:!0}:{},...Qa.length?{routingOverrides:Qa}:{},...es===void 0?{}:{claudeCodeHookPolicy:es},mcp:nr,...ns?{policyTier:ns}:{},...t.revertedTools?.includes(V.id)?{tombstoned:!0}:{},...V.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...ht===void 0?{}:{inferenceIntrospectable:ht.authoritative,...ht.authoritative?{}:{inferenceUnverifiableReason:ht.reason}}})}let Y=s?await(async()=>{let{kind:V,detail:Ne,remedy:nr}=await i(ge({origin:e,clientKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey,subscription:t.authMode==="subscription",placeholder:t.authMode==="placeholder",byoUpstream:t.byoUpstream,...t.authMode==="auto"?{seat:{anthropic:!1,openai:!1,copilot:!1}}:{},user:t.name,team:t.team}),{tools:t.managedTools??[]});return{kind:V,detail:Ne,remedy:nr}})():null,Z=Y?.kind==="provider-rejected"&&await wV(t.managedTools??[],r),W=Y?{...Y,...Z?{notApplicableSubscription:!0}:{}}:null,z=n?hV(await _a({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:de({user:t.name,team:t.team})},fV,{probe:!0}),{mode:x,ssoLink:E}):null,me=await u().catch(()=>({})),Te=In(me.hookLane),re=s?await OI(r):!1,Ke=re?await(async()=>{let V=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...gm(V,{hookRegistered:re,neverInvoked:mm(Te,Date.now())}),lastInvokedAt:Ld(Te)}})():null,De=(await yr()).map(V=>({adapter:V.adapter,op:V.op,requestedAt:V.requestedAt,watcherAlive:wr(V.watcherPid)})),O=De.find(V=>V.adapter==="cursor"),T=O?{op:O.op,requestedAt:O.requestedAt,watcherAlive:O.watcherAlive}:null,H=!!t.refreshSchedulerEnabled,fe=await Jo(),Q=await d(),Ze=t.persistenceOwner==="tray",Fe=Ze?await l(t)==="healthy":null,te=await LE({daemonEnabled:h&&!Ze,daemonHealthy:h?!!m:null,schedulerEnabled:H&&!Ze,schedulerInstalled:fe,binaryDurable:!je(ur())}),Be=await Bu(),Le=0;p&&!p.reachable&&(Le+=1),h&&!m&&(Le+=1),Ze?H&&!Fe&&(Le+=1):H&&!fe&&(Le+=1);for(let V of $)Le+=Py(V);W&&W.kind!=="ok"&&!W.notApplicableSubscription&&(Le+=1),z&&z.kind!=="ok"&&(Le+=1),Ke?.verdict==="dark"&&(Le+=1),P.length>0&&(Le+=1),Le+=De.filter(V=>!V.watcherAlive).length,Be.length>0&&(Le+=1);let Xt=await EI();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:pV(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:gt(),selfUpdate:{managed:Q.managed,available:Q.available,autoUpdate:Q.autoUpdate,state:Q.state}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},toolOrigin:w,fallbackProxy:{enabled:h,port:h?t.fallbackPort:null,healthy:h?!!m:null},refreshScheduler:{enabled:H,installed:fe,owner:Ze?"tray":"os",...Ze?{trayHealthy:!!Fe}:{}},serviceRemoval:te,retiredFallbackState:Be,fleetdPresent:await Po(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:y(t.name)},enrollment:{enrolled:!!b,deploymentId:b?.deploymentId??null,issuedAt:b?.issuedAt??null,expiresAt:A,expired:A?Date.parse(A)<Date.now():null,orgMode:x,ssoLink:E},shell:{profilePath:C,blockPresent:I,staleExports:P},tools:$,...t.fleetToolPolicy?{fleetPlan:Id(t,t.fleetToolPolicy,!1)}:{},cursorQueue:T,pendingOps:De,ambientRepairs:bV(me,r),verify:W,retrieval:z,hookLane:Ke,agentsWindow:Xt,problems:Le}},CV=e=>{if(e.serviceRemoval.suspected){K("Endpoint security"),D(" Anyray installed these background services, but their files are gone from disk \u2014"),D(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),D(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)k(S(` missing: ${t}`));k(S(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(S(" tools straight at the gateway (your key then needs a periodic re-run).")),k(S(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(S(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},AV=e=>{if(e.retiredFallbackState.length!==0){K("Retired fallback lane"),_(" A cached organization provider key from the removed --fallback lane is still on this machine.");for(let t of e.retiredFallbackState)k(S(` ${t}`));k(S(" Fix: `anyray-connect doctor --repair` deletes it (a normal `anyray-connect` run does too)."))}},vV=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${pr(e.connect.remoteContext)}`),At(e.connect.remoteContext)&&k(S(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),K("CLI updates"),e.connect.selfUpdate.state){case"managed":U(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||D(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":D(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),k(S(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":D(" Self-update is unavailable on this platform because no standalone binary is published."),k(S(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(S(" This copy is externally managed; update it with the method that installed it."));break;case"container":k(S(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(K("Gateway"),e.gateway.reachable===null?k(S(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?U(` Reachable: ${e.gateway.origin} ${S(`(${e.gateway.detail})`)}`):(_(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),k(S(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.fallbackProxy.enabled&&(K("Local key-refresh proxy"),e.fallbackProxy.healthy?U(` Running on 127.0.0.1:${e.fallbackProxy.port} \u2192 ${e.gateway.origin} `+S("(auto-refreshes your key so long sessions never 401)")):(_(` Enabled on 127.0.0.1:${e.fallbackProxy.port} but NOT responding \u2014 your tools point at it and cannot reach any gateway until it's back.`),e.serviceRemoval.kinds.includes("daemon")||k(S(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to point tools straight at the gateway.")))),e.refreshScheduler.enabled&&(K("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?U(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh and supervises the daemon."):(_(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),k(S(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?U(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(_(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||k(S(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),CV(e),AV(e),K("Personal key"),mV(e)){case"env":U(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":U(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":D(" Enrolled, but no personal key is cached locally right now."),k(S(" 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:D(" Enrollment required \u2014 no personal gateway key is available."),k(S(` Fix: ${Ty(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?D(` Enrollment cert expired ${S(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):U(` Enrollment cert valid until ${e.enrollment.expiresAt} ${S(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(K("Shell"),_(" This terminal still exports Anyray, but the config is gone."),k(S(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(S(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(S(" Anything you start from this terminal keeps reaching the gateway with")),k(S(" no credential, and fails with 401.")),k(S(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(S(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(S(" reuses the environment it captured at launch, so a new terminal")),k(S(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};K("Claude Code hook policy"),_(` ${Ic(c)}.`),k(S(` ${Rc(c)}`))}K("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])_(` ${c.title}: ${l.problem}.`),k(S(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(_(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),k(S(" Fix: re-run `anyray-connect` to re-register the current binary."))):U(` ${c.title}: retrieval MCP server registered ${S("(anyray_retrieve / anyray_recall)")}`):(D(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),k(S(" Fix: re-run `anyray-connect` from a durable install (registration is skipped for one-off npx runs)."))))};for(let c of e.tools){if(!c.installed){k(S(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){k(S(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){U(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),k(S(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}U(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&Ui(c.id)?S(" (via key-refresh proxy)"):""}`),o(c),c.id==="claude-code"&&k(S(" 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===Wa&&k(S(` ${WC}`)),c.id==="codex"&&k(S(" 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=II(c);if(l==="not-routed"||l==="unverifiable"){let d=Qd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});D(` ${c.title}: ${d.headline}`);for(let u of d.detail)k(S(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(D(` ${c.title}: reverted locally against admin policy (out of compliance)`),k(S(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?D(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):k(S(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(_(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),k(S(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(_(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),k(S(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(D(" No tools are pointed at this gateway yet."),k(S(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){K("Queued operations");for(let c of e.pendingOps){let l=Kt(c.adapter)?.title??c.adapter;c.watcherAlive?D(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(_(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),k(S(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){K("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=Kt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:p,at:h})=>`${c(p)} ${new Date(h).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?D(f):k(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){K("Fleet policy");let c=l=>l.map(d=>Kt(d)?.title??d).join(", ");i.freshIds.length>0&&k(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&D(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(K("Auth probe"),e.verify.notApplicableSubscription)U(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")U(` ${e.verify.detail}`);else{_(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(S(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")U(` ${e.retrieval.detail}`);else{_(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(S(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")U(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(S(` ${c}`))}else{D(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(S(` ${c}`))}e.hookLane.lastInvokedAt!==null&&k(S(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(K("VS Code Agents window"),D(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(K("VS Code Agents window"),U(` ${e.agentsWindow.detail}`)),K("Summary"),e.problems===0?(e.verify?U(" No problems found."):U(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(S(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):_(` ${e.problems} problem(s) found \u2014 see fixes above.`)},SV=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}),EV=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!pm(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??Pa,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??nt)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=In((await(t.readRefreshState??Gt)().catch(()=>({}))).hookLane),l=gm(i,{hookRegistered:await OI(t.adapters??ie).catch(()=>!1),neverInvoked:mm(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:Ld(c)},note:d}},xV=async(e,t,n={})=>{let r=n.adapters??ie,o=n.resolveTarget??Oe,a=n.applyTools??wt,s=await EV(e,n).catch(()=>null),i=s&&e.hookLane?.verdict==="dark"&&s.hookLane?.verdict==="live"?1:0,c=s?{hookLane:s.hookLane,notes:[s.note]}:{notes:[]},l=e.tools.filter(y=>y.installed&&(_y(y)||y.mcp?.commandOk===!1||y.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t,void 0,be);if(!d)return{entries:l.map(y=>({id:y.id,title:y.title,status:"skipped-not-enrolled"})),remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,`Repair needs an enrolled personal key \u2014 ${Ty(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],p=[...c.notes],h=[];for(let y of l){let b=r.find(A=>A.id===y.id);if(!u.has(y.id)||!b){f.push({id:y.id,title:y.title,status:"skipped-unmanaged"});continue}h.push(b)}f.length>0&&p.push("Drifted tools outside the managed record are never auto-repaired \u2014 run `anyray-connect` once to (re)configure and record them.");let m=await a(h,d.target),w=new Map,g=0;for(let y of m){if(f.push(y),!bo(y))continue;let b=e.tools.find(P=>P.id===y.id);if(!b)continue;let A=r.find(P=>P.id===y.id),v=b.mcp;if(A?.mcpStatus)try{let P=await A.mcpStatus();v={...P,commandOk:RI(P)}}catch{}let E=_y(b)?!0:b.pointedAt;if(A?.pointsAt&&b.pointedAt!==null)try{E=await A.pointsAt(Fi(A.id,e.gateway.origin,e.toolOrigin))}catch{}let x=b.routingOverrides,C=b.claudeCodeHookPolicy;if(A?.runtimeDiagnostics)try{let P=await A.runtimeDiagnostics();x=P.routingOverrides.length?P.routingOverrides:void 0,C=P.claudeCodeHookPolicy}catch{}else if(A?.routingOverrides)try{let P=await A.routingOverrides();x=P.length?P:void 0}catch{}let I={...b,pointedAt:E,mcp:v,...x?{routingOverrides:x}:{},...C===void 0?{}:{claudeCodeHookPolicy:C}};x||delete I.routingOverrides,C===void 0&&delete I.claudeCodeHookPolicy,w.set(y.id,I),g+=Py(b)-Py(I)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},IV=e=>{K("Repair"),e.entries.length===0&&U(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?U(` ${t.title}: re-applied`):t.status==="queued"?U(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(S(` ${t.title}: ${t.status}`)):_(` ${t.title}: ${t.status}`);for(let t of e.notes)k(S(` ${t}`))},_I=async(e,t={})=>{let n=await L();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of NE(n.fallbackPort??ke))k(c?` ${c}`:"");return 0}let r;try{r=Dr(e.gateway,n)}catch(c){return e.json?(console.log(JSON.stringify({error:c.message})),1):(k(j("Anyray connect \u2014 doctor")),_(` Gateway URL: ${c.message}`),k(S(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(k(j("Anyray connect \u2014 doctor")),_(" --quick skips the network probes; it cannot be combined with --verify.")),1;let o=!e.noVerify&&!e.quick,a=await kV(r,n,!!e.verify&&!e.quick,t.adapters??ie,t.inferenceIntrospection??qd,t.fleetBootstrap??Vt,o,t.verifyAuth??qi,!e.quick,t.checkTray??xo,t.updateStatus??Oo,t.readRefreshState??Gt,t.probeHookLane??Pa);e.repair&&a.retiredFallbackState.length>0&&(await gc(),a.retiredFallbackState=await Bu(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await xV(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;e.json?console.log(JSON.stringify(SV(i),null,2)):(vV(i),s&&IV(s));try{e.quick||await(t.reportHealth??ES)(xI(i),i.connect.version)}catch{}return i.problems===0?0:1};var RV=()=>{let e=[];for(let t of ie){let n=t.skillsDir?.();n&&e.push(n)}return e},PI=async e=>{let t=await L();k(j("Anyray connect \u2014 sync"));let n;try{n=Dr(e.gateway,t)}catch(s){return _(s.message),1}M(`Gateway: ${n}`);let r=ux(t.clientKey,"anyray-placeholder"),o;try{o=await Od(n,r)}catch(s){return _(`Team policy sync failed: ${Rd(s)}`),1}let a=RV();if(a.length===0)OV();else if(o.skills.length===0)M("No team skills published yet \u2014 nothing to sync.");else{let s=await sS(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?U(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):M(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await oe({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){M(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${rt(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await _d(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(k(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&M(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){M(`Fleet policy reconcile skipped: ${Rd(s)}`)}return 0},OV=()=>{M("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as D2}from"node:zlib";import{promisify as L2}from"node:util";var Mr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Dy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),TI=e=>`
|
|
700
701
|
|
|
701
702
|
\u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
|
|
702
703
|
|
|
703
|
-
`,
|
|
704
|
-
`,E);
|
|
705
|
-
`,v);C!==-1&&C<d&&(v=C),v>E&&u.push([E,v])}}a>0&&u.push([d,r]),u.sort((g,y)=>g[0]-y[0]);let p=[];for(let[g,y]of u){let b=p[p.length-1];b&&g<=b[1]?b[1]=Math.max(b[1],y):p.push([g,y])}let h="",m=0;for(let[g,y]of p)g>m&&(h+=
|
|
704
|
+
`,hu=(e,t={})=>{if(typeof e!="string")return Dy(String(e??""));let n=Math.max(1,t.maxChars??Mr.maxChars);if(e.length<=n)return Dy(e);let r=e.length,o=Math.max(0,t.headChars??Mr.headChars),a=Math.max(0,t.tailChars??Mr.tailChars),s=Math.max(0,t.middleWindows??Mr.middleWindows),i=100*(s+2),c=Math.max(1,n-1-i);o+a>c&&(a=Math.min(a,c),o=Math.max(0,c-a));let l=o,d=r-a,u=[];o>0&&u.push([0,o]);let f=c-o-a;if(s>0&&f>0&&d>l){let g=d-l,y=Math.max(1,Math.floor(f/s));for(let b=0;b<s;b++){let A=l+Math.round((b+.5)/s*g),v=Math.min(d,Math.max(l,A)+Math.ceil(y/2)),E=Math.max(l,v-y),x=e.lastIndexOf(`
|
|
705
|
+
`,E);x>=l&&(E=x+1);let C=e.indexOf(`
|
|
706
|
+
`,v);C!==-1&&C<d&&(v=C),v>E&&u.push([E,v])}}a>0&&u.push([d,r]),u.sort((g,y)=>g[0]-y[0]);let p=[];for(let[g,y]of u){let b=p[p.length-1];b&&g<=b[1]?b[1]=Math.max(b[1],y):p.push([g,y])}let h="",m=0;for(let[g,y]of p)g>m&&(h+=TI(g-m)),h+=e.slice(g,y),m=y;if(r>m&&(h+=TI(r-m)),h.length>=r)return Dy(e);let w=r-h.length;return{text:h,trimmed:!0,originalChars:r,trimmedChars:h.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},_V=["stdout","content","output","text","result"],DI=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} ---
|
|
706
707
|
${d}`);s&&i.push(`--- MCP structuredContent ---
|
|
707
708
|
${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
|
|
708
709
|
|
|
709
|
-
`),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=_V.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 PV=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},zi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},
|
|
710
|
-
`),s=0,i=0;for(let c of a)c.trim()&&(s++,PV(c)&&i++);return s===0||i<o?!1:i/s>=r};var Qi=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,
|
|
711
|
-
${e.slice(-
|
|
712
|
-
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},JV=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,
|
|
710
|
+
`),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=_V.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 PV=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},zi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},mu=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??zi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??zi.minDataLineRatio,o=t.minDataLines??zi.minDataLines,a=e.split(`
|
|
711
|
+
`),s=0,i=0;for(let c of a)c.trim()&&(s++,PV(c)&&i++);return s===0||i<o?!1:i/s>=r};var Qi=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,yu={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"},$I=new Set(["npm","pnpm","yarn","bun"]),gu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},TV=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=gu(r[0]);if(o in yu)return yu[o];if((o==="npx"||o==="bunx")&&r[1]){let a=gu(r[1]);if(a in yu)return yu[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||$I.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},Ny=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=TV(t);if(n)return n}return null},DV={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},LV=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,NV=(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},MI=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=gu(r[0]);if($I.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&LV.test(i)}let a=r[1]?gu(r[1]):void 0;if(NV(o,a,r))return!1;let s=DV[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},$V=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==="]"},MV=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},UV=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=MV(t);return r>0&&t[r+1]===":"},FV=80,BV=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/FV),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,UV(e[o])&&r++;return n>0&&r/n>.3},WV=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,HV=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();(WV.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},KV=[/\b\d+\s+(passed|failed|errors?|skipped|xfailed|xpassed)\b.*\bin\s+[\d.]+\s*s/i,/^=+ FAILURES =+/m,/^=+ short test summary/im,/test session starts/i,/^Test Suites:\s+\d+/m,/^Tests:\s+\d+\s+(failed|passed|total)/m,/^test result:\s+(ok|FAILED)\b/m,/^running \d+ tests?$/m,/^--- (FAIL|PASS): /m,/^(ok|FAIL)\s+\S+\s+[\d.]+s/m],Ly=8192,GV=e=>{let t=e.length>2*Ly?`${e.slice(0,Ly)}
|
|
712
|
+
${e.slice(-Ly)}`:e;return KV.some(n=>n.test(t))},jV=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),VV=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),YV=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},ZV=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),LI=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(VV(i)){t.push(Qi(i));continue}let c=YV(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Qi(c)),o=12;continue}jV(i)||ZV(i)||o>0&&(t.push(Qi(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
|
|
713
|
+
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},JV=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,UI=e=>{let t=JV.exec(e);return t&&/[/.]/.test(t[1])?t:null},XV=/^([^\s:]+)-(\d+)-/,qV=e=>{if(e==="--")return!0;let t=XV.exec(e);return t!=null&&/[/.]/.test(t[1])},zV=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>UI(r)!=null).length;return n>=3&&n/t.length>=.7},NI=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=UI(c);if(!l){if(qV(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(Qi(` ${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(`
|
|
713
714
|
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},QV=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(),e2=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=QV(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=Qi(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
|
|
714
|
-
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},
|
|
715
|
-
`).filter(s=>s.trim()!==""),r=
|
|
715
|
+
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},FI=(e,t)=>{if(typeof t!="string"||t.length===0||$V(t))return null;let n=t.split(`
|
|
716
|
+
`).filter(s=>s.trim()!==""),r=Ny(e),o=GV(t),a=null;return r==="test-run"&&o?a=LI(n):r==="grep"&&(a=NI(n,.5)),a||(o?a=LI(n):zV(n)?a=NI(n,.7):!HV(n)&&!BV(n)&&(a=e2(n))),!a||a.text.length>=t.length?null:a},$y=(e,t)=>t?`
|
|
716
717
|
|
|
717
718
|
\u2026[anyray-hook digest \u2014 ${e}; full output: ${t}]\u2026`:`
|
|
718
719
|
|
|
719
|
-
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,
|
|
720
|
+
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,BI=e=>`
|
|
720
721
|
|
|
721
|
-
\u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as t2}from"node:crypto";import{homedir as n2}from"node:os";import{join as To}from"node:path";import{chmod as r2,mkdir as o2,readdir as
|
|
722
|
-
`):"",
|
|
722
|
+
\u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as t2}from"node:crypto";import{homedir as n2}from"node:os";import{join as To}from"node:path";import{chmod as r2,mkdir as o2,readdir as GI,stat as tc,unlink as ec,utimes as a2,writeFile as Uy}from"node:fs/promises";var wu={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},jI=".swept",s2=".sweeping",WI=64,HI=448,Fy=384,i2=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",VI=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,YI=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=ee();try{if((await tc(t)).isDirectory())return To(t,"hook-tee")}catch{}return To(n2(),".anyray-hook-tee")},c2=async(e,t={})=>{let n=t.limits??wu;try{let r=Date.now(),o=(await GI(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=WI)await Promise.all(o.slice(c,c+WI).map(async l=>{let d=To(e,l);try{let u=await tc(d);if(!u.isFile())return;let f=r-u.mtimeMs>n.ttlMs||r-VI(u)>n.maxAgeMs;if(d!==t.protect&&f){await ec(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 ec(c.path).catch(()=>{})}}catch{}},ZI=async e=>{try{return Date.now()-(await tc(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},KI=async e=>{try{return await Uy(e,"",{mode:Fy,flag:"wx"}),!0}catch{return!1}},l2=async(e,t)=>{let n=wu,r=To(e,s2),o=To(e,jI);if(!await KI(r)){let a=0;try{a=Date.now()-(await tc(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await ec(r).catch(()=>{}),!await KI(r)))return!1}try{return await ZI(o)<n.sweepIntervalMs?!1:(await Uy(o,"",{mode:Fy}).catch(()=>{}),await c2(e,{protect:t}),!0)}finally{await ec(r).catch(()=>{})}},My=async(e,t)=>await ZI(To(e,jI))<wu.sweepIntervalMs?!1:l2(e,t),d2=async()=>{try{let e=await YI();if(!(await GI(e)).some(t=>t.endsWith(".txt")))return;await My(e)}catch{}},JI=async e=>{if(i2())return await d2(),null;try{let t=await YI();await o2(t,{recursive:!0,mode:HI}),await r2(t,HI).catch(()=>{});let n=`${t2("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=To(t,n),o=Date.now();try{let a=await tc(r);if(a.isFile()){if(o-VI(a)<=wu.maxAgeMs){let s=new Date(o);return await a2(r,s,s).catch(()=>{}),await My(t,r),r}await ec(r).catch(()=>{})}}catch{}return await Uy(r,e,{mode:Fy}),await My(t,r),r}catch{return null}};import{createHash as u2}from"node:crypto";import{homedir as XI}from"node:os";import{join as By}from"node:path";import{readFile as p2,writeFile as f2,chmod as h2,stat as m2,unlink as y2}from"node:fs/promises";var g2=200,w2=1440*60*1e3,b2=4e6,qI=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",zI=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},k2=()=>zI("ANYRAY_HOOK_CACHE_MAX_ENTRIES",g2),QI=()=>zI("ANYRAY_HOOK_CACHE_TTL_MS",w2),e0=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=By(XI(),".anyray");try{if((await m2(t)).isDirectory())return By(t,"hook-cache.json")}catch{}return By(XI(),".anyray-hook-cache.json")},t0=(e,t,n)=>u2("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(qI())return null;try{let n=(await n0(await e0())).entries[e];return!n||Date.now()-n.at>QI()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},C2=e=>{let t=Date.now(),n=QI(),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=k2();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>b2&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},o0=async(e,t)=>{if(qI())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=C2(o.entries),n=`${r}.${process.pid}.tmp`,await f2(n,JSON.stringify(o),{mode:384}),await h2(n,384),await he(n,r)}catch{if(n)try{await y2(n)}catch{}}};import{open as A2,stat as v2}from"node:fs/promises";var a0=600,S2=3,E2=256e3,x2=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(`
|
|
723
|
+
`):"",I2=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),R2=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},O2=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=x2(o.message?.content).trim();if(!(!a||I2(a))&&(t.unshift(a),n+=a.length,t.length>=S2||n>=a0))break}return t.join(`
|
|
723
724
|
`).slice(0,a0)};var _2=e=>/(^|[\\/])subagents[\\/]/i.test(e),P2=e=>/\.jsonl$/i.test(e),T2=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||!P2(e))return t;let n;try{let{size:r}=await v2(e),o=Math.max(0,r-E2),a=r-o;if(a<=0)return t;n=await A2(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(`
|
|
724
725
|
`);i=l>=0?i.slice(l+1):""}let c=R2(i.split(`
|
|
725
|
-
`));return T2(c)?{intent:O2(c),kind:_2(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var N2=3e3,$2=1500,M2=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:N2},U2={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},F2=new Set(["claude","opencode"]),B2=(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:U2[t]})},W2={cacheGet:async()=>null,cachePut:async()=>{}},H2=(e,t={cacheGet:r0,cachePut:o0,tee:
|
|
726
|
-
`:"",
|
|
727
|
-
${i0(r.tool_input)}`:i0(r.tool_input),g=t0(o,w,u),y=async E=>{try{await t.cachePut(g,E)}catch{}},b=null;try{b=await t.cacheGet(g)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?h(b.output,b.tokensSaved):m();let A=null;try{A=iY(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{A=null}if(A&&!A.handled&&(A=null),A)return A.optimized&&A.output.length<u.length?(await y({optimized:!0,output:A.output,tokensSaved:
|
|
728
|
-
`}catch{return}},fY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},hY=()=>{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")}},mY=(e,t)=>{let n=t.minChars??zi.minChars,r={maxChars:Math.min(Mr.maxChars,n)},o=
|
|
726
|
+
`));return T2(c)?{intent:O2(c),kind:_2(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var N2=3e3,$2=1500,M2=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:N2},U2={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},F2=new Set(["claude","opencode"]),B2=(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:U2[t]})},W2={cacheGet:async()=>null,cachePut:async()=>{}},H2=(e,t={cacheGet:r0,cachePut:o0,tee:JI})=>e==="claude"?t:W2,K2=1e3,G2=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),bu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),j2=e=>{try{let t=JSON.parse(e);if(!bu(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 bu(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},V2=e=>{try{let t=JSON.parse(e);return bu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},Y2=e=>bu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
727
|
+
`:"",Wy=e=>Math.round(Math.max(0,e)/4),i0=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",Z2=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),J2=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),X2=["tool_output","tool_response","tool_result"],q2=e=>{for(let t of X2)if(t in e)return e[t]},z2=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},Q2=120,eY=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??K2))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=$y(r.stat,null).length+Q2;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=$y(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}}},tY=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let E=JSON.parse(e);if(!E||typeof E!="object")return n;r=E}catch{return n}let o=typeof r.tool_name=="string"?r.tool_name:"unknown";if(Z2.has(o)||J2(o))return n;let a=DI(q2(r));if(!a)return n;let s=async E=>{try{await t.beacon(o,E)}catch{}},i=a.body,c=typeof r.transcript_path=="string"?r.transcript_path:"",l={intent:"",retrievalContext:t.defaultRetrievalContext??"unknown"};if(t.readContext&&c)try{l=await t.readContext(c)}catch{l={intent:"",retrievalContext:"unknown"}}if(c0(o)&&l.retrievalContext!=="available")return n;let d=await eY(t,z2(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!mu(i,{minChars:$2})))return n;let p=i.length-u.length-f.length,h=async(E,x,C=E.length+f.length)=>{let I=d?.teePath??null;if(!I&&t.tee)try{I=await t.tee(i)}catch{I=null}let P=I?E.replaceAll("; not retrievable in this context]","]"):E,$=I&&!f?BI(I):"",Y=P+f+$,Z=$.length,W=Y;if(t.finalizeOutput)try{let re=t.finalizeOutput(Y);re.length<=Y.length&&(W=re)}catch{W=Y}let z=Y.length-W.length,me=Wy(Math.max(0,p-Z))+x+Wy(z);me>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,C+Z-z),estTokensSaved:me,...d&&{digest:d.decision}});let Te=a.rebuild(W);return{stdout:G2(Te),replacement:Te}},m=async()=>d?h(u,0):n;if(d&&u.length<=t.sizeGate)return h(u,0);let w=l.intent?`${l.intent}
|
|
728
|
+
${i0(r.tool_input)}`:i0(r.tool_input),g=t0(o,w,u),y=async E=>{try{await t.cachePut(g,E)}catch{}},b=null;try{b=await t.cacheGet(g)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?h(b.output,b.tokensSaved):m();let A=null;try{A=iY(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{A=null}if(A&&!A.handled&&(A=null),A)return A.optimized&&A.output.length<u.length?(await y({optimized:!0,output:A.output,tokensSaved:Wy(u.length-A.output.length)}),h(A.output,0,u.length+f.length)):(await y({optimized:!1}),m());let v;try{v=t.localTrim(u)}catch{return m()}return v.trimmed?h(v.text,v.estTokensSaved):m()},nc=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},nY=()=>{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")}},rY=L2(D2),oY=async e=>{try{let t=await rY(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()),aY=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},sY=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),iY=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),cY=2048,lY=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,cY),n=Dd(t);if(!n)return;await XS({at:Date.now(),status:e.status,code:n})}catch{}},dY=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),M2());try{let c=await oY(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...c0(t)||aY(t)&&a==="available"?{reversible:!0}:{},...sY(t)?{semanticRerank:!0}:{},output:r})),l=Qt(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 lY(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 nc();if(e!=="cursor"&&V2(t))return 0;let n=e==="cursor"?j2(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Hy(n,e);if(e==="cursor"){let a=Y2(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Hy=async(e,t="claude",n)=>{await Pr(),await JS(t);let r=nY(),o=await at(),a=o&&{...o,metadata:B2(o.metadata,t)},s=H2(t);return tY(e,{optimize:(i,c,l,d,u)=>dY(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=>hu(i,r),beacon:(i,c)=>_c(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Mr.maxChars,digestCommand:FI,tee:s.tee,mediumBand:F2.has(t),finalizeOutput:n})};var d0=async()=>0;var uY=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},pY=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??Vt)();if(!r)return;let o=await(t.ssoGate??Qn)({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})}
|
|
729
|
+
`}catch{return}},fY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},hY=()=>{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")}},mY=(e,t)=>{let n=t.minChars??zi.minChars,r={maxChars:Math.min(Mr.maxChars,n)},o=hu(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},u0=async()=>{let e=await fY(),t=await pY(e);t&&process.stdout.write(t);let n=hY(),r=await at();return await uY(e,{isPaste:o=>mu(o,n),measure:o=>mY(o,n),beacon:o=>_c(r,"prompt",o)}),0};import{spawn as yY}from"node:child_process";var p0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),gY=/[|&;<>`$()\n]/,f0=e=>{if(gY.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},wY=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!p0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!p0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(qu)||!t.isRecognized(o)||f0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},bY=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?f0(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
|
|
729
730
|
`),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
|
|
730
|
-
`),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},kY=16*1024*1024,CY=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=yY(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>kY){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)}}),AY=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Wy(n,"cursor");return typeof r=="string"?r:t},h0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return bY(t,{exec:CY,trim:AY,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},m0=async()=>{let e=await nc();if(process.platform==="win32")return 0;let t=wY(e,{isRecognized:n=>Ly(n)!==null||Mx(n),wrap:n=>Dt(Xu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as vY}from"node:crypto";import{homedir as y0}from"node:os";import{extname as SY,isAbsolute as EY,join as Hy,resolve as rc,sep as g0}from"node:path";import{chmod as IY,readFile as xY,stat as A0,unlink as RY,writeFile as OY}from"node:fs/promises";var Gy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_Y=16*1024,w0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],PY=["pattern","query","regex","search"],TY=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"]),DY=720*60*1e3,LY=512,Ky=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},NY=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],b0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(g0)?n:n+g0)),$Y=(e,t,n)=>EY(e)?[rc(e)]:[...new Set([rc(t,e),...n.map(r=>rc(r,e))])],k0=(e,t,n)=>vY("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),C0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),MY=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!Gy(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!Gy(o))return"";let a=NY(n.workspace_roots).map(d=>rc(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=Ky(o,PY);if(!d)return"";let u=Ky(o,w0);return u&&!b0(rc(s,u),a)||!await t.remember(k0(i,"Grep",d))?"":C0(`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=Ky(o,w0);if(!c||TY.has(SY(c).toLowerCase()))return"";let l=await t.resolveFile($Y(c,s,a));return!l||l.bytes<_Y||!b0(l.path,a)||!await t.remember(k0(i,"Read",l.path))?"":C0(`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.`)},UY=async e=>{for(let t of e)try{let n=await A0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},FY=async()=>{let e=Hy(y0(),".anyray");try{if((await A0(e)).isDirectory())return Hy(e,"cursor-redirects.json")}catch{}return Hy(y0(),".anyray-cursor-redirects.json")},BY=async e=>{let t;try{let n=await FY(),r=Date.now(),o={};try{let s=JSON.parse(await xY(n,"utf-8"));if(s?.v===1&&Gy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=DY&&(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,LY);return t=`${n}.${process.pid}.tmp`,await OY(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await IY(t,384),await he(t,n),!0}catch{if(t)try{await RY(t)}catch{}return!1}},v0=async()=>{let e=await nc(),t="";try{t=await MY(e,{resolveFile:UY,remember:BY})}catch{t=""}return t&&process.stdout.write(t),0};var oc=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},jy=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=oc(n,"deviceCode"),o=oc(n,"privateKeyPem"),a=oc(n,"publicKeyPem"),s=oc(n,"cpOrigin"),i=oc(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=jy(n.gatewayUrl),f=jy(n.gatewayOverride),p=jy(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}},HY=e=>new Promise(t=>setTimeout(t,e)),KY=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??Kd,r=t.verify??dn,o=t.loadProfile??L,a=t.saveProfile??oe,s=t.saveDevKey??mc,i=t.readGateState??Tr,c=t.writeGateState??Gd,l=t.clearGateState??iE,d=t.sleep??HY,u=t.now??Date.now,f=t.recordMint??Ta,p=t.reserveMint??So,h=t.applyClaudeCode??(async I=>{await dr.apply(I,{dryRun:!1})}),m=I=>KY(I,{readGateState:i,writeGateState:c,now:u}),w={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g;try{g=await n(w,{gatewayUrl:e.gatewayOverride})}catch(I){let C=I instanceof jt?I.kind:"cp-unreachable";return await m(C),C}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),A={...b,gateway:y??b.gateway,name:g.cert.payload.user||b.name,team:e.team??g.cert.payload.team??b.team,enrolledCert:g.cert,enrolledCertExpiry:g.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(g.privateKeyPem),await a(A)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let v;await p();for(let I=0;I<3;I++)try{v=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(C){if(C instanceof Ot||I===2)break;await d(1e3)}if(!v)return await m("gateway-unreachable"),"gateway-unreachable";let E={...A,gateway:y,name:v.user,team:e.team??v.team??A.team,clientKey:v.key,clientKeyExpiresAt:v.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:v.expiresAt});let I=ge({origin:y,clientKey:v.key,subscription:!0,user:E.name,team:E.team});return await h(I),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},jY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},S0=async()=>{let e=WY(await jY());if(e)try{await GY(e)}catch{}return 0};var VY=1e4,Vy=/^[\w.:-]{1,64}$/,Jt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Yy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,E0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),VY);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new Jt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},YY=e=>{let t=Yy(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=Yy(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Vy.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Vy.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=Yy(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ie(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Vy.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}}},XY=e=>new Promise(t=>setTimeout(t,e)),qY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Jt("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}k("Available teams:"),e.forEach((i,c)=>k(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Ba("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Jt("invalid-team","Choose one of the teams shown above.");return s},zY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??XY,a=t.loadProfile??L,s=t.saveProfile??oe,i=t.clearDevKey??is,c=t.chooseTeam??qY,l=t.apply??(async g=>{await dr.apply(g,{dryRun:!1})}),d=t.log??M,u=await a(),f=Dr(e.gateway,u),p=await E0(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=YY(p.body);if(p.status!==200||!h)throw new Jt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${h.browser_url}`),d(`Enter this code in the browser: ${h.user_code}`),(t.openBrowser??Da)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await E0(`${f}/sso/cli/poll/${encodeURIComponent(h.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":h.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(g.status===202){await o(h.interval*1e3);continue}if(g.status===401)throw new Jt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new Jt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=ZY(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new Jt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??Yt());continue}let b=JY(g.body);if(g.status!==200||!b)throw new Jt("login-failed","SSO login could not be completed.");let A={...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(A),await l(ge({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Jt("expired","SSO login expired before it completed. Run anyray-connect login again.")},QY=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
731
|
+
`),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},kY=16*1024*1024,CY=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=yY(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>kY){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)}}),AY=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Hy(n,"cursor");return typeof r=="string"?r:t},h0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return bY(t,{exec:CY,trim:AY,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},m0=async()=>{let e=await nc();if(process.platform==="win32")return 0;let t=wY(e,{isRecognized:n=>Ny(n)!==null||MI(n),wrap:n=>Dt(qu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as vY}from"node:crypto";import{homedir as y0}from"node:os";import{extname as SY,isAbsolute as EY,join as Ky,resolve as rc,sep as g0}from"node:path";import{chmod as xY,readFile as IY,stat as A0,unlink as RY,writeFile as OY}from"node:fs/promises";var jy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_Y=16*1024,w0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],PY=["pattern","query","regex","search"],TY=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"]),DY=720*60*1e3,LY=512,Gy=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},NY=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],b0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(g0)?n:n+g0)),$Y=(e,t,n)=>EY(e)?[rc(e)]:[...new Set([rc(t,e),...n.map(r=>rc(r,e))])],k0=(e,t,n)=>vY("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),C0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),MY=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=NY(n.workspace_roots).map(d=>rc(d));if(!a.length)return"";let s=typeof n.cwd=="string"&&n.cwd?n.cwd:a[0],i=typeof n.conversation_id=="string"&&n.conversation_id||typeof n.session_id=="string"&&n.session_id||"";if(r==="Grep"){let d=Gy(o,PY);if(!d)return"";let u=Gy(o,w0);return u&&!b0(rc(s,u),a)||!await t.remember(k0(i,"Grep",d))?"":C0(`Anyray: run this search with the anyray_search MCP tool instead of the built-in search. anyray_search ranks the matches by relevance and drops the noise, so the hits that answer the task reach you without the rest. Call anyray_search with query ${JSON.stringify(d)} now; do not retry the built-in search.`)}let c=Gy(o,w0);if(!c||TY.has(SY(c).toLowerCase()))return"";let l=await t.resolveFile($Y(c,s,a));return!l||l.bytes<_Y||!b0(l.path,a)||!await t.remember(k0(i,"Read",l.path))?"":C0(`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.`)},UY=async e=>{for(let t of e)try{let n=await A0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},FY=async()=>{let e=Ky(y0(),".anyray");try{if((await A0(e)).isDirectory())return Ky(e,"cursor-redirects.json")}catch{}return Ky(y0(),".anyray-cursor-redirects.json")},BY=async e=>{let t;try{let n=await FY(),r=Date.now(),o={};try{let s=JSON.parse(await IY(n,"utf-8"));if(s?.v===1&&jy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=DY&&(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,LY);return t=`${n}.${process.pid}.tmp`,await OY(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await xY(t,384),await he(t,n),!0}catch{if(t)try{await RY(t)}catch{}return!1}},v0=async()=>{let e=await nc(),t="";try{t=await MY(e,{resolveFile:UY,remember:BY})}catch{t=""}return t&&process.stdout.write(t),0};var oc=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Vy=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=oc(n,"deviceCode"),o=oc(n,"privateKeyPem"),a=oc(n,"publicKeyPem"),s=oc(n,"cpOrigin"),i=oc(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=Vy(n.gatewayUrl),f=Vy(n.gatewayOverride),p=Vy(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}},HY=e=>new Promise(t=>setTimeout(t,e)),KY=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??Gd,r=t.verify??dn,o=t.loadProfile??L,a=t.saveProfile??oe,s=t.saveDevKey??mc,i=t.readGateState??Tr,c=t.writeGateState??jd,l=t.clearGateState??iE,d=t.sleep??HY,u=t.now??Date.now,f=t.recordMint??Ta,p=t.reserveMint??So,h=t.applyClaudeCode??(async x=>{await dr.apply(x,{dryRun:!1})}),m=x=>KY(x,{readGateState:i,writeGateState:c,now:u}),w={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g;try{g=await n(w,{gatewayUrl:e.gatewayOverride})}catch(x){let C=x instanceof jt?x.kind:"cp-unreachable";return await m(C),C}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),A={...b,gateway:y??b.gateway,name:g.cert.payload.user||b.name,team:e.team??g.cert.payload.team??b.team,enrolledCert:g.cert,enrolledCertExpiry:g.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(g.privateKeyPem),await a(A)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let v;await p();for(let x=0;x<3;x++)try{v=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(C){if(C instanceof Ot||x===2)break;await d(1e3)}if(!v)return await m("gateway-unreachable"),"gateway-unreachable";let E={...A,gateway:y,name:v.user,team:e.team??v.team??A.team,clientKey:v.key,clientKeyExpiresAt:v.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:v.expiresAt});let x=ge({origin:y,clientKey:v.key,subscription:!0,user:E.name,team:E.team});return await h(x),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},jY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},S0=async()=>{let e=WY(await jY());if(e)try{await GY(e)}catch{}return 0};var VY=1e4,Yy=/^[\w.:-]{1,64}$/,Jt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Zy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,E0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),VY);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new Jt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},YY=e=>{let t=Zy(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=Zy(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Yy.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Yy.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=Zy(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!xe(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Yy.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}}},XY=e=>new Promise(t=>setTimeout(t,e)),qY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Jt("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}k("Available teams:"),e.forEach((i,c)=>k(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Ba("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Jt("invalid-team","Choose one of the teams shown above.");return s},zY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??XY,a=t.loadProfile??L,s=t.saveProfile??oe,i=t.clearDevKey??is,c=t.chooseTeam??qY,l=t.apply??(async g=>{await dr.apply(g,{dryRun:!1})}),d=t.log??M,u=await a(),f=Dr(e.gateway,u),p=await E0(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=YY(p.body);if(p.status!==200||!h)throw new Jt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${h.browser_url}`),d(`Enter this code in the browser: ${h.user_code}`),(t.openBrowser??Da)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await E0(`${f}/sso/cli/poll/${encodeURIComponent(h.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":h.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(g.status===202){await o(h.interval*1e3);continue}if(g.status===401)throw new Jt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new Jt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=ZY(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new Jt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??Yt());continue}let b=JY(g.body);if(g.status!==200||!b)throw new Jt("login-failed","SSO login could not be completed.");let A={...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(A),await l(ge({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Jt("expired","SSO login expired before it completed. Run anyray-connect login again.")},QY=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
731
732
|
|
|
732
733
|
Start browser SSO, choose a team, mint a personal gateway key, and configure
|
|
733
734
|
the subscription-backed Connect lane. In a non-interactive shell, --team may be
|
|
734
|
-
omitted only when the identity authority supplies a default or sole team.`,
|
|
735
|
+
omitted only when the identity authority supplies a default or sole team.`,x0=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return k(QY),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return _(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return _(`unknown login option: ${a}`),1}try{let o=await zY({gateway:n,team:r},t);return U(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof kt)throw o;return _(o instanceof Jt?o.message:"SSO login failed."),1}};var I0=`anyray-connect update [--check] [--auto on|off] [--json]
|
|
735
736
|
|
|
736
737
|
Keep this machine's anyray-connect binary on the published release. Runs
|
|
737
738
|
automatically about every 30 minutes; this command forces it now.
|
|
@@ -742,32 +743,32 @@ Options:
|
|
|
742
743
|
Off still accepts a release the Anyray team marks mandatory.
|
|
743
744
|
--json Emit the result as JSON.
|
|
744
745
|
--help Show this help.
|
|
745
|
-
`,eZ=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},tZ=e=>{switch(e.outcome){case"current":return`Already on the published version (${e.current}).`;case"available":return`Version ${e.latest} is published; this machine is on ${e.current}.`;case"updated":return`Updated ${e.current} \u2192 ${e.latest}. New commands run it immediately.`;case"migrated":return`Installed the managed ${e.latest} binary at ${e.managedPath}.`;case"migration-available":return`Version ${e.latest} will migrate this npm runtime to the managed standalone binary.`;case"migration-deferred":return`The published standalone binary (${e.latest}) is older than this npm runtime (${e.current}); migration was deferred.`;case"disabled":return`Automatic updates are off. Version ${e.latest} is published; this machine is on ${e.current}.`;case"unmanaged":return"This copy is not an Anyray-managed or npm runtime, so it updates elsewhere.";case"container":return"Self-update is skipped inside a container \u2014 it updates by rebuild, not by download-and-swap.";case"platform-unsupported":return"Self-update is unavailable because this platform has no published standalone binary.";case"unavailable":return"Could not reach the release feed to check for a newer version.";case"failed":return`Could not install ${e.latest??"the published version"} \u2014 staying on ${e.current}.`}},R0=async e=>{let t;try{t=eZ(e)}catch(o){return _(o.message),process.stderr.write(
|
|
746
|
+
`,eZ=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},tZ=e=>{switch(e.outcome){case"current":return`Already on the published version (${e.current}).`;case"available":return`Version ${e.latest} is published; this machine is on ${e.current}.`;case"updated":return`Updated ${e.current} \u2192 ${e.latest}. New commands run it immediately.`;case"migrated":return`Installed the managed ${e.latest} binary at ${e.managedPath}.`;case"migration-available":return`Version ${e.latest} will migrate this npm runtime to the managed standalone binary.`;case"migration-deferred":return`The published standalone binary (${e.latest}) is older than this npm runtime (${e.current}); migration was deferred.`;case"disabled":return`Automatic updates are off. Version ${e.latest} is published; this machine is on ${e.current}.`;case"unmanaged":return"This copy is not an Anyray-managed or npm runtime, so it updates elsewhere.";case"container":return"Self-update is skipped inside a container \u2014 it updates by rebuild, not by download-and-swap.";case"platform-unsupported":return"Self-update is unavailable because this platform has no published standalone binary.";case"unavailable":return"Could not reach the release feed to check for a newer version.";case"failed":return`Could not install ${e.latest??"the published version"} \u2014 staying on ${e.current}.`}},R0=async e=>{let t;try{t=eZ(e)}catch(o){return _(o.message),process.stderr.write(I0),1}if(t.help)return process.stdout.write(I0),0;if(t.auto!==void 0){let o=await L();if(o.autoUpdate!==!1!==t.auto&&await oe({...o,autoUpdate:t.auto}),t.json||(U(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||k("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!t.auto)return t.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
|
|
746
747
|
`),0}let n=await Ji({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await Oo();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state},null,2)}
|
|
747
|
-
`),n.outcome==="failed"?1:0}let r=tZ(n);switch(n.outcome){case"updated":case"migrated":U(r);break;case"current":U(r);break;case"available":case"migration-available":k(r),t.check&&k(`Run ${j("anyray-connect update")} to install it.`);break;case"migration-deferred":D(r),k(S("Use the newer npm runtime until that standalone release is published."));break;case"disabled":D(r),k(`Run ${j("anyray-connect update")} to install it now, or ${j("--auto on")} to resume.`);break;case"unmanaged":k(r),k(S("A copy your IT team placed is theirs to roll."));break;case"container":k(r);break;case"platform-unsupported":D(r),k(S("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":D(r);break;case"failed":return _(r),1}return 0};var nZ=3e3,O0=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>
|
|
748
|
+
`),n.outcome==="failed"?1:0}let r=tZ(n);switch(n.outcome){case"updated":case"migrated":U(r);break;case"current":U(r);break;case"available":case"migration-available":k(r),t.check&&k(`Run ${j("anyray-connect update")} to install it.`);break;case"migration-deferred":D(r),k(S("Use the newer npm runtime until that standalone release is published."));break;case"disabled":D(r),k(`Run ${j("anyray-connect update")} to install it now, or ${j("--auto on")} to resume.`);break;case"unmanaged":k(r),k(S("A copy your IT team placed is theirs to roll."));break;case"container":k(r);break;case"platform-unsupported":D(r),k(S("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":D(r);break;case"failed":return _(r),1}return 0};var nZ=3e3,O0=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>Cy(nZ)),o=e.updateStatus??Oo;t(`anyray-connect ${we}
|
|
748
749
|
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&ja(a,we)>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: ${we} \u2192 ${a}
|
|
749
750
|
${i}
|
|
750
|
-
`)}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 rZ=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},oZ=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),aZ=async(e={})=>{try{let t=await(e.readBootstrap??Vt)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??nt)().catch(()=>{});let n=await(e.loadProfile??L)();if(
|
|
751
|
-
`),0};var sZ="2025-06-18",iZ={name:"anyray",version:"1"},P0={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}},cZ=20,T0={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}},$0=
|
|
751
|
+
`)}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 rZ=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},oZ=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),aZ=async(e={})=>{try{let t=await(e.readBootstrap??Vt)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??nt)().catch(()=>{});let n=await(e.loadProfile??L)();if(xe(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Qn)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??L)(),xe(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Tr)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!rZ(a)||!oZ(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"}}},_0=async(e={})=>{let t=await aZ(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
752
|
+
`),0};var sZ="2025-06-18",iZ={name:"anyray",version:"1"},P0={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}},cZ=20,T0={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}},$0=py,lZ=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,$0)},dZ=e=>e==="paths"||e==="lines"||e==="full"?e:"full",D0={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-${$0}). 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}},L0={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}},uZ=8,pZ=3,N0={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}},fZ=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(`
|
|
752
753
|
`)},hZ=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
753
754
|
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,uZ).map(([a,s])=>{let i=s.slice(0,pZ).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
754
755
|
`)});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(`
|
|
755
|
-
`)},Pe=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),
|
|
756
|
+
`)},Pe=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),Jy=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),Ae=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
|
|
756
757
|
|
|
757
758
|
[anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
|
|
758
759
|
|
|
759
760
|
[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(`
|
|
760
761
|
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},mZ=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 Pe(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:sZ,capabilities:{tools:{}},serverInfo:iZ});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Pe(n??null,{});case"tools/list":{let a=[P0,T0];t.advertiseContextTools!==!1&&a.push(D0,L0);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(N0),Pe(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===P0.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Pe(n??null,Ae("handle is required",!0));let c=m=>{if(m!==void 0)return typeof m!="number"||!Number.isFinite(m)?null:Math.max(Math.round(m),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return Pe(n??null,Ae("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return Pe(n??null,Ae("grep must be non-empty",!0));if(s.grep.length>256)return Pe(n??null,Ae("grep is limited to 256 characters",!0));u=s.grep}let f=l!==void 0||d!==void 0||u!==void 0,p;try{p=await t.retrieve(i,f?{startLine:l,endLine:d,grep:u}:void 0)}catch(m){p={ok:!1,message:m instanceof Error?m.message:"retrieve failed"}}let h="this gateway does not support partial retrieval yet \u2014 call again without startLine/endLine/grep for the full content";if(!p.ok)return Pe(n??null,Ae(p.kind==="slice-unsupported"?h:p.message,!0));if(f&&(p.partial===void 0||typeof p.totalLines!="number"))return Pe(n??null,Ae(h,!0));if(p.partial===!0&&typeof p.totalLines=="number"){let m=p.grepMatches!==void 0?`[anyray: partial \u2014 ${p.grepMatches} matching line(s) in lines ${p.startLine}-${p.endLine} of ${p.totalLines}`+(p.grepTruncated?`, windows around the first ${cZ} matches shown \u2014 narrow the range or grep`:"")+` \xB7 retrieve ${i} again with startLine/endLine, another grep, or no params for full]`:`[anyray: partial \u2014 lines ${p.startLine}-${p.endLine} of ${p.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return Pe(n??null,Ae(`${m}
|
|
761
|
-
${p.content}`))}return Pe(n??null,Ae(p.content))}if(a.name===T0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Pe(n??null,Ae("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 Pe(n??null,l.ok?Ae(fZ(l.matches)):Ae(l.message,!0))}if(a.name===D0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Pe(n??null,Ae("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=lZ(s.maxResults),d=dZ(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 Pe(n??null,u.ok?Ae(
|
|
762
|
-
`)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let h;try{h=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let m;try{m=await mZ(h,n)}catch(w){console.error("anyray mcp: dispatch error",w instanceof Error?w.message:w),m=h?.id===void 0?null:
|
|
762
|
+
${p.content}`))}return Pe(n??null,Ae(p.content))}if(a.name===T0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Pe(n??null,Ae("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 Pe(n??null,l.ok?Ae(fZ(l.matches)):Ae(l.message,!0))}if(a.name===D0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Pe(n??null,Ae("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=lZ(s.maxResults),d=dZ(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 Pe(n??null,u.ok?Ae(Vx(i,u,d)):Ae(u.message??"search failed",!0))}if(a.name===N0.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 Pe(n??null,d.ok?Ae(ly(d)):Ae(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Pe(n??null,Ae("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 Pe(n??null,l.ok?Ae(hZ(c,l)):Ae(l.message??"history search failed",!0))}if(a.name===L0.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Pe(n??null,Ae("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 Pe(n??null,l.ok?Ae(ly(l)):Ae(l.message??"read failed",!0))}return Jy(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Jy(n??null,-32601,`method not found: ${o}`)}},yZ=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),Nd);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Qt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},gZ=(e,t=!0)=>({retrieve:async(n,r)=>_a(await e(),n,r),recall:async(n,r)=>$d(await e(),n,r),search:(n,r,o)=>ou(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>ru(n,r),historySearch:n=>Jx(n),historyOpen:n=>Xx(n),historyAvailable:async()=>await Ka()>0,advertiseContextTools:t,heartbeat:()=>{e().then(yZ).catch(()=>{})}}),M0=async(e="auto",t={})=>{let n=gZ(()=>at(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,Pr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=f=>{try{o.write(JSON.stringify(f)+`
|
|
763
|
+
`)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let h;try{h=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let m;try{m=await mZ(h,n)}catch(w){console.error("anyray mcp: dispatch error",w instanceof Error?w.message:w),m=h?.id===void 0?null:Jy(h.id,-32603,"internal error")}m&&c(m),i()};i();let d=setInterval(i,30*6e4);d.unref?.();let u="";try{for await(let f of r){u+=f.toString("utf-8");let p;for(;(p=u.indexOf(`
|
|
763
764
|
`))>=0;){let h=u.slice(0,p);u=u.slice(p+1),await l(h)}}u.trim()&&await l(u)}catch(f){console.error("anyray mcp: stdin error",f instanceof Error?f.message:f)}finally{clearInterval(d)}return 0};import{spawn as wZ}from"node:child_process";var bZ=e=>e==="jetbrains"||e==="windsurf"?e:void 0,kZ=async(e,t,n,r=1e4)=>{let o=await new Promise(a=>{let s="",i=!1,c=p=>{i||(i=!0,clearTimeout(l),t.off("data",d),t.off("error",u),t.off("end",f),a(p))},l=setTimeout(()=>c(void 0),r),d=p=>{s+=p.toString();let h=s.indexOf(`
|
|
764
765
|
`);h!==-1?c(s.slice(0,h)):s.length>65536&&c(void 0)},u=()=>c(void 0),f=()=>c(s.length>0?s:void 0);t.on("data",d),t.once("error",u),t.once("end",f)});if(o===void 0)return!1;try{let s=JSON.parse(o)?.id;return typeof s!="number"&&typeof s!="string"?!1:(n.write(`${JSON.stringify({jsonrpc:"2.0",id:s,error:{code:-32e3,message:e}})}
|
|
765
766
|
`),!0)}catch{return!1}},CZ={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},AZ=(e,t,n)=>{let r=new Set(CZ[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}},U0=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
766
|
-
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!
|
|
767
|
+
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!gd(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
767
768
|
`),1;await(n.refreshIfDue??nt)().catch(()=>{});let s=await(n.loadProfile??L)(),i=await(n.readBootstrap??Vt)().catch(()=>{});if(i){let y=await(n.ssoGate??Qn)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(y.exitCode===2&&y.stderr)return await kZ(y.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(y.stderr),1;s=await(n.loadProfile??L)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
|
|
768
769
|
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??$t)():void 0,d=ge({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=bZ(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",p=(n.hookBinaryIsDurable??le)(),h=Uv(d,t,{mcpServer:p?Ve("profile"):void 0})[f],m=n.spawn??wZ,w=h.command,g=h.args;if(o==="win32"){if(!h.args.every(y=>y==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(y)))return r.write(`Anyray ACP adapter arguments are invalid.
|
|
769
770
|
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",g=["/d","/s","/c",`"${h.command}" ${h.args.join(" ")}`]}return await new Promise(y=>{let b=AZ(e,a,h.env),A=m(w,g,{env:b,stdio:"inherit",windowsHide:!0});A.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
|
|
770
|
-
`),y(1)}),A.once("exit",(v,E)=>{y(typeof v=="number"?v:E?1:0)})})};import{createReadStream as vZ}from"node:fs";import{spawnSync as X0}from"node:child_process";import{createHash as SZ}from"node:crypto";import{access as q0,chmod as
|
|
771
|
+
`),y(1)}),A.once("exit",(v,E)=>{y(typeof v=="number"?v:E?1:0)})})};import{createReadStream as vZ}from"node:fs";import{spawnSync as X0}from"node:child_process";import{createHash as SZ}from"node:crypto";import{access as q0,chmod as zy,copyFile as EZ,lstat as xZ,mkdir as IZ,mkdtemp as z0,readFile as Su,rename as RZ,rm as Ur,stat as OZ,writeFile as _Z}from"node:fs/promises";import{constants as Q0}from"node:fs";import{platform as Ja,tmpdir as PZ}from"node:os";import{dirname as TZ,isAbsolute as DZ,join as Cu}from"node:path";import{z as Ue}from"zod";var LZ="fleetd-installer-v4.89.2",F0=`https://github.com/anyrayHQ/install/releases/download/${LZ}`,NZ=1e4,$Z=1e4,B0=31,MZ=1500,eR=20*1024,Xy=20,UZ="0.25",FZ="/var/tmp",Za="/Library/LaunchDaemons/com.fleetdm.orbit.plist",Au="/etc/default/orbit",sc="/opt/orbit/anyray-enroll-secret.txt",tR="/opt/orbit/secret-orbit-node-key.txt",BZ="/opt/orbit/bin/orbit/orbit",ic="C:\\Program Files\\Orbit",WZ=`${ic}\\bin\\orbit`,nR=`${ic}\\secret-orbit-node-key.txt`,ac=`${ic}\\secret.txt`,HZ=`${ic}\\fleet_url.txt`,rR=`${ic}\\anyray-managed.txt`,vu="Fleet osquery",Qy="C:\\Windows\\System32\\sc.exe",KZ="C:\\Windows\\System32\\whoami.exe",ku="C:\\Windows\\System32\\icacls.exe",GZ="C:\\Windows\\System32\\msiexec.exe",eg="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",W0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],jZ=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],VZ=`anyray-connect endpoint install
|
|
771
772
|
|
|
772
773
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
773
774
|
|
|
@@ -775,11 +776,11 @@ Supported on macOS, Linux and Windows.
|
|
|
775
776
|
|
|
776
777
|
The command uses the current seat's stored gateway key. Administrator access is
|
|
777
778
|
required: on macOS and Linux Connect asks through sudo once when /dev/tty is
|
|
778
|
-
available; on Windows, run it from a shell started as Administrator.`,
|
|
779
|
-
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",sc)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},
|
|
779
|
+
available; on Windows, run it from a shell started as Administrator.`,rg=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),oR=(e,t=Ja())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),aR=(e,t=Ja(),n=!1)=>(rg(e)||n)&&t!=="win32",ce=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},YZ=Ue.object({kind:Ue.enum(["pkg","deb","rpm","msi"]),path:Ue.string().min(1).refine(DZ),sha256:Ue.string().regex(/^[0-9a-f]{64}$/)}).strict(),ZZ=Ue.object({action:Ue.literal("restart"),os:Ue.enum(["darwin","linux","win32"])}).strict(),JZ=Ue.object({action:Ue.literal("configure"),os:Ue.enum(["darwin","linux","win32"]),fleetUrl:Ue.string().min(1).max(2048),enrollSecret:Ue.string().min(1).max(4096),package:YZ.optional()}).strict(),XZ=Ue.discriminatedUnion("action",[ZZ,JZ]),cc=(e,t)=>{let n=X0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},og=async e=>{try{return await q0(e,Q0.F_OK),!0}catch{return!1}},qZ=async e=>{try{let t=await OZ(e);return t.isFile()&&t.size>0}catch{return!1}},ag=(e,t)=>{for(let n=0;;){let r=e.indexOf("<key>",n);if(r<0)return null;let o=e.indexOf("</key>",r);if(o<0)return null;if(e.slice(r+5,o).trim()===t)return{start:r,end:o+6};n=o+6}},qy=(e,t)=>ag(e,t)!==null,H0=e=>e==="win32"?ac:sc,zZ=e=>e==="win32"?nR:tR,QZ=e=>qy(e,"ORBIT_FLEET_URL")&&qy(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${sc}</string>`)&&!qy(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),eJ=e=>{let t=(n,r)=>e.split(`
|
|
780
|
+
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",sc)&&!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()},sR=e=>{let t=e(Qy,["qc",vu,"8192"]);return t.status===0?t.stdout:""},ng=e=>{let t=e(eg,jZ(vu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},tJ=async e=>{try{return e==="win32"?tg(e,sR(cc)):tg(e,await Su(e==="darwin"?Za:Au,"utf8"))}catch{return}},nJ=async e=>{try{if(e==="win32")return await og(rR)&&tg(e,sR(cc))!==void 0;let n=await Su(e==="darwin"?Za:Au,"utf8");return e==="darwin"?QZ(n):eJ(n)}catch{return!1}},iR=async(e,t={})=>{let n=t.exists??og,r=t.command??cc,o,a="absent";if(e==="win32")a=ng(r),o=await n(WZ)&&a!=="absent";else{let l=e==="darwin"?await n(Za):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(BZ)&&l}let s=await(t.configured??nJ)(e),i=await(t.hasNodeKey??(()=>qZ(zZ(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}},rJ=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),cR=(e,t)=>{let n=ag(e,t);if(!n)return null;let r=n.start;for(;r>0&&(e[r-1]===" "||e[r-1]===" ");)r--;r>0&&e[r-1]===`
|
|
780
781
|
`&&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},oJ=(e,t)=>{let n=cR(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},K0=(e,t,n)=>{let r=`
|
|
781
782
|
<key>${t}</key>
|
|
782
|
-
<string>${rJ(n)}</string>`,o=cR(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=
|
|
783
|
+
<string>${rJ(n)}</string>`,o=cR(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=ag(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new ce("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)},aJ=(e,t,n=sc)=>{let r=oJ(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=K0(r,"ORBIT_FLEET_URL",t),K0(r,"ORBIT_ENROLL_SECRET_PATH",n)},sJ=(e,t,n=sc)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
|
|
783
784
|
`).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(`
|
|
784
785
|
`).trimEnd()}
|
|
785
786
|
|
|
@@ -789,13 +790,13 @@ available; on Windows, run it from a shell started as Administrator.`,ng=e=>!!(e
|
|
|
789
790
|
# file, never in this world-readable one.
|
|
790
791
|
ORBIT_FLEET_URL=${t}
|
|
791
792
|
ORBIT_ENROLL_SECRET_PATH=${n}
|
|
792
|
-
`},lR=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}},iJ=Ue.object({code:Ue.string().min(1).optional(),message:Ue.string().min(1).optional()}).passthrough(),G0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},cJ=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=iJ.safeParse(t);if(!r.success)return n;let o=G0(r.data.message??""),a=G0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},j0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??$Z),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":we},body:"{}",signal:r.signal})}catch{throw new ce("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new ce("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new ce(cJ(a.status,c))}let s;try{s=await a.json()}catch{throw new ce("The gateway returned malformed endpoint enrollment data.")}let i=Ue.object({fleetUrl:Ue.string().min(1).max(2048),enrollSecret:Ue.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!lR(i.data.fleetUrl))throw new ce("The gateway returned invalid endpoint enrollment data.");return i.data},lJ=async(e={})=>{let t=e.exists??
|
|
793
|
+
`},lR=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}},iJ=Ue.object({code:Ue.string().min(1).optional(),message:Ue.string().min(1).optional()}).passthrough(),G0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},cJ=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=iJ.safeParse(t);if(!r.success)return n;let o=G0(r.data.message??""),a=G0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},j0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??$Z),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":we},body:"{}",signal:r.signal})}catch{throw new ce("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new ce("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new ce(cJ(a.status,c))}let s;try{s=await a.json()}catch{throw new ce("The gateway returned malformed endpoint enrollment data.")}let i=Ue.object({fleetUrl:Ue.string().min(1).max(2048),enrollSecret:Ue.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!lR(i.data.fleetUrl))throw new ce("The gateway returned invalid endpoint enrollment data.");return i.data},lJ=async(e={})=>{let t=e.exists??og;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 ce("Linux endpoint installation requires either dpkg or rpm.")},dJ=async e=>e==="darwin"?"pkg":e==="win32"?"msi":lJ(),sg=e=>`fleetd.${e}`,uJ=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",pJ=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),NZ);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},fJ=async(e,t={})=>{let n=sg(e),r=t.fetchResponse??fetch,o;try{o=await pJ(`${F0}/SHA256SUMS`,r)}catch{throw new ce("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new ce(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=by(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await z0(Cu(PZ(),"anyray-endpoint-")),i=Cu(s,n);try{await zy(s,448),await(t.download??Ay)(`${F0}/${n}`,i,a)}catch(c){if(await Ur(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Zi&&c.status===404)return;throw new ce("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Ur(s,{recursive:!0,force:!0})}},hJ=async(e,t,n)=>{await IZ(TZ(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Ur(r,{force:!0});try{await _Z(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await RZ(r,e)}catch(o){throw await Ur(r,{force:!0}).catch(()=>{}),o}},V0=async e=>{let t=SZ("sha256");for await(let n of vZ(e))t.update(n);return t.digest("hex")},mJ=async(e,t={})=>{let n=await xZ(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new ce("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await V0(e.path)!==e.sha256)throw new ce("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await z0(Cu(FZ,"anyray-endpoint-root-")),o=Cu(r,sg(e.kind));try{if(await zy(r,448),await EZ(e.path,o),await zy(o,384),await V0(o)!==e.sha256)throw new ce("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Ur(r,{recursive:!0,force:!0})}}catch(a){throw await Ur(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ya=(e,t)=>{if(e.status!==0)throw new ce(t)},Y0="com.fleetdm.fleetd.config",yJ="com.fleetdm.fleetd.enroll.secret",gJ=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",tR],wJ=[HZ,nR],bJ=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(Y0))throw new ce(`This machine already receives its endpoint configuration from an MDM profile (${Y0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},Z0=async(e,t,n)=>{let r=n.removeFile??(o=>Ur(o,{force:!0}));for(let o of e==="win32"?wJ:gJ)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",yJ,"/Library/Keychains/System.keychain"])},kJ=e=>{e(ku,[ac,"/inheritance:r"]),e(ku,[ac,"/grant:r","*S-1-5-18:(F)"]),e(ku,[ac,"/grant:r","*S-1-5-32-544:(F)"]),e(ku,[ac,"/remove:g","*S-1-5-32-545"])},CJ=(e,t,n)=>{if(e.kind==="pkg"){Ya(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ya(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ya(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ya(t(GZ,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},AJ=(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",Za]),n.status===0)return;t("/bin/sleep",[UZ])}throw new ce(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(Qy,["stop",vu]);for(let n=0;n<Xy;n++){let r=ng(t);if(r==="Stopped"||r==="absent")break;t(eg,W0)}for(let n=0;n<Xy;n++){if(t(Qy,["start",vu]).status===0||ng(t)==="Running")return;t(eg,W0)}throw new ce("Orbit was configured, but the Windows service could not be started.")}Ya(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ya(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},vJ=e=>new Promise(t=>setTimeout(t,e)),dR=async(e,t={})=>{let n=t.command??cc,r=t.readText??(c=>Su(c,"utf8")),o=t.writeText??hJ,a=t.removeSecret??(()=>Ur(H0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&bJ(n),e.package&&!uJ(e.os,e.package.kind))throw new ce("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new ce("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await Z0(e.os,n,t),e.package){let d=await(t.preparePackage??mJ)(e.package);i=d.cleanup,CJ(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Za);await o(Za,aJ(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(Au);await o(Au,sJ(d,e.fleetUrl),420)}else await o(rR,`anyray
|
|
793
794
|
`,384);e.os!=="win32"&&await Z0(e.os,n,t),await o(H0(e.os),`${e.enrollSecret}
|
|
794
|
-
`,384),e.os==="win32"&&kJ(n),s=e.os!=="win32"}AJ(e.os,n);let c=t.checkIn??(async d=>{let u=await iR(d);return u.running&&u.checkedIn}),l=t.wait??vJ;for(let d=0;d<(t.attempts??B0);d++){if(await c(e.os))return;d+1<(t.attempts??B0)&&await l(MZ)}throw new ce("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(()=>{})}},SJ=async()=>{try{return await q0("/dev/tty",Q0.R_OK),!0}catch{return!1}},EJ=12288,
|
|
795
|
+
`,384),e.os==="win32"&&kJ(n),s=e.os!=="win32"}AJ(e.os,n);let c=t.checkIn??(async d=>{let u=await iR(d);return u.running&&u.checkedIn}),l=t.wait??vJ;for(let d=0;d<(t.attempts??B0);d++){if(await c(e.os))return;d+1<(t.attempts??B0)&&await l(MZ)}throw new ce("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(()=>{})}},SJ=async()=>{try{return await q0("/dev/tty",Q0.R_OK),!0}catch{return!1}},EJ=12288,xJ=e=>{let t=e(KZ,["/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>=EJ},IJ=async(e,t={})=>{if((t.os??Ja())==="win32")return(t.elevated??(()=>xJ(t.command??cc)))()?(await e(),"direct"):((t.print??k)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
795
796
|
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??SJ)()){if(await(t.reexec??(async()=>1))()!==0)throw new ce("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??k)(`Administrator access is required. Run:
|
|
796
797
|
sudo anyray-connect endpoint install`),"deferred"},RJ=async e=>{let t=`${JSON.stringify(e)}
|
|
797
|
-
`;if(Buffer.byteLength(t)>eR)throw new ce("The privileged endpoint plan is unexpectedly large.");let n=pn(["__anyray-endpoint-install"]);return X0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},OJ=async(e,t={})=>(t.withRoot??
|
|
798
|
-
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Ja()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await L()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},uR=async(e={},t={})=>{let n=t.os??Ja();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new ce("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??iR)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??J0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??tJ)(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??j0)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};M("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new ce("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??J0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new ce("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??j0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>dJ(r)))();if(i=await(t.stagePackage??fJ)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${
|
|
798
|
+
`;if(Buffer.byteLength(t)>eR)throw new ce("The privileged endpoint plan is unexpectedly large.");let n=pn(["__anyray-endpoint-install"]);return X0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},OJ=async(e,t={})=>(t.withRoot??IJ)(()=>(t.apply??dR)(e),{...t.root,reexec:()=>(t.sudo??RJ)(e)}),J0=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return L();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return L();let t;try{let s=(await Su("/etc/passwd","utf8")).split(`
|
|
799
|
+
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Ja()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await L()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},uR=async(e={},t={})=>{let n=t.os??Ja();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new ce("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??iR)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??J0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??tJ)(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??j0)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};M("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new ce("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??J0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new ce("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??j0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>dJ(r)))();if(i=await(t.stagePackage??fJ)(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??OJ)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},ig=e=>e instanceof ce?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",pR=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return k(VZ),0;if(e.length!==1||e[0]!=="install")return _("Usage: anyray-connect endpoint install"),1;try{let t=await uR();return t.message&&(t.outcome==="installed"?U(t.message):M(t.message)),0}catch(t){return _(ig(t)),1}},_J=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>eR)throw new ce("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new ce("The privileged endpoint plan is malformed.")}let r=XZ.safeParse(n);if(!r.success||r.data.os!==Ja()||r.data.action==="configure"&&!lR(r.data.fleetUrl))throw new ce("The privileged endpoint plan is invalid.");return r.data},fR=async e=>{if((process.getuid?.()??-1)!==0)return _("The privileged endpoint step must run as root."),1;if(e.length!==0)return _("The privileged endpoint step does not accept arguments."),1;try{return await dR(await _J()),0}catch(t){return _(ig(t)),1}},hR=async(e,t=uR)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?U(n.message):M(n.message)),n.outcome}catch(n){M(`Endpoint agent: ${ig(n)} Tool routing remains configured.`);return}};import{execSync as cg}from"node:child_process";import{hostname as PJ}from"node:os";var TJ=e=>{try{if(e==="darwin"){let t=cg("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=cg('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 cg("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Eu=(e={platform:process.platform,read:()=>TJ(process.platform),hostname:PJ})=>e.read().trim()||e.hostname().trim();var DJ=(e,t=Date.now())=>e.credentialProtocol==="stable-heartbeat-v1"||!Bd(e,void 0,t),mR=async(e,t={})=>{if(!await(t.fleetdPresent??Po)())return{retired:!1,reason:"no-fleetd",messages:[]};if(!DJ(e,t.now??Date.now()))return{retired:!1,reason:"seat-could-lapse",messages:[]};let r=[],o=await(t.uninstallScheduler??mr)();r.push(...o.messages);let a=await(t.uninstallProxy??en)();return r.push(...a.messages),{retired:!0,messages:r}};var yR=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();return t?t.toLowerCase():(e.platform??process.platform)==="darwin"?(e.readMacUuid??(()=>Eu()))().trim().toLowerCase():""};var gR=["reapply_config","remint","revert","revert_tool"],LJ=/^[a-z0-9][a-z0-9-]{0,31}$/;var NJ=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"||!gR.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&LJ.test(t.tool):t.tool===void 0},lg=e=>e?.name??"error",wR=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":gR.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!NJ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",lg(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",lg(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:",lg(i))}return a.kind};var $J=1e4,Xa=e=>e?.name??"Error",dg=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($J)})}catch(o){console.error(`anyray seat offboard report: ${Xa(o)}`)}},MJ=e=>e==="reverted"||e==="queued",bR=async(e={})=>{let t=e.loadProfile??L,n=e.clearDeviceTokenState??Vd,r=e.reportSeatOffboarded??dg,o=e.clearEnrollment??yc,a=e.recordManagedTools??rr,s=e.markSeatOffboarded??wc,i=e.adapterById??Kt,c=e.uninstallProxy??en,l=e.uninstallScheduler??mr,d=e.unitsPresent??Mi,u=e.saveProfile??oe,f=await t(),p=f.managedTools??[];await r(f).catch(()=>{}),await n().catch(()=>{});let h=!1,m=!1;try{h=await o()}catch(E){m=!0,console.error(`anyray offboard: clearing enrollment: ${Xa(E)}`)}let w=[],g=[],y=[];for(let E of p){let x=i(E);if(!x){y.push(E);continue}try{let C=await x.revert({dryRun:!1,fullRevert:!0});w.push({id:E,status:C.status}),MJ(C.status)?g.push(E):y.push(E)}catch(C){console.error(`anyray offboard: reverting ${E}: ${Xa(C)}`),y.push(E)}}let b=!0;try{await a(w,!0,!0)}catch(E){b=!1,console.error(`anyray offboard: recording managed tools: ${Xa(E)}`)}let A=y.length===0&&b,v=!1;if(A)try{await s(),v=!0}catch(E){console.error(`anyray offboard: stamping offboard: ${Xa(E)}`)}try{let E=await t();(E.fallbackPort||await d("daemon"))&&await c(E.fallbackPort),(E.refreshSchedulerEnabled||await d("scheduler"))&&await l(),await u({...await t(),keyRefreshEnabled:!1,fallbackPort:void 0,refreshSchedulerEnabled:!1})}catch(E){console.error(`anyray offboard: unit teardown: ${Xa(E)}`)}return{reverted:g,unresolved:y,enrollmentCleared:h,credentialHeld:m,recordPersisted:b,offboardMarked:v,ok:y.length===0&&!m&&b&&v}};var kR=e=>e?.name??"Error",CR=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??L,r=t.recordManagedTools??rr,o=t.adapterById??Kt,a=t.isLocked??xi,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}: ${kR(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${kR(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as SR}from"node:os";var ER=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
799
800
|
|
|
800
801
|
${j("Usage")}
|
|
801
802
|
npx anyray-connect [options]
|
|
@@ -832,7 +833,7 @@ ${j("What it does")}
|
|
|
832
833
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
833
834
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
834
835
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
835
|
-
per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
836
|
+
per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,xR=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
836
837
|
|
|
837
838
|
${j("Usage")}
|
|
838
839
|
npx anyray-connect <gateway-url> [options]
|
|
@@ -1028,19 +1029,19 @@ ${j("What it does")}
|
|
|
1028
1029
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1029
1030
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1030
1031
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1031
|
-
per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,FJ=e=>{let t=e?.trim();return t||
|
|
1032
|
-
${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?`}`,zJ=async(e,t={})=>{let n=t.requestQuit??(a=>
|
|
1033
|
-
${o} ${n} tool target(s)?`;return await(r.confirm??Fa)(a)?"proceed":"declined"},hX=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return l0(n)}if(e[0]==="__anyray-codex-hook")return d0();if(e[0]==="__anyray-prompt-hook")return u0();if(e[0]==="__anyray-shell-pretool")return m0();if(e[0]==="__anyray-shell-run")return h0(e.slice(1));if(e[0]==="__anyray-read-pretool")return v0();if(e[0]==="__anyray-sso-gate")return uE(e.slice(1));if(e[0]==="__anyray-sso-poll")return S0();if(e[0]==="__anyray-vscode-gate")return _0();if(e[0]==="__anyray-spawn-refresh")return await Pr(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return M0(n)}if(e[0]==="__anyray-acp-agent")return U0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return fR(e.slice(1));if(e[0]==="__anyray-refresh"){await Ay(),await nt({runAmbientSelfcheck:!0}),await Dm(),await sX(),await qS(),await zS();let n=await L().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await oe(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await Po().catch(()=>!1);if(await mR(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=yR(),i=n.enrolledCert;if(s&&i){let l=await We().catch(()=>{});l&&await lS(o,a,i,l,s).catch(()=>{})}await wR(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await nt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?CR(d):(await bR()).ok?"ok":"failed"}).catch(()=>{})}}return await Ji(),0}if(e[0]==="__anyray-fallback-proxy")return OE();if(e[0]==="__anyray-persistence")return PE(e.slice(1));if(e[0]==="__anyray-quit-watch")return ME(e.slice(1));if(e[0]===li)return bI(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return O0();try{let n=await Kg(e);if(n!==void 0)return n}catch(n){return _(`Could not persist anyray-connect for long-lived integrations: ${n instanceof Error?n.message:String(n)}`),1}if(pX(e)){let n=uX(await yx());n?.level==="warn"?D(n.message):n&&console.error(n.message)}if(e[0]==="managed")return ZE(e.slice(1));if(e[0]==="endpoint")return pR(e.slice(1));if(e[0]==="print-key")return zE(e.slice(1));if(e[0]==="models")return eI(e.slice(1));if(e[0]==="copilot-login")return tI(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=ay(n);return r?ug(r,!1):MI(n)}if(e[0]==="retrieve")return FI(e.slice(1));if(e[0]==="recall")return BI(e.slice(1));if(e[0]==="history")return zI(e.slice(1));if(e[0]==="migrate")return ex(e.slice(1));if(e[0]==="login")return I0(e.slice(1));if(e[0]==="update")return R0(e.slice(1));let t=e[0];if(t&&lX.has(t)){let n=e.slice(1),r;try{r=xR(n)}catch(o){return _(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?IR:ER),0):t==="status"?vx({gateway:r.gateway}):t==="doctor"?_x({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?Px({gateway:r.gateway}):t==="device-url"?nI():ug(n,!0)}return ug(e,!1)},_R=async e=>{try{return await hX(e)}catch(t){if(t instanceof kt)return console.error(S("Cancelled.")),130;throw t}},mX=async(e,t,n={})=>{let r=n.isInteractive??Yt,o;try{o=xR(e)}catch(O){return _(O.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?IR:ER),0;if(o.revert&&(o.sso||o.enroll||o.claim))return _("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(_("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):yI({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return _("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return _("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let O;try{O=new URL(o.upstream.trim())}catch{return _(`invalid --upstream URL: "${o.upstream}"`),1}if(O.protocol!=="http:"&&O.protocol!=="https:")return _(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let T=o.upstreamKey.trim();if(!T)return _("--upstream-key must not be empty."),1;a={url:Je(o.upstream),key:T}}let s=await L();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let O=await Ay();(O==="migrated"||O==="already-direct")&&(s=await L())}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream),o.retiredFallbackFlag&&D("--fallback/--no-fallback are retired and ignored: the local daemon no longer routes around the gateway to the provider. Seamless key refresh is on by default (--no-key-refresh opts out).");let i=!t&&Yt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??eX)(o,s),c=!0);let l;try{l=BJ(o.tools)}catch(O){return _(O.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&Vi(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,k("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,f=!1;if(o.enroll&&(!o.gateway||s.enrolledCert)){let O=iu(o.enroll);if(O)try{let T=await Yi("Resolving enrollment link\u2026",()=>sx(O)),H=!o.gateway;H&&(o.gateway=T.gatewayUrl),d=T.deploymentId,u=T.email,f=!0,H&&M(`Enrollment link${T.org?` for ${T.org}`:""}: gateway ${T.gatewayUrl}`),T.seatMode&&!o.subscription&&(o.subscription=!0,M("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(T){let H=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(H)M(`Could not resolve the gateway from the enrollment link \u2014 using ${H}.`);else return _(T instanceof Error?T.message:String(T)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)M("dry run: not enrolled (skipped redeeming the enrollment link).");else{let O=tE(o.claim);if(!O)return _("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let T=await Yi("Connecting this machine\u2026",()=>nE({cpOrigin:O.cpOrigin,claim:O.claim,gatewayUrl:o.gateway}));p={cert:T.cert,privateKeyPem:T.privateKeyPem},T.deploymentId&&(d=T.deploymentId),!o.gateway&&T.gatewayUrl&&(o.gateway=T.gatewayUrl),h=T.ssoLink}catch(T){return _(T instanceof Error?T.message:String(T)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)M("dry run: not enrolled via SSO (skipped minting a personal key).");else{let O=_t(o.sso);if(!O)return _(Vi(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 T=await Hd({cpOrigin:O.cpOrigin,tenantId:O.tenantId,gatewayUrl:o.gateway,log:fe=>M(fe),open:r()?Da:void 0}),H=await Yi("Waiting for SSO sign-in\u2026",()=>Kd(T,{gatewayUrl:o.gateway}));p={cert:H.cert,privateKeyPem:H.privateKeyPem},H.deploymentId&&(d=H.deploymentId),!o.gateway&&H.gatewayUrl&&(o.gateway=H.gatewayUrl)}catch(T){return _(T instanceof Error?T.message:String(T)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=un(o.gateway)}catch(O){return _(O.message),1}let g,y;m&&!o.revert&&M(`Gateway: ${w} ${S("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&hg(w)&&D(`${w} is plaintext http over a network \u2014 connections can be reset by firewalls/VPNs and traffic is unencrypted. Prefer an https:// gateway URL (front it with the TLS edge).`);let b=process.env.ANYRAY_CLIENT_KEY?.trim(),A=b||HJ(s),v,E,I,C,x,P,$=s.credentialProtocol==="stable-heartbeat-v1",Y=async O=>{await So();let T=cS(O.token),H=dS(s.enrolledCert,s.enrolledCertExpiry,O.deploymentId,Date.now(),T,s.enrolledTokenHash,O.expectedUser),fe=H?await We():void 0,Q=H&&fe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:fe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,Ze=Be=>uS({cpOrigin:O.cpOrigin,token:O.token,gatewayOrigin:w,email:O.email,team:O.team,machineId:O.machineId,deploymentId:O.deploymentId,reuse:Be?Q:void 0}),Fe=!!Q,te=await(async()=>{try{return await Ze(Fe)}catch(Be){if(Q&&Be instanceof Ot)return M("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),Fe=!1,await Ze(!1);throw Be}})();A=te.clientKey,o.user=Eu(o.user,te.user),o.team=Eu(o.team,te.team),v=te.cert,E=te.cert.payload.expiresAt,P=te.expiresAt,$=te.capabilities?.includes(xi)===!0,x=void 0,Fe||(I=te.privateKeyPem),Fe||(C=T),U(`Enrolled${te.user?` as ${te.user}`:""}${Fe?" (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)M("dry run: not enrolled (skipped minting a personal key).");else{let O=iu(o.enroll);if(!O){let T=ax(o.enroll);return _(T?`that is ${T.what}, not an enrollment link \u2014 re-run with ${T.flag} instead of --enroll.`:_t(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 T=o.machine?Su():void 0,H=u??FJ(o.user);if(!o.machine&&!o.user&&!u){let Q=iI();Q.distinct||(D(` Enrolling as "${Q.identity}" \u2014 this may not be unique to you.`),D(Q.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"),D(Q.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."),D(" Re-run with `--user you@company.com` (or set `git config --global"),D(" user.email`) so your usage is attributed to you."))}let fe=o.machine?`machine:${T}`:f?H:void 0;await Y({cpOrigin:O.cpOrigin,token:O.token,email:H,team:o.team,machineId:T,deploymentId:d,expectedUser:fe})}catch(T){return _(T instanceof Error?T.message:String(T)),T instanceof Ot&&M("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),1}}if(p){await So();try{let O=await dn(w,p.cert,p.privateKeyPem);A=O.key,o.user=Eu(o.user,O.user),o.team=Eu(o.team,O.team),v=p.cert,E=p.cert.payload.expiresAt,I=p.privateKeyPem,P=O.expiresAt,$=O.capabilities?.includes(xi)===!0;let T=o.sso?_t(o.sso):void 0;x=T?`${T.cpOrigin}/sso/${T.tenantId}`:h,U(`Enrolled${O.user?` as ${O.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(O){return _(O instanceof Error?O.message:String(O)),O instanceof Ot&&M("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}if(!o.revert){let O=o.yes;g=await lI(o.user,s.name,O),y=await dI(o.team,s.team,O)}if(!o.revert&&!o.dryRun){let O=kx(await bx(w,A),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(O.lane){let T=O.lane==="subscription";o.subscription=T,o.placeholder=!T;let H=T?"your own subscription seat":"the organization's provider account";O.overrodeFlag?M(`Your administrator assigns this machine to ${H}, so that is what was applied (it overrides the lane flag you passed).`):M(`Billing lane set by your administrator: ${H}.`)}}let Z;!o.revert&&!o.subscription&&!o.placeholder&&(Z=await $t(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?rt("BYO upstream key (passthrough)"):Z.anthropic?rt("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${Z.openai?rt("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),!Z.anthropic&&!Z.openai&&!Z.copilot&&Vr()&&(D(" No subscription sign-ins found on this host. Sign-ins do not cross the"),D(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),D(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),D(" and re-run, or everything below routes on the org key instead.")));let W=ge({origin:w,placeholderKey:o.key,clientKey:A,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:Z,user:g,team:y,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),z=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:z};if(!o.revert&&W.clientKey&&!Ie(W.clientKey))return _("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!W.clientKey){K("Enrollment required");let O="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(D(` ${O}`),M(" Dry run only \u2014 no placeholder configuration will be written."),await AR(l,"after-enrollment"),M(`
|
|
1032
|
+
per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,FJ=e=>{let t=e?.trim();return t||Zm()},xu=(e,t)=>t||e,IR=e=>{let t={subscription:!1,placeholder:!1,dryRun:!1,yes:!1,revert:!1,force:!1,skipVerify:!1,verbose:!1,help:!1,helpAll:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>e[++n];switch(r){case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":t.key=o();break;case"--enroll":t.enroll=o();break;case"--sso":t.sso=o();break;case"--claim":t.claim=o();break;case"--machine":t.machine=!0;break;case"--subscription":t.subscription=!0;break;case"--placeholder":case"--org":t.placeholder=!0;break;case"--upstream":t.upstream=o();break;case"--upstream-key":t.upstreamKey=o();break;case"--tools":t.tools=(o()??"").split(",").map(a=>a.trim()).filter(Boolean);break;case"--project":t.project=!0;break;case"--dry-run":t.dryRun=!0;break;case"--yes":case"-y":t.yes=!0;break;case"--force":t.force=!0;break;case"--skip-verify":t.skipVerify=!0;break;case"--fallback":case"--no-fallback":t.retiredFallbackFlag=!0;break;case"--no-key-refresh":t.noKeyRefresh=!0;break;case"--quit-apps":t.quitApps=!0;break;case"--no-quit-apps":t.noQuitApps=!0;break;case"--endpoint":t.endpoint=!0;break;case"--no-endpoint":t.noEndpoint=!0;break;case"--revert":t.revert=!0;break;case"--json":t.json=!0;break;case"--verify":t.verify=!0;break;case"--no-verify":t.noVerify=!0;break;case"--quick":t.quick=!0;break;case"--repair":t.repair=!0;break;case"--security-review":t.securityReview=!0;break;case"--verbose":t.verbose=!0;break;case"--help":case"-h":t.help=!0;break;case"--help-all":t.help=!0,t.helpAll=!0;break;case"--all":if(!e.includes("--help")&&!e.includes("-h"))throw new Error(`unknown option: ${r}`);t.helpAll=!0;break;default:if(!r.startsWith("-")&&t.gateway===void 0)t.gateway=r;else throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r} (gateway already set to ${t.gateway})`)}}return t},BJ=e=>!e||e.length===0?ie:e.map(t=>{let n=Kt(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${ie.map(r=>r.id).join(", ")}`);return n}),WJ=(e,t)=>{if(K("Gateway target"),k(` Origin: ${rt(e.origin)}`),e.byoUpstream)k(` Auth: BYO upstream key ${S(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&k(` Client key: personal gateway key (${Mt(e.clientKey)}) ${S("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=X(e,"anthropic")?rt("your subscription"):"org key",r=X(e,"openai")?rt("your subscription"):"org key";k(` Auth: auto ${S("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&k(` Client key: personal gateway key (${Mt(e.clientKey)})`)}else e.authMode==="subscription"?(k(` Auth: subscription pass-through ${S("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&k(` Client key: personal gateway key (${Mt(e.clientKey)}) ${S("rides x-anyray-api-key")}`)):e.clientKey?k(` Auth: personal gateway key (${Mt(e.clientKey)}) ${S("(replaces the placeholder)")}`):k(` Enrollment: ${S("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&k(` Cursor: ${rt("native Team subscription")} ${S("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(X(e,"anthropic")?(k(` Claude Desktop: ${rt("subscription-backed Gateway lane")} ${S("(verified macOS builds; Windows fails closed)")}`),k(` ${S("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(k(` Claude Desktop: ${rt("third-party API lane")} ${S("(API-billed; switches the active local inference profile)")}`),k(` ${S("The first-party Claude subscription remains untouched.")}`))),k(` Attribution: ${de(e.metadata)??S("(none \u2014 pass --user)")}`)},AR=async(e,t)=>{K("Selected tools");for(let n of e){let r=await n.detect();r.installed?k(` ${n.title} ${S(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):M(` ${n.title} ${S(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},HJ=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!xe(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},KJ={loadDevKey:We,saveDevKey:mc,clearDevKey:is,saveProfile:oe},GJ=async(e,t,n,r=KJ,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}},jJ=async(e,t,n,r,o)=>{n.dryRun||await gc();let a=0,s=[],i=[],c=[],l=[],d=[];for(let u of e){if(!(await u.detect()).installed&&!r){d.push(u.title);continue}K(`${u.title} ${S(`(${u.id})`)}`);try{let p=r?await u.revert(n):await u.apply(t,{...n,explicit:o?.has(u.id)===!0,reportsToUser:!0});for(let h of p.messages)k(` ${h}`);a+=p.changedFiles?.length??0,l.push({id:u.id,status:p.status}),p.status==="configured"||p.status==="reverted"?U(` ${p.status}`):p.status==="manual"?(s.push(u.title),p.manualAudience==="admin"?(i.push(u.title),c.push(u.id),D(" blocked by machine policy \u2014 your IT team owns this one")):D(" manual step required (see above)")):p.status==="held"?M(" left on its own plan (no change)"):M(` ${p.status}`)}catch(p){l.push({id:u.id,status:"failed"}),_(` failed: ${p instanceof Error?p.message:String(p)}`)}}if(d.length>0&&M(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await Cc().catch(()=>[]);u.length&&M(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},VJ=(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},YJ=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>RR(o)&&!r.has(o.id))},ZJ=async e=>{let t=Nx(e,process.platform,ee());if(t){await pe(t.path,t.content);for(let n of $x(t,process.platform))k(` ${n}`)}},JJ=async(e,t,n=SR())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!_b(i,n)||!Ob(i,n))continue;let c=Ib(i,n);if(!o.has(c)){try{if(!(await a.detect()).installed||!s.isRunning()||await a.pointsAt?.(t)===!0)continue}catch{continue}o.add(c),r.push({id:a.id,title:Rb(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},XJ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,qJ=e=>`
|
|
1033
|
+
${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?`}`,zJ=async(e,t={})=>{let n=t.requestQuit??(a=>Tb(a)),r=t.waitFor??(a=>Db(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),U(` Closed ${a.title}.`);continue}D(` ${a.title} is still open \u2014 leaving it alone.`),M(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},QJ=(e,t={})=>{let n=t.relaunch??(o=>Lb(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),U(` Reopened ${o.title}.`)):D(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},RR=e=>e.changesBilling===!0||e.changesOrgManagement===!0,OR=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,ug=e=>!RR(e),eX=async(e,t,n={})=>{let r=n.hasEnrollment??Fu,o=n.canMultiSelect??cI,a=n.multiSelect??lI,s=n.prompt??Ba,i=n.registry??ie;if(k(j("Anyray connect \u2014 guided setup")),k(S("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())k("Stored enrollment will be reused. Run with --revert to clear it.");else if(!e.enroll&&!e.sso&&!e.gateway){K("How do you want to connect?");let c;for(let l=0;l<3&&!c;l++){if(o()){let d=await a({title:"Choose a connection method",single:!0,items:[{value:"enroll",label:"Paste an enrollment link",selected:!0},{value:"sso",label:"Sign in with SSO"},{value:"gateway",label:"I already have a gateway URL"}]});if(d.kind==="cancelled")throw new kt;c=d.values[0]}else{k(" 1. Paste an enrollment link"),k(" 2. Sign in with SSO"),k(" 3. I already have a gateway URL");let d=await s("? Connection method (1-3)","1");c=d==="1"?"enroll":d==="2"?"sso":d==="3"?"gateway":void 0}c||D("Choose one of the three connection methods.")}if(!c)throw new kt;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&Vi(d)&&cu(d)){e.enroll=d;break}D("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&&_t(d)){e.sso=d;break}D("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&&Vi(d)){e.enroll=d,k("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=un(d);break}catch{D("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new kt}if(!e.tools||e.tools.length===0){K("Tools detected");let c=[],l=[];for(let u of i){if(!(await u.detect()).installed){l.push(u);continue}c.push(u)}let d=c.filter(u=>ug(u)).map(u=>u.id);if(c.length>0){for(let u=0;u<3&&!e.tools;u++){let f;if(o()){let p=await a({title:"Tools to configure",items:c.map(h=>({value:h.id,label:`${h.title} (${h.id})`,hint:OR(h),selected:ug(h),requiresExplicitChoice:!ug(h)}))});if(p.kind==="cancelled")throw new kt;f=p.values}else{f=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(w=>w.trim()).filter(Boolean);let h=new Set(c.map(w=>w.id)),m=f.filter(w=>!h.has(w));if(m.length>0){D(`Unknown or unavailable tool id${m.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(f.length===0){D("Choose at least one installed tool.");continue}e.tools=f}if(!e.tools)throw new kt}l.length>0&&M(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},tX=async(e,t)=>{K("Verifying the connection");let n=await Yi("Checking the gateway\u2026",()=>qi(e,{tools:t}));n.kind==="ok"?U(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?D(` ${n.detail}`):_(` ${n.detail}`);for(let r of n.remedy)k(S(` ${r}`))},nX=5e3,rX=500,vR=3,oX=600*1e3,aX=async()=>{try{let e=await UJ(await Mo());return Date.now()-e.mtimeMs}catch{return Number.POSITIVE_INFINITY}},sX=async(e={})=>{try{let t=await(e.load??L)();if(t.keyRefreshEnabled!==!0){if((e.draining??up)()||!await(e.unitExists??Sw)()||await(e.profileAgeMs??aX)()<oX)return;await(e.uninstall??en)(t.fallbackPort??ke);return}if(!t.gateway||t.persistenceOwner==="tray"&&await(e.checkTray??xo)(t)==="healthy")return;let n=t.fallbackPort??ke,r=e.probe??be,o=e.probeGapMs??rX;for(let s=0;s<vR;s++){if(await r(n,s===0?void 0:nX)!==null)return;s<vR-1&&o>0&&await new Promise(c=>setTimeout(c,o))}if((e.draining??up)())return;let a=await(e.install??Nt)({port:n,remoteOrigin:new URL(t.gateway).origin});if(!a.ok)for(let s of a.messages)console.error(s)}catch{}},iX=async(e,t,n={})=>{let r=n.install??Nt,o=n.probe??be,a=n.pollDelayMs??300;K("Seamless key refresh");let s=n.trayManaged?{ok:!0,messages:["Launch-at-login is managed by the Anyray Connect app \u2014 not re-registering the login service."]}:await r({port:t,remoteOrigin:e.origin});for(let l of s.messages)k(` ${l}`);let i=s.ok?10:1,c=null;for(let l=0;l<i&&!c;l++)c=await o(t),!c&&l<i-1&&await new Promise(d=>setTimeout(d,a));return c?(U(` Running on 127.0.0.1:${t} \u2192 ${e.origin} \u2014 your key refreshes automatically, no restart needed.`),_n(e,t)):(D(" Key-refresh proxy did not come up \u2014 pointing tools directly at the gateway for now."),k(S(s.ok?" It will retry on the next run; check the service logs if it persists.":At(gt())?" In a container the key refreshes via Claude Code's helper and on each `anyray-connect` run instead.":" Your key still refreshes on a schedule \u2014 no daemon needed here.")),e)},cX=async(e,t={})=>{if(e.dryRun)return;let n=t.install??hr,r=t.uninstall??mr;if(e.want&&e.trayManaged){e.announcePrimary&&(K("Automatic key refresh"),U(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."));return}if(e.want){let o=await n();if(e.announcePrimary){K("Automatic key refresh");for(let a of o.messages)k(` ${a}`);o.ok&&U(" Your gateway key now re-mints every ~30 min \u2014 no tool will 401 on a stale key mid-session.")}o.ok||await oe({...await L(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){K("Automatic key refresh");let o=await r();for(let a of o.messages)k(` ${a}`);await oe({...await L(),refreshSchedulerEnabled:!1}),U(" Removed the automatic key-refresh schedule.")}},lX=new Set(["login","wizard","status","doctor","sync","device-url"]),dX=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),uX=e=>{if(e.outcome==="migrated"&&e.managedPath)return{level:"info",message:`Installed managed anyray-connect at ${e.managedPath}.`};if(e.outcome==="platform-unsupported")return{level:"warn",message:"Self-update is unavailable on this platform; keeping the durable npm runtime for persistent integrations."};if(e.outcome==="migration-deferred")return{level:"warn",message:`Managed install deferred because the published binary (${e.latest}) is older than this npm runtime (${e.current}).`};if(!(e.outcome==="current"||e.outcome==="unmanaged"||e.outcome==="updated"||e.outcome==="disabled"||e.outcome==="container"))return{level:"warn",message:"Could not install the managed anyray-connect binary; continuing with the current runtime \u2014 it migrates automatically on a later refresh."}},pX=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=sy(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]||!dX.has(e[0])},pg=async(e,t)=>{try{return await mX(e,t)}catch(n){if(n instanceof kt)return console.error(S("Cancelled \u2014 nothing was written.")),130;throw n}},fX=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??Yt)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
|
|
1034
|
+
${o} ${n} tool target(s)?`;return await(r.confirm??Fa)(a)?"proceed":"declined"},hX=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return l0(n)}if(e[0]==="__anyray-codex-hook")return d0();if(e[0]==="__anyray-prompt-hook")return u0();if(e[0]==="__anyray-shell-pretool")return m0();if(e[0]==="__anyray-shell-run")return h0(e.slice(1));if(e[0]==="__anyray-read-pretool")return v0();if(e[0]==="__anyray-sso-gate")return uE(e.slice(1));if(e[0]==="__anyray-sso-poll")return S0();if(e[0]==="__anyray-vscode-gate")return _0();if(e[0]==="__anyray-spawn-refresh")return await Pr(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return M0(n)}if(e[0]==="__anyray-acp-agent")return U0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return fR(e.slice(1));if(e[0]==="__anyray-refresh"){await vy(),await nt({runAmbientSelfcheck:!0}),await Lm(),await sX(),await qS(),await zS();let n=await L().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await oe(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await Po().catch(()=>!1);if(await mR(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=yR(),i=n.enrolledCert;if(s&&i){let l=await We().catch(()=>{});l&&await lS(o,a,i,l,s).catch(()=>{})}await wR(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await nt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?CR(d):(await bR()).ok?"ok":"failed"}).catch(()=>{})}}return await Ji(),0}if(e[0]==="__anyray-fallback-proxy")return OE();if(e[0]==="__anyray-persistence")return PE(e.slice(1));if(e[0]==="__anyray-quit-watch")return ME(e.slice(1));if(e[0]===li)return bx(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return O0();try{let n=await Gg(e);if(n!==void 0)return n}catch(n){return _(`Could not persist anyray-connect for long-lived integrations: ${n instanceof Error?n.message:String(n)}`),1}if(pX(e)){let n=uX(await yI());n?.level==="warn"?D(n.message):n&&console.error(n.message)}if(e[0]==="managed")return ZE(e.slice(1));if(e[0]==="endpoint")return pR(e.slice(1));if(e[0]==="print-key")return zE(e.slice(1));if(e[0]==="models")return ex(e.slice(1));if(e[0]==="copilot-login")return tx(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=sy(n);return r?pg(r,!1):Mx(n)}if(e[0]==="retrieve")return Fx(e.slice(1));if(e[0]==="recall")return Bx(e.slice(1));if(e[0]==="history")return zx(e.slice(1));if(e[0]==="migrate")return eI(e.slice(1));if(e[0]==="login")return x0(e.slice(1));if(e[0]==="update")return R0(e.slice(1));let t=e[0];if(t&&lX.has(t)){let n=e.slice(1),r;try{r=IR(n)}catch(o){return _(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?xR:ER),0):t==="status"?vI({gateway:r.gateway}):t==="doctor"?_I({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?PI({gateway:r.gateway}):t==="device-url"?nx():pg(n,!0)}return pg(e,!1)},_R=async e=>{try{return await hX(e)}catch(t){if(t instanceof kt)return console.error(S("Cancelled.")),130;throw t}},mX=async(e,t,n={})=>{let r=n.isInteractive??Yt,o;try{o=IR(e)}catch(O){return _(O.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?xR:ER),0;if(o.revert&&(o.sso||o.enroll||o.claim))return _("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(_("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):yx({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return _("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return _("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let O;try{O=new URL(o.upstream.trim())}catch{return _(`invalid --upstream URL: "${o.upstream}"`),1}if(O.protocol!=="http:"&&O.protocol!=="https:")return _(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let T=o.upstreamKey.trim();if(!T)return _("--upstream-key must not be empty."),1;a={url:Je(o.upstream),key:T}}let s=await L();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let O=await vy();(O==="migrated"||O==="already-direct")&&(s=await L())}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream),o.retiredFallbackFlag&&D("--fallback/--no-fallback are retired and ignored: the local daemon no longer routes around the gateway to the provider. Seamless key refresh is on by default (--no-key-refresh opts out).");let i=!t&&Yt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??eX)(o,s),c=!0);let l;try{l=BJ(o.tools)}catch(O){return _(O.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&Vi(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,k("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,f=!1;if(o.enroll&&(!o.gateway||s.enrolledCert)){let O=cu(o.enroll);if(O)try{let T=await Yi("Resolving enrollment link\u2026",()=>sI(O)),H=!o.gateway;H&&(o.gateway=T.gatewayUrl),d=T.deploymentId,u=T.email,f=!0,H&&M(`Enrollment link${T.org?` for ${T.org}`:""}: gateway ${T.gatewayUrl}`),T.seatMode&&!o.subscription&&(o.subscription=!0,M("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(T){let H=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(H)M(`Could not resolve the gateway from the enrollment link \u2014 using ${H}.`);else return _(T instanceof Error?T.message:String(T)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)M("dry run: not enrolled (skipped redeeming the enrollment link).");else{let O=tE(o.claim);if(!O)return _("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let T=await Yi("Connecting this machine\u2026",()=>nE({cpOrigin:O.cpOrigin,claim:O.claim,gatewayUrl:o.gateway}));p={cert:T.cert,privateKeyPem:T.privateKeyPem},T.deploymentId&&(d=T.deploymentId),!o.gateway&&T.gatewayUrl&&(o.gateway=T.gatewayUrl),h=T.ssoLink}catch(T){return _(T instanceof Error?T.message:String(T)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)M("dry run: not enrolled via SSO (skipped minting a personal key).");else{let O=_t(o.sso);if(!O)return _(Vi(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 T=await Kd({cpOrigin:O.cpOrigin,tenantId:O.tenantId,gatewayUrl:o.gateway,log:fe=>M(fe),open:r()?Da:void 0}),H=await Yi("Waiting for SSO sign-in\u2026",()=>Gd(T,{gatewayUrl:o.gateway}));p={cert:H.cert,privateKeyPem:H.privateKeyPem},H.deploymentId&&(d=H.deploymentId),!o.gateway&&H.gatewayUrl&&(o.gateway=H.gatewayUrl)}catch(T){return _(T instanceof Error?T.message:String(T)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=un(o.gateway)}catch(O){return _(O.message),1}let g,y;m&&!o.revert&&M(`Gateway: ${w} ${S("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&mg(w)&&D(`${w} is plaintext http over a network \u2014 connections can be reset by firewalls/VPNs and traffic is unencrypted. Prefer an https:// gateway URL (front it with the TLS edge).`);let b=process.env.ANYRAY_CLIENT_KEY?.trim(),A=b||HJ(s),v,E,x,C,I,P,$=s.credentialProtocol==="stable-heartbeat-v1",Y=async O=>{await So();let T=cS(O.token),H=dS(s.enrolledCert,s.enrolledCertExpiry,O.deploymentId,Date.now(),T,s.enrolledTokenHash,O.expectedUser),fe=H?await We():void 0,Q=H&&fe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:fe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,Ze=Be=>uS({cpOrigin:O.cpOrigin,token:O.token,gatewayOrigin:w,email:O.email,team:O.team,machineId:O.machineId,deploymentId:O.deploymentId,reuse:Be?Q:void 0}),Fe=!!Q,te=await(async()=>{try{return await Ze(Fe)}catch(Be){if(Q&&Be instanceof Ot)return M("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),Fe=!1,await Ze(!1);throw Be}})();A=te.clientKey,o.user=xu(o.user,te.user),o.team=xu(o.team,te.team),v=te.cert,E=te.cert.payload.expiresAt,P=te.expiresAt,$=te.capabilities?.includes(Ii)===!0,I=void 0,Fe||(x=te.privateKeyPem),Fe||(C=T),U(`Enrolled${te.user?` as ${te.user}`:""}${Fe?" (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)M("dry run: not enrolled (skipped minting a personal key).");else{let O=cu(o.enroll);if(!O){let T=aI(o.enroll);return _(T?`that is ${T.what}, not an enrollment link \u2014 re-run with ${T.flag} instead of --enroll.`:_t(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 T=o.machine?Eu():void 0,H=u??FJ(o.user);if(!o.machine&&!o.user&&!u){let Q=ix();Q.distinct||(D(` Enrolling as "${Q.identity}" \u2014 this may not be unique to you.`),D(Q.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"),D(Q.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."),D(" Re-run with `--user you@company.com` (or set `git config --global"),D(" user.email`) so your usage is attributed to you."))}let fe=o.machine?`machine:${T}`:f?H:void 0;await Y({cpOrigin:O.cpOrigin,token:O.token,email:H,team:o.team,machineId:T,deploymentId:d,expectedUser:fe})}catch(T){return _(T instanceof Error?T.message:String(T)),T instanceof Ot&&M("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),1}}if(p){await So();try{let O=await dn(w,p.cert,p.privateKeyPem);A=O.key,o.user=xu(o.user,O.user),o.team=xu(o.team,O.team),v=p.cert,E=p.cert.payload.expiresAt,x=p.privateKeyPem,P=O.expiresAt,$=O.capabilities?.includes(Ii)===!0;let T=o.sso?_t(o.sso):void 0;I=T?`${T.cpOrigin}/sso/${T.tenantId}`:h,U(`Enrolled${O.user?` as ${O.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(O){return _(O instanceof Error?O.message:String(O)),O instanceof Ot&&M("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}if(!o.revert){let O=o.yes;g=await lx(o.user,s.name,O),y=await dx(o.team,s.team,O)}if(!o.revert&&!o.dryRun){let O=kI(await bI(w,A),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(O.lane){let T=O.lane==="subscription";o.subscription=T,o.placeholder=!T;let H=T?"your own subscription seat":"the organization's provider account";O.overrodeFlag?M(`Your administrator assigns this machine to ${H}, so that is what was applied (it overrides the lane flag you passed).`):M(`Billing lane set by your administrator: ${H}.`)}}let Z;!o.revert&&!o.subscription&&!o.placeholder&&(Z=await $t(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?rt("BYO upstream key (passthrough)"):Z.anthropic?rt("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${Z.openai?rt("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),!Z.anthropic&&!Z.openai&&!Z.copilot&&Vr()&&(D(" No subscription sign-ins found on this host. Sign-ins do not cross the"),D(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),D(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),D(" and re-run, or everything below routes on the org key instead.")));let W=ge({origin:w,placeholderKey:o.key,clientKey:A,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:Z,user:g,team:y,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),z=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:z};if(!o.revert&&W.clientKey&&!xe(W.clientKey))return _("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!W.clientKey){K("Enrollment required");let O="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(D(` ${O}`),M(" Dry run only \u2014 no placeholder configuration will be written."),await AR(l,"after-enrollment"),M(`
|
|
1034
1035
|
Dry run complete \u2014 no files were written.`),0):(_(` ${O}`),1)}o.revert||WJ(W,l),c&&!o.revert&&await AR(l,"plan"),o.dryRun&&M(`
|
|
1035
1036
|
Dry run \u2014 no files will be written.`);let Te=await fX(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(Te==="non-interactive")return _(`
|
|
1036
|
-
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(Te==="declined")return M(c?"Nothing was written. Re-run `npx anyray-connect wizard` when you're ready.":"Aborted. Nothing changed."),0;if(!o.dryRun&&!o.revert&&!o.force){let O=await
|
|
1037
|
+
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(Te==="declined")return M(c?"Nothing was written. Re-run `npx anyray-connect wizard` when you're ready.":"Aborted. Nothing changed."),0;if(!o.dryRun&&!o.revert&&!o.force){let O=await iu(W.origin);if(!O.reachable)return _(`
|
|
1037
1038
|
Gateway ${W.origin} is not reachable (${O.detail}).`),k(S(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1038
1039
|
that would break them until you re-run with --revert.`)),k(`
|
|
1039
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1;U(`Gateway reachable (${O.detail}).`)}let re=o.revert?[]:await JJ(l,W.origin),Ke=[],De=()=>{Ke.length!==0&&(K("Reopening"),QJ(Ke),Ke=[])};if(re.length>0){let O=re.map(H=>H.title),T=O.length===1?"it":"them";if(K("Open apps"),XJ(o,Yt()))o.quitApps===!0||await Fa(qJ(O))?Ke=await zJ(re):M(` Leaving ${T} open \u2014 restart when convenient.`);else{let H=o.noQuitApps===!0?"":" (or pass --quit-apps)";M(o.dryRun?` Would offer to quit ${O.join(", ")} \u2014 dry run, nothing was closed.`:` ${O.join(", ")} ${O.length===1?"is":"are"} open; restart ${T} to pick this up${H}.`)}}try{if(!o.dryRun)try{await Ct()}catch{return _("Could not prepare the owner-only Anyray state directory."),1}let O=l.some(ye=>ye.id==="claude-code")&&X(W,"anthropic")||l.some(ye=>ye.id==="codex")&&X(W,"openai"),T=
|
|
1040
|
-
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let On=l,qa=YJ(On,o,s.managedTools);if(qa.length>0){K("Not configured \u2014 needs your say-so");for(let Ee of qa)D(` ${Ee.id}: ${OR(Ee)??"changes where inference is billed"}.`),k(` Configure it deliberately with \`npx anyray-connect --tools ${Ee.id}\`.`);let ye=new Set(qa.map(Ee=>Ee.id));On=On.filter(Ee=>!ye.has(Ee.id))}if(o.revert&&!z){let ye=l.filter(Ee=>
|
|
1041
|
-
Remove them from the repo (then commit):`),k(S(" anyray-connect --project --revert")));let Ee=[W,...s.fallbackPort?[_n(W,s.fallbackPort)]:[]],dc=
|
|
1040
|
+
Start the gateway and try again, or pass --force to configure anyway.`),1;U(`Gateway reachable (${O.detail}).`)}let re=o.revert?[]:await JJ(l,W.origin),Ke=[],De=()=>{Ke.length!==0&&(K("Reopening"),QJ(Ke),Ke=[])};if(re.length>0){let O=re.map(H=>H.title),T=O.length===1?"it":"them";if(K("Open apps"),XJ(o,Yt()))o.quitApps===!0||await Fa(qJ(O))?Ke=await zJ(re):M(` Leaving ${T} open \u2014 restart when convenient.`);else{let H=o.noQuitApps===!0?"":" (or pass --quit-apps)";M(o.dryRun?` Would offer to quit ${O.join(", ")} \u2014 dry run, nothing was closed.`:` ${O.join(", ")} ${O.length===1?"is":"are"} open; restart ${T} to pick this up${H}.`)}}try{if(!o.dryRun)try{await Ct()}catch{return _("Could not prepare the owner-only Anyray state directory."),1}let O=l.some(ye=>ye.id==="claude-code")&&X(W,"anthropic")||l.some(ye=>ye.id==="codex")&&X(W,"openai"),T=Bd(s,P),H=s.anyrayFleetManaged===!0&&await Po().catch(()=>!1),fe=aR(o,SR(),H),Q=!o.revert&&o.noKeyRefresh!==!0&&O&&T&&!$&&!fe,Fe=!o.revert&&(o.tools?.length??0)>0&&o.noKeyRefresh!==!0&&!!s.keyRefreshEnabled,te=!!(b&&W.clientKey===b&&!v),Be=!te&&!!(v??s.enrolledCert),Le=l.some(ye=>ZS.has(ye.id)),Xt=!o.revert&&o.noKeyRefresh!==!0&&Be&&(T||!Le),V=o.dryRun?await xo(s):await Lm(),Ne=V==="healthy";V==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath);let nr=W,ht=Q||Fe,Do=ht?s.fallbackPort:void 0;if(Q&&!o.dryRun&&(Do=s.fallbackPort??await Lc()),!o.revert&&!o.dryRun){let ye={...s,gateway:W.origin,name:g,team:y,clientKey:W.clientKey??s.clientKey,enrolledCert:te?void 0:v??s.enrolledCert,enrolledCertExpiry:te?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:te?void 0:C??s.enrolledTokenHash,ssoLink:te?void 0:p?I:v?void 0:s.ssoLink,clientKeyExpiresAt:te?void 0:P??(W.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:W.authMode,byoUpstream:W.byoUpstream,credentialProtocol:te?void 0:ht?"rotating-proxy-v1":$?"stable-heartbeat-v1":s.credentialProtocol,directMigration:te?void 0:ht?"pending":$?"complete":s.directMigration,keyRefreshEnabled:ht,refreshSchedulerEnabled:Xt,fallbackPort:Do};try{await GJ(s,ye,x,void 0,te)}catch{return _("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}P&&!te&&await Ta({expiresAt:P})}if(Q&&!o.dryRun&&(nr=await iX(W,Do,{trayManaged:Ne})),z)if(o.dryRun)await Fu()&&(K("Enrollment"),k(" would remove the stored gateway credential"));else{await dg(s),await Vd().catch(()=>{});try{await yc()&&(K("Enrollment"),U(" Removed the stored gateway credential."),M(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(ye){K("Enrollment"),D(" Could not remove the stored gateway credential."),D(` Delete ${ee()} by hand, or the key-refresh hook may restore your tool config.`)}}else o.revert&&!o.dryRun&&(k(`
|
|
1041
|
+
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let On=l,qa=YJ(On,o,s.managedTools);if(qa.length>0){K("Not configured \u2014 needs your say-so");for(let Ee of qa)D(` ${Ee.id}: ${OR(Ee)??"changes where inference is billed"}.`),k(` Configure it deliberately with \`npx anyray-connect --tools ${Ee.id}\`.`);let ye=new Set(qa.map(Ee=>Ee.id));On=On.filter(Ee=>!ye.has(Ee.id))}if(o.revert&&!z){let ye=l.filter(Ee=>xi(s,Ee.id));if(ye.length>0){K("Fleet policy");for(let Ee of ye)D(` ${Ee.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);On=l.filter(Ee=>!xi(s,Ee.id))}}let{changes:lc,manual:za,manualAdminOnly:Qa,manualAdminOnlyIds:es,results:ts}=await jJ(On,nr,me,o.revert,new Set(o.tools??[])),ns;if(rg(o)){K("Endpoint agent");try{ns=await(n.installEndpointAfterEnrollment??hR)({gateway:w,clientKey:W.clientKey})}catch{M("Endpoint agent setup did not complete. Tool routing remains configured.")}}let Lo=fe&&oR(ns),fg=Xt&&!Lo;if(fe&&!Lo&&Xt&&!o.dryRun&&M(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),Lo&&!o.dryRun&&await oe({...await L(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await rr(ts,o.revert,z).catch(()=>{}),z&&await wc().catch(()=>{})),!ht&&!o.dryRun&&(ot(s)||s.fallbackPort||await Mi("daemon"))){K("Local loopback proxy");let ye=await en(s.fallbackPort);for(let Ee of ye.messages)k(` ${Ee}`);await oe({...await L(),keyRefreshEnabled:!1,fallbackPort:void 0}),U(" Removed the local loopback proxy.")}if(await cX({want:fg,announcePrimary:!Q,scopedRevert:!!o.revert&&!z,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!fg&&await Mi("scheduler"),trayManaged:Ne}),!o.revert&&!o.dryRun&&!te){let ye=x??await We();ye&&await Sm(await L(),ye).catch(()=>{})}if(De(),K("Summary"),o.dryRun)M("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){U(`Reverted (${lc} file(s) touched).`),M("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let ye=await mx();ye.length>0&&(K("This repo carries its own Anyray routing"),D(` Committed here: ${ye.join(", ")}`),D(" Those are tracked files, so they route every checkout of this"),D(" repo \u2014 this machine included, and your teammates' too. This"),D(" revert only removed THIS machine's own configuration."),k(`
|
|
1042
|
+
Remove them from the repo (then commit):`),k(S(" anyray-connect --project --revert")));let Ee=[W,...s.fallbackPort?[_n(W,s.fallbackPort)]:[]],dc=Up(Ee);dc.length>0&&(K("This terminal still points at the gateway"),D(` Still exported here: ${dc.join(", ")}`),D(" Removing the block from your shell profile cannot reach a shell"),D(" that already ran it. Until these are gone, your tools keep"),D(" reaching the gateway and now fail with 401."),k(`
|
|
1042
1043
|
Fix this terminal:`),k(S(` unset ${dc.join(" ")}`)),k(`
|
|
1043
|
-
Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(U(`Done (${lc} file(s) written).`),za.length>0){let Tt=Qa.length===za.length;K(Tt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let
|
|
1044
|
+
Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(U(`Done (${lc} file(s) written).`),za.length>0){let Tt=Qa.length===za.length;K(Tt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let hg of VJ(za,Qa,es.includes("claude-desktop")?process.platform:void 0))D(hg);if(es.includes("claude-desktop")&&!o.dryRun)try{await ZJ(W)}catch{D(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}Yt()&&!o.yes&&!Tt&&(await Fa("Have you applied the manual settings shown above?")?U("Acknowledged."):D("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?M(`
|
|
1044
1045
|
Skipped the connection smoke test (--skip-verify).`):await tX(W,l.map(Tt=>Tt.id)),K("What's next");let ye=new Set(ts.filter(Tt=>Tt.status==="configured").map(Tt=>Tt.id)),Ee=l.filter(Tt=>ye.has(Tt.id)).map(Tt=>Tt.title);if(k(Ee.length>0?` Connected: ${Ee.join(", ")}`:" Connected: no tools completed automatic configuration."),k(" Restart any editor that was already running \u2014 it loaded our config at startup."),k(" If something looks wrong: npx anyray-connect doctor"),!o.verbose)return 0;k(`
|
|
1045
1046
|
Re-test by hand any time:`),W.authMode!=="placeholder"&&l.length===1&&l[0]?.id==="cursor"?(k(S(` curl -sS ${W.origin}/connect/savings \\
|
|
1046
1047
|
-H "x-anyray-api-key: $(anyray-connect print-key)"`)),k(S(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):k(S(` curl -sS ${W.openaiBaseUrl}/chat/completions \\
|