anyray-connect 0.11.152 → 0.11.154
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 +204 -204
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`;if(a||n.tombstoneAbsent!==!1)try{await
|
|
4
|
-
`),await he(o,e),await
|
|
5
|
-
`,{mode:384})}catch(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
|
|
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=
|
|
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(`
|
|
2
|
+
var TR="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},Ru=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,DR=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),yg=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!DR.has(n)}catch{return!1}},un=e=>{let t=Je(e||process.env.ANYRAY_GATEWAY_URL||TR),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:Ru(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:Ru(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:Ru(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 op,readFile as kw,rename as qO,stat as Cw,truncate as zO,writeFile as Aw,rm as Ko}from"node:fs/promises";import{spawnSync as mn}from"node:child_process";import{createServer as QO}from"node:net";import{homedir as Pc}from"node:os";import{join as Tc}from"node:path";import{access as UR,chmod as FR,mkdir as Ou,open as Lu,readFile as vg,rm as qt,stat as wg,utimes as BR}from"node:fs/promises";import{createHash as WR,randomUUID as Sg}from"node:crypto";import{dirname as Nu,join as HR}from"node:path";import{isDeepStrictEqual as No}from"node:util";import{randomUUID as LR}from"node:crypto";import{lstat as NR,rename as uc,rm as $R}from"node:fs/promises";import{platform as gg}from"node:os";var MR=e=>e?.code==="ENOENT",os=async(e,t=gg())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},he=async(e,t,n=gg())=>{if(n!=="win32"){await uc(e,t);return}let r=`${t}.anyray-old-${process.pid}-${LR()}`,o=!1;try{let a=await NR(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(!MR(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 $R(r,{force:!0})};var as=e=>`${e}.anyray-bak`,Eg=async e=>{let t;try{t=await Lu(Nu(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},bg=async(e,t)=>{let n,r;try{n=await Lu(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 Eg(e)},KR=async e=>{let t;try{t=await Lu(e,"r"),await os(t)}finally{await t?.close().catch(()=>{})}await Eg(e)},R=async e=>{try{return await UR(e),!0}catch{return!1}},F=async e=>{if(!await R(e))return{};let t=await vg(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 Ou(Nu(e),{recursive:!0,mode:448});let r=as(e);if(n.backup!==!1&&!await R(r)){let a=await R(e),s=a?await vg(e,"utf-8"):`{}
|
|
3
|
+
`;if(a||n.tombstoneAbsent!==!1)try{await bg(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${Sg()}`;try{await bg(o,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`),await he(o,e),await FR(e,384),await KR(e)}finally{await qt(o,{force:!0}).catch(()=>{})}},xg=1,kg=3e4,GR=5e3,jR=/^[a-f0-9]{64}$/,Ig=e=>`${e}.pending`,VR=e=>`${e}.lock`,_u=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=>_u(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${_u(t[n])}`).join(",")}}`},Pu=(e,t)=>({exists:e,sha256:WR("sha256").update(_u(t)).digest("hex")}),Tu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Cg=e=>Tu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&jR.test(e.sha256),YR=e=>Tu(e)&&e.transactionVersion===xg&&Cg(e.before)&&Cg(e.after)&&Tu(e.journal),Du=(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`)}},ZR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Rg=async e=>{let t=VR(e),n=HR(t,"owner.json");await Ou(Nu(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=Sg();try{await Ou(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 wg(n)).mtimeMs;i=!ZR(c.pid)||l>kg}catch{try{i=Date.now()-(await wg(t)).mtimeMs>kg}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 BR(n,i,i)}catch{}})()},GR);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")},Og=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:Pu(t,n)}},_g=async(e,t)=>{let n=Ig(t);if(!await R(n))return;let r=await $o(n,"prepared ownership transaction");if(!YR(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await Og(e),a=await R(t),s=await R(as(e)),i=Du(o.fingerprint,r.before),c=Du(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 Rg(t);try{return await _g(e,t),await n()}finally{await r()}},Ag=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 Rg(a);try{await _g(n,a);let l=await Og(n),d=Pu(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(!Du(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=Ig(a),w={transactionVersion:xg,before:l.fingerprint,after:Pu(!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 Ag(n,l.value,l.exists,o)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed and config rollback was incomplete")}try{await Ag(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 kO}from"node:fs/promises";import{spawnSync as aO}from"node:child_process";import{readFileSync as sO,realpathSync as cs,statSync as Bg}from"node:fs";import{access as iO,cp as Wg,mkdir as Ug,readdir as cO,readFile as Gu,realpath as lO,rename as dO,rm as Hu,writeFile as uO}from"node:fs/promises";import{tmpdir as pO}from"node:os";import{basename as Uo,dirname as Ge,join as Ie,resolve as fO}from"node:path";import{writeFile as hc,readFile as ss,chmod as Mu,stat as Uu,mkdir as Tg,rm as Br,access as JR}from"node:fs/promises";import{randomUUID as XR}from"node:crypto";import{homedir as Dg}from"node:os";import{join as Pn}from"node:path";var ee=()=>Pn(Dg(),".anyray"),Mo=async()=>{let e=ee();try{if((await Uu(e)).isDirectory())return Pn(e,"connect.json")}catch{}return e},Fu=()=>Pn(ee(),"dev-key.pem"),Ct=async()=>{let e=ee(),t;try{if(!(await Uu(e)).isDirectory())t=await ss(e,"utf-8").catch(()=>{}),await Br(e,{force:!0});else return}catch{}if(await Tg(e,{recursive:!0,mode:448}),t!==void 0){let n=Pn(e,"connect.json");await hc(n,t,{mode:384}),await Mu(n,384)}},mc=async e=>{await Ct();let t=Fu();await hc(t,e,{mode:384}),await Mu(t,384)},We=async()=>{try{let e=await ss(Fu(),"utf-8");return e.trim()?e:void 0}catch{return}},is=async()=>{await Br(Fu(),{force:!0}).catch(()=>{})},qR=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)?{}:qR(t)}catch{return{}}},zR=0,QR=3e4,eO=5e3,tO=25,nO=()=>Pn(Dg(),".anyray-connect-profile.lock"),rO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},oO=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!rO(t.pid)}catch{}return Date.now()-(await Uu(e)).mtimeMs>QR},Lg=async()=>{let e=nO(),t=Pn(e,"owner.json"),n=Date.now()+eO;for(;;){let r=XR();try{await Tg(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 oO(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,tO))}}},Ng=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Mo(),r=`${n}.${process.pid}.${zR++}.tmp`;await hc(r,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,{mode:384}),await Mu(r,384);try{await he(r,n)}catch(o){throw await Br(r,{force:!0}).catch(()=>{}),o}},oe=async e=>{let t=await Lg();try{await Ng(e)}finally{await t()}},$g=async e=>{let t=await Lg();try{let n=await L(),{next:r,result:o}=e(n);return r&&await Ng(r),o}finally{await t()}},$u=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],Pg="ssoLink",Bu=async()=>{let e=await L();return $u.some(t=>e[t]!==void 0)?!0:await We()!==void 0},yc=async()=>{let e=await L(),t=$u.some(a=>e[a]!==void 0),n=e[Pg]!==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 $u)delete a[s];delete a[Pg],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},Mg=["fallback-bundle.enc","fallback-key","fallback-usage-queue.jsonl"],gc=async()=>{let e=ee();for(let t of Mg)await Br(Pn(e,t),{force:!0}).catch(()=>{})},Wu=async()=>{let e=ee(),t=[];for(let n of Mg){let r=Pn(e,n);try{await JR(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=>fO(e).replace(/\\/g,"/").toLowerCase(),Ku=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",ls=e=>`${e}.source`,Hg=e=>/(^|\/)_npx(\/|$)/.test(Fo(e)),ju=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Fo(e)),Vu=e=>{let t=Fo(e),n=[pO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Fo);return Hg(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,Fg=e=>{try{let t=Bg(e);return t.isFile()?t.size:void 0}catch{return}},Yu=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),hO=e=>{let t=Yu(e);if(!t)return;let n=Ie(Ge(t),"bin",Ku());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",Ku(t));try{let r=cs(n),o=cs(Ie(e,"versions"));if(kc(r,o))return n;if(t==="win32"){let a=sO(ls(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=Fg(Ie(o,a,Ku(t)))??Fg(Ie(o,a));if(s!==void 0&&s===Bg(n).size)return n}}catch{return}},Wr=(e=yt())=>{let t=or(e),n=ju(t)||Ju(t)?Bo():void 0;return hO(e.execPath)??n??t},Kg=(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}},Gg=(e=yt())=>{let t=Wr(e);return!ds(e.execPath)&&!Vu(t)?Ge(t):Ie(ee(),"bin")},bc=async e=>{try{return await iO(e),!0}catch{return!1}},mO=async e=>{let t=await lO(e),n=Ge(t),r=Ge(n),o=Ie(r,"package.json"),a=await Gu(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}},yO=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}},gO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Gu(Ie(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await yO(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Wg(i,Ie(t,s),{recursive:!0}),r.push(i)}}},wO=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 mO(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 Hu(a,{recursive:!0,force:!0}),await Ug(a,{recursive:!0,mode:448});try{await Wg(n.dist,Ie(a,"dist"),{recursive:!0}),await uO(Ie(a,"package.json"),await Gu(n.packageJson),{mode:384}),await gO(n.root,Ie(a,"node_modules")),await Ug(Ge(r),{recursive:!0,mode:448});try{await dO(a,r)}catch(s){if(!await bc(o))throw s}}finally{await Hu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Zu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,bO=e=>{let t=Uo(Ge(Ge(e)));return Zu.test(t)?t:void 0},Ju=(e,t=ee())=>{let n=Ge(Ge(e));return Fo(Ge(n))===Fo(Ie(t,"bin"))&&Zu.test(Uo(n))&&Uo(Ge(e))==="dist"&&Uo(e)==="index.js"},Cc=async(e=yt())=>{let t=Ie(ee(),"bin"),n=bO(or(e)),r=[];for(let o of await cO(t).catch(()=>[])){if(!Zu.test(o)||o===n)continue;let a=Ie(t,o);await Hu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},jg=async(e,t=yt())=>{let n=or(t);if(!ds(t.execPath)||!Hg(n)||Bo())return;let r=await wO(t),o=aO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Xu=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,us=(e,t)=>[e,...t].map(Xu).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)},qu=e=>{let t=e.hooks;if(!t)return!1;let n=!1;for(let[r,o]of Object.entries(t)){if(!Array.isArray(o))continue;let a=o.filter(s=>!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",Vg="__anyray-codex-hook",sr="__anyray-prompt-hook",Yg="__anyray-shell-pretool",zu="__anyray-shell-run",Zg="__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(Xu).join(" ")},vc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Dt(t,n),Jg=()=>Dt("print-key"),Re=()=>Wr(),je=Vu,le=()=>!je(Re()),Hr=async()=>{if(!le())return!1;try{return await kO(Re()),!0}catch{return!1}},cr="__anyray-mcp-server",Ve=e=>ps(cr,[e]),CO=(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&&CO(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"],Xg=["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"],AO=(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=AO(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 Qu}from"zod";var vO=5e3,SO=1e3,EO=1e8,xO=Qu.object({modelContext:Qu.object({contextTokens:Qu.number().int().min(SO).max(EO)}).optional()}),qg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},zg=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??vO,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=xO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var IO=1e6,fs="[1m]",RO=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Qg=(e,t)=>!e||t===void 0?{}:RO(e)?{envTokens:t}:t<IO?{}:e.toLowerCase().endsWith(fs)?{}:{model:`${e}${fs}`},ew=(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 OO}from"node:os";var Lt=(e=OO())=>{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()!=="",_O=(e,t)=>typeof e[t]=="string"&&!xc(e[t]),tw=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},PO=()=>F(Lt()).catch(()=>({})),nw=async(e={})=>{let t=e.env??process.env,n=tw(e.userSettings??{}),r=tw(await(e.readManaged??PO)().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}):!_O(n,a)&&xc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},ep=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`,tp=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.",rw=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 TO=Dn.map(e=>e.name),DO=Ec.filter(e=>!TO.includes(e)),ow=e=>typeof e=="string"&&e.trim()!=="",aw=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},LO=(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)},NO=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},np=()=>F(Lt()).catch(()=>({})),sw=np,$O=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))},iw=async(e={})=>{let t=await(e.readManaged??sw)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!$O(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.",cw=async(e={})=>{let t=aw(e.userSettings??{}),n=aw(await(e.readManaged??sw)().catch(()=>({}))),r=[];for(let o of DO){if(!ow(n[o])||!ow(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(LO(n[o],t[o],a))continue;let s=a?NO(n[o]):void 0;r.push({name:o,source:`managed settings (${Lt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},lw=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`,dw=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 MO}from"node:os";import{join as UO}from"node:path";import{readFile as FO}from"node:fs/promises";var ot=e=>!!e.keyRefreshEnabled;var BO=400,uw=async()=>{try{let e=UO(MO(),".claude","settings.json"),n=JSON.parse(await FO(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}},pw=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"?pw():e==="claude"?uw():await uw()??await pw(),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(),BO);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"),WO=Ec,lr="anyray",HO=()=>({type:"stdio",...Ve("claude"),alwaysLoad:!0}),Gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),KO=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]=HO(),e.mcpServers=t,"installed")},fw=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)},GO=e=>{Ac(e,"PostToolUse",Xe,Tn(Dt(Xe),{matcher:"*"})),Ac(e,"UserPromptSubmit",sr,Tn(Dt(sr)))},jO=e=>{Ac(e,"SessionStart",ir,Tn(Dt(ir),{async:!0}))},yw=e=>Wo(e,"SessionStart",ir),hw=e=>{let t=Wo(e,"PostToolUse",Xe),n=Wo(e,"UserPromptSubmit",sr),r=yw(e);return t||n||r},VO="print-key",YO=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]===VO&&YO(t)},ZO=async(e,t)=>{let n=(await Fr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of WO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},JO=e=>typeof e.apiKeyHelper=="string"&&!jr(e),gw=async e=>{let t=await np(),n=async()=>t,[r,o,a]=await Promise.all([nw({userSettings:e,readManaged:n}),cw({userSettings:e,readManaged:n}).catch(()=>[]),iw({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},mw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await gw(e),o=tp(t),a=dw(n);return{routingOverrides:[...t.map(i=>({problem:ep(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:lw(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=qg(r),a=await zg(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 gw(r),h=f.filter(I=>!I.repairable),m=f.filter(I=>I.repairable),w=[...h.map(I=>`WARNING: ${ep(I)}.`),...h.length?[tp(h)]:[],...p.state==="fine"?[]:[`WARNING: ${Ic(p)}.`,Rc(p)],...m.map(I=>rw(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 Xg)delete y[I];let b=!!e.clientKey,A=le(),v=JO(r);!c&&!l&&b&&A&&!v?(r.apiKeyHelper=Jg(),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?(jO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):yw(r),le()?(GO(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.")):(hw(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()?KO(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=fw(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 mw(e)},async routingOverrides(){let e=await F(Ln()).catch(()=>({}));return(await mw(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=hw(n),a=jr(n);a&&delete n.apiKeyHelper;let s=r?await ZO(t,r):[],i=ew(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);fw(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.154";var hn=e=>{let{command:t,args:n}=pn([e]);return{command:t,args:n}},ur=()=>Wr();import{homedir as ww,userInfo as XO}from"node:os";var ms=()=>{try{return ww()!==XO().homedir}catch{return!1}},Ho=e=>[`Skipped ${e} \u2014 HOME (${ww()}) 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 sp="__anyray-fallback-proxy",ws="ai.anyray.connect.fallback",fr="anyray-fallback",vw=ws,ke=8785,bs=60,ip="x-anyray-local",cp=()=>hn(sp),bw=ur,Lc=async(e=ke)=>{let t=n=>new Promise(r=>{let o=QO();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",`${vw}.plist`),ks=()=>jo(gs(),".anyray","logs"),ys=()=>jo(ks(),"connect-daemon.log"),Sw=async(e,t=1048576)=>{await Cw(e).then(r=>r.size,()=>0)>t&&await zO(e).catch(()=>{})},Yo=()=>jo(gs(),".config","systemd","user",`${fr}.service`),rp=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Cs=(e=cp())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${rp(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>${vw}</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>${rp(ys())}</string>
|
|
23
|
+
<key>StandardErrorPath</key><string>${rp(ys())}</string>
|
|
24
24
|
</dict>
|
|
25
25
|
</plist>
|
|
26
|
-
`},As=(e=
|
|
26
|
+
`},As=(e=cp())=>{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}=cp();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)."]},Ew=async()=>{let e=Go();if(e!=="darwin"&&e!=="linux")return!1;let t=e==="darwin"?Vo():Yo();try{return await Cw(t),!0}catch{return!1}},xw=async()=>{let e=Go();if(e!=="darwin"&&e!=="linux")return!0;let t=e==="darwin"?Vo():Yo(),n=e==="darwin"?Cs():As();return await kw(t,"utf-8").catch(()=>null)===n},ap=async e=>{await op(jo(gs(),"Library","LaunchAgents"),{recursive:!0}),await op(ks(),{recursive:!0,mode:448}),await Aw(e,Cs())},Iw=async()=>{let e=Go();return e==="darwin"?(await ap(Vo()),!0):e==="linux"?(await op(jo(gs(),".config","systemd","user"),{recursive:!0}),await Aw(Yo(),As()),!0):!1},Rw=async()=>Iw().catch(()=>!1),e_=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 kw(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(bw()))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 anyray-connect is running from a temporary path (${bw()}).`,"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 e_(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 ap(o),mn("launchctl",["bootout",`gui/${r}`,n]),await Ko(n,{force:!0}).catch(()=>{});try{await qO(o,n)}catch{await ap(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 Iw(),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()]}}},lp=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:{[ip]:"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 lp(e)&&n.push("Stopped the running key-refresh proxy daemon.")}catch{}return{ok:!0,messages:n}};import{stat as FJ}from"node:fs/promises";import{readFileSync as t_,rmSync as n_,writeFileSync as r_,mkdirSync as o_}from"node:fs";import{join as a_}from"node:path";var dp=()=>a_(ee(),"draining"),Ow=e=>{try{o_(ee(),{recursive:!0}),r_(dp(),`${Math.floor(e)}
|
|
39
|
+
`,"utf-8")}catch{}},up=()=>{try{n_(dp(),{force:!0})}catch{}},s_=16*6e4,pp=(e=Date.now())=>{let t;try{t=t_(dp(),"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+s_};import{homedir as yp,platform as gp}from"node:os";import{join as Zo}from"node:path";import{mkdir as fp,readFile as i_,rename as c_,writeFile as Nc,rm as Yr}from"node:fs/promises";import{spawnSync as l_}from"node:child_process";var mp=()=>Zo(ks(),"connect-refresh.log"),Mc=1800,Es="ai.anyray.connect.refresh",Zr="anyray-refresh",Uc="\\AnyrayConnectKeyRefresh",Fc=Es,xs=Zr,Ss=Uc,d_=String(Mc/60),wp=(e,t)=>{let n=l_(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},bp=()=>Zo(yp(),"Library","LaunchAgents",`${Fc}.plist`),kp=()=>Zo(yp(),".config","systemd","user"),_w=()=>Zo(kp(),`${xs}.service`),$c=()=>Zo(kp(),`${xs}.timer`),hp=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Bc=()=>hn(ir),u_=(e=Bc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${hp(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,18 +50,18 @@ ${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>${hp(mp())}</string>
|
|
54
|
+
<key>StandardErrorPath</key><string>${hp(mp())}</string>
|
|
55
55
|
</dict>
|
|
56
56
|
</plist>
|
|
57
|
-
`},
|
|
57
|
+
`},p_=(e=Bc())=>{let{command:t,args:n}=e;return`[Unit]
|
|
58
58
|
Description=Anyray connect gateway key refresh
|
|
59
59
|
After=network-online.target
|
|
60
60
|
|
|
61
61
|
[Service]
|
|
62
62
|
Type=oneshot
|
|
63
63
|
ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
|
|
64
|
-
`},
|
|
64
|
+
`},f_=()=>`[Unit]
|
|
65
65
|
Description=Anyray connect gateway key refresh (every ${Mc/60}m)
|
|
66
66
|
|
|
67
67
|
[Timer]
|
|
@@ -71,57 +71,57 @@ 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(" ")}`],_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("#")})},
|
|
76
|
-
`),o=jc(r),a=
|
|
77
|
-
`),s=jc(a),i=
|
|
74
|
+
`,h_=(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(" ")}`],Pw=e=>!e.run&&ms(),m_=async(e,t)=>await i_(bp(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Fc]).ok,hr=async(e={})=>{let t=e.os??gp(),n=e.invocation??Bc(),r=e.run??wp,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(Pw(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=bp(),i=u_(n);if(await m_(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await fp(ks(),{recursive:!0,mode:448}),await fp(Zo(yp(),"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 c_(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 fp(kp(),{recursive:!0}),await Nc(_w(),p_(n)),await Nc($c(),f_()),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=h_(n);return r("schtasks",["/Create","/TN",Ss,"/TR",s,"/SC","MINUTE","/MO",d_,"/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(mp(),{force:!0}).catch(()=>{});let t=e.os??gp(),n=e.run??wp,r=[];if(Pw(e))return{ok:!0,messages:Ho("scheduler teardown")};try{if(t==="darwin"){let o=bp(),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(_w(),{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=gp(),t=wp)=>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 vW from"node:http";import{spawn as DB}from"node:child_process";import{createHash as LB}from"node:crypto";import{homedir as NB}from"node:os";import{join as jS}from"node:path";import{readFile as $B,writeFile as VS,chmod as MB,stat as UB,unlink as NS}from"node:fs/promises";import{homedir as Kc,platform as Gw}from"node:os";import{join as st}from"node:path";import{execFile as S_}from"node:child_process";import{readFile as E_,readdir as x_}from"node:fs/promises";import{homedir as y_,platform as g_}from"node:os";import{join as Wc}from"node:path";var Ye=e=>{let t=y_();switch(g_()){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 Lw}from"node:fs/promises";import{homedir as Jr,platform as Xo}from"node:os";import{join as Nn,posix as w_,win32 as b_}from"node:path";var Is=["Code","Code - Insiders","VSCodium"],Cp="1.121.0",Tw=1,k_=121,Nw="1.102.0",Dw=1,C_=102,A_={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])}},Ap=e=>{let t=Hc(e);return t?t.major!==Tw?t.major>Tw:t.minor>=k_:!1},$w=e=>{let t=Hc(e);return t?t.major!==Dw?t.major>Dw:t.minor>=C_:!1},v_=async e=>{if(Xo()!=="darwin")return;let t=Nn("/Applications",`${A_[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await Lw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Mw=(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)}},vp=(e,t)=>e?t==="win32"?b_.join:w_.join:Nn,qo=(e,t=!1,n=Xo(),r=Jr(),o=process.env)=>t?vp(t,n)(r,Rs[e],"data","User"):Nn(Mw(e,n,r,o),"User"),Uw=async(e,t=!1,n=Xo(),r=Jr(),o=process.env)=>{try{let a=vp(t,n)(qo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Lw(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[]}},Fw=async(e,t=Xo(),n=Jr(),r=process.env)=>{let a=(await Uw(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},Bw=async(e,t=!1,n=Xo(),r=Jr(),o=process.env)=>{let a=vp(t,n),s=qo(e,t,n,r,o),i=await Uw(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(Mw(e)))return e},Rs={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Ww=(e,t=Jr())=>Nn(t,Rs[e],"extensions"),Sp=async(e=Jr())=>{for(let t of Is)if(await R(Nn(e,Rs[t])))return t},Hw=async e=>{let t=e??await zo();if(!t)return{status:"unknown"};let n=await v_(t);return n?{variant:t,version:n,status:Ap(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var I_=3e3,R_="Claude Code-credentials",O_=["copilot-cli","CopilotCLI"],jw=e=>new Promise(t=>{try{S_("security",["find-generic-password","-s",e],{timeout:I_},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),__=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"))||Gw()==="darwin"&&await jw(R_))},P_=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 E_(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},Kw=async e=>{try{return(await x_(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},Ep=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 Kw(st(Kc(),t,"extensions")))return!0;for(let t of Is){if(await Kw(Ww(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(Gw()==="darwin"){for(let t of O_)if(await jw(t))return!0}return!1},$t=async()=>{let[e,t,n]=await Promise.all([__(),P_(),Ep()]);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 F_}from"node:os";import{join as qc}from"node:path";import{chmod as B_,readFile as Os,rm as qw,copyFile as W_}from"node:fs/promises";var Xr="# >>> anyray connect >>>",Vc="# <<< anyray connect <<<",xp="# restore: ",Vw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Yc=e=>{let t=new RegExp(`\\n*${Vw(Xr)}[\\s\\S]*?${Vw(Vc)}\\n?`,"g");return e.replace(t,"")},Ip=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,Yw=e=>Gc(e,"[")-Gc(e,"]"),T_=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+Yw(Ip(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?T_(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=Ip(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+Yw(l)))}return t},Rp=e=>e.findIndex(t=>t.kind==="table"),Op=e=>e.includes(Xr),Zw=(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("#")})},_p=(e,t)=>Zw(Yc(e),t),Pp=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)},Jw=(e,t)=>{let n=e.indexOf(Xr);if(n<0)return!1;let r=e.indexOf(Vc,n+Xr.length);return r<0?!1:Zw(e.slice(n,r),t)},Tp=(e,t)=>{let r=Yc(e).split(`
|
|
76
|
+
`),o=jc(r),a=Rp(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=Ip(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=Xw(e),a=Yc(e).split(`
|
|
77
|
+
`),s=jc(a),i=Rp(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=Rp(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])=>`${xp}${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
|
+
`},Xw=e=>{let t=new Map,n=Pp(e);if(n===void 0)return t;for(let r of n.split(`
|
|
84
|
+
`)){let o=r.trim();if(!o.startsWith(xp))continue;let a=o.slice(xp.length).trim(),[s]=jc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Jc=e=>{if(!Op(e))return null;let t=[...Xw(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
|
|
88
|
+
`:""};import{randomUUID as D_}from"node:crypto";import{chmod as L_,mkdir as N_,rm as $_,writeFile as M_}from"node:fs/promises";import{dirname as U_}from"node:path";var pe=async(e,t)=>{await N_(U_(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${D_()}`;try{await M_(n,t,{flag:"wx",mode:384}),await he(n,e),await L_(e,384)}finally{await $_(n,{force:!0}).catch(()=>{})}};var H_="codex",K_="Codex app / CLI / IDE",G_="https://chatgpt.com/backend-api/codex",j_="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",V_="x-anyray-client-context-window",Y_="x-anyray-client-auto-compact-limit",zc=()=>process.env.CODEX_HOME?.trim()||qc(F_(),".codex"),qr=()=>qc(zc(),"config.toml"),Xc=()=>`${qr()}.anyray-bak`,Dp=()=>qc(zc(),"hooks.json"),$n=()=>qc(zc(),"anyray.config.toml"),zw=e=>Wo(e,"PostToolUse",Vg),Qw=(e,t=!1)=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||H_,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||K_}),it=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Lp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,_s=(e,t={})=>{let n=Qw(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:Lp(),i=e.clientKey&&!e.viaLocalProxy,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${it(G_)}`,`"x-anyray-forward-headers" = ${it(j_)}`,...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(`"${V_}" = ${it(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${Y_}" = ${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(", ")}]`]:[]]},Z_=()=>Lp()?["model_provider","model"]:["model_provider"],eb={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=Dp(),o=Qw(e),a=X(e,"openai"),s=Lp(),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=zw(c),u=await R(n),f=u?await Os(n,"utf-8"):"";if(_p(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=_p(f,"mcp_servers.anyray"),h=Tp(f,"model_context_window"),m=Tp(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 W_(n,Xc()),await B_(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}),Z_());return await pe(n,b),g.push(n),await R($n())&&(await qw($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(!Jw(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=Pp(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(Dp());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=Dp(),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.`]}}zw(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 qw($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 eP}from"node:os";import{join as tP}from"node:path";import{readFile as ob,rm as $p}from"node:fs/promises";import{readFile as J_,writeFile as tb,access as X_}from"node:fs/promises";import{homedir as q_}from"node:os";import{join as Np}from"node:path";var z_="# >>> anyray connect >>>",Q_="# <<< anyray connect <<<",Ps=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:z_,end:Q_},vt=()=>{let e=q_(),t=process.env.SHELL||"";return t.includes("zsh")?Np(e,".zshrc"):t.includes("bash")?Np(e,".bashrc"):Np(e,".profile")},Qc=async e=>{try{return await X_(e),await J_(e,"utf-8")}catch{return""}},nb=(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=nb(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,"'\\''")}'`,
|
|
98
|
-
`)):w&&y&&await
|
|
95
|
+
`;return await tb(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)},rb=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 tb(e,nb(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,"'\\''")}'`,nP=e=>{let t=ve(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},ab=(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'"]]},rP=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],oP=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],Mp=()=>tP(eP(),".anyray","shell-env.sh"),ib="# Managed by anyray-connect. Do not source this file anywhere else.",sb=e=>e.split(/\r?\n/,1)[0]===ib,Up=e=>oP.some(t=>e.startsWith(`export ${t}=`)),cb=(e,t=process.env)=>Fp([e],t),Fp=(e,t=process.env)=>e.some(r=>t.ANTHROPIC_BASE_URL===r.anthropicBaseUrl||t.OPENAI_BASE_URL===r.openaiBaseUrl)?rP.filter(r=>(t[r]??"")!==""):[],lb={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=>Up(n)||n.includes(Mp()))?["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=ab(e,s,r,o),c=i.filter(Up),l=i.filter(b=>!Up(b)),d=Mp(),u=Gg(),f=[nP(u),...l,...c.length>0?[`[ -r ${ve(d)} ] && . ${ve(d)}`]:[]],p=e.clientKey?ab(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 ob(d,"utf8"):void 0,y=g===void 0||sb(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,[ib,...c,""].join(`
|
|
98
|
+
`)):w&&y&&await $p(d,{force:!0}),await el(n,f)}catch(b){try{g!==void 0&&y?await pe(d,g):y&&await $p(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=Mp(),r=await R(n),o=r?sb(await ob(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 $p(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 FP}from"node:child_process";import{closeSync as BP,copyFileSync as WP,existsSync as Se,mkdirSync as HP,openSync as KP,readFileSync as Wb,readSync as GP,renameSync as jP,rmSync as yn,writeFileSync as ef}from"node:fs";import{homedir as Hb,platform as VP}from"node:os";import{dirname as Kb,join as na,resolve as YP}from"node:path";import{isIP as Yp}from"node:net";import{execFileSync as ol}from"node:child_process";import{mkdtempSync as aP,rmSync as sP,writeFileSync as iP}from"node:fs";import{createRequire as cP}from"node:module";import{tmpdir as lP}from"node:os";import{join as db}from"node:path";var Ds=class extends Error{},Ls=e=>e instanceof Ds?`: ${e.message}`:"",ub=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})`)},pb=()=>{try{return ol("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Wp=64*1024*1024,dP=Wp*2+64,rl=e=>`'${e.replace(/'/g,"''")}'`,uP=(e,t)=>ol("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:dP,stdio:["ignore","pipe","pipe"]}),pP=(e,t)=>ol("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Wp,stdio:["pipe","pipe","pipe"]}),fb=(e,t,n=uP)=>{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")},hb=(e,t=pP)=>{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)},
|
|
106
|
-
`),
|
|
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);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},
|
|
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},
|
|
103
|
+
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");ub(o?.slice(1).map(Number))},fP=(e,t)=>{let n=aP(db(lP(),"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=db(n,`value-${s}`);return iP(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:Wp,stdio:["pipe","ignore","pipe"]})}finally{try{sP(n,{recursive:!0,force:!0})}catch{}}},hP={kind:"sqlite3-cli",readItem:(e,t)=>fb(e,t),checkpointWal:e=>hb(e),mutateRows:fP},mP=()=>{try{let t=cP(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Bp=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},yP=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),gP=e=>({kind:"node-sqlite",readItem:(t,n)=>Bp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:yP(o.value)}),checkpointWal:t=>Bp(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);ub(o)}),mutateRows:(t,n)=>Bp(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=mP();return nl=e?gP(e):pb()?hP:null,nl};import{spawn as wP}from"node:child_process";import{randomUUID as mb}from"node:crypto";import{constants as yb}from"node:fs";import{chmod as bP,copyFile as gb,mkdir as kP,readdir as CP,readFile as AP,rename as vP,rm as $s,writeFile as SP}from"node:fs/promises";import{join as Hp}from"node:path";var Kp=/^[a-z0-9][a-z0-9-]{0,31}$/,EP=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,wb=/^[a-z0-9][a-z0-9-]{0,31}$/,xP=/^[0-9TZ:.+-]{1,40}$/,Gp=()=>Hp(ee(),"pending"),sl=e=>{if(!Kp.test(e)||EP.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Hp(Gp(),`${e}.json`)},bb=()=>Hp(ee(),"cursor-pending.json"),IP=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),RP=(e,t)=>{if(!IP(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Kp.test(n)||typeof e.op!="string"||!wb.test(e.op)||typeof e.requestedAt!="string"||!xP.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}:{}}},jp=async(e,t)=>{try{return RP(JSON.parse(await AP(e,"utf-8")),t)}catch{return}},kb=async()=>{let e=bb(),t=await jp(e,"cursor");if(!t)return;let n=!1;try{await Cb(),await gb(e,sl("cursor"),yb.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 jp(sl(e),e);return t||(e==="cursor"?kb():void 0)},yr=async()=>{let e;try{e=await CP(Gp())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Kp.test(r))continue;let o=await il(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await kb();n&&t.push(n)}return t},Cb=async()=>{await Ct();let e=Gp();await kP(e,{recursive:!0,mode:448});try{await bP(e,448)}catch{}},al=async e=>{await Cb();let t=sl(e.adapter),n=`${t}.${process.pid}.tmp`;await SP(n,`${JSON.stringify(e)}
|
|
105
|
+
`,{mode:384}),await he(n,t)},OP=(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 Vp(e,t)==="claimed",Vp=async(e,t)=>{let n=sl(e);if(t){let o=`${n}.${process.pid}.${mb()}.claimed`;try{await vP(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await jp(o,e);if(a&&OP(a,t))return await $s(o,{force:!0}),"claimed";let s=!1;try{await gb(o,n,yb.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(bb(),{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"}},_P=e=>{let{command:t,args:n}=hn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},PP=e=>{let{exe:t,args:n}=_P(e),r=wP(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},Ab=PP;var vb=async()=>{let e=[],t;try{t=await yr()}catch{return e}for(let n of t)if(!wr(n.watcherPid))try{let r=Ab(n.adapter);if(!r)continue;await al({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},Ms=async(e,t)=>{if(!wb.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await il(e),r=new Date().toISOString(),o=mb();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=Ab(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 TP,spawnSync as Eb}from"node:child_process";import{existsSync as cl}from"node:fs";import{homedir as DP,platform as br}from"node:os";import{join as xb,win32 as Sb}from"node:path";var Ib=(e,t={})=>{let n=t.env??process.env,r=t.exists??cl,o=(t.home??DP)(),a={localAppData:n.LOCALAPPDATA??Sb.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=Sb.join(i,s.path);if(r(c))return c}},zr=/^[A-Za-z0-9 ._-]{1,64}$/,LP=/^[A-Za-z0-9.-]{1,128}$/,ll=e=>e.darwinBundleId&&LP.test(e.darwinBundleId)?e.darwinBundleId:void 0,Rb=(e,t=br())=>t==="darwin"?ll(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",Ob=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",_b=(e,t=br(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return Ib(e,r)!==void 0;let o=e.linuxProcess;return!o||!zr.test(o)?!1:n.split(":").filter(Boolean).some(a=>cl(xb(a,o)))},Pb=(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))},Tb=1e4,Us=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=xb(t,"System32",e);return cl(n)?n:e},NP=e=>{let t=`/usr/bin/${e}`;return cl(t)?t:e},$P=(e,t)=>{try{let n=Eb(e,t,{encoding:"utf-8",timeout:Tb,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}},MP=e=>new Promise(t=>setTimeout(t,e)),Db=(e,t={})=>{let n=t.runtimePlatform??br(),r=t.run??$P;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(NP("pkill"),["-TERM","-o","-x",o])},Lb=async(e,t=2e4,n={})=>{let r=n.sleep??MP,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},UP=(e,t,n={})=>{let r=br();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=Eb(e,t,{stdio:"ignore",timeout:Tb,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=TP(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},Nb=(e,t={})=>{let n=t.runtimePlatform??br(),r=t.launch??UP;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=Ib(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!zr.test(o)?!1:r(o,[])};var ZP={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"}]},JP=e=>e==="apply"||e==="native"||e==="revert",Gb=()=>Ye("Cursor"),Qr=()=>na(Gb(),"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 Jp="/seat/cursor",tf="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"),jb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",XP=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",jb,"",tf,""].join(`
|
|
106
|
+
`),qP=e=>{let t=YP(e);for(;;){if(Se(na(t,".git")))return t;let n=Kb(t);if(n===t)return null;t=n}},zP=e=>e.authMode!=="placeholder",tn=()=>na(Hb(),".cursor","hooks.json"),nn=()=>na(Hb(),".cursor","mcp.json"),Ut="anyray",Vb="--anyray-owner=cursor-v1",QP="postToolUse",eT="beforeSubmitPrompt",$b="preToolUse",tT="^MCP:",nT="UserPromptSubmit",rT="Shell",oT="^(Read|Grep)$",hl="--anyray-owner=cursor-hook-v1",eo=[{event:QP,flag:Xe,trailingArgs:["cursor"],matcher:tT},{event:eT,flag:sr,trailingArgs:[],matcher:nT},{event:$b,flag:Yg,trailingArgs:[],matcher:rT},{event:$b,flag:Zg,trailingArgs:[],matcher:oT}];var Mb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},aT=(e,t,n)=>FP(e,t,n),Ub=aT,sT,iT=()=>{let e=sT??VP();if(e==="win32"){let t=Ub(Us("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],Mb);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=Ub("pgrep",["-x",t],Mb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},cT=iT,pl=()=>cT();var lT=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,qe)??null,openAIKey:e.readItem(n,lt)??null,lastWritten:r};ef(t,`${JSON.stringify(o,null,2)}
|
|
107
|
+
`,{encoding:"utf-8",flag:"wx",mode:384})},Yb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;ef(n,`${JSON.stringify(t,null,2)}
|
|
108
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{jP(n,e)}catch(r){throw yn(n,{force:!0}),r}},dT=(e,t)=>{let n=Qo(e);Yb(e,{...n,lastWritten:t})},ae=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Fb=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=Wb(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(!Fb(r)||!Fb(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}},Bb=e=>{let t=Buffer.alloc(16),n=KP(e,"r");try{return GP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{BP(n)}},uT=(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 Zb=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(".")&&Yp(t)===0||t==="0.0.0.0")return!0;if(Yp(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(Yp(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 Zb(`${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},Xp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Zb(t.hostname)}catch{return!1}},pT=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},fT=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Je(e.origin)}/v1${Jp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Jp}`}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."],Jb=()=>{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"},hT=(e,t)=>{if(!Xp(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${Jp}`;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}},mT=(e,t=[])=>({command:Dt(e,[...t,hl])}),nf=(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} `)},yT=(e,t)=>ae(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Xb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(nf(a,t,n)){r=!0;continue}if(!ae(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!yT(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}},rf=(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},qb=(e,t,n,r,o)=>ae(e.hooks)&&rf(e.hooks,t).some(a=>ae(a)&&a.matcher===o&&nf(a,n,r)),gT=(e,t,n,r,o)=>ae(e.hooks)&&rf(e.hooks,t).some(a=>ae(a)&&a.matcher===o&&nf(a,n,r)&&vc(a.command,n,[...r,hl])),zb=(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}=Xb(rf(a,t),n,r);return s.push({...mT(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},wT=(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}=Xb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},bT=async()=>{let e=tn();if(!le()){let t=await ek();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=zb(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,Vb]}},qp=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]),kT=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)===Vb||kT(e),CT=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,AT=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}}},ek=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=wT(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}}},vT=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=qP(e);if(!n)return t;let r=na(n,Fs),o=XP();try{if(Se(r)){let a=Wb(r,"utf8");if(a===o)return t;if(!a.includes(jb))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: "${tf}"`]}}return HP(Kb(r),{recursive:!0}),ef(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.`]}}},tk=async()=>{let e=await bT(),t=await AT(),n=await vT();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},zp=async()=>{let e=await ek(),t=await Qb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},nk=async()=>{if(!le()){let e=await zp();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=zb(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}}},ST=async()=>{if(!le())return!1;try{let e=await F(tn());if(!ae(e.hooks)||!eo.every(r=>qb(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 qp(n)}catch{return!1}},rk=["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},ET=(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 rk){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}},Zp=(e,t)=>{let n=Ws(e),r=Ws(t??void 0),o={...n};for(let a of rk)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]}},xT=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 nk();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=Jb();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 tk(),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 -- "${tf}" (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:ZP,needsTarget:e=>e!=="revert",async complete(e,t,n){return JP(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=Gb(),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 qp(n)?{registered:!0,command:CT(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=>qb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=eo.every(c=>gT(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=qp(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(zP(e))return xT(e,t);let n=fT(e),r=pT(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(!Xp(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 nk();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{Bb(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,[Zp(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=uT(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{dT(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{lT(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{Yb(a,p)}catch{y=!1}return c({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${a}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${a} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}i=await tk();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(!Xp(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())||Jb()!=="clear"?!1:ST():hT(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 zp(),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(Bb(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,[Zp(s.readItem(t,qe),h.applicationUser),h.openAIKey===null?{key:lt}:{key:lt,value:h.openAIKey}]),c=!0}else i=!0,WP(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,[Zp(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=ET(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 zp();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 wD,mkdir as bD,readFile as Ok,rm as kD,writeFile as CD}from"node:fs/promises";import{randomUUID as AD}from"node:crypto";import{dirname as vD,join as _k}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},RT=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(RT(IT(e)));import{readFile as sD,writeFile as iD}from"node:fs/promises";import{dirname as cD,join as lD}from"node:path";import{mkdir as dD}from"node:fs/promises";var ok=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),OT=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},_T=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},PT=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},of=(e,t,n)=>{let r;try{r=ze(e)}catch{return{ok:!1,reason:"unsupported"}}if(!ok(r))return{ok:!1,reason:"unsupported"};if(t in r)return{ok:!1,reason:"key-present"};let o=OT(e);if(o===-1)return{ok:!1,reason:"unsupported"};let a=_T(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=PT(e,o)?`
|
|
111
111
|
${a}${s}
|
|
112
112
|
`:`
|
|
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+nTPul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GVudF9UeXBlc10ueG1sUEsBAj8DFAAICAgABZINXRMcpkKbAgAApAUAABYAAAAAAAAAAAAAAKSBKQQAAGV4dGVuc2lvbi9wYWNrYWdlLmpzb25QSwECPwMUAAgICACTjQ1dsoZ6jXkCAAAnBAAAFQAAAAAAAAAAAAAApIEIBwAAZXh0ZW5zaW9uL0xJQ0VOU0UudHh0UEsBAj8DFAAICAgABpINXacyHPQDOQAAI6kAABsAAAAAAAAAAAAAAKSBxAkAAGV4dGVuc2lvbi9kaXN0L2V4dGVuc2lvbi5qc1BLBQYAAAAABQAFAFUBAAAQQwAAAAA=";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
|
|
115
|
-
`,{mode:384}),await
|
|
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(!
|
|
118
|
-
`))}`]:[],`export ${
|
|
119
|
-
`).map(
|
|
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&&!
|
|
113
|
+
${a}${s},`,d=`${i}${l}${c}`;try{let u=ze(d);if(!ok(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 TT}from"node:child_process";import{readdirSync as DT,statSync as LT}from"node:fs";import{createHash as lk,randomBytes as NT,randomUUID as dk}from"node:crypto";import{chmod as $T,lstat as lf,mkdir as df,readdir as uk,readFile as wn,rm as pk,unlink as gl,writeFile as uf}from"node:fs/promises";import{homedir as ra,platform as pf}from"node:os";import{dirname as af,join as St,posix as sk,win32 as MT}from"node:path";import{promisify as UT}from"node:util";var gn="0.1.27";var kr="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",yl="b464c3084ddac2d001fca4c71eb8384d55651e77f83928d8aa380548ca735fc5",ak="UEsDBBQAAAgIAAaSDV2VWjUKCAMAALQJAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeoqXlSwt3tYGg2IlQKVAg18cCI3K0mpoiCQ5XlvLrg93Vl5W0jewgt13OzHucDz4yf7teWrHCyORdT3azKynQaW/IlT1ZpXnnd/m2uLzIJ6AfocQxOJojJ/GwC7nOruqg9dI67slFSuFGKdYLXAJnS9LRs5+nTPulMrhC6wNGteJ1p/VR11fd7jb8xrwAoGOQqXQtTnF5cZGPMYGBBPXPRT406BKljRiBKysosSfRdf6aSjE0PQluE2HTWbH2BuUhq6usm13/JsWkmlniBcadqxSqxX1H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ICACTjQ1dsoZ6jXkCAAAnBAAAFQAAAAAAAAAAAAAApIEIBwAAZXh0ZW5zaW9uL0xJQ0VOU0UudHh0UEsBAj8DFAAICAgABpINXacyHPQDOQAAI6kAABsAAAAAAAAAAAAAAKSBxAkAAGV4dGVuc2lvbi9kaXN0L2V4dGVuc2lvbi5qc1BLBQYAAAAABQAFAFUBAAAQQwAAAAA=";var q="anyray.anyray-vscode",ff="vscode-handoffs",fk="vscode-receipts",Ks=2,FT=UT(TT),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"]}},BT={Code:{directory:"Microsoft VS Code",executable:"Code.exe"},"Code - Insiders":{directory:"Microsoft VS Code Insiders",executable:"Code - Insiders.exe"},VSCodium:{directory:"VSCodium",executable:"VSCodium.exe"}},WT=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),hk=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&WT(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Gs=e=>{if(hk(e))try{return new URL(e.trim()).origin}catch{return}},HT=(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)},KT=e=>{try{return DT(e)}catch{return[]}},GT=e=>{try{return LT(e).mtimeMs}catch{return}},jT=(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)},VT=(e,t,n)=>{let{macAppName:r,commands:o}=Mn[e],a=o[0],s=[];for(let i of["/Applications",sk.join(t,"Applications")])for(let c of n(i))HT(c,r)&&s.push(sk.join(i,c,"Contents/Resources/app/bin",a));return s},YT=(e,t=pf(),n=ra(),r=process.env,o=KT,a=GT)=>{let s=jT(e,n,r,o,a);if(t==="darwin")return[...new Set([...Mn[e].commands,...VT(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=BT[e],c=MT.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])]},mk={run:async(e,t)=>({stdout:(await FT(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>NT(24).toString("base64url"),home:"",commandCandidates:e=>YT(e)},to=(e,t)=>St(e,".anyray",fk,`${t}.json`),hf=(e,t)=>St(e,".anyray",fk,`${t}.applied.json`),yk=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{}},sf=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}},gk=async(e,t)=>{let n=await yk(e,t);if(n)return sf(n.command,t)},ZT=async(e,t,n)=>{let r=St(e,".anyray",ff);for(let o of n){if(!o.endsWith(".json"))continue;let a=St(r,o);try{if(!(await lf(a)).isFile()||JSON.parse(await wn(a,"utf8")).variant!==t)continue;await gl(a)}catch{}}},JT=async(e,t)=>{let n=St(e,".anyray",ff),r;try{r=await uk(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=St(n,o);try{if(!(await lf(a)).isFile()||JSON.parse(await wn(a,"utf8")).variant!==t)continue;await gl(a)}catch{}}},XT=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}},wk=250,qT=9e4,zT=qT/wk,QT=async(e,t,n,r)=>{for(let o=0;o<zT;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(wk)}return"timeout"},eD=200,ik=(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,eD))}return r.join(": ")},tD=async e=>{try{let t=await lf(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},ck=e=>lk("sha256").update(e).digest("hex"),nD=async(e=ra())=>{let t=Buffer.from(ak,"base64");if(t.length<4||t[0]!==80||t[1]!==75||ck(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(ck(await wn(r))===yl)return r}catch{}await df(n,{recursive:!0,mode:448});let o=`${r}.${dk()}.tmp`;try{await uf(o,t,{mode:384}),await he(o,r),pf()!=="win32"&&await $T(r,384)}finally{await pk(o,{force:!0})}return r},cf=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=>cf(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${cf(t[n])}`).join(",")}}`},bk=(e,t,n)=>lk("sha256").update(cf({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"),rD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await wn(hf(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==bk(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 gk(e,a)===!0:!1},oD=async(e,t,n,r)=>{let o=hf(e,t),a=`${o}.${dk()}.tmp`;try{await df(af(o),{recursive:!0,mode:448}),await uf(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
114
|
+
`,{mode:384}),await he(a,o)}catch{}finally{await pk(a,{force:!0})}},aD=async(e,t)=>{await gl(hf(e,t)).catch(()=>{})},kk=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...mk,...r,home:r.home??ra()},s=Mn[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!hk(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 yk(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!Ap(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>Fw(b,pf(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await rD(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 nD(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await tD(f))return{ok:!1,reason:"extension-missing"}}let p=a.nonce(),h=St(a.home,".anyray",ff,`${p}.json`),m=to(a.home,s.slug);await df(af(h),{recursive:!0,mode:448});let w=await uk(af(h)).catch(()=>[]);await uf(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 ZT(a.home,s.slug,w).catch(()=>{});let g={installed:[],failed:[]},y=!1;try{if(n==="configure"){let A=await XT(a.home,s.slug);if(A||await sf(l,a)!==!0)try{await a.run(l,["--install-extension",f,"--force"])}catch(v){return y=!0,{ok:!1,reason:"install-failed",detail:ik(v,p)}}for(let v of u)try{(A||await sf(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:ik(A,p)}}let b=await QT(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 oD(a.home,s.slug,bk(t,o,u),p);else{await aD(a.home,s.slug),await JT(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}},Ck=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={...mk,...r,home:n};return await gk(e,i)===!0}catch{return!1}};var bn="extensions.supportAgentsWindow",kn="chat.agentHost.byokModels.enabled",js=e=>lD(Ye(e),"User","settings.json"),Ak=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),uD=e=>Ak(e)&&e[q]===!0,vk=async(e,t={})=>{let n=js(e),r=t.read??(p=>sD(p,"utf-8")),o=t.exists??R,a=t.write??(async(p,h)=>{await dD(cD(p),{recursive:!0}),await iD(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(!Ak(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(bn in i)){let p=of(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=of(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=uD(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}},mf=(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 pD}from"node:child_process";import{platform as fD}from"node:os";var Sk={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},hD=(e,t,n)=>pD(e,t,n),Ek=hD,mD,yD=()=>{let e=mD??fD();if(e==="win32"){let n=Ek(Us("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],Sk);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=Ek("pgrep",[n,r],Sk);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},gD=yD,Vs=()=>gD();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",Pk="--anyray-owner=vscode-profile-v1",Ys=e=>_k(Ye(e),"User","chatLanguageModels.json"),SD=e=>_k(Ye(e),"User","settings.json"),Zs="github.copilot.advanced",Al="debug.overrideCapiUrl",Et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ED=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}},Tk=e=>{let t=e[Zs];if(!Et(t)||!ED(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]},Dk=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 Ok(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"}}},Lk=async(e,t)=>{await bD(vD(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${AD()}`;try{await CD(n,`${JSON.stringify(t,null,2)}
|
|
116
|
+
`,{flag:"wx",mode:384}),await he(n,e),await wD(e,384)}finally{await kD(n,{force:!0}).catch(()=>{})}},yf=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!==Dk(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}})},gf=e=>{let t=e.filter(n=>!yf(n));return{next:t,removed:t.length!==e.length}},xD=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}=gf(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 Lk(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 Ok(e,"utf-8"));if(Et(t))return Tk(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.`]}},Nk=async(e,t)=>{let n=SD(e),r;try{r=await F(n)}catch{return ID(n)}let{next:o,removed:a}=Tk(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.`]}}},RD=async(e,t)=>{let n=await xD(e,t),r=await Nk(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},$k=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,Pk]}},Mk=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},Uk=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),OD=e=>Array.isArray(e.args)&&e.args.at(-1)===Pk,Fk=(e,t)=>{if(!t.hookBinaryIsDurable()||!Et(e)||!Mk(e,["type","command","args"]))return!1;let n=$k(t);return e.type==="stdio"&&e.command===n.command&&Uk(e.args,n.args)},_D=(e,t)=>{if(!Et(e)||!Mk(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&&Uk(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))},wf=(e,t)=>Fk(e,t)?"exact":Et(e)&&OD(e)||_D(e,t)?"stale-owned":"foreign",xk=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.`,PD=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=$k(o),A=y[Cn],v=A===void 0?void 0:wf(A,o);if(v==="exact"){d+=1;continue}if(v==="foreign"){u=!0,l.push(xk(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(wf(h.servers[Cn],o)==="foreign"){u=!0,l.push(xk(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 (${Nw}+).`),{changedFiles:c,messages:l,manual:u}},TD=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)||wf(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}},Bk=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.`]:[]],Wk=()=>`${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."],Hk=(e,t,n,r)=>({runMcp:o=>PD(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):RD(e,o)}),Kk=(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 ${Cp} 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.`}},DD=(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.`}},LD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Hk(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?mf({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:[Kk(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),f=await i(!1),p=a?void 0:await vk(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?[Wk()]:[],...Ik(t),mf(p??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:Bk(d.profiles),...f.messages,...u.messages]}},Rk=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."],ND=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Hk(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.`,...Rk(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:Dk(p)}))});if(!d.ok)return{status:"manual",messages:[Kk(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?[Wk()]:[],...Rk(t),...d.alreadyCurrent?[]:Bk(d.profiles),...f.messages,...u.messages]}},$D=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(!Fk(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 MD=async(e={installedVariant:zo,remoteServerVariant:Sp,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}},UD={installedVariant:zo,remoteServerVariant:Sp,detectVscodeLmProviderEligibility:Hw,configureVscodeExtension:kk,vscodeExtensionPointsAt:Ck,vscodeExtensionAwaitingReload:wl,vscodeExtensionReceiptMode:bl,hookBinaryIsDurable:le,hookBinaryPath:Re,mcpServerCommand:Ve,vscodeUserMcpConfigPaths:Bw,isRemoteDevContext:Vr},FD=(e={})=>{let t={...UD,...e},n=()=>MD(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 ${Cp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||$w(i.version);return X(r,"copilot")?LD(a,r,o,t.configureVscodeExtension,c,s,t):ND(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?$D(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(yf)?.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(yf))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 TD(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await Nk(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${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(DD(y.reason,o,a,y.detail)))}let f=Ys(o),p=await Cl(f),h=p.kind==="missing"||p.kind==="array"&&!gf(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}=gf(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${Cr} Custom Endpoint from ${f}`]};await Lk(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}}}},Gk=FD();import{accessSync as iL,constants as tC,statSync as cL}from"node:fs";import{readFile as nC,rm as zs}from"node:fs/promises";import{homedir as Rf,platform as lC}from"node:os";import{delimiter as lL,join as Of,resolve as dL}from"node:path";import{execFile as GD}from"node:child_process";import{readFile as jD}from"node:fs/promises";import{homedir as Cf,platform as VD}from"node:os";import{join as qs}from"node:path";import{join as BD}from"node:path";var bf="Iv1.b507a08c87ecfe98",WD="https://github.com/login/device/code",HD="https://github.com/login/oauth/access_token",KD="read:user",jk=1e4,oa=()=>BD(ee(),"copilot-seat-login.json"),Vk={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},kf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yk=async(e={})=>{let t={...Vk,...e};try{let n=await t.fetch(WD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:bf,scope:KD}),signal:AbortSignal.timeout(jk)});if(!n.ok)return;let r=await n.json();if(!kf(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}},Zk=async(e,t={})=>{let n={...Vk,...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(HD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:bf,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(jk)})).json();if(!kf(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"}},Jk=async(e,t)=>{let n=oa();return await pe(n,`${JSON.stringify({token:e,clientId:bf,mintedAtIso:t},null,2)}
|
|
117
|
+
`),n},vl=async()=>{try{let e=await F(oa());if(!kf(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var YD=5e3,Af=5e3,ZD=["copilot-cli","CopilotCLI"],JD="https://api.github.com/copilot_internal/user",qk="~/.copilot/config.json",zk="macOS Keychain (Copilot CLI)",Qk=e=>e===qk||e===zk,aa=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),rn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),XD=()=>process.env.XDG_CONFIG_HOME?.trim()||qs(Cf(),".config"),qD=()=>process.env.XDG_DATA_HOME?.trim()||qs(Cf(),".local","share"),zD=async()=>{try{let e=await jD(qs(Cf(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return aa(t)?t:void 0}catch{}},QD=async e=>{try{let t=await F(qs(XD(),"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{}},eL=async()=>{try{let e=await F(qs(qD(),"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{}},tL=(e,t)=>new Promise((n,r)=>{try{GD(e,[...t],{timeout:YD},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),nL=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}},rL=async(e=tL)=>{for(let t of ZD){let n=await nL(t,e);if(n)return n}};var Sl={env:process.env,platform:VD,tokenFromDeviceLogin:vl,tokenFromCopilotCliConfig:zD,tokenFromSharedConfig:QD,tokenFromOpenCode:eL,tokenFromKeychain:rL,fetch:(...e)=>fetch(...e)},oL=new Set([401,403,404]),El=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,eC=e=>{let t=e?.trim().toLowerCase()??"";return t&&t!=="default"&&El.test(t)?t:"default"},aL=e=>e!=="default"&&El.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",sL=e=>{if(typeof e!="string")return"default";let t=e.trim().match(/^https:\/\/api\.([a-z0-9-]{1,63})\.githubcopilot\.com\/?$/)?.[1];return t&&El.test(t)?t:"default"},vf=async(e,t={})=>{let n={...Sl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),Af);try{let a=await n.fetch(JD,{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:sL(s)}}return{verdict:oL.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/${El.test(n)?n:"default"}/header/models`,a=await Xk(o,e,r.clientKey,t);if(a.length>0)return a}return Xk(`${aL(n)}/models`,e,void 0,t)},Xk=async(e,t,n,r={})=>{let o={...Sl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),Af);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)}},xl=async(e,t,n,r={})=>{let o={...Sl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),Af);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)}},Il=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:zk,read:()=>n.tokenFromKeychain()}]:[],{source:qk,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await vf(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",uL=Vs,pL=()=>uL()?["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."]:[],dC=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],_f=()=>Object.fromEntries(dC.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),Sf=()=>Of(Rf(),".anyray","copilot-cli.sh"),uC="# Managed by anyray-connect. Do not source this file anywhere else.",rC=e=>e.split(/\r?\n/,1)[0]===uC,fL=["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"],Rl="COPILOT_PROVIDER_API_KEY",oC=e=>e.startsWith(`export ${Rl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Fn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",hL=()=>Xs()[0],Qs=(e="default")=>`/copilot/${e}/header`,l6=Qs(),no=e=>e.replace(/\/+$/,""),mL=(e,t="default")=>`${no(e.openaiBaseUrl)}${Qs(t)}`,Ef=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),If="claude-sonnet-5",yL=()=>{let e=Xs()[0];return e===Js?If:e},pC=e=>e.endpoints.includes(Fn(e.id)==="responses"?"/responses":"/chat/completions"),Pf=e=>{let t=e.filter(pC),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)=>aC(a.version,s.version)?-1:aC(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var aC=(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},sC=(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}`]:[],...dC];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(mL(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 ${Rl}=${ve(n)}`]},xf=(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 ${Rl}=${ve(n)}`]:[]]},gL=(e,t)=>t||!X(e,"copilot"),iC=()=>{let e=fL.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).`]},cC=(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`."],wL=(e=process.env.PATH,t=lC())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(lL)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=dL(o,n);try{if(!cL(a).isFile())continue;return iL(a,t==="win32"?tC.F_OK:tC.X_OK),a}catch{}}},bL=()=>Of(Rf(),".copilot","config.json"),Un=()=>Of(Rf(),".copilot","mcp-config.json"),ro="anyray",kL=()=>({type:"local",...Ve("profile"),tools:["*"]}),Ar=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),CL=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}},AL=async e=>{let t=Un(),n=e.json,r=Ar(n.mcpServers)?n.mcpServers:{};r[ro]=kL(),n.mcpServers=r,await J(t,n)},vL=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)},SL={resolveCopilotCommand:wL,platform:lC,detectCopilotSeat:Ep,discoverSeatToken:Il,readDeviceLoginToken:vl,fetchSeatModelCatalog:sa,probeSeatChatModel:xl},EL=e=>`'${e.replace(/'/g,"''")}'`,xL=e=>e.split(`
|
|
119
|
+
`).map(EL).join(" + [Environment]::NewLine + "),IL=(e={})=>{let t={...SL,...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&&Ef(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(Sf())},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=bL();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(oC),P=E.filter(De=>!oC(De)),$=Sf(),Y=[...P,...I.length>0?[`[ -r ${ve($)} ] && . ${ve($)}`]:[]],Z=await R($),W=Z?await nC($,"utf8"):void 0,z=W===void 0||rC(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 CL():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.`,...pL()];if(i.dryRun)return{status:"configured",messages:re};let Ke=!1;Te?.status==="installable"&&(await AL(Te),Ke=!0);try{I.length>0?await pe($,[uC,...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&&!Ef(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=yL(),C=x!==If||!!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=Pf(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={..._f(),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??If}let $=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,Y=$&&s.clientKey?Mt($):$,Z=sC(s,x,g.token,$,P,E),W=sC(s,x,Mt(g.token),Y,P,E),z=Fn(x),me=I.filter(re=>pC(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&&Qk(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}', ${xL(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(!gL(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:",...cC(t.platform(),y),...iC()]}}return{status:"held",messages:[...p&&i.dryRun?[`would remove a stale Anyray ${An} block from ${vt()} (org lane, not chosen)`]:[],...cC(t.platform(),y)]}}let b=hL(),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",...xf(s,b,v).map(E=>{let[x,...C]=E.replace(/^export /,"").split("=");return` setx ${x} "${C.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${Rl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(xf(s,b,A),xf(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=Sf(),l=await R(c),d=l?rC(await nC(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 vL(),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()}`]:[],...iC()],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"]:Ef(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(oo)?!0:!await t.detectCopilotSeat()}}},fC=IL();import{homedir as CC}from"node:os";import{join as Sr}from"node:path";import{constants as _L,chmod as PL,copyFile as TL,readFile as Pl}from"node:fs/promises";import{applyEdits as DL,modify as LL}from"jsonc-parser";import{readFile as hC,rm as RL}from"node:fs/promises";var mC="// Managed by anyray-connect: OpenCode trim carrier v1",OL=5e3,Tf=e=>`${mC}
|
|
121
121
|
import { spawn } from "node:child_process"
|
|
122
122
|
|
|
123
123
|
const hookCommand = ${JSON.stringify([e.command,...e.args])}
|
|
124
|
-
const hookTimeoutMs = ${
|
|
124
|
+
const hookTimeoutMs = ${OL}
|
|
125
125
|
|
|
126
126
|
const invokeHook = (payload) =>
|
|
127
127
|
new Promise((resolve) => {
|
|
@@ -188,38 +188,38 @@ export const AnyrayTrimPlugin = async () => ({
|
|
|
188
188
|
}
|
|
189
189
|
},
|
|
190
190
|
})
|
|
191
|
-
`,ei=async e=>await R(e)?(await
|
|
192
|
-
`)?"owned":"foreign":"absent",
|
|
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}},
|
|
191
|
+
`,ei=async e=>await R(e)?(await hC(e,"utf-8")).startsWith(`${mC}
|
|
192
|
+
`)?"owned":"foreign":"absent",yC=async(e,t)=>{let n=Tf(t),r=await ei(e);return r==="foreign"?"foreign":r==="owned"&&await hC(e,"utf-8")===n?"unchanged":(await pe(e,n),"installed")},Df=async e=>{let t=await ei(e);return t!=="owned"?t:(await RL(e,{force:!0}),"removed")};var Lf="https://opencode.ai/config.json",Hn="x-anyray-metadata",Ft="x-anyray-api-key",Nf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Bn="Authorization",vr=["anthropic","openai"],Kn="github-copilot",NL="header",Wn="anyray",$L=()=>process.env.XDG_CONFIG_HOME?.trim()||Sr(CC(),".config"),ML=()=>process.env.XDG_DATA_HOME?.trim()||Sr(CC(),".local","share"),Tl=()=>Sr($L(),"opencode"),Ol=()=>Sr(Tl(),"plugins","anyrayTrim.js"),AC=()=>Sr(ML(),"opencode"),vC=async()=>{try{let e=await Pl(Sr(AC(),"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}}},gC=async()=>(await vC()).chatGptOAuth,UL=["opencode.jsonc","opencode.json","config.json"],ca=async()=>{let e=Tl(),t=[];for(let n of UL){let r=Sr(e,n);await R(r)&&t.push(r)}return t},wC=async()=>(await ca())[0]??Sr(Tl(),"opencode.json"),ia=async e=>{let t=await R(e),n=t?await Pl(e,"utf8"):`{}
|
|
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}},SC=(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(...SC(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}]},bC=async(e,t,n,r)=>{let o=SC(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await TL(e,`${e}.anyray-bak`,_L.COPYFILE_EXCL),await PL(`${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
|
-
`},s=t.raw;for(let i of o)s=
|
|
197
|
+
`},s=t.raw;for(let i of o)s=DL(s,LL(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 _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:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjEuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F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Xlsb2FkU2Vzc2lvbklkZW50aXR5KAogICAgICAgICAgcGF5bG9hZCBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPiwKICAgICAgICAgIHNlc3Npb25JZAogICAgICAgICk7CiAgICAgIH0KICAgICAgcmV0dXJuIGNhbGxlck9uUGF5bG9hZCA/IGNhbGxlck9uUGF5bG9hZChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpIDogcGF5bG9hZDsKICAgIH07CiAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdHMpOwogIH07CiAgcmV0dXJuIHdyYXBwZWQ7Cn07Cg=="}];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"},
|
|
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}},
|
|
199
|
+
`),!0},FL=async e=>{try{let t=ze(await Pl(`${e}.anyray-bak`,"utf8"));return B(t)?t:void 0}catch{return}},$f=()=>eC(process.env.ANYRAY_COPILOT_PLAN),Mf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${$f()}/${NL}`,B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},BL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===vr[0]||n===vr[1]||n===Kn?[]:B(r)&&B(r.options)&&Hf(r.options.baseURL,t)?[n]:[]),Uf=/claude/i,Kf=["model","small_model"],EC=(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)||!Uf.test(o)))return`${vr[0]}/${o}`},Ff=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Ff(n,t);return t}if(!B(e))return t;for(let[n,r]of Object.entries(e))Kf.includes(n)&&typeof r=="string"?t.push(r):Ff(r,t);return t},WL=(e,t,n)=>{if(!B(e)||!B(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Uf.test(a)))return!1;let o=`${n}/`;return Ff(t).filter(a=>a.startsWith(o)).every(a=>Uf.test(a.slice(o.length)))},Bf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Bf(o,t,n));if(!B(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Kf.includes(o)?EC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Bf(a,t,n)}return r},Wf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Wf(o,t[a],n));if(!B(e)||!B(t))return e;let r={};for(let[o,a]of Object.entries(e))Kf.includes(o)&&typeof a=="string"&&EC(t[o],n)===a?r[o]=t[o]:r[o]=Wf(a,t[o],n);return r},HL=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")},_l=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),KL=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return B(t)&&t.tool==="opencode"}catch{return!1}},Gf=e=>X(e,"copilot")&&!!e.clientKey,GL=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".`]:[],jL=(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.`]:[],VL=e=>Gf(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."]:[],YL=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Lf);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=BL(a,t.origin),i=s.every(y=>WL(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=Bf(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 Nf)delete v[E]}v[Ft]=p,h&&(v[Hn]=h),A.headers=v,b.options=A,a[y]=b}let g=c.length===0&&Gf(t);if(g){let y=B(a[Kn])?{...a[Kn]}:{},b=B(y.options)?{...y.options}:{};b.baseURL=Mf(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}},ZL=["baseURL","apiKey"],kC=(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=_l(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"||Nf.some(h=>h in f);if(!o&&!p)return!1;for(let h of ZL)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,...Nf])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},JL=(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)&&_l(a[Ft])&&(delete a[Ft],i=!0),!(Hn in s)&&KL(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},XL=(e,t)=>{let n={...e},r=!1,o=HL(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===Lf&&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)kC(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;JL(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&B(u)&&B(u.options)&&Hf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Wf(n,t,l))}return kC(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===Lf&&(delete n.$schema,r=!0),{next:n,removed:r}},xC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=Tl(),t=AC(),n=await R(e)||await R(t),r=n&&await gC();return{installed:n,detail:n?`${await wC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await wC(),r=e.openaiBaseUrl,o=de({...e.metadata,tool:"opencode"}),a=Gf(e),s=X(e,"openai"),i=await gC(),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(Mf(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}=YL(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)"}`,...GL(e),...jL(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Mf(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. ${$f()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${$f()} 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).",...VL(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 bC(n,c,d,!0)?[n]:[],x=Ol();if(le())try{let C=await yC(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 Df(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))&&Hf(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(Ol());e=i==="absent"?"missing":i,e==="owned"&&(t=await Pl(Ol(),"utf-8")===Tf(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 vC(),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(_l(c[Ft])||_l(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=Ol(),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}=XL(c.data,await FL(i));d&&(await bC(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 Df(n)==="removed"&&(a.push(n),o.push(`removed the Anyray OpenCode trim carrier from ${n}`))}catch{o.push(`Could not remove the Anyray OpenCode trim carrier from ${n}. Remove that file manually.`)}return a.length===0&&s.length===0&&o.push("no Anyray provider settings found"),{status:a.length===0&&s.length>0?"manual":"reverted",messages:o,changedFiles:a.length?a:void 0}}};import{homedir as PC}from"node:os";import{join as Ll}from"node:path";import{constants as tN,chmod as nN,copyFile as rN,readFile as TC}from"node:fs/promises";import{applyEdits as oN,modify as aN}from"jsonc-parser";import{homedir as qL}from"node:os";import{dirname as zL,join as ni}from"node:path";import{mkdir as QL,readFile as RC,rm as eN}from"node:fs/promises";var jf="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",IC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfQogICAgfQogIH0sCiAgImNvbmZpZ1NjaGVtYSI6IHsKICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAiYWRkaXRpb25hbFByb3BlcnRpZXMiOiBmYWxzZSwKICAgICJyZXF1aXJlZCI6IFsiZ2F0ZXdheVVybCJdLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkFueXJheSBnYXRld2F5IG9yaWdpbiwgZS5nLiBodHRwczovL2dhdGV3YXkuZXhhbXBsZS5hbnlyYXkuYWkgKG5vIC92MSBzdWZmaXgpLiIKICAgICAgfSwKICAgICAgImFwaUtleSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJQZXJzb25hbCBBbnlyYXkgY2xpZW50IGtleSAoYXJrX+KApikuIFN1cHBvcnRzICR7RU5WX1ZBUn0gc3Vic3RpdHV0aW9uOyBkZWZhdWx0cyB0byAke0FOWVJBWV9DTElFTlRfS0VZfS4iCiAgICAgIH0sCiAgICAgICJ1c2VyIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkF0dHJpYnV0aW9uIHVzZXIgKGNvbnRlbnQtZnJlZTsgdXN1YWxseSBhbiBlbWFpbCkuIE9wdGlvbmFsIOKAlCB0aGUgY2xpZW50IGtleSBhbHJlYWR5IGF0dHJpYnV0ZXMgdGhlIGVucm9sbGVkIHVzZXIuIgogICAgICB9LAogICAgICAidGVhbSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB0ZWFtIChjb250ZW50LWZyZWUpLiBPcHRpb25hbC4iCiAgICAgIH0KICAgIH0sCiAgICAidWlIaW50cyI6IHsKICAgICAgImdhdGV3YXlVcmwiOiB7CiAgICAgICAgImxhYmVsIjogIkdhdGV3YXkgVVJMIiwKICAgICAgICAiaGVscCI6ICJZb3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IG9yaWdpbi4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgImxhYmVsIjogIkNsaWVudCBrZXkiLAogICAgICAgICJoZWxwIjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudC4gTGVhdmUgdW5zZXQgdG8gcmVhZCAkQU5ZUkFZX0NMSUVOVF9LRVkuIgogICAgICB9CiAgICB9CiAgfQp9Cg=="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjEuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZ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3duPiwKICAgICAgICAgIHNlc3Npb25JZAogICAgICAgICk7CiAgICAgIH0KICAgICAgcmV0dXJuIGNhbGxlck9uUGF5bG9hZCA/IGNhbGxlck9uUGF5bG9hZChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpIDogcGF5bG9hZDsKICAgIH07CiAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdHMpOwogIH07CiAgcmV0dXJuIHdyYXBwZWQ7Cn07Cg=="}];var Vf=".anyray-source-sha",on=()=>ni(qL(),".anyray","openclaw-plugin"),OC=async(e=on())=>{try{if((await RC(ni(e,Vf),"utf8")).trim()===jf)return"current"}catch{}for(let t of IC){let n=ni(e,t.path);await QL(zL(n),{recursive:!0,mode:448}),await pe(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await pe(ni(e,Vf),`${jf}
|
|
200
|
+
`),"installed"},Dl=async(e=on())=>{try{await RC(ni(e,Vf),"utf8")}catch{return!1}return await eN(e,{recursive:!0,force:!0}),!0};var Xf="x-anyray-metadata",la="x-anyray-api-key",qf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],so="Authorization",io="anthropic-beta",Nl="interleaved-thinking-2025-05-14",$l=["anthropic","openai"],DC="short",Qf="anthropic-messages",eh=32e3,Ml="anthropic/claude-sonnet-4-5",th=["anthropic/claude-haiku-4-5"],nh="anyray/claude-sonnet-4-5",rh=["anyray/claude-haiku-4-5"],sN=[Ml,nh],iN=[th,rh],Qe="anyray",Er="ANYRAY_API_KEY",oi="openclaw",LC=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Ll(PC(),".openclaw"),ao=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Ll(LC(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_C=(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 TC(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}},NC=(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(...NC(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}]},Yf=async(e,t,n,r)=>{let o=NC(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await rN(e,`${e}.anyray-bak`,tN.COPYFILE_EXCL),await nN(`${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
|
-
`},s=t.raw;for(let i of o)s=
|
|
205
|
+
`},s=t.raw;for(let i of o)s=oN(s,aN(s,i.path,i.value,{formattingOptions:a}));return await pe(e,s.endsWith(`
|
|
206
206
|
`)?s:`${s}
|
|
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
|
-
`)){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}},
|
|
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 ${
|
|
211
|
-
`),
|
|
212
|
-
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,
|
|
213
|
-
`)},
|
|
207
|
+
`),!0},Zf=async e=>{try{let t=ze(await TC(`${e}.anyray-bak`,"utf8"));return N(t)?t:void 0}catch{return}},zf=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},cN=(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=$l.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=Qf,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=eh)),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 qf)delete x[C]}x[la]=r,o&&(x[Xf]=o),v==="anthropic"&&(io in x?c=x[io]!==Nl:x[io]=Nl),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=DC,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?nh:Ml,w=!0,E.model=C,"fallbacks"in C||(C.fallbacks=p?[...rh]:[...th],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}},lN=["baseUrl","apiKey","api","maxTokens"],Jf=(e,t,n=$l,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=zf(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[Xf]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||qf.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===eh:v==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let v of lN)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,Xf,...qf,..."x-anyray-custom-host"in h?[so]:[]];h[io]===Nl&&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===DC&&("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:{};sN.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),iN.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}},$C={id:oi,title:"OpenClaw",automatic:!0,async detect(){let e=await R(ao())||await R(LC());return{installed:e,detail:e?ao():`no ${Ll(PC(),".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}=Jf(x.data,await Zf(n),$l,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 Yf(n,x,C,!1),await se(n),await Dl(),{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 Dl(),{status:"held",messages:E})}let r=on(),o=!1;if(!t.dryRun)try{await OC(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": ${eh}, "apiKey": "<your personal ark_ key>", "headers": { "${la}": "<your personal ark_ key>", "${io}": "${Nl}" } }`,` "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. "${Ml}") 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}=cN(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=Jf(g,await Zf(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?nh:Ml} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?rh:th).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 Yf(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(zf(t)))if(N(a)&&_C(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)&&_C(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[ao(),Ll(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(zf(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}=Jf(n.data,await Zf(t),$l,on()),a=await Dl();return o?(await Yf(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 QM}from"node:child_process";import{readFile as eU}from"node:fs/promises";import{homedir as vi,platform as Ir}from"node:os";import{join as xn}from"node:path";import{isDeepStrictEqual as Kh,promisify as tU}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},Ul=(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 yM}from"node:crypto";import{promises as ZA}from"node:fs";import{platform as gM,tmpdir as wM}from"node:os";import{join as nd}from"node:path";import{execFile as dN}from"node:child_process";import{promises as si}from"node:fs";import{homedir as uN,platform as pN}from"node:os";import{delimiter as fN,join as Fl}from"node:path";import{promisify as hN}from"node:util";var mN=hN(dN),yN=15*6e4,gN=64*1024*1024,wN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],MC=async(e={})=>{let t=(e.home??uN)(),n=e.env??process.env,r=wN(e.runtimePlatform??pN()),o=[Fl(t,".local","bin"),Fl(t,".claude","local"),...(n.PATH??"").split(fN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Fl(a,`claude${s}`);try{return await si.access(i),i}catch{}}return null},bN=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},kN=async e=>{let t=Fl(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(!vN.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},CN=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:bN(n.projectList)}},AN=async e=>{let t,n;try{let r=await si.readFile(e,"utf8");for(let o of r.split(`
|
|
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}},vN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,SN=/\.(?:cmd|bat)$/i,EN=(e,t)=>SN.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},UC=async(e,t={})=>{let n=t.exec??mN,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=EN(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:yN,maxBuffer:gN,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=CN(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 AN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await kN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as xN}from"node:crypto";import{promises as Gn}from"node:fs";import{homedir as IN,platform as RN}from"node:os";import{join as xt}from"node:path";var FC=448,jn="local_",ON="local-agent-mode-sessions",oh="-3p",_N="cowork_account_settings.json",co=(e={})=>{let t=(e.home??IN)(),n=e.runtimePlatform??RN(),r=e.env??process.env;if(n==="darwin")return xt(t,"Library","Application Support",`Claude${oh}`);if(n==="win32"){let o=r.LOCALAPPDATA??xt(t,"AppData","Local");return xt(o,`Claude${oh}`)}return null},ii=(e={})=>{let t=co(e);return t?t.slice(0,-oh.length):null},ah=e=>{let t=e.replace(/[^a-zA-Z0-9]/g,"-");if(t.length<=200)return t;let n=0;for(let r=0;r<e.length;r+=1)n=Math.imul(n,31)+e.charCodeAt(r)|0;return`${t.slice(0,200)}-${Math.abs(n).toString(36)}`},Bl=async e=>{let t=xt(e,ON),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,_N)),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]}},sh=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),PN=async(e,t)=>{let n=`${jn}${t.sessionId}`,r=xt(e,n),o=xt(r,"outputs"),a=xt(r,".claude"),s=xt(a,"projects",ah(o));await Gn.mkdir(o,{recursive:!0,mode:FC}),await Gn.mkdir(s,{recursive:!0,mode:FC});let i=xt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${xN()}`;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})},BC=async(e,t)=>{let n=await sh(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 PN(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 TN}from"node:os";import{dirname as DN,join as ci}from"node:path";var LN=448,NN=["Documents","Claude","Projects"],$N="spaces.json",MN=(e={})=>ci((e.home??TN)(),...NN),UN=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}}},FN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},ih=async e=>{try{return await ua.access(e),!0}catch{return!1}},BN=async(e,t,n)=>{let r=ci(t,FN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await ih(r)?o:r;return a===o&&await ih(o)?null:(await ua.mkdir(DN(a),{recursive:!0}),await ua.cp(e,a,{recursive:!0}),a)},WN=async e=>{try{let t=(await ua.readFile(ci(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},WC=async e=>{let t=MN({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,$N),{spaces:a,readable:s}=await UN(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 ih(d)){n.failed+=1;continue}let u=await BN(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await WN(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:LN}),await J(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as jN}from"node:crypto";import{execFile as VN,spawnSync as zC}from"node:child_process";import{constants as QC}from"node:fs";import{access as Vl,chmod as YN,mkdir as ZN,readdir as JN,readFile as lh,rename as XN,rm as fa,stat as eA,writeFile as qN}from"node:fs/promises";import{homedir as zN,platform as QN,userInfo as e$}from"node:os";import{basename as t$,dirname as tA,isAbsolute as ha,join as Bt,resolve as VC}from"node:path";import{isDeepStrictEqual as di,promisify as n$}from"node:util";var li="__anyray-claude-desktop-credential";var Wl=["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>`."],Hl=["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."],HC="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 Kl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],KC=["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"],HN=new Set(KC),KN=new Set(KC.map(e=>e.toLowerCase())),GN=new Set(Kl.map(e=>e.toLowerCase())),Gl=(e,t=!1)=>(t?KN:HN).has(t?e.toLowerCase():e),GC=(e,t=!1)=>t?GN.has(e.toLowerCase()):Kl.some(n=>n===e),jC=["*"],lo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...jC]}),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}$/,nA="Anyray",dh=4,hi=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],mi=["deploymentMode","awaitingSignIn"],rA=[...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 Vl(e),!0}catch{return!1}},r$=async e=>{try{let t=await JN(tA(e)),n=t$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},o$=async e=>{try{return await Vl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":r$(e)}},an=(e={})=>{let t=(e.home??zN)(),n=(e.username??(()=>e$().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}},Yl=()=>{let e=zC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},oA=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],a$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...oA(t)]}},uh=(e="json")=>{let t=pn(oA(e)),n=VC(t.command),r=VC(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)}},s$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,ph=e=>[e.command,...e.args].map(s$).join(" "),i$=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")},aA=(e,t)=>{i$(e);let n=Zl(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}`)},sA=e=>(aA(e,"--json"),`#!/bin/sh
|
|
210
|
+
exec ${ph(e)}
|
|
211
|
+
`),c$=`#!/bin/sh
|
|
212
|
+
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,iA=e=>{aA(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 ${ph(t)}`,""].join(`
|
|
213
|
+
`)},l$=e=>e.args.at(-1)==="--passthrough-headers"?iA(e):sA(e),Zl=e=>/[\\/](node|node\.exe)$/i.test(e),fh=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++}},d$=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`,
|
|
218
|
-
`)},
|
|
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]}}},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
|
-
`)),
|
|
222
|
-
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${
|
|
216
|
+
`)||n.includes("\r"))return;let r=fh(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Zl(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 sA(i)===e?i:void 0}catch{return}},u$=e=>{if(!e.startsWith(c$))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=fh(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 iA(a)===e?a:void 0}catch{return}},p$=`#!/bin/sh
|
|
217
|
+
# Anyray subscription pass-through credential helper`,f$=e=>{let t=Zl(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=$(${ph(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
|
+
`)},h$=e=>{if(!e.startsWith(p$))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=fh(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return f$(a)===e?a:void 0},cA=e=>d$(e)??u$(e)??h$(e),m$=async()=>{let e=zC("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},y$=async e=>{let t=[e.command,...Zl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>eA(r)))).every(r=>r.isFile())?(await Vl(e.command,QC.X_OK),!0):!1}catch{return!1}},g$=0,Jl=async(e,t,n)=>{await ZN(tA(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${g$++}.tmp`;try{await qN(r,t,{mode:n}),await YN(r,n),await XN(r,e)}catch(o){throw await fa(r,{force:!0}).catch(()=>{}),o}},Vn=async(e,t)=>{await Jl(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 lh(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 eA(e);return{present:!0,content:await lh(e,"utf-8"),mode:t.mode&511}},lA=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:dt(e[t])}:{present:!1},ch=(e,t,n)=>{n.present?e[t]=dt(n.value):delete e[t]},YC=e=>vn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),w$=e=>vn(e)&&YC(e.original)&&YC(e.lastWritten),b$=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),ZC=(e,t)=>vn(e)&&t.every(n=>w$(e[n])),k$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],C$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],hh=(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!==nA||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!ZC(e.config,r)||r.some(o=>e.config[o].original.present)||!ZC(e.deployment,mi)||!vn(e.helper)||e.helper.path!==t.helper||!b$(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),A$=(e,t)=>hh(e,t,dh,hi),v$=(e,t)=>hh(e,t,2,k$),S$=(e,t)=>hh(e,t,3,C$),E$=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),JC=e=>({...e,version:dh,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),mh=async e=>{if(!await pi(e.journal))return;let t;try{t=JSON.parse(await lh(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(A$(t,e))return t;if(S$(t,e))return JC(t);if(v$(t,e))return JC(E$(t));throw new Error(`${e.journal} is not a valid ownership journal`)},XC=async(e,t)=>{await Jl(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},x$=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:nA};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}}},dA=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),R$=async(e,t,n,r,o,a,s)=>{let i=dA(),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??lA(r.value,d),lastWritten:i[d]}]));return{version:dh,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}:{}}}},jl=e=>({status:"manual",messages:[e]}),O$=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}`)]}},_$=n$(VN),P$=new Set(Kl),T$=async e=>{try{let{stdout:t}=await _$("/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??T$;for(let r of e.managedPolicies){let o=await o$(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=>Gl(i)&&!P$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},yh=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.`},gh=e=>(e.platform??QN)()==="darwin",uA=async(e,t,n={})=>{if(!gh(n))return jl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Yl)()&&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:yh(a)}),r.length>0)return O$(r);let s=!1,i=!1,c=[o.journal];try{let l=X(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??m$)())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=a$((n.credentialCommand??(()=>uh(d)))(),d),f=l$(u),p=await mh(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 x$(o,p,n.randomUUID??jN),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 R$(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 XC(o.journal,A),i=!0,await Jl(o.helper,f,448),A.helper.previousWritten!==void 0&&(delete A.helper.previousWritten,await XC(o.journal,A));let v=dt(g.value);for(let C of hi)ch(v,C,b[C]);await Vn(w,v),m.metaToWrite&&await Vn(o.meta,m.metaToWrite);let E=dt(y.value),x=dA();for(let C of mi)ch(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.",...Wl]}}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.`]}:jl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},qC=(e,t,n,r)=>{let o=dt(e);for(let a of n){let s=t[a];di(lA(e,a),s.lastWritten)?ch(o,a,s.original):r.push(a)}return o},pA=async(e,t={})=>{if(!gh(t))return{status:"not-found",messages:[]};if((t.appRunning??Yl)())return jl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=an(t);try{let r=await mh(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=qC(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=qC(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 Jl(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?[]:Hl]}}catch(r){return jl(`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.`)}},wh=async(e,t={})=>{if(!gh(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 Vl(n.helper,QC.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}},fA=async(e={})=>{try{let t=an(e),n=await yi(t.helper);if(!n.present||typeof n.content!="string")return;let r=cA(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},hA=async(e,t={})=>{if(!await wh(e,t))return!1;let n=an(t);try{let r=await mh(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=cA(a.content??"");return s?await(t.helperLauncherAvailable??y$)(s):!1}catch{return!1}};import{createHash as _A,randomUUID as PA}from"node:crypto";import{spawn as D$,spawnSync as L$}from"node:child_process";import{link as Eh,mkdir as bh,open as TA,readFile as kh,readdir as DA,rename as LA,rm as sn,stat as NA}from"node:fs/promises";import{homedir as xh}from"node:os";import{basename as $A,dirname as wi,join as Ca,win32 as N$}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],mA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",Aa],yA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",Aa],gA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",Aa],MA="Managed by anyray-connect; dynamic credential only.",$$=e=>/^[A-Za-z]:[\\/]/.test(e)&&N$.isAbsolute(e),wA=e=>{if(!$$(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)},UA=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!wA(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&&!wA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},Ih=(e={})=>Ca((e.home??xh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),M$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},U$=e=>(UA(e),["@echo off",`REM ${MA}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(M$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
221
|
+
`)),F$=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},FA=e=>{let t=e.split(`\r
|
|
222
|
+
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${MA}`||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(F$);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return UA(s),s}catch{return}},B$=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>NA(r)))).every(r=>r.isFile())}catch{return!1}},W$=async(e,t)=>{let n=FA(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??B$)(n)}catch{return!1}},Ch=e=>({sha256:po(e),content:e}),bA=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Wt(t,["sha256","content"])&&J$(t.sha256)&&typeof t.content=="string"&&po(t.content)===t.sha256&&FA(t.content)!==void 0},Rh=()=>{let e=L$("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??"")},H$=async(e,t)=>{await bh(wi(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await TA(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await Eh(n,e)}finally{await sn(n,{force:!0}).catch(()=>{})}},K$=e=>`${$A(e)}.anyray-old-`,G$=e=>`${e}.anyray-old-${process.pid}-${PA()}`,BA=async(e,t)=>{try{await Eh(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await sn(t,{force:!0}),!0},ql=async(e,t,n,r,o)=>{let a=G$(e),s=n===void 0?void 0:po(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${PA()}`,c=!1;try{if(i&&n!==void 0){let d=await TA(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 LA(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 Eh(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 BA(e,a).catch(()=>!1),l}finally{i&&await sn(i,{force:!0}).catch(()=>{})}},Ah=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,j$=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=
|
|
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(),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{}})()},
|
|
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(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{}})()},
|
|
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(`
|
|
291
|
+
}`,Zn=async e=>new Promise((t,n)=>{let r=D$("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",j$],{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(Ah(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(Ah({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??xh)(),".anyray","claude-desktop-windows.json"),V$=e=>Ca((e.home??xh)(),".anyray","claude-desktop-windows.lock"),wa=class extends Error{},Y$=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Oh=async e=>{let t=V$(e);await bh(wi(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=_A("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=Ca(t,"owner.json");try{await bh(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 kh(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!Y$(i.pid)}catch{try{s=Date.now()-(await NA(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 kh(o,"utf8")).nonce===r&&await sn(t,{recursive:!0,force:!0})}catch{}}}throw new wa},WA=()=>Object.fromEntries($e.map(e=>[e,{present:!1}])),po=e=>_A("sha256").update(e).digest("hex"),Z$=(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)),ed=(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},kA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,$e)&&$e.every(t=>ed(e[t],t)),CA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,mA)&&mA.every(t=>ed(e[t],t)),J$=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),_h=(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===Ih(t)&&(n.lastWritten===void 0||bA(n.lastWritten))&&(n.pending===void 0||bA(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},X$=(e,t)=>Wt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Ql&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&kA(e.lastWritten)&&(e.pending===void 0||kA(e.pending))&&_h(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),q$=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"&&CA(e.lastWritten)&&(e.pending===void 0||CA(e.pending)),AA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,yA)&&yA.every(t=>ed(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===3&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&AA(e.lastWritten)&&(e.pending===void 0||AA(e.pending))&&_h(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),vA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Wt(e,gA)&&gA.every(t=>ed(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===4&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&vA(e.lastWritten)&&(e.pending===void 0||vA(e.pending))&&_h(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),SA=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),Ph=e=>{let{pending:t,...n}=e;return{...n,version:Ql,lastWritten:SA(e.lastWritten),...t?{pending:SA(t)}:{}}},EA=e=>({...e,chatTabEnabled:{present:!1}}),eM=e=>{let{pending:t,...n}=e;return Ph({...n,version:4,lastWritten:EA(e.lastWritten),...t?{pending:EA(t)}:{}})},xA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),tM=(e,t)=>Ph({version:4,registryKey:_e,keyExisted:e.keyExisted,lastWritten:xA(e.lastWritten),...e.pending?{pending:xA(e.pending)}:{},helper:{path:Ih(t)}}),Th=async(e,t=!0)=>{let n=Ht(e),r=wi(n),o=`${$A(n)}.anyray-old-`,a=(await DA(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 LA(a[0],n):s=a[0]}let i=await F(s),c=q$(i)?tM(i,e):z$(i,e)?eM(i):Q$(i,e)?Ph(i):X$(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},IA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),nM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:_e,keyExisted:e.keyExisted,lastWritten:IA(e.lastWritten),...e.pending?{pending:IA(e.pending)}:{}}:e,Xl=async(e,t)=>{let n=Ht(t),r=`${JSON.stringify(nM(e),null,2)}
|
|
293
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await pe(n,r)},rM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,oM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),aM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),sM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),iM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===sM(t).toUpperCase(),RA=(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},cM=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,lM=(e,t)=>{if(!Gl(e,!0))return!1;let n=cM(t);if(aM.has(n))return!1;if(oM.has(n))return n==="REG_EXPAND_SZ"?!0:!GC(e,!0)},dM=(e,t)=>{let n=WA(),r=!1,o=!1,a=!1,s=t.toUpperCase()===gi.toUpperCase(),i=(l,d)=>{if(!s)return;let u=lM(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),RA(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||iM(d,t))continue;let u=rM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),RA(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:WA(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return dM(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},Dh=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 td=(e,t)=>pa(lo(e,t)),HA=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],uM=(e,t)=>{let n=td(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}]}))},pM=(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}}),fM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,vh=e=>Object.fromEntries($e.map(t=>[t,Z$(t,e[t])])),OA=(e,t,n,r)=>({version:Ql,registryKey:_e,keyExisted:e,lastWritten:vh(t),helper:{path:n,lastWritten:Ch(r)}}),hM=(e,t,n,r,o,a)=>({version:Ql,registryKey:_e,keyExisted:e,lastWritten:vh(t),pending:vh(n),helper:{path:r,...o?{lastWritten:Ch(o)}:{},pending:Ch(a)}}),Sh=(e,t,n)=>ya(n,e.lastWritten[t])||e.pending!==void 0&&ya(n,e.pending[t]),ba=async e=>{try{let t=await kh(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,zl=async(e,t)=>{let n=K$(e),r;try{r=await DA(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 BA(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")},Lh=async(e,t,n)=>(n.present?await e(HA(_e,t,n.value??"",n.type??"REG_SZ")):await e(["delete",_e,"/v",t,"/f"])).code===0,mM=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 Lh(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)]}}),KA=async(e,t,n,r={})=>{if(!xe(t))return et("A valid personal ark_ gateway key is required.",!1,r);let o=Ih(r),a;try{a=U$((r.credentialCommand??uh)())}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 Oh(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(Dh(m),!1,r);let w=await Th(r,!n.dryRun);n.dryRun||await zl(o,w);let g=await Yn(i),y=uM(e,o),b=await ba(o),A=b?.sha256,v=!1;if(d=w,u=g,f=y,w){let C=$e.find(I=>!Sh(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=fM(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[$],pM(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 Xl(OA(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??Rh)()}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=hM(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 Xl(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 Lh(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 H$(o,a):await ql(o,A,a,"apply",r)),await ka(o)!==s)throw new Error("credential helper verification failed");return await Xl(OA(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.",...Wl]}}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 zl(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 ql(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await ka(o)===p.helper.lastWritten.sha256):await ql(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await mM(i,u.values,f))return d?await Xl(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?.()}},GA=async(e,t={})=>{let n=t.runReg??Zn,r=Ht(t),o;if(!e.dryRun)try{o=await Oh(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 Th(t,!e.dryRun);a&&!e.dryRun&&await zl(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&&!Sh(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(!Sh(a,p,m)){u.add(p);continue}await Lh(n,p,{present:!1})||(d=!0)}}let f=await ka(a.helper.path);if(f!==void 0)if(ga(a,f))try{await ql(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?[]:Hl]})}catch{return et(`Could not safely inspect or revert ${_e}; no unproven value was removed.`,!1,t)}finally{await o?.()}},jA=async(e,t={})=>{let n=t.runReg??Zn;if(!await R(Ht(t)))return;let r;try{r=await Oh(t);let o=await Th(t);if(o&&await zl(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 W$(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?.()}},VA=async(e,t={})=>await jA(e,t)!==void 0,YA=async(e,t={})=>await jA(e,t)==="dynamic";var va=(e=gM())=>e==="win32"?Rh:Yl,Nh="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",rd=async(e,t={})=>{let n=(t.profileRoot??co)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Nh};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 ZA.access(e)}catch{return{ok:!1,reason:`no such file: ${e}`,remedy:"Point at the .zip Anthropic emailed you (claude.ai -> Settings -> Privacy -> Export data)."}}let r=await Bl(n);if(!r.ok)return r.reason==="ambiguous"?{ok:!1,reason:"this Claude Desktop profile holds more than one account",remedy:"Choosing which one gets the history is your call, not ours \u2014 "+Nh}:{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??MC)();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=nd(t.stagingRoot??wM(),`anyray-history-${process.pid}-${yM()}`);try{let s=await(t.runImporter??UC)({binary:o,exportPath:e,configDir:nd(a,"config"),workDir:nd(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. "+Nh};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 BC(r.dir,s.conversations),c=await WC({stagedProjectsDir:nd(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 ZA.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Rt}from"node:fs";import{homedir as BM}from"node:os";import{join as ln,sep as WM}from"node:path";import{isDeepStrictEqual as id}from"node:util";import{constants as bM}from"node:fs";import{promises as G}from"node:fs";import{dirname as Sa,isAbsolute as Mh,join as ne,relative as od,resolve as cn,sep as bi}from"node:path";import{randomUUID as cd}from"node:crypto";var En=448,ki=384,zA=448,kM=4,Uh=3e4,QA=5e3,CM=10*6e4,$h=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"),ev=(e,t)=>{let n=od(cn(e),cn(t));return n===""||!n.startsWith(`..${bi}`)&&n!==".."&&!Mh(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,AM=e=>{try{return process.kill(e,0),!0}catch(t){return It(t)&&t.code==="EPERM"}},tv=e=>e===0?"owner.json":`owner.${e}.json`,ad=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}},nv=e=>{if(e.pid===void 0||!AM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Uh&&t-e.createdAtMs>CM},vM=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(Sa(t),{recursive:!0,mode:En});let n=cd(),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 ad(t);if(d){if(!nv(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)<=Uh)return}let l=ne(t,tv(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{}})()},QA);return s.unref(),async()=>{clearInterval(s);try{(await ad(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},SM=async(e,t,n)=>{await G.mkdir(Sa(e),{recursive:!0,mode:En});let r=await vM(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}-${cd()}`;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()}},ld=async(e,t)=>{for(let n=0;n<kM;n+=1){let r=await fo(e);if(!r)return"failed";let o=t(r.value);if(!o||id(o,r.value))return"unchanged";try{if(await SM(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},JA=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},dd=async e=>{let t=[];for(let n of await JA(e))for(let r of await JA(ne(e,n)))t.push(ne(e,n,r));return t},EM=e=>Array.isArray(e.skills)?e.skills.filter(t=>ut(t)&&Ci(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],xM=async e=>{let t=ne(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await dd(t)){let o=await fo(ne(r,"manifest.json"));if(!o)continue;let a=r.split(bi).at(-1)??"";for(let s of EM(o.value))n.push({account:a,packageDir:r,entry:s})}return n},IM=async e=>{let t=await fo(ne(e,".claude-plugin","plugin.json"));return!!t&&Ci(t.value.name)},RM=(e,t)=>{let n=Mh(t)?cn(t):cn(e,t);if(!ev(e,n)||n===cn(e))return;let r=od(cn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},OM=async e=>{let t=await dd(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=RM(o,l.installPath);!d||!await IM(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},_M=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)))},rv=async e=>{let[t,n,r]=await Promise.all([xM(e),OM(e),_M(e)]);return{skills:t,plugins:n,localMcpServers:r}},Fh=async e=>{let t=await rv(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)}},XA=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)},PM=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?zA:ki)}}};await t(e),await G.chmod(e,En)},ov=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},sd=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(!id(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 sd(ne(e,s),ne(t,s)))return!1}else if(!i.isFile()||!await ov(ne(e,s),ne(t,s)))return!1}return!0}catch{return!1}},av=e=>`${e}.anyray-incomplete`,sv=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=cd(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await ad(e)}catch{return}if(f){if(!nv(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)<=Uh)return}let u=ne(e,tv(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{}})()},QA);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await ad(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},iv=async e=>{let t=await sv(e,!1);t&&await t.complete()},TM=async(e,t,n)=>{let r=av(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await sd(e,t))return await iv(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 sv(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,bM.COPYFILE_EXCL);let h=await G.stat(f);await G.chmod(p,(h.mode&73)!==0?zA:ki)}catch(h){if(!It(h)||h.code!=="EEXIST")throw h;if(!await ov(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 sd(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},cv=async(e,t,n,r)=>{if(!await XA(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await sd(e,t))return await iv(av(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-${cd()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await XA(o)?(await PM(o),await n?.(t),await TM(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},qA=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),DM=async e=>{let t=await dd(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"}},LM=async e=>{let t=await dd(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"}},NM=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 cv(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 ld(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}},lv=(e,t)=>({...e,installPath:t}),$M=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=Mh(r.installPath)?cn(r.installPath):cn(o,r.installPath),s=lv(e,od(cn(t),cn(n))),i={...r,installPath:od(cn(o),a)};return id(s,i)},MM=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":ld(t,a=>{let s=ut(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},UM=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(!ev(a,l)){n.invalid+=1;continue}let d=await cv(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 ld(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=$M(c.entry,Sa(c.settingsFile),c.packageDir,y,t),f=!u;return}let b=lv(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 MM(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},FM=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 ld(r,c=>{let l=ut(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=id(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}},dv=async(e,t,n={})=>{let r=await rv(e),o=$h("skill"),a=$h("plugin"),s=$h("local-mcp"),i=[],c=[],l=qA(r.skills,n.account,n.allAccounts),d=qA(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 DM(t);f.state==="found"?await NM(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 LM(t);f.state==="found"?await UM(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await FM(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 HM=async e=>{try{return await Rt.access(e),!0}catch{return!1}},uv=448,KM=384,fv={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},GM=["code","cowork"],Hh=(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.",Bh=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),hv=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},jM=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[]}},VM=async(e,t)=>{let n=await hv(ln(e,fv[t])),r=[];for(let o of n){let a=await jM(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(WM).slice(-2)[0]})}return r},YM=async(e,t)=>{if(t==="cowork"){let r=await Bl(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await hv(ln(e,fv.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},ZM=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await Rt.copyFile(e,n),await Rt.chmod(n,KM),await Rt.rename(n,t)},JM=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",ah(r),`${o}.jsonl`)),!0)}catch{return!1}},XM=async(e,t,n,r)=>{let o=Bh(e),a=await sh(n);for(let s of t)await qM(e,s,n,r,a,o);return o},qM=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 JM(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:uv});for(let f of u)await Rt.cp(ln(l,f),ln(d,f),{recursive:!0,force:!1,errorOnExist:!0});await Rt.chmod(d,uv)}await ZM(c,ln(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},pv=(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
|
+
`)}},Wh=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),mv=async e=>{let t=[];for(let n of GM)t.push({lane:n,sources:await VM(e,n)});return t},yv=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([mv(t),Fh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Wh(n);for(let s of r.accounts)a.add(s);return{sessions:o,accounts:a.size,userSkills:r.skills,userPlugins:r.plugins,localMcpServers:r.localMcpServers}},ho=async(e={})=>{let t=(e.home??BM)(),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([mv(n),Fh(n)]),s;if(e.account){let p=e.account;for(let w of o)w.sources=w.sources.filter(g=>g.account.startsWith(p));let h=a.accounts.filter(w=>w.startsWith(p));if(o.every(w=>w.sources.length===0)&&h.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${p}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let m=Wh(o);for(let w of h)m.add(w);if(m.size>1)return pv(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=Wh(o);for(let h of a.accounts)p.add(h);if(p.size>1)return pv(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 HM(r),l=await dv(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(Bh(p));continue}let m=await YM(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(Bh(p));continue}d.push(await XM(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:Hh(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 zM=e=>[Ye(e)],gv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...zM(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 wv="1.21459.0",nU=tU(QM),rU=async e=>{try{let{stdout:t}=await nU("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},oU=async e=>{try{return await eU(e)}catch{return}},bv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",aU=["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?(kv??=Cv({}),kv):Cv(e),kv,Cv=async e=>{let t=(e.home??vi)(),n=["/Applications/Claude.app",xn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??rU,o=e.readClaudeAppBundle??oU;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} ${bv}`}),c=Ul(s,wv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${wv} or newer.`);let l=await o(xn(a,"Contents","Resources","app.asar"));return l?rA.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. ${bv}`}},ud="anyray",Sv="--anyray-owner=claude-desktop-v1",pd=(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")},Yh=(e={})=>xn((e.home??vi)(),"Library","Application Support","Claude","claude_desktop_config.json"),Ev=()=>{let e=Ve("profile");return{command:e.command,args:[...e.args,Sv]}},mo=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),xv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},sU=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),iU=e=>{if(!mo(e)||!xv(e,["command","args"]))return!1;let t=Ev();return e.command===t.command&&sU(e.args,t.args)},cU=e=>mo(e)&&Array.isArray(e.args)&&e.args.at(-1)===Sv,lU=e=>{if(!mo(e)||!xv(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))},dU=e=>e===void 0?"absent":iU(e)?"exact":cU(e)||lU(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)?.[ud];return{path:e,fileExisted:t,json:n,entry:o,ownership:dU(o)}},fd=e=>{if(e.ownership==="foreign")throw new He(`MCP name conflict in ${e.path}: mcpServers.${ud} 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[ud]:r[ud]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Gh=async(e,t)=>{if(Kh(e.entry,t))return;let n=await yo(e.path);if(!Kh(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}},jh=async e=>{let t=await yo(e.reading.path);if(!Kh(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)},uU=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(pd(e));fd(t);let n=Yh(e),r=(e.platform??Ir)()==="darwin"&&n!==t.path?await yo(n):void 0;return r&&fd(r),{active:t,...r?{legacy:r}:{}}},Av=async e=>{let t=await yo(pd(e));fd(t);let n=Yh(e),r=(e.platform??Ir)()==="darwin"&&n!==t.path?await yo(n):void 0;return r&&fd(r),{active:t,...r?{legacy:r}:{}}},pU=async e=>{let t=[];try{let n=await Gh(e.active,Ev());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Gh(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await jh(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 jh(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)}}},fU=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Gh(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await jh(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)},vv=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)."]},hU={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},hd="claude-desktop",Vh="migrate",Rv=new Set(["app-running","store-missing"]),mU={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},yU={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"}},gU="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",Ov=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"}},_v=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=mU[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.`:"")},Pv=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=yU[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=Ov(e),r=await(e.pendingDesktopMigrationCount??yv)(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=_v(a.lanes),l=Pv(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(hd,Vh);let m=f.reduce((y,b)=>y+b.waiting,0),w=[m>0?`${m} more session${m===1?"":"s"}`:"",p.length>0?`${p.length} extension ${p.length===1?"store":"stores"}`:""].filter(Boolean),g=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...h.length>0?[`Queued: ${h.length} portable configuration ${h.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...g]}if(!Rv.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(hd,Vh);let s=r.sessions+o,i=`${s} Claude Desktop local ${s===1?"item":"items"}`;return[a.kind==="store-missing"?`Queued: the ${i} still in your previous profile move across once Claude Desktop's new profile has been signed in to and the app is fully quit.`:`Queued: the ${i} still in your previous profile will move across the next time you fully quit Claude Desktop.`]}catch{return["Could not check whether Claude Desktop had existing sessions to bring across; run `anyray-connect migrate` if its lists look empty."]}},wU=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await gr(hd),[]}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."]}},bU=e=>gv({id:hd,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:",...vv(t)]:["Claude desktop org/API lane:",...vv(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`."]}),kU=(e={})=>{let t=bU(e),n=()=>(e.platform??Ir)()==="darwin",r=()=>(e.platform??Ir)()==="win32",o=(s,i)=>n()?uA(s,i,e):KA(s,s.clientKey??"",i,e),a=s=>n()?pA(s,e):GA(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??va((e.platform??Ir)()))(),quitTarget:hU,needsTarget:()=>!1,async complete(s){if(s!==Vh)return{status:"manual",messages:[`Claude Desktop could not service a queued "${s}" operation it does not recognise; the queue entry was dropped.`]};let i=await(e.migrateDesktopProfile??ho)(Ov(e));if(i.ok){let c=_v(i.lanes),l=Pv(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 Rv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?hA(s,e):r()?YA(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:[yh(p),...await Ai(e,i)]}}if(r()){let f;try{f=await xr(e.runReg??Zn)}catch{return{status:"manual",manualAudience:"admin",messages:[gU,...await Ai(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[Dh(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 uU(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 pU(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()?aU:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=pd(e),c=await wU(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 Av(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 fU(await Av(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=Yh(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(pd(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?wh(s,e):!1:r()?VA(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await Ea(e)).supported)return["unknown"];let s=await fA(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}}}},Tv=kU();import{homedir as ZU}from"node:os";import{join as JU}from"node:path";import{rm as vd}from"node:fs/promises";import{constants as Dv,accessSync as CU,statSync as AU}from"node:fs";import{platform as Zh}from"node:os";import{delimiter as vU,posix as SU,resolve as EU,win32 as xU}from"node:path";var IU="0.59.0",RU="1.1.4",Jn="Anyray \xB7 Claude",Xn="Anyray \xB7 Codex",md="__anyray-acp-agent",Lv=(e,t,n)=>{let{command:r,args:o}=pn([md,e,t,n]);return{command:r,args:o,env:{}}},yd=(e=Zh())=>e==="win32"?"npx.cmd":"npx",gd=(e=process.env.PATH,t=Zh())=>{if(!e)return;let n=yd(t);for(let r of e.split(vU)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=EU(o,n);try{if(!AU(a).isFile())continue;return CU(a,t==="win32"?Dv.F_OK:Dv.X_OK),a}catch{}}},wd=(e,t=Zh())=>{let n=t==="win32"?xU:SU;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==yd(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},OU="https://chatgpt.com/backend-api/codex",_U="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Nv="ANYRAY_ACP_CODEX_AUTHORIZATION",$v="ANYRAY_ACP_CODEX_CLIENT_KEY",Mv="ANYRAY_ACP_CODEX_METADATA",Uv=e=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),PU=(e,t={})=>{let n=X(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":OU,"x-anyray-forward-headers":_U}:{},o=n?{...e.clientKey?{"x-anyray-api-key":$v}:{}}:{Authorization:Nv};return Uv(e)&&(o["x-anyray-metadata"]=Mv),{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}}}:{}}},TU=e=>{let t=X(e,"openai"),n=Uv(e);return{...t?e.clientKey?{[$v]:e.clientKey}:{}:{[Nv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[Mv]:n}:{}}},Fv=(e,t=yd(),n={})=>({[Jn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${IU}`],env:fn(e).env},[Xn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${RU}`],env:{CODEX_CONFIG:JSON.stringify(PU(e,n)),...TU(e)}}}),Si=(e=yd(),t="jetbrains")=>({[Jn]:Lv("claude",e,t),[Xn]:Lv("codex",e,t)}),go=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as DU}from"node:zlib";import{open as LU,readFile as Qh,readdir as Ad}from"node:fs/promises";import{dirname as Bv,join as ue}from"node:path";import{homedir as Gv,platform as em}from"node:os";var kd="2025.3.2",xa="253.30387.147",Ei="com.intellij.ml.llm",Jh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),NU=1e4,$U=256*1024*1024,MU=16*1024*1024,Xh=1024*1024,qh=22,UU=qh+65535,zh=Ul,FU=()=>{let e=Gv(),t=ue(e,".cache","JetBrains","RemoteDev");switch(em()){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"}]}},BU=()=>em()==="linux"?ue(Gv(),".local","share","JetBrains"):Ye("JetBrains"),WU=()=>em()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),HU=async(e,t=NU)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await Ad(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 Ad(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)]},KU=e=>{let t=Bv(e);return t.endsWith(`${ue("Contents","Resources")}`)?Bv(t):t},GU=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:KU(e)}}catch{return}},Cd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},jU=async(e,t)=>{let n;try{n=await LU(e,"r");let{size:r}=await n.stat();if(r<qh||r>$U)return;let o=Math.min(r,UU),a=await Cd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-qh;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>MU||c+i>r)return;let l=await Cd(n,i,c);if(!l)return;let d=0;for(;d+46<=l.length;){if(l.readUInt32LE(d)!==33639248)return;let u=l.readUInt16LE(d+10),f=l.readUInt32LE(d+20),p=l.readUInt32LE(d+24),h=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),g=l.readUInt32LE(d+42),y=d+46+h+m+w;if(y>l.length)return;let b=l.subarray(d+46,d+46+h).toString("utf8");if(d=y,b!==t)continue;if(f===4294967295||p===4294967295||f>Xh||p>Xh)return;let A=await Cd(n,30,g);if(!A||A.readUInt32LE(0)!==67324752)return;let v=A.readUInt16LE(26),E=A.readUInt16LE(28),x=await Cd(n,f,g+30+v+E);return x?u===0?x.toString("utf8"):u===8?DU(x,{maxOutputLength:Xh}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},Wv=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}},VU=async(e,t)=>{let n=ue(e,"META-INF","plugin.xml");if(await R(n))try{let o=Wv(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 Ad(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 jU(o,"META-INF/plugin.xml"),s=a?Wv(a):void 0;if(s?.id===Ei)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Hv=async e=>{let t;try{t=await Ad(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Jh.has(o.name.toLowerCase()),i=Jh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Jh.has(o.name.toLowerCase());if(!a){let i=ue(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await VU(ue(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},YU=async e=>{try{return(await Qh(ue(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(Ei)}catch{return!1}},Kv=e=>e.reduce((t,n)=>t?(zh(n,t)??-1)>0?n:t:n,void 0),jv=async(e={})=>{let t=e.configRoot??Ye("JetBrains"),n=e.userPluginsRoot??BU(),r=await HU(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):FU(),e.scanBudget),o=(await Promise.all(r.map(h=>GU(h)))).filter(h=>h!==void 0),a=o.length>0||await R(t);if(e.wsl??WU())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=>(zh(h.version,kd)??-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 Hv(y);if(b.present){g=b;break}}if(g??=await Hv(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 YU(m)){c=!0;continue}if(!((zh(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=Kv(o.map(h=>h.version)),f=Kv(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${kd}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${kd}+ 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 ${kd}+ 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 XU=[Jn,Xn],tm=()=>JU(ZU(),".jetbrains","acp.json"),wo=()=>`${tm()}.anyray-state`,qU=(e,t,n="npx")=>{let r=go(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,Si(n,"jetbrains")),{...e,agent_servers:r}},zU=(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 XU)if(c in r){if(!bd(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}},QU=(e=jv)=>({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=tm(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=gd();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:qU(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=tm(),r=async()=>{if(!await R(n))return t.dryRun||(await se(n),await vd(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 vd(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=zU(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 vd(n,{force:!0}):await J(n,l.next,{backup:!1})),t.dryRun||(await se(n),await vd(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)}}),Vv=QU();import{homedir as Ed}from"node:os";import{join as xd}from"node:path";import{rm as nm}from"node:fs/promises";var rm="1.0.0",Id=["anyray-claude-acp","anyray-codex-acp"],eF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],om=()=>xd(Ed(),".windsurf","acp","registry.json"),am=()=>xd(Ed(),".windsurf-next","acp","registry.json"),Ia=e=>`${e}.anyray-state`,Yv=e=>({binary:Object.fromEntries(eF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Jv=(e="npx")=>{let t=Si(e,"windsurf");return[{id:Id[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:Yv(t[Jn])},{id:Id[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:Yv(t[Xn])}]},Sd=e=>!Array.isArray(e)||e.some(t=>!go(t)||typeof t.id!="string")?null:e,tF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==rm||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:Sd(e.agents);if(!n)return null;let r=new Set(Id);return{...e,version:typeof e.version=="string"?e.version:rm,agents:[...n.filter(o=>!r.has(o.id)),...Jv(t)],extensions:e.extensions??[]}},nF=(e,t,n)=>{let r=Sd(e.agents);if(!r)return null;let o=Sd(t.agents)??[],a=new Map((Sd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!Id.includes(u.id)){l.push(u);continue}if(!bd(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===rm&&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}},Zv=async()=>{let e=[];return(await R(am())||await R(xd(Ed(),".windsurf-next")))&&e.push(am()),(await R(om())||await R(xd(Ed(),".windsurf"))||await R(Ye("Devin"))||await R(Ye("Windsurf")))&&e.push(om()),e},Xv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Zv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Zv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=gd();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=tF(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await R(s),d=Jv(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=[om(),am()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await se(a),await nm(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=nF(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 nm(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 nm(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,eb,Hs,Gk,fC,xC,$C,Vv,Tv,Xv,lb],Kt=e=>ie.find(t=>t.id===e);var rF=["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},sm=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(rF.map(o=>[o,"unreadable"]))})}return n},qv=e=>e.filter(t=>!t.integrationStatus),oF=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=oF(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 fF,writeFile as hF}from"node:fs/promises";import{join as oS}from"node:path";import{z as Me}from"zod";var aF=["HTTPS_PROXY","https_proxy"],zv=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"]),Qv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),eS=new Set(["ENOTFOUND","EAI_AGAIN"]),tS=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),nS=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),sF=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 iF(e)},iF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...zv,...Qv,...eS,...tS,...nS])if(t.includes(n))return n}},cF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",lF=e=>aF.filter(t=>(e[t]??"").trim()!==""),dF=(e,t=process.env)=>{let n=sF(e),r=lF(t);return{kind:n&&zv.has(n)?"tls-unknown-issuer":n&&Qv.has(n)?"tls-invalid-cert":n&&eS.has(n)?"dns":cF(e)||n&&nS.has(n)?"timeout":n&&tS.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},uF=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)=>uF(dF(e,t));var Ra="required",pF=e=>e==="subscription"?"subscription":"placeholder",rS=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?pF(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}:{}}},Rd=(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 mF=1e4,yF=1,gF=Me.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),wF=Me.object({id:gF,name:Me.string().min(1),version:Me.string().min(1),body:Me.string()}),bF=Me.object({version:Me.literal(yF).optional(),skills:Me.array(wF),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()}),kF=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",Od=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",_d=async(e,t,n={})=>{let r=n.timeoutMs??mF,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=Od(l),d}return bF.parse(c)},aS=/^[a-z0-9][a-z0-9-]{0,31}$/,sS=64,CF=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>aS.test(o)).slice(0,sS).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>aS.test(o)).slice(0,sS).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},Pd=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=rS(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=Rd(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=CF(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}},iS=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!kF(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=oS(d,i.id),f=oS(u,"SKILL.md");await fF(u,{recursive:!0}),await hF(f,AF(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}},AF=e=>e.endsWith(`
|
|
299
299
|
`)?e:`${e}
|
|
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
|
|
302
|
-
`,{mode:384}),await
|
|
300
|
+
`;import{createHash as vF,createPrivateKey as SF,generateKeyPairSync as EF,randomBytes as im,sign as xF}from"node:crypto";var cm=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",cS="key-heartbeat",IF=["reapply_config","remint","revert"];var lS=e=>vF("sha256").update(e).digest("hex"),tt=e=>typeof e=="string"&&e.trim()?e.trim():void 0,RF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],lm=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}},dm=(e,t,n)=>{try{let r=SF(t),o=new TextEncoder().encode(Co(e));return xF(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Td=()=>{let{publicKey:e,privateKey:t}=EF("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??cm,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:im(16).toString("hex")},c=dm(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 lm(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=OF(p.directive),g=RF(p.capabilities);return{key:h,user:m,team:tt(p.team),expiresAt:tt(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},Dd=async(e,t,n,r,o={})=>{let a=o.timeoutMs??cm,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:im(16).toString("hex"),purpose:cS},l=dm(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 lm(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}},dS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??cm,i=`${e.replace(/\/$/,"")}/connect/machine`,c=tt(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:im(16).toString("hex"),purpose:cS},d=dm(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)}},OF=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}},_F=1e4,PF=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)},TF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??_F,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 lm(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!PF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},uS=(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())},pS=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=Td();return{cert:await TF(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 UF,randomBytes as FF,sign as BF}from"node:crypto";var DF="https://app.anyray.ai",LF=new Set(["localhost","::1","[::1]"]),NF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,$F=e=>LF.has(e)||NF.test(e),um=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&$F(t.hostname)},MF=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||!um(e)?DF:MF(e)};var WF=1e4,HF="machine:",fS=e=>e.startsWith(HF),KF="cert-renew",GF=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)},hS=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:FF(16).toString("hex"),purpose:KF},c;try{let h=UF(t),m=new TextEncoder().encode(Co(i));c=BF(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),WF),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 GF(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var pm=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 pm(e,t,n)).complete;var jF=["claude","codex","cursor","opencode"],VF=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],YF=new Set(["missing_key","key_expired"]);var ZF=600*1e3,JF=600*1e3,mS=1440*60*1e3,XF=1440*60*1e3,qF=10080*60*1e3,zF=3600*1e3,QF=720*60*1e3,eB=e=>Math.min(QF,zF*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,yS=e=>typeof e=="string"&&VF.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 jF){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,...yS(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},Ld=e=>{try{let n=JSON.parse(e);if(Oi(n)&&yS(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"},fm=e=>e!==void 0&&YF.has(e),hm=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=ZF},gS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),mm=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=JF},wS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),bS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,kS=(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},CS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>mS||!fm(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<eB(r.failures??1))},Nd=e=>{let t=Object.values(e?.invoked??{}).filter(Oa);return t.length>0?Math.max(...t):null},ym=(e,t)=>{if(Nd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=qF},AS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=XF)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=mS)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var gm="x-anyray-retrieve-probe",$d=8e3,tB=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",vS=(e,t)=>{let n=Qt(e);return t?.probe&&(n[gm]="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(),$d);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:vS(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=tB(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)}},Md=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(),$d);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:vS(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 nB=5e3,rB=2048,oB=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??nB,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[gm]="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,rB);if(!oB(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Ld(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)}},wm=(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 aB,randomBytes as sB,sign as iB}from"node:crypto";var cB=500,SS=2e3,lB=2e3,dB=250,ES=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),cB);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)}},uB=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},pB=e=>new Promise(t=>setTimeout(t,e)),fB=async(e,t,n=pB)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),SS),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=uB(i)??dB,s>lB))return!1}finally{clearTimeout(a)}await n(s)}},hB=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:sB(16).toString("hex"),events:e},s;try{let i=aB(r),c=new TextEncoder().encode(Co(a));s=iB(null,c,i).toString("base64url")}catch{return!1}return await fB(`${qn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},mB=async(e,t)=>{try{let r=(await L()).enrolledCert,o=await We();if(!r||!o)return;await dn(e,r,o,{timeoutMs:SS,health:{events:t},telemetryOnly:!0})}catch{}},xS=async(e,t)=>{if(e.length!==0)try{let n=await at(),r=n&&await ES(n.origin,Qt(n),e,t);if(n&&await mB(n.origin,e),r)return;await hB(e)}catch{}},bm=async(e,t,n={readTarget:()=>at("profile"),post:ES})=>{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 RS=128,OS=300*1e3,yB=["repaired","repair_failed","flapping","pending"],gB=["settings_not_writable","apply_unconfirmed","apply_threw"],_S=["rebroke_same_day","repeat_days"],PS=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),TS=e=>Pi(e,vo),Ud=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(TS)))return zn(e)},wB=e=>{if(!Ao(e))return;let t=_i(e.checks);if(!(!_r(e.since)||!Pi(e.reason,_S)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},bB=e=>{if(!Ao(e))return;let t={};Ud(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),Ud(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=wB(e.flapping);return s&&(t.flapping=s),t},kB=e=>{if(!Ao(e)||!Ud(e.day)||!_r(e.sequence)||e.sequence===0||typeof e.tool!="string"||!PS.has(e.tool)||!TS(e.checkId)||!Pi(e.status,yB)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!Pi(e.errorClass,gB))return;t=e.errorClass}else if(e.status==="flapping"){if(!Pi(e.errorClass,_S))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 PS){let o=bB(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(kB).filter(n=>n!==void 0).slice(-RS)),_r(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Ao(e.report)&&Ud(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},CB=e=>new Date(e).toISOString().slice(0,10),AB=(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)],Fd=(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(-RS),nextSequence:r}},vB=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),SB=async e=>await Oe(async()=>e,void 0,be)??null,EB=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=Fd(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)},DS=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:AB(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}},xB=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=Fd(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=DS(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=Fd(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),RB=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Fd(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=DS(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)},OB=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>=OS));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??bm)(o.map(vB),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)},_B=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=AS(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},PB=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<OS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await _B(e,t,n,c,o,s);await(s.report??bm)(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)},LS=async(e,t,n)=>{let r=n.now??Date.now,o=CB(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??sm)(a);await EB(i,o,s);let c=await(s.listPending??yr)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await xB(i,l,o,r(),s);let d=await(s.resolveTarget??SB)(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 IB(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 RB(g.id,x.checks,C,I,o,r(),s)}await OB(o,r(),t,s),i=await(s.findIntegrations??sm)(a);let w=await(s.listPending??yr)().catch(()=>[]);return await PB(e,i,w,o,r(),t,s),h}catch{return!1}};var FB=14,BB=.35,WB=900*1e3,$S=360*60*1e3,HB=.2,KB=1800*1e3,MS=3600*1e3,GB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),jB=300*1e3,VB=30*1e3,YB=900*1e3,ZB=(e=0)=>Math.min(YB,VB*2**Math.max(0,e)),US=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}},JB=720*60*1e3,FS=1440*60*1e3,XB=300*1e3,qB=.25,zB=.5,BS=3600*1e3,QB=720*60*60*1e3,e1=360*60*1e3,t1=1440*60*1e3,n1=4,Bd=e=>LB("sha256").update(e).digest("hex").slice(0,32),YS=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(Bd(e))},km=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,n1)}),r1=()=>jS(NB(),".anyray"),Am=()=>jS(r1(),"refresh-state.json"),vm=e=>process.env?.[e],ZS=()=>vm("ANYRAY_REFRESH_DISABLE")==="true",Sm=()=>{let e=vm("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:FB)*t1},Li=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},JS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),o1=10080*60*1e3,Wd=(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)<=o1},Ni=e=>{let t=Sm(),n=e?Li(e):void 0;if(!n)return t;let r=Math.max(WB,Math.round(n*BB));return Math.min(t,r)},a1=e=>{let t=vm("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($S,Math.max(KB,Math.round(e*HB))):$S},Gt=async()=>{try{let e=await $B(Am(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Hd=async e=>{try{let t=Am(),n=`${t}.${process.pid}.tmp`;await VS(n,JSON.stringify(e),{mode:384}),await he(n,t),await MB(t,384).catch(()=>{})}catch{}},s1=3e4,i1=()=>`${Am()}.lock`,WS=async e=>{try{return await VS(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??Hd,s=i1(),i=!1;try{if(i=await WS(s),!i){if(await UB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<s1)return t;await NS(s).catch(()=>{}),i=await WS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await NS(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?Bd(a.clientKey):void 0;await pt(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:km(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(()=>{})},c1=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(QB,Math.max(BS,Math.round(o*zB))):BS},Cm=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Em=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??hS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(fS(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()>c1(e))return{outcome:"not-due",profile:e};if(!await pt(w=>r()-(w.lastCertRenewAt??0)<e1?{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 Cm(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}},HS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*qB):FS,r=Math.min(FS,n);return Math.min(r,XB*2**Math.max(0,e-1))},l1=()=>{let{command:e,args:t}=hn(ir);return{exe:e,args:t}},Pr=async(e={})=>{if(ZS())return;let t=e.now??Date.now,n=e.readState??Gt,r=e.writeState??Hd,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=l1();DB(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await pt(s=>t()-(s.lastSpawnAt??0)<a1(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},d1=Ri,u1=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?qv(a):a;return s.length===0?!1:(await wt(s,o.target),!0)}catch{return!1}},p1=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}},f1=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Gt,a=t.writeState??Hd;return LS(e,we,{now:r,deadWatcherObserved:n,readHookLane:()=>Kd({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})})},Kd=async(e={})=>{let n=await(e.readState??Gt)().catch(()=>({}));return In(n.hookLane)},XS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Kd(t);if(!hm(r,e,n()))return;await pt(o=>{let a=In(o.hookLane);return hm(a,e,n())?{next:{...o,hookLane:gS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},qS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Kd(t);if(!mm(r,n()))return;await pt(o=>{let a=In(o.hookLane);return mm(a,n())?{next:{...o,hookLane:wS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},h1=async(e={})=>{try{let t=e.now??Date.now;if((await Kd(e)).watchSince!==void 0)return;await pt(n=>{let r=In(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:bS(r,t())},result:void 0}},void 0,e)}catch{}},KS=async(e,t={})=>{try{let n=t.now??Date.now;await pt(r=>{let o=In(r.hookLane),a=kS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},zS=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??Kg)())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"}},QS=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"}},m1=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await _d(e.gateway,e.clientKey),n=await Pd(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},GS=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??m1)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>u1(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},nt=async(e={})=>{if(ZS())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??Hd,i=e.remint??dn,c=e.heartbeat??Dd,l=e.detectSeat??$t,d=e.rewriteTools??d1,u=e.rewriteHookLaneTools??pm,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 KS("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 KS(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=>f1(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 h1({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??vb)();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 Em(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)>=JB;if(!g&&CS(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<MS?{result:"throttled"}:T.failureCount&&H<HS(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 p1(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 Cm(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:km(ht.ownKeys,W.sig,Bd(Q.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(Q){H=Q}let fe=US(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 GS(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<ZB(O.failureCount)?{result:"throttled"}:{next:{...O,lastAttemptAt:t()},result:"ok"};let H=O.lastError?.code!==void 0&&GB.has(O.lastError.code)?jB:MS;return T<H?{result:"throttled"}:O.failureCount&&T<HS(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 Cm(Fe,W.sig,$,o)&&(Be=Bd(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:km(Ne.ownKeys,W.sig,Be)}:{}}),{now:t,readState:a,writeState:s}),te&&await GS(te,e,n,h),await E(te?"repaired":"repair_failed"),await x(),"refreshed"}catch(O){let T=US(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 A1}from"node:fs/promises";import{isAbsolute as v1,posix as oE,win32 as Rm}from"node:path";var xm=1e4,y1=900*1e3,tE="tnt_",g1=/^\/sso\/([^/]+)\/?$/,w1=/^\/i\/([^/]+)\/?$/,b1=e=>{let t=e.match(g1);if(t)return t[1];let n=e.match(w1);return n?.[1].startsWith(tE)?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=b1(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(tE))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}},Im=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)}},k1=e=>new Promise(t=>setTimeout(t,e)),Gd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Td)(),a;try{a=await Im(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},xm,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??y1,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}`),C1(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},C1=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},jd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??k1,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 Im(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},xm,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 eE="sdc_",nE=e=>{let t=e.trim();if(!t)return;if(t.startsWith(eE))return{cpOrigin:qn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!um(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(eE)))return{cpOrigin:n.origin,claim:r}},rE=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Td)(),o;try{o=await Im(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},xm,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"?oE.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?Rm.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):oE.join("/etc","anyray","bootstrap.json"),S1=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),aE=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(v1(e)||Rm.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),E1=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 A1(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!S1(n)||n.v!==1||typeof n.sso!="string")return;let r=_t(n.sso);if(!r)return;let o=E1(n.gateway)?n.gateway:void 0,a=aE(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},sE=(e,t,n)=>{let r=_t(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!aE(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&Rm.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 X1}from"node:child_process";import{chmod as x1,readFile as I1,rm as iE,writeFile as R1}from"node:fs/promises";import{join as O1}from"node:path";var Om=()=>O1(ee(),"sso-gate.json"),_1=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 I1(Om(),"utf-8"));return _1(e)?e:null}catch{return null}},P1=0,Vd=async e=>{await Ct();let t=Om(),n=`${t}.${process.pid}.${P1++}.tmp`;try{await R1(n,`${JSON.stringify(e)}
|
|
302
|
+
`,{mode:384}),await x1(n,384),await he(n,t)}catch(r){throw await iE(n,{force:!0}).catch(()=>{}),r}},cE=async()=>{await iE(Om(),{force:!0}).catch(()=>{})},lE=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 L1}from"node:child_process";import{homedir as N1}from"node:os";import{join as $1}from"node:path";import{spawn as T1}from"node:child_process";import{platform as D1}from"node:os";var Da=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=D1(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=T1(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var M1=3e4,U1=5*6e4,F1=30*6e4,B1=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},W1=()=>$1(N1(),".claude","settings.json"),H1=async e=>{try{let n=(await F(W1())).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}},K1=async e=>{await dr.apply(e,{dryRun:!1})},G1=()=>{let{command:e,args:t}=hn("__anyray-sso-poll");return{exe:e,args:t}},j1=()=>{let{exe:e,args:t}=G1(),n=L1(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))}}},V1=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},dE=(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},uE=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
|
+
`,_m=(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
|
-
`,
|
|
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
|
|
312
|
-
${t.stderr??""}`}},
|
|
313
|
-
${j(e)}`),M=e=>console.log(S(e)),U=e=>console.log(`${
|
|
309
|
+
`,Y1=e=>Math.min(U1,M1*2**Math.max(0,e-1)),Z1=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?F1:Y1(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??Vd,c=t.isProcessAlive??lE,l=t.startGrant??Gd,d=t.verify??dn,u=t.routingIntact??H1,f=t.applyClaudeCode??K1,p=t.maybeSpawnRefresh??Pr,h=t.recordMint??Ta,m=t.reserveMint??So,w=t.spawnPoller??j1,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=V1(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=dE(C,b,e.team,b.clientKey);return await u(me)?(Z-n()<=Sm()&&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,_m("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(dE(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,uE(A))}if(A){let Z=Z1(A,n());if(Z)return La(e,_m(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,_m(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,uE(Y))}catch{return{exitCode:0}}},J1=async()=>{try{for await(let e of process.stdin);}catch{}},pE=async e=>{await J1();try{let t=await Qn(B1(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var q1=6e4,z1=10*6e4,er=(e,t)=>{let n=e[t];return typeof n=="string"?n:Array.isArray(n)?n[0]:void 0},Q1=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_")},hE=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_")},mE=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},eW=e=>e.split("?")[0].includes("/v1/"),fE=e=>e.replace(/[^\x20-\x7e]/g,"").replace(/["'`\\$]/g,"").slice(0,300),tW=(e,t,n=process.platform,r=X1)=>{let o=fE(e),a=fE(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{}},yE=(e={})=>{let t=e.readBootstrap??Vt,n=e.ssoGate??Qn,r=e.readState??Tr,o=e.notify??tW,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<z1||(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(!eW(u)||Q1(f)||l||a()-s<q1)return;s=a(),l=!0,d().catch(()=>{}).finally(()=>{l=!1})}catch{}}}};import{watch as nW}from"node:fs";import{basename as rW,dirname as oW}from"node:path";var aW=2e3,sW=6e4,Na=e=>e instanceof Error?e.name:"UnknownError",iW=(e,t,n)=>{let r=nW(e,{persistent:!1},(o,a)=>{t(a==null?null:a.toString())});return r.on("error",n),r},cW=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}},gE=(e={})=>{let t=e.loadProfile??L,n=e.adapters??ie,r=e.probe??be,o=e.repairDrift??(C=>cW(C,r)),a=e.resolveProfileFile??Mo,s=e.watchDir??iW,i=e.debounceMs??aW,c=e.repairFloorMs??sW,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=oW(Z),z=Y.get(W)??new Set;z.add(rW(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 lW}from"node:crypto";import{chmod as dW,readFile as uW,rm as kE,writeFile as pW}from"node:fs/promises";import{join as fW}from"node:path";var hW=/^[A-Za-z0-9_-]{43}$/,mW=3600*1e3,wE=3900,yW=1e4,Pm=()=>fW(ee(),"device-token.json"),gW=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&hW.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},CE=async()=>{try{let e=JSON.parse(await uW(Pm(),"utf-8"));return gW(e)?e:null}catch{return null}},wW=0,bW=async e=>{await Ct();let t=Pm(),n=`${t}.${process.pid}.${wW++}.tmp`;try{await pW(n,`${JSON.stringify(e)}
|
|
311
|
+
`,{mode:384}),await dW(n,384),await he(n,t)}catch(r){throw await kE(n,{force:!0}).catch(()=>{}),r}},Yd=async()=>{await kE(Pm(),{force:!0}).catch(()=>{})},kW=()=>lW(32).toString("base64url"),CW=e=>e instanceof Error?e.name:"UnknownError",AW=(e,t)=>{let n=setInterval(e,t);return n.unref(),{stop:()=>clearInterval(n)}},bE=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=kW(),i=new AbortController,c=setTimeout(()=>i.abort(),yW),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:wE}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await bW({v:1,token:s,expiresAt:t()+wE*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${CW(r)}`),!1}},AE=(e={})=>{bE(e);let n=(e.scheduleRotation??AW)(()=>{bE(e)},mW);return{stop:()=>n.stop()}};var SW=1800*1e3,vE=50,EW=15e3,xW=1e3,IE=bs*1e3-1e4,SE=15*6e4,IW=75e3,RW=8e4,OW=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 Dm(o)}},Zd=e=>{let t=e instanceof Error?e.name:"unknown",n=e?.code;return typeof n=="string"?`${t} ${n}`:t},_W=(e,t={})=>{let n=t.exit??(f=>process.exit(f)),r=t.exitCode??0,o=t.hardCapMs??IE,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()},RE=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),PW=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]),TW=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),DW=45*1e3,LW=600*1e3,NW=new Set(["host","connection","keep-alive","proxy-connection","content-length","transfer-encoding","upgrade"]),$W=new Set(["content-encoding","content-length","transfer-encoding","connection","keep-alive"]),MW=new Set(["missing_key","key_expired"]),UW=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"&&MW.has(r)}catch{return!1}},FW=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(NW.has(n.toLowerCase())||(t[n.toLowerCase()]=Array.isArray(r)?r.join(", "):r));return t},BW=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))}),WW=(e,t)=>e?RE.has(e)?!0:PW.has(e)&&TW.has(t.toUpperCase()):!1,HW=new Set(["127.0.0.1","localhost","[::1]","::1"]),KW=e=>{if(e[ip]===void 0||e.origin!==void 0)return!1;let t=(e.host??"").replace(/:\d+$/,"");return HW.has(t)},GW=(e,t)=>{let n=(t??"").split("?")[0];return e==="GET"&&n==="/__anyray/health"||e==="POST"&&n==="/__anyray/shutdown"},jW=async(e,t,n,r)=>{try{return{res:await fetch(e,{method:t,headers:n,body:r.length?r:void 0,duplex:"half"})}}catch(o){return{failure:{kind:"transport-error",code:o?.cause?.code}}}},Dm=e=>new Promise(t=>setTimeout(t,e)),EE=async(e,t,n,r,o,a=EW)=>{let s=Date.now()+a,i=vE,c=!1;for(;;){let l=await jW(e,t,n,r);if("res"in l||!o())return l;let d=l.failure.code;if(d!==void 0&&RE.has(d)){if(Date.now()+i>s)return l;await Dm(i),i=Math.min(i*2,xW)}else if(!c&&WW(d,t))c=!0,await Dm(vE);else return l;if(!o())return l}},Tm=async(e,t)=>{let n={};if(t.headers.forEach((s,i)=>{$W.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()},xE=(e,t,n)=>{e.headersSent||e.destroyed||(e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify({error:{type:"anyray_proxy",message:n}})))},VW=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(!KW(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 BW(a),d=FW(a.headers),u=mE(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&&!hE(a.headers)){h=!0;try{p=await e.resolveClientKey(),p&&f(p)}catch{}}let m=await EE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("failure"in m){xE(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(UW(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 EE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("res"in E){E.res.status===401&&w(),await Tm(s,E.res);return}}}w(),await Tm(s,new Response(b,{status:m.res.status,headers:m.res.headers}));return}w(),await Tm(s,m.res)},o=vW.createServer((a,s)=>{s.on("error",()=>{}),GW(a.method,a.url)||(n++,s.once("close",()=>{n--})),r(a,s).catch(i=>{console.error(`anyray refresh proxy: request error ${Zd(i)}`),s.headersSent?s.end():xE(s,502,"anyray proxy internal error")})});return o.keepAliveTimeout=IW,o.headersTimeout=RW,o.on("error",a=>{a.code!=="EADDRINUSE"&&console.error(`anyray refresh proxy: server error ${Zd(a)}`)}),{server:o,inFlight:()=>n}},OE=5e3,YW=2e3,ZW=(e={})=>{let t=e.now??Date.now,n=e.loadProfile??L,r=e.refresh??(()=>nt()),o=e.remintBudgetMs??OE,a,s=-1/0,i=3e4;return Object.assign(async()=>{let l=a===void 0?YW: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}})},_E=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=yE(),o=ZW(),a=VW({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,OE).unref?.())]),o()),isOwnClientKey:p=>YS(p),onShutdown:p=>f(0,{drain:p.drain})});nt().catch(()=>{});let s=setInterval(()=>{nt().catch(()=>{})},SW);s.unref();let i=gE(),c=AE(),l=Date.now();a.server.on("request",()=>{l=Date.now()});let d=setInterval(()=>{Date.now()-l>LW||fetch(`${n}/`,{method:"HEAD"}).catch(()=>{})},DW);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"?SE:IE;Ow(Date.now()+m),_W(a.server,{exitCode:p,inFlight:a.inFlight,ceilingMs:h.drain==="idle"?SE:void 0,exit:w=>{up(),process.exit(w)}})};return process.once("SIGTERM",()=>f()),process.once("SIGINT",()=>f()),process.on("uncaughtException",p=>{console.error(`anyray refresh proxy: uncaught exception ${Zd(p)}`),f(1)}),process.on("unhandledRejection",p=>{console.error(`anyray refresh proxy: unhandled rejection ${p instanceof Error?Zd(p):typeof p}`),f(1)}),up(),await Sw(ys()).catch(()=>{}),await OW(a.server,t),console.error(`anyray refresh proxy listening on 127.0.0.1:${t} \u2192 ${n}`),await new Promise(()=>{}),0};import{platform as JW}from"node:os";import{stat as XW}from"node:fs/promises";import{spawnSync as qW}from"node:child_process";var PE="/Applications/Anyray Connect Tray.app",zW=new Set(["V53XMA78UF"]),QW="ai.anyray.connect-tray",eH=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,tH=e=>{let t=qW("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
312
|
+
${t.stderr??""}`}},nH=async e=>{try{return(await XW(e)).isDirectory()}catch{return!1}},rH=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},Lm=async(e,t={})=>{if((t.os??JW())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??nH)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??tH;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?rH(a.output):void 0;return s?zW.has(s)?eH(a.output)!==QW?{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 Lm(n,t)).ok?"healthy":"gone"},Nm=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 oH={"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."},aH=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},sH=async(e,t)=>{let n=t.stderr??console.error,r=aH(e,"--app-path")??PE,o=await Lm(r,t);if(!o.ok)return n(oH[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},iH=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},TE=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await sH(e,t):e.includes("--release-tray")?await iH(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 DE,platform as $m}from"node:os";import{join as $a}from"node:path";import{access as cH}from"node:fs/promises";var Mm=(e=$m(),t=DE())=>{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:[]}]:[]},LE=async e=>{try{return await cH(e),!0}catch{return!1}},Mi=async(e,t={})=>{let n=t.exists??LE,r=t.os??$m();for(let o of Mm(r,t.home))if(o.kind===e){if(o.paths.length===0){if(await(t.supervisorHolds??lH)(e,r))return!0;continue}for(let a of o.paths)if(await n(a))return!0}return!1},lH=async(e,t)=>{if(e!=="scheduler")return!1;try{return await Jo(t)}catch{return!1}},NE=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable)return t;let n=e.exists??LE,r=Mm(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},dH=[ws,`${fr}.service`,Es,`${Zr}.timer`,`${Zr}.service`,Uc],$E=(e,t=$m(),n=DE(),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 Mm(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:",...dH.map(a=>` - ${a}`)),o};var Um=5e3,ME=3e4,uH=1440*60*1e3,pH=e=>new Promise(t=>setTimeout(t,e)),fH=async(e=L,t=$t)=>(await Oe(e,t))?.target,hH=e=>Kt(e)?.quitGated,UE=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??hH,o=t.readPending??il,a=t.clearPending??Vp,s=t.targetFromProfile??fH,i=t.sleep??pH,c=t.now??Date.now,l=t.maxWaitMs??uH;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=Um;for(;;){let h=await o(n);if(!h||c()-f>l)return 0;if(d.isRunning()){await i(p),p=Math.min(ME,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=Um;continue}if((await u(h.op,m,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(p),p=Math.min(ME,p*2);continue}if(await a(n,h)!=="superseded")return 0;await i(p),p=Um}}catch{return 0}};import{writeFileSync as wH}from"node:fs";import{chmod as Fm,stat as bH}from"node:fs/promises";import{platform as Wm}from"node:os";import{dirname as HE,isAbsolute as kH}from"node:path";var Ma=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Jd=Ma(process.stdout,process.env),FE=Ma(process.stderr,process.env),Ua=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,j=e=>Ua("1",e,Jd),S=e=>Ua("2",e,Jd),mH=e=>Ua("32",e,Jd),yH=e=>Ua("33",e,FE),gH=e=>Ua("31",e,FE),rt=e=>Ua("36",e,Jd),k=e=>console.log(e),K=e=>console.log(`
|
|
313
|
+
${j(e)}`),M=e=>console.log(S(e)),U=e=>console.log(`${mH("\u2713")} ${e}`),D=e=>console.error(`${yH("!")} ${e}`),_=e=>console.error(`${gH("\u2717")} ${e}`);var Bm=`${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`,
|
|
402
|
-
`)},Io=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}
|
|
403
|
-
`),
|
|
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},
|
|
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
|
|
406
|
-
`+
|
|
407
|
-
`+
|
|
401
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,BE=["claude-code","jetbrains","shell","bootstrap","proxy"],CH=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(!BE.includes(a))throw new Error(`unknown --tool ${a} (expected ${BE.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 Xd(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 AH=(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,qu(r),n.env&&(r.env={...o,...n.env}),n.hooks){let a=r.hooks??{};for(let[s,i]of Object.entries(n.hooks)){let c=Array.isArray(a[s])?a[s]:[];a[s]=[...c,...i]}r.hooks=a}return r},vH=e=>{let t=e.env,n=qu(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},KE=async e=>{let t=async n=>{try{return(await bH(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(HE(e))!==void 0}},GE=async(e,t)=>(t.dirExisted||await Fm(HE(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await Fm(e,420),{mode:420,keptRestricted:!1}):(await Fm(e,t.mode),{mode:t.mode,keptRestricted:!0})),jE=(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.")))},VE=()=>process.getuid?.()===0,Ce=e=>{process.stderr.write(`${e}
|
|
402
|
+
`)},Io=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}wH(e.out,t,"utf8"),Ce(S(`# Wrote ${e.out}`))},Hm=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??""}),qd=e=>kH(e)||/^[A-Za-z]:[\\/]/.test(e),YE=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(!qd(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}},ZE=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)"}`],Km=(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{}},SH=(e,t)=>({agent_servers:{[Jn]:{command:e,args:[md,"claude",t,"jetbrains"],env:{}},[Xn]:{command:e,args:[md,"codex",t,"jetbrains"],env:{}}}}),WE=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
|
+
`),EH=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(!qd(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(!wd(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return Io(e,`${JSON.stringify(SH(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},xH=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&&!qd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return Io(e,sE(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},IH=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,WE(n)),Ce(S(`# Loopback shell snippet \u2014 pair with \`managed --tool proxy\` (daemon on :${ke}) and \`--tool bootstrap\`.`)),0}let t=Hm(e);return Io(e,WE(t)),Ce(S("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),Km(t,Ce),0},RH=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(!qd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");let t=e.servicePlatform??(Wm()==="darwin"?"launchd":"systemd"),n={command:e.bin,args:[sp]};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},OH=e=>{let t=Hm(e),n=YE(e),r=n?Xd(t,n):Xd(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 ZE(t))Ce(S(`# ${o}`));Km(t,Ce)}return 0},_H=async e=>{let t=Wm();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(!VE())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=Hm(e),r=YE(e);r||Km(n,u=>D(u.replace(/^!\s*/,"")));let o=Lt(t),a=await F(o),s=r?Xd(n,r):Xd(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=AH(a,s),l=await KE(o);await J(o,c);let d=await GE(o,l);U(`Wrote ${o}`),jE(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 ZE(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},PH=async()=>{let e=Wm();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(!VE())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(!vH(n))return k(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await KE(t);await J(t,n);let o=await GE(t,r);return U(`Removed Anyray-owned keys from ${t} (other keys left intact).`),jE(t,o),0},JE=async e=>{let t;try{t=CH(e)}catch(n){return _(n instanceof Error?n.message:"invalid managed arguments"),k(`
|
|
406
|
+
`+Bm),1}if(t.help||e.length===0&&!t.mode)return k(Bm),0;if(!t.mode)return _("Specify a mode: --print, --write, or --revert."),k(`
|
|
407
|
+
`+Bm),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"?EH(t):n==="bootstrap"?xH(t):n==="proxy"?RH(t):IH(t):t.mode==="print"?OH(t):t.mode==="write"?await _H(t):await PH()}catch(n){return _(n instanceof Error?n.message:"managed settings failed"),1}};var TH=`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,10 +416,10 @@ 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
|
-
`,
|
|
420
|
-
`);let s=o.passthroughHeaders
|
|
419
|
+
`,DH=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}},LH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Ni(e):!0},XE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},qE=(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()},Gm=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,NH=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Gm(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 \`${Gm(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 \`${Gm(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""}},jm=async(e={})=>{let t=e.loadProfile??L,n=e.refreshIfDue??nt,r=e.now??Date.now,o=await t();if(XE(o),!o.enrolledCert){if(!qE(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||LH(o,r)){let i=NH(await n(),o);if(i){if(!qE(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(XE(s),!xe(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},zE=e=>de({user:e.name,team:e.team}),$H=({profile:e,token:t})=>{let n={},r=zE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Vm=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=zE(e);return r&&(n["x-anyray-metadata"]=r),n},MH=e=>JSON.stringify(Vm(e)),QE=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=DH(e);if(o.help)return n.write(TH),0;let a=await jm(t);a.warning&&r.write(`${a.warning}
|
|
420
|
+
`);let s=o.passthroughHeaders?MH(a):o.json?$H(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
|
-
`),1}};var
|
|
422
|
+
`),1}};var ex=`anyray-connect models [<model-id>] [--json]
|
|
423
423
|
|
|
424
424
|
List the Copilot models your seat can run on the Anyray lane, or switch the
|
|
425
425
|
Copilot CLI's startup model. The CLI's own /models cannot list models on a
|
|
@@ -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
|
-
`,
|
|
435
|
-
`),0;k(j(`Copilot models your seat serves (via ${o.origin})`));for(let h of l){let m=h.id===p?"*":" ",w=
|
|
434
|
+
`,UH=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},FH=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})},BH=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(" / ")},WH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Qs(t)}/${Fn(n)==="responses"?"responses":"chat/completions"}`,tx=async(e=[],t={})=>{let n=UH(e);if(n.help)return process.stdout.write(ex),0;if(n.error)return _(n.error),process.stdout.write(ex),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??Il)({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=Pf(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=BH(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??xl)(WH(o,i,d.id),{..._f(),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??FH)(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 HH=`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
|
+
`,nx=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(HH),0;k(j("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??Yk)();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??Zk)(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??Jk)(r.token,o);U(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??vf)(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 rx=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??CE)();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 fx,dirname as QH}from"node:path";import{mkdir as eK,readFile as zm,rm as hx,writeFile as mx}from"node:fs/promises";import{fstatSync as VH,openSync as YH,statSync as ZH}from"node:fs";import{createInterface as JH}from"node:readline/promises";import{ReadStream as XH}from"node:tty";import{execFileSync as ox}from"node:child_process";import KH from"node:os";var Ym=e=>{try{return ox("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},GH=e=>{try{return ox("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},jH=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"]),Zm=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:jH.has(t):!0},ax=()=>{try{return KH.userInfo().username||void 0}catch{return}},sx=()=>Ym("user.name")??Ym("user.email")??ax()??"unknown",ix=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Ym),global:e.globalGitConfig??(t||GH)}},Ro=e=>{try{return e()?.trim()||void 0}catch{return}},Jm=(e={})=>{let t=ix(e),n=Ro(e.osUsername??ax),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")},cx=(e={})=>{let t=Jm(e);if(Zm(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=ix(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,qH=()=>{try{let e=VH(0);return e.isCharacterDevice()&&e.rdev===ZH("/dev/tty").rdev}catch{return!1}},Xm=()=>{if(qH()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new XH(YH(`/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"}},lx=async(e,t)=>{let n=t.input??Xm(),r=t.output??process.stdout,o=JH({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 lx(`${e} ${S("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Ba=async(e,t,n={})=>{let r=t?` ${S(`[${t}]`)}`:"";return(await lx(`${e}${r}: `,n)).trim()||t},dx=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=sx();return n||!Yt()?(M(`Your name: ${r} ${S("(auto-detected \u2014 pass --user to change)")}`),r):Ba("? Your name",r)},ux=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)},px=(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,zd=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")}},Qd=e=>e.id!==Wa||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",zH={"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"},eu=(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=zH[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 qm=["claude-code","codex"],tK="anyray-connect print-key",Qm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nK=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:rs,authMode:"placeholder",metadata:{}}),ey=e=>fx(e,".claude","settings.json"),rK=async(e,t,n)=>{let r=ey(e),o=await F(r),{env:a}=fn(t,{includeAuthToken:!1,includeClientKey:!1}),s=Qm(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=tK,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]}},yx=async(e=process.cwd())=>{let t=[],n=ey(e);try{if(await R(n)){let o=await F(n),a=Qm(o.env)?o.env:{};(Kr.some(s=>s in a)||jr(o))&&t.push(n)}}catch{}let r=ty(e);try{if(await R(r)){let o=await zm(r,"utf-8");Op(o)&&t.push(r)}}catch{}return t},oK=async(e,t)=>{let n=ey(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await F(n),o=!1;if(Qm(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 hx(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]}},ty=e=>fx(e,".codex","config.toml"),aK=async(e,t,n)=>{let r=ty(e),o=await zm(r,"utf-8").catch(()=>""),a=Zc(o,_s(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await eK(QH(r),{recursive:!0}),await mx(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]}},sK=async(e,t)=>{let n=ty(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await zm(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 hx(n,{force:!0}):await mx(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},gx=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...qm],r=n.filter(s=>!qm.includes(s));if(r.length>0)return _(`--project supports ${qm.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=nK(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
|
|
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 rK(t,o,e.dryRun):await aK(t,o,e.dryRun):s==="claude-code"?await oK(t,e.dryRun):await sK(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 iK}from"node:child_process";var cK="/usr/bin/security",lK=["find-generic-password","-s","Claude Code-credentials","-w"],dK=1e4,uK=64*1024,pK=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,wx="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",fK=(e,t,n)=>new Promise((r,o)=>{iK(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),bx=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),hK=e=>{let t=JSON.parse(e);if(!bx(t)||!bx(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!pK.test(n))throw new Error("unexpected keychain access token");return n},kx=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${wx}
|
|
449
|
+
`),1;try{let o=await jm(t),a=Vm(o),s=await(t.execSecurity??fK)(cK,[...lK],{encoding:"utf8",timeout:dK,maxBuffer:uK,shell:!1}),i=hK(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
|
|
451
|
+
`),0}catch{return r.write(`${wx}
|
|
452
|
+
`),1}};import{mkdir as HK,writeFile as KK}from"node:fs/promises";import{dirname as GK}from"node:path";import{Buffer as jK}from"node:buffer";import{constants as Cx}from"node:fs";import{access as mK,chmod as yK,mkdir as gK,open as wK,readFile as bK,realpath as kK,rm as CK,stat as Sx,writeFile as AK}from"node:fs/promises";import{randomUUID as vK}from"node:crypto";import{platform as Ex}from"node:os";import{dirname as SK,join as EK,posix as xK,win32 as xx}from"node:path";var Bi="/usr/local/bin/anyray-credential-helper",Wi="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",ny="Managed by anyray-connect desktop helper; do not edit.",IK=`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=
|
|
484
|
-
`)},
|
|
485
|
-
`),0;if(s!==
|
|
482
|
+
`,Ax=(e=Ex())=>e==="win32"?"windows":"posix",RK=e=>e==="windows"?Wi:Bi,vx=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},OK=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":vx(t,"write");break;case"--print":vx(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},_K=e=>/[\0\r\n]/.test(e),PK=e=>/^[A-Za-z]:[\\/]/.test(e)&&xx.isAbsolute(e),Hi=(e,t)=>!_K(e)&&(t==="windows"?PK(e):xK.isAbsolute(e)),ry=e=>e.replace(/\\/g,"/").toLowerCase(),Ix=(e,t)=>{if(!Hi(e,t))return!1;let n=ry(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)))},oy=(e,t)=>t==="windows"?xx.normalize(e):e,TK=e=>`'${e.replace(/'/g,`'"'"'`)}'`,DK=(e,t)=>{if(!Ix(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=oy(t,e);if(e==="windows")return["@echo off",`REM ${ny}`,'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=TK(n);return["#!/bin/sh",`# ${ny}`,'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
|
+
`)},tu=(e,t)=>{if(!Hi(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=oy(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"]}},LK=async e=>{try{return await bK(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},NK=async(e,t)=>{try{let n=await kK(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!Ix(r,t))throw new Error;if(!(await Sx(n)).isFile())throw new Error;await mK(n,t==="posix"?Cx.X_OK:Cx.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},$K=e=>e.slice(0,300).includes(ny),MK=async(e,t,n)=>{let r=await LK(e);if(r!==void 0&&r!==t&&!$K(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 Sx(e)).mode&511)===493)return"unchanged"}catch{}}let o=SK(e);try{await gK(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=EK(o,`.anyray-credential-helper.${process.pid}.${vK()}.tmp`),s=!1;try{await AK(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await yK(a,493);let i=await wK(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 CK(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},Rx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=OK(e);if(o.help)return n.write(IK),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");let a=(t.platform??Ex)(),s=o.targetPlatform??Ax(a),i=oy(o.helperPath??RK(s),s);if(!Hi(i,s))throw new Error(`--path must be an absolute ${s} path`);if(s==="windows"&&tu("windows",i),ry(i)===ry(o.binaryPath))throw new Error("--path must differ from --bin (the helper cannot invoke itself)");let c=DK(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!==Ax(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await NK(o.binaryPath,s);let l=await MK(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
|
|
488
|
+
`),1}};var UK=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),FK=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,BK=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.")},WK=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),nu=(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!==""||BK(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()}},Ox=e=>{if(!WK(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!UK.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:nu(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:nu(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:nu(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},_x=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return Ox(t)},ay=e=>{let t=nu(e.url,"--bootstrap-url"),n=e.oidc?Ox(e.oidc):void 0,r;if(e.deploymentOrganizationUuid!==void 0&&(r=e.deploymentOrganizationUuid.trim(),!FK.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}:{}}},sy=e=>pa(ay(e));var VK=`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
|
-
`,
|
|
531
|
-
<string>${tr(t)}</string>`,
|
|
530
|
+
`,YK=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",ZK=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),JK=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[YK(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...ZK(o)]},XK=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),iy=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>XK.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,"'"),Px=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),qK=(e,t)=>` <key>${tr(e)}</key>
|
|
531
|
+
<string>${tr(t)}</string>`,cy=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>qK(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,20 +561,20 @@ ${s}
|
|
|
561
561
|
<string>${tr(n)}</string>
|
|
562
562
|
</dict>
|
|
563
563
|
</plist>
|
|
564
|
-
`},
|
|
565
|
-
`,
|
|
566
|
-
`,
|
|
567
|
-
`),
|
|
564
|
+
`},Dx=(e,t)=>cy("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))),zK=(e,t)=>`${JSON.stringify(lo(e,t),null,2)}
|
|
565
|
+
`,QK=e=>cy("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",sy(e)),eG=e=>`${JSON.stringify(ay(e),null,2)}
|
|
566
|
+
`,Lx=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries(e).map(([n,r])=>`"${Px(n)}"="${Px(r)}"`),""].join(`
|
|
567
|
+
`),Nx=(e,t)=>{let n=td(e,t);return Lx(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},tG=e=>Lx(sy(e)),$x=(e,t,n)=>{if(t==="darwin"){let r=Bi;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:Dx(e,r),helperPath:r}}if(t==="win32"){let r=Wi;return{path:`${n}\\claude-desktop-anyray.reg`,content:Nx(e,r),helperPath:r}}},Mx=(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."],nG=(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=tu(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${_s(e,o).join(`
|
|
568
568
|
`)}
|
|
569
|
-
`},
|
|
569
|
+
`},rG=e=>cy("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:jK.from(e,"utf-8").toString("base64")}),oG=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},aG=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}}},Tx=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??HK,o=n.writeFile??KK;await r(GK(t),{recursive:!0}),await o(t,e)},sG=(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.
|
|
573
573
|
`):t==="json"&&o.write(`Deploy this file to /etc/claude-desktop/managed-settings.json.
|
|
574
|
-
`)},
|
|
574
|
+
`)},iG=e=>{e.write(`This artifact is a stable MDM trust anchor; it contains no inference credential. Claude Desktop authenticates the user and fetches the effective configuration from the bootstrap service at launch.
|
|
575
575
|
`),e.write(`Update the bootstrap response instead of redeploying MDM. Claude polls every 30 minutes, then applies changed values on the next Claude Desktop launch; no managed action is required for each policy update.
|
|
576
576
|
`),e.write(`Each bootstrap response replaces the allowed managed configuration; omitted keys are unset.
|
|
577
|
-
`)},
|
|
577
|
+
`)},cG=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??ho)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
|
|
578
578
|
${o.remedy}
|
|
579
579
|
`),1;let a=o.lanes.reduce((c,l)=>c+l.migrated,0),s=o.portableAssets.reduce((c,l)=>c+l.migrated,0),i={code:"Claude Code sessions",cowork:"Cowork tasks"};for(let c of o.lanes){let l=[c.alreadyPresent>0?`${c.alreadyPresent} already there`:"",c.skippedNoTranscript>0?`${c.skippedNoTranscript} skipped, transcript no longer on disk`:"",c.failed>0?`${c.failed} failed`:""].filter(Boolean);n.write(` ${i[c.lane]}: ${c.migrated} migrated`+(l.length>0?` (${l.join("; ")})`:"")+`
|
|
580
580
|
`)}for(let c of o.portableAssets){let l=c.migrated+c.alreadyPresent,d=c.conflicts+c.invalid+c.failed;if(l+d===0)continue;let u=c.kind==="skill"?"User-created skills":c.kind==="plugin"?"User-installed plugins":"Local MCP servers";n.write(` ${u}: ${c.migrated} migrated`+(c.alreadyPresent>0?` (${c.alreadyPresent} already there)`:"")+(d>0?` (${d} preserved or skipped)`:"")+`
|
|
@@ -585,10 +585,10 @@ 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},Ux=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=JK(e);if(o[0]==="helper")return Rx(o.slice(1),t);let a=oG(o);if(a.help)return n.write(VK),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 cG(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:_x(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?tG(u):a.artifact==="json"?eG(u):QK(u);return await Tx(f,a.path,t),iG(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"&&tu("windows",i);let l=aG(a),d;if(a.target==="claude")d=a.artifact==="reg"?Nx(l,i):a.artifact==="json"?zK(l,i):Dx(l,i);else{let u=nG(l,i);d=a.artifact==="mobileconfig"?rG(u):u}return await Tx(d,a.path,t),sG(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
|
-
`),1}};var
|
|
591
|
+
`),1}};var lG=`anyray-connect retrieve <handle> [--source auto|claude|profile]
|
|
592
592
|
|
|
593
593
|
Print the original content Anyray externalized behind a "\xB7 retrieve ctx_\u2026"
|
|
594
594
|
marker. The content is written to stdout byte-for-byte (no trailing newline
|
|
@@ -598,7 +598,7 @@ Options:
|
|
|
598
598
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
599
599
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
600
600
|
--help Show this help.
|
|
601
|
-
`,
|
|
601
|
+
`,dG=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
|
|
602
602
|
|
|
603
603
|
Semantic search over your externalized tool outputs. Prints one match per line
|
|
604
604
|
to stdout as: handle<TAB>score<TAB>preview. Fetch a full original with
|
|
@@ -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
|
+
`,Fx=(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},uG=e=>e.replace(/[\t\r\n]+/g," ").trim(),Bx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=Fx(e,!1);if(o.help)return n.write(lG),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}},Wx=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=Fx(e,!0);if(o.help)return n.write(dG),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??Md)(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
|
-
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${
|
|
618
|
+
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${uG(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
|
-
`),1}};import{promises as
|
|
621
|
+
`),1}};import{promises as MG}from"node:fs";var Rn=e=>typeof e=="string"?e:"",pG=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()},
|
|
623
|
+
`).trim()},fG=e=>{let t=Rn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},hG=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=pG(r);if(!o)continue;let a=Rn(r.created_at).trim();t.push({role:fG(r),text:o,...a?{createdAt:a}:{}})}return t},ru=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=hG(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 PG}from"node:crypto";import{promises as Gi}from"node:fs";import{homedir as Zx}from"node:os";import{join as su}from"node:path";import{promises as Hx}from"node:fs";import ly from"node:path";var mG=4e4,yG=16*1024*1024,Ki=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),ou=async(e,t={})=>{let n=(e??"").trim();if(!n)return Ki("","path is required");let r=t.cwd??process.cwd(),o=ly.resolve(r,n),a=ly.relative(r,o);if(a.startsWith("..")||ly.isAbsolute(a))return Ki(n,"path is outside the workspace");let s=t.maxBytes??mG,i;try{let w=await Hx.stat(o);if(!w.isFile())return Ki(n,"not a regular file");let g=t.maxFileBytes??yG;if(w.size>g)return Ki(n,`file too large to read (${w.size} bytes; limit ${g})`);i=await Hx.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}:{}}}},dy=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
|
|
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(x=>E.includes(x))&&(u.push({file:
|
|
628
|
+
${e.content}`};import{spawn as gG}from"node:child_process";import{promises as uy}from"node:fs";import py from"node:path";var fy=400,wG=240,bG=4e3,kG=4e3,CG=512*1024,AG=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),Gx=(e,t)=>e.length>t?e.slice(0,t):e,vG=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"]),SG=8,EG=2e3,xG=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],IG=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")},jx=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!vG.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=SG))break}return n},Vx=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},RG=(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)},Kx=(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:Gx(l,t)})}return r},OG=(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 xG)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=gG("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=Kx(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=Kx(d,o,r+1),w=m.length>r;f({ok:!0,matches:w?m.slice(0,r):m,truncated:w,engine:"ripgrep"})})}),_G=async(e,t,n,r,o,a,s)=>{let i=Vx(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 uy.readdir(m,{withFileTypes:!0})}catch{return}for(let g of w){if(u.length>=r||Date.now()>a){p=!0;return}let y=py.join(m,g.name);if(g.isDirectory()){if(AG.has(g.name))continue;await h(y)}else if(g.isFile()){if(f>=kG){p=!0;return}if(d.length&&!d.some(v=>g.name.endsWith(v))||IG(py.relative(t,y)))continue;f+=1;let b;try{if((await uy.stat(y)).size>CG)continue;b=await uy.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:py.relative(t,y),line:v+1,text:Gx(A[v],o)}),u.length>=r)){p=!0;return}}}}};return await h(t),{ok:!0,matches:u,truncated:p,engine:"walk"}},au=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??fy,s=t.maxColumns??wG,i=t.timeoutMs??bG,c=Date.now()+i,l=jx(n),d=l.length>1,u=Math.min(a*4,EG),f=(g,y)=>_G(n,r,o,g,s,c,y),p=async g=>{let y=await g(u,l);if(!y.ok)return y;let b=RG(y.matches,l,Vx(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)=>OG(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))},Yx=(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=jx(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 Jx=448,TG=384,DG=4e4,Nr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=su(Zx(),".anyray");try{if((await Gi.stat(t)).isDirectory())return su(t,"history")}catch{}return su(Zx(),".anyray-history")},LG=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:NG(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},NG=e=>{let t=PG("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)},$G=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
|
+
`},iu=async e=>{let t=await Nr();await Gi.mkdir(t,{recursive:!0,mode:Jx});try{await Gi.chmod(t,Jx)}catch{}let n=0,r=0;for(let o of e)try{await Gi.writeFile(su(t,LG(o)),$G(o),{mode:TG}),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}},Xx=async e=>{let t=await Nr();return au(e,{cwd:t,globs:["*.md"]})},qx=async e=>{let t=await Nr();return ou(e,{cwd:t,maxBytes:DG})};var zx=`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
|
-
`,
|
|
662
|
+
`,UG=async e=>{try{return{raw:await MG.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"})`}}},FG=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 UG(t);if("error"in n)return _(n.error),1;let r=ru(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 iu(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},BG=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 rd(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)},WG=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)},Qx=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(zx),0):t==="import"?FG(e.slice(1)):t==="restore"?BG(e.slice(1)):t==="status"?WG():(_(`Unknown history command: ${t}`),console.log(zx),1)};import{promises as HG}from"node:fs";var KG=`anyray-connect migrate [options]
|
|
663
663
|
|
|
664
664
|
Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
|
|
665
665
|
|
|
@@ -688,51 +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
|
-
`,
|
|
692
|
-
`).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${
|
|
691
|
+
`,GG=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},eI={code:"Claude Code sessions",cowork:"Cowork tasks"},jG=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`${eI[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},VG=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(` ${jG(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(` ${eI[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${Hh(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},YG=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 rd(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.`))}},ZG=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 HG.readFile(e.conversations,"utf8")}catch{_(` could not read ${e.conversations}`);return}let n=ru(t);if(!n.ok){_(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await iu(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()}`))},JG=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`."))},tI=async(e,t={})=>{let n;try{n=GG(e)}catch(o){return _(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(KG),0;k(j("Migrating Claude Desktop onto Anyray")),k(S("Claude Desktop must be fully quit.")),k("");let r=await VG(n,t);return await YG(n,!r),await ZG(n),r?(JG(n),0):(k(""),D("Fix the item above and re-run to finish the migration."),1)};var XG=3e3,cu=async(e,t={})=>{let n=t.timeoutMs??XG,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 qG="enl_",zG="enp_",nI=e=>e.startsWith(qG)||e.startsWith(zG),QG=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],hy=e=>QG.find(t=>e.startsWith(t.prefix)),rI=/^\/enroll\/([^/]+)\/?$/,oI=/^\/i\/([^/]+)\/?$/,aI=e=>{let t=e.match(rI);if(t)return hy(t[1])?void 0:t[1];let n=e.match(oI);return n&&nI(n[1])?n[1]:void 0},ej=1e4,lu=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=aI(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!hy(t))return{cpOrigin:qn(),token:t}},sI=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(rI)??o.pathname.match(oI);if(!a)return;n=a[1]}catch{}let r=hy(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:aI(n.pathname)!==void 0}catch{return nI(t)}},ji=e=>typeof e=="string"&&e.trim()?e.trim():void 0,iI=async(e,t={})=>{let n=t.timeoutMs??ej,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 cI=()=>Xm(),lI=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??cI)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},tj=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},dI=async(e,t={})=>{let n=(t.openInput??cI)(),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 x of
|
|
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 tj(E)){if(x===""||x==="\x1B"||x==="q"){g({kind:"cancelled"});return}if(e.items.length===0){(x==="\r"||x===`
|
|
696
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
|
|
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()}},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=>`
|
|
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 uI=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],nj=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${uI[a++%uI.length]} ${e}`)};s();let i=setInterval(s,nj);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as rj}from"node:fs";import{spawnSync as oj}from"node:child_process";import{chmod as aj,copyFile as gy,lstat as wy,mkdir as Ga,readdir as by,realpath as uu,rename as du,rm as Pt,stat as sj,symlink as ij,writeFile as cj}from"node:fs/promises";import{createHash as lj}from"node:crypto";import{basename as my,dirname as $r,join as ft}from"node:path";import{Readable as dj}from"node:stream";import{pipeline as uj}from"node:stream/promises";var pI="https://github.com/anyrayHQ/install/releases",fI="connect-v",pj=new RegExp(`/releases/tag/${fI}([0-9][0-9A-Za-z.-]*)$`),fj=300*1024*1024,pu=1e4,hj=5*6e4,mj=360*6e4,yj=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)},hI=(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"}},gj=e=>{if(e)return pj.exec(e.trim())?.[1]},ky=(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()}},mI=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}},wj=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}:{...mI(e),downgradeBlocked:!1},Va=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",bj=(e=process.execPath)=>{let t=Yu(e);return t?$r(t):$r($r(e))},kj=async(e=yt())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=ft(bj(e.execPath),"bin",Va());try{if(await uu(t)!==await uu(e.execPath))return}catch{return}return t},Cy=async(e=yt(),t=ee())=>{let n=await kj(e);if(n)return{kind:"managed",root:$r($r(n)),link:n,entryPath:or(e)};let r=or(e);return Ju(r,t)?{kind:"durable",root:t,entryPath:r}:ju(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},fu=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(o)}},Ay=async(e=pu)=>{let t=await fu(`${pI}/latest`,e,{redirect:"manual"});return gj(t.headers.get("location"))},Cj=async e=>{try{let t=await fu(`${e}/connect-update.json`,pu);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"}},vy=async(e,t,n)=>{let r=await fu(e,hj);if(!r.ok||!r.body)throw new Zi(r.status);let o=lj("sha256"),a=0;if(await uj(dj.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>fj)throw new Error("asset exceeds size cap");o.update(c),yield c}},rj(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},Aj=e=>my(e)===Va()?my($r(e)):my(e),vj=async e=>{let t=await by(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Pt(ft(e,n),{force:!0}).catch(()=>{})},yI=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Pt(r,{force:!0}).catch(()=>{});let o=!1;try{await du(e,r),o=!0}catch{}try{await gy(t,e),await cj(ls(e),Aj(t))}catch(a){throw o&&await du(r,e).catch(()=>{}),a}await Pt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Pt(n,{force:!0}),await ij(t,n),await du(n,e)},Sj=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 wy(a).catch(()=>{}))?.isFile()?a:ft(a,Va());if(!(await wy(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??fu)(`${e.tagUrl}/SHA256SUMS`,pu),d=l.ok?ky(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await Ga($r(i),{recursive:!0,mode:448}),await vj($r(i));let u=`${i}.part-${process.pid}`;try{await(t.download??vy)(`${e.tagUrl}/${e.asset}`,u,d),await aj(u,493),await du(u,i)}catch(f){throw await Pt(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??yI)(o,i),{link:o,target:i,versionsDir:r}},Ej=async e=>{let t=oj(e,["--version"],{stdio:"ignore",timeout:pu});return!t.error&&t.status===0},xj=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??Ej)(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},Rj=async(e,t)=>{let n=await by(e).catch(()=>[]);for(let r of n)t.includes(r)||await Pt(ft(e,r),{force:!0,recursive:!0}).catch(()=>{})},Oj=async e=>{let t=await by(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Pt(ft(e,n),{force:!0}).catch(()=>{})},_j=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 sj(e).catch(()=>{});if(!(!r||t-r.mtimeMs<yj)){await n();try{return await Ga(e,{recursive:!1}),n}catch{return}}},yy=e=>ft(e,"update-state.json"),Pj=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}},Tj=1e3,Dj=16*6e4,Lj=e=>e.inFlight===0,Nj=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??Dj);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&Lj(i))return!0;if(a()>=s)return!1;await o(Tj)}},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 Cy(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=hI(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Ay)().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 Pj(yy(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<mj)return{outcome:"failed",current:n,latest:l};let f=`${pI}/download/${fI}${l}`,p=await(e.load??L)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??Cj)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?wj(w):{...mI(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 _j(ft(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,A;try{await Oj(ft(o,"bin"));let x=await uu(ft(o,"versions")).catch(()=>{}),C=await uu(ft(o,"bin",Va())).catch(()=>{}),I=C&&kc(C,x)?C:void 0,P=ft(o,"bin",Va());i&&process.platform==="win32"&&(await wy(P).catch(()=>{}))?.isFile()&&(A=`${P}.rollback-${process.pid}`,await gy(P,A));let $=()=>(e.installBinary??Sj)({root:o,version:l,asset:c,tagUrl:f});i?b=await Ij({install:$,smoke:e.smoke,rollback:async({link:Y,target:Z})=>{A?(await gy(A,Y),await Pt(ls(Y),{force:!0}).catch(()=>{})):I&&I!==Z?await yI(Y,I):(await Pt(Y,{force:!0}),await Pt(ls(Y),{force:!0}).catch(()=>{}))},repoint:async Y=>e.repoint?e.repoint(p,Y):xj(p),prune:async()=>{await(e.pruneDurable??(Y=>Cc(Y)))(r)}}):b=await $(),await Rj(b.versionsDir,[l,n]),await Pt(yy(o),{force:!0}).catch(()=>{})}finally{A&&await Pt(A,{force:!0}).catch(()=>{}),await y()}let v=e.bounceDaemon??lp,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let x=p.fallbackPort??ke,C=E?!0:await xw().catch(()=>!0),I=await v(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!C&&p.gateway&&((I?await(e.waitForDaemon??Nj)(x,l):!0)?await Nt({port:x,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??Rw)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await J(yy(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},gI=async(e={})=>{let t=e.context??yt(),n=await Cy(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 Cy(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&&!!hI(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 $j=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})},wI=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,Mj=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},Sy=async(e={})=>{let t=e.load??L,n=e.save??oe,r=e.mutate??(e.load||e.save?Mj(t,n):$g),o=e.loadDevKey??We,a=e.heartbeat??Dd,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||!wI(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 $j(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"||!wI(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 bI}from"zod";var Uj=5e3,Fj=bI.object({lane:bI.enum(["subscription","org"]).optional().catch(void 0)}),kI=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??Uj);try{let a=await(n.fetchResponse??fetch)(`${e.replace(/\/$/,"")}/connect/policy`,{headers:{"x-anyray-api-key":t.trim()},signal:r.signal});if(!a.ok)return;let s=Fj.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},CI=(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 Bj=12e3,Wj="anyray-wiring-probe-not-a-real-token",Hj={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},xy={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},vI=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},Iy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},AI=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."],Kj=e=>e.includes("no provider key configured for"),Ry=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},Oy=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."]}),Gj=(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?Ry(t)?Oy(e):Iy(t)?Xi(e):vI(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)."]}:Kj(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")?AI([" \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).",...AI([" \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:[]},jj=(e,t)=>{if(Iy(t))return Xi(e);if(Ry(t))return Oy(e);if(vI(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:[]}},Vj=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),Yj=(e,t)=>{if(Iy(t))return Xi(e);if(Ry(t))return Oy(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")||Vj(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 (${xy.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."]}},Ey=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),r);try{let s=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...t},body:JSON.stringify(n),signal:o.signal});return{status:s.status,bodyText:await s.text()}}finally{clearTimeout(a)}},Zj=async(e,t)=>{if(!e.clientKey)return 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)}},Jj=(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??Bj,r=de(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await Zj(e,n);if(e.byoUpstream){let l={Authorization:`Bearer ${e.byoUpstream.key}`,"anthropic-version":"2023-06-01","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic","x-anyray-custom-host":e.byoUpstream.url};e.clientKey&&(l["x-anyray-api-key"]=e.clientKey),r&&(l["x-anyray-metadata"]=r);let{status:d,bodyText:u}=await Ey(`${e.anthropicBaseUrl}/v1/messages`,l,xy,n);return Yj(d,u)}if(X(e,"anthropic")){let l={Authorization:`Bearer ${Wj}`,"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 Ey(`${e.anthropicBaseUrl}/v1/messages`,l,xy,n);return jj(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await Ey(`${e.openaiBaseUrl}/chat/completions`,s,Hj,n);return Gj(i,c,t.tools??[])}catch(o){return Jj(n,o)}};var SI=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 zd();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=eu(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 uV}from"node:fs";import{isAbsolute as pV}from"node:path";import{access as Xj}from"node:fs/promises";import{constants as qj}from"node:fs";import{platform as zj}from"node:os";var Qj=async e=>{try{return await Xj(e,qj.F_OK),!0}catch{return!1}},eV=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??zj(),n=e.exists??Qj;for(let r of eV(t))if(await n(r))return!0;return!1};import{execFile as tV}from"node:child_process";import{readFile as nV}from"node:fs/promises";import{homedir as rV,platform as oV}from"node:os";import{promisify as aV}from"node:util";var sV=aV(tV),iV="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",EI=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cV=async e=>{let t;try{t=await nV(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(!EI(n))return{readable:!1};let r=n[bn],o=n[kn];return{readable:!0,supportsAnyray:EI(r)?r[q]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},lV=async(e=async()=>(await sV("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(oV()==="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(`${iV}=(\\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"},dV=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",hu=(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."}},xI=async(e={})=>{let{installedVariant:t=zo,receiptMode:n=bl,awaitingReload:r=wl,readSettings:o=cV,probeBridge:a=lV,home:s=rV()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:hu("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.":hu("not-applicable","unknown")}}let l=await o(js(i)),d=await a(),u=dV({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:hu(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:hu("not-applicable","unknown")}}};var Zt="connect",_y=e=>e.replace(/-/g,"_"),II=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=_y(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":_y(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:_y(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 fV(){return we}var hV="ctx_doctor-probe-synthetic",mV=(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: ${Dy(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 yV(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function gV(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Dy(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 RI=e=>Qd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),Py=e=>e.pointedAt===!1&&e.tombstoned!==!0&&RI(e)!=="unverifiable",OI=e=>e.registered&&e.command&&pV(e.command)?uV(e.command):null,Ty=e=>(Py(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),wV=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,bV=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},_I=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},kV=(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},CV=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 cu(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&&Zm(V)?"machine_default":null,b=t.enrolledCert?.payload,A=b?.expiresAt??t.enrolledCertExpiry??null,E=(await a())?.sso??null,x=gV({ssoLink:E,enrolledViaToken:!!t.enrolledTokenHash}),C=vt(),I=await rb(C),P=I?[]:cb(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:OI(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 wV(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 bV(t.managedTools??[],r),W=Y?{...Y,...Z?{notApplicableSubscription:!0}:{}}:null,z=n?mV(await _a({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:de({user:t.name,team:t.team})},hV,{probe:!0}),{mode:x,ssoLink:E}):null,me=await u().catch(()=>({})),Te=In(me.hookLane),re=s?await _I(r):!1,Ke=re?await(async()=>{let V=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...wm(V,{hookRegistered:re,neverInvoked:ym(Te,Date.now())}),lastInvokedAt:Nd(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 NE({daemonEnabled:h&&!Ze,daemonHealthy:h?!!m:null,schedulerEnabled:H&&!Ze,schedulerInstalled:fe,binaryDurable:!je(ur())}),Be=await Wu(),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+=Ty(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 xI();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:fV(),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:Rd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:T,pendingOps:De,ambientRepairs:kV(me,r),verify:W,retrieval:z,hookLane:Ke,agentsWindow:Xt,problems:Le}},AV=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."))}},vV=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)."))}},SV=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.")))),AV(e),vV(e),K("Personal key"),yV(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: ${Dy(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(` ${HC}`)),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=RI(c);if(l==="not-routed"||l==="unverifiable"){let d=eu(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.`)},EV=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}),xV=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!fm(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=wm(i,{hookRegistered:await _I(t.adapters??ie).catch(()=>!1),neverInvoked:ym(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:Nd(c)},note:d}},IV=async(e,t,n={})=>{let r=n.adapters??ie,o=n.resolveTarget??Oe,a=n.applyTools??wt,s=await xV(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&&(Py(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 ${Dy(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:OI(P)}}catch{}let E=Py(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+=Ty(b)-Ty(I)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},RV=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}`))},PI=async(e,t={})=>{let n=await L();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of $E(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 CV(r,n,!!e.verify&&!e.quick,t.adapters??ie,t.inferenceIntrospection??zd,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 Wu(),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(EV(i),null,2)):(SV(i),s&&RV(s));try{e.quick||await(t.reportHealth??xS)(II(i),i.connect.version)}catch{}return i.problems===0?0:1};var OV=()=>{let e=[];for(let t of ie){let n=t.skillsDir?.();n&&e.push(n)}return e},TI=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=px(t.clientKey,"anyray-placeholder"),o;try{o=await _d(n,r)}catch(s){return _(`Team policy sync failed: ${Od(s)}`),1}let a=OV();if(a.length===0)_V();else if(o.skills.length===0)M("No team skills published yet \u2014 nothing to sync.");else{let s=await iS(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 Pd(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(k(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&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: ${Od(s)}`)}return 0},_V=()=>{M("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as L2}from"node:zlib";import{promisify as N2}from"node:util";var Mr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Ly=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),DI=e=>`
|
|
701
701
|
|
|
702
702
|
\u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
|
|
703
703
|
|
|
704
|
-
`,
|
|
704
|
+
`,mu=(e,t={})=>{if(typeof e!="string")return Ly(String(e??""));let n=Math.max(1,t.maxChars??Mr.maxChars);if(e.length<=n)return Ly(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
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+=
|
|
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+=DI(g-m)),h+=e.slice(g,y),m=y;if(r>m&&(h+=DI(r-m)),h.length>=r)return Ly(e);let w=r-h.length;return{text:h,trimmed:!0,originalChars:r,trimmedChars:h.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},PV=["stdout","content","output","text","result"],LI=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} ---
|
|
707
707
|
${d}`);s&&i.push(`--- MCP structuredContent ---
|
|
708
708
|
${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
|
|
709
709
|
|
|
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=
|
|
711
|
-
`),s=0,i=0;for(let c of a)c.trim()&&(s++,
|
|
712
|
-
${e.slice(-
|
|
713
|
-
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},
|
|
714
|
-
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},
|
|
715
|
-
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},
|
|
716
|
-
`).filter(s=>s.trim()!==""),r
|
|
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=PV.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 TV=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},yu=(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++,TV(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,gu={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"},MI=new Set(["npm","pnpm","yarn","bun"]),wu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},DV=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=wu(r[0]);if(o in gu)return gu[o];if((o==="npx"||o==="bunx")&&r[1]){let a=wu(r[1]);if(a in gu)return gu[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||MI.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},$y=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=DV(t);if(n)return n}return null},LV={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},NV=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,$V=(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},UI=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=wu(r[0]);if(MI.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&NV.test(i)}let a=r[1]?wu(r[1]):void 0;if($V(o,a,r))return!1;let s=LV[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},MV=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==="]"},UV=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},FV=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=UV(t);return r>0&&t[r+1]===":"},BV=80,WV=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/BV),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,FV(e[o])&&r++;return n>0&&r/n>.3},HV=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,KV=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();(HV.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},GV=[/\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],Ny=8192,jV=e=>{let t=e.length>2*Ny?`${e.slice(0,Ny)}
|
|
712
|
+
${e.slice(-Ny)}`:e;return GV.some(n=>n.test(t))},VV=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),YV=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),ZV=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},JV=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),NI=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(YV(i)){t.push(Qi(i));continue}let c=ZV(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Qi(c)),o=12;continue}VV(i)||JV(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}},XV=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,FI=e=>{let t=XV.exec(e);return t&&/[/.]/.test(t[1])?t:null},qV=/^([^\s:]+)-(\d+)-/,zV=e=>{if(e==="--")return!0;let t=qV.exec(e);return t!=null&&/[/.]/.test(t[1])},QV=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>FI(r)!=null).length;return n>=3&&n/t.length>=.7},$I=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=FI(c);if(!l){if(zV(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(`
|
|
714
|
+
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},e2=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(),t2=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=e2(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(`
|
|
715
|
+
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},BI=(e,t)=>{if(typeof t!="string"||t.length===0||MV(t))return null;let n=t.split(`
|
|
716
|
+
`).filter(s=>s.trim()!==""),r=$y(e),o=jV(t),a=null;return r==="test-run"&&o?a=NI(n):r==="grep"&&(a=$I(n,.5)),a||(o?a=NI(n):QV(n)?a=$I(n,.7):!KV(n)&&!WV(n)&&(a=t2(n))),!a||a.text.length>=t.length?null:a},My=(e,t)=>t?`
|
|
717
717
|
|
|
718
718
|
\u2026[anyray-hook digest \u2014 ${e}; full output: ${t}]\u2026`:`
|
|
719
719
|
|
|
720
|
-
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,
|
|
720
|
+
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,WI=e=>`
|
|
721
721
|
|
|
722
|
-
\u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as
|
|
723
|
-
`):"",
|
|
724
|
-
`).slice(0,
|
|
725
|
-
`);i=l>=0?i.slice(l+1):""}let c=
|
|
726
|
-
`));return
|
|
727
|
-
`:"",
|
|
728
|
-
${
|
|
729
|
-
`}catch{return}},
|
|
722
|
+
\u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as n2}from"node:crypto";import{homedir as r2}from"node:os";import{join as To}from"node:path";import{chmod as o2,mkdir as a2,readdir as jI,stat as tc,unlink as ec,utimes as s2,writeFile as Fy}from"node:fs/promises";var bu={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},VI=".swept",i2=".sweeping",HI=64,KI=448,By=384,c2=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",YI=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,ZI=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(r2(),".anyray-hook-tee")},l2=async(e,t={})=>{let n=t.limits??bu;try{let r=Date.now(),o=(await jI(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=HI)await Promise.all(o.slice(c,c+HI).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-YI(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{}},JI=async e=>{try{return Date.now()-(await tc(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},GI=async e=>{try{return await Fy(e,"",{mode:By,flag:"wx"}),!0}catch{return!1}},d2=async(e,t)=>{let n=bu,r=To(e,i2),o=To(e,VI);if(!await GI(r)){let a=0;try{a=Date.now()-(await tc(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await ec(r).catch(()=>{}),!await GI(r)))return!1}try{return await JI(o)<n.sweepIntervalMs?!1:(await Fy(o,"",{mode:By}).catch(()=>{}),await l2(e,{protect:t}),!0)}finally{await ec(r).catch(()=>{})}},Uy=async(e,t)=>await JI(To(e,VI))<bu.sweepIntervalMs?!1:d2(e,t),u2=async()=>{try{let e=await ZI();if(!(await jI(e)).some(t=>t.endsWith(".txt")))return;await Uy(e)}catch{}},XI=async e=>{if(c2())return await u2(),null;try{let t=await ZI();await a2(t,{recursive:!0,mode:KI}),await o2(t,KI).catch(()=>{});let n=`${n2("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-YI(a)<=bu.maxAgeMs){let s=new Date(o);return await s2(r,s,s).catch(()=>{}),await Uy(t,r),r}await ec(r).catch(()=>{})}}catch{}return await Fy(r,e,{mode:By}),await Uy(t,r),r}catch{return null}};import{createHash as p2}from"node:crypto";import{homedir as qI}from"node:os";import{join as Wy}from"node:path";import{readFile as f2,writeFile as h2,chmod as m2,stat as y2,unlink as g2}from"node:fs/promises";var w2=200,b2=1440*60*1e3,k2=4e6,zI=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",QI=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},C2=()=>QI("ANYRAY_HOOK_CACHE_MAX_ENTRIES",w2),e0=()=>QI("ANYRAY_HOOK_CACHE_TTL_MS",b2),t0=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Wy(qI(),".anyray");try{if((await y2(t)).isDirectory())return Wy(t,"hook-cache.json")}catch{}return Wy(qI(),".anyray-hook-cache.json")},n0=(e,t,n)=>p2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),r0=async e=>{try{let t=JSON.parse(await f2(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},o0=async e=>{if(zI())return null;try{let n=(await r0(await t0())).entries[e];return!n||Date.now()-n.at>e0()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},A2=e=>{let t=Date.now(),n=e0(),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=C2();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>k2&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},a0=async(e,t)=>{if(zI())return;let n;try{let r=await t0(),o=await r0(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=A2(o.entries),n=`${r}.${process.pid}.tmp`,await h2(n,JSON.stringify(o),{mode:384}),await m2(n,384),await he(n,r)}catch{if(n)try{await g2(n)}catch{}}};import{open as v2,stat as S2}from"node:fs/promises";var s0=600,E2=3,x2=256e3,I2=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
|
+
`):"",R2=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),O2=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},_2=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=I2(o.message?.content).trim();if(!(!a||R2(a))&&(t.unshift(a),n+=a.length,t.length>=E2||n>=s0))break}return t.join(`
|
|
724
|
+
`).slice(0,s0)};var P2=e=>/(^|[\\/])subagents[\\/]/i.test(e),T2=e=>/\.jsonl$/i.test(e),D2=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),i0=async e=>{let t={intent:"",kind:"unknown"};if(!e||!T2(e))return t;let n;try{let{size:r}=await S2(e),o=Math.max(0,r-x2),a=r-o;if(a<=0)return t;n=await v2(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(`
|
|
725
|
+
`);i=l>=0?i.slice(l+1):""}let c=O2(i.split(`
|
|
726
|
+
`));return D2(c)?{intent:_2(c),kind:P2(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var $2=3e3,M2=1500,U2=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:$2},F2={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},B2=new Set(["claude","opencode"]),W2=(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:F2[t]})},H2={cacheGet:async()=>null,cachePut:async()=>{}},K2=(e,t={cacheGet:o0,cachePut:a0,tee:XI})=>e==="claude"?t:H2,G2=1e3,j2=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),ku=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),V2=e=>{try{let t=JSON.parse(e);if(!ku(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 ku(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},Y2=e=>{try{let t=JSON.parse(e);return ku(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},Z2=e=>ku(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
727
|
+
`:"",Hy=e=>Math.round(Math.max(0,e)/4),c0=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",J2=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),X2=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),q2=["tool_output","tool_response","tool_result"],z2=e=>{for(let t of q2)if(t in e)return e[t]},Q2=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},eY=120,tY=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??G2))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=My(r.stat,null).length+eY;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=My(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}}},nY=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(J2.has(o)||X2(o))return n;let a=LI(z2(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(l0(o)&&l.retrievalContext!=="available")return n;let d=await tY(t,Q2(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!yu(i,{minChars:M2})))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?WI(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=Hy(Math.max(0,p-Z))+x+Hy(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:j2(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
|
+
${c0(r.tool_input)}`:c0(r.tool_input),g=n0(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=cY(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:Hy(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")},rY=()=>{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")}},oY=N2(L2),aY=async e=>{try{let t=await oY(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},l0=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),sY=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},iY=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),cY=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),lY=2048,dY=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,lY),n=Ld(t);if(!n)return;await qS({at:Date.now(),status:e.status,code:n})}catch{}},uY=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),U2());try{let c=await aY(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...l0(t)||sY(t)&&a==="available"?{reversible:!0}:{},...iY(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 dY(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)}},d0=async(e="claude")=>{let t=await nc();if(e!=="cursor"&&Y2(t))return 0;let n=e==="cursor"?V2(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Ky(n,e);if(e==="cursor"){let a=Z2(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Ky=async(e,t="claude",n)=>{await Pr(),await XS(t);let r=rY(),o=await at(),a=o&&{...o,metadata:W2(o.metadata,t)},s=K2(t);return nY(e,{optimize:(i,c,l,d,u)=>uY(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await i0(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>mu(i,r),beacon:(i,c)=>_c(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Mr.maxChars,digestCommand:BI,tee:s.tee,mediumBand:B2.has(t),finalizeOutput:n})};var u0=async()=>0;var pY=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},fY=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}},hY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},mY=()=>{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")}},yY=(e,t)=>{let n=t.minChars??zi.minChars,r={maxChars:Math.min(Mr.maxChars,n)},o=mu(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},p0=async()=>{let e=await hY(),t=await fY(e);t&&process.stdout.write(t);let n=mY(),r=await at();return await pY(e,{isPaste:o=>yu(o,n),measure:o=>yY(o,n),beacon:o=>_c(r,"prompt",o)}),0};import{spawn as gY}from"node:child_process";var f0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wY=/[|&;<>`$()\n]/,h0=e=>{if(wY.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},bY=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!f0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!f0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(zu)||!t.isRecognized(o)||h0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},kY=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?h0(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
|
|
730
730
|
`),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
|
|
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
|
+
`),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},CY=16*1024*1024,AY=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=gY(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>CY){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)}}),vY=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Ky(n,"cursor");return typeof r=="string"?r:t},m0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return kY(t,{exec:AY,trim:vY,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},y0=async()=>{let e=await nc();if(process.platform==="win32")return 0;let t=bY(e,{isRecognized:n=>$y(n)!==null||UI(n),wrap:n=>Dt(zu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as SY}from"node:crypto";import{homedir as g0}from"node:os";import{extname as EY,isAbsolute as xY,join as Gy,resolve as rc,sep as w0}from"node:path";import{chmod as IY,readFile as RY,stat as v0,unlink as OY,writeFile as _Y}from"node:fs/promises";var Vy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),PY=16*1024,b0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],TY=["pattern","query","regex","search"],DY=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"]),LY=720*60*1e3,NY=512,jy=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},$Y=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],k0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(w0)?n:n+w0)),MY=(e,t,n)=>xY(e)?[rc(e)]:[...new Set([rc(t,e),...n.map(r=>rc(r,e))])],C0=(e,t,n)=>SY("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),A0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),UY=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!Vy(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!Vy(o))return"";let a=$Y(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=jy(o,TY);if(!d)return"";let u=jy(o,b0);return u&&!k0(rc(s,u),a)||!await t.remember(C0(i,"Grep",d))?"":A0(`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=jy(o,b0);if(!c||DY.has(EY(c).toLowerCase()))return"";let l=await t.resolveFile(MY(c,s,a));return!l||l.bytes<PY||!k0(l.path,a)||!await t.remember(C0(i,"Read",l.path))?"":A0(`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.`)},FY=async e=>{for(let t of e)try{let n=await v0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},BY=async()=>{let e=Gy(g0(),".anyray");try{if((await v0(e)).isDirectory())return Gy(e,"cursor-redirects.json")}catch{}return Gy(g0(),".anyray-cursor-redirects.json")},WY=async e=>{let t;try{let n=await BY(),r=Date.now(),o={};try{let s=JSON.parse(await RY(n,"utf-8"));if(s?.v===1&&Vy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=LY&&(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,NY);return t=`${n}.${process.pid}.tmp`,await _Y(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 OY(t)}catch{}return!1}},S0=async()=>{let e=await nc(),t="";try{t=await UY(e,{resolveFile:FY,remember:WY})}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},Yy=e=>typeof e=="string"&&e.trim()?e.trim():void 0,HY=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=Yy(n.gatewayUrl),f=Yy(n.gatewayOverride),p=Yy(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}},KY=e=>new Promise(t=>setTimeout(t,e)),GY=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})},jY=async(e,t={})=>{let n=t.poll??jd,r=t.verify??dn,o=t.loadProfile??L,a=t.saveProfile??oe,s=t.saveDevKey??mc,i=t.readGateState??Tr,c=t.writeGateState??Vd,l=t.clearGateState??cE,d=t.sleep??KY,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=>GY(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"}},VY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},E0=async()=>{let e=HY(await VY());if(e)try{await jY(e)}catch{}return 0};var YY=1e4,Zy=/^[\w.:-]{1,64}$/,Jt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Jy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,x0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),YY);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)}},ZY=e=>{let t=Jy(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}},JY=e=>{let t=Jy(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Zy.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Zy.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},XY=e=>{let t=Jy(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!xe(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Zy.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}}},qY=e=>new Promise(t=>setTimeout(t,e)),zY=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},QY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??qY,a=t.loadProfile??L,s=t.saveProfile??oe,i=t.clearDevKey??is,c=t.chooseTeam??zY,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 x0(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=ZY(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 x0(`${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=JY(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=XY(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.")},eZ=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
732
732
|
|
|
733
733
|
Start browser SSO, choose a team, mint a personal gateway key, and configure
|
|
734
734
|
the subscription-backed Connect lane. In a non-interactive shell, --team may be
|
|
735
|
-
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.`,I0=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(eZ),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 QY({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 R0=`anyray-connect update [--check] [--auto on|off] [--json]
|
|
736
736
|
|
|
737
737
|
Keep this machine's anyray-connect binary on the published release. Runs
|
|
738
738
|
automatically about every 30 minutes; this command forces it now.
|
|
@@ -743,32 +743,32 @@ Options:
|
|
|
743
743
|
Off still accepts a release the Anyray team marks mandatory.
|
|
744
744
|
--json Emit the result as JSON.
|
|
745
745
|
--help Show this help.
|
|
746
|
-
`,
|
|
746
|
+
`,tZ=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},nZ=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}.`}},O0=async e=>{let t;try{t=tZ(e)}catch(o){return _(o.message),process.stderr.write(R0),1}if(t.help)return process.stdout.write(R0),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)}
|
|
747
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)}
|
|
748
|
-
`),n.outcome==="failed"?1:0}let r=
|
|
748
|
+
`),n.outcome==="failed"?1:0}let r=nZ(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 rZ=3e3,_0=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>Ay(rZ)),o=e.updateStatus??Oo;t(`anyray-connect ${we}
|
|
749
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}
|
|
750
750
|
${i}
|
|
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
|
|
752
|
-
`),0};var
|
|
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,
|
|
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 oZ=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},aZ=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),sZ=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(!oZ(a)||!aZ(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"}}},P0=async(e={})=>{let t=await sZ(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
752
|
+
`),0};var iZ="2025-06-18",cZ={name:"anyray",version:"1"},T0={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}},lZ=20,D0={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}},M0=fy,dZ=e=>{if(e==null||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return;let n=Math.round(t);return n<1?1:Math.min(n,M0)},uZ=e=>e==="paths"||e==="lines"||e==="full"?e:"full",L0={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-${M0}). 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}},N0={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}},pZ=8,fZ=3,$0={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}},hZ=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(`
|
|
753
|
+
`)},mZ=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
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,pZ).map(([a,s])=>{let i=s.slice(0,fZ).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
755
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(`
|
|
756
|
-
`)},Pe=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),
|
|
756
|
+
`)},Pe=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),Xy=(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?`
|
|
757
757
|
|
|
758
758
|
[anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
|
|
759
759
|
|
|
760
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(`
|
|
761
|
-
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},
|
|
762
|
-
${p.content}`))}return Pe(n??null,Ae(p.content))}if(a.name===
|
|
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
|
|
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
|
|
761
|
+
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},yZ=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:iZ,capabilities:{tools:{}},serverInfo:cZ});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Pe(n??null,{});case"tools/list":{let a=[T0,D0];t.advertiseContextTools!==!1&&a.push(L0,N0);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push($0),Pe(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===T0.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 ${lZ} 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}
|
|
762
|
+
${p.content}`))}return Pe(n??null,Ae(p.content))}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=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(hZ(l.matches)):Ae(l.message,!0))}if(a.name===L0.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=dZ(s.maxResults),d=uZ(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(Yx(i,u,d)):Ae(u.message??"search failed",!0))}if(a.name===$0.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(dy(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(mZ(c,l)):Ae(l.message??"history search failed",!0))}if(a.name===N0.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(dy(l)):Ae(l.message??"read failed",!0))}return Xy(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Xy(n??null,-32601,`method not found: ${o}`)}},gZ=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),$d);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Qt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},wZ=(e,t=!0)=>({retrieve:async(n,r)=>_a(await e(),n,r),recall:async(n,r)=>Md(await e(),n,r),search:(n,r,o)=>au(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>ou(n,r),historySearch:n=>Xx(n),historyOpen:n=>qx(n),historyAvailable:async()=>await Ka()>0,advertiseContextTools:t,heartbeat:()=>{e().then(gZ).catch(()=>{})}}),U0=async(e="auto",t={})=>{let n=wZ(()=>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 yZ(h,n)}catch(w){console.error("anyray mcp: dispatch error",w instanceof Error?w.message:w),m=h?.id===void 0?null:Xy(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(`
|
|
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 bZ}from"node:child_process";var kZ=e=>e==="jetbrains"||e==="windsurf"?e:void 0,CZ=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(`
|
|
765
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}})}
|
|
766
|
-
`),!0)}catch{return!1}},
|
|
767
|
-
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!
|
|
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
|
|
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=
|
|
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=
|
|
771
|
-
`),y(1)}),A.once("exit",(v,E)=>{y(typeof v=="number"?v:E?1:0)})})};import{createReadStream as
|
|
766
|
+
`),!0)}catch{return!1}},AZ={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},vZ=(e,t,n)=>{let r=new Set(AZ[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}},F0=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
767
|
+
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!wd(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
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 CZ(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.
|
|
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=kZ(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",p=(n.hookBinaryIsDurable??le)(),h=Fv(d,t,{mcpServer:p?Ve("profile"):void 0})[f],m=n.spawn??bZ,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.
|
|
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=vZ(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.
|
|
771
|
+
`),y(1)}),A.once("exit",(v,E)=>{y(typeof v=="number"?v:E?1:0)})})};import{createReadStream as SZ}from"node:fs";import{spawnSync as q0}from"node:child_process";import{createHash as EZ}from"node:crypto";import{access as z0,chmod as Qy,copyFile as xZ,lstat as IZ,mkdir as RZ,mkdtemp as Q0,readFile as Eu,rename as OZ,rm as Ur,stat as _Z,writeFile as PZ}from"node:fs/promises";import{constants as eR}from"node:fs";import{platform as Ja,tmpdir as TZ}from"node:os";import{dirname as DZ,isAbsolute as LZ,join as Au}from"node:path";import{z as Ue}from"zod";var NZ="fleetd-installer-v4.89.2",B0=`https://github.com/anyrayHQ/install/releases/download/${NZ}`,$Z=1e4,MZ=1e4,W0=31,UZ=1500,tR=20*1024,qy=20,FZ="0.25",BZ="/var/tmp",Za="/Library/LaunchDaemons/com.fleetdm.orbit.plist",vu="/etc/default/orbit",sc="/opt/orbit/anyray-enroll-secret.txt",nR="/opt/orbit/secret-orbit-node-key.txt",WZ="/opt/orbit/bin/orbit/orbit",ic="C:\\Program Files\\Orbit",HZ=`${ic}\\bin\\orbit`,rR=`${ic}\\secret-orbit-node-key.txt`,ac=`${ic}\\secret.txt`,KZ=`${ic}\\fleet_url.txt`,oR=`${ic}\\anyray-managed.txt`,Su="Fleet osquery",eg="C:\\Windows\\System32\\sc.exe",GZ="C:\\Windows\\System32\\whoami.exe",Cu="C:\\Windows\\System32\\icacls.exe",jZ="C:\\Windows\\System32\\msiexec.exe",tg="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",H0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],VZ=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],YZ=`anyray-connect endpoint install
|
|
772
772
|
|
|
773
773
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
774
774
|
|
|
@@ -776,11 +776,11 @@ Supported on macOS, Linux and Windows.
|
|
|
776
776
|
|
|
777
777
|
The command uses the current seat's stored gateway key. Administrator access is
|
|
778
778
|
required: on macOS and Linux Connect asks through sudo once when /dev/tty is
|
|
779
|
-
available; on Windows, run it from a shell started as Administrator.`,
|
|
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")},
|
|
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},
|
|
779
|
+
available; on Windows, run it from a shell started as Administrator.`,og=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),aR=(e,t=Ja())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),sR=(e,t=Ja(),n=!1)=>(og(e)||n)&&t!=="win32",ce=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},ZZ=Ue.object({kind:Ue.enum(["pkg","deb","rpm","msi"]),path:Ue.string().min(1).refine(LZ),sha256:Ue.string().regex(/^[0-9a-f]{64}$/)}).strict(),JZ=Ue.object({action:Ue.literal("restart"),os:Ue.enum(["darwin","linux","win32"])}).strict(),XZ=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:ZZ.optional()}).strict(),qZ=Ue.discriminatedUnion("action",[JZ,XZ]),cc=(e,t)=>{let n=q0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},ag=async e=>{try{return await z0(e,eR.F_OK),!0}catch{return!1}},zZ=async e=>{try{let t=await _Z(e);return t.isFile()&&t.size>0}catch{return!1}},sg=(e,t)=>{for(let n=0;;){let r=e.indexOf("<key>",n);if(r<0)return null;let o=e.indexOf("</key>",r);if(o<0)return null;if(e.slice(r+5,o).trim()===t)return{start:r,end:o+6};n=o+6}},zy=(e,t)=>sg(e,t)!==null,K0=e=>e==="win32"?ac:sc,QZ=e=>e==="win32"?rR:nR,eJ=e=>zy(e,"ORBIT_FLEET_URL")&&zy(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${sc}</string>`)&&!zy(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),tJ=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")},ng=(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()},iR=e=>{let t=e(eg,["qc",Su,"8192"]);return t.status===0?t.stdout:""},rg=e=>{let t=e(tg,VZ(Su)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},nJ=async e=>{try{return e==="win32"?ng(e,iR(cc)):ng(e,await Eu(e==="darwin"?Za:vu,"utf8"))}catch{return}},rJ=async e=>{try{if(e==="win32")return await ag(oR)&&ng(e,iR(cc))!==void 0;let n=await Eu(e==="darwin"?Za:vu,"utf8");return e==="darwin"?eJ(n):tJ(n)}catch{return!1}},cR=async(e,t={})=>{let n=t.exists??ag,r=t.command??cc,o,a="absent";if(e==="win32")a=rg(r),o=await n(HZ)&&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(WZ)&&l}let s=await(t.configured??rJ)(e),i=await(t.hasNodeKey??(()=>zZ(QZ(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}},oJ=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),lR=(e,t)=>{let n=sg(e,t);if(!n)return null;let r=n.start;for(;r>0&&(e[r-1]===" "||e[r-1]===" ");)r--;r>0&&e[r-1]===`
|
|
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},aJ=(e,t)=>{let n=lR(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},G0=(e,t,n)=>{let r=`
|
|
782
782
|
<key>${t}</key>
|
|
783
|
-
<string>${
|
|
783
|
+
<string>${oJ(n)}</string>`,o=lR(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=sg(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new 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)},sJ=(e,t,n=sc)=>{let r=aJ(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=G0(r,"ORBIT_FLEET_URL",t),G0(r,"ORBIT_ENROLL_SECRET_PATH",n)},iJ=(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(`
|
|
784
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(`
|
|
785
785
|
`).trimEnd()}
|
|
786
786
|
|
|
@@ -790,13 +790,13 @@ available; on Windows, run it from a shell started as Administrator.`,rg=e=>!!(e
|
|
|
790
790
|
# file, never in this world-readable one.
|
|
791
791
|
ORBIT_FLEET_URL=${t}
|
|
792
792
|
ORBIT_ENROLL_SECRET_PATH=${n}
|
|
793
|
-
`},
|
|
794
|
-
`,384);e.os!=="win32"&&await
|
|
795
|
-
`,384),e.os==="win32"&&
|
|
796
|
-
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??
|
|
797
|
-
sudo anyray-connect endpoint install`),"deferred"},
|
|
798
|
-
`;if(Buffer.byteLength(t)>
|
|
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}},
|
|
793
|
+
`},dR=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}},cJ=Ue.object({code:Ue.string().min(1).optional(),message:Ue.string().min(1).optional()}).passthrough(),j0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},lJ=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=cJ.safeParse(t);if(!r.success)return n;let o=j0(r.data.message??""),a=j0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},V0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??MZ),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(lJ(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||!dR(i.data.fleetUrl))throw new ce("The gateway returned invalid endpoint enrollment data.");return i.data},dJ=async(e={})=>{let t=e.exists??ag;if(await t("/usr/bin/dpkg")||await t("/bin/dpkg"))return"deb";if(await t("/usr/bin/rpm")||await t("/bin/rpm"))return"rpm";throw new ce("Linux endpoint installation requires either dpkg or rpm.")},uJ=async e=>e==="darwin"?"pkg":e==="win32"?"msi":dJ(),ig=e=>`fleetd.${e}`,pJ=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",fJ=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),$Z);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},hJ=async(e,t={})=>{let n=ig(e),r=t.fetchResponse??fetch,o;try{o=await fJ(`${B0}/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=ky(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await Q0(Au(TZ(),"anyray-endpoint-")),i=Au(s,n);try{await Qy(s,448),await(t.download??vy)(`${B0}/${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})}},mJ=async(e,t,n)=>{await RZ(DZ(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Ur(r,{force:!0});try{await PZ(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await OZ(r,e)}catch(o){throw await Ur(r,{force:!0}).catch(()=>{}),o}},Y0=async e=>{let t=EZ("sha256");for await(let n of SZ(e))t.update(n);return t.digest("hex")},yJ=async(e,t={})=>{let n=await IZ(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 Y0(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 Q0(Au(BZ,"anyray-endpoint-root-")),o=Au(r,ig(e.kind));try{if(await Qy(r,448),await xZ(e.path,o),await Qy(o,384),await Y0(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)},Z0="com.fleetdm.fleetd.config",gJ="com.fleetdm.fleetd.enroll.secret",wJ=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",nR],bJ=[KZ,rR],kJ=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(Z0))throw new ce(`This machine already receives its endpoint configuration from an MDM profile (${Z0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},J0=async(e,t,n)=>{let r=n.removeFile??(o=>Ur(o,{force:!0}));for(let o of e==="win32"?bJ:wJ)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",gJ,"/Library/Keychains/System.keychain"])},CJ=e=>{e(Cu,[ac,"/inheritance:r"]),e(Cu,[ac,"/grant:r","*S-1-5-18:(F)"]),e(Cu,[ac,"/grant:r","*S-1-5-32-544:(F)"]),e(Cu,[ac,"/remove:g","*S-1-5-32-545"])},AJ=(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(jZ,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},vJ=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<qy;r++){if(n=t("/bin/launchctl",["bootstrap","system",Za]),n.status===0)return;t("/bin/sleep",[FZ])}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(eg,["stop",Su]);for(let n=0;n<qy;n++){let r=rg(t);if(r==="Stopped"||r==="absent")break;t(tg,H0)}for(let n=0;n<qy;n++){if(t(eg,["start",Su]).status===0||rg(t)==="Running")return;t(tg,H0)}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.")},SJ=e=>new Promise(t=>setTimeout(t,e)),uR=async(e,t={})=>{let n=t.command??cc,r=t.readText??(c=>Eu(c,"utf8")),o=t.writeText??mJ,a=t.removeSecret??(()=>Ur(K0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&kJ(n),e.package&&!pJ(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 J0(e.os,n,t),e.package){let d=await(t.preparePackage??yJ)(e.package);i=d.cleanup,AJ(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Za);await o(Za,sJ(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(vu);await o(vu,iJ(d,e.fleetUrl),420)}else await o(oR,`anyray
|
|
794
|
+
`,384);e.os!=="win32"&&await J0(e.os,n,t),await o(K0(e.os),`${e.enrollSecret}
|
|
795
|
+
`,384),e.os==="win32"&&CJ(n),s=e.os!=="win32"}vJ(e.os,n);let c=t.checkIn??(async d=>{let u=await cR(d);return u.running&&u.checkedIn}),l=t.wait??SJ;for(let d=0;d<(t.attempts??W0);d++){if(await c(e.os))return;d+1<(t.attempts??W0)&&await l(UZ)}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(()=>{})}},EJ=async()=>{try{return await z0("/dev/tty",eR.R_OK),!0}catch{return!1}},xJ=12288,IJ=e=>{let t=e(GZ,["/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>=xJ},RJ=async(e,t={})=>{if((t.os??Ja())==="win32")return(t.elevated??(()=>IJ(t.command??cc)))()?(await e(),"direct"):((t.print??k)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
796
|
+
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??EJ)()){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:
|
|
797
|
+
sudo anyray-connect endpoint install`),"deferred"},OJ=async e=>{let t=`${JSON.stringify(e)}
|
|
798
|
+
`;if(Buffer.byteLength(t)>tR)throw new ce("The privileged endpoint plan is unexpectedly large.");let n=pn(["__anyray-endpoint-install"]);return q0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},_J=async(e,t={})=>(t.withRoot??RJ)(()=>(t.apply??uR)(e),{...t.root,reexec:()=>(t.sudo??OJ)(e)}),X0=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 Eu("/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}},pR=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??cR)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??X0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??nJ)(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??V0)(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??X0)(),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??V0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>uJ(r)))();if(i=await(t.stagePackage??hJ)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${ig(f)} is not published yet; skipping.`}}s={action:"configure",os:r,...u,...i?{package:{kind:i.kind,path:i.path,sha256:i.sha256}}:{}}}try{return await(t.execute??_J)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},cg=e=>e instanceof ce?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",fR=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return k(YZ),0;if(e.length!==1||e[0]!=="install")return _("Usage: anyray-connect endpoint install"),1;try{let t=await pR();return t.message&&(t.outcome==="installed"?U(t.message):M(t.message)),0}catch(t){return _(cg(t)),1}},PJ=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>tR)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=qZ.safeParse(n);if(!r.success||r.data.os!==Ja()||r.data.action==="configure"&&!dR(r.data.fleetUrl))throw new ce("The privileged endpoint plan is invalid.");return r.data},hR=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 uR(await PJ()),0}catch(t){return _(cg(t)),1}},mR=async(e,t=pR)=>{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: ${cg(n)} Tool routing remains configured.`);return}};import{execSync as lg}from"node:child_process";import{hostname as TJ}from"node:os";var DJ=e=>{try{if(e==="darwin"){let t=lg("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=lg('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 lg("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},xu=(e={platform:process.platform,read:()=>DJ(process.platform),hostname:TJ})=>e.read().trim()||e.hostname().trim();var LJ=(e,t=Date.now())=>e.credentialProtocol==="stable-heartbeat-v1"||!Wd(e,void 0,t),yR=async(e,t={})=>{if(!await(t.fleetdPresent??Po)())return{retired:!1,reason:"no-fleetd",messages:[]};if(!LJ(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 gR=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();return t?t.toLowerCase():(e.platform??process.platform)==="darwin"?(e.readMacUuid??(()=>xu()))().trim().toLowerCase():""};var wR=["reapply_config","remint","revert","revert_tool"],NJ=/^[a-z0-9][a-z0-9-]{0,31}$/;var $J=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"||!wR.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&NJ.test(t.tool):t.tool===void 0},dg=e=>e?.name??"error",bR=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":wR.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!$J(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",dg(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",dg(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:",dg(i))}return a.kind};var MJ=1e4,Xa=e=>e?.name??"Error",ug=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(MJ)})}catch(o){console.error(`anyray seat offboard report: ${Xa(o)}`)}},UJ=e=>e==="reverted"||e==="queued",kR=async(e={})=>{let t=e.loadProfile??L,n=e.clearDeviceTokenState??Yd,r=e.reportSeatOffboarded??ug,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}),UJ(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 CR=e=>e?.name??"Error",AR=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}: ${CR(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${CR(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as ER}from"node:os";var xR=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
800
800
|
|
|
801
801
|
${j("Usage")}
|
|
802
802
|
npx anyray-connect [options]
|
|
@@ -833,7 +833,7 @@ ${j("What it does")}
|
|
|
833
833
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
834
834
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
835
835
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
836
|
-
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.`,IR=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
837
837
|
|
|
838
838
|
${j("Usage")}
|
|
839
839
|
npx anyray-connect <gateway-url> [options]
|
|
@@ -1029,22 +1029,22 @@ ${j("What it does")}
|
|
|
1029
1029
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1030
1030
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1031
1031
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1032
|
-
per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
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?`}`,
|
|
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(`
|
|
1035
|
-
Dry run complete \u2014 no files were written.`),0):(_(` ${O}`),1)}o.revert||
|
|
1036
|
-
Dry run \u2014 no files will be written.`);let Te=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
|
|
1032
|
+
per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,BJ=e=>{let t=e?.trim();return t||Jm()},Iu=(e,t)=>t||e,RR=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},WJ=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}),HJ=(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)")}`)},vR=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}`:""}`)}},KJ=(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},GJ={loadDevKey:We,saveDevKey:mc,clearDevKey:is,saveProfile:oe},jJ=async(e,t,n,r=GJ,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}},VJ=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}},YJ=(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},ZJ=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>OR(o)&&!r.has(o.id))},JJ=async e=>{let t=$x(e,process.platform,ee());if(t){await pe(t.path,t.content);for(let n of Mx(t,process.platform))k(` ${n}`)}},XJ=async(e,t,n=ER())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!Pb(i,n)||!_b(i,n))continue;let c=Rb(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:Ob(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},qJ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,zJ=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?`}`,QJ=async(e,t={})=>{let n=t.requestQuit??(a=>Db(a)),r=t.waitFor??(a=>Lb(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},eX=(e,t={})=>{let n=t.relaunch??(o=>Nb(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},OR=e=>e.changesBilling===!0||e.changesOrgManagement===!0,_R=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,pg=e=>!OR(e),tX=async(e,t,n={})=>{let r=n.hasEnrollment??Bu,o=n.canMultiSelect??lI,a=n.multiSelect??dI,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)&&lu(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=>pg(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:_R(h),selected:pg(h),requiresExplicitChoice:!pg(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},nX=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}`))},rX=5e3,oX=500,SR=3,aX=600*1e3,sX=async()=>{try{let e=await FJ(await Mo());return Date.now()-e.mtimeMs}catch{return Number.POSITIVE_INFINITY}},iX=async(e={})=>{try{let t=await(e.load??L)();if(t.keyRefreshEnabled!==!0){if((e.draining??pp)()||!await(e.unitExists??Ew)()||await(e.profileAgeMs??sX)()<aX)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??oX;for(let s=0;s<SR;s++){if(await r(n,s===0?void 0:rX)!==null)return;s<SR-1&&o>0&&await new Promise(c=>setTimeout(c,o))}if((e.draining??pp)())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{}},cX=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)},lX=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.")}},dX=new Set(["login","wizard","status","doctor","sync","device-url"]),uX=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),pX=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."}},fX=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=iy(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]||!uX.has(e[0])},fg=async(e,t)=>{try{return await yX(e,t)}catch(n){if(n instanceof kt)return console.error(S("Cancelled \u2014 nothing was written.")),130;throw n}},hX=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"},mX=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return d0(n)}if(e[0]==="__anyray-codex-hook")return u0();if(e[0]==="__anyray-prompt-hook")return p0();if(e[0]==="__anyray-shell-pretool")return y0();if(e[0]==="__anyray-shell-run")return m0(e.slice(1));if(e[0]==="__anyray-read-pretool")return S0();if(e[0]==="__anyray-sso-gate")return pE(e.slice(1));if(e[0]==="__anyray-sso-poll")return E0();if(e[0]==="__anyray-vscode-gate")return P0();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 U0(n)}if(e[0]==="__anyray-acp-agent")return F0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return hR(e.slice(1));if(e[0]==="__anyray-refresh"){await Sy(),await nt({runAmbientSelfcheck:!0}),await Nm(),await iX(),await zS(),await QS();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 yR(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=gR(),i=n.enrolledCert;if(s&&i){let l=await We().catch(()=>{});l&&await dS(o,a,i,l,s).catch(()=>{})}await bR(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await nt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?AR(d):(await kR()).ok?"ok":"failed"}).catch(()=>{})}}return await Ji(),0}if(e[0]==="__anyray-fallback-proxy")return _E();if(e[0]==="__anyray-persistence")return TE(e.slice(1));if(e[0]==="__anyray-quit-watch")return UE(e.slice(1));if(e[0]===li)return kx(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return _0();try{let n=await jg(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(fX(e)){let n=pX(await gI());n?.level==="warn"?D(n.message):n&&console.error(n.message)}if(e[0]==="managed")return JE(e.slice(1));if(e[0]==="endpoint")return fR(e.slice(1));if(e[0]==="print-key")return QE(e.slice(1));if(e[0]==="models")return tx(e.slice(1));if(e[0]==="copilot-login")return nx(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=iy(n);return r?fg(r,!1):Ux(n)}if(e[0]==="retrieve")return Bx(e.slice(1));if(e[0]==="recall")return Wx(e.slice(1));if(e[0]==="history")return Qx(e.slice(1));if(e[0]==="migrate")return tI(e.slice(1));if(e[0]==="login")return I0(e.slice(1));if(e[0]==="update")return O0(e.slice(1));let t=e[0];if(t&&dX.has(t)){let n=e.slice(1),r;try{r=RR(n)}catch(o){return _(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?IR:xR),0):t==="status"?SI({gateway:r.gateway}):t==="doctor"?PI({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?TI({gateway:r.gateway}):t==="device-url"?rx():fg(n,!0)}return fg(e,!1)},PR=async e=>{try{return await mX(e)}catch(t){if(t instanceof kt)return console.error(S("Cancelled.")),130;throw t}},yX=async(e,t,n={})=>{let r=n.isInteractive??Yt,o;try{o=RR(e)}catch(O){return _(O.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?IR:xR),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):gx({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 Sy();(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??tX)(o,s),c=!0);let l;try{l=WJ(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=lu(o.enroll);if(O)try{let T=await Yi("Resolving enrollment link\u2026",()=>iI(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=nE(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",()=>rE({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 Gd({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",()=>jd(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&&yg(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||KJ(s),v,E,x,C,I,P,$=s.credentialProtocol==="stable-heartbeat-v1",Y=async O=>{await So();let T=lS(O.token),H=uS(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=>pS({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=Iu(o.user,te.user),o.team=Iu(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=lu(o.enroll);if(!O){let T=sI(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?xu():void 0,H=u??BJ(o.user);if(!o.machine&&!o.user&&!u){let Q=cx();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=Iu(o.user,O.user),o.team=Iu(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 dx(o.user,s.name,O),y=await ux(o.team,s.team,O)}if(!o.revert&&!o.dryRun){let O=CI(await kI(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 vR(l,"after-enrollment"),M(`
|
|
1035
|
+
Dry run complete \u2014 no files were written.`),0):(_(` ${O}`),1)}o.revert||HJ(W,l),c&&!o.revert&&await vR(l,"plan"),o.dryRun&&M(`
|
|
1036
|
+
Dry run \u2014 no files will be written.`);let Te=await hX(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(Te==="non-interactive")return _(`
|
|
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 cu(W.origin);if(!O.reachable)return _(`
|
|
1038
1038
|
Gateway ${W.origin} is not reachable (${O.detail}).`),k(S(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1039
1039
|
that would break them until you re-run with --revert.`)),k(`
|
|
1040
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1;U(`Gateway reachable (${O.detail}).`)}let re=o.revert?[]:await
|
|
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=
|
|
1042
|
-
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 XJ(l,W.origin),Ke=[],De=()=>{Ke.length!==0&&(K("Reopening"),eX(Ke),Ke=[])};if(re.length>0){let O=re.map(H=>H.title),T=O.length===1?"it":"them";if(K("Open apps"),qJ(o,Yt()))o.quitApps===!0||await Fa(zJ(O))?Ke=await QJ(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=Wd(s,P),H=s.anyrayFleetManaged===!0&&await Po().catch(()=>!1),fe=sR(o,ER(),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=>JS.has(ye.id)),Xt=!o.revert&&o.noKeyRefresh!==!0&&Be&&(T||!Le),V=o.dryRun?await xo(s):await Nm(),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 jJ(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 cX(W,Do,{trayManaged:Ne})),z)if(o.dryRun)await Bu()&&(K("Enrollment"),k(" would remove the stored gateway credential"));else{await ug(s),await Yd().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=ZJ(On,o,s.managedTools);if(qa.length>0){K("Not configured \u2014 needs your say-so");for(let Ee of qa)D(` ${Ee.id}: ${_R(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 VJ(On,nr,me,o.revert,new Set(o.tools??[])),ns;if(og(o)){K("Endpoint agent");try{ns=await(n.installEndpointAfterEnrollment??mR)({gateway:w,clientKey:W.clientKey})}catch{M("Endpoint agent setup did not complete. Tool routing remains configured.")}}let Lo=fe&&aR(ns),hg=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 lX({want:hg,announcePrimary:!Q,scopedRevert:!!o.revert&&!z,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!hg&&await Mi("scheduler"),trayManaged:Ne}),!o.revert&&!o.dryRun&&!te){let ye=x??await We();ye&&await Em(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 yx();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=Fp(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(`
|
|
1043
1043
|
Fix this terminal:`),k(S(` unset ${dc.join(" ")}`)),k(`
|
|
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
|
|
1045
|
-
Skipped the connection smoke test (--skip-verify).`):await
|
|
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 mg of YJ(za,Qa,es.includes("claude-desktop")?process.platform:void 0))D(mg);if(es.includes("claude-desktop")&&!o.dryRun)try{await JJ(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(`
|
|
1045
|
+
Skipped the connection smoke test (--skip-verify).`):await nX(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(`
|
|
1046
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 \\
|
|
1047
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 \\
|
|
1048
1048
|
-H "Content-Type: application/json" \\
|
|
1049
1049
|
-H "Authorization: Bearer ${W.clientKey?`<your personal key (${Mt(W.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
|
|
1050
|
-
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(S(" Revert: npx anyray-connect --revert"))}return 0}finally{De()}};
|
|
1050
|
+
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(S(" Revert: npx anyray-connect --revert"))}return 0}finally{De()}};PR(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
|